Skip to main content
Sagara Gunathunga
Head of DevRel - IAM
View all authors

MCP Authorization: The Complete Developer Guide

Why MCP exists when we already have APIs​

Large language models can explain, summarize, and reason over whatever's in front of them. On their own, they can't retrieve private business data, inspect a live account, or approve a payment. They need a way to reach external data and tools, and the APIs that already do that job, REST, GraphQL, gRPC, still work fine underneath.

The problem isn't the APIs themselves. It's how applications integrate with them. Traditionally, a developer studies a system's documentation, maps its schemas, handles credentials, chooses endpoints, writes the integration logic, and ships it as application code. Add another system, and much of that work repeats.

The Model Context Protocol (MCP) standardizes the layer above these APIs. An MCP server describes the tools, resources, and prompts it offers, allowing compatible clients to discover and use those capabilities through a common protocol. The server can still call the same REST or GraphQL APIs that power the underlying business systems. MCP doesn't replace them; it provides a standard way to expose their capabilities to AI applications.

The real limitation is predetermined integration​

Traditional API integrations work well when an application follows a fixed workflow. Developers know which systems it needs to access, which operations to perform, and how the pieces fit together. Those decisions are made during development and shipped with the application.

But general-purpose AI agents work differently. An agent may need to access different systems or use capabilities that weren't anticipated when the application was built. With conventional integrations, supporting those capabilities often means writing and deploying additional application code.

MCP addresses this limitation by allowing compatible clients to discover available capabilities at runtime rather than relying entirely on integrations predetermined during development. Developers still need to configure connections, manage authorization, and enforce access controls, but they no longer need to build a separate tool-integration contract for every client-server combination.

What MCP standardizes​

MCP defines common roles, message formats, capability discovery, lifecycle behavior, and transport conventions. Instead of building a private integration between every AI application and service, the MCP client uses a common protocol while the MCP server adapts the underlying capabilities to it. That makes connections interoperable, not inherently trustworthy or safe.

What MCP does not replace​

MCP does not replace business APIs, data models, domain authorization, or the operational controls protecting them. Nor does it make model output deterministic. The useful mental model is not "MCP instead of REST." It is "MCP in front of, or alongside, existing capabilities so AI applications can discover and use them consistently."

Why static authorization breaks for agents​

Most API authorization starts from something a team can describe in advance. Developers decide which endpoints an integration may call, choose the scopes, write the code path, and review it before shipping. The caller might make dynamic choices within that code, but the reachable operations remain bounded by what was deployed.

An agent weakens that assumption at the root. A model reads the current prompt, discovers available tools, and decides at runtime which MCP server and tool can help. It might make a different choice for the same prompt next time, without anyone deploying new code. The available tools can also change as servers add or remove capabilities.

Picture a support agent connected to a ticketing MCP server. In one conversation, it only reads ticket status. In the next, using the same connection and acting for the same user, it needs to close or escalate a ticket. A permission decision made once, at connection time, cannot distinguish those tasks unless the authorization model supports incremental access.

Two answers look tempting here, and both are wrong.

  • Grant broad access up front so the agent has whatever it might plausibly need, and you've built a caller with more privilege than any individual task requires, a confused deputy waiting for the wrong prompt.

  • Define a permanent scope for every tool call, and you've coupled your permission model to an action surface that can change. The scope list risks becoming stale whenever tools are added, removed, or modified.

What works is a shift from relying solely on permissions granted before execution to enforcing authorization throughout it, with accountability afterward. Start narrow. Expand access only when the task requires it. Bind each token to its intended server and keep its lifetime short. Authorize the actual tool arguments, not just the tool name. Leave a record that can answer who acted, on whose authority, against what, and with what result.

You retain the underlying API's authorization controls while adding task-specific, time-boxed, auditable access for agent-driven operations.

Conventional fixed integrationAgent-driven MCP connection
Reachable operationsBounded by code written and deployed for the integrationSelected at runtime from discovered tools
Initial permission choiceMatched to a known integration designKept narrow, then expanded if the task requires it
Main enforcement pointsAPI gateway and endpoint policyToken boundary plus tool, arguments, target, and context
Blast-radius controlsPredefined client permissionsResource-bound, short-lived tokens and step-up authorization
AccountabilityApplication and API logsUser, client, delegated actor, tool, target, decision, and result

Why this is an authorization problem​

Authentication answers who an actor is. Authorization answers what that actor may do, based on scopes, roles, ownership, organizational policy, or the specific request. Delegation adds another question: whether one actor may act for another, within what boundaries, and for how long. An agent acting on a user's behalf must remain distinguishable from the user.

In a typical web application, these decisions are often handled within the same application boundary. With AI agents, the boundaries extend across independently operated systems. An AI application may authenticate a user once and then connect to several MCP servers on their behalf. Each server must independently determine what the client can access and which actions it can perform.

QuestionTypical evidenceDecision point
Who is the user?Login session, ID token, enterprise SSO assertionIdentity provider and MCP client
Which client is connecting?OAuth client_id and client metadataAuthorization server
May the client access this MCP server for the user?Audience-bound access token and scopesMCP server
May this exact tool run with these arguments?Roles, ownership, policy, consent, risk and request contextMCP server or policy service
May the MCP server call a downstream API?Separate downstream credential or delegated tokenDownstream API

A scope like files:write doesn't establish whether a user can overwrite finance/forecast.xlsx, whether a payment falls within a delegated limit, or whether an action requires human approval. The MCP server must evaluate these conditions before executing the tool. An access token grants access within a defined boundary, not blanket approval for every action.

Why MCP uses OAuth 2.1 instead of OAuth 2.0​

If you've worked with OAuth 2.0, most of this will be familiar. OAuth 2.1 narrows the choices rather than introducing a new framework.

OAuth 2.0 offered several grant types and left many security choices to implementers. That flexibility helped it spread across browsers, mobile apps, servers, and devices. It also left room for patterns later found to be unsafe. MCP builds on OAuth 2.1, which removes those older options.

AreaOriginal OAuth 2.0OAuth 2.1 baseline used by MCP
Authorization CodeSupportedSupported with PKCE required
Implicit grantDefinedRemoved
Password grantDefinedRemoved
Redirect URI comparisonHistorically implemented with varying strictnessExact matching required
Public clientsCould rely on weaker patternsUse Authorization Code with PKCE
MCP discovery and resource bindingNot definedAdded by the MCP authorization specification

PKCE binds the authorization request to the subsequent code exchange. An intercepted authorization code cannot be redeemed without the original verifier. MCP clients may connect to unfamiliar servers, making these protections particularly important against code interception and injection.

What OAuth 2.1 doesn't cover on its own. It doesn't tell an unfamiliar MCP client how to discover the authorization server, register itself, request a token for a specific MCP resource, or request additional scopes mid-task. MCP's authorization specification adds those requirements.

When MCP authorization applies​

MCP authorization is optional and depends on the transport. HTTP-based servers should follow the authorization specification. Servers using stdio should obtain credentials from the environment rather than implement the HTTP authorization flow.

DeploymentStarting position
Local stdio server used by one desktop clientUse local process and operating-system controls. Avoid inventing an OAuth flow inside stdio.
Remote Streamable HTTP server with public data onlyAuthorization may be unnecessary, but rate limits and abuse controls still apply.
Remote server accessing user or company dataUse the MCP OAuth authorization flow.
Remote server performing writes or high-impact actionsUse OAuth, tool-level policy, audit logs, and confirmation or step-up controls where risk requires them.
Service or scheduled agent with no user presentDo not force an interactive user flow. Evaluate the client-credentials extension and workload identity, while checking extension support.

A local stdio server runs as a subprocess, so adding OAuth between it and its client usually solves the wrong problem. Local controls still apply: process isolation, file permissions, secret storage, and command approval. If it calls a remote API, it must also protect the downstream credential.

How MCP authorization reached the current model​

MCP authorization changed quickly. An older example can be internally consistent and still describe a model the specification no longer uses.

2025-03-26 to 2025-06-18. The first authorization specification, 2025-03-26, placed authorization-server responsibilities alongside the MCP server, one component that both served tools and issued tokens. That kept a demo self-contained, and made every remote server responsible for far more identity infrastructure than a resource server should own. The 2025-06-18 revision split the two: the MCP server became a pure resource server, an authorization server became discoverable through Protected Resource Metadata (RFC 9728), and clients gained a required resource parameter (RFC 8707) binding a token to the server it was issued for.

2025-11-25. Client ID Metadata Documents arrived as a recommended registration mechanism alongside Dynamic Client Registration, OpenID Connect Discovery became an accepted alternative to RFC 8414, and incremental step-up scope consent was added.

2026-07-28, the current revision. Dynamic Client Registration was formally deprecated, with a twelve-month removal window. Issuer validation (RFC 9207) became required where advertised. Client credentials must now be bound to the issuing authorization server, so a client that persists a client ID must re-register if that authorization server changes.

An MCP server now acts as a resource server: it publishes authorization metadata, validates tokens issued for it, and enforces its own domain policies. It doesn't need to become an identity provider to expose tools.

Understanding the MCP authorization model​

The model has five roles, even when a single product performs several of them.

  • The resource owner: Usually this is the person who is using the AI application and can approve access. In an enterprise, policy may constrain or partially replace individual choice.

  • The MCP host: The host is the AI application that manages the user experience, model interaction, client instances, tool selection controls, and consent or confirmation UI. It can operate several MCP clients and may run several agents.

  • The MCP client: The MCP client is the protocol component inside an AI application, IDE, desktop application, or agent platform. In OAuth terms it is the client requesting an access token. The host application and MCP client are sometimes packaged together, but their responsibilities are not identical.

  • The MCP server as the protected resource: The MCP server is the protected resource, also called the resource server in OAuth. It exposes tools, resources, and prompts, receives the access token, validates that the token was issued for it, and makes the final authorization decision for each request.

  • The authorization server: The authorization server authenticates the user when necessary, obtains authorization, applies issuance policy, and creates access tokens for the MCP server. It may be operated with the MCP server or supplied by an external identity platform. The July 2026 MCP specification deliberately treats the MCP server as a resource server, so you do not need to turn every MCP server into a new identity provider (MCP authorization specification).

A product may combine these roles, but issuer validation, audience checks, and consent boundaries still need to remain separate.

Who should run the authorization server?​

For production, start with established authorization infrastructure rather than building an authorization server from scratch.

Embed it in the MCP server. This was the pattern described in the 2025-03-26 specification. It keeps a prototype self-contained but leaves your team responsible for login, sessions, consent, token security, and federation, on top of the MCP server itself. Rarely the right production choice unless identity is part of your product.

Use existing identity infrastructure. Your MCP server's protected resource metadata points to a standards-conformant authorization server, whether self-hosted or managed. You can reuse existing MFA, SSO, and federation capabilities rather than maintaining a separate identity system for MCP.

Share an authorization service across several MCP servers. This provides consistent trust, policy, and auditing across servers and organizations. However, each MCP server must still validate that tokens were issued for its own resource. A shared authorization server doesn't mean tokens should work everywhere.

Put common enforcement in a gateway. A gateway can publish or proxy discovery, validate tokens, apply rate limits, and enforce baseline policies across multiple servers. It still cannot determine whether a user may delete a specific document without the domain context available to the tool handler.

Regardless of which approach you choose, the MCP server still needs a protocol and authorization enforcement layer.

How to choose the right architecture​

Choose based on the number of servers and organizations, identity requirements, deployment boundaries, audit obligations, and existing infrastructure. A shorter demo isn't enough reason to embed authorization.

For the MCP server, you can use an official SDK, a framework that handles metadata and token validation, or a gateway for common enforcement. Regardless of the approach, domain authorization stays with the tool handler. Check how the implementation constructs the resource URI, publishes Protected Resource Metadata, validates token audiences, and handles insufficient-scope challenges.

For the MCP client, supporting OAuth goes beyond attaching a bearer token. A general-purpose client needs resource and authorization-server discovery, client registration, PKCE, issuer and state validation, secure token storage, token refresh, and step-up authorization. Supporting one preconfigured authorization server is a valid choice, but it isn't the same as supporting arbitrary conformant servers.

For the authorization server, use established infrastructure rather than building your own. Verify its support for MCP requirements, including Resource Indicators, client registration mechanisms, and authorization-server discovery. Generic OAuth support doesn't guarantee MCP interoperability.

Client registration is a useful early test. Prefer an existing registration, then a Client ID Metadata Document when supported, followed by Dynamic Client Registration when available. Otherwise, request manually registered client credentials.

As you add servers and organizations, shared authorization infrastructure can simplify policy enforcement, auditing, and management.

The complete MCP authorization flow​

Unlike a preconfigured "Sign in with X" integration, an MCP client may connect to a server it has never seen. It must discover the authorization server and establish its client identity before requesting access.

Step 1: The client calls the protected MCP server​

The client makes an MCP request without a valid token. The server responds with 401 Unauthorized and a WWW-Authenticate challenge.

HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer
resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"
scope="documents:read"

The resource_metadata parameter tells the client where to learn about the protected resource. The optional scope tells it what permission is required for the request that failed. A client must also support the standardized well-known URI fallback when the header is absent.

Step 2: The client discovers Protected Resource Metadata​

The client fetches the metadata document described by RFC 9728. At minimum, an MCP protected resource document identifies the resource and one or more authorization servers.

{
"resource": "https://mcp.example.com/mcp",
"authorization_servers": [
"https://login.example.com"
],
"scopes_supported": [
"documents:read"
]
}

The MCP server publishes this document. It identifies the protected resource and its authorization servers; separate authorization-server metadata describes how to obtain tokens.

When more than one authorization server is listed, the client selects one according to RFC 9728 and must keep registration state, tokens, and credentials separate for each issuer. A client ID issued by one authorization server must never be assumed valid at another (MCP authorization-server discovery).

Step 3: The client discovers the authorization server​

The client reads OAuth Authorization Server Metadata or OpenID Connect Discovery metadata to find endpoints and supported capabilities, including:

  • Authorization and token endpoints
  • Supported scopes and response types
  • PKCE support
  • Dynamic Client Registration, when available
  • Client ID Metadata Document support
  • Issuer and token-endpoint authentication methods

Issuer URLs may contain tenant paths, so MCP defines an ordered set of OAuth and OIDC well-known locations that clients must try. If discovery fails, the client should return a useful configuration error rather than guessing /authorize or /token paths.

Step 4: The client establishes its identity​

OAuth needs a client identity. Enterprises can pre-register approved applications, but a general-purpose MCP client may encounter a new authorization server at any time.

The current specification supports three main mechanisms.

Pre-registration. The client already has a client ID for this authorization server, or the user enters one created by an administrator. This is predictable and works well for enterprise allowlists, but it does not scale to every public client and server pair.

Client ID Metadata Documents. The client uses an HTTPS URL as its client_id. The URL returns a JSON document containing the client name, redirect URIs, grant types, and other metadata. The authorization server fetches the document and validates that its internal client_id exactly matches the URL.

{
"client_id": "https://client.example.com/oauth/client.json",
"client_name": "Example AI Client",
"redirect_uris": ["http://127.0.0.1:3456/callback"],
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"],
"token_endpoint_auth_method": "none"
}

An authorization server can resolve this client identity without a prior registration. The underlying IETF specification was still an Internet-Draft (version 02) as of July 2026, so check for changes before implementing it (OAuth Client ID Metadata Document draft).

Dynamic Client Registration. The client sends its metadata to a registration endpoint and receives a client ID, using RFC 7591. It solved the no-prior-relationship problem in earlier MCP revisions, but it also asks every authorization server to expose a write endpoint that creates client registrations. MCP now retains DCR as a fallback rather than the preferred mechanism.

What changed in 2026-07-28?

New clients should no longer assume DCR is the default answer. The current model prioritizes an existing preregistration, then Client ID Metadata Documents when supported, with DCR retained as a deprecated compatibility mechanism. Older tutorials that immediately post to a registration endpoint describe an earlier interoperability model.

Step 5: The client starts Authorization Code with PKCE​

The client generates a high-entropy PKCE code verifier, derives an S256 code challenge, stores the verifier with the request state, and sends the user's browser to the authorization endpoint.

GET /authorize?
response_type=code&
client_id=https%3A%2F%2Fclient.example.com%2Foauth%2Fclient.json&
redirect_uri=http%3A%2F%2F127.0.0.1%3A3456%2Fcallback&
code_challenge=...&
code_challenge_method=S256&
resource=https%3A%2F%2Fmcp.example.com%2Fmcp&
scope=documents%3Aread&
state=...

The resource and scope parameters serve different purposes.

resource identifies the exact MCP server for which the token is requested. The client must include it in both the authorization request and token request, even when an authorization server does not advertise RFC 8707 support. This allows the resulting token to be audience-restricted to the MCP server.

What changed from early MCP OAuth implementations?

Resource Indicators are now mandatory. A token that is validly signed but intended for a different API or MCP server must be rejected.

scope describes the permissions currently needed. On the initial challenge, the client uses the scope from WWW-Authenticate when supplied. Otherwise, it uses the protected resource's scopes_supported, which should represent the minimal permissions needed for basic functionality.

PKCE protects the authorization code from interception or injection. Public clients such as desktop applications and CLIs cannot safely hold a shared client secret, so a secret embedded in their package is not a substitute for PKCE.

Step 6: The human authenticates and authorizes access​

The authorization server handles login, MFA, organizational policy, and consent in the browser. MCP doesn't prescribe that experience, and the client never needs to collect the user's password.

Consent should identify the client, server, requested permissions, and account or tenant. For sensitive scopes, explain what access allows. "Allow access to MCP" says too little when a server can delete repositories or approve payments.

Step 7: The client exchanges the code for tokens​

The authorization server redirects the browser to the registered URI with an authorization code. The client validates state, validates the issuer response according to RFC 9207 when present or advertised, and rejects mismatches before sending a code to any token endpoint. It then exchanges the code together with the original PKCE verifier and the same resource value.

POST /token
Content-Type: application/x-www-form-urlencoded

grant_type=authorization_code&
code=...&
redirect_uri=http%3A%2F%2F127.0.0.1%3A3456%2Fcallback&
client_id=https%3A%2F%2Fclient.example.com%2Foauth%2Fclient.json&
code_verifier=...&
resource=https%3A%2F%2Fmcp.example.com%2Fmcp

The response normally contains a short-lived access token. A refresh token may be issued, but clients must not assume one will be available. Refresh tokens must be protected in storage and transit; native clients should use operating-system-backed secure storage when possible rather than a plain configuration file.

Step 8: The client calls the MCP server​

The client sends the access token in the HTTP Authorization header on every request.

POST /mcp HTTP/1.1
Host: mcp.example.com
Authorization: Bearer eyJhbGciOiJSUzI1NiIs...
Content-Type: application/json
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: delete_document

Never put access tokens in query strings. URLs routinely appear in logs, browser history, analytics, and referrer data.

The last three headers are transport requirements rather than authorization ones. Since the 2026-07-28 revision, every Streamable HTTP request carries its protocol version and mirrors the JSON-RPC method and tool name into headers, so a gateway can route and log a call without parsing its body.

Step 9: The MCP server validates the token​

The MCP server validates JWTs locally or uses token introspection, depending on the token format. Verification must cover:

  • trusted issuer;

  • intended audience or resource;

  • expiry and not-before time;

  • required scopes;

  • token status or revocation where applicable;

  • tenant and subject context used by local policy.

An otherwise valid token issued for another API must be rejected. The MCP specification explicitly forbids token passthrough: a server must not accept or relay tokens that were not issued for that MCP server. This prevents a compromised or confused server from becoming a credential-forwarding proxy.

Step 10: The MCP server authorizes the requested tool operation​

Only after token validation should the request reach MCP dispatch. The handler then applies the authorization rules for the actual operation and arguments.

server.registerTool(
"delete_document",
{
description: "Delete a document",
inputSchema: z.object({ documentId: z.string() }),
scopeChallenge: requireScopes("documents:delete")
},
async ({ documentId }, ctx) => {
const principal = ctx.http?.authInfo;
if (!principal) throw new Error("Unauthenticated request");

const document = await documents.load(documentId);
requireSameTenant(principal, document);
requireOwnerOrRole(principal, document, "document-admin");
await requireHumanApprovalIfSensitive(principal, document);

await documents.remove(documentId);
await audit.record("document.deleted", {
actor: principal.extra?.subject,
client: principal.clientId,
documentId
});

return { content: [{ type: "text", text: "Document deleted" }] };
}
);

The registration follows the official TypeScript SDK v2 (@modelcontextprotocol/server), which implements the 2026-07-28 specification. scopeChallenge declares the scope this tool needs, and the SDK answers a token without it with the 403 insufficient_scope challenge that step-up depends on, before the handler runs. The verified token reaches the handler as ctx.http.authInfo. The policy helpers are application code: the SDK cannot know your tenants, ownership rules, approval thresholds, or audit schema. Token validation happens at the HTTP boundary; operation-level authorization happens inside the tool.

Implementing MCP authorization

The work splits into protocol enforcement, which an SDK and authorization server can largely handle, and domain authorization, which stays with your application because it depends on your tenants, ownership rules, and approval thresholds. Build in that order too: get a working, unauthenticated server first, then add auth rather than debugging both at once.

Scaffold the project. Initialize a Node.js project and install the official MCP TypeScript SDK v2 alongside Express. The SDK now ships separate packages for the server, Express integration, and Node.js HTTP adapter.

npm init -y
npm pkg set type=module
npm install @modelcontextprotocol/server @modelcontextprotocol/express @modelcontextprotocol/node express zod dotenv
npm install -D typescript tsx @types/express @types/node

Build the server with no auth first. Register a tool and expose it over Streamable HTTP. Confirm the tool works before adding authorization.

import { createMcpExpressApp } from "@modelcontextprotocol/express";
import { toNodeHandler } from "@modelcontextprotocol/node";
import { createMcpHandler, McpServer } from "@modelcontextprotocol/server";
import * as z from "zod/v4";

function buildServer(): McpServer {
const server = new McpServer({
name: "documents-server",
version: "1.0.0"
});

server.registerTool(
"delete_document",
{
description: "Simulate deleting a document",
inputSchema: z.object({ documentId: z.string() })
},
async ({ documentId }) => ({
content: [{
type: "text",
text: `Simulated deletion of ${documentId}`
}]
})
);

return server;
}

const app = createMcpExpressApp();
const mcp = toNodeHandler(createMcpHandler(buildServer));

app.all("/mcp", (req, res) => {
void mcp(req, res, req.body);
});

app.listen(3000);

The v2 SDK uses createMcpHandler to handle MCP requests and creates a server instance through buildServer. You no longer need to create and manage the HTTP transport manually.

Test it before adding auth. Start the server using npx tsx server.ts, then launch MCP Inspector:

npx @modelcontextprotocol/inspector

Open the Inspector interface, select Streamable HTTP, and connect to http://localhost:3000/mcp. Confirm the tool lists and runs.

Add auth. This is where your choice of authorization server becomes concrete code rather than an abstract decision. Install an MCP-aware auth SDK for your authorization server. This walkthrough uses WSO2 Identity Platform's @asgardeo/mcp-express package, which provides OAuth discovery endpoints and Express middleware for protecting MCP requests.

npm install @asgardeo/mcp-express

Configure your organization in a .env file:

BASE_URL=https://api.asgardeo.io/t/<your-org>

Then add the authorization middleware to the existing Express application:

import "dotenv/config";
import { configuredAuthServer as auth } from "@asgardeo/mcp-express";

app.use(auth.router());

// Replace the previous unprotected /mcp route.
app.all("/mcp", auth.protect(), (req, res) => {
void mcp(req, res, req.body);
});

auth.router() publishes the OAuth discovery metadata that tells MCP clients where to request authorization. auth.protect() validates the access token before allowing the request to reach the MCP handler.

Keep the resource identifier and token audience consistent with your authorization server's configuration. MCP servers must reject tokens issued for another resource. Check the authorization SDK's audience-validation behavior before using it in production.

Register your test client, then test with auth. Register the MCP server and its scopes in the WSO2 Identity Platform Console. Create an MCP Client Application, configure the Inspector's OAuth redirect URL, and authorize the application to access the MCP server.

Enter the resulting client_id in Inspector's authentication settings and complete the OAuth flow. Once connected, Inspector sends an access token with subsequent requests, which the middleware validates before the tool can run.

Beyond this walkthrough, keep the domain policy separate from the protocol check. With verified authorization context available to the MCP handler, a protected tool can enforce its own rules:

server.registerTool(
"delete_document",
{
description: "Delete a document",
inputSchema: z.object({ documentId: z.string() })
},
async ({ documentId }, ctx) => {
const principal = ctx.http?.authInfo;

requireScope(principal, "documents:delete");

const document = await documents.load(documentId);

requireSameTenant(principal, document);
requireOwnerOrRole(principal, document, "document-admin");
await requireHumanApprovalIfSensitive(principal, document);

await documents.remove(documentId);

await audit.record("document.deleted", {
actor: principal.extra?.subject,
client: principal.clientId,
documentId
});

return {
content: [{ type: "text", text: "Document deleted" }]
};
}
);

The policy helpers and document service are application code. The handler also assumes the authorization middleware provides verified AuthInfo to the v2 SDK; that handoff must be implemented and tested for the chosen integration.

No SDK knows your tenants, ownership rules, or approval thresholds. Validate the token at the HTTP boundary, then authorize the tool and its arguments before performing the operation. Test denied requests as well as successful ones, since a working OAuth login won't reveal cross-tenant access or incorrect audience validation.

Applying just-enough access​

Just-enough access limits permissions to the current task. Just-in-time access requests them only when the task needs them. MCP supports initial scope requests and step-up authorization, but your application must still define the policy.

Consider an agent helping with support tickets. Reading a ticket may require tickets:read. Adding a private note may require tickets:write. Closing a ticket may require tickets:close plus confirmation when the account is high value. The client should not request all three during its first connection simply because the server exposes all three tools. It begins with the access needed for the current work, receives a scope challenge only if the plan reaches a stronger operation, and asks for that stronger authority at that point.

Scope and duration both constrain access. A broad five-minute grant can still be dangerous; a narrow ninety-day grant may last far longer than necessary. Higher-risk operations may need shorter-lived tokens, stronger approval, resource constraints, and revocation rules.

Don't authorize an action solely from the model's interpretation of the user's intent. Prompts can be manipulated and interpretations can change. Evaluate concrete inputs instead: operation, resource, tenant, amount, sensitivity, risk, approval state, and time window. The agent proposes an action; policy determines whether it can run.

Applying just-in-time access​

When the current token is otherwise valid but lacks a required capability, the server returns 403 Forbidden with error="insufficient_scope", the complete scopes needed for that operation, and the resource-metadata location. This distinguishes step-up from missing or invalid authentication.

The client requests the union of previously requested scopes and newly required scopes. Failing to preserve the earlier set can replace rather than extend the grant, causing an authorization loop as the task alternates between operations.

Clients should detect repeated challenges for the same scope set, cap retries, and surface a comprehensible error. Servers should return all scopes required for the operation at once. Authorization servers should make denial explicit rather than redirecting indefinitely.

Stronger access should often expire sooner. A brief token for payments:approve or production:deploy reduces exposure after the action, especially when the initial read-only session may remain active for much longer.

OAuth does not automatically shrink a token when a task completes. Use short-lived elevated tokens, separate token caches, revocation, session termination, or policy-side task grants so exceptional authority does not silently become the next task's baseline.

Keeping a human in the loop​

Connection consent and action approval are separate. The first allows a client to access an MCP server. The second approves a particular operation. An OAuth consent screen doesn't replace transaction-specific approval.

For an online user, show action approval as close as practical to execution. The prompt should identify the tool, target, likely effect, account or tenant, and the authority being exercised. "Allow MCP access" is not meaningful consent for deleting a repository or approving a payment. At the same time, asking for confirmation before every read creates approval fatigue. Classify operations by impact and require fresh human involvement for irreversible, financially consequential, privacy-sensitive, or privilege-changing actions.

The connection experience should name the host or client, MCP server, authorization domain, account, and requested capability groups. The user should be able to distinguish authorizing a familiar enterprise server from sending credentials to an unknown domain.

Action approval should show resolved values, not only tool names: the document that will be deleted, the recipient and amount of a payment, the repository and branch of a deployment, or the people who will receive a message. Approval given before those values are known is weaker than it appears.

Some actions need reauthentication, MFA, a second approver, or out-of-band confirmation based on their risk, not simply because they use MCP.

Do not interrupt users for harmless reads and then expect careful attention to a critical payment prompt. Group low-risk operations into bounded grants, reserve explicit confirmation for meaningful consequences, and make denial or modification easy.

Refresh tokens provide continuity​

A refresh token can let an agent continue after the user leaves, provided the original grant remains valid. It renews access; it does not grant permission to take new kinds of actions.

That's only safe with preauthorized boundaries defining what the offline work is actually allowed to do: which tools and resources may be used, the maximum transaction values or number of changes permitted, the tenant or account involved, the time window the task may run in, and conditions that pause the task and request a fresh approval rather than proceeding past them. An offline agent that reaches one of those boundaries should stop, preserve its task state, and resume only after step-up authorization, not push through on the assumption that the original consent covers whatever comes next.

A related but distinct case has no consent moment to refer back to at all: a scheduled job or a CI pipeline authenticating as itself, not on behalf of any user. The Client Credentials extension is the specification's answer for that case specifically, additive to the core flow and requiring explicit client support to use. It should never be reached for as a shortcut to disguise a delegated human action as a machine one just to skip a consent screen; that's a misuse of the mechanism, not an efficient use of it.

Authorizing access to downstream APIs​

Many MCP tools wrap existing APIs. The MCP client authenticates to the MCP server, while the MCP server uses a separate credential for the downstream API.

Don't send the MCP client's access token to that downstream API unless the downstream API is genuinely the audience that token was issued for, and don't send a downstream token back to the MCP client either. Each token stays with the resource it was issued for, following the same resource-binding rule for both hops.

When a tool needs a user to connect a third-party account the server doesn't already have a credential for, the server itself acts as the OAuth client to that third party: it prompts the user with an authorization URL, completes that flow, and stores the resulting downstream token itself, correlated with the user who authorized it. That credential stays server-side and never travels back through an MCP response. This is also where delegation becomes concrete rather than conceptual: the server needs to know which user authorized the downstream connection, which account was connected, and whether the current request is allowed to use it.

Enterprise-managed authorization​

The stable enterprise-managed authorization extension addresses another problem: a user has already signed in to an enterprise MCP client, and the organization wants that identity and policy context to help obtain access to approved MCP servers without a separate manual consent ceremony for each connection.

The extension uses an identity assertion, token exchange, and a JWT authorization grant across the enterprise identity provider and the MCP server's authorization server. This gives administrators control over which clients, users, and servers may participate while keeping the final MCP access token audience-bound to the resource server (MCP Enterprise-Managed Authorization extension).

Treat this as an extension, not as the baseline flow every public client implements. It is most relevant when both client and server participate in an enterprise trust model.

Why the agent needs its own identity​

OAuth identifies the resource owner and MCP client, but not necessarily the individual agent that chose to invoke a tool.

An MCP host can run several agents. Two agents built on the same model may have different system instructions, tool grants, memory, organizational owners, or risk boundaries. Even the same agent software can run as separate instances for different departments and users. Recording only the human subject and application client_id can leave those executions indistinguishable.

A client_id usually identifies an application or deployment, not each agent or runtime instance it hosts.

A desktop assistant, IDE, or enterprise orchestration platform may host agents with different owners and purposes. Giving them all the host's undifferentiated authority prevents independent policy, revocation, and accountability.

Agent identity doesn't replace the identity of the user behind the request. The same agent may act for Alice in one tenant and Bob in another. Policy and audit need both.

System instructions, enabled tools, model version, memory sources, owner, and approved operating limits can materially change risk. Bind the agent identity to a governed configuration version or record that version alongside every consequential action.

The identity model therefore needs to keep at least three subjects separate:

IdentityWhat it tells you
Human or workloadWhose authority or business purpose stands behind the task
MCP client or hostWhich software established the connection
AgentWhich governed runtime actor selected and performed the operation

The current MCP authorization specification does not define a complete agent-identity lifecycle or a standard token claim for every agent instance. Do not invent one and present it as MCP compliance. Organizations can use workload identity, dedicated credentials, token exchange, or verifiable actor context, but these are architecture choices from the broader identity ecosystem.

Give each governed agent a stable identity linked to its owner and configuration. Restrict its tools, preserve actor context across authorized calls, and support independent revocation and audit.

Production readiness checklist​

MCP server​

  • Publish RFC 9728 Protected Resource Metadata for the canonical MCP endpoint.

  • Return a useful WWW-Authenticate challenge on 401 responses.

  • Validate issuer, audience, expiry, token status, and scopes before MCP dispatch.

  • Reject tokens not issued for this MCP resource.

  • Return 403 with insufficient_scope and all scopes needed for the current operation.

  • Enforce tenant, ownership, object, transaction, and risk policy inside tool handlers.

  • Keep downstream credentials separate from MCP access tokens.

  • Redact secrets and sensitive arguments from logs.

  • Record user, client, tool, target, decision, and outcome in audit events.

  • Record the governed agent identity when it differs from the OAuth client.

  • Define which operations require transaction-specific human approval.

  • Test denial paths, not only the successful connection.

MCP client​

  • Support both header-directed and well-known Protected Resource Metadata discovery.

  • Validate authorization-server metadata and bind state to the selected issuer.

  • Follow the registration priority: pre-registration, Client ID Metadata Document, DCR fallback, then manual registration.

  • Use Authorization Code with S256 PKCE for interactive public-client flows.

  • Send the same canonical resource in authorization and token requests.

  • Validate state and authorization-response issuer information.

  • Store access and refresh tokens using platform-appropriate protected storage.

  • Keep tokens and registrations isolated by MCP resource and authorization server.

  • Accumulate previously requested scopes during step-up authorization.

  • Explain which client, server, account, and permissions the user is connecting.

  • Preserve and resume task state safely when offline work requires human escalation.

Authorization server​

  • Provide OAuth Authorization Server Metadata or OIDC Discovery.

  • Support public clients and Authorization Code with S256 PKCE.

  • Support the MCP deployment's chosen registration mechanisms.

  • Issue access tokens restricted to the requested MCP resource.

  • Apply user, client, organization, scope, and consent policy before issuance.

  • Use short-lived access tokens and secure refresh-token policy.

  • Support key rotation, revocation, audit, and incident response.

  • Verify interoperability with real MCP clients, not only a generic OAuth test client.

  • Keep agent, client, user, and organization policy distinguishable in issued or exchanged credentials.

MCP Server Auth vs MCP Client Auth: Two Different Problems

A couple of years ago, there was no such thing as MCP. Now, chances are, you're building an MCP server, integrating with one as a client, or doing both on the same project within the same few weeks (often without anyone on the team stopping to ask which one they're actually doing). It's become common for developers to start that work with the line between the server role and the client role still blurry, especially where authorization, identity, and overall security are concerned, since the protocol reads as one specification and doesn't go out of its way to tell you that you're actually building two different things.

The Architect's Guide to React Authentication: Choosing a Flow, a Store and a Boundary

You may be asked to add login and user sign-up to your React application.

It sounds like an implementation task, but before you choose an SDK or write any code, there are a few architecture decisions you need to get right. Where should identity live? Who should be responsible for it? What should reach the browser? How should your React application connect to it? And when the application calls a backend, where should access actually be enforced?

React Authentication: The Complete Guide

Most React authentication tutorials open by installing a package. That's the wrong first move, because the install command you run is the last decision in the chain, not the first. Before it you have to decide something more basic: who your app trusts to vouch for a user's identity, where the proof of that gets stored once you have it, what the browser is allowed to know, and which server actually enforces the answer. Later sections put names to these decisions, OAuth 2.0, OpenID Connect, PKCE, but the decisions themselves come first, and you can reason about all four before you know a single one of those names.

This guide is for React developers who want to understand that chain rather than copy it. We'll cover what frontend authentication actually means inside a single-page app, why React authentication differs from server-rendered login, the four real ways to get it, the sequence OAuth 2.0 and OpenID Connect now require, where tokens should live, and how to wire a working sign-in.