mcp-auth
Authorize MCP SDK v2 resource servers with bearer validation, service clients with credentials, or host-session exchanges; browser authorization_code flows use mcp-client.
- License 许可
- MIT
- 最近更新
- 2026-11-15
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- mcp-auth
- metadata
- { "category": "technique" }
- description
- Authorize MCP SDK v2 resource servers with bearer validation, service clients with credentials, or host-session exchanges; browser authorization_code flows use mcp-client.
- user-invocable
- false
03 SKILL.md 正文
MCP SDK v2 authorization
Ref: https://ts.sdk.modelcontextprotocol.io/v2/
Server = Resource Server: IdP issue/revoke token, server validate.
v1 Authorization Server helpers (
mcpAuthRouter,OAuthServerProvider) frozen in@modelcontextprotocol/server-legacy/auth. Resource Server helpers come from@modelcontextprotocol/express(Node:requireBearerAuth,mcpAuthMetadataRouter) or@modelcontextprotocol/server(web-standard hosts:requireBearerAuth,oauthMetadataResponse). Migrate AS role to dedicated IdP.
Browser/SPA login (connect, finishAuth, IssuerMismatchError) belongs in mcp-client "Authenticate the client." Mock authInfo with mcp-test.
Protect a resource server
import {
getOAuthProtectedResourceMetadataUrl,
mcpAuthMetadataRouter,
requireBearerAuth,
} from '@modelcontextprotocol/express';
import { OAuthError, OAuthErrorCode } from '@modelcontextprotocol/server';
const auth = requireBearerAuth({
verifier: {
verifyAccessToken: async (token) => {
try {
const payload = await verifyJwt(token);
return { token, clientId: payload.sub, scopes: payload.scopes, expiresAt: payload.exp };
} catch {
throw new OAuthError(OAuthErrorCode.InvalidToken, 'Invalid or expired token'); // a plain Error here becomes HTTP 500
}
},
},
requiredScopes: ['mcp'],
resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpServerUrl),
});
app.all('/mcp', auth, (req, res) => void node(req, res, req.body));
app.use(mcpAuthMetadataRouter({ oauthMetadata, resourceServerUrl: mcpServerUrl }));
Verify signature, issuer, audience against IdP keys. Decoded JWT claims alone not enough. requireBearerAuth extracts header, attaches verified AuthInfo to req.auth. toNodeHandler forwards it to ctx.http.authInfo.
- [ ]
requireBearerAuthprotects MCP route before tool dispatch;mcpAuthMetadataRouterserves resource metadata. - [ ]
verifyAccessTokensuppliesexpiresAt, rejects bad tokens withOAuthError(OAuthErrorCode.InvalidToken). Plain exception becomes HTTP 500. - [ ] Tool callbacks get tenant/user permissions from
ctx.http?.authInfo, return{ isError: true, content: [...] }on authorization failure. - [ ] Express hosts use
@modelcontextprotocol/express(requireBearerAuth,mcpAuthMetadataRouter); web-standard fetch hosts userequireBearerAuth+oauthMetadataResponsefrom@modelcontextprotocol/server.
// web-standard fetch host (Cloudflare Workers, Hono, Bun, Deno)
import { oauthMetadataResponse, requireBearerAuth } from '@modelcontextprotocol/server';
export default {
async fetch(req: Request): Promise<Response> {
const meta = await oauthMetadataResponse(req, {
oauthMetadata,
resourceServerUrl: mcpServerUrl,
});
if (meta) return meta; // RFC 9728 protected-resource / RFC 8414 AS metadata
// ...route to handler; requireBearerAuth(req) returns AuthInfo or a 401 challenge Response
},
};
Authenticate a service client
Use ClientCredentialsProvider for service with client secret. Use PrivateKeyJwtProvider when authorization server requires private-key client authentication:
new ClientCredentialsProvider({ clientId, clientSecret, expectedIssuer });
new PrivateKeyJwtProvider({
clientId,
privateKey,
algorithm: 'RS256',
jwtLifetimeSeconds: 300,
});
expectedIssuer pins ClientCredentialsProvider credentials; mismatched discovery throws AuthorizationServerMismatchError. Other two providers take none.
For authenticated host session, exchange its assertion with CrossAppAccessProvider:
new CrossAppAccessProvider({
assertion: async (ctx) =>
(await discoverAndRequestJwtAuthGrant({/* issuer/audience */})).jwtAuthGrant,
clientId,
clientSecret,
});
For other grant model, implement OAuthClientProvider with static clientMetadata/redirectUrl plus tokens/saveTokens, clientInformation/saveClientInformation, codeVerifier/saveCodeVerifier, state, redirectToAuthorization, and saveDiscoveryState/discoveryState. Only clientInformation(ctx?) and saveClientInformation(info, ctx?) accept optional ctx; saveTokens(tokens) and tokens() take no ctx — tokens not issuer-partitioned. Override validateResourceURL(serverUrl, resource?) for RFC 8707 resource pinning. Use Client ID Metadata Document — stable HTTPS clientMetadata URL passed as clientId — instead of deprecated registerClient (SEP-991).
- [ ]
ClientCredentialsProvidersetsexpectedIssuer(mismatched discovery throwsAuthorizationServerMismatchError);PrivateKeyJwtProviderandCrossAppAccessProviderdon't accept it. - [ ]
clientInformationandsaveClientInformationaccept optionalctx;tokensandsaveTokensnot issuer-partitioned. - [ ] Custom provider implements every listed persistence and redirect method, plus resource URL validation when RFC 8707 pinning applies.
Handle authorization errors
-
OAuth consolidation: v1
Invalid*Errorfamily andOAUTH_ERRORSreplaced byOAuthError+OAuthErrorCode; switchinstanceoftoerror.code. -
InsufficientScopeError— two distinct classes: OAuth one (OAuthError(OAuthErrorCode.InsufficientScope), surfaced as 403 byrequireBearerAuthscope enforcement) and separate transport class (client-side, SEP-2350), covered in mcp-client. -
[ ] Error handling uses
error.codefor consolidated OAuth errors, distinguishes OAuth vs transportInsufficientScopeErrorclasses. -
[ ] Tests use mock issuers from mcp-test.
04 同仓库更多 Skills
unslop
Use when writing or editing prose a person will read, or when text sounds AI-generated.
show-me
Use when asked to show, diagram, or walk through how code fits together or what a change does, or before explaining a multi-file flow in prose.
pr
Use when writing or updating a pull request description, or before running `gh pr create`.
commit
Use when writing a commit message, or before running `git commit`.
write-specs
Spec a feature's observable behavior. Use when asked for requirements, when a request says what the system should do but not how, or to capture what a built system already guarantees. Not for how to build it (write-plan).
write-skills
Write, fix, or audit a skill's frontmatter, trigger description, and body. Use when a skill is asked for, never fires, or fires at the wrong moment. Not for a hook (write-hooks) or the plugin manifest and catalog.