Sub topic 15
Remote servers and authorization
This chapter assumes you have read the earlier chapters on transports and the SDK client session. You should be comfortable with ClientSession and async/await.
Why remote servers differ
A stdio server runs as a subprocess on your machine. It inherits your user account, and you pass it credentials through environment variables. A remote server runs elsewhere and speaks Streamable HTTP. Anyone who can reach its URL can send it requests, so it must check who is calling.
Connecting over Streamable HTTP
Only the transport changes. The session code stays the same. The SDK's streamablehttp_client takes a URL and optional headers.
import asyncio
import os
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
URL = "https://example.com/mcp" # replace with your server's endpoint
async def main():
headers = {"Authorization": f"Bearer {os.environ['MCP_TOKEN']}"}
async with streamablehttp_client(URL, headers=headers) as (read, write, _):
async with ClientSession(read, write) as session:
await session.initialize()
listed = await session.list_tools()
print([tool.name for tool in listed.tools])
asyncio.run(main())The third value the context manager yields is a callback that returns the session ID. This example ignores it. To test locally, start the server from the earlier chapter with mcp.run(transport="streamable-http"). It serves /mcp on port 8000 by default.
How authorization works
For HTTP transports, the MCP specification builds on OAuth 2.1. The MCP server acts as a resource server. A separate authorization server issues access tokens.
The steps are:
- The server answers an unauthenticated request with
401and points to its metadata. - The metadata names the authorization server.
- The host sends the user through a login and consent step. This uses the authorization code flow with PKCE.
- The host sends the token in the
Authorizationheader on every request.
The SDK includes OAuth client support, but you must supply token storage and a way to open the user's browser. For service-to-service use, a token your organization issues, passed as above, is often enough.
Common errors
- Hardcoded tokens. Read them from the environment or a secret store. Never put them in source code or logs.
- No refresh handling. Access tokens expire. When a call fails with
401, refresh the token or ask the user to sign in again. Do not pass the failure to the model as if it were a tool result. - Forwarding tokens. A token issued for one server must not be sent to another server. Keep one credential per server.
- Trusting the URL blindly. Connect only to servers you have chosen. A remote server's tool descriptions and results are untrusted input, as the security chapter covers.
- Ignoring network failure. Remote calls can time out. Apply the timeout and step limits from the error-handling chapter.
Exercise
A remote MCP server returns 401 in the middle of an agent loop. Why should the host not pass that failure to the model as a tool result, and what should it do instead?
Show answer
A 401 means the host's credential is missing or expired. The model cannot fix this by choosing different arguments, and showing it the failure wastes context. The host should refresh the token or start the sign-in flow, then retry the request. It should report an error to the model only if recovery fails.