Skip to content

Commit 6852368

Browse files
docs: cover tool content types, prompt image content, elicitation defaults, ping, legacy SSE serving (#2679)
1 parent e3f39c1 commit 6852368

14 files changed

Lines changed: 377 additions & 3 deletions

docs/clients/calling.md

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -169,10 +169,30 @@ The updates stream in while the call is still pending; the return type does not
169169
[ { type: 'text', text: '2 orders exported as csv' } ]
170170
```
171171

172+
## Check the connection
173+
174+
`ping` sends a `ping` request and resolves with the empty result the server returns; the SDK answers a `ping` on both sides automatically, so neither side registers a handler.
175+
176+
```ts source="../../examples/guides/clients/calling.examples.ts#ping_basic"
177+
const pong = await client.ping({ timeout: 5000 });
178+
console.log(pong);
179+
```
180+
181+
The `orders` server answers at once:
182+
183+
```
184+
{}
185+
```
186+
187+
A server that stops answering rejects the call with an `SdkError` coded `REQUEST_TIMEOUT` once `timeout` elapses.
188+
189+
`ping` is a 2025-era method — see [Protocol versions](../protocol-versions.md).
190+
172191
## Recap
173192

174193
- `listTools`, `listResources`, `listResourceTemplates`, and `listPrompts` aggregate every page; `{ cursor }` fetches a single raw page and `listMaxPages` caps the walk.
175194
- `callTool` returns `content` for the model and, when the tool declares an `outputSchema`, `structuredContent` for your application.
176195
- `readResource({ uri })` and `getPrompt({ name, arguments })` follow the same list-then-fetch shape as tools.
177196
- `complete()` returns the server's suggestions for a prompt or resource-template argument.
178197
- `onprogress` in the request options streams progress updates without changing the call's return type.
198+
- `ping()` checks that the server still answers; both sides answer pings automatically.

docs/protocol-versions.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,7 @@ This table is the only copy of the era differences in these docs. `getProtocolEr
171171
| `ctx.mcpReq.log()` level filter | session-scoped `logging/setLevel` | per-request `logLevel` `_meta` envelope key (absent = no logs) |
172172
| HTTP `400` with a JSON-RPC error body | `SdkHttpError` | `ProtocolError`, delivered in-band |
173173
| Era-mismatched spec method (outbound) | n/a | `SdkError(MethodNotSupportedByProtocolVersion)` |
174+
| Liveness check | `client.ping()` | not defined — outbound call rejects per the era-mismatch row |
174175

175176
## Separate deprecation from era
176177

docs/servers/elicitation.md

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,45 @@ server.registerTool(
123123
[ { type: 'text', text: 'Declined - nothing deleted.' } ]
124124
```
125125

126+
## Prefill a field with a default
127+
128+
Set `default` on a field and the client renders the form with that value already filled in.
129+
130+
```ts source="../../examples/guides/servers/elicitation.examples.ts#registerTool_elicitDefault"
131+
server.registerTool(
132+
'export-report',
133+
{
134+
description: 'Export a report after the user picks a format',
135+
inputSchema: z.object({ name: z.string() })
136+
},
137+
async ({ name }, ctx) => {
138+
const result = await ctx.mcpReq.elicitInput({
139+
mode: 'form',
140+
message: `Export ${name} as which format?`,
141+
requestedSchema: {
142+
type: 'object',
143+
properties: { format: { type: 'string', title: 'Format', enum: ['pdf', 'csv'], default: 'pdf' } },
144+
required: ['format']
145+
}
146+
});
147+
if (result.action !== 'accept') {
148+
return { content: [{ type: 'text', text: `Export ${result.action}.` }] };
149+
}
150+
return { content: [{ type: 'text', text: `Exported ${name} as ${result.content?.format}.` }] };
151+
}
152+
);
153+
```
154+
155+
`requestedSchema` reaches the client unchanged, `default` included; the end user submits the prefilled `pdf` or picks `csv`. An accept with `format` left out still returns:
156+
157+
```
158+
[ { type: 'text', text: 'Exported quarterly-sales as pdf.' } ]
159+
```
160+
161+
::: info
162+
A client that declares `elicitation: { form: { applyDefaults: true } }` — an SDK flag, not a protocol capability — fills defaulted fields the end user leaves out before the accept reaches your handler; the output above is that case.
163+
:::
164+
126165
## Send the end user to a URL
127166

128167
**URL mode** replaces the form with a browser flow: pass `url` and a unique `elicitationId` instead of `requestedSchema`.
@@ -181,5 +220,6 @@ Elicitation only works against a client that declared the `elicitation` capabili
181220
- `ctx.mcpReq.elicitInput` sends an `elicitation/create` request mid-handler and resolves with the end user's answer.
182221
- Form mode carries a `message` and a flat JSON-Schema `requestedSchema`; the SDK validates accepted content against it.
183222
- `result.action` is `accept`, `decline`, or `cancel`; `result.content` is present only on accept.
223+
- `default` on a `requestedSchema` field prefills the form; a client that declares `applyDefaults` fills the field in when the end user leaves it out.
184224
- URL mode hands the end user a browser flow — use it for anything sensitive.
185225
- Calls against a client that never declared the `elicitation` capability fail before reaching the wire.

docs/servers/prompts.md

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,47 @@ server.registerPrompt(
116116

117117
The host hands the messages to the model in order, so the trailing `assistant` message becomes the start of its reply. `content` accepts the same union a tool result does: `text`, `image`, `audio`, `resource_link`, and `resource`.
118118

119+
## Add an image to a message
120+
121+
An `image` block carries base64 `data` and a `mimeType`; pair it with a `text` block that says what to do with the image.
122+
123+
```ts source="../../examples/guides/servers/prompts.examples.ts#registerPrompt_image"
124+
server.registerPrompt(
125+
'describe-image',
126+
{
127+
description: 'Describe an image for alt text',
128+
argsSchema: z.object({ imageBase64: z.string().describe('Base64-encoded PNG') })
129+
},
130+
({ imageBase64 }) => ({
131+
messages: [
132+
{
133+
role: 'user' as const,
134+
content: { type: 'image' as const, data: imageBase64, mimeType: 'image/png' }
135+
},
136+
{
137+
role: 'user' as const,
138+
content: { type: 'text' as const, text: 'Write one sentence of alt text for this image.' }
139+
}
140+
]
141+
})
142+
);
143+
```
144+
145+
`prompts/get` returns the image block as the first message, bytes unchanged:
146+
147+
```
148+
{
149+
role: 'user',
150+
content: {
151+
type: 'image',
152+
data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=',
153+
mimeType: 'image/png'
154+
}
155+
}
156+
```
157+
158+
`audio` takes the same shape: base64 `data` plus `mimeType`.
159+
119160
## Embed a resource in a message
120161

121162
`type: 'resource'` puts a resource's contents inside a message. Register the resource as usual — see [Resources](./resources.md) — and embed the same `uri`, `mimeType`, and `text` in the prompt.
@@ -201,5 +242,5 @@ The client sends `completion/complete` with the characters typed so far; the SDK
201242
- `argsSchema` is one Zod object: the advertised argument list, argument validation, and the callback's argument types.
202243
- Arguments that fail the schema reject `prompts/get` with a `-32602` protocol error; the callback never runs.
203244
- The callback returns `{ messages }`; each message names a `role` and one `content` block.
204-
- A message can embed a registered resource's contents with `type: 'resource'`.
245+
- A message can carry an `image` (base64 `data` plus `mimeType`) or embed a registered resource's contents with `type: 'resource'`.
205246
- `completable()` adds per-argument autocompletion.

docs/servers/tools.md

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -129,6 +129,69 @@ Calling `product-details` with `{ name: 'Travel mug' }` returns both renderings:
129129

130130
The wire encoding of structured results differs by protocol era — see [Protocol versions](../protocol-versions.md).
131131

132+
## Return other content types
133+
134+
One result can mix content blocks: `image` and `audio` carry base64 `data` with a `mimeType`; `resource` embeds a resource's contents inline; `resource_link` names a resource by `uri` without its bytes.
135+
136+
```ts source="../../examples/guides/servers/tools.examples.ts#registerTool_contentTypes"
137+
// Base64 payloads; read yours from disk: readFileSync('card.png').toString('base64')
138+
const cardPng = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
139+
const spokenNameWav = 'UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA=';
140+
141+
server.registerTool(
142+
'product-card',
143+
{
144+
description: 'Render one product as an image, a spoken name, and its catalog record',
145+
inputSchema: z.object({ name: z.string() })
146+
},
147+
async ({ name }) => {
148+
const product = catalog.find(candidate => candidate.name === name);
149+
if (!product) throw new Error(`No product named ${name}`);
150+
return {
151+
content: [
152+
{ type: 'image', data: cardPng, mimeType: 'image/png' },
153+
{ type: 'audio', data: spokenNameWav, mimeType: 'audio/wav' },
154+
{
155+
type: 'resource',
156+
resource: {
157+
uri: `catalog://products/${encodeURIComponent(product.name)}`,
158+
mimeType: 'application/json',
159+
text: JSON.stringify(product)
160+
}
161+
}
162+
]
163+
};
164+
}
165+
);
166+
```
167+
168+
Calling `product-card` with `{ name: 'Travel mug' }` returns the three blocks as written:
169+
170+
```
171+
[
172+
{
173+
type: 'image',
174+
data: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=',
175+
mimeType: 'image/png'
176+
},
177+
{
178+
type: 'audio',
179+
data: 'UklGRiQAAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQAAAAA=',
180+
mimeType: 'audio/wav'
181+
},
182+
{
183+
type: 'resource',
184+
resource: {
185+
uri: 'catalog://products/Travel%20mug',
186+
mimeType: 'application/json',
187+
text: '{"name":"Travel mug","price":24}'
188+
}
189+
}
190+
]
191+
```
192+
193+
The blocks reach the client exactly as returned, and the embedded `resource` arrives without a `resources/read` round trip.
194+
132195
## Annotate the tool
133196

134197
`title` is the display name; `annotations` are behavior hints for the client.
@@ -156,4 +219,5 @@ A tool that takes no arguments omits `inputSchema`. Annotations never change how
156219
- The one schema yields the advertised JSON Schema, argument validation, and the handler's argument types.
157220
- Arguments that fail the schema come back as an `isError: true` tool result; the handler never runs.
158221
- `outputSchema` plus `structuredContent` add machine-readable results, validated before they leave the server.
222+
- `content` blocks are `text`, `image`, `audio`, `resource_link`, or an embedded `resource`; one result can mix them.
159223
- `title` and `annotations` describe the tool to clients and never change execution.

docs/serving/legacy-clients.md

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,12 +91,45 @@ Behind an Express body parser the Node stream is already drained: build the `Req
9191

9292
The v2 server never serves the HTTP+SSE transport. An SSE server moving to v2 moves to Streamable HTTP — `createMcpHandler` above — as part of the [v2 upgrade](../migration/upgrade-to-v2.md).
9393

94-
The client side keeps `SSEClientTransport`, so a v2 `Client` still reaches old SSE servers. For a server deployment that cannot move yet, a frozen v1 copy of the transport ships as `@modelcontextprotocol/server-legacy/sse` (deprecated).
94+
The client side keeps `SSEClientTransport`, so a v2 `Client` still reaches old SSE servers. For a server deployment that cannot move yet, a frozen v1 copy of the transport ships as `@modelcontextprotocol/server-legacy/sse` (deprecated, planned for removal in v3).
95+
96+
Mount the frozen transport on two Express routes: `GET /sse` opens the stream and `POST /messages` delivers each client message to the session its `sessionId` query names. `createMcpExpressApp` takes the same options as on the [Express](./express.md) page: binding beyond localhost drops the default `Host`/`Origin` validation, so name the hosts you serve in `allowedHosts`, and raise `jsonLimit` above Express's 100kb default, since the SSE transport itself accepts messages up to 4mb.
97+
98+
```ts source="../../examples/guides/serving/legacy-clients.examples.ts#SSEServerTransport_express"
99+
import { createMcpExpressApp } from '@modelcontextprotocol/express';
100+
import { SSEServerTransport } from '@modelcontextprotocol/server-legacy/sse';
101+
102+
const sessions = new Map<string, SSEServerTransport>();
103+
const sseApp = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['sse.example.com'], jsonLimit: '4mb' });
104+
105+
sseApp.get('/sse', async (_req, res) => {
106+
const transport = new SSEServerTransport('/messages', res);
107+
sessions.set(transport.sessionId, transport);
108+
transport.onclose = () => sessions.delete(transport.sessionId);
109+
await buildServer().connect(transport);
110+
});
111+
112+
sseApp.post('/messages', async (req, res) => {
113+
const sessionId = req.query.sessionId;
114+
if (typeof sessionId !== 'string') {
115+
res.status(400).send('Missing sessionId parameter');
116+
return;
117+
}
118+
const transport = sessions.get(sessionId);
119+
if (!transport) {
120+
res.status(404).send('Session not found');
121+
return;
122+
}
123+
await transport.handlePostMessage(req, res, req.body);
124+
});
125+
```
126+
127+
Each `GET /sse` connects a fresh instance from `buildServer` and answers with an `endpoint` event naming `/messages?sessionId=…`; the client POSTs every JSON-RPC message there and reads responses off the stream.
95128

96129
## Recap
97130

98131
- Both entry points serve 2025-era clients from the same factory by default; `legacy: 'reject'` makes an endpoint modern-only.
99132
- The default HTTP posture is per request and stateless: legacy `GET` and `DELETE` session operations answer `405`.
100133
- `serveStdio` decides the era once per connection; its default is `'serve'`.
101134
- `isLegacyRequest` in front of a strict handler keeps an existing sessionful 2025 deployment serving its clients.
102-
- The v2 server never serves SSE; the frozen v1 transport is `@modelcontextprotocol/server-legacy/sse`, and the client keeps `SSEClientTransport`.
135+
- The v2 server never serves SSE; the frozen v1 `SSEServerTransport` in `@modelcontextprotocol/server-legacy/sse` mounts on `GET /sse` + `POST /messages`, and the client keeps `SSEClientTransport`.

examples/guides/clients/calling.examples.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,5 +201,14 @@ const exported = await client.callTool(
201201
console.log(exported.content);
202202
//#endregion callTool_progress
203203

204+
// "Check the connection" — the empty result the page quotes.
205+
//#region ping_basic
206+
const pong = await client.ping({ timeout: 5000 });
207+
console.log(pong);
208+
//#endregion ping_basic
209+
if (Object.keys(pong).length !== 0) {
210+
throw new Error(`calling.md claim failed: ping resolved with ${JSON.stringify(pong)}`);
211+
}
212+
204213
await client.close();
205214
await server.close();

examples/guides/servers/elicitation.examples.ts

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,37 @@ server.registerTool(
7878
);
7979
//#endregion registerTool_elicitActions
8080

81+
// "Prefill a field with a default" — the requested schema carries `default`.
82+
// Wrapped so the harness can register the same tool on a second server whose
83+
// client declares `applyDefaults`; the page's fence shows the body unindented.
84+
function registerExportReport(server: McpServer): void {
85+
//#region registerTool_elicitDefault
86+
server.registerTool(
87+
'export-report',
88+
{
89+
description: 'Export a report after the user picks a format',
90+
inputSchema: z.object({ name: z.string() })
91+
},
92+
async ({ name }, ctx) => {
93+
const result = await ctx.mcpReq.elicitInput({
94+
mode: 'form',
95+
message: `Export ${name} as which format?`,
96+
requestedSchema: {
97+
type: 'object',
98+
properties: { format: { type: 'string', title: 'Format', enum: ['pdf', 'csv'], default: 'pdf' } },
99+
required: ['format']
100+
}
101+
});
102+
if (result.action !== 'accept') {
103+
return { content: [{ type: 'text', text: `Export ${result.action}.` }] };
104+
}
105+
return { content: [{ type: 'text', text: `Exported ${name} as ${result.content?.format}.` }] };
106+
}
107+
);
108+
//#endregion registerTool_elicitDefault
109+
}
110+
registerExportReport(server);
111+
81112
// "Send the end user to a URL" — url mode hands the browser flow to the client.
82113
//#region registerTool_elicitUrl
83114
server.registerTool(
@@ -144,6 +175,28 @@ client.setRequestHandler('elicitation/create', async () => ({ action: 'decline'
144175
const declined = await client.callTool({ name: 'delete-dataset', arguments: { name: 'staging-snapshots' } });
145176
console.log(declined.content);
146177

178+
// "Prefill a field with a default" — a client that declares `applyDefaults`
179+
// accepts with `format` left out; the SDK fills it from the schema before the
180+
// accept reaches the handler.
181+
const defaultsClient = new Client(
182+
{ name: 'defaults-host', version: '1.0.0' },
183+
{ capabilities: { elicitation: { form: { applyDefaults: true } } } }
184+
);
185+
defaultsClient.setRequestHandler('elicitation/create', async () => ({ action: 'accept', content: {} }));
186+
const [defaultsClientTransport, defaultsServerTransport] = InMemoryTransport.createLinkedPair();
187+
const defaultsServer = new McpServer({ name: 'feedback', version: '1.0.0' });
188+
registerExportReport(defaultsServer);
189+
await defaultsServer.connect(defaultsServerTransport);
190+
await defaultsClient.connect(defaultsClientTransport);
191+
const exported = await defaultsClient.callTool({ name: 'export-report', arguments: { name: 'quarterly-sales' } });
192+
console.log(exported.content);
193+
const exportedText = Array.isArray(exported.content) && exported.content[0]?.type === 'text' ? exported.content[0].text : undefined;
194+
if (exported.isError || exportedText !== 'Exported quarterly-sales as pdf.') {
195+
throw new Error(`elicitation.md claim failed: applyDefaults round returned ${JSON.stringify(exported.content)}`);
196+
}
197+
await defaultsClient.close();
198+
await defaultsServer.close();
199+
147200
// "Require the elicitation capability" — the same form tool served to a client
148201
// that never declared the elicitation capability. elicitInput throws before
149202
// anything reaches the wire and the message becomes the tool result.

0 commit comments

Comments
 (0)