Skip to content

Commit aa2a3fe

Browse files
feat(server): add per-tool OAuth scope challenges
Let tools declare alternative authorization paths, require all scope checks within a path, choose paths from the request, and return an HTTP 403 scope challenge before tool execution when the token is insufficient. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
1 parent 3924de9 commit aa2a3fe

12 files changed

Lines changed: 994 additions & 29 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 per-tool OAuth scope challenges. Tools can accept alternative named paths,
7+
require all scopes in a path, accept exact alternatives for each scope, and
8+
choose applicable paths from the request.
9+
10+
`createMcpHandler` and Streamable HTTP transports return HTTP 403 with an
11+
`insufficient_scope` challenge before tool execution. A `string[]` requires
12+
every listed scope.

‎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 policy and challenge selection | `packages/server/test/server/scopeChallenge.test.ts` |
3334

3435
## Writing a new pin
3536

‎docs/serving/authorization.md‎

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
import { toNodeHandler } from '@modelcontextprotocol/node';
2323
import type { AuthInfo, OAuthMetadata } from '@modelcontextprotocol/server';
2424
import { createMcpHandler, McpServer } 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,46 @@ 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, declare `scopes` on the tool and pass `scopeChallenge.resourceMetadataUrl` to `createMcpHandler` (or a directly constructed Streamable HTTP transport). The SDK checks the verified `AuthInfo.scopes` before invocation and returns `403 insufficient_scope` without opening SSE.
129+
130+
`scopes: ['notes:read', 'notes:write']` is one execution path with exact `allOf` semantics. For alternatives, put named paths in the policy's `anyOf`. Each path has an `allOf`, and each entry accepts its canonical `challenge` scope or an exact alternative in `anyOf`.
131+
132+
```ts source="../../examples/guides/serving/authorization.examples.ts#perToolScopes_policy"
133+
server.registerTool(
134+
'read-repository',
135+
{
136+
inputSchema: z.object({ visibility: z.enum(['public', 'private']) }),
137+
scopes: {
138+
anyOf: [
139+
{
140+
name: 'public',
141+
allOf: [{ challenge: 'public_repo', anyOf: [] }]
142+
},
143+
{
144+
name: 'private',
145+
allOf: [{ challenge: 'repo:read', anyOf: ['repo'] }]
146+
}
147+
],
148+
select: request => {
149+
const visibility = (request.params as { arguments?: { visibility?: unknown } }).arguments?.visibility;
150+
if (visibility === 'public' || visibility === 'private') return [visibility];
151+
return;
152+
}
153+
}
154+
},
155+
async ({ visibility }) => ({ content: [{ type: 'text', text: `Read ${visibility} repository` }] })
156+
);
130157
```
131158

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.
159+
The selector receives the full parsed request and returns applicable path names. Declaration order determines which path is used for a challenge. The challenge keeps a held scope for each check already met and requests `challenge` for each unmet check. Return `undefined` for malformed or incomplete arguments so normal input validation handles them.
133160

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-
:::
161+
Scope matching is exact. Keep provider-specific authorization checks in your token verifier or handler. Scoped tools remain visible in `tools/list`. Do not expose sensitive selector arguments through `x-mcp-header`.
137162

138163
## Recap
139164

140165
- `requireBearerAuth` from `@modelcontextprotocol/server` is the same gate for web-standard `fetch` hosts; the Express middleware adapts the same core.
141166
- `requireBearerAuth` plus a `verifyAccessToken` you write turn an Express-mounted MCP route into an OAuth resource server; the SDK never issues tokens.
142167
- 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.
143168
- `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`.
169+
- Verified auth flows `req.auth` → `ctx.http.authInfo`; per-tool scope policies can trigger HTTP `403` step-up before invocation.
145170
- The v1 Authorization Server helpers are frozen in `@modelcontextprotocol/server-legacy/auth`.

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

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
import { toNodeHandler } from '@modelcontextprotocol/node';
2424
import type { AuthInfo, OAuthMetadata } from '@modelcontextprotocol/server';
2525
import { createMcpHandler, McpServer } 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,32 @@ 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_policy
83+
server.registerTool(
84+
'read-repository',
85+
{
86+
inputSchema: z.object({ visibility: z.enum(['public', 'private']) }),
87+
scopes: {
88+
anyOf: [
89+
{
90+
name: 'public',
91+
allOf: [{ challenge: 'public_repo', anyOf: [] }]
92+
},
93+
{
94+
name: 'private',
95+
allOf: [{ challenge: 'repo:read', anyOf: ['repo'] }]
96+
}
97+
],
98+
select: request => {
99+
const visibility = (request.params as { arguments?: { visibility?: unknown } }).arguments?.visibility;
100+
if (visibility === 'public' || visibility === 'private') return [visibility];
101+
return;
102+
}
103+
}
104+
},
105+
async ({ visibility }) => ({ content: [{ type: 'text', text: `Read ${visibility} repository` }] })
106+
);
107+
//#endregion perToolScopes_policy
83108

84109
return server;
85110
}

‎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+
ScopeResolver,
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 resolver used by the wrapped Web Standard transport. */
174+
setScopeResolver(resolver: ScopeResolver): void {
175+
this._webStandardTransport.setScopeResolver(resolver);
176+
}
177+
172178
/**
173179
* Handles an incoming HTTP request, whether `GET` or `POST`.
174180
*

‎packages/server/src/index.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,15 @@ export { InMemoryServerEventBus } from './server/serverEventBus';
6363
// StdioServerTransport and the serveStdio entry are exported from the './stdio' subpath — server stdio
6464
// has only type-level Node imports (erased at compile time), but matching the client's `./stdio` subpath
6565
// gives consumers a consistent shape across packages.
66+
export type {
67+
ScopeChallengeConfig,
68+
ScopePath,
69+
ScopePathSelector,
70+
ScopeRequirement,
71+
ScopeResolver,
72+
ToolScopeConfig,
73+
ToolScopePolicy
74+
} from './server/scopeChallenge';
6675
export type {
6776
EventId,
6877
EventStore,

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

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ import { invoke } from './invoke';
6363
import { createListenRouter, DEFAULT_MAX_SUBSCRIPTIONS } from './listenRouter';
6464
import { McpServer } from './mcp';
6565
import type { PerRequestResponseMode } from './perRequestTransport';
66+
import type { ScopeChallengeConfig } from './scopeChallenge';
67+
import { createScopeChallengeResponse, findScopeChallenge } from './scopeChallenge';
6668
import type { Server } from './server';
6769
import { installModernOnlyHandlers, seedClientIdentityFromEnvelope, serverIdentityOf } from './server';
6870
import type { ServerEventBus, ServerNotifier } from './serverEventBus';
@@ -201,6 +203,8 @@ export interface CreateMcpHandlerOptions {
201203
* @default 15000
202204
*/
203205
keepAliveMs?: number;
206+
/** Enables per-tool OAuth scope challenges. */
207+
scopeChallenge?: ScopeChallengeConfig;
204208
}
205209

206210
/**
@@ -311,7 +315,8 @@ function internalServerErrorResponse(id: RequestId | null = null): Response {
311315
function createLegacyStatelessFallback(
312316
factory: McpServerFactory,
313317
onerror?: (error: Error) => void,
314-
keepAliveMs?: number
318+
keepAliveMs?: number,
319+
scopeChallenge?: ScopeChallengeConfig
315320
): LegacyHttpHandler {
316321
return async (request, options) => {
317322
if (request.method.toUpperCase() !== 'POST') {
@@ -325,7 +330,8 @@ function createLegacyStatelessFallback(
325330
});
326331
const transport = new WebStandardStreamableHTTPServerTransport({
327332
sessionIdGenerator: undefined,
328-
...(keepAliveMs !== undefined && { keepAliveMs })
333+
...(keepAliveMs !== undefined && { keepAliveMs }),
334+
...(scopeChallenge !== undefined && { scopeChallenge })
329335
});
330336
await product.connect(transport);
331337

@@ -663,7 +669,7 @@ export function createMcpHandler(factory: McpServerFactory, options: CreateMcpHa
663669
// The default posture is the stateless fallback; 'reject' is the only way
664670
// to turn legacy serving off (modern-only strict).
665671
const legacyHandler: LegacyHttpHandler | undefined =
666-
legacy === 'reject' ? undefined : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs);
672+
legacy === 'reject' ? undefined : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs, options.scopeChallenge);
667673

668674
async function serveModern(route: InboundModernRoute, request: Request, authInfo: AuthInfo | undefined): Promise<Response> {
669675
const claimedRevision = route.classification.revision;
@@ -777,6 +783,24 @@ export function createMcpHandler(factory: McpServerFactory, options: CreateMcpHa
777783
}
778784
}
779785
}
786+
787+
// Run selectors after Mcp-Param headers have been checked against the body.
788+
if (options.scopeChallenge !== undefined) {
789+
try {
790+
const challenge = findScopeChallenge([route.message], authInfo, requestMessage => {
791+
const toolName = (requestMessage.params as { name?: unknown } | undefined)?.name;
792+
return typeof toolName === 'string' ? product.getToolScopes(toolName) : undefined;
793+
});
794+
if (challenge !== undefined) {
795+
void product.close().catch(reportError);
796+
return createScopeChallengeResponse(options.scopeChallenge, challenge);
797+
}
798+
} catch (error) {
799+
void product.close().catch(reportError);
800+
reportError(toError(error));
801+
return internalServerErrorResponse(route.message.id);
802+
}
803+
}
780804
}
781805

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

0 commit comments

Comments
 (0)