SDK v2 migration (behavior-neutral, versionNegotiation: 'legacy') (#1624)
Migrate all three clients + core + test-servers from
@modelcontextprotocol/sdk@1.29 to SDK v2 (2.0.0-beta.4), keeping behavior
identical against legacy (2025-11-25) servers. Foundation for the SDK V2 +
New Spec stack.
Packages
- Split @modelcontextprotocol/sdk -> @modelcontextprotocol/client (Client,
transports, OAuth, error taxonomy, protocol types) + core (Zod schemas);
stdio -> client/stdio, Ajv -> client/validators/ajv. Test-servers ->
@modelcontextprotocol/server (+ server-legacy/sse). Deterministic import
rewrite (schemas -> core, everything else -> client); the codemod misroutes
client code to /server so it was not used for path routing.
- new Client(..., { versionNegotiation: { mode: 'legacy' } }) — nothing
2026-era goes on the wire.
Runtime (core/mcp/inspectorClient.ts)
- Error taxonomy: McpError -> ProtocolError, ErrorCode -> ProtocolErrorCode;
RequestTimeout -> SdkError/SdkErrorCode.
- Handlers take method strings; task methods (tasks/*, notifications/tasks/*)
use the 3-arg custom form (excluded from v2's spec-method set).
- Legacy tasks kept working (per project requirement): requestor tasks re-
implemented over raw client.request + explicit deprecated schemas;
experimental.tasks.callToolStream replaced by a local pollTaskToolCall
async generator (with _progressHandlers revival so task-execution progress
still reaches the caller). Receiver (server-initiated) tasks: the v2 Client
validates a sampling/elicit handler result and rejects the legacy { task }
response with -32602 — installReceiverTaskResponseBypass swaps the wrapped
entry in the private _requestHandlers map for the task-augmented branch so
{ task } reaches the wire (fixes server-initiated sampling-via-task).
- Pagination: list verbs use raw client.request({method}, List*ResultSchema)
for single-page behavior (v2's client.listX() auto-aggregate all pages).
Web / auth / apps
- Rename local JsonSchemaType -> InspectorFormSchema + add toFormSchema()
structural narrowing at the SDK-schema -> form boundary.
- ext-apps still peers on SDK v1: one compat boundary with documented casts
(remove when ext-apps#702 lands a v2 peer).
- OAuth provider saveClientInformation reconciled with v2's
OAuthClientInformationContext; InvalidClientMetadataError re-homed as a
local class (server-legacy/auth is not browser-safe).
- vitest.shared.mts dedupes @modelcontextprotocol/client+core to one copy so
vi.mock intercepts the SUT's import.
Accepted v2 behavior changes (per #1624 / spec §9.2): unknown-tool call
rejects with -32602; cancellation is stream-abort (no guaranteed
notifications/cancelled frame); output-schema strictness restored via the
Inspector's own Ajv check on the default path.
npm run ci green: validate (web 3087 / cli 212 / tui 274 / launcher 5),
coverage (>=90 per-file, all clients), smoke (launcher/cli/web), storybook
(410).
Closes #1624
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
8d33e76f97
commit
19a6df7ad3
1 changed files with 2545 additions and 2123 deletions
|
|
@ -1,11 +1,15 @@
|
|||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import {
|
||||
McpServer,
|
||||
WebStandardStreamableHTTPServerTransport,
|
||||
} from "@modelcontextprotocol/server";
|
||||
import type { JSONRPCMessage } from "@modelcontextprotocol/server";
|
||||
import { createMcpServer } from "./test-server-fixtures.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
|
||||
import { SSEServerTransport } from "@modelcontextprotocol/server-legacy/sse";
|
||||
import type { Request, Response } from "express";
|
||||
import express from "express";
|
||||
import { createServer as createHttpServer, Server as HttpServer } from "http";
|
||||
import { createServer as createNetServer } from "net";
|
||||
import { Readable } from "node:stream";
|
||||
import * as crypto from "node:crypto";
|
||||
import type { ServerConfig } from "./test-server-fixtures.js";
|
||||
import {
|
||||
|
|
@ -20,6 +24,53 @@ import {
|
|||
type ServerControl,
|
||||
} from "./test-server-control.js";
|
||||
|
||||
/**
|
||||
* Build a Web-standard {@link Request} from an Express request.
|
||||
*
|
||||
* SDK v2's {@link WebStandardStreamableHTTPServerTransport} speaks the Fetch API
|
||||
* (`Request`/`Response`) rather than Node `req`/`res`. The JSON body is passed
|
||||
* to `handleRequest` via `parsedBody` (Express already parsed it), so the Web
|
||||
* request carries only method, URL, and headers.
|
||||
*/
|
||||
function toWebRequest(req: Request): globalThis.Request {
|
||||
const headers = new Headers();
|
||||
for (const [key, value] of Object.entries(req.headers)) {
|
||||
if (Array.isArray(value)) {
|
||||
for (const v of value) headers.append(key, v);
|
||||
} else if (value != null) {
|
||||
headers.set(key, String(value));
|
||||
}
|
||||
}
|
||||
const url = `http://localhost${req.originalUrl || req.url}`;
|
||||
return new globalThis.Request(url, { method: req.method, headers });
|
||||
}
|
||||
|
||||
/**
|
||||
* Stream a Web-standard {@link Response} (from `handleRequest`) back onto an
|
||||
* Express response, preserving status, headers, and any SSE body stream. The
|
||||
* body stream is destroyed if the client disconnects first.
|
||||
*/
|
||||
async function writeWebResponse(
|
||||
res: Response,
|
||||
webResponse: globalThis.Response,
|
||||
): Promise<void> {
|
||||
res.status(webResponse.status);
|
||||
webResponse.headers.forEach((value, key) => {
|
||||
res.setHeader(key, value);
|
||||
});
|
||||
if (!webResponse.body) {
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
const nodeStream = Readable.fromWeb(
|
||||
webResponse.body as import("node:stream/web").ReadableStream,
|
||||
);
|
||||
res.on("close", () => {
|
||||
nodeStream.destroy();
|
||||
});
|
||||
nodeStream.pipe(res);
|
||||
}
|
||||
|
||||
export interface RecordedRequest {
|
||||
method: string;
|
||||
params?: Record<string, unknown>;
|
||||
|
|
@ -79,7 +130,9 @@ export class TestServerHttp {
|
|||
private _closing = false;
|
||||
private recordedRequests: RecordedRequest[] = [];
|
||||
private httpServer?: HttpServer;
|
||||
private transport?: StreamableHTTPServerTransport | SSEServerTransport;
|
||||
private transport?:
|
||||
| WebStandardStreamableHTTPServerTransport
|
||||
| SSEServerTransport;
|
||||
private baseUrl?: string;
|
||||
private currentRequestHeaders?: Record<string, string>;
|
||||
private currentLogLevel: string | null = null;
|
||||
|
|
@ -105,10 +158,10 @@ export class TestServerHttp {
|
|||
* This wraps the transport's onmessage handler to record requests/notifications
|
||||
*/
|
||||
private setupMessageInterception(
|
||||
transport: StreamableHTTPServerTransport | SSEServerTransport,
|
||||
transport: WebStandardStreamableHTTPServerTransport | SSEServerTransport,
|
||||
): void {
|
||||
const originalOnMessage = transport.onmessage;
|
||||
transport.onmessage = async (message) => {
|
||||
transport.onmessage = async (message: JSONRPCMessage) => {
|
||||
const timestamp = Date.now();
|
||||
const method =
|
||||
"method" in message && typeof message.method === "string"
|
||||
|
|
@ -191,7 +244,8 @@ export class TestServerHttp {
|
|||
}
|
||||
|
||||
// Store transports and one McpServer per session (SDK allows only one transport per server)
|
||||
const transports: Map<string, StreamableHTTPServerTransport> = new Map();
|
||||
const transports: Map<string, WebStandardStreamableHTTPServerTransport> =
|
||||
new Map();
|
||||
this.mcpServersBySession = new Map();
|
||||
|
||||
// Bearer token middleware for MCP routes if requireAuth
|
||||
|
|
@ -224,7 +278,10 @@ export class TestServerHttp {
|
|||
}
|
||||
|
||||
try {
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
const webResponse = await transport.handleRequest(toWebRequest(req), {
|
||||
parsedBody: req.body,
|
||||
});
|
||||
await writeWebResponse(res, webResponse);
|
||||
} catch (error) {
|
||||
// If response already sent (e.g., by OAuth middleware), don't send another
|
||||
if (!res.headersSent) {
|
||||
|
|
@ -236,7 +293,7 @@ export class TestServerHttp {
|
|||
} else {
|
||||
// New session - create a new transport and a new McpServer (one server per connection)
|
||||
const sessionMcpServer = createMcpServer(this.configWithCallback);
|
||||
const newTransport = new StreamableHTTPServerTransport({
|
||||
const newTransport = new WebStandardStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => crypto.randomUUID(),
|
||||
onsessioninitialized: (sessionId: string) => {
|
||||
transports.set(sessionId, newTransport);
|
||||
|
|
@ -257,7 +314,11 @@ export class TestServerHttp {
|
|||
await sessionMcpServer.connect(newTransport);
|
||||
|
||||
try {
|
||||
await newTransport.handleRequest(req, res, req.body);
|
||||
const webResponse = await newTransport.handleRequest(
|
||||
toWebRequest(req),
|
||||
{ parsedBody: req.body },
|
||||
);
|
||||
await writeWebResponse(res, webResponse);
|
||||
} catch (error) {
|
||||
// If response already sent (e.g., by OAuth middleware), don't send another
|
||||
if (!res.headersSent) {
|
||||
|
|
@ -292,7 +353,8 @@ export class TestServerHttp {
|
|||
// Let the transport handle the GET request
|
||||
this.currentRequestHeaders = extractHeaders(req);
|
||||
try {
|
||||
await transport.handleRequest(req, res);
|
||||
const webResponse = await transport.handleRequest(toWebRequest(req));
|
||||
await writeWebResponse(res, webResponse);
|
||||
} catch (error) {
|
||||
if (!res.headersSent) {
|
||||
res.status(500).json({
|
||||
|
|
|
|||
Loading…
Reference in a new issue