Implement MCP 2026-07-28 (#2286)
Co-authored-by: Matt <77928207+mattzcarey@users.noreply.github.com> Co-authored-by: Konstantin Konstantinov <KKonstantinov@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
This commit is contained in:
parent
e4227d135c
commit
1823aae891
4 changed files with 69131 additions and 9001 deletions
12
examples/sse-polling/README.md
Normal file
12
examples/sse-polling/README.md
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
# sse-polling
|
||||
|
||||
SEP-1699 server-initiated SSE disconnection + client reconnection with `Last-Event-ID` replay. **Sessionful 2025** by definition (the feature lives on `NodeStreamableHTTPServerTransport` + an `EventStore`). `eventStore` resumability is a 2025-session concern with no 2026-07-28
|
||||
per-request equivalent.
|
||||
|
||||
The `long-operation` tool emits two log notifications, calls `ctx.http?.closeSSE()` mid-stream, emits two more while the client is disconnected, then returns. The client transport reconnects after `retryInterval` (300 ms) with `Last-Event-ID`; the event store replays the buffered
|
||||
events. The client asserts the result arrived AND the post-disconnect log was delivered.
|
||||
|
||||
```bash
|
||||
pnpm --filter @mcp-examples/sse-polling server -- --http --port 3001 # term 1
|
||||
pnpm --filter @mcp-examples/sse-polling client -- --http http://127.0.0.1:3001/mcp # term 2
|
||||
```
|
||||
48
examples/sse-polling/client.ts
Normal file
48
examples/sse-polling/client.ts
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
/**
|
||||
* SSE Polling Example Client (SEP-1699)
|
||||
*
|
||||
* Connects (2025-era), calls `long-operation`, and asserts the result arrives
|
||||
* AFTER the server's mid-stream `closeSSE()` — i.e. the client transport
|
||||
* automatically reconnects with `Last-Event-ID` and replays the events the
|
||||
* `eventStore` buffered while disconnected. Also asserts every progress log
|
||||
* (including the one emitted while disconnected) was delivered.
|
||||
*/
|
||||
import { check, parseExampleArgs } from '@mcp-examples/shared';
|
||||
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
|
||||
|
||||
const { url } = parseExampleArgs();
|
||||
|
||||
// `closeSSE`/`eventStore` live on the sessionful-2025 transport, so this
|
||||
// story is legacy-only by design — it was previously reaching 2025 by
|
||||
// negotiation fallback; pin it.
|
||||
const client = new Client({ name: 'sse-polling-client', version: '1.0.0' }, { versionNegotiation: { mode: 'legacy' } });
|
||||
const logs: string[] = [];
|
||||
client.setNotificationHandler('notifications/message', n => {
|
||||
logs.push(String(n.params.data));
|
||||
});
|
||||
|
||||
const transport = new StreamableHTTPClientTransport(new URL(url));
|
||||
// The mid-stream disconnect surfaces as a transport error before the
|
||||
// automatic reconnect; that is the EXPECTED flow, not a failure.
|
||||
transport.onerror = () => {};
|
||||
await client.connect(transport);
|
||||
|
||||
let lastEventId: string | undefined;
|
||||
const result = await client.request(
|
||||
{ method: 'tools/call', params: { name: 'long-operation', arguments: {} } },
|
||||
{ onresumptiontoken: token => (lastEventId = token) }
|
||||
);
|
||||
|
||||
const text = (result as { content?: Array<{ type: string; text?: string }> }).content?.[0]?.text ?? '';
|
||||
check.match(text, /completed successfully/);
|
||||
check.ok(lastEventId, 'resumption tokens should have been observed');
|
||||
// The 75% line is emitted WHILE the client is disconnected; receiving it
|
||||
// proves the event store replayed it on reconnect. (Replay ordering relative
|
||||
// to the terminal result is not asserted — the result resolving is the
|
||||
// signal the disconnect was survived.)
|
||||
check.ok(
|
||||
logs.some(l => l.includes('75%')),
|
||||
`events emitted while disconnected should be replayed (got: ${logs.join(' | ')})`
|
||||
);
|
||||
|
||||
await client.close();
|
||||
30
examples/sse-polling/package.json
Normal file
30
examples/sse-polling/package.json
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"name": "@mcp-examples/sse-polling",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"server": "tsx server.ts",
|
||||
"client": "tsx client.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@mcp-examples/shared": "workspace:*",
|
||||
"@modelcontextprotocol/client": "workspace:*",
|
||||
"@modelcontextprotocol/express": "workspace:*",
|
||||
"@modelcontextprotocol/node": "workspace:*",
|
||||
"@modelcontextprotocol/server": "workspace:*",
|
||||
"cors": "catalog:runtimeServerOnly",
|
||||
"express": "catalog:runtimeServerOnly"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tsx": "catalog:devTools"
|
||||
},
|
||||
"example": {
|
||||
"transports": [
|
||||
"http"
|
||||
],
|
||||
"era": "legacy",
|
||||
"path": "/mcp",
|
||||
"timeoutMs": 20000,
|
||||
"//": "SEP-1699 closeSSE/eventStore/retryInterval live on the sessionful-2025 transport; the client is era-blind so dual would duplicate."
|
||||
}
|
||||
}
|
||||
133
examples/sse-polling/server.ts
Normal file
133
examples/sse-polling/server.ts
Normal file
|
|
@ -0,0 +1,133 @@
|
|||
/**
|
||||
* SSE Polling Example Server (SEP-1699)
|
||||
*
|
||||
* This example demonstrates server-initiated SSE stream disconnection
|
||||
* and client reconnection with Last-Event-ID for resumability.
|
||||
*
|
||||
* Key features:
|
||||
* - Configures `retryInterval` to tell clients how long to wait before reconnecting
|
||||
* - Uses `eventStore` to persist events for replay after reconnection
|
||||
* - Uses `ctx.http?.closeSSE()` callback to gracefully disconnect clients mid-operation
|
||||
*
|
||||
* HTTP-only, sessionful 2025 by definition — `closeSSE`/`eventStore`/`retryInterval`
|
||||
* live on `NodeStreamableHTTPServerTransport`, so this story wires that transport
|
||||
* directly instead of the canonical `createMcpHandler` entry.
|
||||
*/
|
||||
import { randomUUID } from 'node:crypto';
|
||||
|
||||
import { parseExampleArgs } from '@mcp-examples/shared';
|
||||
import { InMemoryEventStore } from '@mcp-examples/shared/auth';
|
||||
import { createMcpExpressApp } from '@modelcontextprotocol/express';
|
||||
import { NodeStreamableHTTPServerTransport } from '@modelcontextprotocol/node';
|
||||
import type { CallToolResult } from '@modelcontextprotocol/server';
|
||||
import { isInitializeRequest, McpServer } from '@modelcontextprotocol/server';
|
||||
import cors from 'cors';
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
function buildServer(): McpServer {
|
||||
const server = new McpServer(
|
||||
{
|
||||
name: 'sse-polling-example',
|
||||
version: '1.0.0'
|
||||
},
|
||||
{
|
||||
capabilities: { logging: {} }
|
||||
}
|
||||
);
|
||||
|
||||
// Register a long-running tool that demonstrates server-initiated disconnect
|
||||
server.registerTool(
|
||||
'long-operation',
|
||||
{
|
||||
description: 'A long-running operation that sends progress updates. Server will disconnect mid-stream to demonstrate polling.'
|
||||
},
|
||||
async (ctx): Promise<CallToolResult> => {
|
||||
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
|
||||
|
||||
console.error(`[${ctx.sessionId}] Starting long-operation...`);
|
||||
|
||||
// Send first progress notification
|
||||
await ctx.mcpReq.log('info', 'Progress: 25% - Starting work...');
|
||||
await sleep(200);
|
||||
|
||||
// Send second progress notification
|
||||
await ctx.mcpReq.log('info', 'Progress: 50% - Halfway there...');
|
||||
await sleep(200);
|
||||
|
||||
// Server decides to disconnect the client to free resources
|
||||
// Client will reconnect via GET with Last-Event-ID after the transport's retryInterval
|
||||
// Use ctx.http?.closeSSE callback - available when eventStore is configured
|
||||
if (ctx.http?.closeSSE) {
|
||||
console.error(`[${ctx.sessionId}] Closing SSE stream to trigger client polling...`);
|
||||
ctx.http?.closeSSE();
|
||||
}
|
||||
|
||||
// Continue processing while client is disconnected
|
||||
// Events are stored in eventStore and will be replayed on reconnect
|
||||
await sleep(200);
|
||||
await ctx.mcpReq.log('info', 'Progress: 75% - Almost done (sent while client disconnected)...');
|
||||
|
||||
await sleep(200);
|
||||
await ctx.mcpReq.log('info', 'Progress: 100% - Complete!');
|
||||
|
||||
console.error(`[${ctx.sessionId}] Operation complete`);
|
||||
|
||||
return {
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'Long operation completed successfully!'
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
// Set up Express app
|
||||
const app = createMcpExpressApp();
|
||||
app.use(cors());
|
||||
|
||||
// Create event store for resumability
|
||||
const eventStore = new InMemoryEventStore();
|
||||
|
||||
// Track transports by session ID for session reuse
|
||||
const transports = new Map<string, NodeStreamableHTTPServerTransport>();
|
||||
|
||||
// Handle all MCP requests (standard sessionful routing: known sid → reuse;
|
||||
// no sid + initialize → new session; unknown sid → 404; otherwise → 400).
|
||||
app.all('/mcp', async (req: Request, res: Response) => {
|
||||
const sid = req.headers['mcp-session-id'] as string | undefined;
|
||||
if (sid && transports.has(sid)) {
|
||||
await transports.get(sid)!.handleRequest(req, res, req.body);
|
||||
} else if (!sid && isInitializeRequest(req.body)) {
|
||||
const transport = new NodeStreamableHTTPServerTransport({
|
||||
sessionIdGenerator: () => randomUUID(),
|
||||
eventStore,
|
||||
retryInterval: 300, // Default retry interval for priming events
|
||||
onsessioninitialized: id => {
|
||||
console.error(`[${id}] Session initialized`);
|
||||
transports.set(id, transport);
|
||||
}
|
||||
});
|
||||
transport.onclose = () => transport.sessionId && transports.delete(transport.sessionId);
|
||||
await buildServer().connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
} else if (sid) {
|
||||
// Unknown/expired session ID → 404 so the client knows to re-initialize.
|
||||
res.status(404).json({ jsonrpc: '2.0', error: { code: -32_001, message: 'Session not found' }, id: null });
|
||||
} else {
|
||||
res.status(400).json({ jsonrpc: '2.0', error: { code: -32_000, message: 'Bad Request: Session ID required' }, id: null });
|
||||
}
|
||||
});
|
||||
|
||||
const { port } = parseExampleArgs();
|
||||
app.listen(port, () => {
|
||||
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
|
||||
console.error('This server demonstrates SEP-1699 SSE polling:');
|
||||
console.error('- retryInterval: 300ms (client waits before reconnecting)');
|
||||
console.error('- eventStore: InMemoryEventStore (events are persisted for replay)');
|
||||
console.error('Try calling the "long-operation" tool to see server-initiated disconnect in action.');
|
||||
});
|
||||
Loading…
Reference in a new issue