fix(server): serve agent MCP to 2026-07-28 clients (#10558)

* fix(server): serve agent MCP over the 2026-07-28 protocol

Reasoning:
- The bundled `@modelcontextprotocol/sdk@1.29.0` only speaks up to protocol `2025-11-25`, while current MCP clients (Claude Code, Codex, Grok CLI, ACP harnesses) send `mcp-protocol-version: 2026-07-28` and get `400 Bad Request: Unsupported protocol version` on the first request after `initialize`. The agent then runs without any Paseo tool, so `list_agents`, `create_agent`, and the rest silently disappear from the tool surface (#3009).
- Widening the accepted version list (the approach in #4570 / #4375) hides the rejection but leaves the server implementing 2025 semantics while telling the client it speaks 2026-07-28.

Changes:
- Replace the v1 `StreamableHTTPServerTransport` wiring in `bootstrap.ts` with the v2 dual-era `createMcpHandler(..., { legacy: "stateless" })` plus `toNodeHandler` from `@modelcontextprotocol/node`. Modern 2026-07-28 requests and 2025-era clients are served by the same handler; per-request stateless serving is unchanged.
- Move `agent/mcp-server.ts` to `@modelcontextprotocol/server` (`McpServer`, `ServerContext`, `context.mcpReq.signal`).
- Keep `@modelcontextprotocol/sdk` for the existing client-side integrations (e.g. the OMP MCP bridge).
- Assert the JSON-RPC `-32602` rejection in `mcp-server.test.ts`: a call to an unregistered tool is a protocol error, which the v1 server folded into an `isError` result.

Verification:
- `npx tsc -p packages/server/tsconfig.server.json` clean; `npm run typecheck` clean; `oxfmt`/`oxlint` clean on the touched files.
- `npm ci --dry-run` accepts the lockfile.
- `packages/server`: `mcp-server.test.ts` 194/194, `agent-mcp.e2e.test.ts` 8/8, `mcp-parity.e2e.test.ts` 38/38.
- Manual check on macOS against a real daemon: a `dsh` agent (sends 2026-07-28) lists Paseo tools (`create_workspace`, `list_workspaces`, `create_agent`) and the daemon logs zero `MCP transport error` / `Unsupported protocol version` entries.

* test(server): cover the modern MCP envelope on the agent endpoint

Reasoning:
- Greptile flagged that the tool registration used a `registerTool` re-cast, which defeats the SDK's type check on a path every agent tool call goes through.
- The modern (2026-07-28) path had no regression coverage, so a looser "accept the version header" implementation would also pass the existing tests.

Changes:
- Narrow only the schema at the registration boundary (`inputSchema as StandardSchemaWithJSON`) and document why: Paseo declares schemas through the `zod` root entry, the SDK types them through `zod/v4` core; same runtime, distinct type identities.
- Add a modern-protocol test that drives `createMcpHandler` with a per-request envelope (`_meta` protocol version + `mcp-method` header) and asserts the catalog tools come back.

Verification:
- `npx vitest run src/server/agent/mcp-server.test.ts` 195/195.
- `npx tsc -p packages/server/tsconfig.server.json` clean; `oxfmt` / `oxlint` clean.

* test(server): expect the agent MCP handler's own rejection

The stateless MCP handler answers a body-less POST with 415 (unsupported
media type) instead of the old transport's 406. The smoke test only needs the
route to be live before the reload and gone after it, so assert that answer and
say why the code changed.

* fix(server): give native host tools the schema the agent MCP serves

The agent MCP endpoint now registers tools with @modelcontextprotocol/server,
which converts input schemas with zod at the draft 2020-12 target. The OpenCode
bridge and OMP host tools still serialized through the v1 SDK internals as
draft-07, so the plugin parity test (native schema equals advertised schema)
failed. Serialize with the same zod conversion so one schema reaches both paths,
and drop the dependency on unexported v1 SDK internals.

OpenCode reads both dialects and defaults to 2020-12. OMP rewrites draft-07 to
2020-12 before sending to a model.

* test(server): negotiate the agent MCP with pinned, auto and legacy clients

Drive a real daemon's /mcp/agents with @modelcontextprotocol/client 2.4.0:
- pinned to 2026-07-28: fails on the v1 transport ("server did not offer
  pinned protocol version 2026-07-28").
- auto: falls back to 2025-11-25 on the v1 transport. The test also asserts
  that the daemon logs no transport errors.
- legacy: the 2025-era compatibility guard.

Run the block in test:integration so CI keeps it, and translate the modern
envelope test comment to English.

* test(ci): route the agent MCP negotiation block through server integration

The block shares the existing name-filtered vitest invocation, so it adds no extra vitest start to the Windows integration job.

* test(website): play the orchestration scene on a held page clock

The scene player advances at most 64ms per animation frame, so on a CI
runner where headless WebKit paints a few frames a second the scene ran
in slow motion and missed the 20s wait for the subagents pill. The test
now pauses Playwright's page clock after hydration, checks the empty
chat, then runs the clock past the scene before asserting the roster.

---------

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
This commit is contained in:
Mohamed BoudraandOuyang Xingyuan authored and GitHub committed 2026-11-23 10:43:23 +07:00
1 parent 8fa22b39eb
commit df9886b2f1
12 files changed
+313 -80

No files matched your search

+65 -3
View File
@@ -8520,6 +8520,52 @@
"integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==",
"license": "BSD-2-Clause"
},
"node_modules/@modelcontextprotocol/client": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.4.0.tgz",
"integrity": "sha512-LgrD2OphHuG12vfKFKz6SOnq7bKHQmhGJIAYdD+MZBn2npHEyry6uD8zvktodtl5CQM85MO0anUyD9JwmUmxww==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"@modelcontextprotocol/core": "2.4.0",
"cross-spawn": "^7.0.5",
"eventsource": "^3.0.2",
"eventsource-parser": "^3.0.8",
"jose": "^6.1.3",
"pkce-challenge": "^5.0.0",
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@modelcontextprotocol/core": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.4.0.tgz",
"integrity": "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q==",
"dependencies": {
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@modelcontextprotocol/node": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/node/-/node-2.1.2.tgz",
"integrity": "sha512-IIcIqBpr6NCQQs5DgJTgvbSOAw+3iaR/uquqg+e0nXCdudfjPg/80x0TseUnQx14AUAtE4fsJCEpJKPyb6WPVA==",
"license": "Apache-2.0",
"dependencies": {
"@hono/node-server": "^1.19.9 || ^2.1.3",
"hono": "^4.11.4"
},
"engines": {
"node": ">=20"
},
"peerDependencies": {
"@modelcontextprotocol/server": "^2.4.0"
}
},
"node_modules/@modelcontextprotocol/sdk": {
"version": "1.29.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
@@ -8906,6 +8952,19 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/@modelcontextprotocol/server": {
"version": "2.4.0",
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.4.0.tgz",
"integrity": "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q==",
"license": "Apache-2.0",
"dependencies": {
"@modelcontextprotocol/core": "2.4.0",
"zod": "^4.2.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": {
"version": "3.0.4",
"resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz",
@@ -20579,9 +20638,9 @@
}
},
"node_modules/eventsource-parser": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
"integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
"integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
@@ -40542,7 +40601,9 @@
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
"@modelcontextprotocol/server": "2.4.0",
"@opencode-ai/sdk": "1.14.46",
"@opencode/client": "2.0.10",
"@xterm/addon-serialize": "0.14.0",
@@ -40581,6 +40642,7 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@modelcontextprotocol/client": "2.4.0",
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
+4 -1
View File
@@ -90,7 +90,7 @@
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
"test": "npm run test:unit && npm run test:integration",
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t \"merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history\"",
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
"test:integration:all": "npm run test:e2e",
"test:integration:real": "vitest run real.e2e.test.ts",
@@ -115,7 +115,9 @@
"@getpaseo/protocol": "0.17.3",
"@getpaseo/relay": "0.17.3",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
"@modelcontextprotocol/server": "2.4.0",
"@opencode-ai/sdk": "1.14.46",
"@opencode/client": "2.0.10",
"@xterm/addon-serialize": "0.14.0",
@@ -154,6 +156,7 @@
"zod": "^4.4.3"
},
"devDependencies": {
"@modelcontextprotocol/client": "2.4.0",
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
@@ -6,6 +6,11 @@ import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { describe, expect, test } from "vitest";
import { experimental_createMCPClient } from "ai";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import {
Client as StandardMcpClient,
StreamableHTTPClientTransport as StandardMcpHttpTransport,
type VersionNegotiationMode,
} from "@modelcontextprotocol/client";
import pino from "pino";
import { withTimeout } from "../../utils/promise-timeout.js";
@@ -89,12 +94,12 @@ async function createMcpClient(url: string, authToken?: string): Promise<McpClie
return { callTool: boundCallTool, close: () => rawClient.close() };
}
interface OfflineMcpDaemon {
client: McpClient;
interface OfflineDaemon {
mcpUrl: string;
stop: () => Promise<void>;
}
async function startOfflineMcpDaemon(): Promise<OfflineMcpDaemon> {
async function startOfflineDaemon(logger = pino({ level: "silent" })): Promise<OfflineDaemon> {
const paseoHome = await mkdtemp(path.join(os.tmpdir(), "paseo-home-"));
const staticDir = await mkdtemp(path.join(os.tmpdir(), "paseo-static-"));
const removeDirectories = async () => {
@@ -114,29 +119,92 @@ async function startOfflineMcpDaemon(): Promise<OfflineMcpDaemon> {
agentClients: createTestAgentClients(),
agentStoragePath: path.join(paseoHome, "agents"),
},
pino({ level: "silent" }),
logger,
).catch(async (error: unknown) => {
await removeDirectories();
throw error;
});
const stop = async () => {
await daemon.stop();
await removeDirectories();
};
try {
await daemon.start();
const client = await createMcpClient(`http://127.0.0.1:${port}/mcp/agents`);
} catch (error) {
await stop();
throw error;
}
return { mcpUrl: `http://127.0.0.1:${port}/mcp/agents`, stop };
}
interface OfflineMcpDaemon {
client: McpClient;
stop: () => Promise<void>;
}
async function startOfflineMcpDaemon(): Promise<OfflineMcpDaemon> {
const daemon = await startOfflineDaemon();
try {
const client = await createMcpClient(daemon.mcpUrl);
return {
client,
stop: async () => {
await client.close();
await daemon.stop();
await removeDirectories();
},
};
} catch (error) {
await daemon.stop();
await removeDirectories();
throw error;
}
}
interface CapturedLog {
level: number;
msg?: string;
}
function createCapturingLogger(): { logger: pino.Logger; logs: CapturedLog[] } {
const logs: CapturedLog[] = [];
const logger = pino(
{ level: "warn" },
{
write: (line: string) => {
logs.push(JSON.parse(line) as CapturedLog);
},
},
);
return { logger, logs };
}
interface StandardMcpSession {
negotiatedProtocolVersion: string | undefined;
toolNames: string[];
listWorkspacesResult: unknown;
}
async function runStandardMcpSession(
mcpUrl: string,
mode: VersionNegotiationMode,
): Promise<StandardMcpSession> {
const client = new StandardMcpClient(
{ name: "agent-mcp-e2e", version: "0.0.0" },
{ versionNegotiation: { mode } },
);
await client.connect(new StandardMcpHttpTransport(new URL(mcpUrl)));
try {
const tools = await client.listTools();
const workspaces = await client.callTool({ name: "list_workspaces", arguments: {} });
return {
negotiatedProtocolVersion: client.getNegotiatedProtocolVersion(),
toolNames: tools.tools.map((tool) => tool.name),
listWorkspacesResult: workspaces.structuredContent,
};
} finally {
await client.close();
}
}
type WorkspaceCreation = { workspaceId: unknown } | { error: unknown };
async function createLocalWorkspace(client: McpClient, cwd: string): Promise<WorkspaceCreation> {
@@ -899,3 +967,42 @@ describe("agent MCP end-to-end (offline)", () => {
}
}, 60_000);
});
describe("agent MCP protocol negotiation", () => {
test("a client pinned to 2026-07-28 lists and calls tools", async () => {
const daemon = await startOfflineDaemon();
try {
const session = await runStandardMcpSession(daemon.mcpUrl, { pin: "2026-07-28" });
expect(session.negotiatedProtocolVersion).toBe("2026-07-28");
expect(session.toolNames).toEqual(expect.arrayContaining(["create_agent", "update_agent"]));
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
} finally {
await daemon.stop();
}
}, 30_000);
test("an auto-negotiating client settles on 2026-07-28 without transport errors", async () => {
const { logger, logs } = createCapturingLogger();
const daemon = await startOfflineDaemon(logger);
try {
const session = await runStandardMcpSession(daemon.mcpUrl, "auto");
expect(session.negotiatedProtocolVersion).toBe("2026-07-28");
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
expect(logs.filter((log) => log.msg === "Agent MCP transport error")).toEqual([]);
} finally {
await daemon.stop();
}
}, 30_000);
test("a legacy client still initializes over a 2025 protocol version", async () => {
const daemon = await startOfflineDaemon();
try {
const session = await runStandardMcpSession(daemon.mcpUrl, "legacy");
expect(session.negotiatedProtocolVersion).toMatch(/^2025-/);
expect(session.toolNames).toEqual(expect.arrayContaining(["create_agent", "update_agent"]));
expect(session.listWorkspacesResult).toMatchObject({ workspaces: [] });
} finally {
await daemon.stop();
}
}, 30_000);
});
@@ -24,6 +24,7 @@ import { z } from "zod";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { createAgentMcpServer as createAgentMcpServerWithDependencies } from "./mcp-server.js";
import { createMcpHandler } from "@modelcontextprotocol/server";
import { AgentManager, type ManagedAgent } from "./agent-manager.js";
import { AgentStorage, type StoredAgentRecord } from "./agent-storage.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
@@ -1248,14 +1249,16 @@ describe("browser MCP tools", () => {
expect(toolNames).not.toContain("list_agents");
expect(toolNames).not.toContain("browser_list_tabs");
expect(toolNames).toEqual(expect.arrayContaining(["create_agent", "browser_snapshot"]));
await expect(client.callTool({ name: "list_agents", arguments: {} })).resolves.toEqual({
content: [{ type: "text", text: "MCP error -32602: Tool list_agents not found" }],
isError: true,
});
await expect(client.callTool({ name: "browser_list_tabs", arguments: {} })).resolves.toEqual({
content: [{ type: "text", text: "MCP error -32602: Tool browser_list_tabs not found" }],
isError: true,
});
// Calling a tool that is not registered is a JSON-RPC error (-32602) on the
// wire, not a tool result. The v1 SDK server folded it into an `isError`
// result; the v2 server surfaces it as the protocol error it is, so assert
// the rejection here.
await expect(client.callTool({ name: "list_agents", arguments: {} })).rejects.toThrow(
/Tool list_agents not found/,
);
await expect(client.callTool({ name: "browser_list_tabs", arguments: {} })).rejects.toThrow(
/Tool browser_list_tabs not found/,
);
expect(broker.calls).toEqual([]);
} finally {
await client.close();
@@ -7522,3 +7525,58 @@ describe("local durable finish subscription MCP wiring", () => {
}
});
});
describe("modern MCP protocol (2026-07-28)", () => {
// 2026-07-28 clients skip initialize and carry the protocol version and
// capabilities on every request. Drive createMcpHandler directly so this
// covers the modern path: widening the accepted version list alone would
// keep the legacy tests green without serving it.
const modernRequest = (id: number, method: string): Request =>
new Request("http://localhost/mcp/agents", {
method: "POST",
headers: {
"content-type": "application/json",
accept: "application/json, text/event-stream",
"mcp-protocol-version": "2026-07-28",
// SEP-2243: modern requests must also repeat the method in a header.
"mcp-method": method,
},
body: JSON.stringify({
jsonrpc: "2.0",
id,
method,
params: {
_meta: {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": { name: "test-client", version: "1.0.0" },
},
},
}),
});
it("answers a per-request modern envelope and lists catalog tools", async () => {
const server = await createAgentMcpServerWithDependencies({
agentManager: new BoundaryAgentManagerFake() as unknown as AgentManager,
agentStorage: new BoundaryAgentStorageFake() as unknown as AgentStorage,
providerSnapshotManager:
new BoundaryProviderSnapshotManagerFake() as unknown as ProviderSnapshotManager,
logger: createTestLogger(),
});
const handler = createMcpHandler(() => server, { legacy: "stateless" });
try {
const response = await handler.fetch(modernRequest(1, "tools/list"));
expect(response.status).toBe(200);
const payload = (await response.json()) as {
result?: { tools?: Array<{ name: string }> };
};
const names = (payload.result?.tools ?? []).map((tool) => tool.name);
expect(names.length).toBeGreaterThan(0);
expect(names).toContain("list_agents");
} finally {
await handler.close();
await server.close();
}
});
});
+13 -8
View File
@@ -1,10 +1,9 @@
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import type { RequestHandlerExtra } from "@modelcontextprotocol/sdk/shared/protocol.js";
import { McpServer } from "@modelcontextprotocol/server";
import type {
CallToolResult,
ServerNotification,
ServerRequest,
} from "@modelcontextprotocol/sdk/types.js";
ServerContext,
StandardSchemaWithJSON,
} from "@modelcontextprotocol/server";
import { addModelVisibleStructuredContent } from "./tools/paseo-tool-serialization.js";
import { createPaseoToolCatalog, type PaseoToolHostDependencies } from "./tools/paseo-tools.js";
@@ -12,7 +11,7 @@ import type { PaseoToolResult } from "./tools/types.js";
export type AgentMcpServerOptions = PaseoToolHostDependencies;
type McpToolContext = RequestHandlerExtra<ServerRequest, ServerNotification>;
type McpToolContext = ServerContext;
function toMcpToolResult(result: PaseoToolResult): CallToolResult {
const modelVisibleResult = addModelVisibleStructuredContent(result);
@@ -41,10 +40,16 @@ export async function createAgentMcpServer(options: AgentMcpServerOptions): Prom
{
title: tool.title,
description: tool.description,
inputSchema: tool.inputSchema,
// Paseo declares tool schemas through the `zod` root entry; the SDK types
// its input schema through the `zod/v4` core entry. Both are the same zod
// runtime, but the two entry points carry distinct type identities, so a
// single narrowing cast is required at this boundary.
inputSchema: tool.inputSchema as StandardSchemaWithJSON,
},
async (args: unknown, context?: McpToolContext) =>
toMcpToolResult(await catalog.executeTool(tool.name, args, { signal: context?.signal })),
toMcpToolResult(
await catalog.executeTool(tool.name, args, { signal: context?.mcpReq?.signal }),
),
);
}
@@ -5,7 +5,7 @@ import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { z } from "zod";
import Ajv from "ajv";
import Ajv2020 from "ajv/dist/2020.js";
import { afterEach, describe, expect, test, vi } from "vitest";
import { createTestLogger } from "../../../../test-utils/test-logger.js";
@@ -280,7 +280,7 @@ describe("OpenCodeBridge", () => {
properties: { notifyOnFinish: { default: false } },
});
}
const ajv = new Ajv({ useDefaults: true, strict: false });
const ajv = new Ajv2020({ useDefaults: true, strict: false });
const createInput = {
title: "Bridge child",
provider: "codex/gpt-5.4",
@@ -465,7 +465,7 @@ describe("OpenCodeBridge", () => {
type: "object",
properties: { value: { type: "string" } },
required: ["value"],
$schema: "http://json-schema.org/draft-07/schema#",
$schema: "https://json-schema.org/draft/2020-12/schema",
},
},
],
@@ -1,12 +1,4 @@
// These SDK internals are reachable through @modelcontextprotocol/sdk's wildcard export,
// not a curated public subpath. Keep that package pinned exactly and re-verify these
// paths on every SDK bump so native host-tool schemas stay byte-compatible.
import {
normalizeObjectSchema,
type AnySchema,
type ZodRawShapeCompat,
} from "@modelcontextprotocol/sdk/server/zod-compat.js";
import { toJsonSchemaCompat } from "@modelcontextprotocol/sdk/server/zod-json-schema-compat.js";
import { z } from "zod";
import type { PaseoToolDefinition, PaseoToolResult } from "./types.js";
@@ -63,16 +55,19 @@ export function addModelVisibleStructuredContent(result: PaseoToolResult): Paseo
};
}
// Native host tools must advertise the schema the agent MCP endpoint serves.
// @modelcontextprotocol/server converts tool input schemas with zod's
// standard JSON Schema hook at the draft 2020-12 target, so do the same here.
export function serializePaseoToolInputParameters(
tool: PaseoToolDefinition,
): Record<string, unknown> {
const schema = normalizeObjectSchema(
tool.inputSchema as AnySchema | ZodRawShapeCompat | undefined,
);
return schema
? toJsonSchemaCompat(schema, {
strictUnions: true,
pipeStrategy: "input",
})
: { ...EMPTY_OBJECT_JSON_SCHEMA };
if (tool.inputSchema === undefined) {
return { ...EMPTY_OBJECT_JSON_SCHEMA };
}
const schema =
tool.inputSchema instanceof z.ZodType ? tool.inputSchema : z.object(tool.inputSchema);
return {
type: "object",
...z.toJSONSchema(schema, { target: "draft-2020-12", io: "input" }),
};
}
@@ -243,7 +243,9 @@ describe("paseo daemon bootstrap", () => {
const beforeMcp = await fetch(`http://127.0.0.1:${target.port}/mcp/agents`, {
method: "POST",
});
expect(beforeMcp.status).toBe(406);
// Any answer from the agent MCP handler proves the route is live; the handler
// rejects a body-less POST as an unsupported media type.
expect(beforeMcp.status).toBe(415);
const beforeProxyReload = await httpGetWithHost(target.port, proxyHost, "/", {
"x-forwarded-proto": "https",
});
+21 -27
View File
@@ -18,7 +18,8 @@ import { open, rm, stat } from "fs/promises";
import { randomUUID } from "node:crypto";
import { getHostName } from "./host-name.js";
import path from "node:path";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { createMcpHandler } from "@modelcontextprotocol/server";
import { toNodeHandler } from "@modelcontextprotocol/node";
import type { Logger } from "pino";
import { z } from "zod";
import { createBranchChangeRouteHandler } from "./script-route-branch-handler.js";
@@ -1681,6 +1682,11 @@ export async function createPaseoDaemon(
{
const agentMcpRoute = "/mcp/agents";
// Stateless serving: createMcpHandler builds a fresh server per request and
// serves both protocol eras — modern 2026-07-28 (per-request envelope) and
// 2025-era clients through its stateless legacy fallback. No per-session
// state is retained between requests, matching the previous
// `sessionIdGenerator: undefined` transport.
const createAgentMcpSession = async (callerAgentId?: string) => {
const agentMcpServer = await createAgentMcpServer(
createAgentToolHostDependencies({
@@ -1691,25 +1697,13 @@ export async function createPaseoDaemon(
}),
);
// Stateless mode: each HTTP request builds a fresh server + transport that is
// torn down when the response closes, so no per-session state is retained between
// requests. The agent control plane only lists and calls tools, neither of which
// needs cross-request state, so sessions would only pin memory for the life of the
// daemon (agents that exit without a clean DELETE never get reaped).
const transport = new StreamableHTTPServerTransport({
sessionIdGenerator: undefined,
// NOTE: We enforce a Vite-like host allowlist at the app/websocket layer.
// StreamableHTTPServerTransport's built-in check requires exact Host header matches.
enableDnsRebindingProtection: false,
});
Object.assign(transport, {
const handler = createMcpHandler(() => agentMcpServer, {
legacy: "stateless",
onerror: (err: Error) => {
logger.error({ err }, "Agent MCP transport error");
},
});
await agentMcpServer.connect(transport);
return { server: agentMcpServer, transport };
return { handler };
};
const runAgentMcpRequest = async (
@@ -1768,17 +1762,17 @@ export async function createPaseoDaemon(
} else if (Array.isArray(callerAgentIdRaw) && typeof callerAgentIdRaw[0] === "string") {
callerAgentId = callerAgentIdRaw[0];
}
const { server, transport } = await createAgentMcpSession(callerAgentId);
res.on("close", () => {
void transport.close();
void server.close();
});
await transport.handleRequest(
req as unknown as IncomingMessage,
res as unknown as ServerResponse,
req.body,
);
const { handler } = await createAgentMcpSession(callerAgentId);
try {
// express.json() already consumed the stream, so hand the parsed body over.
await toNodeHandler(handler)(
req as unknown as IncomingMessage,
res as unknown as ServerResponse,
req.body,
);
} finally {
await handler.close();
}
} catch (err) {
logger.error({ err }, "Failed to handle Agent MCP request");
if (!res.headersSent) {
@@ -29,6 +29,7 @@ test("agent tool schemas survive the process boundary and catalog round trip", (
}),
).toEqual({
...metadata.inputSchema,
$schema: "https://json-schema.org/draft/2020-12/schema",
additionalProperties: {},
properties: {
...metadata.inputSchema.properties,
+9 -3
View File
@@ -110,7 +110,12 @@ test("the hero opens on orchestration across providers and machines", async ({ p
test("the orchestration scene plays from an empty chat to the open roster of subagents", async ({
page,
}) => {
// The scene clock moves at most 64ms per animation frame. Headless WebKit on a busy CI runner
// paints a few frames a second, so on the real clock the scene plays in slow motion and misses
// any wall-clock timeout. The test holds the page clock and plays the scene itself.
await page.clock.install();
await openHomepage(page);
await page.clock.pauseAt(await page.evaluate(() => Date.now() + 1000));
const mockup = page.getByRole("img", { name: desktopName, exact: true });
const composer = mockup.getByText("Message the agent, tag @files, or use /commands and /skills");
await playScene(page, "Orchestration", composer);
@@ -118,8 +123,9 @@ test("the orchestration scene plays from an empty chat to the open roster of sub
await expect(mockup.getByText("3 subagents", { exact: true })).toHaveCount(0);
// The orchestrator lists the issues and the agent profiles, launches three agents and says so,
// then the pointer clicks the pill and the roster opens.
await expect(mockup.getByText("3 subagents", { exact: true })).toBeVisible({ timeout: 20_000 });
// then the pointer clicks the pill and the roster opens. Ten seconds outlasts the scene.
await page.clock.runFor(10_000);
await expect(mockup.getByText("3 subagents", { exact: true })).toBeVisible();
await expect(mockup.getByText("gh issue list --label ready", { exact: true })).toBeVisible();
await expect(mockup.getByText("List agent profiles", { exact: true })).toBeVisible();
await expect(
@@ -131,7 +137,7 @@ test("the orchestration scene plays from an empty chat to the open roster of sub
await expect(
mockup.getByText("All three are launched. Paseo will notify me when each one finishes."),
).toBeVisible();
await expect(mockup.getByText("Pi · GLM-5.2", { exact: true })).toBeVisible({ timeout: 10_000 });
await expect(mockup.getByText("Pi · GLM-5.2", { exact: true })).toBeVisible();
});
test("the opening scene waits until most of the mockup is on screen", async ({ page }) => {
+1 -1
View File
@@ -568,7 +568,7 @@ test("Windows units and integration run independently with complete routed cover
assert.doesNotMatch(invocations[0], / -t /);
assert.equal(
invocations[1],
'vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts -t "merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history"',
'vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts -t "agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history"',
);
const serverConfig = readFileSync(new URL("packages/server/vitest.config.ts", repoRoot), "utf8");
assert.doesNotMatch(serverConfig, /maxWorkers:\s*1\b/);