diff --git a/pkgs/mcpx/internal/cli/client.go b/pkgs/mcpx/internal/cli/client.go index fa313bd15b..7b33334f8a 100644 --- a/pkgs/mcpx/internal/cli/client.go +++ b/pkgs/mcpx/internal/cli/client.go @@ -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) { diff --git a/pkgs/mcpx/internal/cli/serve.go b/pkgs/mcpx/internal/cli/serve.go index 05c6d8b168..c320122007 100644 --- a/pkgs/mcpx/internal/cli/serve.go +++ b/pkgs/mcpx/internal/cli/serve.go @@ -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 diff --git a/pkgs/mcpx/internal/cli/serve_ask.go b/pkgs/mcpx/internal/cli/serve_ask.go index a341774647..ccf29544fe 100644 --- a/pkgs/mcpx/internal/cli/serve_ask.go +++ b/pkgs/mcpx/internal/cli/serve_ask.go @@ -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 @@ -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) } } diff --git a/pkgs/mcpx/internal/daemon/callerr.go b/pkgs/mcpx/internal/daemon/callerr.go index 8a4e77e5d5..5c940dabe1 100644 --- a/pkgs/mcpx/internal/daemon/callerr.go +++ b/pkgs/mcpx/internal/daemon/callerr.go @@ -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 diff --git a/pkgs/mcpx/internal/daemon/registry.go b/pkgs/mcpx/internal/daemon/registry.go index c542749309..27963a755c 100644 --- a/pkgs/mcpx/internal/daemon/registry.go +++ b/pkgs/mcpx/internal/daemon/registry.go @@ -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" @@ -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 diff --git a/pkgs/mcpx/internal/daemon/routes_proto.go b/pkgs/mcpx/internal/daemon/routes_proto.go index cf4fa37725..7617201938 100644 --- a/pkgs/mcpx/internal/daemon/routes_proto.go +++ b/pkgs/mcpx/internal/daemon/routes_proto.go @@ -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 @@ -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 } @@ -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 @@ -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 { diff --git a/pkgs/mcpx/internal/daemon/write_policy_test.go b/pkgs/mcpx/internal/daemon/write_policy_test.go index 1298bcf3bb..a636f86819 100644 --- a/pkgs/mcpx/internal/daemon/write_policy_test.go +++ b/pkgs/mcpx/internal/daemon/write_policy_test.go @@ -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" ) @@ -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") + } +} diff --git a/pkgs/mcpx/internal/mcpclient/modern.go b/pkgs/mcpx/internal/mcpclient/modern.go index 2796a298fc..317260ce1f 100644 --- a/pkgs/mcpx/internal/mcpclient/modern.go +++ b/pkgs/mcpx/internal/mcpclient/modern.go @@ -283,6 +283,28 @@ func CallerVersionFrom(ctx context.Context) string { return v } +type taskExecutionKey struct{} + +// WithTaskExecution marks ctx as carrying a call that runs as the inner +// call of a protocol task (SEP-2663): the MCP server turns a task-augmented +// tools/call into a task and runs the call under the task's own context. +// The daemon's write ledger reads the mark (restored from +// daemon.TaskExecutionHeader on /v1/call and /v1/ask) to tell a task +// cancellation -- the write was abandoned by the client and its outcome is +// moot -- from a call whose outcome is genuinely unknown (#8922). +func WithTaskExecution(ctx context.Context) context.Context { + return context.WithValue(ctx, taskExecutionKey{}, true) +} + +// TaskExecutionFrom reports whether ctx was marked by WithTaskExecution. +func TaskExecutionFrom(ctx context.Context) bool { + if ctx == nil { + return false + } + v, _ := ctx.Value(taskExecutionKey{}).(bool) + return v +} + // CallerLegacy reports whether ctx carries a caller revision from before // 2026-07-28 -- one that has a session a server can send requests on. func CallerLegacy(ctx context.Context) bool { diff --git a/pkgs/mcpx/internal/mcpclient/tasks.go b/pkgs/mcpx/internal/mcpclient/tasks.go index 84404270cd..1f34b668db 100644 --- a/pkgs/mcpx/internal/mcpclient/tasks.go +++ b/pkgs/mcpx/internal/mcpclient/tasks.go @@ -226,6 +226,21 @@ func (c *Client) callToolAsLegacyTask(ctx context.Context, name string, args any Task *legacyTask `json:"task"` } if err := json.Unmarshal(created, &wrap); err != nil || wrap.Task == nil || wrap.Task.TaskID == "" { + // A server may answer a task-augmented call in line when the + // tool finishes at once -- the extension permits it, and the + // fixture's failing_job does exactly that. A CallToolResult + // payload is the call's definitive answer, not a malformed + // handle: return it as the result. Anything else stays the + // malformed-response error it was. + var inLine struct { + Content []json.RawMessage `json:"content"` + IsError bool `json:"isError"` + StructuredContent json.RawMessage `json:"structuredContent"` + } + if jerr := json.Unmarshal(created, &inLine); jerr == nil && + (len(inLine.Content) > 0 || inLine.IsError || len(inLine.StructuredContent) > 0) { + return created, nil + } return nil, fmt.Errorf("mcpx: tool %s: malformed task-augmented response: expected a {task} handle, got %s", name, shortRaw(created)) } task := wrap.Task diff --git a/pkgs/mcpx/internal/mcpserver/tasks.go b/pkgs/mcpx/internal/mcpserver/tasks.go index e7abc88246..30622739a1 100644 --- a/pkgs/mcpx/internal/mcpserver/tasks.go +++ b/pkgs/mcpx/internal/mcpserver/tasks.go @@ -179,6 +179,19 @@ func isWithinTask(ctx context.Context) bool { return v } +// MarkWithinTask is withinTask for cross-package callers (the daemon's +// ledger classification, tests): it stamps the context as a task's +// inner call. +func MarkWithinTask(ctx context.Context) context.Context { + return withinTask(ctx) +} + +// WithinTask is isWithinTask for cross-package callers: it reports +// whether the context is a task's inner call (see runInner). +func WithinTask(ctx context.Context) bool { + return isWithinTask(ctx) +} + // Tool-level task support, from execution.taskSupport. const ( supportForbidden = "forbidden" @@ -451,6 +464,22 @@ func (s *Server) askTask(ctx context.Context, req request, peer Peer) (*response return s.created(req, t.TaskID), true } +// abandonAsked stops an asked call. A task's own cancellation goes +// through the driver's AbandonTask when it offers one, so the daemon can +// tell a protocol task's cancellation (SEP-2663 -- the task store owns +// the disposition, and the write ledger must not record the call's +// outcome as unknown, #8922) from a request the client merely dropped, +// which keeps the ordinary Abandon. +func (s *Server) abandonAsked(callID string, forTask bool) { + if forTask { + if ta, ok := s.Ask.(interface{ AbandonTask(string) }); ok { + ta.AbandonTask(callID) + return + } + } + s.Ask.Abandon(callID) +} + // driveAsked is the body of an asked task: wait for the call, publishing the // questions it is waiting on as the task's inputRequests. func (s *Server) driveAsked(ctx context.Context, req request, peer Peer, callID string) (any, *tasks.Fault) { @@ -459,7 +488,7 @@ func (s *Server) driveAsked(ctx context.Context, req request, peer Peer, callID for { if ctx.Err() != nil { // Cancelled: tasks/cancel, or the TTL. Nobody will answer. - s.Ask.Abandon(callID) + s.abandonAsked(callID, true) return nil, &tasks.Fault{Code: codeInternal, Message: "the task was cancelled"} } out, err := s.Ask.Poll(ctx, callID, tm.AskPoll)