Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

server-auth.md

259 lines8.4 KB

1---
2title: MCP Server Auth
3id: mcp-server-auth
4order: 13
5description: "Accept the access tokens your authorization server issues, so only a signed-in user can call your MCP tools."
6keywords:
7 - tanstack ai
8 - mcp
9 - model context protocol
10 - mcp server
11 - bearer token
12 - createMCPServer
13 - OAuthTokenVerifier
14 - jwtVerifier
15 - introspectionVerifier
16 - oauthMetadataResponse
17---
18​
19Your MCP server is on a public URL. As a result, any client that can reach that URL can call your tools.
20​
21An MCP server is an OAuth resource server. It does not sign users in. Your authorization server does that, and it issues the access token. The MCP server checks that token on each request.
22​
23Pass `auth` to `createMCPServer`. Then a missing or bad token returns 401.
24​
25## Verify a JWT
26​
27Most providers issue a JWT and publish their keys at a JWKS URL. Auth0, Clerk, WorkOS, Keycloak, Supabase, and the Better Auth MCP plugin all do.
28​
291. Find the issuer URL and the JWKS URL of your provider.
302. Register your MCP server URL as the audience of the token.
313. Serve MCP with this handler.
32​
33```ts
34import { createMCPServer, jwtVerifier } from '@tanstack/ai-mcp/server'
35​
36const server = createMCPServer({
37 name: 'notes',
38 version: '1.0.0',
39 auth: {
40 verifier: jwtVerifier({
41 jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
42 issuer: 'https://auth.example.com/',
43 audience: 'https://mcp.example.com/mcp',
44 }),
45 },
46})
47​
48export default {
49 async fetch(request: Request) {
50 return server.fetch(request)
51 },
53```
54​
55Add your tools on the `tools` field.
56​
57`jwtVerifier` checks the signature, `iss`, `aud`, `exp`, and `nbf`. It reads the keys from `jwksUrl` and caches them. A token that fails one check returns 401.
58​
59## Verify an opaque token
60​
61If your provider issues opaque tokens, pass `introspectionVerifier`. It posts the token to the RFC 7662 introspection endpoint with the client credentials of your MCP server.
62​
63```ts
64import { createMCPServer, introspectionVerifier } from '@tanstack/ai-mcp/server'
65​
66const server = createMCPServer({
67 name: 'notes',
68 version: '1.0.0',
69 auth: {
70 verifier: introspectionVerifier({
71 introspectionUrl: 'https://auth.example.com/oauth/introspect',
72 clientId: process.env.OAUTH_CLIENT_ID ?? '',
73 clientSecret: process.env.OAUTH_CLIENT_SECRET ?? '',
74 }),
75 },
76})
77```
78​
79A token that is not `active` returns 401. If the endpoint is down, the caller gets 500.
80​
81## Write your own verifier
82​
83`verifier` is the `OAuthTokenVerifier` type from the MCP SDK. It has one method, `verifyAccessToken`. Return an `AuthInfo`, or throw `OAuthError` with `OAuthErrorCode.InvalidToken`.
84​
85```ts
86import { OAuthError, OAuthErrorCode, createMCPServer } from '@tanstack/ai-mcp/server'
87import type { OAuthTokenVerifier } from '@tanstack/ai-mcp/server'
88import { findSession } from './sessions'
89​
90const verifier: OAuthTokenVerifier = {
91 async verifyAccessToken(token) {
92 const session = await findSession(token)
93 if (session === undefined) {
94 throw new OAuthError(OAuthErrorCode.InvalidToken, 'Unknown token')
95 }
96 return {
97 token,
98 clientId: session.appId,
99 scopes: session.scopes,
100 expiresAt: session.expiresAt,
101 extra: { sub: session.userId },
102 }
103 },
105​
106const server = createMCPServer({
107 name: 'notes',
108 version: '1.0.0',
109 auth: { verifier },
110})
111```
112​
113`expiresAt` is required. The SDK rejects an `AuthInfo` without it.
114​
115## Require a scope
116​
117Pass `requiredScopes`. A token without one of those scopes returns 403 with `insufficient_scope`.
118​
119```ts
120import { createMCPServer, jwtVerifier } from '@tanstack/ai-mcp/server'
121​
122const server = createMCPServer({
123 name: 'notes',
124 version: '1.0.0',
125 auth: {
126 verifier: jwtVerifier({
127 jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
128 issuer: 'https://auth.example.com/',
129 audience: 'https://mcp.example.com/mcp',
130 }),
131 requiredScopes: ['notes:read'],
132 },
133})
134```
135​
136## Tell clients where to sign in
137​
138An MCP client finds your authorization server through two documents on your origin. Serve them with `oauthMetadataResponse` next to the MCP route. Pass `resourceMetadataUrl` to `auth`, so the 401 response names the first document.
139​
140```ts
141import {
142 createMCPServer,
143 getOAuthProtectedResourceMetadataUrl,
144 jwtVerifier,
145 oauthMetadataResponse,
146} from '@tanstack/ai-mcp/server'
147​
148const mcpUrl = new URL('https://mcp.example.com/mcp')
149const metadata = {
150 resourceServerUrl: mcpUrl,
151 oauthMetadata: {
152 issuer: 'https://auth.example.com/',
153 authorization_endpoint: 'https://auth.example.com/oauth/authorize',
154 token_endpoint: 'https://auth.example.com/oauth/token',
155 response_types_supported: ['code'],
156 },
158​
159const server = createMCPServer({
160 name: 'notes',
161 version: '1.0.0',
162 auth: {
163 verifier: jwtVerifier({
164 jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
165 issuer: 'https://auth.example.com/',
166 audience: mcpUrl.href,
167 }),
168 resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpUrl),
169 },
170})
171​
172export default {
173 async fetch(request: Request) {
174 return oauthMetadataResponse(request, metadata) ?? server.fetch(request)
175 },
177```
178​
179- `/.well-known/oauth-protected-resource/mcp` is the RFC 9728 document. It names your authorization server.
180- `/.well-known/oauth-authorization-server` is the RFC 8414 document. It is `oauthMetadata`, served as is.
181​
182Copy `oauthMetadata` from the discovery document of your provider.
183​
184## Read the caller in a tool
185​
186The verified token is on `ctx.context.authInfo`. Give `.server()` the type `MCPToolContext`.
187​
188```ts
189import { toolDefinition } from '@tanstack/ai'
190import type { MCPToolContext } from '@tanstack/ai-mcp/server'
191import { z } from 'zod'
192​
193export const listNotes = toolDefinition({
194 name: 'list_notes',
195 description: 'List the notes of the signed-in user',
196 inputSchema: z.object({}),
197}).server<MCPToolContext>(async (_args, ctx) => {
198 const userId = ctx.context.authInfo?.extra?.sub
199 if (typeof userId !== 'string') {
200 throw new Error('This tool needs a signed-in user.')
201 }
202 return { userId, notes: [] }
203})
204```
205​
206`authInfo` is `undefined` when the server has no `auth`, and for `createMCPClient({ server })`.
207​
208## Use the auth you already have
209​
210Your app already checks the caller in a middleware. That middleware puts the user and a database handle on the request. You do not want to check the token a second time in `createMCPServer`.
211​
212Pass the verified token and your values to `server.handle`. The server skips its `auth` gate for that request. Every tool call of that request reads your values on `ctx.context`.
213​
214```ts
215import { server } from './mcp-server'
216import { verifyCaller } from './auth'
217​
218export async function handleMcp(request: Request) {
219 const caller = await verifyCaller(request)
220 if (caller instanceof Response) return caller
221 return server.handle(request, {
222 authInfo: caller.authInfo,
223 context: { db: caller.db },
224 })
226```
227​
228`server.fetch(request)` stays a plain Fetch handler. `server.handle` is the same handler with options.
229​
230In a tool, name the values you expect with `MCPToolContext`:
231​
232```ts
233import { toolDefinition } from '@tanstack/ai'
234import type { MCPToolContext } from '@tanstack/ai-mcp/server'
235import { z } from 'zod'
236import type { Db } from './db'
237​
238export const listNotes = toolDefinition({
239 name: 'list_notes',
240 description: 'List the notes of the signed-in user',
241 inputSchema: z.object({}),
242}).server<MCPToolContext<{ db: Db }>>(async (_args, ctx) => {
243 return ctx.context.db.notes.list()
244})
245```
246​
247- `authInfo` is the SDK `AuthInfo`. A tool reads it as `ctx.context.authInfo`. A session or a task belongs to its `clientId` plus `extra.sub`.
248- `context` sits next to `authInfo`, `requestInput`, and `sample` on `ctx.context`. Those three names win over a value of yours.
249- `createMCPClient({ server })` passes no `context`.
250​
251## Sessions and tasks per caller
252​
253A spec 2025 session belongs to the caller that opened it. A task belongs to the caller that started it. The caller is the `clientId` of the token plus its `sub` claim. A request from another caller gets "not found".
254​
255## Cookie sessions
256​
257An MCP client like Claude Desktop or Cursor does not send your app cookies. It needs an OAuth authorization server. If your app signs users in with a cookie session only, add an authorization server in front of it. The Better Auth MCP plugin, Keycloak, and the hosted providers above all give you one.
258​
259A request with no token, or with a bad token, returns 401. The response names your metadata document. A request with a token from your provider calls the server, and the tool reads the user from `ctx.context.authInfo`.