Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/tool-missing-client-capability.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@modelcontextprotocol/server': patch
---

On a 2026-07-28 request, a tool that throws `MissingRequiredClientCapabilityError` now answers `tools/call` with JSON-RPC error `-32021` and its `requiredCapabilities`, as that revision requires, instead of an `isError` tool result. This changes what such a tool returns for every `McpServer` on 2026-07-28: a client that read the message from the tool result now gets a `ProtocolError` with code `-32021`. On 2025-11-25, which does not define that code, the tool error is unchanged. Over HTTP the response status is 400, unless the response stream is already open. The same applies to a `-32021` a tool relays from a downstream server: catch and translate it instead of rethrowing, because its `requiredCapabilities` describe the downstream hop.
10 changes: 5 additions & 5 deletions docs/servers/errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ The model reads the message, sees `welcome` in it, and retries with an id that e

## Let a thrown exception become a tool error

Throw instead: the SDK catches anything a tool handler throws and converts it to the same `isError: true` shape.
Throw instead: the SDK catches what a tool handler throws and converts it to the same `isError: true` shape. The two exceptions reach the client as protocol errors: `UrlElicitationRequiredError` on 2025-11-25 and `MissingRequiredClientCapabilityError` on 2026-07-28 (see [Throw a protocol error](#throw-a-protocol-error)).

```ts source="../../examples/guides/servers/errors.examples.ts#registerTool_throw"
server.registerTool(
Expand Down Expand Up @@ -147,7 +147,7 @@ Pick by audience. The model drives `tools/call`, so a failure it can recover fro

The handler decides which channel exists:

- A tool handler produces only tool errors. The SDK converts every exception it throws — including a thrown `ProtocolError` — into an `isError: true` result. `UrlElicitationRequiredError` is the one exception; it propagates as a JSON-RPC error so the host can open the URL — see [Elicitation](./elicitation.md).
- A tool handler produces only tool errors. The SDK converts every exception it throws — including a thrown `ProtocolError` — into an `isError: true` result. `UrlElicitationRequiredError` and `MissingRequiredClientCapabilityError` are the two exceptions. On 2025-11-25 the first propagates as a JSON-RPC error so the host can open the URL — see [Elicitation](./elicitation.md); on 2026-07-28 the second tells the client which capability to declare.
- A resource, prompt, or completion callback produces only protocol errors. Throw a `ProtocolError`.

## Use the typed error subclasses
Expand Down Expand Up @@ -175,9 +175,9 @@ The error carries the requested URI in `data` and the code the spec mandates for

Three more subclasses cover the other structured protocol errors:

- `UrlElicitationRequiredError(elicitations)` — `-32042`; the only error a tool handler can propagate. See [Elicitation](./elicitation.md).
- `UrlElicitationRequiredError(elicitations)` — `-32042`; a tool handler can propagate it on 2025-11-25. On 2026-07-28 return `inputRequired.elicitUrl(...)` instead. See [Elicitation](./elicitation.md).
- `UnsupportedProtocolVersionError({ supported, requested })` — `-32022`; `data.supported` lets the peer pick a version and retry.
- `MissingRequiredClientCapabilityError({ requiredCapabilities })` — `-32021`; `data.requiredCapabilities` names exactly what the client must declare.
- `MissingRequiredClientCapabilityError({ requiredCapabilities })` — `-32021`; `data.requiredCapabilities` names exactly what the client must declare. A tool handler can propagate it on 2026-07-28, where over HTTP it is answered with status 400 unless the response stream is already open; on 2025-11-25 it becomes a tool error like any other throw.

Match these by `code` and `data` shape when peers may run pre-brand SDK copies or hand you plain wire shapes; on brand-aware releases `instanceof` also matches across separately bundled copies of the SDK. The same check is available as an explicit static guard — `ProtocolError.isInstance(err)`, `ResourceNotFoundError.isInstance(err)` — which narrows in TypeScript and reads the same brand.

Expand All @@ -203,7 +203,7 @@ Match these by `code` and `data` shape when peers may run pre-brand SDK copies o

- `isError: true` is a successful JSON-RPC result carrying a tool failure the model reads and acts on.
- A tool handler that throws produces the same `isError: true` result; the exception's `message` becomes the `content` text.
- A tool handler cannot produce a protocol error — only `UrlElicitationRequiredError` escapes.
- A tool handler cannot produce a protocol error — only `UrlElicitationRequiredError` (2025-11-25) and `MissingRequiredClientCapabilityError` (2026-07-28) escape.
- `ProtocolError` and its subclasses, thrown from resource, prompt, and completion callbacks, become JSON-RPC error responses the model never sees.
- `ResourceNotFoundError` and the other subclasses pick the code and pack structured `data`; match them by `code` and `data` — or, on brand-aware releases, by `instanceof`.
- The table above lists every `ProtocolErrorCode` member.
11 changes: 11 additions & 0 deletions packages/server/src/server/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
attachCacheHintFallback,
guardLogger,
isInputRequiredResult,
isModernProtocolVersion,
normalizeRawShapeSchema,
promptArgumentsFromStandardSchema,
ProtocolError,
Expand Down Expand Up @@ -354,6 +355,16 @@ export class McpServer {
if (error instanceof ProtocolError && error.code === ProtocolErrorCode.UrlElicitationRequired) {
throw error; // Return the error to the caller without wrapping in CallToolResult
}
// -32021 is defined from 2026-07-28; earlier revisions keep the tool error.
const version = this.server.getNegotiatedProtocolVersion();
if (
error instanceof ProtocolError &&
error.code === ProtocolErrorCode.MissingRequiredClientCapability &&
version !== undefined &&
isModernProtocolVersion(version)
) {
throw error;
}
return this.createToolError(error instanceof Error ? error.message : String(error));
}
});
Expand Down
23 changes: 23 additions & 0 deletions test/e2e/requirements.ts
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,22 @@ export const REQUIREMENTS: Record<string, Requirement> = {
source: 'sdk',
behavior: "Registering a tool whose name violates the spec's tool-naming conventions emits a warning; registration still succeeds."
},
'mcpserver:tool:missing-client-capability-error': {
source: 'https://modelcontextprotocol.io/specification/draft/basic#_meta',
behavior:
'On 2026-07-28, a tool that throws MissingRequiredClientCapabilityError answers tools/call with JSON-RPC error -32021 and its requiredCapabilities, not an isError tool result.',
transports: ['entryModern'],
addedInSpecVersion: '2026-07-28',
supersedes: ['typescript:mcpserver:tool:missing-client-capability-error:legacy'],
note: 'entryModern is the arm that serves 2026-07-28 requests.'
},
'typescript:mcpserver:tool:missing-client-capability-error:legacy': {
source: 'sdk',
behavior:
'On 2025-11-25, which does not define -32021, a tool that throws MissingRequiredClientCapabilityError answers with an isError tool result carrying the message, like any other throw.',
removedInSpecVersion: '2026-07-28',
supersededBy: 'mcpserver:tool:missing-client-capability-error'
},
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
'mcpserver:tool:url-elicitation-error': {
source: 'sdk',
behavior:
Expand Down Expand Up @@ -2808,6 +2824,13 @@ export const REQUIREMENTS: Record<string, Requirement> = {
transports: ['entryStateless', 'entryModern'],
note: 'Runs on the createMcpHandler entry arms; the malformed body is POSTed through wired.fetch so the HTTP status and JSON-RPC error code are observed directly.'
},
'typescript:hosting:entry:tool-missing-capability-400': {
source: 'https://modelcontextprotocol.io/specification/draft/basic#_meta',
behavior:
'A tool that throws MissingRequiredClientCapabilityError is answered HTTP 400 by a createMcpHandler endpoint on a 2026-07-28 request, with the -32021 JSON-RPC error and its requiredCapabilities as the body.',
transports: ['entryModern'],
note: 'The spec ties the 400 to the 2026-07-28 error; the status is read through wired.fetch. A response whose stream is already open keeps its 200 and carries the error in-stream.'
},
'typescript:hosting:entry:legacy-accept-406': {
source: 'sdk',
behavior:
Expand Down
43 changes: 42 additions & 1 deletion test/e2e/scenarios/hosting-entry-http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
*/
import { Client } from '@modelcontextprotocol/client';
import type { McpRequestContext } from '@modelcontextprotocol/server';
import { McpServer } from '@modelcontextprotocol/server';
import { McpServer, MissingRequiredClientCapabilityError } from '@modelcontextprotocol/server';
import { expect } from 'vitest';
import { z } from 'zod/v4';

Expand Down Expand Up @@ -154,3 +154,44 @@ verifies('typescript:hosting:entry:no-session-id', async ({ transport }: TestArg
expect(exchange.response.headers.get('mcp-session-id')).toBeNull();
}
});

verifies('typescript:hosting:entry:tool-missing-capability-400', async ({ transport }: TestArgs) => {
const required = { extensions: { 'com.example/gate': {} } };
const factory = () => {
const server = new McpServer({ name: 'e2e-entry-gated', version: '1.0.0' });
server.registerTool('gated', { inputSchema: z.object({}) }, () => {
throw new MissingRequiredClientCapabilityError({ requiredCapabilities: required }, 'declare com.example/gate');
});
return server;
};
const client = new Client({ name: 'gated-client', version: '1.0.0' });
await using wired = await wire(transport, factory, client);

const response = await wired.fetch!(wired.url!, {
method: 'POST',
headers: {
'content-type': 'application/json',
accept: 'application/json, text/event-stream',
'mcp-protocol-version': '2026-07-28',
'mcp-method': 'tools/call',
'mcp-name': 'gated'
},
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'tools/call',
params: {
name: 'gated',
arguments: {},
_meta: {
'io.modelcontextprotocol/protocolVersion': '2026-07-28',
'io.modelcontextprotocol/clientInfo': { name: 'gated-client', version: '1.0.0' },
'io.modelcontextprotocol/clientCapabilities': {}
}
}
})
});
expect(response.status).toBe(400);
const body = (await response.json()) as { error: { code: number; data: unknown } };
expect(body.error).toMatchObject({ code: -32_021, data: { requiredCapabilities: required } });
});
33 changes: 33 additions & 0 deletions test/e2e/scenarios/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import type {
import {
isJSONRPCRequest,
McpServer,
MissingRequiredClientCapabilityError,
ProtocolError,
ProtocolErrorCode,
Server,
Expand Down Expand Up @@ -1362,3 +1363,35 @@ verifies('mcpserver:tool:metadata-roundtrip', async ({ transport }: TestArgs) =>
expect(tool.annotations).toEqual(annotations);
expect(tool._meta).toEqual(meta);
});

const gatedFactory = () => {
const s = new McpServer({ name: 's', version: '0' });
s.registerTool('gated', { inputSchema: z.object({}) }, () => {
throw new MissingRequiredClientCapabilityError(
{ requiredCapabilities: { extensions: { 'com.example/gate': {} } } },
'declare com.example/gate'
);
});
return s;
};

verifies('mcpserver:tool:missing-client-capability-error', async ({ transport }: TestArgs) => {
const client = newClient();
await using _ = await wire(transport, gatedFactory, client);

const err = await client.callTool({ name: 'gated', arguments: {} }).catch((error: unknown) => error);
expect(err).toBeInstanceOf(ProtocolError);
expect(err).toMatchObject({
code: ProtocolErrorCode.MissingRequiredClientCapability,
data: { requiredCapabilities: { extensions: { 'com.example/gate': {} } } }
});
});

verifies('typescript:mcpserver:tool:missing-client-capability-error:legacy', async ({ transport }: TestArgs) => {
const client = newClient();
await using _ = await wire(transport, gatedFactory, client);

const result = await client.callTool({ name: 'gated', arguments: {} });
expect(result.isError).toBe(true);
expect(result.content).toEqual([{ type: 'text', text: 'declare com.example/gate' }]);
});
Loading