Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 3

Lab: A Host and Your Own Client on Local and Remote Servers

Build a small MCP server and client for revision 2026-07-28, run them over stdio and Streamable HTTP, test that the HTTP endpoint rejects bad requests, then connect the official SDK clients, the MCP Inspector and an agent host to the same server.

Contentsand lesson path

What you will learn

  • Connect an agent host and a minimal client you write with an official SDK to a local (stdio) and a remote (Streamable HTTP) MCP server, and inspect their tools with the MCP Inspector.

Prerequisites: Tool Calling

01. Goal and setup

In this lab you run one MCP server, atlas-units, with one tool, one resource and one prompt, over both standard transports: stdio for a local child process and Streamable HTTP for a server on a port. You talk to it from a client you write, then from the official SDK clients, the MCP Inspector and an agent host. Steps 1 to 5 use only the Python standard library, so you see every byte the protocol sends; the messages are the same ones the SDKs send.

You need: Python 3.12 or later and curl (tested with Python 3.12.13 on Linux; Python 3.10 reached end of life in October 2026). For step 6, Node.js 22.23.4+, 24.22.1+ or 26.12.1+ (what MCP Inspector 2.15.0 requires) and an MCP host such as Claude Code. For step 7, the same Python with mcp 2.x (pip install "mcp[cli]") or @modelcontextprotocol/client 2.x. Everything speaks protocol revision 2026-07-28. The HTTP steps use port 8931; if it is busy, pick another everywhere.

Project layout at the end of the lab
mcp-lab/
├── mcp_core.py     step 1: the server logic, independent of transport
├── server.py       step 2: runs mcp_core over stdio or Streamable HTTP
├── client.py       step 3: a minimal client with stdio and HTTP transports
├── run_lab.py      step 3: calls every feature of the server
├── call.json       step 4: one raw tools/call request for curl
└── http_checks.py  step 5: negative tests for the HTTP endpoint
Terminal
mkdir mcp-lab && cd mcp-lab
python3 --version

02. Step 1: The server logic

Create mcp_core.py in three parts. The first part holds the definitions the server advertises and two helpers. complete() builds every successful result: it sets the resultType that 2026-07-28 requires and puts the server's identity in the result's _meta. CACHE holds the ttlMs and cacheScope hints that list and read results carry.

Python · mcp_core.py · part 1 of 3
"""Transport-independent core of a tiny MCP server (protocol revision 2026-07-28)."""
import json

SUPPORTED = ["2026-07-28"]
P = "io.modelcontextprotocol/"
SERVER_INFO = {"name": "atlas-units", "version": "0.1.0"}
CACHE = {"ttlMs": 60000, "cacheScope": "public"}

TOOLS = [{
    "name": "celsius_to_fahrenheit",
    "title": "Celsius to Fahrenheit",
    "description": "Convert a temperature in degrees Celsius to Fahrenheit.",
    "inputSchema": {
        "type": "object",
        "properties": {"celsius": {"type": "number", "minimum": -273.15}},
        "required": ["celsius"],
        "additionalProperties": False,
    },
    "outputSchema": {
        "type": "object",
        "properties": {"fahrenheit": {"type": "number"}},
        "required": ["fahrenheit"],
    },
    "annotations": {"readOnlyHint": True},
}]
RESOURCES = {
    "docs://units/scales": "Water freezes at 0 C (32 F) and boils at 100 C (212 F).",
}
PROMPTS = [{
    "name": "explain_conversion",
    "title": "Explain a conversion",
    "description": "Ask the model to explain one Celsius to Fahrenheit conversion.",
    "arguments": [{"name": "celsius", "required": True}],
}]


class RpcError(Exception):
    def __init__(self, code, message, data=None, http_status=200):
        super().__init__(message)
        self.code, self.message, self.data = code, message, data
        self.http_status = http_status


def text(value):
    return {"type": "text", "text": value}


def complete(**fields):
    meta = {P + "serverInfo": SERVER_INFO}
    return {"resultType": "complete", "_meta": meta, **fields}

The second part handles each method. call_tool reports problems in two ways. An unknown tool or non-object arguments is a protocol error: it raises RpcError and the client gets a JSON-RPC error. Well-formed but invalid arguments, such as a temperature below absolute zero, produce a tool execution error: a normal result with isError: true that the model can use to correct itself.

Python · mcp_core.py · part 2 of 3
def discover(params):
    caps = {"tools": {}, "resources": {}, "prompts": {}}
    return complete(supportedVersions=SUPPORTED, capabilities=caps, **CACHE)


def call_tool(params):
    name, args = params.get("name"), params.get("arguments", {})
    if name != "celsius_to_fahrenheit":
        raise RpcError(-32602, f"Unknown tool: {name}")
    if not isinstance(args, dict):
        raise RpcError(-32602, "params.arguments must be an object")
    c = args.get("celsius")
    if isinstance(c, bool) or not isinstance(c, (int, float)) or c < -273.15:
        problem = f"celsius must be a number >= -273.15, got {json.dumps(c)}"
        return complete(content=[text(problem)], isError=True)
    out = {"fahrenheit": round(c * 9 / 5 + 32, 2)}
    return complete(content=[text(json.dumps(out))], structuredContent=out)


def read_resource(params):
    uri = params.get("uri")
    if uri not in RESOURCES:
        raise RpcError(-32602, f"Resource not found: {uri}")
    item = {"uri": uri, "mimeType": "text/plain", "text": RESOURCES[uri]}
    return complete(contents=[item], **CACHE)


def get_prompt(params):
    c = (params.get("arguments") or {}).get("celsius")
    if params.get("name") != "explain_conversion" or c is None:
        raise RpcError(-32602, "Unknown prompt or missing argument 'celsius'")
    ask = f"Convert {c} degrees Celsius to Fahrenheit and show each step."
    return complete(messages=[{"role": "user", "content": text(ask)}])


HANDLERS = {
    "server/discover": discover,
    "tools/list": lambda p: complete(tools=TOOLS, **CACHE),
    "tools/call": call_tool,
    "resources/list": lambda p: complete(resources=[
        {"uri": u, "name": u.rsplit("/", 1)[-1], "mimeType": "text/plain"}
        for u in RESOURCES], **CACHE),
    "resources/read": read_resource,
    "prompts/list": lambda p: complete(prompts=PROMPTS, **CACHE),
    "prompts/get": get_prompt,
}

The third part checks every request before dispatching it. There is no handshake, so the version and capabilities must arrive in each request's _meta. A request without them is malformed (-32602); a version the server does not speak gets -32022 with the supported list. Each error also carries the HTTP status that the Streamable HTTP transport requires, which the stdio transport simply ignores.

Python · mcp_core.py · part 3 of 3
def check_meta(params):
    meta = params.get("_meta") or {}
    version = meta.get(P + "protocolVersion")
    if version is None or P + "clientCapabilities" not in meta:
        raise RpcError(-32602, "Missing required _meta fields; supported versions: "
                       + ", ".join(SUPPORTED), http_status=400)
    if version not in SUPPORTED:
        raise RpcError(-32022, "Unsupported protocol version",
                       {"supported": SUPPORTED, "requested": version}, http_status=400)


def handle(msg):
    """Return (reply, http_status). reply is None for a notification."""
    if not isinstance(msg, dict):  # e.g. a JSON-RPC batch array: not allowed in MCP
        error = {"code": -32600, "message": "Invalid Request"}
        return {"jsonrpc": "2.0", "error": error}, 400
    if "id" not in msg:
        return None, 202
    params = msg.get("params") or {}
    try:
        if not isinstance(params, dict):
            raise RpcError(-32602, "params must be an object", http_status=400)
        check_meta(params)
        handler = HANDLERS.get(msg.get("method"))
        if handler is None:
            raise RpcError(-32601, f"Method not found: {msg.get('method')}",
                           http_status=404)
        return {"jsonrpc": "2.0", "id": msg["id"], "result": handler(params)}, 200
    except RpcError as e:
        error = {"code": e.code, "message": e.message}
        if e.data is not None:
            error["data"] = e.data
        return {"jsonrpc": "2.0", "id": msg["id"], "error": error}, e.http_status

03. Step 2: Two transports for one server

Create server.py. With no arguments it speaks stdio: one JSON message per line on standard input and output. Its log line goes to standard error, because anything else on standard output would corrupt the stream. When standard input closes, it exits; that is how a client shuts a stdio server down.

With --http PORT it serves Streamable HTTP on 127.0.0.1 only. The single endpoint /mcp accepts POST and checks, before running the core: the Origin header (so a web page on another site cannot reach your local server, an attack called DNS rebinding), the Accept header, and that MCP-Protocol-Version, Mcp-Method and Mcp-Name match the body. tools/call answers come back as a one-event SSE stream and the rest as plain JSON, so clients must handle both. GET returns 405: 2026-07-28 has no GET stream. One simplification: real servers must also decode Base64-encoded Mcp-Name values.

Python · server.py
"""Serve mcp_core over stdio (default) or Streamable HTTP (--http PORT)."""
import json
import sys
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

from mcp_core import P, handle

NAMED = {"tools/call": "name", "prompts/get": "name", "resources/read": "uri"}


def serve_stdio():
    print("atlas-units: serving on stdio", file=sys.stderr)  # logs: stderr only
    for line in sys.stdin:  # one JSON-RPC message per line
        if not line.strip():
            continue
        try:
            reply, _ = handle(json.loads(line))
        except json.JSONDecodeError:
            error = {"code": -32700, "message": "Parse error"}
            reply = {"jsonrpc": "2.0", "error": error}
        if reply is not None:
            sys.stdout.write(json.dumps(reply) + "\n")
            sys.stdout.flush()
    # stdin closed: the client is shutting us down, so exit promptly


def header_problem(headers, msg):
    params = msg.get("params") if isinstance(msg.get("params"), dict) else {}
    version = (params.get("_meta") or {}).get(P + "protocolVersion")
    expected = {"MCP-Protocol-Version": version, "Mcp-Method": msg.get("method")}
    if msg.get("method") in NAMED:
        expected["Mcp-Name"] = params.get(NAMED[msg["method"]])
    for name, value in expected.items():
        if headers.get(name) != value:
            return f"{name} header {headers.get(name)!r} does not match body {value!r}"
    return None


class McpEndpoint(BaseHTTPRequestHandler):
    allowed_origins = {None}  # add your web app's origin here if a browser must call

    def send_json(self, status, body, stream=False):
        data = json.dumps(body).encode() if body is not None else b""
        if stream:  # a one-event SSE stream; real servers may send notifications first
            data = b"data: " + data + b"\n\n"
        self.send_response(status)
        if body is not None:
            ctype = "text/event-stream" if stream else "application/json"
            self.send_header("Content-Type", ctype)
            if stream:
                self.send_header("X-Accel-Buffering", "no")
        self.send_header("Content-Length", str(len(data)))
        self.end_headers()
        self.wfile.write(data)

    def do_GET(self):  # no GET stream in 2026-07-28
        self.send_json(405, None)

    def do_POST(self):
        if self.path != "/mcp":
            return self.send_json(404, None)
        origin = self.headers.get("Origin")
        if origin not in self.allowed_origins:  # DNS-rebinding protection
            print("rejected Origin:", origin, file=sys.stderr)
            return self.send_json(403, None)
        accept = self.headers.get("Accept", "")
        if "application/json" not in accept or "text/event-stream" not in accept:
            return self.send_json(406, None)
        try:
            length = int(self.headers.get("Content-Length", 0))
            msg = json.loads(self.rfile.read(length))
        except json.JSONDecodeError:
            err = {"code": -32700, "message": "Parse error"}
            return self.send_json(400, {"jsonrpc": "2.0", "error": err})
        has_id = isinstance(msg, dict) and "id" in msg
        problem = header_problem(self.headers, msg) if has_id else None
        if problem:
            err = {"code": -32020, "message": f"Header mismatch: {problem}"}
            reply = {"jsonrpc": "2.0", "id": msg["id"], "error": err}
            return self.send_json(400, reply)
        reply, status = handle(msg)
        stream = has_id and msg.get("method") == "tools/call"
        self.send_json(status, reply, stream=stream)

    def log_message(self, fmt, *args):  # access log to stderr, one short line
        print("http:", fmt % args, file=sys.stderr)


if __name__ == "__main__":
    if len(sys.argv) == 3 and sys.argv[1] == "--http":
        address = ("127.0.0.1", int(sys.argv[2]))  # localhost only
        print(f"atlas-units: http://{address[0]}:{address[1]}/mcp", file=sys.stderr)
        ThreadingHTTPServer(address, McpEndpoint).serve_forever()
    else:
        serve_stdio()

Start it on stdio. It prints its log line and then waits silently for a client to write to it. Press Ctrl+D to close its input; it exits at once.

Terminal
python3 server.py
Expected output
atlas-units: serving on stdio

04. Step 3: Your own client over stdio

Create client.py. McpClient.request() gives each request a new id and the three _meta keys. StdioTransport starts the server as a child process and reads lines until the reply with the matching id arrives, skipping notifications. HttpTransport POSTs with the required headers and reads a JSON body or an SSE stream. call() retries once if the server answers -32022, using a version both sides speak.

Python · client.py
"""A minimal MCP client for revision 2026-07-28, standard library only."""
import itertools
import json
import subprocess
import sys
import urllib.error
import urllib.request

P = "io.modelcontextprotocol/"
KNOWN_VERSIONS = ["2026-07-28"]  # versions this client can speak, newest first
NAMED = {"tools/call": "name", "prompts/get": "name", "resources/read": "uri"}


class McpError(Exception):
    def __init__(self, error):
        super().__init__(f"{error['code']} {error['message']}")
        self.code, self.data = error["code"], error.get("data")


class StdioTransport:
    def __init__(self, command):
        self.proc = subprocess.Popen(command, stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE, text=True)

    def send(self, msg):
        self.proc.stdin.write(json.dumps(msg) + "\n")
        self.proc.stdin.flush()
        while True:
            line = self.proc.stdout.readline()
            if not line:
                raise ConnectionError("server closed its stdout")
            reply = json.loads(line)
            if reply.get("id") == msg["id"]:
                return reply  # anything else is a notification: skip it

    def close(self):
        self.proc.stdin.close()  # the polite shutdown signal for stdio servers
        self.proc.wait(timeout=5)


class HttpTransport:
    def __init__(self, url):
        self.url = url

    def send(self, msg):
        params = msg["params"]
        headers = {"Content-Type": "application/json",
                   "Accept": "application/json, text/event-stream",
                   "MCP-Protocol-Version": params["_meta"][P + "protocolVersion"],
                   "Mcp-Method": msg["method"]}
        if msg["method"] in NAMED:
            headers["Mcp-Name"] = params[NAMED[msg["method"]]]
        request = urllib.request.Request(self.url, json.dumps(msg).encode(), headers)
        try:
            response = urllib.request.urlopen(request, timeout=30)
        except urllib.error.HTTPError as e:
            response = e  # 4xx bodies still carry a JSON-RPC error
        with response:
            if response.headers.get("Content-Type", "").startswith("text/event-stream"):
                for raw in response:  # assumes one data: line per event
                    if raw.startswith(b"data:"):
                        reply = json.loads(raw[5:])
                        if reply.get("id") == msg["id"]:
                            return reply
                raise ConnectionError("stream ended without a response")
            return json.loads(response.read())

    def close(self):
        pass


class McpClient:
    def __init__(self, transport, version=KNOWN_VERSIONS[0]):
        self.transport, self.version = transport, version
        self.ids = itertools.count(1)

    def request(self, method, params=None):
        meta = {P + "protocolVersion": self.version,
                P + "clientCapabilities": {},
                P + "clientInfo": {"name": "atlas-lab-client", "version": "0.1.0"}}
        msg = {"jsonrpc": "2.0", "id": next(self.ids), "method": method,
               "params": {**(params or {}), "_meta": meta}}
        reply = self.transport.send(msg)
        if "error" in reply:
            raise McpError(reply["error"])
        return reply["result"]

    def call(self, method, params=None):
        """request(), retrying once if the server rejects our protocol version."""
        try:
            return self.request(method, params)
        except McpError as e:
            if e.code != -32022:
                raise
            shared = [v for v in KNOWN_VERSIONS if v in e.data["supported"]]
            if not shared:
                raise
            self.version = shared[0]
            return self.request(method, params)

Create run_lab.py, which uses the client to call every feature once: discovery, the tool list, a good and a bad tool call, the resource, the prompt and a tool that does not exist.

Python · run_lab.py
"""Exercise the atlas-units server over stdio (default) or Streamable HTTP."""
import sys

from client import HttpTransport, McpClient, McpError, P, StdioTransport

target = sys.argv[1] if len(sys.argv) > 1 else "stdio"
if target.startswith("http"):
    transport = HttpTransport(target)
else:
    transport = StdioTransport([sys.executable, "server.py"])
client = McpClient(transport)
try:
    found = client.call("server/discover")
    print("server:", found["_meta"][P + "serverInfo"]["name"],
          found["supportedVersions"], sorted(found["capabilities"]))
    tools = client.call("tools/list")["tools"]
    print("tools:", [tool["name"] for tool in tools])
    convert = "celsius_to_fahrenheit"
    ok = client.call("tools/call", {"name": convert, "arguments": {"celsius": 21.5}})
    print("call ok:", ok["structuredContent"], "| isError:", ok.get("isError", False))
    bad = client.call("tools/call", {"name": convert, "arguments": {"celsius": "warm"}})
    print("call bad:", bad["content"][0]["text"], "| isError:", bad["isError"])
    read = client.call("resources/read", {"uri": "docs://units/scales"})
    print("resource:", read["contents"][0]["text"])
    args = {"name": "explain_conversion", "arguments": {"celsius": "21.5"}}
    print("prompt:", client.call("prompts/get", args)["messages"][0]["content"]["text"])
    try:
        client.call("tools/call", {"name": "delete_everything", "arguments": {}})
    except McpError as e:
        print("protocol error:", e)
finally:
    transport.close()
Terminal
python3 run_lab.py
Expected output
atlas-units: serving on stdio
server: atlas-units ['2026-07-28'] ['prompts', 'resources', 'tools']
tools: ['celsius_to_fahrenheit']
call ok: {'fahrenheit': 70.7} | isError: False
call bad: celsius must be a number >= -273.15, got "warm" | isError: True
resource: Water freezes at 0 C (32 F) and boils at 100 C (212 F).
prompt: Convert 21.5 degrees Celsius to Fahrenheit and show each step.
protocol error: -32602 Unknown tool: delete_everything

The first line is the server's standard error, which the child process shares with your terminal. Note the two failure shapes: the bad argument came back as a result with isError: True, and the unknown tool as a JSON-RPC error, which McpClient raises as McpError.

05. Step 4: The same server over Streamable HTTP

In a second terminal, start the HTTP server and leave it running. Then, back in the first terminal, run the same script against its URL. The output should match step 3 except that there is no stderr line, because the server now logs in its own terminal.

Terminal 2 (leave running)
python3 server.py --http 8931
Terminal 1
python3 run_lab.py http://127.0.0.1:8931/mcp
Expected output
server: atlas-units ['2026-07-28'] ['prompts', 'resources', 'tools']
tools: ['celsius_to_fahrenheit']
call ok: {'fahrenheit': 70.7} | isError: False
call bad: celsius must be a number >= -273.15, got "warm" | isError: True
resource: Water freezes at 0 C (32 F) and boils at 100 C (212 F).
prompt: Convert 21.5 degrees Celsius to Fahrenheit and show each step.
protocol error: -32602 Unknown tool: delete_everything

Now look at one exchange without any client code. Save a raw tools/call request as call.json and POST it with curl, sending the headers a 2026-07-28 client must send. fold only wraps the long body line so it fits on screen.

JSON · call.json
{"jsonrpc": "2.0", "id": 1, "method": "tools/call",
 "params": {"name": "celsius_to_fahrenheit", "arguments": {"celsius": 100},
  "_meta": {"io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": {}}}}
Terminal 1
curl -sS -i http://127.0.0.1:8931/mcp \
  -H 'Content-Type: application/json' \
  -H 'Accept: application/json, text/event-stream' \
  -H 'MCP-Protocol-Version: 2026-07-28' \
  -H 'Mcp-Method: tools/call' -H 'Mcp-Name: celsius_to_fahrenheit' \
  --data @call.json | fold -w 80
Expected output (the Date and Server lines depend on your machine)
HTTP/1.0 200 OK
Server: BaseHTTP/0.6 Python/3.12.13
Date: Thu, 26 Nov 2026 12:21:29 GMT
Content-Type: text/event-stream
X-Accel-Buffering: no
Content-Length: 277

data: {"jsonrpc": "2.0", "id": 1, "result": {"resultType": "complete", "_meta": 
{"io.modelcontextprotocol/serverInfo": {"name": "atlas-units", "version": "0.1.0
"}}, "content": [{"type": "text", "text": "{\"fahrenheit\": 212.0}"}], "structur
edContent": {"fahrenheit": 212.0}}}

The response is text/event-stream and its one data: line holds the JSON-RPC result. A server doing slow work would send notifications/progress events on the same stream before the result. If that stream broke, 2026-07-28 offers no resume: the client sends the request again with a new id.

06. Step 5: Negative tests for the HTTP endpoint

A security check you have not seen fail is a check you cannot trust. http_checks.py sends one valid request and six broken ones, and prints PASS when the server answers with the expected status. It exits with code 1 if any check fails, so it can run in CI. Keep the HTTP server from step 4 running.

Python · http_checks.py
"""Negative tests: the HTTP endpoint must reject each broken request."""
import json
import sys
import urllib.error
import urllib.request

URL = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8931/mcp"
BODY = json.load(open("call.json"))
failures = []
GOOD = {"Content-Type": "application/json",
        "Accept": "application/json, text/event-stream",
        "MCP-Protocol-Version": "2026-07-28",
        "Mcp-Method": "tools/call", "Mcp-Name": "celsius_to_fahrenheit"}


def send(label, headers, body=BODY, method="POST", expect=200):
    data = json.dumps(body).encode() if method == "POST" else None
    req = urllib.request.Request(URL, data, headers, method=method)
    try:
        resp = urllib.request.urlopen(req, timeout=10)
    except urllib.error.HTTPError as e:
        resp = e
    with resp:
        raw = resp.read().decode()
    code = ""
    if raw:
        payload = json.loads(raw.removeprefix("data: "))
        code = payload.get("error", {}).get("code", "")
    verdict = "PASS" if resp.status == expect else "FAIL"
    if verdict == "FAIL":
        failures.append(label)
    print(f"{verdict} {label:<32} HTTP {resp.status} {code}".rstrip())


send("valid request", GOOD)
send("Mcp-Name does not match body", {**GOOD, "Mcp-Name": "drop_tables"}, expect=400)
send("Mcp-Method header missing",
     {k: v for k, v in GOOD.items() if k != "Mcp-Method"}, expect=400)
send("foreign Origin (DNS rebinding)", {**GOOD, "Origin": "https://evil.example"},
     expect=403)
send("Accept without event-stream", {**GOOD, "Accept": "application/json"}, expect=406)
old = json.loads(json.dumps(BODY))
old["params"]["_meta"]["io.modelcontextprotocol/protocolVersion"] = "1900-01-01"
send("unsupported protocol version", {**GOOD, "MCP-Protocol-Version": "1900-01-01"},
     body=old, expect=400)
send("GET (no standalone stream)", {}, method="GET", expect=405)
sys.exit(1 if failures else 0)
Terminal 1
python3 http_checks.py
echo "exit=$?"
Expected output
PASS valid request                    HTTP 200
PASS Mcp-Name does not match body     HTTP 400 -32020
PASS Mcp-Method header missing        HTTP 400 -32020
PASS foreign Origin (DNS rebinding)   HTTP 403
PASS Accept without event-stream      HTTP 406
PASS unsupported protocol version     HTTP 400 -32022
PASS GET (no standalone stream)       HTTP 405
exit=0

Now prove that the Origin test can fail. In server.py, temporarily replace if origin not in self.allowed_origins: with if False:, restart the server in terminal 2 and run the checks again. You should see exactly one FAIL and exit code 1, as below. Then undo the change and confirm that all seven checks pass again.

Expected output with the Origin check removed
PASS valid request                    HTTP 200
PASS Mcp-Name does not match body     HTTP 400 -32020
PASS Mcp-Method header missing        HTTP 400 -32020
FAIL foreign Origin (DNS rebinding)   HTTP 200
PASS Accept without event-stream      HTTP 406
PASS unsupported protocol version     HTTP 400 -32022
PASS GET (no standalone stream)       HTTP 405
exit=1

07. Step 6: The MCP Inspector and an agent host

The MCP Inspector is the reference tool for poking at a server by hand. It ships as one npm package with a web UI, a scriptable CLI and a terminal UI. One setting matters for this server: the Inspector's protocol era defaults to legacy, which opens with the initialize handshake of 2025-11-25 and earlier. Our server speaks only 2026-07-28, so pass --protocol-era modern (or auto, which probes with server/discover first). Run these from the mcp-lab folder, with the HTTP server still running for the second command.

Terminal 1 · MCP Inspector CLI 2.15.0
npx -y @modelcontextprotocol/[email protected] --cli python3 server.py \
  --protocol-era modern --method tools/list
npx -y @modelcontextprotocol/[email protected] --cli http://127.0.0.1:8931/mcp \
  --transport http --protocol-era modern --method tools/call \
  --tool-name celsius_to_fahrenheit --tool-arg celsius=21.5
Expected output (the first npx run also downloads the package)
atlas-units: serving on stdio
{
  "tools": [
    {
      "name": "celsius_to_fahrenheit",
      "title": "Celsius to Fahrenheit",
      "description": "Convert a temperature in degrees Celsius to Fahrenheit.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "celsius": {
            "type": "number",
            "minimum": -273.15
          }
        },
        "required": [
          "celsius"
        ],
        "additionalProperties": false
      },
      "outputSchema": {
        "type": "object",
        "properties": {
          "fahrenheit": {
            "type": "number"
          }
        },
        "required": [
          "fahrenheit"
        ]
      },
      "annotations": {
        "readOnlyHint": true
      }
    }
  ]
}
{
  "_meta": {
    "io.modelcontextprotocol/serverInfo": {
      "name": "atlas-units",
      "version": "0.1.0"
    }
  },
  "content": [
    {
      "type": "text",
      "text": "{\"fahrenheit\": 70.7}"
    }
  ],
  "structuredContent": {
    "fahrenheit": 70.7
  }
}

The first command lists the tool with the schema from step 1; the second returns one call's result. The web UI (npx @modelcontextprotocol/[email protected], Protocol Era set to modern in Server Settings) shows the raw messages in its Protocol tab. An HTTP 403 there is the Origin check working; the server prints the rejected origin.

Then register the server in an agent host. For Claude Code the commands are below; other hosts take the same command or URL in their configuration file. Use the absolute path to server.py, then ask the host to convert 21.5 degrees Celsius and approve the call.

Terminal · register the server in Claude Code (not run here)
claude mcp add atlas-units -- python3 /absolute/path/to/mcp-lab/server.py
claude mcp add --transport http atlas-units-http http://127.0.0.1:8931/mcp

08. Step 7: The official SDK clients

The official SDKs do the work of your client.py in a few lines and add what production needs: timeouts, pagination, cancellation, authorisation and both protocol eras. Both files below connect to the stdio server and to the HTTP server from step 4. The Python file was run with mcp 2.3.0, with the HTTP server from step 4 running; the TypeScript file follows the SDK documentation but was not run.

Note the defaults. The Python SDK's Client uses mode="auto": it probes with server/discover and falls back to initialize only for an older server. The TypeScript SDK v2 defaults to the legacy handshake, so ask for auto or it fails against this modern-only server.

Python · sdk_client.py · official SDK mcp 2.x
"""List and call the lab server's tool with the official Python SDK (mcp 2.x)."""
import anyio

from mcp import Client, StdioServerParameters


async def main() -> None:
    local = StdioServerParameters(command="python3", args=["server.py"])
    for target in (local, "http://127.0.0.1:8931/mcp"):
        async with Client(target) as client:  # default mode="auto": probe, fall back
            print("protocol:", client.protocol_version)
            listed = await client.list_tools()
            print("tools:", [tool.name for tool in listed.tools])
            args = {"celsius": 21.5}
            result = await client.call_tool("celsius_to_fahrenheit", args)
            print("result:", result.structured_content, "| is_error:", result.is_error)


anyio.run(main)
Terminal 1 (in mcp-lab, with mcp 2.x installed)
python sdk_client.py 2>/dev/null
Expected output (mcp 2.3.0)
protocol: 2026-07-28
tools: ['celsius_to_fahrenheit']
result: {'fahrenheit': 70.7} | is_error: False
protocol: 2026-07-28
tools: ['celsius_to_fahrenheit']
result: {'fahrenheit': 70.7} | is_error: False
TypeScript · sdk_client.ts · @modelcontextprotocol/client 2.x (not run here; API names checked against 2.4.0)
// The same client with the official TypeScript SDK v2 (@modelcontextprotocol/client).
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';

const transports = [
  new StdioClientTransport({ command: 'python3', args: ['server.py'] }),
  new StreamableHTTPClientTransport(new URL('http://127.0.0.1:8931/mcp')),
];
for (const transport of transports) {
  // v2 defaults to the legacy handshake; 'auto' probes with server/discover first
  const client = new Client(
    { name: 'atlas-lab-client', version: '0.1.0' },
    { versionNegotiation: { mode: 'auto' } },
  );
  await client.connect(transport);
  console.log('era:', client.getProtocolEra());
  const { tools } = await client.listTools();
  console.log('tools:', tools.map((tool) => tool.name));
  const name = 'celsius_to_fahrenheit';
  const result = await client.callTool({ name, arguments: { celsius: 21.5 } });
  console.log('result:', result.structuredContent, '| isError:', result.isError);
  await client.close();
}

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Practice check

Use what you saw in the lab.

Q1. Why does `StdioTransport.send()` keep reading lines until it finds a reply whose `id` matches the request?
Q2. After a teammate edits `server.py`, `http_checks.py` reports FAIL for the foreign Origin check. What risk does that open up?
Q3. You run the Inspector CLI against the lab server without any era flag and the connection fails. What is the most likely reason?
Practice only: not graded, not saved, not evidence.

11. Apply it

Now do the skill's practice task. Connect a filesystem server limited to one folder and a fetch server to your agent host and to a minimal client built on an official SDK (adapt sdk_client.py). List their tools in the Inspector with the right protocol era. Capture the JSON-RPC messages of one successful and one failing tool call, annotate them, and keep the file for the next lesson.

12. Review prompt

Without looking: what does a stdio server do with standard output, standard error and the end of its input? Which headers must a 2026-07-28 client send on a Streamable HTTP POST, and what happens when they do not match the body? Why must you tell the Inspector or the TypeScript SDK which protocol era to use?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check