All articles

Building a permission-aware MCP server in Python

2026-10-13 · Deep dive AI agents MCP LLMOps

Audience checks, per-tool scopes and tool annotations with the official MCP Python SDK, plus the spec rules that most first implementations get wrong.

Your MCP server probably accepts tokens that were never meant for it. In the official Python SDK, that's what happens when you leave one setting unset. And the tool someone adds six months from now will probably skip your scope check, unless a test stops it.

This matters now because Atlassian's rebuilt MCP server is generally available, and it shows the pattern that's becoming the norm. It uses OAuth 2.1 with PKCE so the agent only gets the user's own permissions, it sorts tools into read, write and destructive, and it adds admin scopes and audit logging. You can build the same controls into your own server with the official Python SDK and the current MCP specification (2026-07-28). The example is a small "tickets" server, and the code below runs in CI against mcp 2.3.0, the current release.

Reject tokens issued for someone else

Your MCP server is an OAuth 2.1 resource server. It never logs anyone in. It validates tokens issued by your authorization server (Okta, Entra ID, Keycloak and the like). The spec makes two checks mandatory: servers MUST validate that a token was issued for them as the audience (RFC 8707), and MUST NOT accept or pass on any other tokens.

from pydantic import AnyHttpUrl
from mcp.server import MCPServer
from mcp.server.auth.provider import AccessToken, TokenVerifier
from mcp.server.auth.settings import AuthSettings

RESOURCE = "https://mcp.example.com/mcp"  # canonical URI of this server, no trailing slash

class JwtVerifier(TokenVerifier):
    async def verify_token(self, token: str) -> AccessToken | None:
        claims = validate_jwt(token)  # YOUR code: JWKS signature, exp, iss checks
        if claims is None:
            return None
        return AccessToken(
            token=token,
            client_id=claims["client_id"],
            scopes=claims.get("scope", "").split(),
            expires_at=claims["exp"],
            resource=claims["aud"],   # RFC 8707 resource indicator / audience
            subject=claims["sub"],
        )

mcp = MCPServer(
    "tickets",
    token_verifier=JwtVerifier(),
    auth=AuthSettings(
        issuer_url=AnyHttpUrl("https://auth.example.com"),
        resource_server_url=AnyHttpUrl(RESOURCE),
        required_scopes=["tickets:read"],
        validate_token_resource=True,
    ),
)

Set validate_token_resource=True explicitly. In mcp 2.3.0, leaving it unset while resource_server_url is set logs a warning and behaves as False, so tokens minted for other services get accepted. The SDK says 3.0 will flip the default. If your verifier already checks the audience, set it to False on purpose rather than leaving it unset. If your IdP issues multi-audience tokens, the SDK's docstring says to set resource to the entry that equals resource_server_url.

resource_server_url also drives discovery. The SDK uses it as the base route for OAuth Protected Resource Metadata (RFC 9728), which the spec requires so clients can find your authorization server from the WWW-Authenticate header on a 401.

Check scopes inside every tool

required_scopes gates the whole server. Real systems need more: read for search, write for updates, a separate scope for deletes. The SDK exposes the current token inside a tool:

from mcp.server.auth.middleware.auth_context import get_access_token
from mcp.server.mcpserver.exceptions import ToolError

def require_scope(scope: str) -> AccessToken:
    token = get_access_token()
    if token is None or scope not in token.scopes:  # no token fails closed
        raise ToolError(f"This action needs the '{scope}' scope. Re-authorize to grant it.")
    return token

Raise ToolError, not a generic exception. The SDK turns ToolError into an isError: true result the model can read and act on. Anything else is treated as a crash, and the model sees only Error executing tool <name>, which gives the agent nothing to recover from.

Keep the token is None branch. Writing the check as if token and scope not in token.scopes reads almost the same, but it lets every call without a token straight through.

At the HTTP level, the spec describes the full step-up flow: respond 403 with WWW-Authenticate: Bearer error="insufficient_scope", scope="...", resource_metadata="...", and list all the scopes the operation needs in one challenge, not one per retry. If a gateway in front of the server can see which tool is being called, issue the challenge there. The in-tool check is the minimum.

Annotations are hints, not security

from mcp.types import ToolAnnotations

@mcp.tool(title="Search tickets",
          annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False))
def search_tickets(query: str) -> list[dict]:
    require_scope("tickets:read")
    ...

@mcp.tool(title="Close ticket",
          annotations=ToolAnnotations(read_only_hint=False, destructive_hint=False,
                                      idempotent_hint=True))
def close_ticket(ticket_id: str) -> str:
    require_scope("tickets:write")
    ...

@mcp.tool(title="Delete ticket",
          annotations=ToolAnnotations(read_only_hint=False, destructive_hint=True))
def delete_ticket(ticket_id: str) -> str:
    require_scope("tickets:admin")
    ...

Annotations let a client ask for confirmation before delete_ticket runs, the same read/write/destructive split Atlassian describes. But destructive_hint=False on close_ticket is a claim the client has to take on trust, and the spec tells clients to treat annotations from untrusted servers as untrusted. The SDK docs say not to rely on clients honouring them. Your scope check is the control. destructive_hint and idempotent_hint only mean something on tools that write, which is why the read-only tool leaves them out.

Hints aren't purely decorative, which is exactly why they can't be trusted. VS Code skips its confirmation prompt for tools marked readOnlyHint and asks for every other tool, so a write tool mislabelled as read-only runs with no prompt at all. Most clients do far less: in March the MCP project's own blog noted that no client surfaces annotations in its approval prompts. The strongest version of this rule isn't a hint. If a deployment doesn't need write tools, don't register them, and turn them on only through server config. A tool that doesn't exist can't be called.

Make the scope check impossible to forget

A scope check that lives in each tool body is only as good as the next person who adds a tool. So test the rule, not the tools you have today, and don't let annotations decide what gets tested. Declare the scope each tool needs next to its registration:

# tickets_server.py, next to the tools
REQUIRED_SCOPE = {"search_tickets": "tickets:read", "close_ticket": "tickets:write", "delete_ticket": "tickets:admin"}

Then enumerate the registry, check that the matrix covers exactly the registered tools, and call each tool with every scope except its own:

import asyncio
import pytest
from mcp.server import MCPServer
from mcp.server.auth.middleware.auth_context import auth_context_var
from mcp.server.auth.middleware.bearer_auth import AuthenticatedUser
from mcp.server.auth.provider import AccessToken
from mcp.server.mcpserver.exceptions import ToolError

from tickets_server import REQUIRED_SCOPE, TICKETS, mcp


async def as_caller(scopes, fn, *args):
    user = AuthenticatedUser(AccessToken(token="t", client_id="test", scopes=scopes))
    reset = auth_context_var.set(user)  # what the auth middleware does per request
    try:
        return await fn(*args)
    finally:
        auth_context_var.reset(reset)


def assert_every_tool_needs_its_scope(server, required, store):
    # enumerate the registry itself: a scope-filtered tools/list override can't hide a tool from this
    tools = asyncio.run(MCPServer.list_tools(server))
    assert {t.name for t in tools} == set(required), "every registered tool needs an entry in REQUIRED_SCOPE"
    all_scopes = sorted(set(required.values()))
    for tool in tools:
        need = required[tool.name]
        if tool.annotations and tool.annotations.read_only_hint:
            assert need == "tickets:read", f"{tool.name} is marked read-only but needs {need}"
        args = {p: "T-1" for p in tool.input_schema.get("required", [])}
        before = dict(store)
        with pytest.raises(ToolError, match="scope"):  # every scope except its own
            asyncio.run(as_caller([s for s in all_scopes if s != need], server.call_tool, tool.name, args))
        assert store == before, f"{tool.name} changed data without its scope"
        asyncio.run(as_caller([need], server.call_tool, tool.name, args))  # and its own scope is enough


def test_every_tool_needs_its_declared_scope():
    assert_every_tool_needs_its_scope(mcp, REQUIRED_SCOPE, TICKETS)

When someone adds reopen_ticket next year and forgets both require_scope and the matrix entry, the coverage line goes red before the tool ships. If they add the entry but not the check, the call with the wrong scopes doesn't raise and the test fails. If they mark it read_only_hint=True while it needs tickets:write, the annotation line fails. TICKETS is the example's stand-in for the ticketing backend, and comparing it before and after catches a tool that writes first and checks the scope second.

This version replaces an earlier test that picked its targets by annotation: it called every tool not marked read-only with a tickets:read token. A reader showed the hole. Mark a write tool read_only_hint=True, skip require_scope, and that test never calls it, so it passes while a read token changes data. The annotation decided what got tested, which is backwards when annotations are the thing you can't trust. The new test also calls MCPServer.list_tools(server) directly, so a scope-filtered tools/list override (see below) can't hide a tool from it, and it builds the scope list from the matrix rather than from a hard-coded list that goes stale when you add a scope. The example repo has a mutation test for each of these cases. You could instead scan the registry for tools without require_scope in their source, which is cheaper. But that only proves the call appears somewhere in the function, not that it runs before the side effect. The behavioral test is the one to keep.

Background work keeps a stale token

get_access_token() reads a context variable that the SDK's auth middleware sets for each request and resets when the request ends. What your code sees depends on how it starts extra work:

Started with Sees the token?
A sync tool (def), which the SDK runs via anyio.to_thread.run_sync Yes, AnyIO copies the context to the worker thread
asyncio.create_task() Yes, and it keeps seeing it after the request ends
asyncio.to_thread() Yes
loop.run_in_executor() No, None
threading.Thread No, None

The None cases are the safe ones: require_scope fails closed and denies. The dangerous case is the task that outlives its request. It authorizes with a snapshot of the token, even after that token has expired or been revoked. So check scopes in the handler before you spawn anything, pass the values the background work needs explicitly, and never call require_scope from a task that can outlive the request.

Spec details that cost you tokens

The spec lets tools/list vary by the authorization on the request, so you can list only the tools the caller's scopes allow. Be careful what you hide. The spec has clients start with the minimal scopes_supported set and add scopes through step-up when a call fails with insufficient_scope. A tool the model never sees is never called, so the challenge never fires and a user who would happily grant tickets:write is never asked. Hide only the tools behind scopes this caller can't get at all, such as delete_ticket for users who will never hold tickets:admin. That still saves prompt tokens, since every tool definition the client loads costs context on every turn, and it doesn't break the upgrade path for the rest.

Keep tool order stable. The spec says servers SHOULD return tools in the same order when the set hasn't changed, because it improves prompt-cache hit rates when tools sit in the model's context. A shuffled list quietly defeats prefix caching.

Never forward the user's token downstream. If close_ticket calls your ticketing API, use the server's own credentials or a token from a proper exchange. Passing the incoming token through breaks the spec's "MUST NOT ... transit any other tokens" rule.

Do this today

Add the scope-matrix test above to your server's CI. It takes a few minutes, it catches the mistakes annotations can't, and it keeps protecting you as the tool list grows. Then check your server for the four basics: no token gets a 401 with resource_metadata in WWW-Authenticate; the protected resource metadata is served at that URL; a token for a different audience gets a 401; and a tickets:read token calling close_ticket gets an isError: true result that names the missing scope.

Thanks to Arhan Canli, whose comment prompted the scope test and the background-task section, and to Edward Izgorodin and Moein, whose comments corrected the advice on hiding tools and hardened the test, and to tgapps, who showed that a write tool mislabelled as read-only slipped past the old test, which led to the scope matrix. Updated October 26, 2026. The code is tested in CI against mcp 2.3.0 on Python 3.13 (articles/examples/mcp-scopes in this site's repo). validate_jwt stands in for your identity provider's JWT validation. Pin your SDK version, because names like MCPServer replaced earlier ones.

Sources

Need GPU and LLM API prices in your own scripts or dashboards? The daily-verified data behind this site is available as a price API on Apify and a full price history ($9).