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
2 changes: 2 additions & 0 deletions a2a/typescript/src/server/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
49 changes: 36 additions & 13 deletions a2a/typescript/src/server/task-persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand All @@ -20,8 +20,16 @@ const TERMINAL_STATES = new Set<TaskState>([
]);

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);
Expand Down Expand Up @@ -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));
Expand All @@ -166,20 +178,20 @@ class TaskPersistence implements TaskStore {
};
}

private async listScoped(
params: Parameters<TaskStore["list"]>[0], context: ServerCallContext, authority: string,
private async listVisible(
params: Parameters<TaskStore["list"]>[0], context: ServerCallContext, authority: string | null, after?: bigint,
): ReturnType<TaskStore["list"]> {
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");
}
Expand All @@ -189,15 +201,26 @@ class TaskPersistence implements TaskStore {
// Page and count the visible results, never expose storage cursors or counts.
const tasks: Task[] = [];
const seenTokens = new Set<string>();
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 {
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");
Expand Down
102 changes: 100 additions & 2 deletions a2a/typescript/tests/security/task-scoping.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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" }) },
Expand All @@ -68,6 +70,7 @@ function makeApp(auth?: Authenticator): Express {
version: "1",
url: "http://localhost",
auth,
taskStore,
pushNotifications: true,
},
);
Expand Down Expand Up @@ -413,3 +416,98 @@ 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();
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, 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 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 });
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());
});
32 changes: 12 additions & 20 deletions mcp/conformance/README.md
Original file line number Diff line number Diff line change
@@ -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.

Expand All @@ -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. |
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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.
29 changes: 29 additions & 0 deletions mcp/conformance/fixtures/request_cancellation.json
Original file line number Diff line number Diff line change
@@ -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" }
}
}
]
}
Loading
Loading