
Building an MCP Server with OAuth Authorization (2026): A Tested, Step-by-Step Guide
A local MCP server is easy to trust. It runs as a child process on your own machine, with your own permissions. A remote MCP server is a different animal. It sits on the internet, many clients connect to it, and each tool call may read or change real data. It needs to know who is calling and what they are allowed to do.
The Model Context Protocol answers that question with OAuth. Your MCP server becomes an OAuth resource server, a separate authorization server issues the tokens, and clients discover everything through standard metadata documents. The design is sound, but there are many moving parts, and most tutorials skip the checks that actually keep a server safe.
This guide builds a remote MCP server with OAuth from scratch, using the official TypeScript SDK. It covers token validation, the discovery documents, per-tool scopes, and the step-up flow that asks for more permission when a tool needs it. It also explains what changes for user-facing clients, and how to choose an authorization server.
I tested everything end to end. The server runs on @modelcontextprotocol/server 2.4.0, and the test client uses @modelcontextprotocol/client 2.4.0. A small test authorization server issues real signed tokens. Seventeen checks passed, covering rejected tokens, the discovery flow, per-record access, a scope hierarchy, and a full step-up attempt. The protocol facts come from the MCP specification, version 2026-07-28, which I read on November 30, 2026.
This article builds on my MCP servers guide, which covers the protocol basics, and my OAuth 2.1 and OpenID Connect guide, which explains the OAuth side in depth.
Table of Contents
- The Short Answer
- When an MCP Server Needs OAuth
- The Three Roles
- What the Specification Requires
- How Discovery Works
- Build the Server
- A Test Authorization Server
- Testing It End to End
- User-Facing Clients
- Choosing an Authorization Server
- Designing Scopes
- Calling Downstream APIs
- Production Checklist
- Common Mistakes
- Frequently Asked Questions
- Conclusion
- References
1. The Short Answer
Your MCP server never runs the login flow itself. It checks tokens that a separate authorization server issued, and it tells clients where that server is.
| Job | How |
|---|---|
| Tell clients where to log in | Serve Protected Resource Metadata (RFC 9728) and point to it from every 401 response |
| Accept only your own tokens | Check the signature, issuer, expiry, and audience, which must be your server’s URL |
| Limit what each caller does | Require a base scope for every request, and extra scopes for sensitive tools |
| Ask for more when needed | Answer 403 insufficient_scope with the scopes the operation needs |
| Protect downstream systems | Never forward the client’s token, and use your own credentials or token exchange |
The official TypeScript SDK now ships helpers for every row except the last one. You supply a token verifier, a few options, and your tools.
Security invariants: Reject any token whose audience is not your server, even one from your own authorization server. Never forward a client’s token to another service. Require a base scope on every request, and an extra scope on every sensitive tool. Answer bad or expired tokens with 401, and missing scopes with 403, both carrying
resource_metadata.
2. When an MCP Server Needs OAuth
Not every MCP server needs OAuth. The transport decides most of it.
- Stdio servers: The client starts the server as a local process. The specification says these servers should not follow the HTTP authorization flow, and should take credentials from the environment instead.
- Remote servers over Streamable HTTP: Anyone who can reach the URL can send requests. If the server exposes anything private, it needs authorization, and the MCP specification defines it with OAuth.
- Internal servers behind a gateway: Some teams put MCP servers behind an API gateway that already authenticates users. That can work, but the server should still check that each request carries a valid identity for it.
If your server reads or changes user data, assume it needs OAuth as soon as it leaves your laptop.
3. The Three Roles
OAuth splits the work between three parties. In MCP, they map like this.
- The MCP client is the OAuth client. It might be Claude Code, an IDE, or your own agent. It obtains tokens and sends them with each request.
- The authorization server authenticates users, asks for consent, and issues access tokens. It can be Keycloak, Auth0, Microsoft Entra ID, or any standards-compliant provider.
- The MCP server is the OAuth resource server. It validates tokens and serves tools, resources, and prompts.
The specification is explicit that these are separate roles. Your MCP server can run its own authorization server, but it does not have to, and usually it should not. Identity is a large, security-critical product, as my OAuth guide explains.
4. What the Specification Requires
The authorization section of the 2026-07-28 specification sets these rules for servers. I quote the requirement level as the specification states it.
| Requirement | Level |
|---|---|
| Implement OAuth 2.0 Protected Resource Metadata (RFC 9728) | MUST |
| Validate access tokens as OAuth 2.1 section 5.2 describes | MUST |
| Accept only tokens issued specifically for this server as the audience | MUST |
| Answer invalid or expired tokens with HTTP 401 | MUST |
| Never accept or pass through any other tokens | MUST NOT |
| Account for scope hierarchies when judging whether a token is sufficient | MUST |
Include a scope parameter in the WWW-Authenticate challenge |
SHOULD |
Answer insufficient scope with 403 and error="insufficient_scope" |
SHOULD |
| Include all scopes the current operation needs in one challenge | SHOULD |
Avoid advertising offline_access in challenges or scopes_supported |
SHOULD NOT |
Clients have their own list. They must use the Protected Resource Metadata to find the authorization server. They must send the RFC 8707 resource parameter in both the authorization and the token request. They must check the iss parameter in the authorization response when the server sends it. Client registration also changed: Client ID Metadata Documents are now the preferred method, and Dynamic Client Registration is deprecated.
The good news for server authors is that the client side is the SDK’s job. Your work is the resource server side.
5. How Discovery Works
A client that has never seen your server knows only its URL. Everything else follows from the first rejected request.
Client MCP server Authorization server
| POST /mcp (no token) | |
|------------------------------->| |
| 401 WWW-Authenticate: Bearer | |
| resource_metadata="..." | |
|<-------------------------------| |
| GET /.well-known/oauth-protected-resource/mcp |
|------------------------------->| |
| { resource, authorization_servers, scopes_supported } |
|<-------------------------------| |
| GET /.well-known/oauth-authorization-server ------------------->|
|<------------------------------------ { token_endpoint, ... } ----|
| POST /token (resource=https://.../mcp, scope=...) ------------->|
|<------------------------------------------- access token -------|
| POST /mcp Authorization: Bearer <token> |
|------------------------------->| verify signature, issuer, |
| | expiry, audience, scopes |
| 200 result | |
|<-------------------------------| |
Three details make this work.
- The 401 points to the metadata. The
resource_metadataparameter inWWW-Authenticategives the URL of the Protected Resource Metadata document. The path of your MCP endpoint is part of that URL, so one host can serve several MCP servers. - The metadata names the authorization server. The client then reads the authorization server’s own metadata, using RFC 8414 or OpenID Connect discovery.
- The
resourceparameter sets the audience. The client asks for a token for your server’s exact URL. A good authorization server puts that URL in the token’s audience, and your server rejects tokens with any other audience.
6. Build the Server
The example is a small invoice server with two tools. Listing invoices needs the invoices:read scope. Creating an invoice also needs invoices:write.
Set up the project
mkdir invoice-mcp && cd invoice-mcp
npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server @modelcontextprotocol/client zod
The jose library, which the code uses to verify JWTs, arrived as a dependency of the SDK in my install. Add it to your own package.json explicitly, because you import it directly.
The complete server
// server.mjs: an MCP server that acts as an OAuth 2.1 resource server.
import http from "node:http";
import {
McpServer,
createMcpHandler,
requireBearerAuth,
oauthMetadataResponse,
getOAuthProtectedResourceMetadataUrl,
OAuthError,
OAuthErrorCode,
} from "@modelcontextprotocol/server";
import { createRemoteJWKSet, jwtVerify } from "jose";
import { z } from "zod";
const AUTH_ISSUER = process.env.AUTH_ISSUER ?? "http://localhost:9400";
const SERVER_URL = new URL(
process.env.SERVER_URL ?? "http://localhost:9401/mcp",
);
// 1. Verify access tokens: signature, issuer, expiry, and audience.
const jwks = createRemoteJWKSet(new URL(`${AUTH_ISSUER}/jwks`));
const verifier = {
async verifyAccessToken(token) {
try {
const { payload } = await jwtVerify(token, jwks, {
issuer: AUTH_ISSUER,
audience: SERVER_URL.href, // RFC 8707: only tokens minted for this server
algorithms: ["RS256"],
typ: "at+jwt",
});
return {
token,
clientId: String(payload.client_id ?? payload.sub),
scopes: String(payload.scope ?? "")
.split(" ")
.filter(Boolean),
expiresAt: payload.exp,
resource: SERVER_URL,
extra: { subject: payload.sub },
};
} catch (err) {
throw new OAuthError(
OAuthErrorCode.InvalidToken,
`token rejected: ${err.code ?? err.message}`,
);
}
},
};
// 2. Advertise the authorization server (RFC 9728 Protected Resource Metadata).
const metadataOptions = {
oauthMetadata: await (
await fetch(`${AUTH_ISSUER}/.well-known/oauth-authorization-server`)
).json(),
resourceServerUrl: SERVER_URL,
scopesSupported: ["invoices:read", "invoices:write"],
resourceName: "Invoice MCP server",
dangerouslyAllowInsecureIssuerUrl: AUTH_ISSUER.startsWith("http://localhost"), // local tests only
};
const resourceMetadataUrl = getOAuthProtectedResourceMetadataUrl(SERVER_URL);
// 3. Every MCP request needs a valid token with at least invoices:read.
const gate = requireBearerAuth({
verifier,
requiredScopes: ["invoices:read"],
resourceMetadataUrl,
expectedResource: SERVER_URL,
});
// 4. The MCP server itself. Writing needs an extra scope, checked per tool.
const invoices = [
{ id: "INV-1", owner: "reader-app", customer: "Acme", total: 1200 },
{ id: "INV-2", owner: "writer-app", customer: "Initech", total: 800 },
];
// invoices:admin implies invoices:write, so accept either for writes.
// requireScopes() matches exact names, so hierarchies need a small handler like this.
const canWrite = ({ authInfo }) => {
const scopes = authInfo?.scopes ?? [];
if (scopes.includes("invoices:write") || scopes.includes("invoices:admin"))
return undefined;
return { scopes: ["invoices:read", "invoices:write"] };
};
function createServer() {
const server = new McpServer({ name: "invoices", version: "1.0.0" });
server.registerTool(
"list_invoices",
{
description: "List invoices visible to the caller.",
inputSchema: z.object({}),
annotations: { readOnlyHint: true },
},
async (_args, ctx) => {
const auth = ctx.http?.authInfo;
// Object-level authorization: scopes allow listing, ownership decides which rows.
const isAdmin = auth?.scopes.includes("invoices:admin");
const visible = invoices.filter(
(inv) => isAdmin || inv.owner === auth?.clientId,
);
return {
content: [
{
type: "text",
text: JSON.stringify({ caller: auth?.clientId, invoices: visible }),
},
],
};
},
);
server.registerTool(
"create_invoice",
{
description: "Create a new invoice.",
inputSchema: z.object({
customer: z.string().min(1),
total: z.number().positive(),
}),
scopeChallenge: canWrite,
},
async ({ customer, total }, ctx) => {
const invoice = {
id: `INV-${invoices.length + 1}`,
owner: ctx.http?.authInfo?.clientId,
customer,
total,
};
invoices.push(invoice);
return { content: [{ type: "text", text: JSON.stringify(invoice) }] };
},
);
return server;
}
const handler = createMcpHandler(createServer, {
onerror: (e) => console.error("mcp error:", e.message),
});
// 5. One web-standard fetch function: discovery documents, then the auth gate, then MCP.
export async function fetchHandler(request) {
const discovery = oauthMetadataResponse(request, metadataOptions);
if (discovery) return discovery;
if (new URL(request.url).pathname !== SERVER_URL.pathname)
return new Response("Not found", { status: 404 });
const auth = await gate(request);
if (auth instanceof Response) return auth;
return handler.fetch(request, { authInfo: auth });
}
// 6. A minimal node:http adapter. In real projects, use toNodeHandler from @modelcontextprotocol/node.
export const mcpHttpServer = http.createServer(async (req, res) => {
const chunks = [];
for await (const c of req) chunks.push(c);
const request = new Request(new URL(req.url, SERVER_URL.origin), {
method: req.method,
headers: req.headers,
body: ["GET", "HEAD"].includes(req.method)
? undefined
: Buffer.concat(chunks),
});
const response = await fetchHandler(request);
res.writeHead(response.status, Object.fromEntries(response.headers));
if (response.body) for await (const chunk of response.body) res.write(chunk);
res.end();
});
How the pieces fit
The verifier is the only part the SDK cannot write for you, because it depends on your authorization server. This one validates a JWT locally against the server’s published keys. It pins the algorithm, checks the issuer and the audience, and requires the at+jwt type that RFC 9068 defines for JWT access tokens. That last check stops an ID token from being used as an access token. Note that the SDK rejects any token whose expiresAt is missing, so the verifier must fill it. Some authorization servers put the resource identifier in a custom claim instead of aud. In that case, read it from that claim, and still return it as resource, so the gate can compare it with your server’s URL.
The audience check is the most important line. audience: SERVER_URL.href means a token minted for another service is rejected, even when it is signed by the same authorization server. The expectedResource option on the gate checks the same thing a second time, using the resource value the verifier returns.
If you ship only one check, ship the audience check. A token that your authorization server issued for any other resource must be rejected. Skipping it is one of the most common real-world mistakes, because the token still looks valid: right signature, right issuer, not expired.
The metadata options feed oauthMetadataResponse. It serves two documents: your Protected Resource Metadata, and a copy of the authorization server’s metadata for older clients that look on your host. The dangerouslyAllowInsecureIssuerUrl flag exists only because my test authorization server runs on plain HTTP on localhost. The SDK refuses non-HTTPS issuers outside localhost unless you set it.
The gate from requireBearerAuth returns either the verified token information or a ready-made error response. It enforces the base scope for every request, and it adds the resource_metadata parameter to every 401 and 403 challenge.
Keep the base scope even though each tool can check its own. It rejects tokens that grant nothing for this API before any MCP processing happens, including tool listing. It also tells clients which scope to ask for first, as section 8 shows.
The scope challenge on create_invoice runs after authentication, inside the MCP handler. The SDK’s requireScopes helper would work here, but it matches exact names only. This server defines invoices:admin as implying write access, so a small canWrite function accepts either scope. When neither is present, it returns the scopes to request, and the SDK answers 403 with exactly those in the challenge. That matches the specification’s advice to include every scope the operation needs in one challenge.
The tool callbacks read the caller through ctx.http.authInfo. list_invoices uses it for object-level authorization: a normal client sees only the invoices it owns, and only an admin sees all of them. Scopes say what kind of action is allowed, and your code still decides which records the caller may touch. create_invoice records the caller as the new invoice’s owner.
The Node adapter at the bottom is deliberately minimal. The SDK’s handler speaks web-standard Request and Response, so it runs unchanged on Cloudflare Workers, Deno, and Bun. For Express, Fastify, or plain Node in production, use the official @modelcontextprotocol/node adapter instead of my twelve lines.
7. A Test Authorization Server
To test the server for real, I needed something that issues real signed tokens. This tiny authorization server does that. It supports RFC 8414 metadata, a key set endpoint, and the client_credentials grant with the resource parameter. It knows three clients: one allowed to read, one allowed to read and write, and one with read and admin rights. Its issueToken helper also lets the tests mint unusual tokens on purpose, such as one with the wrong issuer or no scope claim.
Never use it in production. It has no user login, no consent, no rate limiting, and in-memory secrets. It exists only so the tests exercise real JWT signatures and real OAuth error responses.
// auth-server.mjs: a tiny TEST authorization server. Never use it in production.
// Supports RFC 8414 metadata, a JWKS endpoint, and the client_credentials grant
// with client_secret_basic and the RFC 8707 resource parameter.
import http from "node:http";
import { generateKeyPair, exportJWK, SignJWT } from "jose";
export const ISSUER = "http://localhost:9400";
const { publicKey, privateKey } = await generateKeyPair("RS256");
const jwk = {
...(await exportJWK(publicKey)),
kid: "test-key-1",
alg: "RS256",
use: "sig",
};
// Registered clients and the scopes each one may receive.
const CLIENTS = {
"reader-app": { secret: "reader-secret", allowed: ["invoices:read"] },
"writer-app": {
secret: "writer-secret",
allowed: ["invoices:read", "invoices:write"],
},
"admin-app": {
secret: "admin-secret",
allowed: ["invoices:read", "invoices:admin"],
},
};
export async function issueToken({
clientId,
scopes,
audience,
ttl = 300,
issuer = ISSUER,
}) {
const claims = { client_id: clientId };
if (scopes) claims.scope = scopes.join(" "); // tests can omit the scope claim entirely
return new SignJWT(claims)
.setProtectedHeader({ alg: "RS256", kid: "test-key-1", typ: "at+jwt" })
.setIssuer(issuer)
.setAudience(audience)
.setSubject(clientId)
.setIssuedAt()
.setExpirationTime(Math.floor(Date.now() / 1000) + ttl)
.sign(privateKey);
}
const json = (res, status, body) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(body));
};
export const authServer = http.createServer(async (req, res) => {
const url = new URL(req.url, ISSUER);
if (url.pathname === "/.well-known/oauth-authorization-server") {
return json(res, 200, {
issuer: ISSUER,
authorization_endpoint: `${ISSUER}/authorize`, // not implemented in this test server
token_endpoint: `${ISSUER}/token`,
jwks_uri: `${ISSUER}/jwks`,
grant_types_supported: ["client_credentials"],
token_endpoint_auth_methods_supported: ["client_secret_basic"],
response_types_supported: ["code"],
code_challenge_methods_supported: ["S256"],
});
}
if (url.pathname === "/jwks") return json(res, 200, { keys: [jwk] });
if (url.pathname === "/token" && req.method === "POST") {
let body = "";
for await (const chunk of req) body += chunk;
const form = new URLSearchParams(body);
const [id, secret] = Buffer.from(
(req.headers.authorization || "").replace(/^Basic /, ""),
"base64",
)
.toString()
.split(":")
.map(decodeURIComponent);
const client = CLIENTS[id];
if (!client || client.secret !== secret)
return json(res, 401, { error: "invalid_client" });
if (form.get("grant_type") !== "client_credentials")
return json(res, 400, { error: "unsupported_grant_type" });
const resource = form.get("resource");
if (!resource)
return json(res, 400, {
error: "invalid_target",
error_description: "resource is required",
});
const requested = (form.get("scope") || "").split(" ").filter(Boolean);
const granted = requested.filter((s) => client.allowed.includes(s));
if (requested.length && granted.length < requested.length) {
return json(res, 400, {
error: "invalid_scope",
error_description: `not allowed: ${requested.filter((s) => !granted.includes(s)).join(" ")}`,
});
}
const access_token = await issueToken({
clientId: id,
scopes: granted,
audience: resource,
});
return json(res, 200, {
access_token,
token_type: "Bearer",
expires_in: 300,
scope: granted.join(" "),
});
}
json(res, 404, { error: "not_found" });
});
The token’s audience is whatever resource the client asked for. That mirrors how RFC 8707 is meant to work, and it lets the tests mint a token for the wrong server on purpose.
A gotcha I hit
My first version of the metadata had no authorization_endpoint, because the test server only supports client_credentials. The SDK client refused it with a validation error before it ever asked for a token. RFC 8414 requires authorization_endpoint unless the server supports no grant type that uses it, and the SDK’s metadata schema treats the field as required. Real authorization servers always publish it, so this only bites test setups like mine.
8. Testing It End to End
The test starts both servers, sends raw HTTP requests to check the security behavior, and then connects two real SDK clients. Each client uses the ClientCredentialsProvider, which handles discovery and the token request on its own.
import {
Client,
StreamableHTTPClientTransport,
ClientCredentialsProvider,
} from "@modelcontextprotocol/client";
async function connect(clientId, secret, scope) {
const provider = new ClientCredentialsProvider({
clientId,
clientSecret: secret,
scope,
expectedIssuer: ISSUER,
});
const transport = new StreamableHTTPClientTransport(new URL(MCP), {
authProvider: provider,
});
const client = new Client({ name: "test-client", version: "1.0.0" });
await client.connect(transport);
return client;
}
const reader = await connect("reader-app", "reader-secret", "invoices:read");
const result = await reader.callTool({ name: "list_invoices", arguments: {} });
The expectedIssuer option matters. It ties the client’s credentials to one authorization server, so a compromised MCP server cannot redirect the client to send its secret somewhere else. The SDK marks the constructor without it as deprecated.
Results
| # | Check | Result |
|---|---|---|
| 1 | Request with no token gets 401 | Pass |
| 2 | The 401 carries resource_metadata pointing to the metadata document |
Pass |
| 3 | The metadata names the authorization server and both scopes | Pass |
| 4 | A token minted for another server gets 401 | Pass |
| 5 | An expired token gets 401 | Pass |
| 6 | A malformed token gets 401 | Pass |
| 7 | A valid token without invoices:read gets 403 insufficient_scope |
Pass |
| 8 | A token with the right audience but the wrong issuer gets 401 | Pass |
| 9 | A token with no scope claim at all gets 403 insufficient_scope |
Pass |
| 10 | A valid token gets 200 | Pass |
| 11 | The SDK reader client discovers, authenticates, and lists both tools | Pass |
| 12 | The reader sees only its own invoice, not another client’s | Pass |
| 13 | The reader cannot create an invoice | Pass |
| 14 | The tool call was answered 403 with both scopes in the challenge | Pass |
| 15 | The writer client creates an invoice, after a step-up | Pass |
| 16 | A token with invoices:admin can create an invoice, through the hierarchy |
Pass |
| 17 | The admin sees every invoice | Pass |
What the step-up attempt looked like
Checks 13 and 14 show the full step-up flow in action. I recorded every HTTP response the reader client received.
-
The reader called
create_invoicewith a read-only token. -
The server answered 403 with this challenge.
Bearer error="insufficient_scope", error_description="Insufficient scope", scope="invoices:read invoices:write", resource_metadata="http://localhost:9401/.well-known/oauth-protected-resource/mcp" -
The client did what the specification describes. It asked the token endpoint for a new token with both scopes.
-
The authorization server refused with
invalid_scope, because the reader app is not allowed to write. -
The client stopped and raised an
OAuthErrorwith the message “not allowed: invoices:write” instead of retrying forever.
That is the correct outcome. The decision about who may write lives in the authorization server, and the MCP server only states what each operation needs.
A surprise: the challenge decides the first scope
I configured the writer client to request invoices:read invoices:write. Its first token contained only invoices:read. I logged the scopes the server saw, and the writer reached create_invoice twice: first with read only, then with both scopes after a step-up.
The reason is the specification’s priority order for scope selection. A client should first use the scope parameter from the server’s 401 challenge, and that challenge said invoices:read, because the gate requires it. The SDK followed that rule, then stepped up when the write tool asked for more. Everything worked, at the cost of one extra token request.
The same rule caught out my admin client. It may hold invoices:admin, but not invoices:write. When the write tool challenged it for invoices:read invoices:write, the client asked for exactly those scopes, and the authorization server refused. The server would have accepted invoices:admin, but the challenge never mentioned it. Test 16 therefore uses an admin token issued directly.
Two practical lessons follow from this. First, the scopes in your challenges are what clients will request, so name scopes they can actually obtain. Second, if you use hierarchies, configure the authorization server so that a client allowed the broader scope can also obtain the narrower one your challenges name.
One more observation: the reader still saw create_invoice in its tool list. Scope checks happen when a tool is called, not when tools are listed. That is fine for this example, but if the mere existence of a tool is sensitive, filter the list yourself.
9. User-Facing Clients
My tests use the client_credentials grant, because a test cannot click through a login page. Most real MCP clients act on behalf of a person, so they use the authorization code flow with PKCE instead. Your server code does not change at all. The differences are all on the client and the authorization server.
- The user signs in at the authorization server, in a browser, and approves the requested scopes. The MCP client never sees the password.
- PKCE is always required. The client sends a code challenge and proves it holds the matching verifier when it redeems the code.
- The client sends
resourcein both the authorization request and the token request, so the token’s audience is your server. - The client checks
issin the authorization response before it redeems the code, which defends against mix-up attacks. - The client needs a client ID. The preferred way is a Client ID Metadata Document: the client’s ID is an HTTPS URL that serves a JSON document describing the client. Pre-registration with the authorization server also works. Dynamic Client Registration is deprecated but still allowed for older authorization servers.
A Client ID Metadata Document is a small JSON file that the client hosts. Its URL is the client ID. According to the current IETF draft, revision 03 from November 2, 2026, the URL must use HTTPS and have a path, and the document’s client_id must equal that URL exactly. Shared secrets are not allowed, so public clients use none as the authentication method. A minimal example looks like this.
{
"client_id": "https://app.example.com/oauth/client-metadata.json",
"client_name": "Example MCP Client",
"client_uri": "https://app.example.com",
"redirect_uris": ["https://app.example.com/oauth/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none"
}
The authorization server fetches the document when it first sees the client ID, and checks redirect URIs against it. The client needs no registration step.
The SDK’s client package implements this flow, including PKCE, the resource parameter, and the issuer check. My OAuth guide walks through each of these steps in detail.
10. Choosing an Authorization Server
Any standards-compliant OAuth server can work, but check these points before you commit.
| Requirement | Why it matters |
|---|---|
| RFC 8414 metadata or OpenID Connect discovery | Clients find the endpoints automatically |
| Authorization code flow with PKCE (S256) | Required for user-facing clients |
| A way to set the token audience to your server | The MCP server must reject tokens meant for anything else |
| Client ID Metadata Documents or pre-registration | Clients need a client ID, and Dynamic Client Registration is deprecated |
| JWT access tokens or token introspection | Your verifier needs some way to validate tokens |
| Scopes you define | Fine-grained permissions per tool |
The iss response parameter (RFC 9207) |
Recommended by the specification to stop mix-up attacks |
The audience requirement is the one to test first. Some providers honor the RFC 8707 resource parameter directly. Others use their own setting, such as an API identifier configured in the dashboard. Either way, mint a token, decode it, and confirm that its aud claim is your MCP server’s URL before you ship.
If your tokens are opaque instead of JWTs, write the verifier around token introspection (RFC 7662). The shape stays the same: return the client ID, scopes, expiry, and resource, or throw an InvalidToken error.
11. Designing Scopes
Scopes are the main way to limit what a client, and the model behind it, can do with your server. A few rules keep them useful.
- Name scopes by resource and action, such as
invoices:readandinvoices:write. Avoid one giantmcpscope, and never use wildcards like*orfull-access. - Require a small base scope for every request, as the gate does with
invoices:read. It proves the token was issued for your API at all. - Put extra scopes on dangerous tools, using
scopeChallenge. Writes, deletes, payments, and anything that sends data out of the system deserve their own scope. - Handle scope hierarchies correctly. The specification says a server must account for broader scopes that imply narrower ones. If you define
invoices:adminas including write, your checks must accept it for writes too. The simplerequireScopeshelper matches exact names, so write your ownscopeChallengefunction for hierarchies, likecanWritein section 6. Then read the surprise in section 8, because your challenges decide which scopes clients request. - Do not advertise
offline_access. The specification says servers should not list it, because refresh tokens are the client’s concern, not a requirement of your resource.
Scopes also help with the AI-specific risks in my prompt injection guide. A client that only holds read scopes cannot be tricked into writing, however persuasive the injected text is.
12. Calling Downstream APIs
Many MCP servers are wrappers around another API, such as a CRM or a ticket system. The tempting shortcut is to forward the client’s token to that API. The specification forbids it. MCP servers must not accept or transit tokens other than their own, and clients must not send them tokens meant for other services.
The reason is the confused deputy problem. If your server forwards whatever token it receives, it lets clients use your server to act on systems that never authorized them. It also breaks audit trails, because the downstream API cannot tell your server’s calls from the client’s.
You have two safe options.
- Use your server’s own credentials for the downstream API, and enforce per-user permissions in your code, based on the verified identity in
authInfo. - Use token exchange (RFC 8693) to swap the incoming token for a new, narrower token issued for the downstream API. The authorization server then decides what the downstream token may do.
If your server is a proxy in front of a third-party API with a single static client ID, read the confused deputy section of the MCP security best practices. It requires per-client consent and careful redirect handling, and it is easy to get wrong.
13. Production Checklist
- Use HTTPS for everything. Remove
dangerouslyAllowInsecureIssuerUrl, and serve both the MCP server and the authorization server over TLS. - Validate
OriginandHostheaders. The SDK exports helpers for this. They matter most for servers that also listen on localhost or a private network, where a malicious web page can reach them through DNS rebinding. - Cache the key set, and handle rotation.
createRemoteJWKSetcaches keys and refetches when it sees an unknown key ID. - Keep access tokens short-lived. Five to fifteen minutes is typical, since your server cannot revoke a JWT before it expires. Longer sessions belong to the authorization server’s refresh tokens, with rotation and revocation.
- Log decisions, not tokens. Record the client ID, subject, tool name, scopes, and outcome. Never log the bearer token itself.
- Rate-limit each client separately. A valid token is not permission to call a tool a million times.
- Check object-level permissions in every tool, using the verified identity.
- Pin the SDK version, and read the changelog before upgrades. The authorization parts of MCP have changed several times since 2025, so re-run your full authorization test suite after every SDK upgrade.
14. Common Mistakes
- Skipping the audience check. A token from the same authorization server, issued for a different API, would then work on your server.
- Forwarding the client’s token downstream. The specification forbids token passthrough.
- One scope for everything. A read-only client should never be able to call a write tool.
- Answering 403 when the token is invalid. Invalid or expired tokens get 401, and missing scopes get 403.
- Leaving out the
resource_metadataparameter. Without it, clients cannot discover your authorization server from the challenge. - Treating scopes as complete authorization. Scopes say what kind of action is allowed. Your code decides which records the caller may touch.
- Building a custom login flow inside the MCP server. Use an established authorization server instead.
- Shipping test shortcuts to production. Insecure issuer flags and test authorization servers belong in tests only.
- Relying on Dynamic Client Registration for new work. It is deprecated in favor of Client ID Metadata Documents.
- Logging the bearer tokens themselves. Logs leak, and a logged token works for anyone who finds it until it expires.
15. Frequently Asked Questions
Does every MCP server need OAuth?
No, it does not. Local stdio servers take credentials from their environment. Remote servers that expose private data or actions need authorization, and OAuth is the method the specification defines.
Can my MCP server also be the authorization server?
Yes, the specification allows it. It is still a separate role with its own endpoints and security duties. For most teams, a dedicated identity provider is safer and less work.
Do I need JWT access tokens?
No, you do not. JWTs let you validate tokens locally, which is fast. Opaque tokens with introspection work too, and they allow instant revocation. The SDK only needs a verifier that returns the token’s details.
How do I test without a real identity provider?
Do what I did. Run a small test authorization server that signs real tokens, and drive it with the SDK’s ClientCredentialsProvider. Then repeat a smaller test against your real provider before launch, to confirm the audience and scope claims.
What happens when a client lacks a scope?
Your server answers 403 with the needed scopes. A client acting for a user should start a step-up flow and ask the user to approve more access. A client_credentials client may try once or stop. In my test, it tried once, got invalid_scope, and stopped.
Is OAuth enough to make a remote MCP server safe?
No, it handles identity and permissions only. You still need input validation, rate limits, careful tool design, and defenses against prompt injection. OAuth makes sure the right client is calling. It cannot make sure the model behind that client is behaving.
16. Conclusion
A secure remote MCP server comes down to a few checks done well. Publish Protected Resource Metadata, point to it from every challenge, and accept only tokens whose audience is your server. Require a base scope for every request, and stronger scopes for every dangerous tool.
The 2026 TypeScript SDK makes most of this short. You write a verifier, configure the gate and the metadata, and add a scope challenge to sensitive tools. The tests showed the whole chain working: discovery, token validation, rejection of foreign and expired tokens, and a step-up attempt that ended correctly at the authorization server.
The hard decisions are outside the code. Choose an authorization server that sets the audience correctly, design scopes that match real risks, and never forward tokens downstream. MCP authorization has changed often, so treat this guide as accurate for the 2026-07-28 specification and SDK 2.4.0.
17. References
Specifications
- MCP specification: Authorization (2026-07-28)
- MCP: Security best practices
- RFC 9728: OAuth 2.0 Protected Resource Metadata
- RFC 8707: Resource Indicators for OAuth 2.0
- RFC 8414: OAuth 2.0 Authorization Server Metadata
- RFC 9068: JWT Profile for OAuth 2.0 Access Tokens
- RFC 6750: Bearer Token Usage
- RFC 8693: OAuth 2.0 Token Exchange
- IETF draft: OAuth Client ID Metadata Document