Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions .changeset/register-tool-output-typing.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
'@modelcontextprotocol/server': minor
---

`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.
`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.

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

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

- returns `structuredContent` that does not match the schema, or a successful result without it;
- builds the value from a wider type than the schema (e.g. `string` for an enum);
- 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;
- is registered with an `outputSchema` typed `S | undefined`, which is checked as if present.
- is registered with a typed `outputSchema` that may be `undefined`, which is checked as if present.
5 changes: 5 additions & 0 deletions .changeset/tool-structured-content-text.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/server': minor
---

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 })`.
4 changes: 3 additions & 1 deletion docs/servers/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,14 @@ server.registerTool(
);
```

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.
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.

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.

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()`.

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.

Calling `product-details` with `{ name: 'Travel mug' }` returns both renderings:

```
Expand Down
53 changes: 39 additions & 14 deletions packages/server/src/server/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ import {
ResourceNotFoundError,
scanXMcpHeaderDeclarations,
standardSchemaToJsonSchema,
TOOL_RESULT_FOREIGN_FAMILY_KEYS,
UriTemplate,
validateAndWarnToolName,
validateStandardSchema
Expand Down Expand Up @@ -342,12 +343,13 @@ export class McpServer {
const result = await this.executeToolHandler(tool, args, ctx);
await this.validateToolOutput(tool, result, request.params.name);
if (isInputRequiredResult(result)) return result;
const completed = withStructuredContentText(result);
// SEP-2106 result-side projection (the era-agnostic TextContent auto-append; the
// `{result:…}` wrap on the 2025 era) lives behind the wire codec's
// `projectCallToolResult`. The codec receives the SAME advertised JSON Schema
// `tools/list` emits (and that the codec's `encodeResult('tools/list', …)` may have
// wrapped) so the listing and the call cannot diverge.
return this.server.projectCallToolResult(result, tool.outputSchemaJson);
return this.server.projectCallToolResult(completed, tool.outputSchemaJson);
} catch (error) {
if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {
throw error; // Return the error to the caller without wrapping in CallToolResult
Expand Down Expand Up @@ -1035,8 +1037,8 @@ export class McpServer {
needsExecutorRegen = true;
}
if (updates.callback !== undefined) {
registeredTool.handler = updates.callback;
currentHandler = updates.callback as AnyToolHandler<StandardSchemaWithJSON | undefined>;
registeredTool.handler = currentHandler;
needsExecutorRegen = true;
}
if (needsExecutorRegen) {
Expand Down Expand Up @@ -1374,6 +1376,18 @@ export class ResourceTemplate {
}
}

// Mirrors `structuredContent` as JSON text when a tool result omits `content`; other result families are left to fail validation.
function withStructuredContentText(result: CallToolResult): CallToolResult {
if (
(result as { content?: unknown }).content !== undefined ||
result.structuredContent === undefined ||
TOOL_RESULT_FOREIGN_FAMILY_KEYS.some(key => key in result)
) {
return result;
}
return { ...result, content: [{ type: 'text', text: JSON.stringify(result.structuredContent) }] };
}

/**
* A plain record of Zod field schemas, e.g. `{ name: z.string() }`. Accepted by
* `registerTool`/`registerPrompt` as a shorthand; auto-wrapped with `z.object()`.
Expand All @@ -1394,9 +1408,9 @@ export type InferRawShape<S extends ZodRawShape> = z.infer<z.ZodObject<S>>;
* the intersection of input and output otherwise — so a transforming schema whose output is not
* a valid input cannot be satisfied by accident. `undefined` is excluded because the runtime
* treats `structuredContent: undefined` as absent; `null` is kept when the schema allows it.
* When the schema's output type is `unknown` (an untyped `fromJsonSchema(...)`, `z.unknown()`),
* any value is accepted, so forwarded `unknown` values type-check; the key is still required.
* A branded output (Zod `.brand()`) requires a branded value, as brands are meant to.
* For a schema whose output type is `unknown` this is `unknown`, and `registerTool` does not
* check the result at compile time (see {@linkcode ToolResultFor}).
*
* @typeParam Output - the tool's `outputSchema`: a Standard Schema or a {@linkcode ZodRawShape}.
*/
Expand All @@ -1414,14 +1428,18 @@ export type ToolStructuredContent<Output extends StandardSchemaWithJSON | ZodRaw
: never;

/**
* The successful result of a tool that declares an `outputSchema`: `structuredContent` is
* The successful result of a tool that declares a typed `outputSchema`: `structuredContent` is
* required and typed by {@linkcode ToolStructuredContent}.
*
* `content` is optional here: when it is omitted, the server sends the JSON of
* `structuredContent` as a single text block. Supply your own `content` to control what
* clients that ignore `structuredContent` see.
*/
export type ToolResultWithStructuredContent<T> = {
// `Omit` would collapse CallToolResult's known keys into its index signature; key remapping keeps them.
[K in keyof CallToolResult as K extends 'content' | 'structuredContent' | 'isError' ? never : K]: CallToolResult[K];
} & {
content: CallToolResult['content'];
content?: CallToolResult['content'];
Comment thread
mattzcarey marked this conversation as resolved.
Resolved
structuredContent: T;
isError?: false;
};
Expand All @@ -1432,19 +1450,22 @@ export type ToolErrorResult = CallToolResult & { isError: true };
/**
* Maps a tool's declared `outputSchema` to the {@link CallToolResult} its handler may return.
*
* With an `outputSchema`, a successful result must carry matching `structuredContent`
* With a typed `outputSchema`, a successful result must carry matching `structuredContent`
* ({@linkcode ToolResultWithStructuredContent}); `isError: true` results are unconstrained.
* Without one, any {@link CallToolResult} is allowed. A schema typed `S | undefined` also allows
* any result here, but `registerTool`'s optional `outputSchema` property drops the `undefined`
* when inferring, so a forwarded optional schema is checked as if present.
* Without one, or with one whose output type is `unknown` (such as an untyped
* `fromJsonSchema(...)`), any {@link CallToolResult} is allowed. A schema typed `S | undefined`
* also allows any result here, but `registerTool`'s optional `outputSchema` property drops the
* `undefined` when inferring, so a forwarded optional typed schema is checked as if present.
* Input-required results are added by {@linkcode ToolCallback} and are never constrained.
*
* @typeParam Output - the tool's `outputSchema`: a Standard Schema, a {@linkcode ZodRawShape}, or `undefined`.
*/
export type ToolResultFor<Output extends StandardSchemaWithJSON | ZodRawShape | undefined> = [Output] extends [
StandardSchemaWithJSON | ZodRawShape
]
? ToolResultWithStructuredContent<ToolStructuredContent<Output>> | ToolErrorResult
? unknown extends ToolStructuredContent<Output>
? CallToolResult
Comment thread
mattzcarey marked this conversation as resolved.
Resolved
: ToolResultWithStructuredContent<ToolStructuredContent<Output>> | ToolErrorResult
: CallToolResult;

/** {@linkcode ToolCallback} variant used when `inputSchema` is a {@linkcode ZodRawShape}. */
Expand Down Expand Up @@ -1486,8 +1507,8 @@ export type BaseToolCallback<
/**
* Callback for a tool handler registered with {@linkcode McpServer.registerTool}.
*
* `registerTool` passes the tool's `outputSchema` as `Output`, so a successful result's
* `structuredContent` is checked against the schema at compile time (see {@linkcode ToolResultFor}).
* `registerTool` passes the tool's `outputSchema` as `Output`, so for a typed schema a successful
* result's `structuredContent` is checked at compile time (see {@linkcode ToolResultFor}).
* Runtime validation still runs and remains authoritative.
*/
export type ToolCallback<
Expand Down Expand Up @@ -1546,7 +1567,11 @@ export type RegisteredTool = {
icons?: Icon[];
scopeChallenge?: ScopeChallengeHandler | null;
_meta?: Record<string, unknown>;
callback?: ToolCallback<StandardSchemaWithJSON>;
callback?: BaseToolCallback<
CallToolResult | ToolResultWithStructuredContent<unknown> | InputRequiredResult,
ServerContext,
StandardSchemaWithJSON
>;
enabled?: boolean;
}): void;
remove(): void;
Expand Down
Loading
Loading