Skip to content

Commit be40c1e

Browse files
committed
feat: server and client extensions, request middleware (use), acceptResultType
ServerOptions.extensions and ClientOptions.extensions take extension objects ({ id, install }). Each is advertised under capabilities.extensions[id] and installed at construction; capability settings are registered inside install with registerCapabilities. Protocol.use(method, (request, ctx, next) => ...) is request middleware around the registered handler, Koa-shaped, composed at dispatch time in registration order. Method names are exact, no wildcard. Protocol.acceptResultType(method, resultType) lets a client extension receive its own result kind (the Tasks extension's resultType "task" on tools/call), validated against the caller's explicit result schema. McpServer tool dispatch re-throws MissingRequiredClientCapabilityError (-32021) as a JSON-RPC error instead of an isError tool result.
1 parent b022522 commit be40c1e

14 files changed

Lines changed: 741 additions & 3 deletions

File tree

‎.changeset/server-extensions.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@modelcontextprotocol/core-internal': minor
3+
'@modelcontextprotocol/client': minor
4+
'@modelcontextprotocol/server': minor
5+
---
6+
7+
Server and client extensions (experimental: the `extensions` option and the extension shapes may change in a minor release). `ServerOptions.extensions` takes `ServerExtension` objects (`{ id, install(server) }`): each is advertised under `capabilities.extensions[id]` and installed at construction; everything else an extension does, settings included, happens in `install`. Extensions register custom methods with `setRequestHandler(method, { params, result }, handler)` and intercept spec methods with the new `Protocol.use(method, (request, ctx, next) => …)` — middleware around the registered handler, composed at dispatch time in registration order (so middleware on `tools/call` applies even though `McpServer` registers that handler lazily); it returns a remover. `ClientOptions.extensions` takes the symmetric `ClientExtension` objects, advertised under the client's `capabilities.extensions[id]` (in `initialize` on a legacy connection, in every request's client-capabilities envelope on 2026-07-28) and installed with the `Client`. `Protocol.acceptResultType(method, resultType)` declares an extension result kind for a method: a raw response carrying that `resultType` bypasses the era codec's closed vocabulary and is validated against the caller's explicit result schema as-is, which is how a client extension receives shapes such as the Tasks extension's `resultType: "task"` on `tools/call`.
8+
9+
`McpServer` tool dispatch now re-throws `MissingRequiredClientCapabilityError` (`-32021`) as a JSON-RPC error instead of converting it into an `isError` tool result, matching the existing `UrlElicitationRequiredError` passthrough.

‎docs/.vitepress/nav.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ export const guideSidebar: DefaultTheme.SidebarItem[] = [
6666
items: [
6767
{ text: 'Low-level server', link: '/advanced/low-level-server' },
6868
{ text: 'Custom methods', link: '/advanced/custom-methods' },
69+
{ text: 'Server extensions', link: '/advanced/extensions' },
6970
{ text: 'Schema libraries', link: '/advanced/schema-libraries' },
7071
{ text: 'Custom transports', link: '/advanced/custom-transports' },
7172
{ text: 'Wire schemas', link: '/advanced/wire-schemas' },

‎docs/advanced/extensions.md‎

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
---
2+
shape: how-to
3+
---
4+
5+
# Server extensions
6+
7+
::: warning Experimental
8+
The `extensions` option and the `ServerExtension` and `ClientExtension` shapes are experimental and may change in a minor release.
9+
:::
10+
11+
A **server extension** packages protocol behaviour outside the core specification — an MCP extension such as `io.modelcontextprotocol/tasks`, or a vendor feature — as one object you pass to the server. The SDK advertises it, installs it, and gives it two hooks: custom methods and middleware on spec methods. What the extension does behind those hooks is its own business.
12+
13+
## Write an extension
14+
15+
An extension is an `id` and an `install` function that receives the low-level `Server`. Everything it does to the protocol happens in `install`.
16+
17+
```ts
18+
import type { ServerExtension } from '@modelcontextprotocol/server';
19+
import { MissingRequiredClientCapabilityError, CLIENT_CAPABILITIES_META_KEY } from '@modelcontextprotocol/server';
20+
import * as z from 'zod/v4';
21+
22+
const GATE = 'com.example/gate';
23+
24+
export const gate: ServerExtension = {
25+
id: GATE,
26+
install(server) {
27+
// Settings for the advertised capability, if the extension has any.
28+
server.registerCapabilities({ extensions: { [GATE]: { exampleData: true } } });
29+
30+
// A custom method, exactly as in Custom methods.
31+
server.setRequestHandler('gate/status', { params: z.looseObject({}) }, () => ({ armed: true }));
32+
33+
// Middleware on a spec method: runs around the registered handler,
34+
// may answer, transform, or refuse.
35+
server.use('tools/call', (request, ctx, next) => {
36+
const declared = ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY]?.extensions ?? {};
37+
if (!(GATE in declared)) {
38+
throw new MissingRequiredClientCapabilityError({ requiredCapabilities: { extensions: { [GATE]: {} } } }, 'declare the gate');
39+
}
40+
return next(request, ctx);
41+
});
42+
}
43+
};
44+
```
45+
46+
## Install it
47+
48+
Pass extensions at construction. Each is advertised under `capabilities.extensions[id]` as `{}` — legacy connections see it in the `initialize` result, 2026-07-28 connections in `server/discover` — and then installed in order, after the built-in handlers exist. An extension with settings registers them in `install`, as above; the maps merge.
49+
50+
```ts
51+
const server = new McpServer({ name: 'gated', version: '1.0.0' }, { extensions: [gate] });
52+
```
53+
54+
The same option exists on the low-level `Server`.
55+
56+
## Client extensions
57+
58+
The client half is symmetric: `ClientExtension` is `{ id, install(client) }`, passed in `ClientOptions.extensions`. The client advertises it under its own `capabilities.extensions[id]` — in `initialize` on a legacy connection, and in every request's `_meta` client-capabilities envelope on a 2026-07-28 connection, which is where a server extension reads it — and `install` receives the `Client` to register handlers for server-to-client requests and notifications, or wrap the ones the SDK installs with middleware.
59+
60+
```ts
61+
import type { ClientExtension } from '@modelcontextprotocol/client';
62+
63+
const gateClient: ClientExtension = {
64+
id: GATE,
65+
install(client) {
66+
client.setRequestHandler('gate/ping', { params: z.looseObject({}) }, () => ({ pong: true }));
67+
// Results of tools/call may carry the extension's own kind; the
68+
// explicit-schema request() path then hands them to the caller's
69+
// schema as-is instead of rejecting the unknown resultType.
70+
client.acceptResultType('tools/call', 'gate');
71+
}
72+
};
73+
74+
const client = new Client({ name: 'gated-client', version: '1.0.0' }, { extensions: [gateClient] });
75+
```
76+
77+
## How middleware composes
78+
79+
`setRequestHandler` is the route handler; `use(method, middleware)` is the middleware around it, Koa-shaped: `await next(request, ctx)` yields the result and the middleware returns what goes on the wire. It wraps whatever handler serves `method` at dispatch time. That matters for `tools/call`, which `McpServer` registers on the first tool registration: middleware installed at construction still applies. With no underlying handler, `next` throws `MethodNotFound`. Several middleware nest in registration order, the first installed outermost. The returned function removes the middleware. Method names are exact; there is no wildcard. Something every peer must know about the extension belongs in its advertised capability (`registerCapabilities`), not in per-request `_meta`. Where a result does carry extension `_meta`, the middleware adds its own namespaced key and the encoder still stamps the SDK's reserved keys and `resultType` on top.
80+
81+
A thrown `ProtocolError` becomes the JSON-RPC error response. Inside a tool handler, `McpServer` converts most throws into an `isError` tool result; the exceptions are protocol-level errors the client must see as errors — `UrlElicitationRequiredError` and `MissingRequiredClientCapabilityError` (`-32021`).
82+
83+
## Recap
84+
85+
- `ServerExtension` is `{ id, install(server) }`; pass it in `ServerOptions.extensions`. `ClientExtension` mirrors it on `ClientOptions.extensions`.
86+
- `install` gets the low-level `Server`: `setRequestHandler` for custom methods, `use` for middleware on spec methods, `registerCapabilities` for the extension's settings.
87+
- Middleware composes at dispatch time, in registration order, and applies to handlers registered later.
88+
- `acceptResultType(method, resultType)` lets a client extension receive a result kind outside `complete` / `input_required` through the explicit-schema `request()` path.
89+
- The SDK owns the hooks and the capability advertisement, not the extension's state or execution.

‎packages/client/src/client/client.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ import {
8080
SUPPORTED_MODERN_PROTOCOL_VERSIONS
8181
} from '@modelcontextprotocol/core-internal';
8282

83+
import type { ClientExtension } from './extension';
8384
import type { PriorDiscovery } from './probeClassifier';
8485
import type { CacheMode, CacheScope, ResponseCacheStore } from './responseCache';
8586
import { ClientResponseCache, InMemoryResponseCacheStore, MAX_CACHE_TTL_MS } from './responseCache';
@@ -181,6 +182,17 @@ export function getSupportedElicitationModes(capabilities: ClientCapabilities['e
181182
}
182183

183184
export type ClientOptions = ProtocolOptions & {
185+
/**
186+
* Extensions to install at construction. Each is advertised under
187+
* `capabilities.extensions[extension.id]` and then installed, in order —
188+
* see {@linkcode ClientExtension}.
189+
*
190+
* Experimental: the shape of an extension may change in a minor release.
191+
*
192+
* @experimental
193+
*/
194+
extensions?: ClientExtension[];
195+
184196
/**
185197
* Capabilities to advertise as being supported by this client.
186198
*/
@@ -658,6 +670,11 @@ export class Client extends Protocol<ClientContext> {
658670
if (options?.listChanged) {
659671
this._listChangedConfig = options.listChanged;
660672
}
673+
674+
for (const extension of options?.extensions ?? []) {
675+
this.registerCapabilities({ extensions: { [extension.id]: {} } });
676+
extension.install(this);
677+
}
661678
}
662679

663680
protected override buildContext(ctx: BaseContext, _transportInfo?: MessageExtraInfo): ClientContext {
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import type { Client } from './client';
2+
3+
/**
4+
* A client extension: the client half of protocol behaviour outside the
5+
* core specification (an MCP extension such as `io.modelcontextprotocol/tasks`,
6+
* or a vendor feature) that installs itself onto a {@linkcode Client}.
7+
*
8+
* Pass extensions at construction — `new Client(info, { extensions: [ext] })`.
9+
* The client advertises each extension under `capabilities.extensions[id]`
10+
* (as `{}`: supported, no settings)
11+
* (in `initialize` on a legacy connection, in every request's
12+
* `_meta` client-capabilities envelope on a 2026-07-28 connection) and then
13+
* calls `install`, which is where the extension registers handlers for
14+
* server-to-client requests and notifications, or wraps the ones the SDK
15+
* installs with middleware (`client.use('elicitation/create', …)`).
16+
* The SDK provides the hooks; what an extension does behind them is its own.
17+
*
18+
* Experimental: the shape of an extension may change in a minor release.
19+
*
20+
* @experimental
21+
*/
22+
export interface ClientExtension {
23+
/**
24+
* The extension identifier, prefix-qualified (`io.modelcontextprotocol/tasks`,
25+
* `com.example/feature-flags`). Advertised as the key under
26+
* `capabilities.extensions`. Settings for that key, if any, are the
27+
* extension's to register in `install` via `registerCapabilities`.
28+
*/
29+
readonly id: string;
30+
/** Installs the extension's handlers and middleware onto the client. Called once, at construction. */
31+
install(client: Client): void;
32+
}

‎packages/client/src/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ export {
6868
StaticPrivateKeyJwtProvider
6969
} from './client/authExtensions';
7070
export type { CacheableRequestOptions, CallToolRequestOptions, ClientOptions, ConnectOptions, McpSubscription } from './client/client';
71+
export type { ClientExtension } from './client/extension';
7172
export { Client } from './client/client';
7273
export { getSupportedElicitationModes } from './client/client';
7374
export type { DiscoverAndRequestJwtAuthGrantOptions, JwtAuthGrantResult, RequestJwtAuthGrantOptions } from './client/crossAppAccess';
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
/**
2+
* `ClientOptions.extensions`: an extension is advertised under the client's
3+
* `capabilities.extensions[id]` — in `initialize` on a legacy connection, in
4+
* every request's `_meta` client-capabilities envelope on a 2026-07-28
5+
* connection — and installed at construction, where it can register
6+
* handlers for server-to-client requests.
7+
*/
8+
import type { JSONRPCMessage } from '@modelcontextprotocol/core-internal';
9+
import { CLIENT_CAPABILITIES_META_KEY, InMemoryTransport, LATEST_PROTOCOL_VERSION } from '@modelcontextprotocol/core-internal';
10+
import { describe, expect, it } from 'vitest';
11+
import * as z from 'zod/v4';
12+
13+
import { Client } from '../../src/client/client';
14+
import type { ClientExtension } from '../../src/client/extension';
15+
16+
const MODERN = '2026-07-28';
17+
const EXT_ID = 'com.example/gate';
18+
19+
const flush = () => new Promise(resolve => setTimeout(resolve, 20));
20+
21+
function gateExtension(log: string[]): ClientExtension {
22+
return {
23+
id: EXT_ID,
24+
install(client) {
25+
log.push('installed');
26+
client.registerCapabilities({ extensions: { [EXT_ID]: { exampleData: true } } });
27+
client.setRequestHandler('gate/ping', { params: z.looseObject({}) }, () => ({ pong: true }));
28+
client.acceptResultType('tools/call', 'task');
29+
}
30+
};
31+
}
32+
33+
/** A scripted server side: answers the handshake for the requested era and records everything the client writes. */
34+
async function scriptedServer(era: 'modern' | 'legacy') {
35+
const [clientTx, serverTx] = InMemoryTransport.createLinkedPair();
36+
const written: JSONRPCMessage[] = [];
37+
serverTx.onmessage = message => {
38+
written.push(message);
39+
const request = message as { id?: number | string; method?: string };
40+
if (request.id === undefined) return;
41+
if (request.method === 'server/discover') {
42+
void serverTx.send(
43+
era === 'modern'
44+
? {
45+
jsonrpc: '2.0',
46+
id: request.id,
47+
result: {
48+
resultType: 'complete',
49+
supportedVersions: [MODERN],
50+
capabilities: { tools: {} },
51+
_meta: { 'io.modelcontextprotocol/serverInfo': { name: 'scripted', version: '1.0.0' } }
52+
}
53+
}
54+
: { jsonrpc: '2.0', id: request.id, error: { code: -32_601, message: 'Method not found' } }
55+
);
56+
} else if (request.method === 'initialize') {
57+
void serverTx.send({
58+
jsonrpc: '2.0',
59+
id: request.id,
60+
result: {
61+
protocolVersion: LATEST_PROTOCOL_VERSION,
62+
capabilities: { tools: {} },
63+
serverInfo: { name: 'scripted', version: '1.0.0' }
64+
}
65+
});
66+
} else if (request.method === 'tools/call') {
67+
void serverTx.send({
68+
jsonrpc: '2.0',
69+
id: request.id,
70+
result: { resultType: 'task', taskId: 't-1', status: 'working', createdAt: 'now', lastUpdatedAt: 'now', ttlMs: null }
71+
});
72+
} else if (request.method === 'tools/list') {
73+
void serverTx.send({
74+
jsonrpc: '2.0',
75+
id: request.id,
76+
result: era === 'modern' ? { resultType: 'complete', tools: [], ttlMs: 0, cacheScope: 'public' } : { tools: [] }
77+
});
78+
}
79+
};
80+
await serverTx.start();
81+
return { clientTx, serverTx, written };
82+
}
83+
84+
const paramsOf = (message: JSONRPCMessage): Record<string, unknown> => (message as { params?: Record<string, unknown> }).params ?? {};
85+
86+
describe('ClientOptions.extensions', () => {
87+
it('installs the extension at construction', () => {
88+
const log: string[] = [];
89+
new Client({ name: 'c', version: '1' }, { extensions: [gateExtension(log)] });
90+
expect(log).toEqual(['installed']);
91+
});
92+
93+
it('advertises {} when install sets no settings', async () => {
94+
const { clientTx, written } = await scriptedServer('legacy');
95+
const client = new Client({ name: 'c', version: '1' }, { extensions: [{ id: 'com.example/plain', install: () => {} }] });
96+
await client.connect(clientTx);
97+
const initialize = written.find(message => (message as { method?: string }).method === 'initialize');
98+
expect(paramsOf(initialize as JSONRPCMessage)['capabilities']).toMatchObject({ extensions: { 'com.example/plain': {} } });
99+
await client.close();
100+
});
101+
102+
it('sends the extension in initialize on a legacy connection', async () => {
103+
const { clientTx, written } = await scriptedServer('legacy');
104+
const client = new Client({ name: 'c', version: '1' }, { extensions: [gateExtension([])] });
105+
await client.connect(clientTx);
106+
const initialize = written.find(message => (message as { method?: string }).method === 'initialize');
107+
expect(paramsOf(initialize as JSONRPCMessage)['capabilities']).toMatchObject({ extensions: { [EXT_ID]: { exampleData: true } } });
108+
await client.close();
109+
});
110+
111+
it('stamps the extension into every request envelope on a 2026-07-28 connection', async () => {
112+
const { clientTx, written } = await scriptedServer('modern');
113+
const client = new Client({ name: 'c', version: '1' }, { versionNegotiation: { mode: 'auto' }, extensions: [gateExtension([])] });
114+
await client.connect(clientTx);
115+
await client.listTools();
116+
await flush();
117+
const toolsList = written.find(message => (message as { method?: string }).method === 'tools/list');
118+
const meta = paramsOf(toolsList as JSONRPCMessage)['_meta'] as Record<string, unknown>;
119+
expect(meta[CLIENT_CAPABILITIES_META_KEY]).toMatchObject({ extensions: { [EXT_ID]: { exampleData: true } } });
120+
await client.close();
121+
});
122+
123+
it('receives an extension result kind the extension accepted, discriminator included', async () => {
124+
const { clientTx } = await scriptedServer('modern');
125+
const client = new Client({ name: 'c', version: '1' }, { versionNegotiation: { mode: 'auto' }, extensions: [gateExtension([])] });
126+
await client.connect(clientTx);
127+
const taskSchema = z.looseObject({ resultType: z.literal('task'), taskId: z.string(), status: z.string() });
128+
const result = await client.request({ method: 'tools/call', params: { name: 'slow', arguments: {} } }, taskSchema);
129+
expect(result).toMatchObject({ resultType: 'task', taskId: 't-1', status: 'working' });
130+
// callTool validates against CallToolResultSchema, which a task handle does not satisfy.
131+
await expect(client.callTool({ name: 'slow', arguments: {} })).rejects.toThrow(/Invalid result for tools\/call/);
132+
await client.close();
133+
});
134+
135+
it('serves the handler the extension installed for a server-to-client request', async () => {
136+
const { clientTx, serverTx, written } = await scriptedServer('legacy');
137+
const client = new Client({ name: 'c', version: '1' }, { extensions: [gateExtension([])] });
138+
await client.connect(clientTx);
139+
await serverTx.send({ jsonrpc: '2.0', id: 'srv-1', method: 'gate/ping', params: {} });
140+
await flush();
141+
const response = written.find(message => 'id' in message && message.id === 'srv-1');
142+
expect((response as { result?: unknown }).result).toEqual({ pong: true });
143+
await client.close();
144+
});
145+
});

0 commit comments

Comments
 (0)