Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pkgs/mcpx/internal/cli/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,9 @@ func (c *Client) open(ctx context.Context, method, path string, body []byte, con
req.Header.Set(daemon.CallerVersionHeader, v)
}
c.authorize(req)
if mcpclient.TaskExecutionFrom(ctx) {
req.Header.Set(daemon.TaskExecutionHeader, "1")
}
resp, err := c.hc.Do(req)
if err != nil {
if isDialErr(err) {
Expand Down
6 changes: 6 additions & 0 deletions pkgs/mcpx/internal/cli/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,12 @@ func (b mcpBackend) Call(ctx context.Context, ns, tool string, args json.RawMess
ctx = mcpclient.WithClientCapabilities(ctx, mcpserver.DeclaredCapabilities(ctx))
}
ctx = mcpclient.WithCallerVersion(ctx, mcpserver.PeerVersion(ctx))
if mcpserver.WithinTask(ctx) {
// The call is a task's inner call (SEP-2663): say so on the way
// to the daemon, whose write ledger must not record the call's
// cancellation as an unknown write outcome (#8922).
ctx = mcpclient.WithTaskExecution(ctx)
}
var res *CallResult
if r := mcpserver.RelayFrom(ctx); r != nil {
notify := r.Notify
Expand Down
21 changes: 19 additions & 2 deletions pkgs/mcpx/internal/cli/serve_ask.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,13 @@ func (d daemonAsker) Begin(ctx context.Context, kind string, params json.RawMess
if r := mcpserver.RelayFrom(ctx); r != nil && kind == "tools/call" {
body["relay"] = daemon.CallRelay{ProgressToken: r.ProgressToken, LogLevel: r.LogLevel, Meta: r.Meta}
}
if mcpserver.WithinTask(ctx) {
// The call is a task's inner call (SEP-2663): say so on the way
// to the daemon, as the direct path does (mcpBackend.Call), so
// the write ledger does not record the task's cancellation as
// an unknown write outcome (#8922).
ctx = mcpclient.WithTaskExecution(ctx)
}
raw, err := c.do(ctx, http.MethodPost, "/v1/ask", body)
if err != nil {
return "", err
Expand Down Expand Up @@ -375,13 +382,23 @@ func (d daemonAsker) Reply(ctx context.Context, callID string, answers map[strin
return nil
}

func (d daemonAsker) Abandon(callID string) {
func (d daemonAsker) Abandon(callID string) { d.abandon(callID, nil) }

// AbandonTask is Abandon for a call a protocol task owned (SEP-2663):
// the abandon body says so, and the daemon marks the call before
// cancelling it, so its write ledger does not record the task's
// cancellation as an unknown write outcome (#8922).
func (d daemonAsker) AbandonTask(callID string) {
d.abandon(callID, map[string]any{"taskCancelled": true})
}

func (d daemonAsker) abandon(callID string, body any) {
// Best effort, on its own deadline: the request that wanted this is
// already being failed, and its context is cancelled or about to be.
ctx, cancel := context.WithTimeout(context.Background(), defaults.ProtoAbandonGrace)
defer cancel()
if c, err := d.client(ctx); err == nil {
_, _ = c.do(ctx, http.MethodPost, "/v1/ask/"+callID+"/abandon", nil)
_, _ = c.do(ctx, http.MethodPost, "/v1/ask/"+callID+"/abandon", body)
}
}

Expand Down
8 changes: 8 additions & 0 deletions pkgs/mcpx/internal/daemon/callerr.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,17 @@ const ClientCapsHeader = "X-Mcpx-Client-Capabilities"
// mcpclient.WithCallerVersion.
const CallerVersionHeader = "X-Mcpx-Caller-Protocol"

// TaskExecutionHeader carries, on /v1/call and /v1/ask, that the call is
// the inner call of a protocol task (SEP-2663); see
// mcpclient.WithTaskExecution.
const TaskExecutionHeader = "X-Mcpx-Task-Execution"

// withClientCaps applies ClientCapsHeader and CallerVersionHeader to ctx.
func withClientCaps(ctx context.Context, r *http.Request) context.Context {
ctx = mcpclient.WithCallerVersion(ctx, r.Header.Get(CallerVersionHeader))
if r.Header.Get(TaskExecutionHeader) != "" {
ctx = mcpclient.WithTaskExecution(ctx)
}
raw := r.Header.Get(ClientCapsHeader)
if raw == "" || !json.Valid([]byte(raw)) {
return ctx
Expand Down
31 changes: 30 additions & 1 deletion pkgs/mcpx/internal/daemon/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"github.com/developing-today/code/pkgs/mcpx/internal/events"
"github.com/developing-today/code/pkgs/mcpx/internal/logstore"
"github.com/developing-today/code/pkgs/mcpx/internal/mcpclient"
"github.com/developing-today/code/pkgs/mcpx/internal/mcpserver"
"github.com/developing-today/code/pkgs/mcpx/internal/nearmiss"
"github.com/developing-today/code/pkgs/mcpx/internal/policy"
"github.com/developing-today/code/pkgs/mcpx/internal/pool"
Expand Down Expand Up @@ -2710,12 +2711,40 @@ func (r *Registry) callWithLedger(ctx context.Context, p *pool.Pool, server, too
// block later writes. declaredReadOnly reads the requested server's
// view -- the same name this call was made under.
readOnly := toolReadOnly(p, tool) || r.declaredReadOnly(server, tool)
if err != nil && dispatched.Load() && !readOnly && r.writeLedger != nil && !mcpclient.IsConclusiveUpstreamError(err) {
if err != nil && dispatched.Load() && !readOnly && r.writeLedger != nil && !mcpclient.IsConclusiveUpstreamError(err) && !r.taskCancelled(ctx) {
return nil, r.recordUnknownOutcome(p, server, tool, args, surface)
}
return result, err
}

// taskCancelled reports whether this call is a task's inner call whose
// task context was cancelled (#8922). A tasks/cancel is a protocol-level
// disposition owned by the task store: the task's status becomes
// cancelled, visible to the client that cancelled it, so the outcome is
// accounted for -- not unknown. Recording it poisoned the server: the
// conformance suite cancels the task it just created as cleanup, the
// in-flight upstream call aborted with the cancellation, and every
// later non-read-only call to that server was refused as an unknown
// write. A task call that fails while its context is still live (a
// genuine transport failure) still records, exactly as before. The mark
// reaches this check three ways: directly, for the in-process surfaces
// (mcpserver.WithinTask); restored from the X-Mcpx-Task-Execution
// header for calls that crossed the daemon API, where context values do
// not travel (mcpclient.TaskExecutionFrom); and, for an interruptible
// (ask) call, through the ask table -- an asked call starts before its
// task exists, so the flag can only be set retroactively, when the
// task's cancellation abandons the ask (Registry.markAskTaskCancelled).
func (r *Registry) taskCancelled(ctx context.Context) bool {
if ctx.Err() == nil {
return false
}
if mcpserver.WithinTask(ctx) || mcpclient.TaskExecutionFrom(ctx) {
return true
}
id, _ := ctx.Value(askCallKey{}).(string)
return r.askTaskCancelled(id)
}

// ledgerLookupFor finds an unknown-outcome block affecting server, across
// every name sharing its pool. Pools are shared by process identity, so an
// alias added later must not lose the block recorded under the earlier
Expand Down
49 changes: 49 additions & 0 deletions pkgs/mcpx/internal/daemon/routes_proto.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,10 @@ type askCall struct {
Server string
Key string
Session string
// taskCancelled records that this call was abandoned because the
// protocol task that owned it was cancelled (SEP-2663): the write
// ledger consults it before recording an unknown outcome (#8922).
taskCancelled bool
// Run is the exec run id when this call is a script, "" otherwise.
Run string

Expand Down Expand Up @@ -477,6 +481,32 @@ func (r *Registry) beginAsk(id, server, key, session string) {

func (r *Registry) endAsk(id string) { r.asks.end(id) }

// markAskTaskCancelled flags the ask call id as abandoned by its owning
// protocol task's cancellation. The abandon route calls it before
// cancelling the ask, so the flag is in place before the call unwinds
// into the write ledger.
func (r *Registry) markAskTaskCancelled(id string) {
if r.asks == nil {
return
}
r.asks.mu.Lock()
defer r.asks.mu.Unlock()
if a, ok := r.asks.byID[id]; ok {
a.taskCancelled = true
}
}

// askTaskCancelled reports whether the ask call id was so flagged.
func (r *Registry) askTaskCancelled(id string) bool {
if r.asks == nil || id == "" {
return false
}
r.asks.mu.Lock()
defer r.asks.mu.Unlock()
a, ok := r.asks.byID[id]
return ok && a.taskCancelled
}

// Asks exposes the table so the routes below can read it.
func (r *Registry) Asks() *askTable { return r.asks }

Expand Down Expand Up @@ -568,6 +598,13 @@ func (s *Server) handleAskBegin(w http.ResponseWriter, r *http.Request) {
// by value rather than through r.Context().
ctx = mcpclient.WithClientCapabilities(ctx, mcpclient.ClientCapabilitiesFrom(caps))
ctx = mcpclient.WithCallerVersion(ctx, mcpclient.CallerVersionFrom(caps))
if mcpclient.TaskExecutionFrom(caps) {
// The call is a protocol task's inner call (SEP-2663): the
// mark rides by value like the caps above, so the write
// ledger can tell the task's cancellation from an unknown
// write outcome (#8922).
ctx = mcpclient.WithTaskExecution(ctx)
}
ctx = withCallSettings(ctx, cs)
var (
raw json.RawMessage
Expand Down Expand Up @@ -863,6 +900,18 @@ func answerFromResult(id, method string, raw json.RawMessage) (elicit.Answer, er

func (s *Server) handleAskAbandon(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
// A task's cancellation is flagged before the cancel lands, so the
// write ledger sees it when the call unwinds (#8922). The body is
// optional: ordinary abandons send none.
var body struct {
TaskCancelled bool `json:"taskCancelled"`
}
if r.Body != nil {
_ = json.NewDecoder(r.Body).Decode(&body)
}
if body.TaskCancelled {
s.reg.markAskTaskCancelled(id)
}
askRelays.Delete(id)
t, ok := s.taskStore().Cancel(id)
if !ok {
Expand Down
153 changes: 153 additions & 0 deletions pkgs/mcpx/internal/daemon/write_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"github.com/developing-today/code/pkgs/mcpx/internal/config"
"github.com/developing-today/code/pkgs/mcpx/internal/elicit"
"github.com/developing-today/code/pkgs/mcpx/internal/mcpclient"
"github.com/developing-today/code/pkgs/mcpx/internal/mcpserver"
"github.com/developing-today/code/pkgs/mcpx/internal/pool"
"github.com/developing-today/code/pkgs/mcpx/internal/testsupport"
)
Expand Down Expand Up @@ -519,3 +520,155 @@ func TestGateRefusalsAreTyped(t *testing.T) {
t.Errorf("callErrorBody(plain error).Code = %q, want empty", body.Code)
}
}

// (#8922) A task's inner call whose task context is cancelled — the
// client cancelled the task (tasks/cancel), the disposition the task
// store owns and reports — must not record an unknown write outcome:
// the outcome is accounted for, and recording it refused every later
// non-read-only call to the server (the conformance tasks cascade:
// the suite cancels the task it just created as cleanup, and the
// in-flight slow_compute aborted with the cancellation). Oracle: with
// the task mark, a mid-call cancellation returns the raw call error
// and leaves the ledger empty; without the mark, the same cancellation
// still records ErrUnknownOutcome, so the exemption stays scoped to
// task execution.
func TestCallWithLedgerTaskCancellationDoesNotRecordUnknownOutcome(t *testing.T) {
run := func(t *testing.T, mark int) (error, bool) {
t.Helper()
ledger, err := OpenWriteLedger(t.TempDir())
if err != nil {
t.Fatal(err)
}
r := writePolicyRegistry("allow")
r.writeLedger = ledger
cfg := &config.Config{MCPServers: map[string]*config.Server{
"demo": {Name: "demo", Command: testsupport.FakeMCPBinary(t)},
}}
resolved, err := cfg.Resolve("demo")
if err != nil {
t.Fatalf("resolve: %v", err)
}
scopeKey, _ := resolved.Scope.Key(config.CallContext{})
p := pool.New(resolved)
t.Cleanup(p.Close)
warmCtx, warmCancel := context.WithTimeout(context.Background(), 90*time.Second)
defer warmCancel()
if _, err := p.Call(warmCtx, config.ResolvedScope{Key: scopeKey}, "echo", map[string]any{"message": "warm"}); err != nil {
t.Fatalf("warm-up call: %v", err)
}
ctx, cancel := context.WithCancel(context.Background())
switch mark {
case 1:
ctx = mcpserver.MarkWithinTask(ctx)
case 2:
// The mark as the daemon API carries it: restored from the
// X-Mcpx-Task-Execution header (see daemon.TaskExecutionHeader).
ctx = mcpclient.WithTaskExecution(ctx)
}
go func() {
time.Sleep(300 * time.Millisecond)
cancel()
}()
defer cancel()
_, callErr := r.callWithLedger(ctx, p, "demo", "slow", map[string]any{"ms": 30000}, config.ResolvedScope{Key: scopeKey}, "call")
if callErr == nil {
t.Fatal("slow call unexpectedly succeeded")
}
_, blocked := ledger.Lookup("demo")
return callErr, blocked
}

callErr, blocked := run(t, 1)
var unknown ErrUnknownOutcome
if errors.As(callErr, &unknown) {
t.Fatalf("task-cancelled call = %v, want the raw call error", callErr)
}
if blocked {
t.Fatal("task-cancelled call recorded an unknown outcome")
}

callErr, blocked = run(t, 2)
if errors.As(callErr, &unknown) {
t.Fatalf("header-marked task-cancelled call = %v, want the raw call error", callErr)
}
if blocked {
t.Fatal("header-marked task-cancelled call recorded an unknown outcome")
}

callErr, blocked = run(t, 0)
if !errors.As(callErr, &unknown) {
t.Fatalf("unmarked cancelled call = %T %v, want ErrUnknownOutcome", callErr, callErr)
}
if !blocked {
t.Fatal("unmarked cancelled call recorded no unknown outcome")
}
}

// An interruptible (ask) call starts before its task exists, so no
// context mark can ride with it; the exemption arrives retroactively
// when the task's cancellation abandons the ask and the daemon flags
// the ask id (Registry.markAskTaskCancelled, #8922).
func TestCallWithLedgerAskTaskCancellationDoesNotRecordUnknownOutcome(t *testing.T) {
run := func(t *testing.T, flagged bool) (error, bool) {
t.Helper()
ledger, err := OpenWriteLedger(t.TempDir())
if err != nil {
t.Fatal(err)
}
r := writePolicyRegistry("allow")
r.writeLedger = ledger
if r.asks == nil {
r.asks = newAskTable()
}
cfg := &config.Config{MCPServers: map[string]*config.Server{
"demo": {Name: "demo", Command: testsupport.FakeMCPBinary(t)},
}}
resolved, err := cfg.Resolve("demo")
if err != nil {
t.Fatalf("resolve: %v", err)
}
scopeKey, _ := resolved.Scope.Key(config.CallContext{})
p := pool.New(resolved)
t.Cleanup(p.Close)
warmCtx, warmCancel := context.WithTimeout(context.Background(), 90*time.Second)
defer warmCancel()
if _, err := p.Call(warmCtx, config.ResolvedScope{Key: scopeKey}, "echo", map[string]any{"message": "warm"}); err != nil {
t.Fatalf("warm-up call: %v", err)
}
r.beginAsk("ask-1", "demo", scopeKey, "")
defer r.endAsk("ask-1")
if flagged {
r.markAskTaskCancelled("ask-1")
}
ctx, cancel := context.WithCancel(context.Background())
ctx = withAskCall(ctx, "ask-1")
go func() {
time.Sleep(300 * time.Millisecond)
cancel()
}()
defer cancel()
_, callErr := r.callWithLedger(ctx, p, "demo", "slow", map[string]any{"ms": 30000}, config.ResolvedScope{Key: scopeKey}, "ask")
if callErr == nil {
t.Fatal("slow call unexpectedly succeeded")
}
_, blocked := ledger.Lookup("demo")
return callErr, blocked
}

callErr, blocked := run(t, true)
var unknown ErrUnknownOutcome
if errors.As(callErr, &unknown) {
t.Fatalf("task-cancelled ask call = %v, want the raw call error", callErr)
}
if blocked {
t.Fatal("task-cancelled ask call recorded an unknown outcome")
}

callErr, blocked = run(t, false)
if !errors.As(callErr, &unknown) {
t.Fatalf("unflagged cancelled ask call = %T %v, want ErrUnknownOutcome", callErr, callErr)
}
if !blocked {
t.Fatal("unflagged cancelled ask call recorded no unknown outcome")
}
}
Loading