Secure Your MCP Server
Use this guide to build a Python MCP server whose tools are each protected by a Choreo Identity & Access Management OAuth scope, using FastMCP, then verify the setup end to end with MCP Inspector.
What You Will Learn
- Turn an MCP server into an OAuth 2.0 resource server that answers unauthenticated calls with a
401and RFC 9728 protected-resource metadata - Validate Choreo Identity & Access Management JWTs offline (signature, issuer, audience, and expiry) against the JWKS endpoint
- Protect each tool with its own scope, so a token missing a scope cannot see or call that tool
Prerequisites
- About 10 minutes
uv, which manages Python and dependencies automatically- Node.js 22.19+ (for MCP Inspector)
- Your preferred code editor
Check out the complete Calculator MCP Sample in the Choreo Identity & Access Management repository.
How It Works
Your MCP server becomes an OAuth 2.0 resource server. When a client connects without a token, the server responds with a 401 and RFC 9728 metadata that points the client to Choreo Identity & Access Management for authentication. The client runs an Authorization Code + PKCE flow, gets a JWT scoped to the user's role-based permissions, and presents it on reconnect. The server validates the token offline against Choreo Identity & Access Management's JWKS and filters visible tools by the token's scopes.
Register the MCP Resource and Scopes
- Sign in to the Console at https://console.cloud.choreolabs.com/iam/.
- Navigate to Resource servers and click Add resource server.
- On the Type step, select MCP.
- On the Name step, enter:
- MCP server name:
Calculator MCP - Identifier:
http://localhost:8000/mcp
- MCP server name:
- On the Permission delimiter step, keep the default colon (
:) and click Create MCP server. If your deployment has multiple organization units, click Continue instead, select one, then click Create MCP server.
Now add each of the four calculator tools as a tool permission:
-
On the Capabilities tab, the server has no capabilities yet. Click Add tool permission.
-
Repeat for the remaining three tools: click the + icon in the panel header, then select Add tool permission from the menu.
-
For each tool, enter the Name. Choreo Identity & Access Management generates the Handle automatically from the name (lowercased), so confirm it matches the table below before clicking Add: the handle becomes the exact scope
require_scopes(...)checks for inserver.py.Name Handle Generated permission Add addaddSubtract subtractsubtractMultiply multiplymultiplyDivide dividedivide
Code in this guide uses https://<DATA_PLANE_URL> for your environment's data plane URL, where users sign in and tokens are issued. Replace it with the URL on the environment's Endpoints page. To open it, select your project, go to Deployment pipeline, and click Open environment on the environment's card. See Control Plane and Data Plane URLs.
Saving a change does not make it live. You author in the control plane, and your users sign in on a separate data plane, so a change takes effect in an environment only after you deploy it. Go to Deploy, deploy the latest version to your first environment, then promote it to the next environment when you are ready.
Auto-sync deploys saved changes to your first environment within seconds. Turning it on is your choice, per project. See Deploy a Version, or learn why you deploy and how auto-sync works.
Create a Role for the Calculator Permissions
Registering the permissions in the previous step only defines them. Choreo Identity & Access Management puts a scope into an access token only when the signing-in user actually holds the matching permission through a role, and scopes the user doesn't hold are silently dropped from the token. A token missing a tool's scope means that tool never appears in the tool list, so before you connect Inspector, create a role that grants the four calculator permissions and assign it to the user you'll sign in with.
- Navigate to Roles and click Add role.
- On the Create a Role step, enter a name (for example,
Calculator) and click Continue. If prompted, select an organization unit and click Continue again. - On the Permissions step, expand Calculator MCP and check add, subtract, multiply, and divide under Tools.
- Click Continue to create the role.
- Open the role from the Roles list, select the Assignments tab, and click Add.
- In the Add assignment dialog, on the Users tab, select
adminand click Add selected.
Create the Server
The whole server lives in a single file. Create server.py.
FastMCP's RemoteAuthProvider turns the server into an OAuth 2.0 resource server: it publishes RFC 9728 protected-resource metadata and rejects requests without a valid token before any tool runs. The JWTVerifier validates each token offline, with no call back to Choreo Identity & Access Management per request, by checking the signature against the JWKS endpoint, the issuer, the audience, and the expiry:
# /// script
# requires-python = ">=3.11"
# dependencies = ["fastmcp>=3.4,<4", "python-dotenv>=1"]
# ///
"""Scope-protected calculator MCP server."""
import os
from dotenv import load_dotenv
from fastmcp import FastMCP
from fastmcp.exceptions import ToolError
from fastmcp.server.auth import RemoteAuthProvider, require_scopes
from fastmcp.server.auth.providers.jwt import JWTVerifier
load_dotenv(override=True)
ISSUER = os.environ["THUNDERID_ISSUER"]
JWKS_URI = os.environ["THUNDERID_JWKS_URI"]
AUDIENCE = os.environ["MCP_AUDIENCE"]
SCOPES = ["add", "subtract", "multiply", "divide"]
verifier = JWTVerifier(
jwks_uri=JWKS_URI,
issuer=ISSUER,
audience=AUDIENCE,
)
mcp = FastMCP(
"Calculator",
auth=RemoteAuthProvider(
token_verifier=verifier,
authorization_servers=[ISSUER],
base_url="http://localhost:8000",
scopes_supported=SCOPES,
),
)
The # /// script header at the top of the file is inline script metadata (PEP 723). uv run server.py reads it and resolves fastmcp and python-dotenv automatically, in an isolated environment, so there's no separate pip install step.
Append the four tools below the auth setup, still in the same server.py file. Each tool declares the single scope it needs with require_scopes(...). A token that doesn't carry that scope can't see the tool in tools/list and can't call it:
@mcp.tool(auth=require_scopes("add"))
def add(a: float, b: float) -> float:
"""Add two numbers."""
return a + b
@mcp.tool(auth=require_scopes("subtract"))
def subtract(a: float, b: float) -> float:
"""Subtract b from a."""
return a - b
@mcp.tool(auth=require_scopes("multiply"))
def multiply(a: float, b: float) -> float:
"""Multiply two numbers."""
return a * b
@mcp.tool(auth=require_scopes("divide"))
def divide(a: float, b: float) -> float:
"""Divide a by b."""
if b == 0:
raise ToolError("Cannot divide by zero.")
return a / b
if __name__ == "__main__":
mcp.run(transport="http", host="localhost", port=8000)
Configure the Environment
Create a .env file next to server.py:
THUNDERID_ISSUER=https://<DATA_PLANE_URL>
THUNDERID_JWKS_URI=https://<DATA_PLANE_URL>/oauth2/jwks
MCP_AUDIENCE=http://localhost:8000/mcp
| Variable | Description |
|---|---|
THUNDERID_ISSUER | Must exactly match the iss claim Choreo Identity & Access Management puts in every access token. |
THUNDERID_JWKS_URI | Where the server fetches Choreo Identity & Access Management's public signing keys to verify token signatures. |
MCP_AUDIENCE | The resource server identifier you registered in the previous step. JWTVerifier rejects tokens whose aud claim doesn't match. |
Both the issuer and the JWKS URI are discoverable from https://<DATA_PLANE_URL>.
Run and Verify Protection
Start the server:
uv run server.py
It serves the MCP endpoint at http://localhost:8000/mcp.
With no token, the server rejects the request:
curl -si -X POST http://localhost:8000/mcp
HTTP/1.1 401 Unauthorized
www-authenticate: Bearer resource_metadata="http://localhost:8000/.well-known/oauth-protected-resource/mcp"
Fetch that metadata directly:
curl -s http://localhost:8000/.well-known/oauth-protected-resource/mcp
The response names Choreo Identity & Access Management as the authorization server and lists the four scopes:
{
"resource": "http://localhost:8000/mcp",
"authorization_servers": ["https://<DATA_PLANE_URL>/"],
"scopes_supported": ["add", "subtract", "multiply", "divide"],
"bearer_methods_supported": ["header"]
}
Connect an MCP Client
Choreo Identity & Access Management supports two ways for a client to obtain OAuth credentials: pre-register an application in the Console, which both MCP Inspector and Claude Code use below. Hosted tenants do not enable Dynamic Client Registration (DCR), so you must pre-register every MCP client. See Register an MCP client.
- MCP Inspector
- Claude Code
Connect with MCP Inspector
MCP Inspector connects with a client application you pre-register in the Console.
Register an MCP Client for Inspector
Choreo Identity & Access Management has a dedicated application type for MCP clients like Inspector. In the Console:
- Go to Applications and click Add application.
- Select MCP client.
- Enter a name (for example,
Calculator Inspector). - If prompted, select an organization unit.
- On the Client type step, select On behalf of a user. This configures the Authorization Code flow with PKCE as a public client.
- Under Redirect URIs, add
http://localhost:6274/oauth/callback. - Click Finish.
- From the completion screen, copy the Client ID. No client secret is required because this is a public client.
Allow the MCP Inspector Origin
MCP Inspector runs in the browser at http://localhost:6274 and calls Choreo Identity & Access Management cross-origin, so its origin must be allowed in the CORS configuration.
In the Choreo Identity & Access Management Console, switch to the organization view and go to Configurations. On the CORS tab, under Allowed origins, click Add origin, enter http://localhost:6274, and click Save changes.
Launch and Connect
Start Inspector:
npx @modelcontextprotocol/inspector
Inspector opens in your browser at http://localhost:6274.
- Set Transport type to Streamable HTTP and URL to
http://localhost:8000/mcp. - Expand the Authentication section.
- Under OAuth 2.0 Flow, enter the Client ID you copied earlier. Leave Client secret empty.
- Click Connect. Inspector reads your server's protected-resource metadata, discovers Choreo Identity & Access Management as the authorization server, and requests all four scopes by default.
- A browser tab opens with Choreo Identity & Access Management's sign-in page. Sign in with your test user.
- You're redirected back to Inspector, now connected.
- Open the Tools tab and click List Tools. You see
add,subtract,multiply, anddivide.
If the browser shows "Cannot GET /authorize" instead of the sign-in page, first confirm Transport type is set to Streamable HTTP, since the deprecated SSE transport probes without a token and misroutes the authorize request to Inspector's own proxy. If Transport Type is already correct, Inspector was launched without NODE_EXTRA_CA_CERTS or the path is wrong, so it couldn't fetch Choreo Identity & Access Management's OAuth discovery metadata. Relaunch with the variable pointing at the exported certificate.
The tools you see in Inspector are exactly the ones your token's scopes allow. Try it: click Disconnect, then in the Auth panel's Scope field, type add subtract multiply, leaving out divide, and Connect again. Sign in once more and list the tools. divide is gone, because the token Inspector obtained this time never carries that scope, and require_scopes("divide") hides the tool from anyone without it.
Claude Code connects with a client application you pre-register in the Console. Hosted tenants do not enable Dynamic Client Registration (DCR), so Claude Code cannot register itself.
Register an MCP Client for Claude Code
Register Claude Code the same way you registered Inspector. See Register an MCP client for details. In the Console:
- Go to Applications and click Add Application.
- Select MCP Client.
- Enter a name (for example,
Calculator Claude Code). - If prompted, select an organization unit.
- On the Client type step, select On behalf of a user.
- Under Redirect URIs, add
http://localhost:8080/callback. - Click Finish and copy the Client ID.
Connect Claude Code
Add the Calculator server, from the same directory as server.py:
claude mcp add --transport http --client-id <CLIENT_ID> --callback-port 8080 calculator http://localhost:8000/mcp
Replace <CLIENT_ID> with the Client ID you copied. The --callback-port value must match the redirect URI you registered. Then start Claude Code:
claude
-
Inside Claude Code, run
/mcp. -
Choose the
calculatorserver and authenticate. -
A browser tab opens with Choreo Identity & Access Management's sign-in page. Sign in with your test user.
-
Back in Claude Code, ask it to run both tools:
"Add 7 and 5, then divide 10 by 4."
Claude Code calls the
addanddividetools and returns the results.
Claude Code only sees the tools your token's scopes allow, the same as Inspector. Try it: in the Console, open the Calculator role, remove the divide permission, then run /mcp in Claude Code again and re-authenticate. Ask Claude to divide two numbers again: it can no longer call the tool, because your token no longer carries the divide scope.
What's Next
Was this page helpful?