Skip to content

Commit 5ee54ee

Browse files
authored
feat(server): send structuredContent as JSON text when a tool omits content (#3153)
1 parent 600f69d commit 5ee54ee

10 files changed

Lines changed: 213 additions & 53 deletions

File tree

‎.changeset/register-tool-output-typing.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
'@modelcontextprotocol/server': minor
33
---
44

5-
`McpServer.registerTool` now type-checks a callback's successful result against the tool's `outputSchema`, for Standard Schema and deprecated raw-shape schemas. A successful result must include `structuredContent` that matches the schema and is not `undefined`; `isError: true` results, input-required results and tools without an `outputSchema` are unchanged. Runtime output validation is unchanged.
5+
`McpServer.registerTool` now type-checks a callback's successful result against the tool's `outputSchema`, for Standard Schema and deprecated raw-shape schemas. A successful result must include `structuredContent` that matches the schema and is not `undefined`; `isError: true` results, input-required results, tools without an `outputSchema`, and tools whose schema has an `unknown` output type (such as an untyped `fromJsonSchema(...)`) are unchanged. Runtime output validation is unchanged.
66

77
New exported types: `ToolResultFor`, `ToolStructuredContent`, `ToolResultWithStructuredContent`, `ToolErrorResult`. `ToolCallback` takes an optional second type parameter for the output schema.
88

9-
Code that compiled before can now fail to compile, for a tool with an `outputSchema`, when the callback:
9+
Code that compiled before can now fail to compile, for a tool with a typed `outputSchema`, when the callback:
1010

1111
- returns `structuredContent` that does not match the schema, or a successful result without it;
1212
- builds the value from a wider type than the schema (e.g. `string` for an enum);
1313
- has its result typed as plain `CallToolResult` (a `Promise<CallToolResult>` annotation, a helper returning `CallToolResult`, or `ToolCallback<typeof inputSchema>`); use `ToolCallback<typeof inputSchema, typeof outputSchema>` or drop the annotation;
14-
- is registered with an `outputSchema` typed `S | undefined`, which is checked as if present.
14+
- is registered with a typed `outputSchema` that may be `undefined`, which is checked as if present.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@modelcontextprotocol/server': minor
3+
---
4+
5+
A `McpServer` tool result with `structuredContent` and no `content` now gets a text block holding the serialized JSON of `structuredContent`, as the tools spec recommends, instead of `content: []`. This applies to every tool result, with or without an `outputSchema` or `isError`. A result that supplies `content`, even an empty array, is handled as before. To match, successful results of a tool with a typed `outputSchema` may omit `content` in TypeScript, both in `registerTool` and in `RegisteredTool.update({ callback })`.

‎docs/servers/tools.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,12 +116,14 @@ server.registerTool(
116116
);
117117
```
118118

119-
TypeScript checks the callback against `outputSchema`: in this example, returning a string, leaving out `price`, or returning `price: '24'` is a compile error, and so is a successful result with no `structuredContent`. Results with `isError: true` and [input-required results](input-required.md) are exempt. `structuredContent: undefined` counts as missing; `null` is fine when the schema allows it.
119+
TypeScript checks the callback against `outputSchema`: in this example, returning a string, leaving out `price`, or returning `price: '24'` is a compile error, and so is a successful result with no `structuredContent`. Results with `isError: true` and [input-required results](input-required.md) are exempt. `structuredContent: undefined` counts as missing; `null` is fine when the schema allows it. A schema with no static output type, such as an untyped `fromJsonSchema(...)`, is not checked at compile time.
120120

121121
The SDK validates the value you return and sends it as is, without the parsed result. So the type TypeScript asks for is one that satisfies both the input and the output side of the schema: fields with a `.default()` must be supplied, coerced fields must already have the output type, and a `.transform()` whose output is not a valid input cannot be satisfied at all. Values built from wider types, such as a `string` that should be one of an enum's members, need narrowing or a `satisfies` annotation before you return them.
122122

123123
The SDK also validates `structuredContent` against `outputSchema` at runtime before the result leaves your server, and advertises the derived JSON Schema in `tools/list` so clients can validate it too. The runtime check is still the one that counts: it covers JavaScript callers, values cast with `as`, and constraints TypeScript cannot express, such as `.min()`, `.email()` or `.refine()`.
124124

125+
With a typed `outputSchema` you may leave out `content`; the server then sends the JSON of `structuredContent` as a single text block, so clients that ignore `structuredContent` still see the result. Supply your own `content` to control that text.
126+
125127
Calling `product-details` with `{ name: 'Travel mug' }` returns both renderings:
126128

127129
```

‎packages/server/src/server/mcp.ts‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
ResourceNotFoundError,
4343
scanXMcpHeaderDeclarations,
4444
standardSchemaToJsonSchema,
45+
TOOL_RESULT_FOREIGN_FAMILY_KEYS,
4546
UriTemplate,
4647
validateAndWarnToolName,
4748
validateStandardSchema
@@ -342,12 +343,13 @@ export class McpServer {
342343
const result = await this.executeToolHandler(tool, args, ctx);
343344
await this.validateToolOutput(tool, result, request.params.name);
344345
if (isInputRequiredResult(result)) return result;
346+
const completed = withStructuredContentText(result);
345347
// SEP-2106 result-side projection (the era-agnostic TextContent auto-append; the
346348
// `{result:…}` wrap on the 2025 era) lives behind the wire codec's
347349
// `projectCallToolResult`. The codec receives the SAME advertised JSON Schema
348350
// `tools/list` emits (and that the codec's `encodeResult('tools/list', …)` may have
349351
// wrapped) so the listing and the call cannot diverge.
350-
return this.server.projectCallToolResult(result, tool.outputSchemaJson);
352+
return this.server.projectCallToolResult(completed, tool.outputSchemaJson);
351353
} catch (error) {
352354
if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {
353355
throw error; // Return the error to the caller without wrapping in CallToolResult
@@ -1035,8 +1037,8 @@ export class McpServer {
10351037
needsExecutorRegen = true;
10361038
}
10371039
if (updates.callback !== undefined) {
1038-
registeredTool.handler = updates.callback;
10391040
currentHandler = updates.callback as AnyToolHandler<StandardSchemaWithJSON | undefined>;
1041+
registeredTool.handler = currentHandler;
10401042
needsExecutorRegen = true;
10411043
}
10421044
if (needsExecutorRegen) {
@@ -1374,6 +1376,18 @@ export class ResourceTemplate {
13741376
}
13751377
}
13761378

1379+
// Mirrors `structuredContent` as JSON text when a tool result omits `content`; other result families are left to fail validation.
1380+
function withStructuredContentText(result: CallToolResult): CallToolResult {
1381+
if (
1382+
(result as { content?: unknown }).content !== undefined ||
1383+
result.structuredContent === undefined ||
1384+
TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key => key in result)
1385+
) {
1386+
return result;
1387+
}
1388+
return { ...result, content: [{ type: 'text', text: JSON.stringify(result.structuredContent) }] };
1389+
}
1390+
13771391
/**
13781392
* A plain record of Zod field schemas, e.g. `{ name: z.string() }`. Accepted by
13791393
* `registerTool`/`registerPrompt` as a shorthand; auto-wrapped with `z.object()`.
@@ -1394,9 +1408,9 @@ export type InferRawShape<S extends ZodRawShape> = z.infer<z.ZodObject<S>>;
13941408
* the intersection of input and output otherwise — so a transforming schema whose output is not
13951409
* a valid input cannot be satisfied by accident. `undefined` is excluded because the runtime
13961410
* treats `structuredContent: undefined` as absent; `null` is kept when the schema allows it.
1397-
* When the schema's output type is `unknown` (an untyped `fromJsonSchema(...)`, `z.unknown()`),
1398-
* any value is accepted, so forwarded `unknown` values type-check; the key is still required.
13991411
* A branded output (Zod `.brand()`) requires a branded value, as brands are meant to.
1412+
* For a schema whose output type is `unknown` this is `unknown`, and `registerTool` does not
1413+
* check the result at compile time (see {@linkcode ToolResultFor}).
14001414
*
14011415
* @typeParam Output - the tool's `outputSchema`: a Standard Schema or a {@linkcode ZodRawShape}.
14021416
*/
@@ -1414,14 +1428,18 @@ export type ToolStructuredContent<Output extends StandardSchemaWithJSON | ZodRaw
14141428
: never;
14151429

14161430
/**
1417-
* The successful result of a tool that declares an `outputSchema`: `structuredContent` is
1431+
* The successful result of a tool that declares a typed `outputSchema`: `structuredContent` is
14181432
* required and typed by {@linkcode ToolStructuredContent}.
1433+
*
1434+
* `content` is optional here: when it is omitted, the server sends the JSON of
1435+
* `structuredContent` as a single text block. Supply your own `content` to control what
1436+
* clients that ignore `structuredContent` see.
14191437
*/
14201438
export type ToolResultWithStructuredContent<T> = {
14211439
// `Omit` would collapse CallToolResult's known keys into its index signature; key remapping keeps them.
14221440
[K in keyof CallToolResult as K extends 'content' | 'structuredContent' | 'isError' ? never : K]: CallToolResult[K];
14231441
} & {
1424-
content: CallToolResult['content'];
1442+
content?: CallToolResult['content'];
14251443
structuredContent: T;
14261444
isError?: false;
14271445
};
@@ -1432,19 +1450,22 @@ export type ToolErrorResult = CallToolResult & { isError: true };
14321450
/**
14331451
* Maps a tool's declared `outputSchema` to the {@link CallToolResult} its handler may return.
14341452
*
1435-
* With an `outputSchema`, a successful result must carry matching `structuredContent`
1453+
* With a typed `outputSchema`, a successful result must carry matching `structuredContent`
14361454
* ({@linkcode ToolResultWithStructuredContent}); `isError: true` results are unconstrained.
1437-
* Without one, any {@link CallToolResult} is allowed. A schema typed `S | undefined` also allows
1438-
* any result here, but `registerTool`'s optional `outputSchema` property drops the `undefined`
1439-
* when inferring, so a forwarded optional schema is checked as if present.
1455+
* Without one, or with one whose output type is `unknown` (such as an untyped
1456+
* `fromJsonSchema(...)`), any {@link CallToolResult} is allowed. A schema typed `S | undefined`
1457+
* also allows any result here, but `registerTool`'s optional `outputSchema` property drops the
1458+
* `undefined` when inferring, so a forwarded optional typed schema is checked as if present.
14401459
* Input-required results are added by {@linkcode ToolCallback} and are never constrained.
14411460
*
14421461
* @typeParam Output - the tool's `outputSchema`: a Standard Schema, a {@linkcode ZodRawShape}, or `undefined`.
14431462
*/
14441463
export type ToolResultFor<Output extends StandardSchemaWithJSON | ZodRawShape | undefined> = [Output] extends [
14451464
StandardSchemaWithJSON | ZodRawShape
14461465
]
1447-
? ToolResultWithStructuredContent<ToolStructuredContent<Output>> | ToolErrorResult
1466+
? unknown extends ToolStructuredContent<Output>
1467+
? CallToolResult
1468+
: ToolResultWithStructuredContent<ToolStructuredContent<Output>> | ToolErrorResult
14481469
: CallToolResult;
14491470

14501471
/** {@linkcode ToolCallback} variant used when `inputSchema` is a {@linkcode ZodRawShape}. */
@@ -1486,8 +1507,8 @@ export type BaseToolCallback<
14861507
/**
14871508
* Callback for a tool handler registered with {@linkcode McpServer.registerTool}.
14881509
*
1489-
* `registerTool` passes the tool's `outputSchema` as `Output`, so a successful result's
1490-
* `structuredContent` is checked against the schema at compile time (see {@linkcode ToolResultFor}).
1510+
* `registerTool` passes the tool's `outputSchema` as `Output`, so for a typed schema a successful
1511+
* result's `structuredContent` is checked at compile time (see {@linkcode ToolResultFor}).
14911512
* Runtime validation still runs and remains authoritative.
14921513
*/
14931514
export type ToolCallback<
@@ -1546,7 +1567,11 @@ export type RegisteredTool = {
15461567
icons?: Icon[];
15471568
scopeChallenge?: ScopeChallengeHandler | null;
15481569
_meta?: Record<string, unknown>;
1549-
callback?: ToolCallback<StandardSchemaWithJSON>;
1570+
callback?: BaseToolCallback<
1571+
CallToolResult | ToolResultWithStructuredContent<unknown> | InputRequiredResult,
1572+
ServerContext,
1573+
StandardSchemaWithJSON
1574+
>;
15501575
enabled?: boolean;
15511576
}): void;
15521577
remove(): void;

0 commit comments

Comments
 (0)