Open History to see the last commit
1---
2title: MCP Server Auth
3id: mcp-server-auth
4order: 13
5description: "Accept the access tokens that 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
19Require a credential on your public MCP route. A client that cannot present it cannot call your tools.
20
21Pass `auth` to `createMCPServer`. The server then checks the access token on each request, and a missing or bad token gets 401.
22
23## Quick setup
24
25Most 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.
26
271. Find the issuer URL and the JWKS URL of your provider.
282. In your provider, register the URL of your MCP server as the audience of the token.
293. Pass `jwtVerifier` to `auth`:
30
31```ts
32import { createMCPServer, jwtVerifier } from '@tanstack/ai-mcp/server'
33
34const server = createMCPServer({
35 name: 'notes',
36 version: '1.0.0',
37 auth: {
38 verifier: jwtVerifier({
39 jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
40 issuer: 'https://auth.example.com/',
41 audience: 'https://mcp.example.com/mcp',
42 }),
43 },
44})
45
46export default {
47 async fetch(request: Request) {
48 return server.fetch(request)
49 },
50}
51```
52
534. Add your tools on the `tools` field.
54
55Now a request with no token, or with a bad token, gets 401. A request with a valid token from your provider calls your tools.
56
57## How it works
58
59An MCP server is an OAuth resource server. It does not sign users in:
60
61- Your authorization server signs the user in and issues the access token.
62- The MCP client sends that token on each request.
63- The MCP server checks the token with the `verifier`.
64
65`jwtVerifier` checks the signature, `iss`, `aud`, `exp`, and `nbf`. It reads the keys from `jwksUrl` and caches them. A token that fails one check gets 401.
66
67## Tell clients where to sign in
68
69An 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.
70
71```ts
72import {
73 createMCPServer,
74 getOAuthProtectedResourceMetadataUrl,
75 jwtVerifier,
76 oauthMetadataResponse,
77} from '@tanstack/ai-mcp/server'
78
79const mcpUrl = new URL('https://mcp.example.com/mcp')
80const metadata = {
81 resourceServerUrl: mcpUrl,
82 oauthMetadata: {
83 issuer: 'https://auth.example.com/',
84 authorization_endpoint: 'https://auth.example.com/oauth/authorize',
85 token_endpoint: 'https://auth.example.com/oauth/token',
86 response_types_supported: ['code'],
87 },
88}
89
90const server = createMCPServer({
91 name: 'notes',
92 version: '1.0.0',
93 auth: {
94 verifier: jwtVerifier({
95 jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
96 issuer: 'https://auth.example.com/',
97 audience: mcpUrl.href,
98 }),
99 resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(mcpUrl),
100 },
101})
102
103export default {
104 async fetch(request: Request) {
105 return oauthMetadataResponse(request, metadata) ?? server.fetch(request)
106 },
107}
108```
109
110The two documents:
111
112- `/.well-known/oauth-protected-resource/mcp` is the RFC 9728 document. It names your authorization server.
113- `/.well-known/oauth-authorization-server` is the RFC 8414 document. It is `oauthMetadata`, served as is.
114
115Copy `oauthMetadata` from the discovery document of your provider.
116
117## Read the caller in a tool
118
119The verified token is on `ctx.context.authInfo`. Give `.server()` the type `MCPToolContext`.
120
121```ts
122import { toolDefinition } from '@tanstack/ai'
123import type { MCPToolContext } from '@tanstack/ai-mcp/server'
124import { z } from 'zod'
125
126export const listNotes = toolDefinition({
127 name: 'list_notes',
128 description: 'List the notes of the signed-in user',
129 inputSchema: z.object({}),
130}).server<MCPToolContext>(async (_args, ctx) => {
131 const userId = ctx.context.authInfo?.extra?.sub
132 if (typeof userId !== 'string') {
133 throw new Error('This tool needs a signed-in user.')
134 }
135 return { userId, notes: [] }
136})
137```
138
139`authInfo` is `undefined` in two cases:
140
141- The server has no `auth`.
142- The client is `createMCPClient({ server })`.
143
144## Require a scope
145
146Pass `requiredScopes`. A token without one of those scopes gets 403 with `insufficient_scope`.
147
148```ts
149import { createMCPServer, jwtVerifier } from '@tanstack/ai-mcp/server'
150
151const server = createMCPServer({
152 name: 'notes',
153 version: '1.0.0',
154 auth: {
155 verifier: jwtVerifier({
156 jwksUrl: 'https://auth.example.com/.well-known/jwks.json',
157 issuer: 'https://auth.example.com/',
158 audience: 'https://mcp.example.com/mcp',
159 }),
160 requiredScopes: ['notes:read'],
161 },
162})
163```
164
165## Advanced
166
167### Verify an opaque token
168
169If 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.
170
171```ts
172import { createMCPServer, introspectionVerifier } from '@tanstack/ai-mcp/server'
173
174const server = createMCPServer({
175 name: 'notes',
176 version: '1.0.0',
177 auth: {
178 verifier: introspectionVerifier({
179 introspectionUrl: 'https://auth.example.com/oauth/introspect',
180 clientId: process.env.OAUTH_CLIENT_ID ?? '',
181 clientSecret: process.env.OAUTH_CLIENT_SECRET ?? '',
182 }),
183 },
184})
185```
186
187A token that is not `active` gets 401. If the endpoint is down, the caller gets 500.
188
189### Write your own verifier
190
191`verifier` is the `OAuthTokenVerifier` type from the MCP SDK. It has one method, `verifyAccessToken`. Return an `AuthInfo`, or throw `OAuthError` with `OAuthErrorCode.InvalidToken`.
192
193```ts
194import { OAuthError, OAuthErrorCode, createMCPServer } from '@tanstack/ai-mcp/server'
195import type { OAuthTokenVerifier } from '@tanstack/ai-mcp/server'
196import { findSession } from './sessions'
197
198const verifier: OAuthTokenVerifier = {
199 async verifyAccessToken(token) {
200 const session = await findSession(token)
201 if (session === undefined) {
202 throw new OAuthError(OAuthErrorCode.InvalidToken, 'Unknown token')
203 }
204 return {
205 token,
206 clientId: session.appId,
207 scopes: session.scopes,
208 expiresAt: session.expiresAt,
209 extra: { sub: session.userId },
210 }
211 },
212}
213
214const server = createMCPServer({
215 name: 'notes',
216 version: '1.0.0',
217 auth: { verifier },
218})
219```
220
221`expiresAt` is required. The SDK rejects an `AuthInfo` without it.
222
223### Use the auth you already have
224
225Your 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`.
226
227Pass the verified token and your values to `server.handle`. The server skips its `auth` gate for that request. Every tool call, resource read, and resource list of that request reads your values on `ctx.context`.
228
229```ts
230import { server } from './mcp-server'
231import { verifyCaller } from './auth'
232
233export async function handleMcp(request: Request) {
234 const caller = await verifyCaller(request)
235 if (caller instanceof Response) return caller
236 return server.handle(request, {
237 authInfo: caller.authInfo,
238 context: { db: caller.db },
239 })
240}
241```
242
243`server.fetch(request)` stays a plain Fetch handler. `server.handle` is the same handler with options.
244
245In a tool, name the values that you expect with `MCPToolContext`:
246
247```ts
248import { toolDefinition } from '@tanstack/ai'
249import type { MCPToolContext } from '@tanstack/ai-mcp/server'
250import { z } from 'zod'
251import type { Db } from './db'
252
253export const listNotes = toolDefinition({
254 name: 'list_notes',
255 description: 'List the notes of the signed-in user',
256 inputSchema: z.object({}),
257}).server<MCPToolContext<{ db: Db }>>(async (_args, ctx) => {
258 return ctx.context.db.notes.list()
259})
260```
261
262- `authInfo` is the SDK `AuthInfo`. A tool or a resource reads it as `ctx.context.authInfo`.
263- `context` sits next to `authInfo`, `requestInput`, and `sample` on `ctx.context`. If one of your values has one of those three names, the built-in value wins.
264- `createMCPClient({ server })` passes no `context`.
265
266### Sessions and tasks per caller
267
268When the server has `auth`, each spec 2025 session and each task belongs to one caller:
269
270- The caller is the `clientId` of the token plus its `sub` claim.
271- A session belongs to the caller that opened it.
272- A task belongs to the caller that started it.
273- A request from another caller gets "not found".
274
275### Cookie sessions
276
277An 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.