Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
Deploy one invoice MCP server two ways: locally over stdio with the key in the environment, and remotely over HTTP with a bearer token checked for audience and scope, without leaking a secret in config, tool results or logs.
What you will learn
- Explain how a credential reaches a local stdio MCP server and a remote HTTP one
- Walk through the OAuth-based handshake: 401 challenge, metadata, token, bearer header
- Return the right status for a missing token, a wrong audience, a missing scope and a token in the URL
- Keep secrets out of a committed .mcp.json, tool results and access logs
Before you start
- MCP transports: stdio or Streamable HTTP
- Basic HTTP status codes
Building an MCP server is half the job. Deploying it, and deciding who may call it, is the other half. Picture a support bot that asks to void invoice A-101. Who is allowed to do that?
In this article we deploy one small invoice server two ways. Locally over stdio, with the key in the environment. And remotely over HTTP, where every request needs a bearer token with the right scope. Along the way we keep every secret out of the repo, out of tool results and out of the logs.
Two deployments, two ways to prove who you are
Think of a key to your own drawer, and a visitor badge at reception.
- stdio, the drawer key. The host app starts the server as a subprocess. The key sits in the environment and the process inherits it. There is no network, so there is nothing to sign in to.
- HTTP, the visitor badge. The server runs on its own and any client can reach the endpoint. So every request carries a bearer token from an authorization server. Reception checks the right building (the audience) and the right floors (the scope).
In the MCP spec, authorization is optional. HTTP servers should follow it; stdio servers should not, and take credentials from the environment instead.
The remote handshake
The spec builds HTTP authorization on OAuth 2.1, and your MCP server plays the resource server. The client runs the sign-in; your server only checks the token.
The project
The lecture's project is a deliberately small, hand-written sketch in plain Python, localhost only. All keys and tokens in it are fake stand-ins: issuer.py stands in for the authorization server and backend.py for the real invoice service. The real OAuth sign-in (browser, consent) is done by the MCP client and the authorization server and is not part of the sketch. Real servers use an official MCP SDK.
.mcp.json: the config you commit
{
"mcpServers": {
"invoices-local": {
"type": "stdio",
"command": "python",
"args": ["stdio_server.py"],
"env": {
"INVOICE_API_KEY": "${INVOICE_API_KEY}"
}
},
"invoices-shared": {
"type": "http",
"url": "https://mcp.example.test/mcp",
"headers": {
"Authorization": "Bearer ${INVOICE_TOKEN}"
}
}
}
}
The stdio server gets its key through env, but only as a reference to a variable. The HTTP server's bearer token is a reference too. The real values stay in the environment, never in the repo, and .gitignore keeps .env and *.key files out of version control.
auth.py: the gatekeeper
"""The HTTP door's gatekeeper: who may call, and with which scope."""
from urllib.parse import parse_qs, urlparse
import issuer
METADATA = "https://mcp.example.test/.well-known/oauth-protected-resource"
SCOPE_FOR = {"invoice_lookup": "invoices:read", "invoice_void": "invoices:write"}
def www(error=None, scope=None):
parts = [f'error="{error}"'] if error else []
parts += [f'scope="{scope}"'] if scope else []
parts.append(f'resource_metadata="{METADATA}"')
return "Bearer " + ", ".join(parts)
def check(headers, path, tool):
"""Returns (status, error, scope)."""
if "access_token" in parse_qs(urlparse(path).query):
return 400, "invalid_request", None
auth = headers.get("Authorization", "")
if not auth.startswith("Bearer "):
return 401, None, None
info = issuer.lookup(auth[len("Bearer "):])
if info is None or info["aud"] != issuer.RESOURCE:
return 401, "invalid_token", None
need = SCOPE_FOR.get(tool)
if need and need not in info["scope"].split():
return 403, "insufficient_scope", need
return 200, None, None
www()builds theWWW-Authenticatechallenge. Every failure points the client to the metadata address.- A token in the query string is a 400. The spec says the token goes in the header only, because URLs get logged.
- No bearer header is a 401.
- An unknown token, or one issued for another audience, is a 401 too. The server accepts only tokens meant for itself.
- A valid token without the tool's scope is a 403, and the challenge names the scope needed.
invoice_core.py: secrets stay out of tool results
def run_tool(name, invoice_id):
key = os.environ.get("INVOICE_API_KEY", "")
try:
if name == "invoice_void":
done = backend.void(invoice_id, key)
if done:
text = f"voided {invoice_id}"
return tool_result(text)
text = f"{invoice_id} is not open"
return tool_result(text, True)
status = backend.status(invoice_id, key)
except backend.BackendError:
text = "invoice service unavailable"
return tool_result(text, True)
if status is None:
text = f"no invoice {invoice_id}"
return tool_result(text, True)
return tool_result(f"invoice {invoice_id}: {status}")
The key is read from the environment when it is used; it is not in the code. When the backend fails, its own error text stays here, and the tool returns a short, safe message. The model needs to know the call failed. It never needs to see the key.
Run the client
client.py runs the stdio server with a valid key and an expired one, then makes six HTTP calls, then checks two config files and compares a leaky tool result with the safe one. The server is real and runs on this machine; there is no model in the loop.
stdio: the client starts stdio_server.py with the key in its environment
-> invoice_lookup A-100 (valid key)
<- invoice A-100: paid
-> invoice_lookup A-100 (expired key)
<- invoice service unavailable (isError true)
http: every request carries Authorization: Bearer <token>
POST /mcp with no token -> 401
challenge: resource_metadata=/.well-known/oauth-protected-resource
GET protected resource metadata -> 200 https://auth.example.test
POST /mcp invoice_lookup, read token -> 200 invoice A-100: paid
POST /mcp invoice_void, read token -> 403
challenge: error=insufficient_scope scope=invoices:write
POST /mcp invoice_void, write token -> 200 voided A-101
POST /mcp token for another server -> 401
challenge: error=invalid_token
POST /mcp token in the query string -> 400
challenge: error=invalid_request
The expired key gives a short tool error that never shows the key. With no token, the 401 challenge points to the metadata. A read token can look up an invoice but gets a 403 when it tries to void, and the challenge names invoices:write. A write token can void. A token meant for another server is a 401, and a token in the URL is a 400.
Reading auth failures from the access log
The server writes one log line per request: the tool, the last four characters of the token, and the status. Never the whole token.
server access log:
POST /mcp tools/call invoice_lookup token=...none -> 401
POST /mcp tools/call invoice_lookup token=...ad-1 -> 200
POST /mcp tools/call invoice_void token=...ad-1 -> 403 insufficient_scope invoices:write
POST /mcp tools/call invoice_void token=...te-1 -> 200
POST /mcp tools/call invoice_lookup token=...er-9 -> 401 invalid_token
POST /mcp tools/call invoice_lookup token=...none -> 400 invalid_request
| Log line | What it means | What to do |
|---|---|---|
| 401, token none | No token was sent | Follow the challenge and get one |
| 403 insufficient_scope | Valid token, missing scope | Ask for a token with that scope; retry only a few times |
| 401 invalid_token | Unknown, expired or issued for another server | A bigger scope will not help; get a token for this server |
| 400 invalid_request, token none | The token came in the query string | Send it in the Authorization header |
The last line shows token=...none because the log drops the query string, so the token never lands in the log.
Match the deployment to the job
| Deployment | Transport | Credential | Scope |
|---|---|---|---|
| A script on one developer's laptop | stdio | Key in the environment | Read-only key |
| A shared lookup for forty support agents | HTTP | Bearer token per person | invoices:read |
| A finance bot that may void invoices | HTTP | Bearer token | Starts with read, steps up to invoices:write only when it must void |
The transport follows who runs the server. The scope follows what the caller must do, and nothing more.
Break it: two leaks
Leak one: a literal token in a committed file. bad_mcp.json holds "Authorization": "Bearer tok-write-1". Once it is committed, everyone who clones the repo holds that token. The project's config check flags it:
config check: .mcp.json
ok invoices-local env INVOICE_API_KEY: ${INVOICE_API_KEY}
ok invoices-shared header Authorization: Bearer ${INVOICE_TOKEN}
config check: bad_mcp.json
BAD invoices-shared header Authorization: holds a literal token
Leak two: a tool result that repeats the backend's error. leaky_core.py passes the backend exception text straight into the tool result. The model reads it, and so does every log of the conversation:
tool result, leaky: backend rejected key demo-key-OLD (isError true)
tool result, safe: invoice service unavailable (isError true)
The fixes are small: a ${VARIABLE} reference in the file, a short message in the tool, and .env in .gitignore. The same goes for your Anthropic API key: keep it server side, scoped to its workspace, rotated, and never embedded in a client.
Recap
- stdio: the key comes from the environment of the process that starts the server.
- HTTP: every request carries a bearer token, checked for audience (401 if wrong) and scope (403 if missing).
- Tokens go in the Authorization header, never the URL (400).
- Secrets stay references in config, and out of tool results and logs.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
Claude Certified Developer - Foundations (CCDV-F) Exam Prep
Build and ship Claude apps: the API, agents, tools and MCP, prompts, evals, security and model choice.View on Udemy ↗: Claude Certified Developer - Foundations (CCDV-F) Exam Prep (paid course, opens in a new tab)Related posts
Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
A support agent forgets the customer's name, order and contact choice after twenty turns and fails 0 of 4 checks. Measure the window, clear old tool output, compact old turns and keep a notes file, and the same chat passes 4 of 4 with 470 tokens instead of 2,945.
What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
LangChain is a box of standard parts (models, prompts, retrievers, tools, parsers) that snap together with a pipe. The same refund question through the plain Anthropic SDK (1 import, 13 lines) and a chain (3 imports, 14 lines) gives the same answer word for word. It pays off when the bot grows; for one call, the SDK is simpler, with 16 packages instead of 38.
Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
A refund assistant built three ways. The chain runs classify, retrieve, reply once: it answers an opening-hours question with the billing line, misses the 30-day window, and sends a $150 refund with approved False. Plain if/while fixes it but hides the flow; a LangGraph StateGraph puts the branch, the retry loop and the approval stop in the arrows.
LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
Two small graphs. A refund skeleton: SupportState, a classify node, a route function on a conditional edge, and an Annotated log that appends instead of overwriting. A help desk: classify and answer call a scripted test model, spam goes straight to END after one model call instead of two, and the same run read with invoke, stream values and stream updates.