Sub topic 15
Remote servers and authorization
This chapter covers connecting your host to an MCP server that runs somewhere else, and how that server decides who may call it. It assumes you have read the chapters on transports and the SDK client session. You should be comfortable with async/await and basic HTTP headers.
Why remote servers differ from local ones
With stdio, your host starts the server as a subprocess. The operating system already limits who can talk to it, because only your process holds the pipes. Credentials usually arrive through environment variables that you pass at launch.
A remote server is a separate service reached over a network. Anyone who can reach the URL can send it requests. Three things change:
- The server has to identify callers and decide what each may do.
- Requests cross a network, so they need TLS, timeouts and retries.
- The server can serve many users at once, so state and tokens must be kept per user.
Streamable HTTP is the transport for this case. The authorization rules in the MCP specification apply to HTTP transports only. For stdio, the specification expects credentials to come from the environment.
How Streamable HTTP works
A Streamable HTTP server exposes one HTTP endpoint, for example https://tools.example.com/mcp. The same JSON-RPC messages you already know travel over it.
- The client sends each JSON-RPC message as an HTTP
POSTto the endpoint. - For a request, the server answers with either a plain JSON body or a Server-Sent Events (SSE) stream. SSE is a long-lived HTTP response that delivers several messages in sequence. The server uses a stream when it wants to send progress notifications or its own requests before the final result.
- The client may also open a
GETto the endpoint to receive server-initiated messages. - The server may assign a session by returning an
Mcp-Session-Idheader on the initialize response. The client must send that header on every later request. - After initialization, the client sends an
MCP-Protocol-Versionheader with the negotiated version.
The SDK handles all of this. Your code changes only in how you open the connection.
Connecting with the Python SDK
Compare this with the stdio client from earlier. Only the connection function changes. The ClientSession code, list_tools and call_tool stay the same.
import asyncio
import os
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
SERVER_URL = "https://tools.example.com/mcp"
async def main():
token = os.environ["MCP_ACCESS_TOKEN"]
headers = {"Authorization": f"Bearer {token}"}
async with streamablehttp_client(SERVER_URL, headers=headers) as (
read,
write,
get_session_id,
):
async with ClientSession(read, write) as session:
await session.initialize()
print("session id:", get_session_id())
listed = await session.list_tools()
for tool in listed.tools:
print(tool.name, "-", tool.description)
asyncio.run(main())The context manager yields a third value, get_session_id, a function that returns the session ID the server assigned, or None if it assigned none. Recent SDK releases have been renaming this helper, so check the name your installed version exports.
To test against a server you run yourself, change the last line of server.py to mcp.run(transport="streamable-http"). The SDK serves it at http://127.0.0.1:8000/mcp by default.
The authorization model
The MCP specification builds authorization on OAuth 2.1. The roles map like this:
| OAuth role | In MCP |
|---|---|
| Resource server | The MCP server. It accepts or rejects access tokens. |
| Client | Your host application. It obtains tokens and presents them. |
| Authorization server | A separate service that authenticates the user and issues tokens. |
| Resource owner | The user who grants your host access. |
The MCP server does not need to issue tokens itself. It only validates them. Most deployments delegate login to an existing identity provider.
The discovery and token flow
A client that has never seen a server needs to find out where to log in. The specification solves this with standard metadata documents.
The steps in words:
- The client sends a request with no token. The server answers
401 Unauthorizedand aWWW-Authenticateheader that points to its protected resource metadata (RFC 9728). - That metadata names one or more authorization servers.
- The client fetches the authorization server's metadata (RFC 8414) to learn its authorization and token endpoints.
- The client registers itself if needed. The specification supports OAuth Client ID Metadata Documents and Dynamic Client Registration (RFC 7591), so a host does not need a hand-issued client ID for every server.
- The client sends the user to the authorization endpoint using the authorization code flow with PKCE. PKCE (Proof Key for Code Exchange) ties the code to a secret that only your client knows, so a stolen code is useless.
- The client includes a
resourceparameter (RFC 8707) naming the MCP server. The issued token is then bound to that server through its audience. - The client exchanges the code for an access token, usually with a refresh token, and sends
Authorization: Bearer <token>on every request.
The Python SDK includes client-side OAuth support that takes a token storage object and a redirect handler, so you do not need to write these steps by hand. The details of that API change between releases, so read the docs for your version. What you must supply yourself is secure token storage and a way to open the browser.
Rules for the server side
If you write the remote server, follow these rules:
- Validate every token on every request. Check the signature, the expiry and that the audience is your server.
- Reject tokens that were issued for a different service. Never forward a token you received from a client to an upstream API. This "token passthrough" lets a malicious or buggy client use your server as a confused deputy, an intermediary that gets tricked into using its own authority for someone else.
- Return
401for missing or invalid tokens and403for valid tokens that lack the required scope. - Check the
Originheader on HTTP requests, and bind local test servers to127.0.0.1, not0.0.0.0. A web page in the user's browser could otherwise reach a local server through DNS rebinding.
What your host must handle
Remote calls fail in ways stdio calls do not. Plan for these cases:
- Expired tokens. Refresh the token and retry once. If the refresh fails, send the user through login again.
- Lost sessions. A server may answer
404for a session ID it no longer knows. Start a freshinitializeand discard the old session. - Network failures. Set explicit connect and read timeouts. Feed a timeout back to the model as a tool error, as described in the chapter on results and errors, so the conversation continues.
- Secrets in logs. Keep tokens out of log lines, tracebacks and the messages you send to the model.
Exercise
Your host connects to a remote MCP server and receives 401 with a WWW-Authenticate header. List, in order, what the client should do before it can send a successful tools/list request.
Show answer
Fetch the protected resource metadata that the header points to and read the authorization server it names. Fetch that server's metadata to find its endpoints. Register the client if needed. Send the user through the authorization code flow with PKCE, including the resource parameter for the MCP server. Exchange the code for an access token. Then retry the request with Authorization: Bearer <token>, after initialize completes on the session.
Exercise
A teammate's remote MCP server receives a user token and passes it unchanged to a third-party API. Why is this unsafe, and what should the server do instead?
Show answer
The token was issued for the MCP server, not for the third-party API. Passing it on lets any holder of a token act through the server with authority it was never granted, and it breaks audience checks (the confused deputy problem). The server should validate that the token's audience is itself, then call the third-party API with a separate credential obtained for that purpose, such as its own token or a delegated one issued by that API's authorization server.