---
title: "Lock Down Every MCP Server Tool with OAuth 2.1 Scopes"
description: "Replace MCP server API keys with OAuth 2.1 scoped tokens. Configure Protected Resource Metadata, per-tool scopes, and JWT audience checks step by step."
canonical: "https://adamtheautomator.com/mcp-server-oauth-scopes/"
---

# Lock Down Every MCP Server Tool with OAuth 2.1 Scopes

> Replace MCP server API keys with OAuth 2.1 scoped tokens. Configure Protected Resource Metadata, per-tool scopes, and JWT audience checks step by step.

Source: https://adamtheautomator.com/mcp-server-oauth-scopes/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Lock Down Every MCP Server Tool with OAuth 2.1 Scopes](https://adamtheautomator.com/wp-content/uploads/publisher/4165d9c85b2b81cab1a9f6c2d4bf4f28/24b4612d776acd9f3268000b289022431818d0a88087d9b754ea38bf7c44c695.webp)

# Lock Down Every MCP Server Tool with OAuth 2.1 Scopes

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)23 November 202621 min. read

Categories: [AI Agents](/category/ai-agents/)

Tags:[Security](/tag/security/)[AI](/tag/ai/)[API](/tag/api/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Required Tools and Services](#required-tools-and-services)
*   [Background Knowledge](#background-knowledge)
*   [Why OAuth Beats API Keys for MCP Servers](#why-oauth-beats-api-keys-for-mcp-servers)
*   [What Scoped Tokens Stop That Keys Can’t](#what-scoped-tokens-stop-that-keys-cant)
*   [Understanding the MCP OAuth 2.1 Architecture](#understanding-the-mcp-oauth-21-architecture)
*   [Discovery Through Protected Resource Metadata](#discovery-through-protected-resource-metadata)
*   [Client Registration Options](#client-registration-options)
*   [The Authorization Code Flow with PKCE](#the-authorization-code-flow-with-pkce)
*   [Setting Up Protected Resource Metadata](#setting-up-protected-resource-metadata)
*   [The RFC 9728 Metadata Format](#the-rfc-9728-metadata-format)
*   [Building the Metadata Document](#building-the-metadata-document)
*   [Configuring Your Authorization Server](#configuring-your-authorization-server)
*   [Choosing an Authorization Server](#choosing-an-authorization-server)
*   [Registering Scopes and Clients](#registering-scopes-and-clients)
*   [Enabling RFC 9207 Issuer Validation](#enabling-rfc-9207-issuer-validation)
*   [Verifying the Metadata Endpoint](#verifying-the-metadata-endpoint)
*   [Implementing JWT Validation in Your MCP Server](#implementing-jwt-validation-in-your-mcp-server)
*   [What the Token Must Prove](#what-the-token-must-prove)
*   [JWT Validation Code Examples](#jwt-validation-code-examples)
*   [Mapping Tools to Scopes](#mapping-tools-to-scopes)
*   [Testing the OAuth Flow End-to-End](#testing-the-oauth-flow-end-to-end)
*   [Setting Up the Test Environment](#setting-up-the-test-environment)
*   [Testing the Initial Authorization](#testing-the-initial-authorization)
*   [Testing Step-Up Authorization](#testing-step-up-authorization)
*   [Testing Token Expiration](#testing-token-expiration)
*   [Troubleshooting Common OAuth Integration Errors](#troubleshooting-common-oauth-integration-errors)
*   [Error: invalid\_client During Token Exchange](#error-invalid_client-during-token-exchange)
*   [Error: invalid\_grant During Token Exchange](#error-invalid_grant-during-token-exchange)
*   [Error: invalid\_grant With “PKCE verification failed”](#error-invalid_grant-with-pkce-verification-failed)
*   [Error: HTTP 403 insufficient\_scope After the User Approves](#error-http-403-insufficient_scope-after-the-user-approves)
*   [Error: aud Claim Does Not Match the Resource URI](#error-aud-claim-does-not-match-the-resource-uri)
*   [Error: Infinite Redirect Loop Between Client and Authorization Server](#error-infinite-redirect-loop-between-client-and-authorization-server)
*   [Error: Client Ignores the HTTP 403 Step-Up Challenge](#error-client-ignores-the-http-403-step-up-challenge)
*   [Security Checklist Before Production](#security-checklist-before-production)
*   [Token and Scope Security](#token-and-scope-security)
*   [Client and Transport Security](#client-and-transport-security)
*   [What You Built](#what-you-built)

Stop shipping [Model Context Protocol (MCP)](https://modelcontextprotocol.io/specification/2026-07-28) servers with API keys. Picture the agent holding that key getting prompt-injected: every tool you registered, including the ones that write to your database, now answers to whoever hijacked it. Then go rotate that key in every client config you ever deployed, and hope nothing ran in the meantime.

Make every tool call prove it holds the right [OAuth 2.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13) scope instead. Publish [Protected Resource Metadata (RFC 9728)](https://datatracker.ietf.org/doc/html/rfc9728) so clients find your authorization server on their own, then validate each JSON Web Token (JWT) so a token minted for another service gets rejected at yours. Map every tool to the scopes it needs, and finish by running a real client through the full handshake, including the step-up prompt that asks the user for one more scope.

## Prerequisites

You’ll need an [HTTP-based MCP server](https://adamtheautomator.com/practical-guide-hosting-managing-remote-mcp/), an OAuth 2.1 authorization server, and a compatible MCP client to test the full flow.

### Required Tools and Services

Build the server with the [MCP TypeScript SDK](https://github.com/modelcontextprotocol/typescript-sdk) or another SDK that serves HTTP. [`stdio` servers](https://adamtheautomator.com/powershell-mcp-server-automate-windows-admin-tasks/) sit outside this tutorial because the [MCP authorization specification tells `stdio` implementations](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#protocol-requirements) to pull credentials from the environment instead of running OAuth. The authorization-server commands use Keycloak, and [Keycloak runs in a container](https://www.keycloak.org/server/containers), so you can prove the whole flow on localhost before anything touches production. [Auth0](https://auth0.com/ai/docs/mcp/guides/resource-param-compatibility-profile) or [WorkOS AuthKit](https://workos.com/docs/authkit/mcp) can fill the same role if they support the [RFC 8707 `resource` parameter](https://www.rfc-editor.org/rfc/rfc8707.html) covered below. The code samples need Node.js 20+ or Python 3.10+. If you’re on Node.js 18, run `npm install express jose@5` instead of the default `jose` version. The [MCP Inspector](https://github.com/modelcontextprotocol/inspector) requires Node.js 22.23.4 or later.

For end-to-end testing on localhost, use the MCP Inspector, which runs the authorization code flow with [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636). [Claude Desktop’s remote MCP connectors](https://support.claude.com/en/articles/11175166-getting-started-with-custom-connectors-using-remote-mcp) work once your MCP server and authorization server are deployed at public HTTPS URLs, because Claude connectors connect from Anthropic’s cloud rather than locally. A client without OAuth support still lets you check the server with `curl` and hand-requested tokens, but you won’t see the browser consent step.

### Background Knowledge

You should understand how OAuth 2.1 differs from OAuth 2.0: PKCE (RFC 7636) is mandatory for all clients, the implicit and password grants are gone, and bearer tokens must bind to the client that requested them. If “authorization code flow” and “code verifier” are new terms, read [OAuth 2.1 draft-13](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13) first.

## Why OAuth Beats API Keys for MCP Servers

The [Model Context Protocol 2026-07-28 specification](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization) states: “Authorization is **OPTIONAL** for MCP implementations.” On localhost, with one agent you trust, take the spec at its word. Once an agent reaches your server over HTTP, an API key hands it every tool you registered with no expiry and no scope limit, while an OAuth token expires, names the one server it works at, and covers only the scopes the user approved.

### What Scoped Tokens Stop That Keys Can’t

Start with an agent holding `files:read` that calls a tool needing `files:write`. With an API key, you either regenerate the key with write access for every client, so the read-only agent can now delete things too, or you leave writes broken. With scoped tokens, the server returns HTTP 403 with `insufficient_scope`, the client triggers step-up authorization, and the consent screen asks the user for `files:write` alone. The new token carries the old scopes plus the new one. If the agent later tries a tool that needs `database:admin` and the user never granted it, the server refuses with another 403. The agent can ask again, but it can’t [quietly promote itself](https://adamtheautomator.com/entra-agent-id-privilege-escalation/).

A second failure mode: token replay across services. [RFC 8707’s resource parameter rules](https://www.rfc-editor.org/rfc/rfc8707.html#section-2) require the client to include `resource=https://mcp.example.com/mcp` in token requests, and the authorization server mints a token with `"aud": "https://mcp.example.com/mcp"`. The MCP server rejects any token where the `aud` (audience) claim doesn’t match its own canonical URI (the exact URL clients put in the `resource` parameter). API keys have no equivalent; they work at any backend.

## Understanding the MCP OAuth 2.1 Architecture

Your MCP server is the OAuth 2.1 resource server. It checks each token against the tool being called and never sees the user’s password. Login and consent happen at a separate authorization server, which mints the tokens. The client drives the browser flow and retries the request when your server answers with a 403.

The diagram below shows the three roles and the status codes that pass between them.

![OAuth 2.1 MCP roles](https://adamtheautomator.com/wp-content/uploads/publisher/aac4551d386b0d84fab321ff6ae38c88734ffc9060804a255ed27bd20608dac6.jpg)

### Discovery Through Protected Resource Metadata

When the client makes an unauthenticated request, the MCP server responds with HTTP 401 and a `WWW-Authenticate` header pointing to its Protected Resource Metadata document. That document, published at `https://mcp.example.com/.well-known/oauth-protected-resource`, tells the client which authorization servers the resource trusts, which scopes it supports, and where to send bearer tokens (header, body, or query string; MCP requires the `Authorization: Bearer <token>` header per [OAuth 2.1 Section 5.1.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13#section-5.1.1)).

The client fetches that metadata document, extracts the authorization server URL, and fetches the authorization server’s metadata from `https://auth.example.com/.well-known/oauth-authorization-server` (OAuth 2.0 metadata per [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414)) or `/.well-known/openid-configuration` ([OpenID Connect Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html)).

### Client Registration Options

Your client needs a `client_id` before it can start the flow, and the 2026-07-28 specification prefers [Client ID Metadata Documents (CIMD)](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-client-id-metadata-document-00): the client uses an HTTPS URL as its `client_id`, and the authorization server fetches the client’s redirect URIs from that URL. Nobody pre-registers anything. If your authorization server lacks CIMD, the client falls back to [Dynamic Client Registration (RFC 7591)](https://datatracker.ietf.org/doc/html/rfc7591) and POSTs its metadata to `/register` for a `client_id`. If neither exists, someone on your team hand-registers every client out of band, and every new agent becomes a ticket in that person’s queue.

### The Authorization Code Flow with PKCE

The client generates a PKCE `code_verifier`, derives the `code_challenge` (Base64-URL-encoded SHA-256 hash of the verifier), and opens the browser to the authorization server’s `authorization_endpoint` with these parameters:

```text
response_type=code
&client_id=<client-id>
&redirect_uri=<redirect-uri>
&scope=files:read files:write
&code_challenge=<challenge>
&code_challenge_method=S256
&resource=https://mcp.example.com/mcp
```

The user authenticates and consents. The authorization server redirects with an authorization code and `iss` parameter per [RFC 9207](https://datatracker.ietf.org/doc/html/rfc9207). The client validates `iss` matches the authorization server, then exchanges the code for a token by POSTing to the `token_endpoint`:

```text
grant_type=authorization_code
&code=<authorization-code>
&redirect_uri=<redirect-uri>
&code_verifier=<verifier>
&client_id=<client-id>
&resource=https://mcp.example.com/mcp
```

The authorization server validates the `code_verifier` against the `code_challenge` (PKCE proof), confirms the `redirect_uri` matches, and issues an access token. The client retries the MCP request with `Authorization: Bearer <access-token>`, and the server validates the token before executing the tool.

The sequence diagram below traces every step, from the first 401 to the validated tool call.

![OAuth PKCE flow](https://adamtheautomator.com/wp-content/uploads/publisher/0e63c5c063634a299a2668d3cd6d94e989a5434378522e3313bcf4b13bfb58e7.jpg)

## Setting Up Protected Resource Metadata

Your MCP server publishes a JSON document at `/.well-known/oauth-protected-resource` that tells clients which authorization servers you trust and which scopes you support.

### The RFC 9728 Metadata Format

[RFC 9728’s introduction](https://datatracker.ietf.org/doc/html/rfc9728#section-1) states: “This specification defines a metadata format enabling OAuth 2.0 clients and authorization servers to obtain information needed to interact with an OAuth 2.0 protected resource.” OAuth 2.1 clients use the same document. Serve it at `/.well-known/oauth-protected-resource` derived from your server’s canonical URI, as JSON with `Content-Type: application/json`, accessible without authentication.

### Building the Metadata Document

Here’s a minimal Protected Resource Metadata document:

```json
{
  "resource": "https://mcp.example.com/mcp",
  "authorization_servers": [
    "https://auth.example.com"
  ],
  "scopes_supported": [
    "files:read",
    "files:write",
    "database:read"
  ],
  "bearer_methods_supported": [
    "header"
  ]
}
```

The `resource` field holds your server’s canonical URI. The `authorization_servers` array lists the authorization server URLs you trust. The `scopes_supported` array defines the minimal set of scopes your server accepts; clients request these during initial authorization, then incrementally request more through step-up authorization. The `bearer_methods_supported` field tells clients where to send tokens; MCP requires `"header"`.

Install [Express](https://expressjs.com/en/starter/installing.html) and the [`jose` library](https://github.com/panva/jose) before you write any server code (`npm install express jose`), then serve this document from your server:

```javascript
import express from 'express';

const app = express();

app.get('/.well-known/oauth-protected-resource', (req, res) => {
  res.json({
    resource: 'https://mcp.example.com/mcp',
    authorization_servers: ['https://auth.example.com'],
    scopes_supported: ['files:read', 'files:write', 'database:read'],
    bearer_methods_supported: ['header']
  });
});
```

Deploy this endpoint before you lock down your MCP routes. Test it:

```bash
curl https://mcp.example.com/.well-known/oauth-protected-resource
```

You should see your JSON document. If you get a 404 or the document is served with the wrong `Content-Type`, clients will fail during discovery and never reach the authorization flow.

## Configuring Your Authorization Server

The metadata you just published sends every client to `https://auth.example.com`, so the server answering at that URL decides which tokens your MCP server will ever see. The Keycloak container below plays that role on localhost.

### Choosing an Authorization Server

Check [RFC 8707 resource indicator](https://www.rfc-editor.org/rfc/rfc8707.html) support before anything else when you pick an authorization server. A server that ignores the `resource` parameter still issues tokens, just without your MCP server’s URI in `aud`, and those tokens work at every service that trusts the same issuer. Confirm RFC 8707 support in your server’s documentation before you register a single scope.

### Registering Scopes and Clients

Start Keycloak first, because every Admin CLI command below talks to the running server. Name the container so you can exec into it:

```bash
docker run --name keycloak -p 127.0.0.1:8080:8080 -e KC_BOOTSTRAP_ADMIN_USERNAME=admin -e KC_BOOTSTRAP_ADMIN_PASSWORD=change_me quay.io/keycloak/keycloak:26.0 start-dev
```

`start-dev` runs Keycloak in development mode over plain HTTP, so keep it on localhost. The two `KC_BOOTSTRAP_ADMIN_*` variables create the first admin account, and `127.0.0.1:8080:8080` publishes the port to your machine only.

Set up Keycloak with its [Admin CLI](https://www.keycloak.org/docs/latest/server_admin/index.html#admin-cli), `kcadm.sh`, which lives in `/opt/keycloak/bin` inside the container. Log in against `master` first. Omit `--password` so the CLI prompts for it, which keeps the admin password out of your shell history. The CLI saves the session inside the container, so the later commands reuse it:

```bash
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh config credentials --server http://localhost:8080 --realm master --user admin
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh create realms -s realm=mcp -s enabled=true
```

Register each scope your MCP server lists in `scopes_supported`. The `name` must match the metadata string exactly, because a scope registered as `files_read` against metadata that says `files:read` shows up later as a 403 that looks like a server bug:

```bash
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh create client-scopes -r mcp -s name=files:read -s protocol=openid-connect
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh create client-scopes -r mcp -s name=files:write -s protocol=openid-connect
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh create client-scopes -r mcp -s name=database:read -s protocol=openid-connect
```

The `-r mcp` flag points each command at `mcp` instead of `master`. On Auth0, register the same scope names in your tenant.

Keycloak 26.0 doesn’t support RFC 8707’s `resource` parameter out of the box, so tokens won’t carry the `aud` claim your MCP server needs. Replace every `https://mcp.example.com/mcp` placeholder in the commands below with the URL your local MCP server actually answers on (such as `http://localhost:3000/mcp`). Then add an audience mapper to each scope so the authorization server includes your server’s URI in every token:

```bash
for s in files:read files:write database:read; do
  id=$(docker exec keycloak /opt/keycloak/bin/kcadm.sh get client-scopes -r mcp | jq -r --arg s "$s" '.[] | select(.name==$s) | .id')
  docker exec keycloak /opt/keycloak/bin/kcadm.sh create client-scopes/$id/protocol-mappers/models -r mcp -s name=mcp-audience -s protocol=openid-connect -s protocolMapper=oidc-audience-mapper -s 'config."included.custom.audience"=https://mcp.example.com/mcp' -s 'config."access.token.claim"=true'
done
```

This loop looks up each scope’s ID, then attaches an audience mapper that writes your server’s URI to the `aud` claim. If you already ran the loop with the placeholder URL and need to fix it, run this repair loop:

```bash
for s in files:read files:write database:read; do
  id=$(docker exec keycloak /opt/keycloak/bin/kcadm.sh get client-scopes -r mcp | jq -r --arg s "$s" '.[] | select(.name==$s) | .id')
  mid=$(docker exec keycloak /opt/keycloak/bin/kcadm.sh get client-scopes/$id/protocol-mappers/models -r mcp | jq -r '.[] | select(.name=="mcp-audience") | .id')
  docker exec keycloak /opt/keycloak/bin/kcadm.sh update client-scopes/$id/protocol-mappers/models/$mid -r mcp -s 'config."included.custom.audience"=http://localhost:3000/mcp'
done
```

If your authorization server supports Client ID Metadata Documents, turn that on so clients can register themselves by URL. Keycloak 26.0 doesn’t ship the experimental `cimd` feature, so you’ll need Dynamic Client Registration or manual client registration instead. [Keycloak’s MCP integration guide](https://www.keycloak.org/securing-apps/mcp-authz-server) covers CIMD setup on newer releases. Without CIMD, enable Dynamic Client Registration at `/register` and set Keycloak’s [client registration policies](https://www.keycloak.org/securing-apps/client-registration) to require an initial access token or a bearer token in production. An open endpoint lets anyone mint a client.

For testing, register a client manually with the Admin CLI. This client runs the authorization code flow with PKCE and requires user consent for every scope:

```bash
docker exec keycloak /opt/keycloak/bin/kcadm.sh create clients -r mcp -s clientId=mcp-client -s publicClient=true -s consentRequired=true -s 'redirectUris=["http://localhost:6274/oauth/callback","http://127.0.0.1:6274/oauth/callback"]' -s 'attributes."pkce.code.challenge.method"=S256'
```

Then attach the three scopes as optional client scopes so the user can approve them during the flow. Grab the client’s UUID first, then add each scope:

```bash
client_uuid=$(docker exec keycloak /opt/keycloak/bin/kcadm.sh get clients -r mcp -q clientId=mcp-client | jq -r '.[0].id')
for s in files:read files:write database:read; do
  scope_id=$(docker exec keycloak /opt/keycloak/bin/kcadm.sh get client-scopes -r mcp | jq -r --arg s "$s" '.[] | select(.name==$s) | .id')
  docker exec keycloak /opt/keycloak/bin/kcadm.sh update clients/$client_uuid/optional-client-scopes/$scope_id -r mcp
done
```

### Enabling RFC 9207 Issuer Validation

Turn on the `iss` parameter in authorization responses, which your server advertises as `authorization_response_iss_parameter_supported: true` in its metadata. A client that never validates `iss` can’t tell which authorization server sent a code back, so a malicious server it also talks to can collect a code meant for yours. Keycloak’s MCP integration guide lists RFC 9207 as supported. If you’re on a server that lacks it, upgrade before you continue. The metadata check below shows whether your server sends it.

### Verifying the Metadata Endpoint

Every `https://auth.example.com` URL in this tutorial stands for the issuer Keycloak assigns to `mcp`, so point the check at the container you started:

```bash
curl http://localhost:8080/realms/mcp/.well-known/openid-configuration
```

Confirm the response includes `authorization_endpoint`, `token_endpoint`, `jwks_uri`, `code_challenge_methods_supported` with `S256`, and `grant_types_supported` with `authorization_code`, and check whether it lists `authorization_response_iss_parameter_supported: true`. Then copy two values into your code. The `issuer` value replaces `https://auth.example.com` in both validators and in your metadata’s `authorization_servers`, and the `jwks_uri` value replaces the JWKS URL. The `example.com` defaults make the validator reject every token Keycloak mints.

Also replace every `https://auth.example.com` placeholder with Keycloak’s issuer (such as `http://localhost:8080/realms/mcp`), and replace every `https://mcp.example.com/mcp` placeholder with your local MCP server URL (such as `http://localhost:3000/mcp`). This includes the Protected Resource Metadata’s `resource` field, both validators’ `audience` parameter, and the `METADATA_URL` constant. The discovery chain fails if clients are sent to a hostname that doesn’t resolve.

## Implementing JWT Validation in Your MCP Server

When your MCP server receives a bearer token, validate the signature, issuer, audience, expiration, and scopes before executing any tool.

### What the Token Must Prove

The MCP specification requires servers to “validate that access tokens were issued specifically for them as the intended audience, according to [RFC 8707 Section 2](https://www.rfc-editor.org/rfc/rfc8707.html#section-2).” Run the signature check against the authorization server’s public key first, because every claim inside a forged token is attacker-controlled until the signature holds. Then confirm `iss` matches your authorization server, `aud` matches your MCP server’s canonical URI, `exp` has not passed, and `nbf` (when present) has arrived. The scope check comes last: a token that fails only that check gets a 403 instead of a 401.

### JWT Validation Code Examples

Here’s JWT validation in Node.js using the `jose` library:

```javascript
import { jwtVerify, createRemoteJWKSet } from 'jose';

const JWKS = createRemoteJWKSet(new URL('https://auth.example.com/.well-known/jwks.json'));

async function validateToken(token, requiredScopes) {
  try {
    const { payload } = await jwtVerify(token, JWKS, {
      issuer: 'https://auth.example.com',
      audience: 'https://mcp.example.com/mcp'
    });

    const tokenScopes = payload.scope ? payload.scope.split(' ') : [];
    const hasRequiredScopes = requiredScopes.every(scope => tokenScopes.includes(scope));
    
    if (!hasRequiredScopes) {
      return { valid: false, reason: 'insufficient_scope' };
    }

    return { valid: true, payload };
  } catch (error) {
    return { valid: false, reason: 'invalid_token', error: error.message };
  }
}
```

In Python using [`python-jose`](https://python-jose.readthedocs.io/en/latest/) (install it with `pip install "python-jose[cryptography]" requests`):

```python
from jose import jwt, jwk
from jose.utils import base64url_decode
import requests

JWKS_URL = 'https://auth.example.com/.well-known/jwks.json'
ISSUER = 'https://auth.example.com'
AUDIENCE = 'https://mcp.example.com/mcp'

def get_jwks():
    response = requests.get(JWKS_URL)
    return response.json()

def validate_token(token, required_scopes):
    try:
        jwks = get_jwks()
        header = jwt.get_unverified_header(token)
        key = next((k for k in jwks['keys'] if k['kid'] == header['kid']), None)
        
        if not key:
            return {'valid': False, 'reason': 'invalid_token', 'error': 'Key not found'}
        
        public_key = jwk.construct(key)
        payload = jwt.decode(
            token,
            public_key,
            algorithms=['RS256'],
            audience=AUDIENCE,
            issuer=ISSUER,
            options={"require_aud": True}
        )
        
        token_scopes = payload.get('scope', '').split()
        has_required_scopes = all(scope in token_scopes for scope in required_scopes)
        
        if not has_required_scopes:
            return {'valid': False, 'reason': 'insufficient_scope'}
        
        return {'valid': True, 'payload': payload}
    except Exception as e:
        return {'valid': False, 'reason': 'invalid_token', 'error': str(e)}
```

`createRemoteJWKSet` fetches the key set from `jwks_uri` only when its cache is missing or stale, so the Node version doesn’t call the authorization server on every request. The Python version does: `get_jwks()` runs inside `validate_token`, so each tool call pays one extra HTTP round trip to the authorization server until you cache the result. The Python version also pins `algorithms=['RS256']`, because accepting whatever algorithm the token header names lets an attacker pick a weaker one. `jwtVerify` checks the signature, `exp`, issuer, and audience automatically. `jwt.decode` checks the same claims, but only validates `audience` when you pass `options={"require_aud": True}`. The scope check after them is yours, and it decides between a 401 and a 403, so both functions return `reason: 'insufficient_scope'` when only that check fails and `reason: 'invalid_token'` for everything else.

Your middleware returns two different `WWW-Authenticate` responses. When a request arrives without a token, return HTTP 401 with the `WWW-Authenticate` header pointing to your Protected Resource Metadata:

```text
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"
```

When a request arrives with a token but the token lacks the required scopes for the tool, return HTTP 403 with `insufficient_scope`:

```text
WWW-Authenticate: Bearer error="insufficient_scope", scope="files:write", resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"
```

The `scope` parameter tells the client which scopes to request during step-up authorization.

## Mapping Tools to Scopes

Each tool maps to one or more scopes. When the client calls `tools/call` with a specific tool name, check whether the token’s scopes cover it. Store this mapping in your server configuration:

```json
{
  "tools": {
    "read_file": ["files:read"],
    "write_file": ["files:write"],
    "delete_file": ["files:write"],
    "query_database": ["database:read"],
    "execute_migration": ["database:write", "database:admin"]
  }
}
```

Putting `delete_file` under `files:write` means any agent allowed to save a file can also erase one. If deletion should need its own approval, give it a `files:delete` scope and add that scope to `scopes_supported`.

When `tools/call` arrives with `{"name": "execute_migration"}`, extract the token from the `Authorization` header, validate it, and check whether the token’s scopes include both `database:write` and `database:admin`. If not, return HTTP 403 with `scope="database:write database:admin"` in the `WWW-Authenticate` header.

Here’s that lookup as Express middleware. It reuses `app` and `validateToken` from earlier and reads the map above from `tool-scopes.json`:

```javascript
import { readFileSync } from 'node:fs';

const { tools: TOOL_SCOPES } = JSON.parse(readFileSync('./tool-scopes.json', 'utf8'));
const METADATA_URL = 'https://mcp.example.com/.well-known/oauth-protected-resource';

app.post('/mcp', express.json(), async (req, res, next) => {
  const auth = req.get('Authorization') || '';
  if (!auth.startsWith('Bearer ')) {
    res.set('WWW-Authenticate', `Bearer resource_metadata="${METADATA_URL}"`);
    return res.status(401).end();
  }

  const toolName = req.body?.method === 'tools/call' ? req.body.params?.name : null;
  if (toolName && !TOOL_SCOPES[toolName]) {
    return res.status(403).end();
  }
  const requiredScopes = toolName ? TOOL_SCOPES[toolName] : [];
  const result = await validateToken(auth.slice(7), requiredScopes);

  if (result.reason === 'insufficient_scope') {
    res.set('WWW-Authenticate',
      `Bearer error="insufficient_scope", scope="${requiredScopes.join(' ')}", resource_metadata="${METADATA_URL}"`);
    return res.status(403).end();
  }
  if (!result.valid) {
    res.set('WWW-Authenticate', `Bearer error="invalid_token", resource_metadata="${METADATA_URL}"`);
    return res.status(401).end();
  }
  next();
});
```

Requests that aren’t `tools/call` still need a valid token, and a tool missing from the map gets a 403, so a new tool stays locked until someone assigns it a scope. Register this middleware before your MCP SDK handler. Express runs `/mcp` handlers in order, so reversing them skips `validateToken` on every request.

This mapping applies the [principle of least privilege](https://csrc.nist.gov/glossary/term/least_privilege) one tool at a time. An agent that only reads files starts with `files:read`, and its first write triggers a step-up challenge for `files:write` that the user approves or refuses. If the agent gets prompt-injected into calling `execute_migration`, the server rejects the call unless the user explicitly granted `database:admin`.

## Testing the OAuth Flow End-to-End

So far you’ve only pointed `curl` at two metadata documents, which proves discovery works. Put a real client through the handshake now, starting with a request that carries no token at all.

### Setting Up the Test Environment

Any [MCP client](https://modelcontextprotocol.io/clients) that runs OAuth 2.1 with PKCE works as the test client. Start your MCP server (Keycloak is already running from the `mcp` setup above), then confirm the server rejects an anonymous request with a 401 before any client gets involved:

```bash
curl -i -X POST https://mcp.example.com/mcp
```

The response should be HTTP 401 with a `WWW-Authenticate: Bearer resource_metadata="..."` header. A 200 means the middleware isn’t wrapping the route.

Before launching a client, create a test user in the `mcp` realm:

```bash
docker exec keycloak /opt/keycloak/bin/kcadm.sh create users -r mcp -s username=testuser -s enabled=true -s email=testuser@example.com -s emailVerified=true -s firstName=Test -s lastName=User
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh set-password -r mcp --username testuser
```

The `set-password` command prompts for a password, so type one that you’ll remember for the login screen.

Next, launch the MCP Inspector with `npx @modelcontextprotocol/inspector` and configure it. Click Add Servers, choose Add manually, set the transport to `streamable-http`, and set the URL to `http://localhost:3000/mcp`. Then open Settings > OAuth Settings, set Client ID to `mcp-client`, and untick Request refresh token before you connect. Set Scopes to `files:read` so the step-up authorization test triggers when you call `write_file`. The client makes an unauthenticated request, receives HTTP 401, fetches your Protected Resource Metadata, and opens the browser to the authorization endpoint.

### Testing the Initial Authorization

Log in with the test user you just created, and the authorization server shows the consent screen listing the scopes the client requested, as you can see below.

![Consent screen scopes](https://adamtheautomator.com/wp-content/uploads/publisher/2f9ebd1530c144121d02dbc475252836a838602dbc56c20a084d5ea9b44113ef.jpg)

Approve the scopes, and the authorization server redirects back to the client’s `redirect_uri` with an authorization code. The client exchanges the code for an access token and retries the MCP request. Your server validates the token and executes the tool. Check the server logs to confirm the token’s `aud` claim matched your canonical URI and the scopes covered the tool.

### Testing Step-Up Authorization

Test step-up authorization. Have the client call a tool requiring a scope it doesn’t have (for example, `write_file` when the token only has `files:read`). Your server returns HTTP 403 with `insufficient_scope` and `scope="files:write"`. The client triggers another browser redirect, the user approves the new scope, and the client receives a new token with both scopes. Retry the tool call; it should succeed.

* * *

_**Key Insight: If the step-up consent screen lists `files:read` again next to `files:write`, the client sent `prompt=consent`, which forces Keycloak to list every scope again. The MCP Inspector does this while Request refresh token is on (the default). With that option off, Keycloak will issue refresh tokens and the Inspector will refresh silently, so step-up lists only the new scope.**_

* * *

### Testing Token Expiration

Test token expiration by dropping `accessTokenLifespan` on `mcp` to 60 seconds. Keycloak reads `accessTokenLifespan` in seconds:

```bash
docker exec -it keycloak /opt/keycloak/bin/kcadm.sh update realms/mcp -s accessTokenLifespan=60
```

Wait for the next token to pass its `exp`, then call a tool again. The server should return HTTP 401 with `invalid_token`, and the client should refresh or re-authorize on its own. If it keeps retrying the expired token, the fix belongs in the client’s refresh handling.

## Troubleshooting Common OAuth Integration Errors

When the OAuth flow breaks, the error usually surfaces at the token exchange, during JWT validation, or when the client retries after receiving HTTP 403. Each error below names where it surfaces and the check that clears it.

### Error: `invalid_client` During Token Exchange

The authorization server couldn’t verify your `client_id`. Confirm it matches what you registered or that your CIMD document is fetchable over HTTPS.

### Error: `invalid_grant` During Token Exchange

The authorization code is invalid, expired, or was already used. Codes are single-use and expire quickly. Verify the `redirect_uri` in the token request exactly matches the authorization request (byte-for-byte, including trailing slashes).

### Error: `invalid_grant` With “PKCE verification failed”

Your PKCE `code_verifier` doesn’t hash to the `code_challenge`. Keycloak’s error message reads “PKCE verification failed: Code mismatch”. Per [RFC 7636 Section 4.6](https://datatracker.ietf.org/doc/html/rfc7636#section-4.6), the authorization server returns `invalid_grant` when PKCE validation fails. Confirm you’re using SHA-256 and Base64-URL-encoding without padding.

### Error: HTTP 403 `insufficient_scope` After the User Approves

The authorization server issued a token without the scope because the user lacks the entitlement behind it. Copy the token from the `Authorization` header of the request that got the 403 and decode its payload locally, so a live token never lands on a website:

```bash
python3 -c "import sys,json,base64; p=sys.argv[1].split('.')[1]; print(json.dumps(json.loads(base64.urlsafe_b64decode(p + '=' * (-len(p) % 4))), indent=2))" "<access-token>"
```

Confirm the `scope` claim includes what you requested. If it doesn’t, fix the user-to-scope mapping in your authorization server. Until you do, the client re-authorizes, presents a token that still lacks the scope, and gets another 403. The [MCP specification’s scope challenge rules](https://modelcontextprotocol.io/specification/2026-07-28/basic/authorization#scope-challenge-handling) tell clients to retry no more than a few times and then treat the failure as permanent, so a compliant client gives up and reports an authorization error.

### Error: `aud` Claim Does Not Match the Resource URI

Your authorization server isn’t binding tokens to the `resource` parameter. Check RFC 8707 support. Without it, tokens are replayable across services.

### Error: Infinite Redirect Loop Between Client and Authorization Server

The client is re-authorizing on every request. Add logging to your JWT validation middleware and confirm it’s accepting valid tokens. Verify signature, `aud`, and `iss` checks are passing.

### Error: Client Ignores the HTTP 403 Step-Up Challenge

Some MCP clients skip step-up authorization entirely. Check your client’s documentation for how it handles an HTTP 403 with `insufficient_scope` before you start debugging the server. A client without step-up support fails the tool call and shows the user the error instead of re-authorizing. Test with a compatible client, or re-authorize by hand: clear the client’s token cache and restart the session.

## Security Checklist Before Production

Run through these controls before your MCP server takes traffic from any agent you don’t control. Several map to risks in [OWASP’s API Security Top 10](https://owasp.org/API-Security/editions/2023/en/0x11-t10/).

* * *

_**Reality Check: Prove the `aud` check works before you trust it. Send your MCP server a token the same authorization server minted for a different API and expect a 401. If it comes back 200, every service that trusts that issuer can call your tools.**_

* * *

### Token and Scope Security

*   Your server rejects any token where the `aud` claim doesn’t exactly match your canonical URI. Without that check, a token minted for another service works here too.
    
*   Your authorization server rejects authorization requests without `code_challenge` and token requests without `code_verifier`. Without PKCE, an intercepted authorization code can be redeemed by anyone.
    
*   Your Protected Resource Metadata’s `scopes_supported` lists only the minimal set of scopes clients need for basic functionality, and everything else arrives through step-up authorization.
    
*   Access tokens expire within a reasonable window; shorter windows (5-15 minutes) limit how long a stolen token stays valid, though they force more frequent refreshes. Refresh tokens expire or rotate after use.
    

### Client and Transport Security

*   If using Dynamic Client Registration, your `/register` endpoint requires authentication. An open endpoint lets any script that finds the URL register clients.
    
*   Your Client ID Metadata Document (if you’re using CIMD) is served over HTTPS with correct CORS headers.
    
*   Your MCP server, authorization server, and Client ID Metadata Document serve HTTPS only. A bearer token sent once over plain HTTP can be replayed by anyone on that network segment until it expires.
    
*   Your MCP client validates `iss` in every authorization response per RFC 9207, or a malicious authorization server can insert itself mid-flow and collect the authorization code meant for yours.
    
*   Token validation failures, insufficient scope errors, and authorization code exchanges are logged, and unusual patterns (repeated 403s, rapid re-authorization, mismatched `aud` claims) trigger alerts.
    

## What You Built

Your MCP server now enforces [OAuth 2.1 authorization](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1-13) on every tool call. An unauthenticated request gets a 401 pointing at your Protected Resource Metadata. A token minted for another service fails the `aud` check. A token missing a scope gets a 403 naming the exact scope to request. A compromised agent can call only the tools whose scopes the user approved, and each token expires in minutes.

Take two more steps before real agents connect. Shorten the access token lifetime and watch how often clients refresh, because that rate tells you whether users will tolerate the window you picked. Then put your tool-to-scope map under code review, so a new `delete_` or `execute_` tool can’t ship under a scope that already grants writes.

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fmcp-server-oauth-scopes%2F&text=Lock%20Down%20Every%20MCP%20Server%20Tool%20with%20OAuth%202.1%20Scopes)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fmcp-server-oauth-scopes%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fmcp-server-oauth-scopes%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/publisher/4065d9c85b2b810f8ec2f16d43234514/30a1ebd88fe7d0a348fc74f3679ed0a07cd493411310d679fd9886586ec027dd.webp)

### [Azure Human Approvals: Stop the Agent Before the Tool Fires](/azure-agent-approval-gate/)

Build a real human approval gate in Microsoft Foundry Agent Service that suspends the run, verifies an Entra ID approver, and logs each decision.

![](https://adamtheautomator.com/wp-content/uploads/publisher/4065d9c85b2b81bf9605cb37d967f788/a9812525518a5125a43d2341858253da973f79467a0eba39ef631295b5a8807b.png)

### [Entra Agent IDs: How to Stop AI Privilege Escalation](/entra-agent-id-privilege-escalation/)

Map the four objects behind a Microsoft Entra Agent ID, follow four documented paths to tenant control, and apply eight controls in risk order.

![](https://adamtheautomator.com/wp-content/uploads/publisher/4065d9c85b2b81cb8cd5e63895d6d603/a290484691de461d47cf56c4c5e9178e3574a1bff6e7fc0a813e3b45039f936a.webp)

### [5 Ways to Stop Azure AI Agents from Blowing Your Budget](/azure-ai-agent-budget-guardrails/)

Cap Azure AI agent spend with an API Management token limit, Application Insights telemetry, semantic caching, loop caps, and budget alerts.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
