docs(servers): document resources/subscribe serving; exercise subscriptions in the resources example (#2413)
This commit is contained in:
parent
35f6856a17
commit
ddf6cc1d73
3 changed files with 221 additions and 11 deletions
|
|
@ -1,6 +1,6 @@
|
|||
# resources
|
||||
|
||||
Direct resources (a fixed URI string) and templated resources (`ResourceTemplate('greeting://{name}')`). The client lists both, reads the direct config, and reads a templated greeting.
|
||||
Direct resources (a fixed URI string), templated resources (`ResourceTemplate('greeting://{name}')`), and per-resource subscriptions. The client lists both kinds, reads the direct config and a templated greeting, then subscribes to `counter://value` — `subscriptions/listen` on 2026-07-28, `resources/subscribe` on 2025 — calls the `increment` tool, and asserts the `notifications/resources/updated` it produces. Per-request legacy HTTP has no delivery channel, so that leg skips the delivery assertion.
|
||||
|
||||
```bash
|
||||
pnpm tsx examples/resources/client.ts
|
||||
|
|
|
|||
|
|
@ -1,5 +1,11 @@
|
|||
/**
|
||||
* Drives the resources example: list, list templates, read direct + templated.
|
||||
* Drives the resources example: list, list templates, read direct + templated,
|
||||
* then subscribe to `counter://value` and assert the update notification. The
|
||||
* subscription sender is era-split — `subscriptions/listen` on 2026-07-28,
|
||||
* `resources/subscribe` on 2025 — while the notification handler is one
|
||||
* registration either way. Per-request legacy HTTP has no channel to deliver
|
||||
* notifications, so that leg asserts the calls succeed and skips the delivery
|
||||
* assertion.
|
||||
*/
|
||||
import { check, parseExampleArgs, siblingPath } from '@mcp-examples/shared';
|
||||
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
|
||||
|
|
@ -18,6 +24,7 @@ await (transport === 'stdio'
|
|||
|
||||
const list = await client.listResources();
|
||||
check.ok(list.resources.some(r => r.uri === 'config://app'));
|
||||
check.ok(list.resources.some(r => r.uri === 'counter://value'));
|
||||
|
||||
const templates = await client.listResourceTemplates();
|
||||
check.ok(templates.resourceTemplates.some(t => t.uriTemplate === 'greeting://{name}'));
|
||||
|
|
@ -30,4 +37,52 @@ const hello = await client.readResource({ uri: 'greeting://world' });
|
|||
const helloContent = hello.contents[0];
|
||||
check.equal(helloContent && 'text' in helloContent ? helloContent.text : '', 'Hello, world!');
|
||||
|
||||
// --- Subscriptions ---------------------------------------------------------
|
||||
|
||||
// One handler serves both delivery paths: the 2026-07-28 listen stream and a
|
||||
// 2025-era connection's unsolicited notification dispatch the same way.
|
||||
let resolveUpdated: ((uri: string) => void) | undefined;
|
||||
client.setNotificationHandler('notifications/resources/updated', notification => {
|
||||
resolveUpdated?.(notification.params.uri);
|
||||
});
|
||||
|
||||
// Per-request legacy HTTP answers each POST in isolation: subscribing succeeds,
|
||||
// but there is no stream to deliver the notification on.
|
||||
const deliverable = !(era === 'legacy' && transport === 'http');
|
||||
|
||||
const updated = new Promise<string>(resolve => {
|
||||
resolveUpdated = resolve;
|
||||
});
|
||||
|
||||
const subscription = era === 'modern' ? await client.listen({ resourceSubscriptions: ['counter://value'] }) : undefined;
|
||||
if (era === 'legacy') {
|
||||
await client.subscribeResource({ uri: 'counter://value' });
|
||||
}
|
||||
|
||||
const bumped = await client.callTool({ name: 'increment', arguments: {} });
|
||||
check.ok(!bumped.isError);
|
||||
const bumpedContent = bumped.content[0];
|
||||
const bumpedValue = bumpedContent && bumpedContent.type === 'text' ? bumpedContent.text : '';
|
||||
|
||||
if (deliverable) {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error('no resources/updated within 8s')), 8000);
|
||||
});
|
||||
const updatedUri = await Promise.race([updated, timeout]).finally(() => clearTimeout(timer));
|
||||
check.equal(updatedUri, 'counter://value');
|
||||
|
||||
// The resource and the tool observe the same state: the re-read matches the
|
||||
// value increment returned (not a literal, so a long-lived server re-runs).
|
||||
const counter = await client.readResource({ uri: 'counter://value' });
|
||||
const counterContent = counter.contents[0];
|
||||
check.equal(counterContent && 'text' in counterContent ? counterContent.text : '', bumpedValue);
|
||||
}
|
||||
|
||||
if (subscription) {
|
||||
await subscription.close();
|
||||
} else if (era === 'legacy') {
|
||||
await client.unsubscribeResource({ uri: 'counter://value' });
|
||||
}
|
||||
|
||||
await client.close();
|
||||
|
|
|
|||
|
|
@ -1,19 +1,33 @@
|
|||
/**
|
||||
* Resources primitive — direct + templated.
|
||||
* Resources primitive — direct, templated, and subscribable.
|
||||
*
|
||||
* `McpServer.registerResource` accepts either a fixed URI string (direct
|
||||
* resource) or a `ResourceTemplate` (URI template with substitution). One
|
||||
* binary, either transport — selected from argv below.
|
||||
* resource) or a `ResourceTemplate` (URI template with substitution). The
|
||||
* `counter://value` resource is mutable: the `increment` tool bumps it and
|
||||
* announces the change — in-band to this connection (2025-era subscribers
|
||||
* tracked per connection, 2026-07-28 listen streams routed by the entry), and
|
||||
* on the handler's notifier for clients on other requests. One binary, either
|
||||
* transport — selected from argv below.
|
||||
*/
|
||||
import { createServer } from 'node:http';
|
||||
|
||||
import { parseExampleArgs } from '@mcp-examples/shared';
|
||||
import { toNodeHandler } from '@modelcontextprotocol/node';
|
||||
import type { McpRequestContext } from '@modelcontextprotocol/server';
|
||||
import { createMcpHandler, McpServer, ResourceTemplate } from '@modelcontextprotocol/server';
|
||||
import { serveStdio } from '@modelcontextprotocol/server/stdio';
|
||||
|
||||
function buildServer(): McpServer {
|
||||
const server = new McpServer({ name: 'resources-example', version: '1.0.0' });
|
||||
const COUNTER_URI = 'counter://value';
|
||||
|
||||
// The counter is application state, shared by every connection; which URIs a
|
||||
// connection subscribed to is connection state, tracked inside buildServer.
|
||||
let counter = 0;
|
||||
|
||||
function buildServer(reqCtx: McpRequestContext, publishUpdated?: (uri: string) => void): McpServer {
|
||||
const server = new McpServer(
|
||||
{ name: 'resources-example', version: '1.0.0' },
|
||||
{ capabilities: { resources: { subscribe: true, listChanged: true } } }
|
||||
);
|
||||
|
||||
// A direct resource at a fixed URI.
|
||||
server.registerResource(
|
||||
|
|
@ -31,16 +45,52 @@ function buildServer(): McpServer {
|
|||
async (uri, vars) => ({ contents: [{ uri: uri.href, text: `Hello, ${vars.name}!` }] })
|
||||
);
|
||||
|
||||
// A mutable resource — the subscription story's subject.
|
||||
server.registerResource(
|
||||
'counter',
|
||||
COUNTER_URI,
|
||||
{ mimeType: 'text/plain', description: 'A number the increment tool bumps' },
|
||||
async uri => ({ contents: [{ uri: uri.href, mimeType: 'text/plain', text: String(counter) }] })
|
||||
);
|
||||
|
||||
// resources/subscribe bookkeeping is the application's: the SDK routes the
|
||||
// two verbs, and which URIs THIS connection watches lives here.
|
||||
const subscribedUris = new Set<string>();
|
||||
server.server.setRequestHandler('resources/subscribe', request => {
|
||||
subscribedUris.add(request.params.uri);
|
||||
return {};
|
||||
});
|
||||
server.server.setRequestHandler('resources/unsubscribe', request => {
|
||||
subscribedUris.delete(request.params.uri);
|
||||
return {};
|
||||
});
|
||||
|
||||
server.registerTool('increment', { description: `Bump ${COUNTER_URI} by one` }, async () => {
|
||||
counter += 1;
|
||||
if (publishUpdated) {
|
||||
// Per-request serving: this instance answers one request and is gone,
|
||||
// so the change is published on the entry's notifier for the listen
|
||||
// streams other requests hold open.
|
||||
publishUpdated(COUNTER_URI);
|
||||
} else if (reqCtx.era === 'modern' || subscribedUris.has(COUNTER_URI)) {
|
||||
// Connection serving (stdio): announce in-band. The entry routes it
|
||||
// onto 2026-07-28 listen streams; on a 2025-era connection it goes
|
||||
// only to subscribers — unsolicited per-resource updates are wrong.
|
||||
await server.server.sendResourceUpdated({ uri: COUNTER_URI }).catch(() => {});
|
||||
}
|
||||
return { content: [{ type: 'text', text: String(counter) }] };
|
||||
});
|
||||
|
||||
return server;
|
||||
}
|
||||
|
||||
const { transport, port } = parseExampleArgs();
|
||||
|
||||
if (transport === 'stdio') {
|
||||
void serveStdio(buildServer);
|
||||
void serveStdio(reqCtx => buildServer(reqCtx));
|
||||
console.error('[server] serving over stdio');
|
||||
} else {
|
||||
const handler = createMcpHandler(buildServer);
|
||||
const handler = createMcpHandler(reqCtx => buildServer(reqCtx, uri => handler.notify.resourceUpdated(uri)));
|
||||
createServer(toNodeHandler(handler)).listen(port, () => {
|
||||
console.error(`[server] listening on http://127.0.0.1:${port}/mcp`);
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue