test(e2e): host the sse matrix column on the shipped legacy SSEServerTransport (#2229)
This commit is contained in:
parent
e03bca90c1
commit
c54abdb172
8 changed files with 101 additions and 97 deletions
3
pnpm-lock.yaml
generated
3
pnpm-lock.yaml
generated
|
|
@ -1164,6 +1164,9 @@ importers:
|
|||
'@modelcontextprotocol/server':
|
||||
specifier: workspace:^
|
||||
version: link:../../packages/server
|
||||
'@modelcontextprotocol/server-legacy':
|
||||
specifier: workspace:^
|
||||
version: link:../../packages/server-legacy
|
||||
'@modelcontextprotocol/test-helpers':
|
||||
specifier: workspace:^
|
||||
version: link:../helpers
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@
|
|||
* `AsyncDisposable` for `await using` teardown. All wiring is in-process —
|
||||
* no real sockets, no child processes — except the legacy SSE transport,
|
||||
* whose client half opens a real EventSource stream, so it runs over a
|
||||
* loopback HTTP listener backed by the test-only bridge in sse-host.ts.
|
||||
* loopback HTTP listener hosting the shipped server-side SSE transport
|
||||
* (see sse-host.ts).
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
|
@ -67,8 +68,9 @@ export async function wire(transport: Transport, makeServer: ServerFactory, clie
|
|||
};
|
||||
}
|
||||
case 'sse': {
|
||||
// v2 removed the server-side SSE transport, so the factory's server is hosted behind the
|
||||
// test-only bridge in sse-host.ts and the real shipped SSEClientTransport connects to it.
|
||||
// The legacy SSE transport needs a real socket: the factory's server is hosted on the
|
||||
// shipped SSEServerTransport (@modelcontextprotocol/server-legacy/sse) behind a loopback
|
||||
// listener, and the real shipped SSEClientTransport connects to it.
|
||||
const host = await startLegacySseHost(makeServer);
|
||||
await client.connect(sniffTransport(new SSEClientTransport(host.url), 'client', sniff));
|
||||
return {
|
||||
|
|
|
|||
|
|
@ -1,22 +1,18 @@
|
|||
/**
|
||||
* Test-only legacy HTTP+SSE host bridge.
|
||||
* Legacy HTTP+SSE host.
|
||||
*
|
||||
* v2 removed the server-side SSE transport, but the client-side
|
||||
* SSEClientTransport is still shipped for talking to legacy servers. This
|
||||
* bridge stands in for the removed server half so the e2e matrix can exercise
|
||||
* the real client transport end to end: it speaks the legacy wire protocol
|
||||
* (an `endpoint` SSE event carrying the POST URL with the sessionId,
|
||||
* `message` SSE events for server→client JSON-RPC, plain POSTs for
|
||||
* client→server JSON-RPC) over a real loopback listener and bridges to a real
|
||||
* v2 server through the Transport interface.
|
||||
* Hosts the SDK's shipped server-side SSE transport (`SSEServerTransport` from
|
||||
* `@modelcontextprotocol/server-legacy/sse`) on a real loopback listener so the
|
||||
* e2e matrix exercises both shipped halves of the legacy transport end to end:
|
||||
* GET opens the SSE stream (an `endpoint` event carries the POST URL with the
|
||||
* sessionId), POSTs deliver client→server JSON-RPC to the owning session.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import type { IncomingMessage, ServerResponse } from 'node:http';
|
||||
import { createServer } from 'node:http';
|
||||
|
||||
import { JSONRPCMessageSchema } from '@modelcontextprotocol/core';
|
||||
import type { JSONRPCMessage, McpServer, Server, Transport } from '@modelcontextprotocol/server';
|
||||
import type { McpServer, Server } from '@modelcontextprotocol/server';
|
||||
import { SSEServerTransport } from '@modelcontextprotocol/server-legacy/sse';
|
||||
|
||||
const SSE_PATH = '/sse';
|
||||
const POST_PATH = '/messages';
|
||||
|
|
@ -27,74 +23,6 @@ function toError(value: unknown): Error {
|
|||
return value instanceof Error ? value : new Error(String(value));
|
||||
}
|
||||
|
||||
/** Test-only server half of the legacy HTTP+SSE transport (v2 ships only the client half). */
|
||||
export class LegacySseServerTransport implements Transport {
|
||||
private _response?: ServerResponse;
|
||||
readonly sessionId: string = randomUUID();
|
||||
|
||||
onclose?: () => void;
|
||||
onerror?: (error: Error) => void;
|
||||
onmessage?: (message: JSONRPCMessage) => void;
|
||||
|
||||
constructor(private readonly _res: ServerResponse) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
if (this._response) throw new Error('LegacySseServerTransport already started');
|
||||
this._res.writeHead(200, {
|
||||
'content-type': 'text/event-stream',
|
||||
'cache-control': 'no-cache, no-transform',
|
||||
connection: 'keep-alive'
|
||||
});
|
||||
// The legacy protocol's first event tells the client where to POST its messages.
|
||||
this._res.write(`event: endpoint\ndata: ${POST_PATH}?sessionId=${this.sessionId}\n\n`);
|
||||
this._response = this._res;
|
||||
this._res.on('close', () => {
|
||||
this._response = undefined;
|
||||
this.onclose?.();
|
||||
});
|
||||
}
|
||||
|
||||
async send(message: JSONRPCMessage): Promise<void> {
|
||||
if (!this._response) throw new Error('SSE stream not established');
|
||||
this._response.write(`event: message\ndata: ${JSON.stringify(message)}\n\n`);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this._response?.end();
|
||||
this._response = undefined;
|
||||
this.onclose?.();
|
||||
}
|
||||
|
||||
/** Delivers a client→server POST to the server side and answers the HTTP request (202 on success). */
|
||||
async handlePostMessage(req: IncomingMessage, res: ServerResponse): Promise<void> {
|
||||
if (!this._response) {
|
||||
res.writeHead(500).end('SSE connection not established');
|
||||
return;
|
||||
}
|
||||
const contentTypeHeader = req.headers['content-type'] ?? '';
|
||||
if (!contentTypeHeader.includes('application/json')) {
|
||||
res.writeHead(400).end(`Unsupported content-type: ${contentTypeHeader}`);
|
||||
return;
|
||||
}
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of req) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk)));
|
||||
}
|
||||
const raw = Buffer.concat(chunks).toString('utf8');
|
||||
|
||||
let message: JSONRPCMessage;
|
||||
try {
|
||||
message = JSONRPCMessageSchema.parse(JSON.parse(raw));
|
||||
} catch (error) {
|
||||
res.writeHead(400).end(`Invalid message: ${raw}`);
|
||||
this.onerror?.(toError(error));
|
||||
return;
|
||||
}
|
||||
res.writeHead(202).end('Accepted');
|
||||
this.onmessage?.(message);
|
||||
}
|
||||
}
|
||||
|
||||
export interface LegacySseHost {
|
||||
/** URL of the SSE endpoint; GET it to open a stream. */
|
||||
readonly url: URL;
|
||||
|
|
@ -108,12 +36,12 @@ export interface LegacySseHost {
|
|||
* become 500.
|
||||
*/
|
||||
export async function startLegacySseHost(makeServer: () => AnyServer): Promise<LegacySseHost> {
|
||||
const sessions = new Map<string, { tx: LegacySseServerTransport; server: AnyServer }>();
|
||||
const sessions = new Map<string, { tx: SSEServerTransport; server: AnyServer }>();
|
||||
|
||||
const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
|
||||
const requestUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
|
||||
if (req.method === 'GET' && requestUrl.pathname === SSE_PATH) {
|
||||
const tx = new LegacySseServerTransport(res);
|
||||
const tx = new SSEServerTransport(POST_PATH, res);
|
||||
const server = makeServer();
|
||||
sessions.set(tx.sessionId, { tx, server });
|
||||
// connect() starts the transport, which writes the SSE headers and the endpoint event.
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@
|
|||
"@modelcontextprotocol/client": "workspace:^",
|
||||
"@modelcontextprotocol/core": "workspace:^",
|
||||
"@modelcontextprotocol/server": "workspace:^",
|
||||
"@modelcontextprotocol/server-legacy": "workspace:^",
|
||||
"@modelcontextprotocol/express": "workspace:^",
|
||||
"@modelcontextprotocol/fastify": "workspace:^",
|
||||
"@modelcontextprotocol/hono": "workspace:^",
|
||||
|
|
|
|||
|
|
@ -2268,16 +2268,14 @@ export const REQUIREMENTS: Record<string, Requirement> = {
|
|||
behavior:
|
||||
'A single server instance can serve streamable HTTP and the legacy SSE transport concurrently; clients on either transport can call the same tools.',
|
||||
transports: ['streamableHttp'],
|
||||
note: 'Deferred flows test legacy SSE; transport restriction reflects test infrastructure, not behavioral exclusion.',
|
||||
deferred: 'Legacy SSE transport is deprecated in the spec. Back-compat flows that require an SSE server are deferred.'
|
||||
note: 'This is an HTTP-specific compatibility flow; the matrix transport arg is ignored, so it runs as a single streamableHttp-labelled cell to avoid duplicate runs. The SSE half is hosted with SSEServerTransport from @modelcontextprotocol/server-legacy/sse.'
|
||||
},
|
||||
'flow:compat:streamable-then-sse-fallback': {
|
||||
source: 'https://modelcontextprotocol.io/specification/2025-11-25/basic/transports#backwards-compatibility',
|
||||
behavior:
|
||||
'When a streamable HTTP initialize fails with 400, 404, or 405, falling back to the legacy SSE client transport against the same server connects successfully.',
|
||||
transports: ['streamableHttp'],
|
||||
note: 'This is an HTTP-specific compatibility flow; the matrix transport arg is ignored, so it runs as a single streamableHttp-labelled cell to avoid duplicate runs.',
|
||||
deferred: 'Legacy SSE transport is deprecated in the spec. Back-compat flows that require an SSE server are deferred.'
|
||||
note: 'This is an HTTP-specific compatibility flow; the matrix transport arg is ignored, so it runs as a single streamableHttp-labelled cell to avoid duplicate runs.'
|
||||
},
|
||||
'flow:elicitation:multi-step-form': {
|
||||
transports: STATEFUL_TRANSPORTS,
|
||||
|
|
@ -2717,12 +2715,7 @@ export const REQUIREMENTS: Record<string, Requirement> = {
|
|||
behavior:
|
||||
'The SDK provides a server-side legacy HTTP+SSE transport so existing SSE deployments can be hosted on SDK components alone.',
|
||||
transports: ['sse'],
|
||||
note: 'This asserts the availability of the server half of the legacy SSE transport; the matrix transport arg is ignored, so it runs as a single sse-labelled cell.',
|
||||
knownFailures: [
|
||||
{
|
||||
note: 'changed in v2: the server-side SSE transport was removed from the SDK; only the client-side SSEClientTransport remains, so the e2e sse column is hosted by a test-only bridge.'
|
||||
}
|
||||
]
|
||||
note: 'This asserts the availability of the server half of the legacy SSE transport (SSEServerTransport from @modelcontextprotocol/server-legacy/sse); the matrix transport arg is ignored, so it runs as a single sse-labelled cell.'
|
||||
}
|
||||
} satisfies Record<string, Requirement>;
|
||||
|
||||
|
|
|
|||
|
|
@ -9,7 +9,7 @@
|
|||
*/
|
||||
|
||||
import type { OAuthClientProvider } from '@modelcontextprotocol/client';
|
||||
import { Client, StreamableHTTPClientTransport, UnauthorizedError } from '@modelcontextprotocol/client';
|
||||
import { Client, SdkHttpError, SSEClientTransport, StreamableHTTPClientTransport, UnauthorizedError } from '@modelcontextprotocol/client';
|
||||
import type {
|
||||
ElicitRequest,
|
||||
ElicitResult,
|
||||
|
|
@ -25,9 +25,84 @@ import { expect, vi } from 'vitest';
|
|||
import { z } from 'zod/v4';
|
||||
|
||||
import { hostPerSession, hostResumable, wire } from '../helpers/index.js';
|
||||
import { startLegacySseHost } from '../helpers/sse-host.js';
|
||||
import { verifies } from '../helpers/verifies.js';
|
||||
import type { TestArgs } from '../types.js';
|
||||
|
||||
verifies('flow:compat:dual-transport-server', async (_args: TestArgs) => {
|
||||
// One deployment, one server factory, both transports: the modern Streamable HTTP
|
||||
// endpoint and the legacy SSE endpoint serve the same tools to concurrent clients.
|
||||
const makeServer = () => {
|
||||
const s = new McpServer({ name: 'dual-transport', version: '1.0.0' });
|
||||
s.registerTool('add', { inputSchema: z.object({ a: z.number(), b: z.number() }) }, ({ a, b }) => ({
|
||||
content: [{ type: 'text', text: String(a + b) }]
|
||||
}));
|
||||
return s;
|
||||
};
|
||||
|
||||
const streamableHost = hostPerSession(makeServer);
|
||||
const sseHost = await startLegacySseHost(makeServer);
|
||||
try {
|
||||
const httpClient = new Client({ name: 'streamable-client', version: '1.0.0' });
|
||||
const fetch = (u: URL | string, init?: RequestInit) => streamableHost.handleRequest(new Request(u, init));
|
||||
await httpClient.connect(new StreamableHTTPClientTransport(new URL('http://in-process/mcp'), { fetch }));
|
||||
|
||||
const sseClient = new Client({ name: 'sse-client', version: '1.0.0' });
|
||||
await sseClient.connect(new SSEClientTransport(sseHost.url));
|
||||
|
||||
// Both clients are connected at the same time and reach the same tool surface.
|
||||
const [httpResult, sseResult] = await Promise.all([
|
||||
httpClient.callTool({ name: 'add', arguments: { a: 1, b: 2 } }),
|
||||
sseClient.callTool({ name: 'add', arguments: { a: 3, b: 4 } })
|
||||
]);
|
||||
expect(httpResult.content).toEqual([{ type: 'text', text: '3' }]);
|
||||
expect(sseResult.content).toEqual([{ type: 'text', text: '7' }]);
|
||||
|
||||
await httpClient.close();
|
||||
await sseClient.close();
|
||||
} finally {
|
||||
await streamableHost.close();
|
||||
await sseHost.close();
|
||||
}
|
||||
});
|
||||
|
||||
verifies('flow:compat:streamable-then-sse-fallback', async (_args: TestArgs) => {
|
||||
// An SSE-only deployment (a pre-Streamable-HTTP server). A client that prefers
|
||||
// Streamable HTTP gets a 4xx on initialize and falls back to the legacy SSE
|
||||
// client transport against the same URL, per the spec's backwards-compatibility
|
||||
// guidance for clients.
|
||||
const makeServer = () => {
|
||||
const s = new McpServer({ name: 'sse-only', version: '1.0.0' });
|
||||
s.registerTool('greet', { inputSchema: z.object({}) }, () => ({ content: [{ type: 'text', text: 'hello' }] }));
|
||||
return s;
|
||||
};
|
||||
|
||||
const host = await startLegacySseHost(makeServer);
|
||||
try {
|
||||
// 1. Streamable HTTP attempt: POSTing initialize to the legacy SSE endpoint fails with a 4xx.
|
||||
const streamableClient = new Client({ name: 'fallback-client', version: '1.0.0' });
|
||||
let rejection: unknown;
|
||||
try {
|
||||
await streamableClient.connect(new StreamableHTTPClientTransport(host.url));
|
||||
} catch (error) {
|
||||
rejection = error;
|
||||
}
|
||||
expect(rejection).toBeInstanceOf(SdkHttpError);
|
||||
if (!(rejection instanceof SdkHttpError)) throw new Error('rejection is not an SdkHttpError');
|
||||
// 400/404/405 is the signal to fall back to the legacy transport.
|
||||
expect([400, 404, 405]).toContain(rejection.status);
|
||||
|
||||
// 2. Fall back to the legacy SSE client transport against the same server.
|
||||
const sseClient = new Client({ name: 'fallback-client', version: '1.0.0' });
|
||||
await sseClient.connect(new SSEClientTransport(host.url));
|
||||
const result = await sseClient.callTool({ name: 'greet', arguments: {} });
|
||||
expect(result.content).toEqual([{ type: 'text', text: 'hello' }]);
|
||||
await sseClient.close();
|
||||
} finally {
|
||||
await host.close();
|
||||
}
|
||||
});
|
||||
|
||||
verifies('flow:elicitation:multi-step-form', async ({ transport }: TestArgs) => {
|
||||
// Server: tool that issues three sequential elicitation/create requests
|
||||
const makeServer = () => {
|
||||
|
|
|
|||
|
|
@ -16,7 +16,8 @@ verifies('transport:sse:server-transport', async (_args: TestArgs) => {
|
|||
const surfaces = await Promise.all([
|
||||
import('@modelcontextprotocol/server'),
|
||||
import('@modelcontextprotocol/node'),
|
||||
import('@modelcontextprotocol/express')
|
||||
import('@modelcontextprotocol/express'),
|
||||
import('@modelcontextprotocol/server-legacy/sse')
|
||||
]);
|
||||
const exported = surfaces.flatMap(surface => Object.keys(surface));
|
||||
const sseServerExports = exported.filter(name => /sse/i.test(name) && /server/i.test(name));
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@
|
|||
"@modelcontextprotocol/server/_shims": ["./node_modules/@modelcontextprotocol/server/src/shimsNode.ts"],
|
||||
"@modelcontextprotocol/server/validators/ajv": ["./node_modules/@modelcontextprotocol/server/src/validators/ajv.ts"],
|
||||
"@modelcontextprotocol/server/validators/cf-worker": ["./node_modules/@modelcontextprotocol/server/src/validators/cfWorker.ts"],
|
||||
"@modelcontextprotocol/server-legacy/sse": ["./node_modules/@modelcontextprotocol/server-legacy/src/sse/index.ts"],
|
||||
"@modelcontextprotocol/express": ["./node_modules/@modelcontextprotocol/express/src/index.ts"],
|
||||
"@modelcontextprotocol/fastify": ["./node_modules/@modelcontextprotocol/fastify/src/index.ts"],
|
||||
"@modelcontextprotocol/hono": ["./node_modules/@modelcontextprotocol/hono/src/index.ts"],
|
||||
|
|
|
|||
Loading…
Reference in a new issue