Developer DocsMCP & agent security

Secure Remote MCP Servers in 2026: OAuth, Stateless HTTP and Python Preflight Tests

A practical MCP 2026-07-28 engineering guide to OAuth discovery, token audiences, issuer validation, stateless routing headers and tested Python preflight checks.

Original illustration of an OAuth client, MCP resource server and least-privilege tools for the 2026 stateless protocol.
Original LLM Scorebook editorial illustration; not a production deployment screenshot or independent security assessment.

Remote Model Context Protocol servers are easy to demonstrate and surprisingly easy to authorize incorrectly. A successful OAuth login does not prove that the resulting access token belongs to the MCP server, that a tool call is scoped to the right tenant, or that a gateway is interpreting the same request as the application. The July 28, 2026 MCP revision makes those boundaries more explicit while replacing the old transport-session model with a stateless request envelope.

This guide treats authorization and transport as one engineering problem. We will identify which component is responsible for each decision, examine current protocol requirements, build an offline Python preflight for resource metadata and routing headers, and define a test plan for a production deployment. The downloadable example was exercised with Python 3.11 standard-library tests. It is not a complete OAuth client, JWT validator, MCP SDK or penetration test, and no live identity provider was contacted.

The real design decision: where trust starts and ends

Imagine a course-building agent with a remote MCP tool named get_project. The agent's host application authenticates a user, calls a tool server, and retrieves project details. Three questions must be answered independently: Who issued the access token? Which resource was the token issued for? Which project is the authenticated user permitted to read? If the server answers only the first question, it can become a confused deputy. If it answers only the second, it can still expose data across tenants.

OAuth client discovers an issuer, obtains a resource-bound token, and calls an MCP server that checks issuer, audience, scope and tenant before executing a tool
Figure 1. Original LLM Scorebook architecture diagram based on the MCP authorization specification. Arrows show responsibilities, not measured traffic.

The central rule is that authentication identifies a principal while authorization constrains what that principal may do to a specific resource. An LLM's decision to call a tool is a proposal, not permission. Enforce permission outside the prompt, at the resource boundary, and again at the object lookup when a tool reads or mutates data.

ActorOwnsMust not assume
MCP clientDiscovery, registration, PKCE, state and issuer checks, resource-bound token requestAny token from the identity provider can be sent to any server
Authorization serverUser consent, token issuance, issuer identity and metadataEvery resource shares the same authorization policy
MCP resource serverInbound token validation, audience, scopes, tenant and object isolationA valid signature alone authorizes a tool or database row
Downstream APIIts own audience, credentials, policy and auditAn inbound MCP token is valid for another service

What MCP 2026-07-28 changed

The maintainers released revision 2026-07-28 on July 28, 2026. The new core removes the initialize/initialized handshake and protocol-level Mcp-Session-Id for modern requests. Every request carries its protocol version and client metadata; server/discover is optional. Standard routing headers let gateways identify methods and tools without parsing JSON. Authorization updates strengthen issuer validation, discovery and client-registration practices.

These are protocol-version differences, not evidence that every SDK has migrated. Older 2025-era clients can still use compatibility flows. Identify the negotiated revision before deleting session handling. The official release notes explain the migration; the transport specification defines exact wire requirements.

Discovery must happen before login

A remote MCP client should not guess an OAuth authorization endpoint from the MCP host. The MCP server is a protected resource and advertises one or more authorization servers through OAuth Protected Resource Metadata, defined by RFC 9728. For an MCP endpoint at https://mcp.example.com/mcp, a client can discover metadata at the path-specific well-known URI or the root well-known URI; a WWW-Authenticate challenge may supply the authoritative metadata URL directly.

json · illustrative metadata
{ "resource": "https://mcp.example.com/mcp",
  "authorization_servers": ["https://login.example.com/tenant-a"],
  "scopes_supported": ["projects:read"] }

The resource value identifies the intended audience. It is not a display label. A token requested for https://mcp.example.com/mcp should not automatically authorize https://api.example.com or another tenant's MCP endpoint. A client must validate the resource metadata it receives and avoid substituting a different resource merely because a redirect or tool description suggests one.

The issuer may have a path component. MCP requires clients to try the documented OAuth and OpenID Connect well-known discovery forms in priority order, then validate that the returned metadata's issuer exactly matches the expected issuer. This prevents a discovery response from quietly redirecting token exchange to an unrelated authority. Consult the 2026 authorization-server discovery rules rather than hardcoding a single well-known URL.

Client registration, PKCE and issuer mix-up protection

The 2026 authorization profile prefers OAuth Client ID Metadata Documents where supported. Pre-registration is another valid route; Dynamic Client Registration remains available for backward compatibility but is deprecated as the preferred mechanism. The client ID belongs to one issuer. If a user connects two independent authorization servers, do not share client credentials, refresh tokens or cached grants between them. The authorization-server metadata and issuer are part of the credential's identity.

For authorization-code flows, clients use PKCE with the S256 challenge method. The authorization server's discovery document must advertise supported challenge methods; if that field is missing, the MCP security rules require clients to refuse the flow rather than assume PKCE is present. Store the code verifier and expected issuer with the request's state, bind the redirect to that request, and validate state before exchanging the authorization code.

There is an easily missed 2026-specific check: RFC 9207 authorization-response issuer validation. If metadata advertises authorization_response_iss_parameter_supported=true, the callback must contain iss and it must exactly match the issuer recorded before redirection. If the metadata does not advertise it but the response contains iss, the client still compares it. Only when support was not advertised and iss is absent may the client proceed under the current specification. Do not normalize slashes, letter case or percent-encoding before comparison. An issuer mismatch is a hard stop, not a warning.

The official authorization overview and security considerations make these rules explicit. They protect the code exchange, but they do not replace application-level approval for a destructive tool.

The resource parameter is not optional decoration

Clients must include the RFC 8707 resource parameter in both authorization and token requests. Use the canonical URI of the intended MCP server, including a meaningful path when multiple resources share a host. The value is a request for a token usable at that resource, not a promise that every issuer supports the same representation. On the resource-server side, validate the resulting token's audience according to the issuer's token format or introspection contract. Never infer audience merely from the presence of a bearer string.

http · schematic authorization parameters
response_type=code
client_id=registered-client-id
redirect_uri=https://app.example.com/callback
code_challenge_method=S256
code_challenge=...
state=...
resource=https%3A%2F%2Fmcp.example.com%2Fmcp

Production clients must generate cryptographically random state and a PKCE verifier, validate the exact registered redirect URI and preserve issuer-specific token storage. The code above deliberately omits real credentials and is not a copy-and-run login implementation. On the token request, repeat the same resource value alongside the authorization code and PKCE verifier. Never put bearer tokens in URL query parameters, logs, prompts or model-visible tool descriptions.

One tempting shortcut is to accept an identity token because it contains a familiar user ID. That is incorrect: an OpenID Connect ID token proves an authentication event to its client audience; it is not automatically an access token for the MCP resource. Another shortcut is to accept a token for a broad API gateway hostname while the actual MCP server has a narrower audience. Define the resource identity explicitly and verify it at every entry point.

The relevant normative references are RFC 8707 and the MCP token requirements.

The resource server must enforce four boundaries

First, validate token authenticity with the configured issuer. For signed JWT access tokens this usually means a trusted JWKS URL, a fixed allowlist of acceptable signing algorithms, signature verification, expiration and issuer checks. For opaque access tokens, use the issuer's documented introspection mechanism instead. A JWT decoder is not an authorization system by itself: check audience, token type and revocation policy appropriate to the provider. Do not select a signing algorithm from an untrusted token header without enforcing a server-side allowlist.

Second, evaluate the scopes required by the actual operation. A projects:read token must not authorize projects:delete. The 2026 MCP profile recommends a 403 response and a WWW-Authenticate challenge with error="insufficient_scope" plus the required scopes. A client can request step-up authorization using the union of its previous scopes and the newly challenged scopes, with a bounded retry count. An expired or invalid token instead requires 401; an absent credential should not be confused with a missing permission.

Third, bind every database query to the verified tenant or account context, not to an arbitrary tenant ID supplied by the model. A tool input may specify a project identifier, but the server should resolve it under the authenticated tenant, such as WHERE tenant_id = verified_tenant AND project_id = requested_project. Returning a generic not-found response for inaccessible objects can reduce accidental information disclosure.

Fourth, if the tool calls another API, acquire a separate credential for that downstream resource. The MCP security specification forbids simply passing the inbound MCP token through. Separate tokens, audiences, audit trails and least-privilege permissions preserve the boundary between a user-authorized MCP operation and a provider API operation.

Stateless HTTP changes gateway design

In the 2026 transport, each JSON-RPC request is a separate HTTP POST to the MCP endpoint. The client advertises support for application/json and text/event-stream, and the server may answer with a single JSON response or request-scoped SSE stream. A long-running change subscription is a separate subscriptions/listen request; it is not the old global GET event stream. Server-to-client requests such as elicitation move into Multi Round-Trip Requests rather than unsolicited requests on an open connection.

Diagram comparing the HTTP routing envelope and JSON-RPC request fields that must agree
Figure 2. Original request-envelope diagram derived from the Streamable HTTP specification. It illustrates required agreement; it is not a captured network trace.

The required MCP-Protocol-Version header must agree with io.modelcontextprotocol/protocolVersion inside the request's _meta. Mcp-Method must match the JSON-RPC method. For tools/call, resources/read and prompts/get, Mcp-Name mirrors the relevant name or URI. A mismatch is a 400 protocol error, not an invitation for the gateway to guess the intended operation. When a name contains unsafe header characters, the specification defines a Base64 sentinel representation that must be decoded before comparison.

Gateways gain simpler routing and rate limits, but the JSON body remains authoritative. A reverse proxy can choose a backend using Mcp-Method; the backend still verifies the header against the body before execution. A client-controlled routing header must never become a substitute for authorization. Origin validation also remains mandatory for Streamable HTTP, including rejecting invalid browser origins with 403. On a local machine, bind to loopback unless an explicit network exposure is required.

Build an offline Python preflight before touching production

The companion Python source file implements three intentionally narrow checks: protected-resource metadata identity, RFC 9207 callback issuer comparison, and agreement between a 2026 JSON-RPC tool request and its routing headers. It uses only Python 3.11+ standard-library modules. It neither sends OAuth requests nor validates access tokens. That distinction is important: this is a reproducible preflight for integration tests, not a substitute for an issuer, resource-server middleware or the current MCP SDK.

python · from the companion example
from mcp_2026_preflight import (
    validate_protected_resource, build_tool_call,
    verify_routing_headers, validate_callback_issuer
)

metadata = {
    "resource": "https://mcp.example.com/mcp",
    "authorization_servers": ["https://auth.example.com/tenant"]
}
issuers = validate_protected_resource(
    metadata, "https://mcp.example.com/mcp"
)
validate_callback_issuer(issuers[0], issuers[0], True)
body, headers = build_tool_call(
    "get_project", {"project_id": "alpha"}
)
verify_routing_headers(body, headers)
print(headers["MCP-Protocol-Version"], headers["Mcp-Method"])

Expected offline output is 2026-07-28 tools/call. The example encodes non-ASCII and whitespace-sensitive tool names using the protocol's Base64 sentinel, then decodes them for comparison. It rejects a metadata document that advertises a different protected resource or an insecure authorization-server URI. It also rejects an issuer mismatch when an authorization response supplies an unexpected iss value.

For a real client, the next layer is an MCP SDK that implements negotiation, authorization-code flow, PKCE, token storage, JSON-RPC response handling, SSE and cancellation. The offline functions are useful for assertions in your own integration harness, but they intentionally do not implement those runtime responsibilities.

Run the sample and interpret the result correctly

Download both mcp_2026_preflight.py and test_mcp_2026_preflight.py into the same directory, or use them directly from the repository. No API key, network access or paid model is required. The standard-library unittest runner makes the test contract visible without introducing a dependency on a test framework.

shell · offline validation
python --version
python -m unittest discover -s examples -p 'test_mcp_2026_preflight.py' -v

In the authoring environment, this command completed with six passing test methods on Python 3.11. The cases cover matching metadata, wrong resource, HTTP authorization server, callback issuer rules, round-trip encoding of ASCII and non-ASCII names, and a deliberate method/header mismatch. This is an actual local unit-test result, not an OAuth interoperability claim. Fixture domains are examples; no external service was contacted.

CheckEvidenceStatus
Resource identity and issuer metadataOffline unittest fixturesPASS
Issuer callback decision logicOffline unittest fixturesPASS
Header encoding and mirror comparisonOffline unittest fixturesPASS
Real OAuth code exchange and refreshRequires configured issuer and SDKNOT RUN
Live JWT verification and tenant isolationRequires resource server and IdP integrationNOT RUN
Multi-instance HTTP/SSE interoperabilityRequires deployed MCP serviceNOT RUN

Passing these tests does not certify protocol compliance. They prove only that a small deterministic helper behaves as asserted. Production negative tests should include an expired token, a valid token with the wrong audience, insufficient scope, a mismatched tenant, an unapproved browser origin, inconsistent request headers, stale issuer metadata and interrupted SSE responses. Do not call a mock-auth test a successful production authentication test.

Threat model: four failures that look like normal traffic

Cross-resource token reuse. A host application connects both a document MCP server and a billing MCP server. An attacker or faulty integration sends a token intended for documents to the billing endpoint. The signature can be perfectly valid because both servers trust the same issuer. Only the resource-specific audience check stops the request. This is why a shared login session is not sufficient evidence of permission.

Issuer mix-up during login. A client discovers multiple identity providers. A malicious endpoint attempts to return an authorization response that causes the client to redeem a code at a different provider. The issuer comparison and per-issuer credential isolation prevent that class of cross-provider confusion. PKCE protects code exchange, but it does not excuse skipping the expected issuer check.

Tenant confusion inside a tool. A model calls get_project with a project ID copied from retrieved text. The user is authenticated and the token has read scope, yet the project belongs to another tenant. If the server queries by project ID alone, the tool can disclose a valid record. Query by verified tenant and object ID, and test a negative cross-tenant case.

Header/body disagreement. A gateway routes on a header that says tools/list while the JSON body asks for tools/call. A naïve edge policy may apply a cheaper permission or rate-limit class than the backend operation actually performs. The 2026 header-mirror validation requirement closes that ambiguity when implemented at the boundary that dispatches requests.

These are threat-model examples, not claims of attacks observed against a particular company. They explain why the individual checks are necessary and why each must be tested independently. For broader empirical context, see the May 2026 remote-MCP authentication measurement study; its sample and methodology should not be generalized to every MCP deployment.

From offline preflight to a deployable service

For production, use a maintained MCP SDK implementing the 2026 revision rather than treating the preflight module as a complete transport. Put HTTPS termination at a trusted reverse proxy. Configure exact allowed hosts and browser origins, request size limits, timeouts and bounded concurrency. Keep the OAuth resource metadata publicly reachable; protect the actual MCP endpoint and tool execution with token validation and operation-level authorization. A missing Origin header from a legitimate non-browser client is not automatically malicious, but a present invalid Origin must be rejected.

Resolve JWKS from a configured, trusted issuer URL. Cache keys with a controlled refresh policy and handle key rotation without accepting arbitrary JWKS URLs embedded in incoming tokens. Validate iss, aud, expiry and other issuer-specific claims; if using introspection, check the active state and resource binding there. Fail closed when the issuer is unavailable and a token cannot be validated. Distinguish temporary dependency failures from invalid credentials in internal logs, but do not reveal token contents in public error bodies.

For horizontal scaling, the stateless core eliminates the old requirement to preserve protocol sessions on one worker. It does not eliminate application state. If a tool launches a background job, persist a server-generated job handle and ownership in a database, and require the same authenticated tenant to retrieve its result. If a tool requests user input through Multi Round-Trip Requests, validate that the resumed request still belongs to the same authorized operation. Retries need idempotency rules for writes, not just a transport reconnect.

Set separate budgets for discovery, token verification, tool execution and downstream API calls. A model can trigger retries, so bound tool-call count and wall-clock duration as well as API rate. Collect per-operation latency, rejection reasons, tenant-safe audit identifiers and token-issuer identifiers, but avoid logging bearer tokens, raw prompts or sensitive tool results by default. This creates enough evidence to debug failures without turning observability into a credential store.

A migration plan that can be rolled back

Begin by inventorying your existing MCP clients and servers. Record each SDK version, supported protocol revision, transport, session dependency, OAuth provider, canonical resource URI, tool catalog and tool-specific scopes. Capture a representative request/response trace with secrets removed. A migration should be evaluated on whether existing user operations still complete safely, not merely whether a health check returns HTTP 200.

Next, deploy the modern endpoint behind a staging hostname and use a compatibility client that can negotiate both protocol eras. Test server/discover where supported, tools/list, tools/call, errors, cancellation, response streaming and any subscription behavior. Confirm that Mcp-Method, Mcp-Name and protocol-version headers agree with the JSON-RPC body. The new server should reject malformed requests deterministically rather than silently guessing an older version.

Then exercise authorization as a separate matrix: a correct resource-bound token; a token for another audience; a token from another issuer; expired credentials; insufficient scope; a request for another tenant's object; an invalid browser origin; and a downstream API that requires a different token. Record expected HTTP status, challenge headers and whether a tool was invoked. Every rejected request should leave the underlying tool unexecuted.

Finally, roll out to a small client cohort and compare error rates, successful tool outcomes, p95 tool latency, token-refresh behavior, and cross-worker request handling with the old path. These are measurements to collect, not numbers this article claims to have observed. Keep a rollback route until the client population and SDK versions are known. If the new server supports both eras, test that older session traffic cannot be confused with modern stateless traffic.

For related architecture decisions, read LLM Scorebook's agent context and state guide and cost-per-accepted-task analysis. Those address persistence and economics, while this article defines the security and transport boundary.

Alternatives and engineering trade-offs

Remote MCP with OAuth is appropriate when tools serve multiple users, access cloud data or need central policy and audit. It carries operational obligations: an authorization server, client registration, key rotation, metadata discovery, scope design and failure handling. The reward is an explicit security boundary that survives changes in the model or orchestration framework.

Local stdio MCP is a different trust model. The specification does not recommend applying the HTTP OAuth profile to stdio; a local host typically passes credentials through a controlled process environment. That may be simpler for a single-user desktop tool, but the process still inherits filesystem, network and account permissions. Sandbox it and avoid exposing its command line or environment in logs. Local execution is not automatically safe execution.

A conventional REST tool API may be preferable when only one application needs a few stable endpoints and MCP interoperability offers little benefit. REST still needs OAuth audience checks, tenant isolation and idempotency. MCP adds discoverable tool schemas and a common agent-facing contract, but it does not remove normal API engineering. Choose the protocol because it reduces integration friction, not because it substitutes for access control.

For either approach, treat authorization scopes as an application contract. Broad scopes are easier to configure but make every compromised token more powerful. Extremely granular scopes improve least privilege yet can cause repeated consent prompts and complicated policy management. Start with operations that reflect actual business permissions, such as read versus write, and use explicit step-up for destructive actions. Keep model instructions separate from these enforcement rules.

A release checklist for engineering teams

Before exposing a protected MCP endpoint publicly, require an approved resource URI, validated issuer metadata, issuer-specific client registration, PKCE and state, strict callback issuer comparison, resource-bound access tokens, server-side audience and scope checks, tenant-scoped data access, origin/header validation, distinct downstream credentials, bounded retries and secret-safe logs. Exercise every negative test, not only a happy-path tool call. Treat missing evidence as an open deployment blocker rather than a passing check.

Sources, verification and what was not tested

Primary documents were reviewed on October 12, 2026. This guide refers specifically to MCP protocol revision 2026-07-28; older tutorials often describe the 2025 handshake and different authorization registration defaults. The diagrams are original editorial explanations. No provider-supplied performance figures, external screenshots, production credentials or third-party photographs were reused.

  1. MCP maintainers: July 28, 2026 specification announcement — stateless core, routing headers and authorization changes.
  2. MCP 2026-07-28 authorization specification — resource indicators, scopes, token handling and issuer checks.
  3. MCP protected-resource and authorization-server discovery — well-known URI precedence and issuer validation.
  4. MCP authorization security considerations — PKCE, audience binding and token passthrough.
  5. MCP Streamable HTTP transport — header/body agreement, origin checks, request framing and SSE.
  6. RFC 9728, RFC 8707, RFC 9207 — underlying OAuth standards.

The included source and tests were checked offline. Live OAuth interoperability, production JWKS rotation, refresh-token handling, browser integration, model-driven tool behavior, horizontal scaling and real security testing remain not run. Do not interpret this guide as a certification of an MCP server.

Found something that needs a correction?

Let the editorial desk know

Continue reading

Browse developer docs