From aa75a2de9f11ae88a99822a5d37b3a7f0bec6c9a Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 09:44:56 +0800 Subject: [PATCH 1/3] fix(a2a): include the ListTasks timestamp boundary Signed-off-by: tercel --- a2a/typescript/src/server/factory.ts | 2 + a2a/typescript/src/server/task-persistence.ts | 42 ++++++--- .../tests/security/task-scoping.test.ts | 88 ++++++++++++++++++- 3 files changed, 117 insertions(+), 15 deletions(-) diff --git a/a2a/typescript/src/server/factory.ts b/a2a/typescript/src/server/factory.ts index 823e6eea..e03fd477 100644 --- a/a2a/typescript/src/server/factory.ts +++ b/a2a/typescript/src/server/factory.ts @@ -123,6 +123,8 @@ export interface A2AServerCreateOptions { * `InMemoryTaskStore` scopes by `ownerResolver`; a third-party store must do * the same. Upstream states the requirement as a SHOULD on the `TaskStore` * contract, so it cannot be enforced here. + * Custom `list` implementations must treat `statusTimestampAfter` as an + * inclusive lower bound applied before pagination. */ taskStore?: TaskStore; auth?: Authenticator; diff --git a/a2a/typescript/src/server/task-persistence.ts b/a2a/typescript/src/server/task-persistence.ts index ca06022d..bf0ce6c1 100644 --- a/a2a/typescript/src/server/task-persistence.ts +++ b/a2a/typescript/src/server/task-persistence.ts @@ -5,7 +5,7 @@ import type { AgentCard, CancelTaskRequest, Message, SendMessageRequest, StreamResponse, Task, TaskStatus, } from "@a2a-js/sdk"; import { RequestMalformedError, TaskNotFoundError } from "@a2a-js/sdk/errors"; -import { DefaultRequestHandler, resolveUserScope } from "@a2a-js/sdk/server"; +import { DefaultRequestHandler, InMemoryTaskStore, resolveUserScope } from "@a2a-js/sdk/server"; import type { AgentExecutionEvent, AgentExecutor, ExecutionEventBus, ExtendedAgentCardProvider, RequestContext, ServerCallContext, TaskStore, } from "@a2a-js/sdk/server"; @@ -20,8 +20,16 @@ const TERMINAL_STATES = new Set([ ]); const DEFAULT_PAGE_SIZE = 50; -const SCOPED_SCAN_PAGE_SIZE = 100; -const SCOPED_PAGE_TOKEN = /^v1\.([1-9][0-9]{0,14})\.([0-9a-f]{64})$/; +const SCAN_PAGE_SIZE = 100; +const PAGE_TOKEN = /^v1\.([1-9][0-9]{0,14})\.([0-9a-f]{64})$/; + +function timestampNanos(timestamp?: string): bigint | undefined { + if (!timestamp) return undefined; + const millis = Date.parse(timestamp); + if (Number.isNaN(millis)) return undefined; + const fraction = /\.\d{3}(\d{1,6})\d*(?:Z|[+-]\d{2}:?\d{2})$/i.exec(timestamp)?.[1] ?? ""; + return BigInt(millis) * 1_000_000n + BigInt(fraction.padEnd(6, "0")); +} function isTerminal(state: TaskState | undefined): boolean { return state !== undefined && TERMINAL_STATES.has(state); @@ -151,8 +159,12 @@ class TaskPersistence implements TaskStore { // optional filter expects an absent key despite the generated type. const params = status === TaskState.TASK_STATE_UNSPECIFIED ? (withoutStatus as typeof request) : request; const identity = identityOf(context); - const authority = identity?.authorityKey?.(); - if (authority != null) return this.listScoped(params, context, authority); + const authority = identity?.authorityKey?.() ?? null; + // The SDK's in-memory implementation uses a strict Date comparison. Apply the + // inclusive cutoff before paging ourselves, with the original cutoff in the cursor. + const after = this.store.list === InMemoryTaskStore.prototype.list + ? timestampNanos(params.statusTimestampAfter) : undefined; + if (authority !== null || after !== undefined) return this.listVisible(params, context, authority, after); const page = await this.store.list(params, context); const tasks = page.tasks.filter(task => this.canRead(task, context)); @@ -166,20 +178,20 @@ class TaskPersistence implements TaskStore { }; } - private async listScoped( - params: Parameters[0], context: ServerCallContext, authority: string, + private async listVisible( + params: Parameters[0], context: ServerCallContext, authority: string | null, after?: bigint, ): ReturnType { const pageSize = params.pageSize ?? DEFAULT_PAGE_SIZE; if (!Number.isSafeInteger(pageSize) || pageSize < 1) { throw new RequestMalformedError("pageSize must be a positive integer"); } const binding = JSON.stringify([ - context.tenant ?? null, authority, params.contextId, params.status, params.statusTimestampAfter, + context.tenant ?? null, resolveUserScope(context), authority, params.contextId, params.status, params.statusTimestampAfter, params.historyLength, params.includeArtifacts, ]); let offset = 0; if (params.pageToken) { - const cursor = SCOPED_PAGE_TOKEN.exec(params.pageToken); + const cursor = PAGE_TOKEN.exec(params.pageToken); if (!cursor || !timingSafeEqual(this.signOffset(binding, cursor[1]), Buffer.from(cursor[2], "hex"))) { throw new RequestMalformedError("Invalid page token"); } @@ -189,15 +201,19 @@ class TaskPersistence implements TaskStore { // Page and count the visible results, never expose storage cursors or counts. const tasks: Task[] = []; const seenTokens = new Set(); + const storeParams = after === undefined ? params : { ...params, statusTimestampAfter: undefined }; let storageToken = ""; let totalSize = 0; do { - const page = await this.store.list({ ...params, pageSize: SCOPED_SCAN_PAGE_SIZE, pageToken: storageToken }, context); + const page = await this.store.list({ ...storeParams, pageSize: SCAN_PAGE_SIZE, pageToken: storageToken }, context); for (const task of page.tasks) { - if (this.canRead(task, context)) { - if (offset <= totalSize && totalSize < offset + pageSize) tasks.push(task); - totalSize++; + if (!this.canRead(task, context)) continue; + if (after !== undefined) { + const statusTime = timestampNanos(task.status?.timestamp); + if (statusTime === undefined || statusTime < after) continue; } + if (offset <= totalSize && totalSize < offset + pageSize) tasks.push(task); + totalSize++; } storageToken = page.nextPageToken; if (storageToken && seenTokens.has(storageToken)) throw new Error("TaskStore repeated a pagination token"); diff --git a/a2a/typescript/tests/security/task-scoping.test.ts b/a2a/typescript/tests/security/task-scoping.test.ts index 3f0dbdfb..8621dcde 100644 --- a/a2a/typescript/tests/security/task-scoping.test.ts +++ b/a2a/typescript/tests/security/task-scoping.test.ts @@ -14,9 +14,11 @@ import { describe, it, expect, vi, afterAll } from "vitest"; import request from "supertest"; import type { Express } from "express"; import type { Server } from "node:http"; -import { InMemoryTaskStore } from "@a2a-js/sdk/server"; +import { TaskState } from "@a2a-js/sdk"; +import { InMemoryTaskStore, type TaskStore } from "@a2a-js/sdk/server"; import { ACL, Executor, Registry as CoreRegistry, createIdentity } from "apcore-js"; import jwt from "jsonwebtoken"; +import { anonymousContext } from "../../src/server/context.js"; import { A2AServerFactory } from "../../src/server/factory.js"; import { JWTAuthenticator } from "../../src/auth/jwt.js"; import type { Registry } from "../../src/adapters/agent-card.js"; @@ -58,7 +60,7 @@ const bearerIsPrincipal: Authenticator = { securitySchemes: () => ({ bearerAuth: { type: "http", scheme: "bearer" } }), }; -function makeApp(auth?: Authenticator): Express { +function makeApp(auth?: Authenticator, taskStore?: TaskStore): Express { const { app } = new A2AServerFactory().create( makeRegistry(), { callAsync: vi.fn().mockResolvedValue({ result: "ok" }) }, @@ -68,6 +70,7 @@ function makeApp(auth?: Authenticator): Express { version: "1", url: "http://localhost", auth, + taskStore, pushNotifications: true, }, ); @@ -413,3 +416,84 @@ it("paginates unfiltered and filtered results using live JSON-RPC with caller is expect((byContext.result as Page).tasks.map(t => t.id)).toEqual([page.tasks[0].id]); } }); + +it.each(["anonymous", "scoped"])("includes the exact status timestamp boundary in %s listings", async (mode) => { + const registry = new CoreRegistry(); + await registry.register("echo", { + description: "Echo a result", + inputSchema: { type: "object" }, outputSchema: { type: "object" }, + execute: () => ({ result: "ok" }), + }); + const executor = new Executor({ registry, acl: new ACL([{ + callers: ["@external"], targets: ["echo"], effect: "allow", + conditions: mode === "scoped" ? { scopes: ["read"] } : undefined, + }]) }); + const auth: Authenticator | undefined = mode === "scoped" ? { + ...bearerIsPrincipal, + authenticate: () => createIdentity(ALICE, "user", [], {}, { scopes: ["read"] }), + } : undefined; + const { app } = new A2AServerFactory().create(registry as never, executor, { + name: "Timestamp Agent", description: "d", version: "1", url: "http://localhost", auth, + }); + + let equal: string; + let newer: string; + vi.useFakeTimers({ toFake: ["Date"] }); + try { + vi.setSystemTime(new Date("2026-02-01T01:59:59.999Z")); + await submit(app, ALICE, "older"); + vi.setSystemTime(new Date("2026-02-01T02:00:00.000Z")); + equal = await submit(app, ALICE, "equal"); + vi.setSystemTime(new Date("2026-02-01T02:00:00.001Z")); + newer = await submit(app, ALICE, "newer"); + } finally { + vi.useRealTimers(); + } + + const filter = { pageSize: 1, statusTimestampAfter: "2026-02-01T03:00:00.000000000+01:00" }; + const first = await rpc(app, ALICE, "ListTasks", filter); + expect(first.error).toBeUndefined(); + expect(first.result).toMatchObject({ tasks: [{ id: newer }], totalSize: 2, pageSize: 1 }); + expect(first.result?.nextPageToken).toBeTruthy(); + + const second = await rpc(app, ALICE, "ListTasks", { ...filter, pageToken: first.result?.nextPageToken }); + expect(second.error).toBeUndefined(); + expect(second.result).toMatchObject({ tasks: [{ id: equal }], totalSize: 2, nextPageToken: "" }); + + const fractional = await rpc(app, ALICE, "ListTasks", { statusTimestampAfter: "2026-02-01T02:00:00.000000001Z" }); + expect(fractional.error).toBeUndefined(); + expect(fractional.result).toMatchObject({ tasks: [{ id: newer }], totalSize: 1, nextPageToken: "" }); +}); + +it("compares fractional timestamps in an explicitly provided SDK store", async () => { + const store = new InMemoryTaskStore(); + const context = anonymousContext(); + for (const [id, fraction] of [["older", "001"], ["equal", "002"], ["newer", "003"]]) { + await store.save({ + id, contextId: "fractional", + status: { state: TaskState.TASK_STATE_COMPLETED, timestamp: `2026-02-01T02:00:00.000000${fraction}Z` }, + }, context); + } + const app = makeApp(undefined, store); + const filter = { statusTimestampAfter: "2026-02-01T03:00:00.000000002+01:00" }; + const response = await rpc(app, ALICE, "ListTasks", filter); + expect(response.error).toBeUndefined(); + expect(response.result).toMatchObject({ tasks: [{ id: "newer" }, { id: "equal" }], totalSize: 2, pageSize: 50 }); + + const maxPage = await rpc(app, ALICE, "ListTasks", { ...filter, pageSize: 100 }); + expect(maxPage.result).toMatchObject({ totalSize: 2, pageSize: 100 }); + const oversizedPage = await rpc(app, ALICE, "ListTasks", { ...filter, pageSize: 101 }); + expect(oversizedPage.error?.message).toBe("pageSize must be between 1 and 100"); +}); + +it("passes the original timestamp filter to a custom store", async () => { + const backing = new InMemoryTaskStore(); + const list = vi.fn(backing.list.bind(backing)); + const app = makeApp(undefined, { + load: backing.load.bind(backing), save: backing.save.bind(backing), list, + }); + const statusTimestampAfter = "2026-02-01T03:00:00.000000002+01:00"; + const response = await rpc(app, ALICE, "ListTasks", { statusTimestampAfter }); + expect(response.error).toBeUndefined(); + expect(list).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ statusTimestampAfter }), expect.anything()); +}); From 805fb60f6796d4ab6f331263490ffc69ae048bcf Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 09:44:56 +0800 Subject: [PATCH 2/3] test(mcp): verify request cancellation across SDKs Signed-off-by: tercel --- mcp/conformance/README.md | 32 +-- .../fixtures/request_cancellation.json | 29 +++ mcp/docs/features/execution-router.md | 64 +++--- mcp/docs/features/transport-manager.md | 10 +- .../tests/server/test_request_cancellation.py | 96 +++++--- mcp/rust/src/input_contract_tests.rs | 10 +- mcp/rust/src/lib.rs | 3 + mcp/rust/src/server/transport.rs | 104 ++++++--- mcp/typescript/src/server/router.ts | 10 +- .../tests/server/request-cancellation.test.ts | 216 +++++++++++++----- 10 files changed, 396 insertions(+), 178 deletions(-) create mode 100644 mcp/conformance/fixtures/request_cancellation.json diff --git a/mcp/conformance/README.md b/mcp/conformance/README.md index 716d9620..ff0895cc 100644 --- a/mcp/conformance/README.md +++ b/mcp/conformance/README.md @@ -1,10 +1,8 @@ # Cross-language conformance fixtures -These JSON files are the **behavioural contract** shared by the three apcore-mcp bridges. Each one -pins a mapping that must produce byte-identical results in `apcore-mcp-python`, -`apcore-mcp-typescript` and `apcore-mcp-rust`. They are data, not tests: every SDK loads them from -this directory and runs its own assertions against them, so a divergence surfaces as a failing test -in whichever bridge drifted rather than as a review comment. +These JSON files are the **behavioural contract** shared by `apcore-mcp-python`, +`apcore-mcp-typescript` and `apcore-mcp-rust`. Every SDK loads the data from this directory and +runs its own assertions against the same expected results. Fixtures live in `fixtures/`. Nothing else in this directory is normative. @@ -15,6 +13,7 @@ Fixtures live in `fixtures/`. Nothing else in this directory is normative. | `tool_mapping.json` | `MCPServerFactory.build_tool(descriptor)` | 2 | apcore Module → MCP `Tool` (SRS §7.1). Contract 2.0: runtime input-schema preservation, basic field mapping, and that `x-` extensions survive into the MCP input schema. | | `openai_tool_mapping.json` | `OpenAIConverter.convert_descriptor(descriptor, embed_annotations, strict)` | 4 | apcore Module → OpenAI function definition (SRS §7.2). Module-ID normalization (`.` → `-`), `x-llm-description` priority, `x-` stripping, and `mcp_` extras reaching the description. | | `output_redaction.json` | `ExecutionRouter` output redaction | 2 | F-038. `x-sensitive` fields masked with `***REDACTED***`; unmarked fields left alone under an empty schema. | +| `request_cancellation.json` | `tools/call`, `notifications/cancelled` | 2 | A direct tool call observes cancellation and exits before an unrelated call is released. Covers different request IDs on one stdio connection and the same request ID in two initialized Streamable HTTP sessions. | | `acl_config.json` | Config Bus `mcp.acl` loading | 11 + 21 error | How a raw `mcp.acl` JSON value becomes an ACL — null/empty means no ACL, `default_effect`, rule ordering, the `approval` key's closed value set, and PROTOCOL_SPEC §6.2.1's closed pattern-array shape with its normative validation order (`contract_version` 1.2). | | `system_surface.json` | `tools/list`, `resources/list`, `resources/templates/list` | 9 modules (3 tools + 3 resources + 3 templates), plus 6 `not_tools` negatives | Each canonical `system.*` module's exact MCP primitive and its name or URI, including the RFC 6570 `{?period}` suffix on `system.usage.module`. **Not case-shaped** — it is a declarative surface description with `tools` / `not_tools` / `resources` / `resource_templates` / `extension` keys rather than `test_cases`. Added in 0.19.0. | | `middleware_config.json` | Config Bus `mcp.middleware` loading | 6 + 4 error | How a raw `mcp.middleware` array becomes a middleware chain — supported types, per-type defaults, and order preservation. | @@ -23,9 +22,8 @@ Fixtures live in `fixtures/`. Nothing else in this directory is normative. ### Runtime input contract -Publish the canonical fixture changes before the SDK commits: SDK CI checks out -this repository's default branch. A missing new fixture must fail CI rather than -being replaced by private fixture copies or skipped tests. +Commit canonical fixture changes with their SDK drivers. CI loads the fixture +from the Surfaces checkout under test and fails if it is missing. `mcp_input_contract.json` (contract 1.0) pins issue #20 using 11 schemas and 27 valid/invalid inputs. All three SDK drivers use real registries and executors to @@ -104,8 +102,8 @@ Do not "fix" a bridge to match a known gap; fix it upstream, then delete the gap ## Adding or changing a fixture -1. A fixture change is a **contract change**. Land it here first, then update all three SDKs — a - fixture that only one bridge satisfies is worse than no fixture. +1. A fixture change is a **contract change**. Update the fixture and the affected drivers in all + three SDKs together. 2. Keep case `id`s stable; SDK tests reference them in failure messages. 3. Give every case a `description` that says what would be wrong if it failed. 4. Prefer inputs with no incidental ambiguity. `output_redaction.json`'s @@ -115,20 +113,14 @@ Do not "fix" a bridge to match a known gap; fix it upstream, then delete the gap ## How each SDK loads them -All three walk up from the test file looking for `apcore-mcp/conformance/fixtures`, so a sibling -checkout of this repo is found automatically, as is the CI layout where the spec repo is checked out -inside the workspace. All three honour the same environment override — -**`APCORE_CONFORMANCE_FIXTURES`**, pointing at a fixtures directory — and each decides for itself -whether a missing directory is a skip (local dev) or a failure (CI): +The SDKs read `mcp/conformance/fixtures` in the Surfaces checkout. They also honour +**`APCORE_CONFORMANCE_FIXTURES`** for an explicit fixtures directory. Missing fixtures fail CI. | SDK | Loader | |---|---| | Python | `tests/conformance_fixtures.py` | | TypeScript | `tests/conformance-fixtures.ts` | -| Rust | `conformance_fixture()` in the `src/server/router.rs` test module | +| Rust | `tests/common/mod.rs` for integration tests and the inline input and cancellation tests. Some older inline tests use their own `conformance_fixture()` helper. | -Rust's conformance assertions are inline `#[cfg(test)]` tests inside `src/`, not files under -`tests/` — a coverage audit that only looks at `tests/` will wrongly conclude Rust skips a fixture. - -If you are implementing a fourth bridge, these eight fixtures plus +If you are implementing a fourth bridge, these fixtures plus [`docs/examples-spec.md`](../docs/examples-spec.md) are the compliance surface to target. diff --git a/mcp/conformance/fixtures/request_cancellation.json b/mcp/conformance/fixtures/request_cancellation.json new file mode 100644 index 00000000..b3fa6907 --- /dev/null +++ b/mcp/conformance/fixtures/request_cancellation.json @@ -0,0 +1,29 @@ +{ + "description": "A wire cancellation notification reaches the Context token of a running direct tool call. The selected tool observes cancellation and exits before the test releases the peer, which returns its normal result.", + "entry_point": "MCP tools/call and notifications/cancelled", + "spec": "features/execution-router.md#cancellation-handling", + "test_cases": [ + { + "id": "stdio_other_request_survives", + "description": "Two calls with distinct request IDs share a stdio connection. Only the selected call is cancelled.", + "transport": "stdio", + "target": "selected-stdio", + "peer": "parallel-stdio", + "expected": { + "cancelled": "selected-stdio", + "peer_result": { "name": "parallel-stdio" } + } + }, + { + "id": "http_same_request_id_in_another_session_survives", + "description": "Two initialized Streamable HTTP sessions run calls with the same request ID. Only the call in the notifying session is cancelled.", + "transport": "streamable-http", + "target": "selected-http", + "peer": "parallel-http", + "expected": { + "cancelled": "selected-http", + "peer_result": { "name": "parallel-http" } + } + } + ] +} diff --git a/mcp/docs/features/execution-router.md b/mcp/docs/features/execution-router.md index c87e1d89..c86743fc 100644 --- a/mcp/docs/features/execution-router.md +++ b/mcp/docs/features/execution-router.md @@ -143,37 +143,37 @@ When the request carries `_meta.trace == true`, `version_hint` may be unavailabl ## Cancellation Handling -> **Status (v0.14.x, post-sync):** The `ExecutionRouter.cancel(call_id, reason)` public API now exists in all three SDKs (Python `ExecutionRouter.cancel`, TypeScript `ExecutionRouter.cancel`, Rust `ExecutionRouter::cancel_call`) with end-to-end wiring through `handle_call` (auto-registers a CancelToken per call, releases in a `finally` block / RAII guard, with FIFO-bounded eviction at 4096 entries). The router's cancel layer is now functional for callers that invoke `router.cancel(call_id)` directly. -> -> **MCP `notifications/cancelled` integration (clarification):** The MCP Python and TypeScript SDKs both ALREADY handle inbound `notifications/cancelled` *internally* — Python via `mcp.shared.session._receive_loop` which calls `self._in_flight[cancelled_id].cancel()` (anyio cancel scope), TypeScript via the SDK's built-in `setNotificationHandler(CancelledNotificationSchema, ...)` registered at protocol construction time. So inbound MCP cancel notifications **already** abort the in-flight `tools/call` request task at the SDK level — the executing `handle_call` will see a `CancelledError` / equivalent at its next `.await`. The router-level `cancel(call_id)` API is therefore a *cooperative* additional layer for modules that want to check `ctx.cancel_token.is_cancelled` and exit gracefully without raising; it is orthogonal to MCP-level task cancellation, not a replacement. - -### What works today (v0.14.0) - -- **Process-level cancellation (stdio):** When the parent MCP client closes the stdio pipe, the transport manager exits the read loop and the server shuts down. In-flight tool calls are abandoned (no cooperative drain). All three SDKs (Python, TypeScript, Rust) behave this way. -- **Async-task cancellation (Rust only):** Rust's `TransportManager` accepts a `cancel_handler` callback (`set_cancel_handler` / `notify_cancel`). At server build time, `apcore_mcp::APCoreMCP` wires this callback to `AsyncTaskBridge::cancel_session_tasks(session_key)` and `AsyncTaskBridge::cancel(task_id)`. When an MCP `notifications/cancelled` message is received, async-task-bridge tasks bound to that session are cooperatively cancelled. **Synchronous** tool calls (those routed through `ExecutionRouter::handle_call`) are NOT cancelled — there is no `CancelToken` map and no `ContextVar` propagation. Python and TypeScript SDKs do not implement this at all. -- **Error mapping for explicit `ExecutionCancelledError`:** if a module itself raises `ExecutionCancelledError` (e.g., on a timeout), the router catches it and forwards to the Error Mapper, which emits MCP error code `EXECUTION_CANCELLED`. This is downstream-only; nothing in the router *initiates* cancellation in response to MCP `notifications/cancelled`. - -### What's still missing today - -What's still missing today is automatic transport-level wiring of MCP `notifications/cancelled` for sync calls in Python+TS — Rust handles this via `TransportManager::set_cancel_handler` / `notify_cancel`. The cross-SDK ExecutionRouter dispatcher is a 0.15.0 roadmap item. - -> **Note:** Rust uses `cancel_call(call_id, reason)` instead of `cancel` due to Rust naming idiom — same semantics. - -### Roadmap (planned for 0.15.0) - -The following design is preserved verbatim from earlier drafts as the implementation target: - -- A per-server `Dict[call_id, CancelToken]` (guarded by a lock). On tool-call entry, the router generates/extracts the MCP `call_id`, creates a fresh `CancelToken`, inserts into the map, and attaches it to the `Context` via `Context.create(cancel_token=token)`. On completion the entry is removed in `finally`. -- An `ExecutionRouter.cancel(call_id, reason)` method that: - 1. Looks up the `CancelToken` for `call_id`. - 2. Calls `token.cancel()` (cooperative signal picked up by the module's next `token.check()`). - 3. Also calls `executor.cancel(call_id)` when the apcore feature is available. - 4. Emits a `mcp.call.cancelled` observability event with the reason. -- `ContextVar` propagation so the active token is visible across `asyncio.to_thread()` boundaries. -- Race handling: before-start tombstones, after-complete no-op-with-debug, idempotent concurrent-cancel. -- Cross-transport parity (stdio, streamable-http, sse) — all transports parse `notifications/cancelled` and forward to `ExecutionRouter.cancel`. - -The `EXECUTION_CANCELLED` error code is already reserved in all three SDKs for this purpose; only the dispatcher half of the contract remains to be implemented. +### In-flight tool calls + +Python, TypeScript, and Rust forward [MCP request cancellation](https://modelcontextprotocol.io/specification/2025-11-25/basic/utilities/cancellation) +to the APCore `CancelToken` for the in-flight `tools/call` on stdio and +initialized Streamable HTTP sessions. The transport resolves +`params.requestId` within the connection or HTTP session that sent the +notification. Other calls in that session and calls with the same request ID +in other sessions continue. + +| SDK | How the notification reaches the module | +|---|---| +| Python | The MCP SDK cancels the request coroutine. The factory flips the invocation token before cancelling and awaiting the router task. | +| TypeScript | The MCP SDK aborts the request signal. The router's abort listener flips the invocation token. | +| Rust | The transport flips the request-scoped token. Its child token is attached to the module's execution context. | + +Modules can poll the token in synchronous work or check it at asynchronous +work boundaries. Cancellation is cooperative. A module that starts a +subprocess or acquires a resource must stop that work and release the resource +when it observes cancellation or otherwise unwinds. Clients should discard +any response that races with their cancellation notification. + +### Programmatic calls and background tasks + +Programmatic callers use `ExecutionRouter.cancel(call_id, reason)` in Python +and TypeScript or `ExecutionRouter::cancel_call` in Rust. These APIs take the +router's call ID. If a module raises `ExecutionCancelledError` and the router +returns an error result, the Error Mapper uses `EXECUTION_CANCELLED`. + +APCore background tasks have their own lifecycle. Cancel a submitted task +with `__apcore_task_cancel` and its `task_id`. Session teardown has a +[separate background-task hook](transport-manager.md#contract-transportmanagerset_async_task_bridge). ## Notes @@ -192,7 +192,7 @@ The `EXECUTION_CANCELLED` error code is already reserved in all three SDKs for t ### Errors - Returns `(content, is_error=True, trace_id)` with ErrorMapper output — for all execution exceptions (ModuleNotFoundError, ACLDeniedError, etc.) - Returns `(content, is_error=True, None)` with validation message — when `validate_inputs=True` and schema fails -- Never raises; all exceptions are caught and converted to error tuples +- The router converts execution exceptions to error tuples. Transport-level request cancellation can interrupt the call. ### Returns - On success: tuple `(content: list[dict], is_error: bool, trace_id: str|None)` diff --git a/mcp/docs/features/transport-manager.md b/mcp/docs/features/transport-manager.md index 3540fcd0..3d0d6316 100644 --- a/mcp/docs/features/transport-manager.md +++ b/mcp/docs/features/transport-manager.md @@ -92,7 +92,7 @@ The manager installs signal handlers that trigger an internal shutdown event. Th - `streamable-http` is the modern, recommended network transport, replacing the legacy `sse` transport. - For embedded use (e.g., within a larger FastAPI app), the manager yields an ASGI app rather than running its own Uvicorn instance. -- **Cancellation Forwarding:** Rust: `set_cancel_handler` / `notify_cancel` (since 0.13.0). Python (post-TM-4 fix in 0.14.0): `set_async_task_bridge` + `transport_session_var` ContextVar — auto-wired by `serve()`/`async_serve()`. TypeScript: `setAsyncTaskBridge` (analogous wiring). The cross-SDK `ExecutionRouter.cancel(call_id, reason)` dispatcher remains a 0.15.0 roadmap item — see Execution Router "Cancellation Handling" section. +- On stdio and initialized Streamable HTTP sessions, `notifications/cancelled` signals the matching call's execution token. See [Execution Router cancellation handling](execution-router.md#cancellation-handling). --- @@ -107,9 +107,9 @@ The manager installs signal handlers that trigger an internal shutdown event. Th - No explicit bind errors (stdio is process-bound) ### Returns -- On success: None — blocks until the stdio connection closes (parent process terminates or closes pipe); in-flight calls are abandoned on close (no cooperative drain) +- Returns `None` in Python after the stdio connection closes and session cleanup runs. - Per-language method names: Python `run_stdio`, TypeScript `runStdio`, Rust `run_stdio`. All three SDKs implement this transport. -- Graceful teardown is signal-driven: the method installs SIGINT/SIGTERM handlers internally and returns when a shutdown signal fires or the stdio pipe closes. There is no separate `shutdown()` method — teardown is owned by this `run_*` call's signal-handling lifecycle. +- At end of input, Python tears down the MCP session, TypeScript closes its SDK transport and drains tracked work, and Rust drains requests already in flight. Use an explicit cancellation notification to signal an individual call while the connection is open. ### Properties - async: true @@ -185,7 +185,7 @@ The manager installs signal handlers that trigger an internal shutdown event. Th TM-4 transport-disconnect cancellation forwarding (0.14.0). Per-language method names: Python `set_async_task_bridge(bridge)`, TypeScript `setAsyncTaskBridge(bridge)`, Rust `set_cancel_handler(handler)` (with companion `notify_cancel(session_id)` since 0.13.0). All three SDKs share the contract below. -The transport scopes a per-connection session id (Python: `transport_session_var` ContextVar; TS: per-request closure; Rust: tokio task-local). When `factory.handle_call_tool` runs, it forwards that session id as `session_key` to `bridge.submit(...)` so async tasks are tagged with the connection that started them. On transport teardown, the manager calls `bridge.cancel_session_tasks(session_id)` to cancel all in-flight async tasks for the disconnecting client. `serve()` / `async_serve()` / `APCoreMCP.serve` / `async_serve` wire this automatically when an `AsyncTaskBridge` is present. +The bridge can tag submissions with the transport-owned session ID as `session_key`. The teardown hook calls `bridge.cancel_session_tasks(session_id)` for session-bound background tasks. The server wires this when an `AsyncTaskBridge` is present. Python and TypeScript run this cleanup on stdio and Streamable HTTP session teardown, and Rust runs the hook on stdio and legacy SSE teardown. TypeScript detaches background tasks when it evicts an idle HTTP session to free capacity. ### Inputs - bridge: AsyncTaskBridge, required, validates[not_null], reject_with=TypeError(code=INVALID_ARG) @@ -200,7 +200,7 @@ The transport scopes a per-connection session id (Python: `transport_session_var ### Returns - On success: None / void / `()` -- Side effect: stores the bridge reference on the TransportManager instance; subsequent transport-disconnect events will call `bridge.cancel_session_tasks(session_id)` with the per-connection session id captured at request time +- Installs the session teardown hook for background tasks. ### Properties - async: false diff --git a/mcp/python/tests/server/test_request_cancellation.py b/mcp/python/tests/server/test_request_cancellation.py index d80a4c4e..4a427b68 100644 --- a/mcp/python/tests/server/test_request_cancellation.py +++ b/mcp/python/tests/server/test_request_cancellation.py @@ -4,14 +4,15 @@ import asyncio import json +import sys from typing import Any import anyio import httpx +import pytest from apcore import Context, Executor, Identity, Registry from apcore.async_task import AsyncTaskManager, TaskStatus -from mcp import types -from mcp.shared.message import SessionMessage +from mcp.server.stdio import stdio_server from pydantic import BaseModel from apcore_mcp.auth.middleware import AuthMiddleware @@ -19,6 +20,13 @@ from apcore_mcp.server.factory import MCPServerFactory from apcore_mcp.server.router import ExecutionRouter from apcore_mcp.server.transport import TransportManager, transport_session_var +from tests.conformance_fixtures import load_fixture + + +def _cancellation_case(transport: str) -> dict: + cases = load_fixture("request_cancellation.json")["test_cases"] + (case,) = (case for case in cases if case["transport"] == transport) + return case class _Inputs(BaseModel): @@ -34,43 +42,69 @@ class _GatedModule: output_schema = _Outputs description = "Await the test gate and record the invocation token at exit" - def __init__(self) -> None: + def __init__(self, subprocess_target: str | None = None) -> None: self.entered = asyncio.Queue[str]() self.exited = asyncio.Queue[tuple[str, bool]]() self.release = asyncio.Event() self.sessions: dict[str, str | None] = {} + self.subprocess_target = subprocess_target + self.child: asyncio.subprocess.Process | None = None async def execute(self, inputs: dict[str, Any], context: Context) -> dict[str, str]: name = inputs["name"] assert context.cancel_token is not None self.sessions[name] = transport_session_var.get() - await self.entered.put(name) + child = None try: + if name == self.subprocess_target: + child = self.child = await asyncio.create_subprocess_exec( + sys.executable, "-c", "import time; time.sleep(60)", stdin=asyncio.subprocess.DEVNULL + ) + self.entered.put_nowait(name) while not self.release.is_set(): context.cancel_token.check() await asyncio.sleep(0.01) return {"name": name} finally: + if child is not None: + with anyio.CancelScope(shield=True): + if child.returncode is None: + child.terminate() + await child.wait() self.exited.put_nowait((name, context.cancel_token.is_cancelled)) -async def test_wire_cancel_marks_only_the_target_module_token() -> None: - module = _GatedModule() +async def test_stdio_wire_cancellation(monkeypatch: pytest.MonkeyPatch) -> None: + case = _cancellation_case("stdio") + module = _GatedModule(subprocess_target=case["target"]) registry = Registry() registry.register("test.gated", module) factory = MCPServerFactory() server = factory.create_server() factory.register_handlers(server, factory.build_tools(registry), ExecutionRouter(Executor(registry=registry))) init = factory.build_init_options(server, "test", "1") - send_client, read_server = anyio.create_memory_object_stream(10) - send_server, read_client = anyio.create_memory_object_stream(10) + send_client, read_server = anyio.create_memory_object_stream[str](10) + send_server, read_client = anyio.create_memory_object_stream[str](10) + + class ProtocolOutput: + async def write(self, line: str) -> None: + await send_server.send(line) + + async def flush(self) -> None: + pass + + # Replace only the OS streams. The SDK still parses and emits real JSON-RPC lines. + monkeypatch.setattr( + "apcore_mcp.server.transport.stdio_server", + lambda **_: stdio_server(stdin=read_server, stdout=ProtocolOutput()), + ) async def send(message: dict[str, Any]) -> None: - await send_client.send(SessionMessage(types.JSONRPCMessage.model_validate({"jsonrpc": "2.0", **message}))) + await send_client.send(json.dumps({"jsonrpc": "2.0", **message}) + "\n") with anyio.fail_after(5): async with anyio.create_task_group() as group: - group.start_soon(TransportManager()._run_scoped, server, read_server, send_server, init, "test") + group.start_soon(TransportManager().run_stdio, server, init) await send( { "id": 1, @@ -82,9 +116,9 @@ async def send(message: dict[str, Any]) -> None: }, } ) - assert (await read_client.receive()).message.root.id == 1 + assert json.loads(await read_client.receive())["id"] == 1 await send({"method": "notifications/initialized"}) - for request_id, name in [(2, "target"), (3, "peer")]: + for request_id, name in [(2, case["target"]), (3, case["peer"])]: await send( { "id": request_id, @@ -92,21 +126,22 @@ async def send(message: dict[str, Any]) -> None: "params": {"name": "test.gated", "arguments": {"name": name}}, } ) - assert {await module.entered.get(), await module.entered.get()} == {"target", "peer"} + assert {await module.entered.get(), await module.entered.get()} == {case["target"], case["peer"]} + assert module.child is not None and module.child.returncode is None await send({"method": "notifications/cancelled", "params": {"requestId": 2}}) try: - assert await module.exited.get() == ("target", True) + assert await module.exited.get() == (case["expected"]["cancelled"], True), case["id"] + assert module.child.returncode is not None finally: module.release.set() - assert await module.exited.get() == ("peer", False) + assert await module.exited.get() == (case["peer"], False), case["id"] while True: - response = (await read_client.receive()).message.root - if response.id == 3: - assert isinstance(response, types.JSONRPCResponse) - assert not response.result["isError"] - assert json.loads(response.result["content"][0]["text"]) == {"name": "peer"} + response = json.loads(await read_client.receive()) + if response.get("id") == 3: + assert not response["result"]["isError"] + assert json.loads(response["result"]["content"][0]["text"]) == case["expected"]["peer_result"] break group.cancel_scope.cancel() @@ -120,6 +155,7 @@ async def cancel_session_tasks(self, session_key: str) -> int: await self.closed.put(session_key) return 0 + case = _cancellation_case("streamable-http") module = _GatedModule() registry = Registry() registry.register("test.gated", module) @@ -171,10 +207,10 @@ async def call(session_headers: dict[str, str], name: str) -> httpx.Response: }, ) - first_call = asyncio.create_task(call(first_headers, "target")) - second_call = asyncio.create_task(call(second_headers, "peer")) + first_call = asyncio.create_task(call(first_headers, case["target"])) + second_call = asyncio.create_task(call(second_headers, case["peer"])) try: - assert {await module.entered.get(), await module.entered.get()} == {"target", "peer"} + assert {await module.entered.get(), await module.entered.get()} == {case["target"], case["peer"]} response = await client.post( "/mcp/", headers=first_headers, @@ -185,19 +221,23 @@ async def call(session_headers: dict[str, str], name: str) -> httpx.Response: }, ) assert response.status_code == 202 - assert await module.exited.get() == ("target", True) + assert await module.exited.get() == (case["expected"]["cancelled"], True), case["id"] finally: module.release.set() await asyncio.gather(first_call, second_call) assert first_call.result().status_code == 200 - assert "peer" in second_call.result().text - assert await module.exited.get() == ("peer", False) - assert module.sessions["target"] != module.sessions["peer"] + peer = second_call.result() + peer.raise_for_status() + result = next(json.loads(line[5:])["result"] for line in peer.iter_lines() if line.startswith("data:")) + assert not result["isError"] + assert json.loads(result["content"][0]["text"]) == case["expected"]["peer_result"] + assert await module.exited.get() == (case["peer"], False), case["id"] + assert module.sessions[case["target"]] != module.sessions[case["peer"]] assert None not in module.sessions.values() removed = await client.delete("/mcp/", headers=first_headers) assert removed.status_code == 200 - assert await bridge.closed.get() == module.sessions["target"] + assert await bridge.closed.get() == module.sessions[case["target"]] assert bridge.closed.empty() diff --git a/mcp/rust/src/input_contract_tests.rs b/mcp/rust/src/input_contract_tests.rs index a77c3818..b02e3907 100644 --- a/mcp/rust/src/input_contract_tests.rs +++ b/mcp/rust/src/input_contract_tests.rs @@ -1,12 +1,10 @@ //! Issue #20: exercise the real Registry, Executor and shipped router adapter. use super::*; +use crate::conformance_fixtures; use apcore::registry::ModuleDescriptor; use apcore::{Config, Module, ModuleAnnotations}; use serde_json::json; -#[path = "../tests/common/mod.rs"] -mod common; - #[derive(Debug)] struct Echo { schema: Value, @@ -33,8 +31,8 @@ impl Module for Echo { #[tokio::test] async fn mcp_input_contract() { - let fixture: Value = - common::load_fixture("mcp_input_contract.json").expect("canonical input contract fixture"); + let fixture: Value = conformance_fixtures::load_fixture("mcp_input_contract.json") + .expect("canonical input contract fixture"); for case in fixture["schema_cases"].as_array().expect("schema cases") { for validate_inputs in [false, true] { let schema = case["input_schema"].clone(); @@ -157,7 +155,7 @@ fn descriptor_for(module: &Echo) -> ModuleDescriptor { #[tokio::test] async fn mcp_root_schema_contract() { - let fixture: Value = common::load_fixture("mcp_input_contract.json").unwrap(); + let fixture: Value = conformance_fixtures::load_fixture("mcp_input_contract.json").unwrap(); for case in fixture["root_schema_cases"].as_array().unwrap() { let schema = case["input_schema"].clone(); let registry = Arc::new(Registry::new()); diff --git a/mcp/rust/src/lib.rs b/mcp/rust/src/lib.rs index 2adb61a6..7024bc57 100644 --- a/mcp/rust/src/lib.rs +++ b/mcp/rust/src/lib.rs @@ -21,6 +21,9 @@ mod artifacts; pub mod auth; pub mod cli; pub mod config; +#[cfg(test)] +#[path = "../tests/common/mod.rs"] +mod conformance_fixtures; pub mod constants; pub mod converters; pub mod explorer; diff --git a/mcp/rust/src/server/transport.rs b/mcp/rust/src/server/transport.rs index 965e2943..7b30484a 100644 --- a/mcp/rust/src/server/transport.rs +++ b/mcp/rust/src/server/transport.rs @@ -400,10 +400,8 @@ pub struct TransportManager { module_count: usize, metrics_exporter: Option>, usage_exporter: Option>, - /// Optional handler called when the transport detects a session - /// disconnect / cancellation notification. Used by - /// [`AsyncTaskBridge::cancel_session_tasks`] to forward cancellation - /// to any tasks launched from that session. + /// Optional session teardown handler for background tasks. + /// In-flight tool calls use the session's `DirectRequests` instead. #[allow(clippy::type_complexity)] cancel_handler: Option>, } @@ -425,16 +423,14 @@ impl TransportManager { self.usage_exporter = exporter; } - /// Install a cancellation handler invoked with the session id when the - /// transport observes a client disconnect or explicit cancel. The - /// handler typically forwards to - /// [`AsyncTaskBridge::cancel_session_tasks`]. + /// Install a handler invoked with the session ID on transport teardown. + /// The handler typically calls [`AsyncTaskBridge::cancel_session_tasks`]. #[allow(clippy::type_complexity)] pub fn set_cancel_handler(&mut self, handler: Option>) { self.cancel_handler = handler; } - /// Invoke the cancellation handler with the given session id. + /// Invoke the session teardown handler with the given session ID. /// No-op when no handler is installed. pub fn notify_cancel(&self, session_id: &str) { if let Some(h) = &self.cancel_handler { @@ -1350,12 +1346,9 @@ struct SseMessageQuery { /// This is the Rust counterpart of the TypeScript SDK's `extra.sessionId` /// (supplied by `SSEServerTransport`) and of the Python SDK's /// `transport_session_var` ContextVar, which `_scoped_session` sets around the -/// server run. All three publish the *transport's own* id, not the client's: -/// the value keys [`AsyncTaskBridge::session_tasks`], and -/// `notifications/cancelled` already routes a caller-supplied key into -/// `cancel_session_tasks`, so a client permitted to choose its own session id -/// could name — and mass-cancel — another connection's tasks. The write is -/// therefore an unconditional **overwrite**, never a default-if-absent. +/// server run. The transport-owned ID keys [`AsyncTaskBridge::session_tasks`] +/// during submission and teardown. Always overwrite client-supplied metadata +/// so one connection cannot register tasks to another connection's session. /// /// Requests with absent `params` receive an empty object so list operations /// retain connection-scoped protocol negotiation. Malformed non-object params @@ -1641,6 +1634,7 @@ mod tests { use super::*; use std::error::Error; + use crate::conformance_fixtures; use crate::server::router::SessionHandle; // ----------------------------------------------------------------------- @@ -3922,8 +3916,48 @@ mod tests { }) } + #[derive(serde::Deserialize)] + struct CancellationCase { + id: String, + transport: String, + target: String, + peer: String, + expected: CancellationOutcome, + } + + #[derive(serde::Deserialize)] + struct CancellationOutcome { + cancelled: String, + peer_result: Value, + } + + fn cancellation_case(transport: &str) -> Option { + #[derive(serde::Deserialize)] + struct Fixture { + test_cases: Vec, + } + + let fixture: Fixture = conformance_fixtures::load_fixture("request_cancellation.json")?; + Some( + fixture + .test_cases + .into_iter() + .find(|case| case.transport == transport) + .unwrap_or_else(|| panic!("missing {transport} request cancellation case")), + ) + } + + fn assert_cancellation_peer_result(response: &Value, expected: &Value) { + assert_eq!(response["result"]["isError"], false); + let content = response["result"]["content"][0]["text"].as_str().unwrap(); + assert_eq!(&serde_json::from_str::(content).unwrap(), expected); + } + #[tokio::test] async fn stdio_notification_cancels_only_the_matching_wire_request() { + let Some(case) = cancellation_case("stdio") else { + return; + }; let GatedCalls { handler, mut entries, @@ -3946,8 +3980,8 @@ mod tests { clients.push((BufReader::new(reader).lines(), writer)); } - send(&mut clients[0].1, gated_call(7.into(), "target")).await; - send(&mut clients[0].1, gated_call("7".into(), "same-session")).await; + send(&mut clients[0].1, gated_call(7.into(), &case.target)).await; + send(&mut clients[0].1, gated_call("7".into(), &case.peer)).await; send(&mut clients[1].1, gated_call(7.into(), "second-session")).await; let deadline = std::time::Duration::from_secs(3); @@ -3960,11 +3994,18 @@ mod tests { send(&mut clients[0].1, cancel_request(7.into())).await; let target = tokio::time::timeout(deadline, cancellations.recv()).await; release.add_permits(2); - assert_eq!(target.unwrap().as_deref(), Some("target")); - assert_eq!(recv(&mut clients[0].0).await["id"], "7"); - let peer = recv(&mut clients[1].0).await; - assert_eq!(peer["id"], 7); - assert_eq!(peer["result"]["isError"], false); + assert_eq!( + target.unwrap().unwrap(), + case.expected.cancelled, + "{}", + case.id + ); + let peer = recv(&mut clients[0].0).await; + assert_eq!(peer["id"], "7"); + assert_cancellation_peer_result(&peer, &case.expected.peer_result); + let second_session_peer = recv(&mut clients[1].0).await; + assert_eq!(second_session_peer["id"], 7); + assert_eq!(second_session_peer["result"]["isError"], false); assert!(cancellations.try_recv().is_err()); drop(clients); @@ -4000,6 +4041,9 @@ mod tests { async fn http_notification_cancels_only_the_request_in_the_initialized_session() { use tower::ServiceExt; + let Some(case) = cancellation_case("streamable-http") else { + return; + }; let GatedCalls { handler, mut entries, @@ -4032,12 +4076,14 @@ mod tests { let a = tokio::spawn({ let app = app.clone(); let session = sessions[0].clone(); - async move { post_http_rpc(&app, Some(&session), gated_call(2.into(), "target")).await } + let call = gated_call(2.into(), &case.target); + async move { post_http_rpc(&app, Some(&session), call).await } }); let b = tokio::spawn({ let app = app.clone(); let session = sessions[1].clone(); - async move { post_http_rpc(&app, Some(&session), gated_call(2.into(), "peer")).await } + let call = gated_call(2.into(), &case.peer); + async move { post_http_rpc(&app, Some(&session), call).await } }); let deadline = std::time::Duration::from_secs(3); @@ -4055,7 +4101,12 @@ mod tests { ); let target = tokio::time::timeout(deadline, cancellations.recv()).await; release.add_permits(1); - assert_eq!(target.unwrap().as_deref(), Some("target")); + assert_eq!( + target.unwrap().unwrap(), + case.expected.cancelled, + "{}", + case.id + ); assert_eq!(a.await.unwrap().status(), StatusCode::ACCEPTED); let peer = b.await.unwrap(); assert_eq!(peer.status(), StatusCode::OK); @@ -4063,7 +4114,8 @@ mod tests { .await .unwrap(); let peer: Value = serde_json::from_slice(&bytes).unwrap(); - assert_eq!(peer["result"]["isError"], false); + assert_eq!(peer["id"], 2); + assert_cancellation_peer_result(&peer, &case.expected.peer_result); assert!(cancellations.try_recv().is_err()); let delete = Request::builder() diff --git a/mcp/typescript/src/server/router.ts b/mcp/typescript/src/server/router.ts index 48850a37..06f8228d 100644 --- a/mcp/typescript/src/server/router.ts +++ b/mcp/typescript/src/server/router.ts @@ -288,8 +288,8 @@ export class ExecutionRouter { * subsequent same-id submit immediately sees the cancellation. * * Returns true when a token was found and cancelled; false when the - * callId was unknown (tombstone recorded). Wired by transport-level - * handlers parsing inbound MCP `notifications/cancelled` messages. + * callId was unknown (tombstone recorded). For wire requests the MCP SDK + * supplies a request-scoped abort signal to `handleCall`. */ cancel(callId: string, reason?: string): boolean { const existing = this._cancelTokens.get(callId); @@ -467,11 +467,7 @@ export class ExecutionRouter { args: Record, extra?: HandleCallExtra, ): Promise { - // [B-002] Register a CancelToken for this call so that an inbound - // MCP `notifications/cancelled` (forwarded by the transport into - // `router.cancel(callId, reason)`) cooperatively cancels in-flight - // work. The callId is sourced from `extra.callId`, - // `_meta.progressToken`, or generated. Released in `finally`. + // [B-002] Bridge the MCP SDK's abort signal to the invocation token. const rawCallId = (extra as { callId?: string | number } | undefined)?.callId ?? extra?._meta?.progressToken; diff --git a/mcp/typescript/tests/server/request-cancellation.test.ts b/mcp/typescript/tests/server/request-cancellation.test.ts index fd1c9229..7f0d4fe8 100644 --- a/mcp/typescript/tests/server/request-cancellation.test.ts +++ b/mcp/typescript/tests/server/request-cancellation.test.ts @@ -1,62 +1,170 @@ +import { once } from "node:events"; +import { createServer } from "node:http"; +import type { AddressInfo } from "node:net"; +import { PassThrough } from "node:stream"; import { Client } from "@modelcontextprotocol/sdk/client/index.js"; -import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; -import { Executor, Registry, type Context } from "apcore-js"; -import { expect, it } from "vitest"; +import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; +import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; +import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js"; +import { CallToolRequestSchema, type JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js"; +import { ACL, Executor, Identity, Registry, type Context } from "apcore-js"; +import { expect, it, vi } from "vitest"; import { MCPServerFactory } from "../../src/server/factory.js"; import { ExecutionRouter } from "../../src/server/router.js"; +import { TransportManager } from "../../src/server/transport.js"; +import { loadFixture, skipMessage } from "../conformance-fixtures.js"; -it("routes a wire cancellation to the target Core invocation only", async () => { - const targetStarted = Promise.withResolvers(); - const peerStarted = Promise.withResolvers(); - const targetExited = Promise.withResolvers(); - const release = Promise.withResolvers(); - const registry = new Registry(); - registry.register("test.gated", { - description: "Wait for cancellation or the test gate", - inputSchema: { type: "object" }, - outputSchema: { type: "object" }, - async execute(inputs: Record, context: Context) { - if (inputs.name === "target") { +interface CancellationCase { + id: string; + transport: "stdio" | "streamable-http"; + target: string; + peer: string; + expected: { cancelled: string; peer_result: { name: string } }; +} + +const fixtureName = "request_cancellation.json"; +const fixture = loadFixture<{ test_cases: CancellationCase[] }>(fixtureName); + +function callId(messages: JSONRPCMessage[], name: string) { + for (const message of messages) { + const call = CallToolRequestSchema.safeParse(message); + if (call.success && call.data.params.arguments?.name === name && "id" in message) { + return message.id; + } + } + throw new Error(`tools/call for ${name} was not sent`); +} + +if (fixture === null) { + it.skip(skipMessage(fixtureName), () => {}); +} else { + it.each(fixture.test_cases)("$id", async (testCase) => { + const separateSession = testCase.transport === "streamable-http"; + const bothStarted = Promise.withResolvers(); + const firstExit = Promise.withResolvers<{ name: string; cancelled: boolean }>(); + const release = Promise.withResolvers(); + const started = new Set(); + const exits: { name: string; cancelled: boolean }[] = []; + const registry = new Registry(); + await registry.register("test.gated", { + description: "Wait for cancellation or the test gate", + inputSchema: { type: "object" }, + outputSchema: { type: "object" }, + async execute(inputs: Record, context: Context) { + const name = inputs.name as string; + const token = context.cancelToken; + if (!token) throw new Error(`Missing invocation cancel token for ${name}`); const aborted = Promise.withResolvers(); - context.signal.addEventListener("abort", () => aborted.resolve(), { once: true }); - targetStarted.resolve(); - await Promise.race([aborted.promise, release.promise]); - targetExited.resolve(context.signal.aborted); + const onAbort = () => aborted.resolve(); + context.signal.addEventListener("abort", onAbort, { once: true }); + started.add(name); + if (started.size === 2) bothStarted.resolve(); + try { + await Promise.race([aborted.promise, release.promise]); + return { name }; + } finally { + context.signal.removeEventListener("abort", onAbort); + const exit = { name, cancelled: token.isCancelled }; + exits.push(exit); + firstExit.resolve(exit); + } + }, + } as never); + const factory = new MCPServerFactory(); + const tools = factory.buildTools(registry as never); + const acl = separateSession + ? new ACL([{ callers: ["@external"], targets: ["test.gated"], effect: "allow", conditions: { scopes: ["call"] } }]) + : null; + const router = new ExecutionRouter(Executor.fromRegistry(registry, null, acl) as never); + function newServer() { + const server = factory.createServer(); + factory.registerHandlers(server, tools, router); + return server; + } + + const targetClient = new Client({ name: "target-client", version: "1" }); + const peerClient = separateSession ? new Client({ name: "peer-client", version: "1" }) : targetClient; + let closeTransport: (() => Promise) | undefined; + const timedOut = Promise.withResolvers(); + const deadline = setTimeout(() => timedOut.reject(new Error(`Timed out running ${testCase.id}`)), 8_000); + void timedOut.promise.catch(() => undefined); + const withinDeadline = (operation: Promise) => Promise.race([operation, timedOut.promise]); + try { + let targetTransport: Transport; + let peerTransport: typeof targetTransport; + if (separateSession) { + const manager = new TransportManager(); + manager.setAuthenticator({ + authenticate: async () => new Identity("conformance", "user", [], {}, { scopes: ["call"] }), + }); + manager.setScopedServerFactory(newServer); + const app = await manager.buildStreamableHttpApp(newServer()); + const http = createServer(app.handler); + closeTransport = async () => { + await app.close(); + http.closeAllConnections(); + await new Promise((resolve) => http.close(() => resolve())); + }; + http.listen(0, "127.0.0.1"); + await once(http, "listening"); + const url = new URL(`http://127.0.0.1:${(http.address() as AddressInfo).port}/mcp`); + targetTransport = new StreamableHTTPClientTransport(url); + peerTransport = new StreamableHTTPClientTransport(url); } else { - peerStarted.resolve(); - await release.promise; + const stdin = new PassThrough(); + const stdout = new PassThrough(); + const server = newServer(); + closeTransport = async () => { + await server.close(); + stdin.destroy(); + stdout.destroy(); + }; + await server.connect(new StdioServerTransport(stdin, stdout)); + // Both ends frame and parse newline-delimited JSON-RPC over the paired streams. + targetTransport = peerTransport = new StdioServerTransport(stdout, stdin); } - return { name: inputs.name, cancelled: context.signal.aborted }; - }, - } as never); - const factory = new MCPServerFactory(); - const server = factory.createServer(); - const executor = Executor.fromRegistry(registry); - const router = new ExecutionRouter(executor as never); - factory.registerHandlers(server, factory.buildTools(registry as never), router); - const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); - const client = new Client({ name: "wire-cancellation", version: "1" }); - await server.connect(serverTransport); - await client.connect(clientTransport); - - const controller = new AbortController(); - const cancellation = new Error("cancel the target request"); - const target = client.callTool({ name: "test.gated", arguments: { name: "target" } }, undefined, { - signal: controller.signal, - }).catch((error: unknown) => error); - const peer = client.callTool({ name: "test.gated", arguments: { name: "peer" } }); - void peer.catch(() => undefined); - try { - await Promise.all([targetStarted.promise, peerStarted.promise]); - controller.abort(cancellation); - expect(await target).toMatchObject({ message: expect.stringContaining(cancellation.message) }); - expect(await targetExited.promise).toBe(true); - release.resolve(); - expect((await peer).structuredContent).toEqual({ name: "peer", cancelled: false }); - } finally { - release.resolve(); - await client.close(); - await server.close(); - } -}); + + const targetSends = vi.spyOn(targetTransport, "send"); + const peerSends = separateSession ? vi.spyOn(peerTransport, "send") : targetSends; + await withinDeadline(targetClient.connect(targetTransport)); + if (separateSession) { + await withinDeadline(peerClient.connect(peerTransport)); + expect(peerTransport.sessionId).toBeDefined(); + expect(peerTransport.sessionId).not.toEqual(targetTransport.sessionId); + } + + const controller = new AbortController(); + const cancellation = new Error("cancel the target request"); + const target = targetClient.callTool({ name: "test.gated", arguments: { name: testCase.target } }, undefined, { + signal: controller.signal, + }).catch((error: unknown) => error); + const peer = peerClient.callTool({ name: "test.gated", arguments: { name: testCase.peer } }); + void peer.catch(() => undefined); + await withinDeadline(bothStarted.promise); + expect(started).toEqual(new Set([testCase.target, testCase.peer])); + const targetId = callId(targetSends.mock.calls.map(([message]) => message), testCase.target); + const peerId = callId(peerSends.mock.calls.map(([message]) => message), testCase.peer); + expect(targetId === peerId).toBe(separateSession); + + controller.abort(cancellation); + expect(await withinDeadline(target)).toMatchObject({ message: expect.stringContaining(cancellation.message) }); + expect(await withinDeadline(firstExit.promise)).toEqual({ name: testCase.expected.cancelled, cancelled: true }); + expect(targetSends.mock.calls.map(([message]) => message)).toContainEqual(expect.objectContaining({ + method: "notifications/cancelled", + params: expect.objectContaining({ requestId: targetId }), + })); + release.resolve(); + const result = await withinDeadline(peer); + expect(result.isError).not.toBe(true); + expect(result.structuredContent).toEqual(testCase.expected.peer_result); + expect(exits).toHaveLength(2); + expect(exits[1]).toEqual({ name: testCase.peer, cancelled: false }); + } finally { + clearTimeout(deadline); + release.resolve(); + await Promise.all([...new Set([targetClient, peerClient])].map((client) => client.close())); + await closeTransport?.(); + } + }, 10_000); +} From 7574978b53fec5ec5c253652238655e38473cd8e Mon Sep 17 00:00:00 2001 From: tercel Date: Sun, 29 Nov 2026 09:51:59 +0800 Subject: [PATCH 3/3] perf(a2a): prefilter timestamped task scans Signed-off-by: tercel --- a2a/typescript/src/server/task-persistence.ts | 9 +++++++- .../tests/security/task-scoping.test.ts | 22 +++++++++++++++---- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/a2a/typescript/src/server/task-persistence.ts b/a2a/typescript/src/server/task-persistence.ts index bf0ce6c1..45a84e13 100644 --- a/a2a/typescript/src/server/task-persistence.ts +++ b/a2a/typescript/src/server/task-persistence.ts @@ -201,7 +201,14 @@ class TaskPersistence implements TaskStore { // Page and count the visible results, never expose storage cursors or counts. const tasks: Task[] = []; const seenTokens = new Set(); - const storeParams = after === undefined ? params : { ...params, statusTimestampAfter: undefined }; + const storeParams = { ...params }; + if (after !== undefined && params.statusTimestampAfter) { + // Start one whole millisecond earlier so the stock store retains every + // possible match even when it uses a strict millisecond comparison. + const previousMillisecond = new Date(Date.parse(params.statusTimestampAfter) - 1); + storeParams.statusTimestampAfter = Number.isNaN(previousMillisecond.getTime()) + ? undefined : previousMillisecond.toISOString(); + } let storageToken = ""; let totalSize = 0; do { diff --git a/a2a/typescript/tests/security/task-scoping.test.ts b/a2a/typescript/tests/security/task-scoping.test.ts index 8621dcde..d310420d 100644 --- a/a2a/typescript/tests/security/task-scoping.test.ts +++ b/a2a/typescript/tests/security/task-scoping.test.ts @@ -468,17 +468,31 @@ it.each(["anonymous", "scoped"])("includes the exact status timestamp boundary i it("compares fractional timestamps in an explicitly provided SDK store", async () => { const store = new InMemoryTaskStore(); const context = anonymousContext(); + const state = TaskState.TASK_STATE_COMPLETED; + // A recent filter should not require loading past the store's scan page size. + for (let index = 0; index < 100; index++) { + await store.save({ + id: `old-${index}`, contextId: "fractional", + status: { state, timestamp: "2026-02-01T01:59:59.999Z" }, + }, context); + } for (const [id, fraction] of [["older", "001"], ["equal", "002"], ["newer", "003"]]) { await store.save({ id, contextId: "fractional", - status: { state: TaskState.TASK_STATE_COMPLETED, timestamp: `2026-02-01T02:00:00.000000${fraction}Z` }, + status: { state, timestamp: `2026-02-01T02:00:00.000000${fraction}Z` }, }, context); } const app = makeApp(undefined, store); const filter = { statusTimestampAfter: "2026-02-01T03:00:00.000000002+01:00" }; - const response = await rpc(app, ALICE, "ListTasks", filter); - expect(response.error).toBeUndefined(); - expect(response.result).toMatchObject({ tasks: [{ id: "newer" }, { id: "equal" }], totalSize: 2, pageSize: 50 }); + const list = vi.spyOn(InMemoryTaskStore.prototype, "list"); + try { + const response = await rpc(app, ALICE, "ListTasks", filter); + expect(response.error).toBeUndefined(); + expect(response.result).toMatchObject({ tasks: [{ id: "newer" }, { id: "equal" }], totalSize: 2, pageSize: 50 }); + expect(list).toHaveBeenCalledTimes(1); + } finally { + list.mockRestore(); + } const maxPage = await rpc(app, ALICE, "ListTasks", { ...filter, pageSize: 100 }); expect(maxPage.result).toMatchObject({ totalSize: 2, pageSize: 100 });