If you strip away the hype, a Model Context Protocol (MCP) server is a small JSON-RPC 2.0 server that tells AI clients (Claude, Codex, custom agent loops) two things: what tools exist (tools/list) and how to execute one (tools/call).
That’s the entire meaning of an MCP server. Instead of writing custom glue code for every AI client that wants to talk to your database, CMS, or internal API, you expose one typed tool interface over either stdio (local process) or Streamable HTTP (remote server with OAuth).
Getting a hello-world MCP server running takes ten minutes. Making one survive real usage—large documents, retries, auth, reverse proxies, and untrusted inputs—is where the real work starts. Below is a working, zero-dependency Python MCP server you can test locally right now, followed by the five production bugs we actually hit while dogfooding Colophon CMS’s remote MCP server (colophonapp.404human.dev/mcp).
Local stdio vs. remote HTTP: pick the right transport first
| Transport | Best for | Auth model | Main gotcha |
|---|---|---|---|
stdio (local process) | Developer CLIs, local repo tools, SQLite/file inspection | Inherits local OS user permissions | Never print debug logs to stdout—stdout is the JSON-RPC wire. Log only to stderr. |
| Streamable HTTP (remote) | Hosted SaaS, team CMS/CRMs, multi-tenant apps | OAuth 2.1 + PKCE (/.well-known/* discovery) or scoped bearer tokens | Edge proxies (like Cloudflare) can block non-browser clients before requests reach your app. |
Start with stdio while designing your tool schemas and error envelopes. Move to remote HTTP when humans and teams need role-based access to a shared service.
Build a working MCP server in ~85 lines of Python (zero dependencies)
Official SDKs (@modelcontextprotocol/sdk, mcp for Python, rmcp for Rust) are great once you ship, but reading the raw protocol once removes every bit of mystery.
Save this as notes_mcp.py. It implements the real MCP handshake (initialize), lists two bounded tools (read_note, patch_note), enforces sandboxed paths and byte limits, and uses optimistic locking (expected_sha256) on edits so stale writes are refused cleanly.
#!/usr/bin/env python3
import hashlib
import json
import sys
from pathlib import Path
WORKSPACE = Path("./notes").resolve()
MAX_READ_BYTES = 8_000
TOOLS = [
{
"name": "read_note",
"description": "Read a UTF-8 note from the sandbox and return its content plus sha256 digest.",
"inputSchema": {
"type": "object",
"properties": {"filename": {"type": "string"}},
"required": ["filename"],
"additionalProperties": False,
},
},
{
"name": "patch_note",
"description": "Replace one exact substring in a note, guarded by expected_sha256 to prevent stale overwrites.",
"inputSchema": {
"type": "object",
"properties": {
"filename": {"type": "string"},
"expected_sha256": {"type": "string"},
"find": {"type": "string"},
"replace": {"type": "string"},
},
"required": ["filename", "expected_sha256", "find", "replace"],
"additionalProperties": False,
},
},
]
def safe_path(filename: str) -> Path:
target = (WORKSPACE / filename).resolve()
if not target.is_relative_to(WORKSPACE):
raise ValueError("path_outside_workspace")
return target
def call_tool(name: str, args: dict) -> tuple[bool, dict]:
if name == "read_note":
path = safe_path(args["filename"])
if not path.exists():
return True, {"error": "not_found", "filename": args["filename"]}
raw = path.read_bytes()
digest = hashlib.sha256(raw).hexdigest()
return False, {
"filename": path.name,
"sha256": digest,
"truncated": len(raw) > MAX_READ_BYTES,
"content": raw[:MAX_READ_BYTES].decode("utf-8", errors="replace"),
}
if name == "patch_note":
path = safe_path(args["filename"])
if not path.exists():
return True, {"error": "not_found"}
raw = path.read_bytes()
current = hashlib.sha256(raw).hexdigest()
if current != args["expected_sha256"]:
return True, {"error": "conflict_stale_digest", "current_sha256": current}
text = raw.decode("utf-8")
if args["find"] not in text:
return True, {"error": "target_text_not_found"}
updated = text.replace(args["find"], args["replace"], 1)
if updated == text:
return False, {"status": "no_op", "sha256": current}
new_bytes = updated.encode("utf-8")
path.write_bytes(new_bytes)
return False, {"status": "updated", "sha256": hashlib.sha256(new_bytes).hexdigest()}
return True, {"error": f"unknown_tool:{name}"}
def handle(msg: dict) -> dict | None:
method = msg.get("method")
req_id = msg.get("id")
if method == "notifications/initialized" or req_id is None:
return None
if method == "initialize":
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"protocolVersion": "2025-03-26",
"capabilities": {"tools": {}},
"serverInfo": {"name": "notes-mcp", "version": "0.1.0"},
},
}
if method == "tools/list":
return {"jsonrpc": "2.0", "id": req_id, "result": {"tools": TOOLS}}
if method == "tools/call":
params = msg.get("params") or {}
try:
is_err, payload = call_tool(params.get("name", ""), params.get("arguments") or {})
except (KeyError, TypeError, ValueError) as exc:
is_err, payload = True, {"error": f"invalid_arguments:{exc}"}
return {
"jsonrpc": "2.0",
"id": req_id,
"result": {
"isError": is_err,
"content": [{"type": "text", "text": json.dumps(payload)}],
},
}
return {
"jsonrpc": "2.0",
"id": req_id,
"error": {"code": -32601, "message": f"Method not found: {method}"},
}
def main() -> None:
for line in sys.stdin:
line = line.strip()
if not line:
continue
reply = handle(json.loads(line))
if reply is not None:
sys.stdout.write(json.dumps(reply) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()
You can smoke-test the server straight from the shell without even opening an AI client:
printf '%s\n%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
| python3 notes_mcp.py
Every MCP client does the exact same exchange over stdio or HTTP—discovering your schemas first, then translating user goals into tools/call requests (see how to build an AI agent without a framework for the client side of that loop).
Five real traps we hit running a production MCP server
Unit tests pass easily on a minimal MCP server. Running a real website (colophon.404human.dev) through our own hosted MCP server (bugs from day one) immediately exposed five bugs that don’t show up in tutorials:
1. Whole-document overwrite tools burn tokens and cause silent data loss
Our first write tool took the full document body. Fixing a single typo in an 85,000-character post forced the model to regenerate and resend the entire 85 KB body—wasting tokens and risking accidental edits elsewhere in the file.
Fix: Provide a targeted patch / edit_entry tool (like patch_note above) paired with an optimistic-locking digest or revision ID so concurrent edits fail with conflict_stale_digest instead of silently clobbering someone else’s work.
2. No-op saves mint fake revisions
When an agent retried an edit whose resulting bytes were identical to the stored version, our server still created a new revision ID—making the CMS UI show “unpublished changes” when nothing had changed.
Fix: Compare digests before writing and return {"status": "no_op"} cleanly, as shown in patch_note above.
3. Substring matching in approval gates misfires on similar tool names
In Colophon’s MCP server, writes that publish, delete, or change access require human approval. Early on, our approval rule checked whether a tool name contained the substring "review"—which accidentally matched "preview" and triggered human approval prompts on read-only draft previews.
Fix: Never use substring or regex heuristics for security boundaries. Classify every tool explicitly in a static allowlist (read, draft, requires_approval) and keep destructive operations (like deleting a whole project) off the MCP surface completely.
4. Cloudflare Error 1010 blocks non-browser MCP clients before they reach your server
When you expose a remote MCP server behind Cloudflare, Browser Integrity Check inspects User-Agent headers and rejects clients like Python’s default urllib with HTTP 403 / error code: 1010—never even logging a hit on your origin server.
Fix: Add a narrow Cloudflare Configuration Rule turning Browser Integrity Check off for /mcp, /oauth/*, and /.well-known/* (full walkthrough in Cloudflare Error 1010 on /mcp and /oauth).
5. Exposing admin tools instead of role-scoped, draft-only capabilities
If your MCP server shares a single superuser API key across agents, prompt injection inside any record the agent reads becomes an admin exploit.
Fix: Authenticate remote MCP callers as real users (OAuth 2.1 + PKCE) so every tool call runs under that user’s role, enforce tenant isolation in the database with PostgreSQL Row-Level Security, and keep writes draft-only until a human approves (full checklist in securing MCP servers for AI agents).
Production MCP server checklist
-
Zero stdout pollution (
stdio): All logging goes strictly tostderr. - Targeted edits + optimistic locking: Don’t force full-document rewrites; check version/hash before mutating.
-
No-op detection: Byte-identical writes return
no_opwithout creating fake revisions or audit noise. -
Bounded responses: Truncate large reads with an explicit
truncated: truefield so one tool call cannot blow up the model’s context window. - Explicit permission table: Every tool declared as read, draft, or approval-gated—no substring matching, no self-approval.
-
Edge-safe discovery (HTTP): Verify
/.well-known/oauth-protected-resource,/oauth/*, and/mcprespond cleanly to non-browser HTTP clients.
Frequently asked questions
What does an MCP server actually do?
An MCP server exposes a standard JSON-RPC 2.0 interface (tools/list, tools/call, plus optional resources and prompts) so any MCP-compatible AI client can discover and invoke your application’s capabilities without writing a bespoke integration per client.
Should I use an official MCP SDK or raw JSON-RPC?
For production servers—especially remote Streamable HTTP servers with OAuth discovery and session handling—use an official SDK so protocol upgrades stay painless. Writing a small raw JSON-RPC stdio server once is still the fastest way to understand how tool discovery, isError, and transport framing actually work.
Can an MCP server replace my REST API? No. REST/HTTP APIs are still better for deterministic app-to-app calls, public caching, and high-throughput reads. MCP is an adapter layer on top of your domain logic designed specifically for AI tool discovery and human-in-the-loop workflows. See MCP vs API vs RAG for the exact breakdown.