Skip to content

Commit 77846c2

Browse files
Merge main into scope-challenge-server-sdk
Resolve request body size limit conflicts while retaining scope challenge support. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
2 parents 7b781ed + f724f40 commit 77846c2

12 files changed

Lines changed: 699 additions & 33 deletions

File tree

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@modelcontextprotocol/server': minor
3+
'@modelcontextprotocol/node': minor
4+
---
5+
6+
Add request-time OAuth scope challenges for tools. A tool's `scopeChallenge`
7+
callback receives the parsed request and verified authentication info, then
8+
either continues or returns the exact scope set for an `insufficient_scope`
9+
response. `requireScopes` provides a small helper for static all-of checks.
10+
11+
`createMcpHandler` and Streamable HTTP transports return HTTP 403 with an
12+
`insufficient_scope` challenge before tool execution or SSE setup.

‎docs/behavior-surface-pins.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ CI pass — that reopens the silent-drift hole the pin exists to close.
3030
| Published package set, export maps, dual ESM/CJS topology | `packages/core-internal/test/packageTopologyPins.test.ts` |
3131
| stdio environment-inheritance safelist | `packages/client/test/client/stdioEnvPins.test.ts` |
3232
| 2025-11-25 wire method-registry membership, schema identity | `packages/core-internal/test/types/registryPins.test.ts` |
33+
| OAuth scope challenge timing and serialization | `packages/server/test/server/scopeChallenge.test.ts` |
3334

3435
## Writing a new pin
3536

‎docs/serving/authorization.md‎

Lines changed: 36 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,8 @@ import {
2121
} from '@modelcontextprotocol/express';
2222
import { toNodeHandler } from '@modelcontextprotocol/node';
2323
import type { AuthInfo, OAuthMetadata } from '@modelcontextprotocol/server';
24-
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
24+
import { createMcpHandler, McpServer, requireScopes } from '@modelcontextprotocol/server';
25+
import * as z from 'zod/v4';
2526

2627
const mcpServerUrl = new URL('https://api.example.com/mcp');
2728
const verifier: OAuthTokenVerifier = { verifyAccessToken };
@@ -33,7 +34,13 @@ const auth = requireBearerAuth({
3334
});
3435

3536
const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['api.example.com'] });
36-
const node = toNodeHandler(createMcpHandler(buildServer));
37+
const node = toNodeHandler(
38+
createMcpHandler(buildServer, {
39+
scopeChallenge: {
40+
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl)
41+
}
42+
})
43+
);
3744
app.all('/mcp', auth, (req, res) => void node(req, res, req.body));
3845
```
3946

@@ -118,28 +125,40 @@ The per-request factory itself receives the same value as `ctx.authInfo`, so it
118125

119126
## Enforce per-tool scopes
120127

121-
`requiredScopes` gates the whole endpoint. For a scope only some tools need, check inside the handler — the handler is the only place that knows which tool is executing.
122-
123-
```ts source="../../examples/guides/serving/authorization.examples.ts#perToolScopes_handler"
124-
server.registerTool('purge-notes', { description: 'Delete every note' }, async ctx => {
125-
if (!ctx.http?.authInfo?.scopes.includes('notes:write')) {
126-
return { content: [{ type: 'text', text: 'insufficient_scope: purge-notes requires notes:write' }], isError: true };
127-
}
128-
return { content: [{ type: 'text', text: 'All notes deleted' }] };
129-
});
128+
`requiredScopes` gates the whole endpoint. For scope step-up on an individual tool, set its `scopeChallenge` callback and configure `scopeChallenge.resourceMetadataUrl` on `createMcpHandler` (or a directly constructed Streamable HTTP transport). The callback receives the full parsed request and verified `authInfo`. Return `undefined` to continue, or return the exact, complete scope set to send `403 insufficient_scope` before invocation or SSE. Throwing or rejecting fails closed.
129+
130+
Use `requireScopes` for a static exact all-of check. Use a callback when the required scope set depends on the request:
131+
132+
```ts source="../../examples/guides/serving/authorization.examples.ts#perToolScopes_challenge"
133+
server.registerTool('purge-notes', { scopeChallenge: requireScopes('notes:write') }, async () => ({
134+
content: [{ type: 'text', text: 'All notes deleted' }]
135+
}));
136+
137+
server.registerTool(
138+
'read-repository',
139+
{
140+
inputSchema: z.object({ visibility: z.enum(['public', 'private']) }),
141+
scopeChallenge: ({ request, authInfo }) => {
142+
const visibility = (request.params as { arguments?: { visibility?: unknown } }).arguments?.visibility;
143+
if (visibility !== 'public' && visibility !== 'private') return;
144+
145+
const scopes = visibility === 'private' ? (['repo:read'] as const) : (['public_repo'] as const);
146+
return scopes.every(scope => authInfo?.scopes.includes(scope))
147+
? undefined
148+
: { scopes, errorDescription: `${visibility} repository access is required` };
149+
}
150+
},
151+
async ({ visibility }) => ({ content: [{ type: 'text', text: `Read ${visibility} repository` }] })
152+
);
130153
```
131154

132-
A caller holding only `mcp` gets an ordinary tool result with `isError: true`, so the model reads the refusal and moves on instead of losing the connection.
133-
134-
::: info
135-
Responding `403 insufficient_scope` at the HTTP layer instead triggers the client transport's automatic scope step-up (SEP-2350) — see [Authenticate a user with OAuth](../clients/oauth.md).
136-
:::
155+
Scope interpretation belongs to your callback; the SDK does not infer hierarchies, alternatives, or missing scopes. Challenged tools remain visible in `tools/list`.
137156

138157
## Recap
139158

140159
- `requireBearerAuth` from `@modelcontextprotocol/server` is the same gate for web-standard `fetch` hosts; the Express middleware adapts the same core.
141160
- `requireBearerAuth` plus a `verifyAccessToken` you write turn an Express-mounted MCP route into an OAuth resource server; the SDK never issues tokens.
142161
- Missing, invalid, or expired tokens get `401 invalid_token`; a token missing a `requiredScopes` entry gets `403 insufficient_scope`; both carry a `WWW-Authenticate: Bearer` challenge.
143162
- `mcpAuthMetadataRouter` publishes the RFC 9728 document that challenge points at, plus a mirror of the AS metadata.
144-
- Verified auth flows `req.auth` → `ctx.http.authInfo`; per-tool scopes are a check inside the handler that returns `isError: true`.
163+
- Verified auth flows `req.auth` → `ctx.http.authInfo`; per-tool callbacks can trigger HTTP `403` scope step-up before invocation.
145164
- The v1 Authorization Server helpers are frozen in `@modelcontextprotocol/server-legacy/auth`.

‎examples/guides/serving/authorization.examples.ts‎

Lines changed: 31 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ import {
2222
} from '@modelcontextprotocol/express';
2323
import { toNodeHandler } from '@modelcontextprotocol/node';
2424
import type { AuthInfo, OAuthMetadata } from '@modelcontextprotocol/server';
25-
import { createMcpHandler, McpServer } from '@modelcontextprotocol/server';
25+
import { createMcpHandler, McpServer, requireScopes } from '@modelcontextprotocol/server';
26+
import * as z from 'zod/v4';
2627

2728
const mcpServerUrl = new URL('https://api.example.com/mcp');
2829
const verifier: OAuthTokenVerifier = { verifyAccessToken };
@@ -34,7 +35,13 @@ const auth = requireBearerAuth({
3435
});
3536

3637
const app = createMcpExpressApp({ host: '0.0.0.0', allowedHosts: ['api.example.com'] });
37-
const node = toNodeHandler(createMcpHandler(buildServer));
38+
const node = toNodeHandler(
39+
createMcpHandler(buildServer, {
40+
scopeChallenge: {
41+
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl)
42+
}
43+
})
44+
);
3845
app.all('/mcp', auth, (req, res) => void node(req, res, req.body));
3946
//#endregion requireBearerAuth_basic
4047

@@ -72,14 +79,28 @@ function buildServer(): McpServer {
7279
});
7380
//#endregion authInfo_handler
7481

75-
//#region perToolScopes_handler
76-
server.registerTool('purge-notes', { description: 'Delete every note' }, async ctx => {
77-
if (!ctx.http?.authInfo?.scopes.includes('notes:write')) {
78-
return { content: [{ type: 'text', text: 'insufficient_scope: purge-notes requires notes:write' }], isError: true };
79-
}
80-
return { content: [{ type: 'text', text: 'All notes deleted' }] };
81-
});
82-
//#endregion perToolScopes_handler
82+
//#region perToolScopes_challenge
83+
server.registerTool('purge-notes', { scopeChallenge: requireScopes('notes:write') }, async () => ({
84+
content: [{ type: 'text', text: 'All notes deleted' }]
85+
}));
86+
87+
server.registerTool(
88+
'read-repository',
89+
{
90+
inputSchema: z.object({ visibility: z.enum(['public', 'private']) }),
91+
scopeChallenge: ({ request, authInfo }) => {
92+
const visibility = (request.params as { arguments?: { visibility?: unknown } }).arguments?.visibility;
93+
if (visibility !== 'public' && visibility !== 'private') return;
94+
95+
const scopes = visibility === 'private' ? (['repo:read'] as const) : (['public_repo'] as const);
96+
return scopes.every(scope => authInfo?.scopes.includes(scope))
97+
? undefined
98+
: { scopes, errorDescription: `${visibility} repository access is required` };
99+
}
100+
},
101+
async ({ visibility }) => ({ content: [{ type: 'text', text: `Read ${visibility} repository` }] })
102+
);
103+
//#endregion perToolScopes_challenge
83104

84105
return server;
85106
}

‎packages/middleware/node/src/streamableHttp.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import type {
1515
JSONRPCMessage,
1616
MessageExtraInfo,
1717
RequestId,
18+
ScopeChallengeHandler,
1819
Transport,
1920
WebStandardStreamableHTTPServerTransportOptions
2021
} from '@modelcontextprotocol/server';
@@ -169,6 +170,11 @@ export class NodeStreamableHTTPServerTransport implements Transport {
169170
this._webStandardTransport.setSupportedProtocolVersions(versions);
170171
}
171172

173+
/** Sets the scope challenge resolver used by the wrapped Web Standard transport. */
174+
setScopeChallengeResolver(resolver: ScopeChallengeHandler): void {
175+
this._webStandardTransport.setScopeChallengeResolver(resolver);
176+
}
177+
172178
/**
173179
* Handles an incoming HTTP request, whether `GET` or `POST`.
174180
*

‎packages/server/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ export { InMemoryServerEventBus } from './server/serverEventBus';
6565
// StdioServerTransport and the serveStdio entry are exported from the './stdio' subpath — server stdio
6666
// has only type-level Node imports (erased at compile time), but matching the client's `./stdio` subpath
6767
// gives consumers a consistent shape across packages.
68+
export type { ScopeChallenge, ScopeChallengeConfig, ScopeChallengeHandler } from './server/scopeChallenge';
69+
export { requireScopes } from './server/scopeChallenge';
6870
export type {
6971
EventId,
7072
EventStore,

‎packages/server/src/server/createMcpHandler.ts‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,8 @@ import { createListenRouter, DEFAULT_MAX_SUBSCRIPTIONS } from './listenRouter';
6464
import { McpServer } from './mcp';
6565
import type { PerRequestResponseMode } from './perRequestTransport';
6666
import { DEFAULT_MAX_REQUEST_BODY_SIZE, readRequestBody, requestBodyTooLargeMessage, resolveMaxRequestBodySize } from './requestBody';
67+
import type { ScopeChallengeConfig } from './scopeChallenge';
68+
import { createScopeChallengeResponse, findScopeChallenge } from './scopeChallenge';
6769
import type { Server } from './server';
6870
import { installModernOnlyHandlers, seedClientIdentityFromEnvelope, serverIdentityOf } from './server';
6971
import type { ServerEventBus, ServerNotifier } from './serverEventBus';
@@ -212,6 +214,8 @@ export interface CreateMcpHandlerOptions {
212214
* @default 4194304 (4 MiB)
213215
*/
214216
maxRequestBodySize?: number;
217+
/** Enables per-tool OAuth scope challenges. */
218+
scopeChallenge?: ScopeChallengeConfig;
215219
}
216220

217221
/**
@@ -323,7 +327,8 @@ function createLegacyStatelessFallback(
323327
factory: McpServerFactory,
324328
onerror?: (error: Error) => void,
325329
keepAliveMs?: number,
326-
maxRequestBodySize?: number
330+
maxRequestBodySize?: number,
331+
scopeChallenge?: ScopeChallengeConfig
327332
): LegacyHttpHandler {
328333
return async (request, options) => {
329334
if (request.method.toUpperCase() !== 'POST') {
@@ -338,7 +343,8 @@ function createLegacyStatelessFallback(
338343
const transport = new WebStandardStreamableHTTPServerTransport({
339344
sessionIdGenerator: undefined,
340345
...(keepAliveMs !== undefined && { keepAliveMs }),
341-
...(maxRequestBodySize !== undefined && { maxRequestBodySize })
346+
...(maxRequestBodySize !== undefined && { maxRequestBodySize }),
347+
...(scopeChallenge !== undefined && { scopeChallenge })
342348
});
343349
await product.connect(transport);
344350

@@ -715,7 +721,9 @@ export function createMcpHandler(factory: McpServerFactory, options: CreateMcpHa
715721
// The default posture is the stateless fallback; 'reject' is the only way
716722
// to turn legacy serving off (modern-only strict).
717723
const legacyHandler: LegacyHttpHandler | undefined =
718-
legacy === 'reject' ? undefined : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs, maxRequestBodySize);
724+
legacy === 'reject'
725+
? undefined
726+
: createLegacyStatelessFallback(factory, reportError, options.keepAliveMs, maxRequestBodySize, options.scopeChallenge);
719727

720728
async function serveModern(route: InboundModernRoute, request: Request, authInfo: AuthInfo | undefined): Promise<Response> {
721729
const claimedRevision = route.classification.revision;
@@ -829,6 +837,21 @@ export function createMcpHandler(factory: McpServerFactory, options: CreateMcpHa
829837
}
830838
}
831839
}
840+
841+
// Run scope preflight after Mcp-Param headers have been checked against the body.
842+
if (options.scopeChallenge !== undefined) {
843+
try {
844+
const result = await findScopeChallenge([route.message], authInfo, context => product.resolveScopeChallenge(context));
845+
if (result !== undefined) {
846+
void product.close().catch(reportError);
847+
return createScopeChallengeResponse(options.scopeChallenge, result.challenge, result.requestId);
848+
}
849+
} catch (error) {
850+
void product.close().catch(reportError);
851+
reportError(toError(error));
852+
return internalServerErrorResponse(route.message.id);
853+
}
854+
}
832855
}
833856

834857
// Era-write at instance binding, then modern-only handler installation —

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

Lines changed: 28 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ import {
4747
import type * as z from 'zod/v4';
4848

4949
import { getCompleter, isCompletable } from './completable';
50+
import type { ScopeChallengeHandler } from './scopeChallenge';
51+
import { supportsScopeChallengeResolver } from './scopeChallenge';
5052
import type { ServerOptions } from './server';
5153
import { Server } from './server';
5254

@@ -146,6 +148,9 @@ export class McpServer {
146148
* ```
147149
*/
148150
async connect(transport: Transport): Promise<void> {
151+
if (supportsScopeChallengeResolver(transport)) {
152+
transport.setScopeChallengeResolver(context => this.resolveScopeChallenge(context));
153+
}
149154
return await this.server.connect(transport);
150155
}
151156

@@ -156,6 +161,16 @@ export class McpServer {
156161
await this.server.close();
157162
}
158163

164+
/** @internal */
165+
resolveScopeChallenge: ScopeChallengeHandler = context => {
166+
if (context.request.method !== 'tools/call') return;
167+
const toolName = (context.request.params as { name?: unknown } | undefined)?.name;
168+
if (typeof toolName !== 'string') return;
169+
const tool = this._registeredTools[toolName];
170+
if (tool === undefined || !tool.enabled) return;
171+
return tool.scopeChallenge?.(context);
172+
};
173+
159174
private _toolHandlersInitialized = false;
160175

161176
private setToolRequestHandlers() {
@@ -811,6 +826,7 @@ export class McpServer {
811826
annotations: ToolAnnotations | undefined,
812827
icons: Icon[] | undefined,
813828
execution: ToolExecution | undefined,
829+
scopeChallenge: ScopeChallengeHandler | undefined,
814830
_meta: Record<string, unknown> | undefined,
815831
handler: AnyToolHandler<StandardSchemaWithJSON | undefined>
816832
): RegisteredTool {
@@ -856,6 +872,7 @@ export class McpServer {
856872
annotations,
857873
icons,
858874
execution,
875+
scopeChallenge,
859876
_meta,
860877
handler: handler,
861878
executor: createToolExecutor(inputSchema, handler),
@@ -911,6 +928,9 @@ export class McpServer {
911928
}
912929
if (updates.annotations !== undefined) registeredTool.annotations = updates.annotations;
913930
if (updates.icons !== undefined) registeredTool.icons = updates.icons;
931+
if (updates.scopeChallenge !== undefined) {
932+
registeredTool.scopeChallenge = updates.scopeChallenge === null ? undefined : updates.scopeChallenge;
933+
}
914934
if (updates._meta !== undefined) registeredTool._meta = updates._meta;
915935
if (updates.enabled !== undefined) registeredTool.enabled = updates.enabled;
916936
this.sendToolListChanged();
@@ -959,6 +979,8 @@ export class McpServer {
959979
outputSchema?: OutputArgs;
960980
annotations?: ToolAnnotations;
961981
icons?: Icon[];
982+
/** Determines whether this tool call needs an OAuth scope challenge. */
983+
scopeChallenge?: ScopeChallengeHandler;
962984
_meta?: Record<string, unknown>;
963985
},
964986
cb: ToolCallback<InputArgs>
@@ -973,6 +995,7 @@ export class McpServer {
973995
outputSchema?: OutputArgs;
974996
annotations?: ToolAnnotations;
975997
icons?: Icon[];
998+
scopeChallenge?: ScopeChallengeHandler;
976999
_meta?: Record<string, unknown>;
9771000
},
9781001
cb: LegacyToolCallback<InputArgs>
@@ -986,6 +1009,7 @@ export class McpServer {
9861009
outputSchema?: StandardSchemaWithJSON | ZodRawShape;
9871010
annotations?: ToolAnnotations;
9881011
icons?: Icon[];
1012+
scopeChallenge?: ScopeChallengeHandler;
9891013
_meta?: Record<string, unknown>;
9901014
},
9911015
cb: ToolCallback<StandardSchemaWithJSON | undefined> | LegacyToolCallback<ZodRawShape>
@@ -994,8 +1018,7 @@ export class McpServer {
9941018
throw new Error(`Tool ${name} is already registered`);
9951019
}
9961020

997-
const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config;
998-
1021+
const { title, description, inputSchema, outputSchema, annotations, icons, scopeChallenge, _meta } = config;
9991022
return this._createRegisteredTool(
10001023
name,
10011024
title,
@@ -1005,6 +1028,7 @@ export class McpServer {
10051028
annotations,
10061029
icons,
10071030
undefined,
1031+
scopeChallenge,
10081032
_meta,
10091033
cb as ToolCallback<StandardSchemaWithJSON | undefined>
10101034
);
@@ -1278,6 +1302,7 @@ export type RegisteredTool = {
12781302
annotations?: ToolAnnotations;
12791303
icons?: Icon[];
12801304
execution?: ToolExecution;
1305+
scopeChallenge?: ScopeChallengeHandler;
12811306
_meta?: Record<string, unknown>;
12821307
handler: AnyToolHandler<StandardSchemaWithJSON | undefined>;
12831308
/** @hidden */
@@ -1293,6 +1318,7 @@ export type RegisteredTool = {
12931318
outputSchema?: StandardSchemaWithJSON;
12941319
annotations?: ToolAnnotations;
12951320
icons?: Icon[];
1321+
scopeChallenge?: ScopeChallengeHandler | null;
12961322
_meta?: Record<string, unknown>;
12971323
callback?: ToolCallback<StandardSchemaWithJSON>;
12981324
enabled?: boolean;

0 commit comments

Comments
 (0)