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:
Felix Weinberger 2026-06-26 14:01:10 +01:00 • committed by GitHub
commit 1823aae891
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 69131 additions and 9001 deletions

View file

@ -0,0 +1,16 @@
# subscriptions
`subscriptions/listen` change-notification streams (protocol revision 2026-07-28). The server publishes `tools/list_changed`; the client receives it both via the auto-opened stream (`ClientOptions.listChanged`, the same option a 2025-era client sets) and a manual
`client.listen()` call.
The publish surface differs by entry: over HTTP (`createMcpHandler`) the example calls `handler.notify.toolsChanged()` on the cross-request `ServerEventBus`; over stdio (`serveStdio`) it toggles a `RegisteredTool` on the pinned instance, whose `tools/list_changed` the entry's
listen router fans onto every open subscription.
```bash
# stdio (the client spawns the server itself):
pnpm tsx examples/subscriptions/client.ts
# Streamable HTTP (two terminals):
pnpm tsx examples/subscriptions/server.ts --http --port 3000
pnpm tsx examples/subscriptions/client.ts --http http://127.0.0.1:3000/
```

View file

@ -0,0 +1,90 @@
/**
* Drives the `subscriptions/listen` server (`./server.ts`) two ways on a
* 2026-07-28 connection:
*
* 1. **auto-open via `ClientOptions.listChanged`** — the same option a
* 2025-era client sets; on a modern connection the SDK auto-opens a
* listen stream with the filter derived from which sub-options were set,
* so the configured `onChanged` handlers fire on every published change;
* 2. **manual `client.listen()`** — opens a stream explicitly, registers a
* `notifications/tools/list_changed` handler the stream feeds, and closes
* after a few notifications.
*
* The example calls `flip_tools` to mutate the server's tool set on demand
* (rather than a timer), then asserts the change notification arrived.
*/
import { check, parseExampleArgs, siblingPath } from '@mcp-examples/shared';
import type { ClientOptions, McpSubscription } from '@modelcontextprotocol/client';
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
/** Wait until `pred()` is true or `timeoutMs` elapses. */
async function until(pred: () => boolean, timeoutMs = 5000): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!pred()) {
if (Date.now() > deadline) throw new Error('timed out waiting for change notification');
await new Promise(r => setTimeout(r, 25));
}
}
const { transport, url } = parseExampleArgs();
// Both legs connect identically and differ only in ClientOptions; the local
// helper keeps the SDK transport setup visible in THIS file (the canonical
// shape) while avoiding duplicating it for each leg. Modern-only —
// `subscriptions/listen` is a 2026-07-28 protocol feature.
const connect = async (options?: ClientOptions): Promise<Client> => {
const client = new Client(
{ name: 'subscriptions-example-client', version: '1.0.0' },
{ versionNegotiation: { mode: 'auto' }, ...options }
);
await (transport === 'stdio'
? client.connect(new StdioClientTransport({ command: 'npx', args: ['-y', 'tsx', siblingPath(import.meta.url, 'server.ts')] }))
: client.connect(new StreamableHTTPClientTransport(new URL(url))));
return client;
};
// --- auto-open via ClientOptions.listChanged ---
{
let count = 0;
const client = await connect({
listChanged: {
tools: {
autoRefresh: false,
// The default debounce coalesces bursts; this example asserts
// raw delivery, so disable it.
debounceMs: 0,
onChanged: () => void count++
}
}
});
check.ok(client.autoOpenedSubscription, 'a listChanged option should auto-open a subscription on a modern connection');
check.ok(client.autoOpenedSubscription?.honoredFilter.toolsListChanged, 'auto-opened filter should include toolsListChanged');
await client.callTool({ name: 'flip_tools' });
await until(() => count >= 1);
await client.callTool({ name: 'flip_tools' });
await until(() => count >= 2);
await client.autoOpenedSubscription?.close();
await client.close();
check.ok(count >= 2, 'auto-open leg should receive at least two tools/list_changed');
}
// --- manual client.listen() ---
{
const client = await connect();
let count = 0;
client.setNotificationHandler('notifications/tools/list_changed', () => void count++);
const sub: McpSubscription = await client.listen({ toolsListChanged: true });
check.ok(sub.honoredFilter.toolsListChanged, 'manual listen should honor toolsListChanged');
await client.callTool({ name: 'flip_tools' });
await until(() => count >= 1);
await client.callTool({ name: 'flip_tools' });
await until(() => count >= 2);
await sub.close();
await client.close();
check.ok(count >= 2, 'manual leg should receive at least two tools/list_changed');
}

View file

@ -0,0 +1,23 @@
{
"name": "@mcp-examples/subscriptions",
"private": true,
"type": "module",
"scripts": {
"server": "tsx server.ts",
"client": "tsx client.ts"
},
"dependencies": {
"@mcp-examples/shared": "workspace:*",
"@modelcontextprotocol/client": "workspace:*",
"@modelcontextprotocol/node": "workspace:*",
"@modelcontextprotocol/server": "workspace:*",
"zod": "catalog:runtimeShared"
},
"devDependencies": {
"tsx": "catalog:devTools"
},
"example": {
"era": "modern",
"//": "subscriptions/listen is a 2026-07-28 protocol feature."
}
}

View file

@ -0,0 +1,89 @@
/**
* `subscriptions/listen` change notifications (protocol revision 2026-07-28).
*
* One factory, either transport — but the publish surface differs by entry:
*
* - **HTTP** (`createMcpHandler`): the handler exposes `.notify`
* ({@link ServerNotifier}) over its cross-request {@link ServerEventBus};
* `handler.notify.toolsChanged()` reaches every open `subscriptions/listen`
* stream that opted in to `toolsListChanged`.
* - **stdio** (`serveStdio`): one `McpServer` instance is pinned for the
* connection; toggling a `RegisteredTool` (`.enable()/.disable()`) emits the
* instance's own `notifications/tools/list_changed`, which the stdio entry's
* listen router fans onto every open subscription.
*
* The `flip_tools` tool toggles the `farewell` tool and publishes the change,
* so the client decides when to mutate (no timer race with the runner). The
* canonical-shape transport branch below assigns `publish` per entry.
*/
import { createServer } from 'node:http';
import { parseExampleArgs } from '@mcp-examples/shared';
import { toNodeHandler } from '@modelcontextprotocol/node';
import type { RegisteredTool, ServerEventBus, ServerNotifier } from '@modelcontextprotocol/server';
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
let extraToolEnabled = false;
/**
* Publishes `tools/list_changed` to every open subscription. Assigned by the
* transport branch below: `handler.notify.toolsChanged()` over HTTP; toggling
* the pinned instance's `RegisteredTool` over stdio.
*/
let publish: () => void = () => {};
function buildServer(): McpServer {
const server = new McpServer(
{ name: 'subscriptions-listen-example', version: '1.0.0' },
{ capabilities: { tools: { listChanged: true } } }
);
server.registerTool('greet', { description: 'Returns a greeting', inputSchema: z.object({ name: z.string() }) }, async ({ name }) => ({
content: [{ type: 'text', text: `hello, ${name}` }]
}));
const farewell: RegisteredTool = server.registerTool(
'farewell',
{ description: 'Returns a farewell', inputSchema: z.object({ name: z.string() }) },
async ({ name }) => ({ content: [{ type: 'text', text: `goodbye, ${name}` }] })
);
if (!extraToolEnabled) farewell.disable();
server.registerTool(
'flip_tools',
{ description: 'Toggle the farewell tool and publish tools/list_changed to every open subscription' },
async () => {
extraToolEnabled = !extraToolEnabled;
// Over stdio this `update` IS the publish (the entry's listen
// router fans the instance's outbound list_changed onto every open
// subscription); over HTTP it just keeps this per-request instance
// consistent and `publish()` reaches the cross-request bus.
farewell.update({ enabled: extraToolEnabled });
publish();
return { content: [{ type: 'text', text: `farewell ${extraToolEnabled ? 'enabled' : 'disabled'}` }] };
}
);
return server;
}
const { transport, port } = parseExampleArgs();
if (transport === 'stdio') {
// Over stdio the per-instance `farewell.update` inside `flip_tools` IS the
// publish, so `publish` stays a no-op here.
void serveStdio(buildServer);
console.error('[server] serving over stdio');
} else {
// Host with the per-request HTTP entry on its default posture. The handler
// creates an in-process bus by default; supply your own `bus` for
// multi-process deployments.
const handler = createMcpHandler(buildServer);
const bus: ServerEventBus = handler.bus;
const notify: ServerNotifier = handler.notify;
void bus; // (the typed publish facade `notify` wraps `bus.publish`)
publish = () => notify.toolsChanged();
createServer(toNodeHandler(handler)).listen(port, () => {
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
});
}