Skip to content

Commit 2f64ff6

Browse files
docs(examples): runnable subscriptions/listen example pair
A server hosted via createMcpHandler that mutates its tool set every two seconds and publishes the change via handler.notify.toolsChanged(); a client that drives it two ways on a 2026-07-28 connection: auto-open via ClientOptions.listChanged (the same option a 2025-era client sets), then manual client.listen() with a setNotificationHandler registration. Both legs verified running from source via tsx; README-indexed.
1 parent 78a4de1 commit 2f64ff6

4 files changed

Lines changed: 140 additions & 0 deletions

File tree

‎examples/client/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ Most clients expect a server to be running. Start one from [`../server/README.md
3636
| Client credentials (M2M) | Machine-to-machine OAuth client credentials example. | [`src/simpleClientCredentials.ts`](src/simpleClientCredentials.ts) |
3737
| URL elicitation client | Drives URL-mode elicitation flows (sensitive input in a browser). | [`src/elicitationUrlExample.ts`](src/elicitationUrlExample.ts) |
3838
| Multi-round-trip client (2026-07-28) | Calls a write-once tool twice: default auto-fulfilment, then manual mode. | [`src/multiRoundTripClient.ts`](src/multiRoundTripClient.ts) |
39+
| Subscriptions/listen client (2026-07-28) | `listChanged` auto-open then manual `client.listen()`; closes after a few changes. | [`src/subscriptionsListenClient.ts`](src/subscriptionsListenClient.ts) |
3940

4041
## URL elicitation example (server + client)
4142

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
/**
2+
* Drives the `subscriptions/listen` server example
3+
* (`examples/server/src/subscriptionsListen.ts`) two ways on a 2026-07-28
4+
* connection:
5+
*
6+
* 1. **auto-open via `ClientOptions.listChanged`** — the same option a
7+
* 2025-era client sets; on a modern connection the SDK auto-opens a
8+
* listen stream with the filter derived from which sub-options were set,
9+
* so the configured `onChanged` handlers fire on every published change;
10+
* 2. **manual `client.listen()`** — opens a stream explicitly, registers a
11+
* `notifications/tools/list_changed` handler the stream feeds, and closes
12+
* after a few notifications.
13+
*
14+
* Start the server first, then:
15+
*
16+
* tsx examples/client/src/subscriptionsListenClient.ts
17+
*/
18+
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
19+
20+
const URL = process.env.MCP_SERVER_URL ?? 'http://localhost:3000/';
21+
const CLIENT_INFO = { name: 'subscriptions-listen-example-client', version: '1.0.0' };
22+
23+
async function autoOpenLeg(): Promise<void> {
24+
console.log('--- auto-open via ClientOptions.listChanged ---');
25+
let count = 0;
26+
let done!: () => void;
27+
const finished = new Promise<void>(resolve => {
28+
done = resolve;
29+
});
30+
const client = new Client(CLIENT_INFO, {
31+
versionNegotiation: { mode: 'auto' },
32+
listChanged: {
33+
tools: {
34+
// autoRefresh: false — automatic per-request envelope emission
35+
// is a client-side follow-up; until then a refreshing
36+
// listTools() on a 2026 connection needs the envelope attached
37+
// explicitly (see the multi-round-trip example).
38+
autoRefresh: false,
39+
onChanged: () => {
40+
console.log('[client] (auto) tools/list_changed received');
41+
if (++count >= 2) done();
42+
}
43+
}
44+
}
45+
});
46+
await client.connect(new StreamableHTTPClientTransport(new globalThis.URL(URL)));
47+
console.log(`[client] (auto) connected (${client.getNegotiatedProtocolVersion()}); auto-opened filter:`, client.autoOpenedSubscription?.honoredFilter);
48+
await finished;
49+
await client.autoOpenedSubscription?.close();
50+
await client.close();
51+
}
52+
53+
async function manualLeg(): Promise<void> {
54+
console.log('--- manual client.listen() ---');
55+
const client = new Client(CLIENT_INFO, { versionNegotiation: { mode: 'auto' } });
56+
let count = 0;
57+
let done!: () => void;
58+
const finished = new Promise<void>(resolve => {
59+
done = resolve;
60+
});
61+
client.setNotificationHandler('notifications/tools/list_changed', () => {
62+
console.log('[client] (manual) tools/list_changed received');
63+
if (++count >= 2) done();
64+
});
65+
await client.connect(new StreamableHTTPClientTransport(new globalThis.URL(URL)));
66+
const sub = await client.listen({ toolsListChanged: true });
67+
console.log('[client] (manual) listening; honored filter:', sub.honoredFilter);
68+
await finished;
69+
await sub.close();
70+
await client.close();
71+
}
72+
73+
await autoOpenLeg();
74+
await manualLeg();
75+
console.log('done.');

‎examples/server/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ pnpm tsx src/simpleStreamableHttp.ts
3939
| Hono Streamable HTTP server | Streamable HTTP server built with Hono instead of Express. | [`src/honoWebStandardStreamableHttp.ts`](src/honoWebStandardStreamableHttp.ts) |
4040
| SSE polling demo server | Legacy SSE server intended for polling demos. | [`src/ssePollingExample.ts`](src/ssePollingExample.ts) |
4141
| Multi-round-trip server (2026-07-28) | Write-once tool that returns `inputRequired(...)` (form + URL elicitation, requestState echo) via `createMcpHandler`. | [`src/multiRoundTrip.ts`](src/multiRoundTrip.ts) |
42+
| Subscriptions/listen server (2026-07-28) | Publishes `tools/list_changed` to open `subscriptions/listen` streams via `handler.notify.toolsChanged()`. | [`src/subscriptionsListen.ts`](src/subscriptionsListen.ts) |
4243

4344
## OAuth demo flags (Streamable HTTP server)
4445

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
/**
2+
* `subscriptions/listen` change notifications served via `createMcpHandler`
3+
* (protocol revision 2026-07-28).
4+
*
5+
* The handler exposes `.notify` typed publish sugar over its
6+
* `subscriptions/listen` bus: this example calls
7+
* `handler.notify.toolsChanged()` whenever a tool is added or removed, and
8+
* every open `subscriptions/listen` stream that opted in to
9+
* `toolsListChanged` receives a stamped `notifications/tools/list_changed`.
10+
*
11+
* Run with:
12+
*
13+
* tsx examples/server/src/subscriptionsListen.ts
14+
*
15+
* and point the paired client example at it:
16+
*
17+
* tsx examples/client/src/subscriptionsListenClient.ts
18+
*/
19+
import { createServer } from 'node:http';
20+
21+
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
22+
import * as z from 'zod/v4';
23+
24+
let extraToolEnabled = false;
25+
26+
function buildServer(): McpServer {
27+
const server = new McpServer({ name: 'subscriptions-listen-example', version: '1.0.0' });
28+
29+
server.registerTool(
30+
'greet',
31+
{ description: 'Returns a greeting', inputSchema: z.object({ name: z.string() }) },
32+
async ({ name }) => ({ content: [{ type: 'text', text: `hello, ${name}` }] })
33+
);
34+
if (extraToolEnabled) {
35+
server.registerTool(
36+
'farewell',
37+
{ description: 'Returns a farewell', inputSchema: z.object({ name: z.string() }) },
38+
async ({ name }) => ({ content: [{ type: 'text', text: `goodbye, ${name}` }] })
39+
);
40+
}
41+
42+
return server;
43+
}
44+
45+
// Host with the per-request HTTP entry on its default posture (2026-07-28
46+
// served per request; 2025-era traffic served stateless from the same
47+
// factory). The handler creates an in-process bus by default; supply your
48+
// own `bus` for multi-process deployments.
49+
const handler = createMcpHandler(() => buildServer());
50+
const port = Number(process.env.PORT ?? '3000');
51+
52+
createServer((req, res) => void handler.node(req, res)).listen(port, () => {
53+
console.error(`subscriptions/listen example server listening on http://localhost:${port}/`);
54+
});
55+
56+
// Mutate the tool set every two seconds and publish the change to every open
57+
// subscription stream that opted in to toolsListChanged. Safe to call when no
58+
// subscription is open (no-op).
59+
setInterval(() => {
60+
extraToolEnabled = !extraToolEnabled;
61+
console.error(`tools changed: farewell ${extraToolEnabled ? 'added' : 'removed'}`);
62+
handler.notify.toolsChanged();
63+
}, 2000);

0 commit comments

Comments
 (0)