Skip to content

Commit 96868ae

Browse files
committed
feat: server and client extensions (install and attach), request middleware (use), acceptResultType
1 parent a7da98d commit 96868ae

14 files changed

Lines changed: 940 additions & 4 deletions

File tree

‎.changeset/server-extensions.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
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, the extension shapes, `use` and `acceptResultType` may change in a minor release). `ServerOptions.extensions` and `McpServerOptions.extensions` take `ServerExtension` objects, `{ id, install?(server), attach?(mcp) }`. `install` receives the low-level `Server` and registers custom methods, middleware and capability settings. `attach` receives the `McpServer` and registers resources and tools, so the Skills extension can be passed as `extensions: [skills]`. Each extension is advertised under `capabilities.extensions[id]`; every `install` runs in order, then every `attach`. The low-level `Server` runs only `install` and refuses an extension with `attach`. A duplicate id, or an extension with neither hook, fails construction before anything is installed.
8+
9+
`Protocol.use(method, (request, ctx, next) => …)` is 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 `ClientExtension` objects (`{ id, install(client) }`), 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`; duplicate ids fail construction. `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`.
10+
11+
`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
@@ -68,6 +68,7 @@ export const guideSidebar: DefaultTheme.SidebarItem[] = [
6868
items: [
6969
{ text: 'Low-level server', link: '/advanced/low-level-server' },
7070
{ text: 'Custom methods', link: '/advanced/custom-methods' },
71+
{ text: 'Server extensions', link: '/advanced/extensions' },
7172
{ text: 'Schema libraries', link: '/advanced/schema-libraries' },
7273
{ text: 'Custom transports', link: '/advanced/custom-transports' },
7374
{ text: 'Wire schemas', link: '/advanced/wire-schemas' },

‎docs/advanced/extensions.md‎

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
---
2+
shape: how-to
3+
---
4+
5+
# Server extensions
6+
7+
::: warning Experimental
8+
The `extensions` option, the `ServerExtension` and `ClientExtension` shapes, `use` and `acceptResultType` are experimental and may change in a minor release.
9+
:::
10+
11+
A **server extension** packages protocol behaviour outside the core specification, such as the `io.modelcontextprotocol/tasks` or `io.modelcontextprotocol/skills` extension or a vendor feature, as one object you pass to the server. The SDK advertises it and installs it, and gives it hooks at two levels: the protocol, where it adds methods and middleware, and the high-level `McpServer`, where it registers resources and tools. What the extension does behind those hooks is its own business.
12+
13+
## Write an extension
14+
15+
An extension is an `id` plus one or both of two hooks:
16+
17+
- `install(server)` receives the low-level `Server`. Use it for custom methods (`setRequestHandler`), middleware on spec methods (`use`), notification handlers and capability settings (`registerCapabilities`). It runs on both `Server` and `McpServer`.
18+
- `attach(mcp)` receives the `McpServer`. Use it for anything registered through the high-level API, such as `registerResource` with a `ResourceTemplate`, or `registerTool`. It runs only through `McpServer`.
19+
20+
This extension works at the protocol level only:
21+
22+
```ts
23+
import type { ServerExtension } from '@modelcontextprotocol/server';
24+
import { MissingRequiredClientCapabilityError, CLIENT_CAPABILITIES_META_KEY } from '@modelcontextprotocol/server';
25+
import * as z from 'zod/v4';
26+
27+
const GATE = 'com.example/gate';
28+
29+
export const gate: ServerExtension = {
30+
id: GATE,
31+
install(server) {
32+
// Settings for the advertised capability, if the extension has any.
33+
server.registerCapabilities({ extensions: { [GATE]: { exampleData: true } } });
34+
35+
// A custom method, exactly as in Custom methods.
36+
server.setRequestHandler('gate/status', { params: z.looseObject({}) }, () => ({ armed: true }));
37+
38+
// Middleware on a spec method: runs around the registered handler,
39+
// may answer, transform, or refuse.
40+
server.use('tools/call', (request, ctx, next) => {
41+
const declared = ctx.mcpReq.envelope?.[CLIENT_CAPABILITIES_META_KEY]?.extensions ?? {};
42+
if (!(GATE in declared)) {
43+
throw new MissingRequiredClientCapabilityError({ requiredCapabilities: { extensions: { [GATE]: {} } } }, 'declare the gate');
44+
}
45+
return next(request, ctx);
46+
});
47+
}
48+
};
49+
```
50+
51+
An extension that serves resources attaches instead. The Skills extension is one: it has an `id` and an `attach(mcp)`, so it is a `ServerExtension` as it stands.
52+
53+
```ts
54+
import { McpServer } from '@modelcontextprotocol/server';
55+
import { loadSkills } from '@modelcontextprotocol/server/ext/skills/node';
56+
57+
const skills = await loadSkills('./skills');
58+
const server = new McpServer({ name: 'skills-server', version: '1.0.0' }, { extensions: [skills] });
59+
```
60+
61+
Passing it in `extensions` is the same as calling `skills.attach(server)` before connecting.
62+
63+
## Install it
64+
65+
Pass extensions at construction:
66+
67+
```ts
68+
const server = new McpServer({ name: 'gated', version: '1.0.0' }, { extensions: [gate, skills] });
69+
```
70+
71+
The server then does three things, in this order:
72+
73+
1. Advertises each extension under `capabilities.extensions[id]` as `{}`. Legacy connections see it in the `initialize` result, and 2026-07-28 connections see it in `server/discover`. Settings an extension registers itself replace the `{}`.
74+
2. Runs every `install`, in array order, after the built-in handlers exist.
75+
3. Runs every `attach`, in array order.
76+
77+
Construction fails before anything is installed if two extensions share an `id`, or if an extension has neither hook. A hook that throws fails the constructor, so a server with a partly installed extension never exists.
78+
79+
The low-level `Server` takes the same `extensions` option and runs only `install`. It refuses an extension that has `attach`, because that extension needs `McpServer`.
80+
81+
## Client extensions
82+
83+
The client half has one level: `ClientExtension` is `{ id, install(client) }`, passed in `ClientOptions.extensions`. The client advertises it under its own `capabilities.extensions[id]`. On a legacy connection that is the `initialize` request, and on a 2026-07-28 connection it is every request's `_meta` client-capabilities envelope, which is where a server extension reads it. `install` receives the `Client` to register handlers for server-to-client requests and notifications, or to wrap the ones the SDK installs with middleware. A duplicate `id` fails construction here too.
84+
85+
```ts
86+
import type { ClientExtension } from '@modelcontextprotocol/client';
87+
88+
const gateClient: ClientExtension = {
89+
id: GATE,
90+
install(client) {
91+
client.setRequestHandler('gate/ping', { params: z.looseObject({}) }, () => ({ pong: true }));
92+
// Results of tools/call may carry the extension's own kind; the
93+
// explicit-schema request() path then hands them to the caller's
94+
// schema as-is instead of rejecting the unknown resultType.
95+
client.acceptResultType('tools/call', 'gate');
96+
}
97+
};
98+
99+
const client = new Client({ name: 'gated-client', version: '1.0.0' }, { extensions: [gateClient] });
100+
```
101+
102+
## How middleware composes
103+
104+
`setRequestHandler` is the route handler. `use(method, middleware)` is the middleware around it, in the Koa style: `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, including a handler another extension registered. 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`.
105+
106+
Several middleware nest in registration order, the first installed outermost. The returned function removes the middleware. Method names are exact, and there is no wildcard.
107+
108+
An extension wraps the methods it doesn't own with `use`, and never registers them again. 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.
109+
110+
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 the protocol-level errors the client must see as errors: `UrlElicitationRequiredError` and `MissingRequiredClientCapabilityError` (`-32021`).
111+
112+
## Recap
113+
114+
- `ServerExtension` is `{ id, install?(server), attach?(mcp) }`, passed in `extensions`. `install` gets the low-level `Server` and `attach` gets the `McpServer`.
115+
- Every `install` runs before every `attach`, each in array order. Only `McpServer` runs `attach`.
116+
- Duplicate ids, and extensions with no hook, fail construction before anything is installed.
117+
- `ClientExtension` is `{ id, install(client) }` on `ClientOptions.extensions`.
118+
- Middleware composes at dispatch time, in registration order, and applies to handlers registered later, including other extensions' handlers.
119+
- `acceptResultType(method, resultType)` lets a client extension receive a result kind outside `complete` / `input_required` through the explicit-schema `request()` path.
120+
- The SDK owns the hooks and the capability advertisement, not the extension's state or execution.

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

Lines changed: 26 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,18 @@ 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}. A duplicate `id` fails construction
189+
* before any extension is installed.
190+
*
191+
* Experimental: the shape of an extension may change in a minor release.
192+
*
193+
* @experimental
194+
*/
195+
extensions?: ClientExtension[];
196+
184197
/**
185198
* Capabilities to advertise as being supported by this client.
186199
*/
@@ -680,6 +693,19 @@ export class Client extends Protocol<ClientContext> {
680693
if (options?.listChanged) {
681694
this._listChangedConfig = options.listChanged;
682695
}
696+
697+
const extensions = options?.extensions ?? [];
698+
const ids = new Set<string>();
699+
for (const extension of extensions) {
700+
if (ids.has(extension.id)) {
701+
throw new Error(`Extension "${extension.id}" is listed more than once; pass each extension once`);
702+
}
703+
ids.add(extension.id);
704+
}
705+
for (const extension of extensions) {
706+
this.registerCapabilities({ extensions: { [extension.id]: {} } });
707+
extension.install(this);
708+
}
683709
}
684710

685711
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
@@ -72,6 +72,7 @@ export { Client } from './client/client';
7272
export { getSupportedElicitationModes } from './client/client';
7373
export type { DiscoverAndRequestJwtAuthGrantOptions, JwtAuthGrantResult, RequestJwtAuthGrantOptions } from './client/crossAppAccess';
7474
export { discoverAndRequestJwtAuthGrant, exchangeJwtAuthGrant, requestJwtAuthorizationGrant } from './client/crossAppAccess';
75+
export type { ClientExtension } from './client/extension';
7576
// DPoP (RFC 9449 / SEP-1932) sender-constrained tokens: the signing session plus key-pair
7677
// primitives. Wire a DpopSession into OAuthClientProvider.dpop() for full OAuth+DPoP via `auth`/
7778
// the transports' authProvider option, or use `withDpop` directly when you manage tokens yourself.

0 commit comments

Comments
 (0)