Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

AI Engineering
  • The AI Stack in One Picture: Six Layers Every AI Product Is Built From
  • Tokenization: What an LLM Actually Sees When You Type
  • LLM Tokens, Context Windows and Cost: What One Question Really Costs
  • What an LLM Can and Cannot Do: One Prediction Loop, Its Strengths and Its Gaps
  • Structured LLM Output with Pydantic: Describe the Shape Once, Check Every Reply
  • Temperature, Top-p and Sampling: Why the Same Prompt Gives a Different Answer
  • Open vs Closed LLMs: Cost, Control, Privacy and Capability, Decided per Workload
  • Streaming and Error Handling for LLM Calls: Show the First Word Early, Retry Politely, Fail Calmly
  • Practice: Build a CLI Chat Tool with Memory, Commands, Error Handling and a History Cap
  • Explicit Criteria vs Vague Prompts: Turn Every Adjective Into a Check a Script Can Run
  • Few-Shot Prompting Done Right: How Many Examples, How Different, What Order, and the Leak That Lies
  • Prompt Caching: Keep the Start of Every Request Identical and Pay for the Long Part Once
  • Prompt Versioning and Testing in a Repo: Prompt Files, a Registry, a Hash per Answer and Tests That Gate
  • Context Engineering: What Belongs in the Context Window, Turn by Turn
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What an Embedding Actually Is: Meaning as Numbers, Search by Closeness, and Where Hand-Made Numbers Break
  • The RAG Pipeline Explained: 7 Stages From Documents to a Cited Answer
  • Similarity Search: Finding the Closest Vectors with NumPy and NearestNeighbors
  • Why RAG Exists: The Problem It Solves, Compared With Pasting Everything and Fine-Tuning
  • Real Embedding Models: an Open Model or a Provider API, Then Search, Duplicates and Recommendations
  • Chunking Strategies for RAG: Fixed Size, Sentences or Headings, Measured on One Handbook
  • Vector Databases Hands-On: The Same Search in Chroma and pgvector
  • RAG Prompt Assembly and Citations: Number the Blocks, Fit a Token Budget, Check Every Claim
  • Hybrid Search: BM25 Plus Dense Embeddings, Merged With Reciprocal Rank Fusion
  • Reranking With a Cross-Encoder: When the Second Pass Helps, and When It Doesn't
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Choosing a Vector Index: Flat, HNSW or IVF-PQ, a Memory Estimate, and Filters That Starve Small Customers
  • Citations and Abstention in RAG: What a Citation Proves, and When the Right Answer Is "It's Not in the Documents"
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Cosine, Dot Product or Euclidean Distance: Why Three Measures Pick Three Winners, and the One Fix
  • Choosing an Embedding Model: Dimension, Context Length, Domain and Cost, Tested on Your Own Questions
  • Loading and Parsing Real Documents for RAG: PDF Headers, Wrapped Lines, Tables and HTML Chrome, Scored
  • Where Naive RAG Fails: Five Ways the Simplest Retriever Hands the Model the Wrong Pages
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • Capstone: A Production RAG Service Over the Python Standard Library, With an Eval a Hiring Manager Can Rerun
  • Context Engineering for a Long-Running Agent: Clear, Compact, Take Notes, Prove It
  • What LangChain Is For, and When to Skip It: Five Standard Parts, One Pipe, and a Decision Table
  • Why Chains Break: No Branch, No Retry, No Pause, and the Same Refund Assistant as a LangGraph Graph
  • LangGraph Nodes, Edges and State: Build Your First Graph, Route With a Conditional Edge, and Read the Run Three Ways
  • Human-in-the-Loop and Checkpointing in LangGraph: interrupt, a SQLite Save Slot and Command(resume=...)
  • Multi-Agent Patterns: Hub and Spoke in LangGraph, With Short Briefs, Owned Tools and a Retry the Hub Decides
  • A Research Agent in LangGraph: Plan, Search, Read, Write, and a Check Node That Rejects Citations Nobody Read
  • What Is MCP? One Plug Between AI Apps and Tools: Host, Client, Server and the Three Messages
  • Configuring MCP Servers in Claude Code: A Command or a URL, Three Scopes, and Three Moves When One Breaks
  • Workflow or Agent: Decide Who Picks the Next Step, Then Let the Constraints Choose the Design
  • Custom Agent Loops and Harnesses: A Dispatch Table, an Approval Hold, Error Results and a Turn Budget
  • Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
  • MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
  • Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
  • From ML Metrics to LLM Evals: Same Ruler, New Targets
  • Why You Cannot Ship an LLM Feature Without an Eval: Five Parts, Three Graders, One Tiny Eval
  • Building a Golden Dataset for LLM Evals: Cases, a Schema, a Coverage Table and a Seeded Split
  • Retrieval Evals: Score the Retriever With Recall@K, MRR and nDCG Before Blaming the Model
  • Regression Testing an LLM Bot in CI: A Golden Set, Two pytest Gates and GitHub Actions
  • Testing a RAG Bot Before It Ships: Slices, a Release Gate per Slice, and the Week After
  • RAG Generation Metrics: Faithfulness, Groundedness and Relevance, One Claim at a Time
  • LLM-as-Judge: Write a Rubric, Check Every Verdict, and Trust the Grader Only After Kappa Says So
  • RAGAS and Custom Evals: Framework Faithfulness Plus Your Own Citation and Required-Fact Checks, Behind One Gate
  • Which Test Layer Owns the Failure? Unit, Functional, Integration and End-to-End Tests for a Claude App
  • Six Ways a 200 Can Still Be Wrong: Hallucination, Refusal, Under-Acting, Context Loss, Format Drift and Inconsistency
  • Proving a Model Upgrade Is Ready: A Frozen Golden Set, a Calibrated Judge, the Right Layer and a Release Gate
  • Fallback Models for an LLM App: A Chain That Checks Region and Fit, Flags Degraded Answers and Gets Rehearsed
  • Back Pressure for LLM Traffic: Bound the Queue, Give Chat Its Own Lane, Count Tokens, Cancel When the Caller Leaves
  • Load Balancing LLM Traffic: Count the Work, Weigh the Prefix Cache, Check Real Health, Drain Before Deploys
  • A Message Queue for Document Ingestion: At Least Once, Leases, an Idempotent Consumer and a Dead Letter Queue
  • Caching for AI Apps: Four Layers, What Goes in Each Key, and How a Delete Travels
  • Semantic Caching: Why a Similarity Threshold Can't Stop Confident Wrong Answers
  • LLM Model Routing: Rules, a Classifier or a Cascade, Judged on Cost per Win and Every Topic
  • Cutting p95 and Cost in Half for an LLM App: Read the Bill, Match the Lever, Guard Success
  • Observability and Tracing for LLM Apps: A Span per Stage, Redaction First, Bad Traces Become Tests
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • Embedding Migration With Zero Downtime: Two Indexes, a Dual-Write Backfill, a Shadow Check and a Flag
  • Design a Multi-Tenant RAG Assistant, Part 1: Requirements, Rough Numbers and a Contract
  • Design a Multi-Tenant RAG Assistant, Part 2: Tenant Isolation, a Scoped Cache and Walking an Outage
  • A 500 MB PDF Takes 50 s to Answer, Get It to 2 s: Measure First, Then Promise Per Path
  • A 500 MB PDF From 50 s to 2 s, the Fast Path: Queue, Status, Streaming and an Acceptance Test That Fails
  • FastAPI for AI Services: Schemas at the Door, Load Once in the Lifespan, Depends, and def vs async def
  • Streaming LLM Answers From FastAPI: Sources First, Token Events Over SSE, and the Same Events Over a WebSocket
  • Docker for AI Apps: Bake the Model Weights In at Build Time, Use CPU-Only PyTorch, and Run Offline
  • Deploy a RAG Service: A Service Key, Health and Ready Checks, Caddy in Front and a Smoke Test
  • Cost Tracking and Budget Guards for an LLM App: Count the Tokens, Log Every Call, Check Before You Spend
  • Versioning Prompts, Models and Indexes: Three Moving Parts, One Release File and a One-Line Rollback
  • Guardrails for an LLM Agent: Check What Comes In, What It Wants to Do, and What Goes Out
  • The Agent Attack Surface: Blast Radius, Narrow Tools, Scoped Keys and the Dangerous Three
  • Prompt Injection, Jailbreaks and Untrusted Input: Label What Comes In, Gate What Goes Out
  • Injection Exposure Review for an Agent: Map Inputs, Data and Effects, Layer Every Path, Retest the Job
  • Data Leakage and PII in LLM Apps: Redact, Minimize, Log Safely and Count Every Place
  • Hooks That Block Destructive Actions: a PreToolUse Gate That Allows, Asks or Denies
  • Claude API Keys: Keep the Key on a Server Proxy, One Key per Environment, Rotate and Scope It
  1. Blog
  2. /
  3. AI Engineering
  4. /
  5. Agents and MCP

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.

Chaand Sheikh

·27 November 2026Agents and MCP

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 MCP authorization handshake Client MCP server Auth server 1. POST /mcp, no token 401 + WWW-Authenticate 2. GET resource metadata names the auth server 3. token for this server, with a scope 4. Authorization: Bearer token checked, then the result
The 401 challenge points the client to metadata; the client gets a token; every request carries it.

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 the WWW-Authenticate challenge. 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 lineWhat it meansWhat to do
401, token noneNo token was sentFollow the challenge and get one
403 insufficient_scopeValid token, missing scopeAsk for a token with that scope; retry only a few times
401 invalid_tokenUnknown, expired or issued for another serverA bigger scope will not help; get a token for this server
400 invalid_request, token noneThe token came in the query stringSend 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

DeploymentTransportCredentialScope
A script on one developer's laptopstdioKey in the environmentRead-only key
A shared lookup for forty support agentsHTTPBearer token per personinvoices:read
A finance bot that may void invoicesHTTPBearer tokenStarts 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.

Keep going in AI Engineering · 49 of 89

Previous
MCP Transports: stdio or Streamable HTTP, and Who Starts the Server
Next post
From ML Metrics to LLM Evals: Same Ruler, New Targets
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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.

On this page

  • Two deployments, two ways to prove who you are
  • The remote handshake
  • The project
  • .mcp.json: the config you commit
  • auth.py: the gatekeeper
  • invoice_core.py: secrets stay out of tool results
  • Run the client
  • Reading auth failures from the access log
  • Match the deployment to the job
  • Break it: two leaks
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

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

Join free on Skool

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)

Single logo

Empowering Education, One Course at a Time

About
About usContact usFAQs
Legal
Terms of ServicePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.