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

MCP Transports: stdio or Streamable HTTP, and Who Starts the Server

Reach one small order server two ways, as a stdio subprocess and as a Streamable HTTP endpoint, see why a stray print to stdout breaks the session, and pick a transport by who runs the server.

Chaand Sheikh

·27 November 2026Agents and MCP

What you will learn

  • Explain the four layers of one MCP call: host app, client, transport and server
  • Describe how stdio and Streamable HTTP carry the same JSON-RPC messages
  • Keep the server's logic free of any transport so both doors share it
  • Choose a transport by who runs the server and who may reach it

Before you start

  • Building an MCP server: tools, resources and prompts
  • Basic Python

Someone asks your app: where is order 1042? The answer lives in an order server. But how does your app reach it?

MCP has two standard ways: stdio and Streamable HTTP. Both reach the same server and carry the same messages. What changes is who starts the server and how the messages travel. In this article we reach one small server both ways, then break it with a single line.

One call, four layers

On the left is the host app: Claude Code, or your own program. Next comes the MCP client, then the transport, and last the MCP server. A tools/call with the order id goes right. The reply, order 1042: shipped, comes back the same way.

Host app, client, transport and server Host app MCP client Transport stdio or HTTP MCP server handle() request: tools/call order_status {"order_id": "1042"} reply: order 1042: shipped Only the transport changes. The server's brain stays the same.
The host asks, the client carries, the transport moves, the server answers.

A helper at your desk, or a shop with a front door

stdio is a helper at your desk. You start the helper yourself and it lives as long as you do. You pass notes through one slot, and nobody else can reach them. Technically: a subprocess with pipes.

Streamable HTTP is a shop with a front door. It is open on its own, customers walk in through one address, and a doorman checks who comes in.

Client sideServer side
stdioLaunches the server process and writes one message per lineReads stdin, writes stdout, one line each
Streamable HTTPSends one POST per message to one endpointAlready running; answers each POST and can serve many clients

In both cases the client asks first; the server never starts a request. With stdio the client owns the server's life. With HTTP the server lives on its own.

The project

The lecture's project is a deliberately small, hand-written sketch in plain Python (standard library only, localhost only). Real servers use an official MCP SDK, which also handles protocol version, metadata and capabilities. The point here is to see the transports with nothing hidden.

server_core.py: the brain, with no transport

"""The server's brain: a JSON-RPC message in, a JSON-RPC reply out."""

ORDERS = {"1042": "shipped", "1043": "packed"}

TOOLS = [{
    "name": "order_status",
    "description": "Looks up one shop order by its digits-only id and "
                   "returns its status, like shipped or packed.",
    "inputSchema": {
        "type": "object",
        "properties": {
            "order_id": {"type": "string", "pattern": "^[0-9]+$"},
        },
        "required": ["order_id"],
    },
}]


def reply(mid, result=None, error=None):
    body = {"jsonrpc": "2.0", "id": mid}
    body["error" if error else "result"] = error or result
    return body


def handle(msg):
    """Same code answers on every transport."""
    method, mid = msg["method"], msg["id"]
    if method == "tools/list":
        return reply(mid, {"tools": TOOLS})
    if method == "tools/call":
        oid = msg["params"]["arguments"]["order_id"]
        status = ORDERS.get(oid)
        text = f"order {oid}: {status}" if status else f"no order {oid}"
        content = [{"type": "text", "text": text}]
        return reply(mid, {"content": content, "isError": status is None})
    return reply(mid, error={"code": -32601, "message": "Method not found"})

Three things to notice. There is no transport anywhere in this file. A missing order comes back as a tool error (isError: true), not a crash. And an unknown method gets a JSON-RPC error reply, -32601.

stdio_server.py: the first door

"""stdio transport: the client starts this process and talks through pipes."""
import json
import sys

from server_core import handle


def serve():
    print("server up", file=sys.stderr, flush=True)
    for line in sys.stdin:
        answer = handle(json.loads(line))
        sys.stdout.write(json.dumps(answer) + "\n")
        sys.stdout.flush()
    print("stdin closed", file=sys.stderr, flush=True)


if __name__ == "__main__":
    serve()

Logs go to stderr, never stdout. Each message is one line on stdin; each reply is one line on stdout. When the client closes stdin, the loop ends and the server exits. That is the normal shutdown.

http_server.py: the second door

"""Streamable HTTP transport: one endpoint, one POST per message."""
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from server_core import handle, reply

ALLOWED_ORIGINS = {"http://localhost:3000"}


class McpEndpoint(BaseHTTPRequestHandler):
    def do_POST(self):
        origin = self.headers.get("Origin")
        if origin and origin not in ALLOWED_ORIGINS:
            return self.send_json(403, "bad origin")
        size = int(self.headers["Content-Length"])
        msg = json.loads(self.rfile.read(size))
        if self.headers.get("Mcp-Method") != msg["method"]:
            err = {"code": -32020, "message": "Mismatch"}
            body = reply(msg["id"], error=err)
            return self.send_json(400, body)
        self.send_json(200, handle(msg))

    def send_json(self, code, body):
        data = json.dumps(body).encode()
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def log_message(self, *args):
        pass


def make_server():
    return ThreadingHTTPServer(("127.0.0.1", 0), McpEndpoint)
  • The Origin check. An origin that is not allowed gets a 403. The MCP spec says HTTP servers must validate the Origin header.
  • One POST, one message, to a single endpoint.
  • The header check. In this sketch, an Mcp-Method header that does not match the body is a bad request.
  • The same handle() answers as on stdio.
  • Bound to 127.0.0.1. Running locally, only this machine can connect. Port 0 lets the OS pick a free port.

Run the client

client.py starts the stdio server and sends four messages, then POSTs to the HTTP server, then tries a server with one mistake. The server here is real and runs on this machine; there is no model in the loop. The printout:

stdio: the client starts stdio_server.py
  -> tools/list
  <- order_status
  -> tools/call 1042
  <- order 1042: shipped
  -> tools/call 9999
  <- no order 9999 (isError true)
  -> tools/remove
  <- error -32601 Method not found
  server log (stderr): server up
  server log (stderr): stdin closed
  stdin closed, exit code 0
http: one POST per message, to one endpoint
  POST /mcp tools/list -> 200 order_status
  POST /mcp tools/call -> 200 order 1042: shipped
  POST /mcp from Origin http://evil.test -> 403
  POST /mcp with the wrong Mcp-Method -> 400 error -32020 Mismatch
stdio: a server that prints a banner to stdout
  stdout line is not JSON-RPC: Welcome to the order server!

Order 9999 is missing, so it is a tool error. The log lines arrive on stderr, and closing stdin ends the server with exit code 0. Over HTTP, the unknown origin gets 403 and the wrong header gets 400. The last block is the bug in the next section.

Break it: one stray print

noisy_server.py is the stdio server with one extra line:

"""A stdio server with one mistake: it prints a banner to stdout."""
import stdio_server

print("Welcome to the order server!")
stdio_server.serve()

On stdio, stdout is the message channel. The client reads every line as JSON-RPC, and this line is not a message, so the session breaks before any real call. The fix is to print to stderr instead. A normal print is harmless in most programs; on stdio it corrupts the protocol.

Choosing a transport

stdioStreamable HTTP
FitsA local tool with one user: files, scripts, your own machineA shared or remote service: many clients, one server
Who starts itThe clientIt runs on its own
NetworkNone, no portOne endpoint
NeedsLogs on stderrOrigin check and authentication
In Claude Codeclaude mcp add --transport stdio <name> -- <command>claude mcp add --transport http <name> <url>

Two more words you may meet. The older SSE transport is deprecated. And stdio's line framing can run over a TCP socket, but the spec calls that a custom transport.

Authentication for the HTTP door (bearer tokens, audience and scope) is covered in Deploying and authenticating an MCP server.

Common mistakes

  • Printing to stdout in a stdio server. Banners, debug prints and progress bars all break the session. Log to stderr.
  • Putting transport code in the tool logic. Keep one handle() and wrap it in each door.
  • A shared server on stdio. If several apps on other machines must use one server, each would launch its own copy. Use Streamable HTTP.
  • An open HTTP endpoint. No Origin check and no authentication means anyone who can reach the URL can call your tools.

Recap

  • The server's logic does not change with the transport.
  • stdio: the client launches the server and talks in lines; logs go to stderr.
  • Streamable HTTP: one endpoint, one POST per message, Origin checks and authentication.
  • Pick by who runs the server and who may reach it.

Keep going in AI Engineering · 48 of 89

Previous
Building an MCP Server: Tools, Resources and Prompts in Python and TypeScript
Next post
Deploying and Authenticating an MCP Server: Environment Keys for stdio, Bearer Tokens and Scopes for HTTP
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

  • One call, four layers
  • A helper at your desk, or a shop with a front door
  • The project
  • server_core.py: the brain, with no transport
  • stdio_server.py: the first door
  • http_server.py: the second door
  • Run the client
  • Break it: one stray print
  • Choosing a transport
  • Common mistakes
  • 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.