GNGiseldo Neo and Alana NeoBooks
Building AI Agents10 / 18

MCP: a protocol for tools

“Separating the agent from the tool is what allows the tool to have an owner, permissions and a version.”

Objective

Implement a Model Context Protocol server and client from scratch, in JSON-RPC over stdio, understand the three-step handshake and use the official SDK. By the end, the reader has a tool that runs in another process and is called through the same interface as before.

7.1 Why separate the tool from the process

So far, the tools have lived in the same process as the agent. That works until you want two people to use the same tool, or the tool to be written in another language, or the tool to have access to a system you do not want to expose to the agent’s process.

The Model Context Protocol — MCP — solves this with a message protocol (Anthropic 2024). The central idea: the agent (client) and the tool (server) are separate processes that talk over JSON-RPC 2.0 (JSON-RPC Working Group 2013).

GainPractical consequence
ReuseAn MCP tool serves any client: your agent, someone else’s editor, a third-party app
IsolationThe server runs with different permissions: a server that only reads one directory cannot write to another
LanguageThe server can be written in TypeScript, Go, Rust — the protocol is JSON
CompositionThe harness discovers tools at runtime, without recompiling

Table 7.1. What process separation buys.

7.2 The transport

MCP defines two main transports: stdio, where the server is a subprocess and the conversation happens over stdin/stdout, and HTTP, where the server is a network service. stdio is the most common for local tools, and it is what we are going to build.

The format is one JSON message per line:

Listing 7.1. Transport format: one JSON message per line.

{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {...}}
{"jsonrpc": "2.0", "id": 1, "result": {...}}

7.3 The three-step handshake

Every MCP conversation begins with a handshake. It exists so that client and server agree on the protocol version and capabilities before exchanging anything.

  1. The client sends initialize with the protocol version it supports.

  2. The server responds with the version it accepts and the capabilities it offers (tools, resources, prompts).

  3. The client sends notifications/initialized — a notification, without an id, that expects no response.

Only after that can the client call tools/list.

7.4 An MCP server from scratch

No SDK, no dependencies. Just JSON, stdin and stdout.

Listing 7.2. Method routing in a minimal MCP server.

def handle(req: dict) -> dict | None:
    method = req.get("method")
    rid = req.get("id")
    params = req.get("params") or {}

    if method == "initialize":
        return {"jsonrpc": "2.0", "id": rid, "result": {
            "protocolVersion": "2024-11-05",
            "capabilities": {"tools": {"listChanged": False}},
            "serverInfo": {"name": "demo-mcp", "version": "0.1.0"},
        }}
    if method == "notifications/initialized":
        return None  # notification: no response
    if method == "tools/list":
        return {"jsonrpc": "2.0", "id": rid, "result": {"tools": TOOLS}}
    if method == "tools/call":
        result = call_tool(params.get("name"),
                           params.get("arguments") or {})
        return {"jsonrpc": "2.0", "id": rid, "result": result}
    return {"jsonrpc": "2.0", "id": rid,
            "error": {"code": -32601,
                      "message": f"Method not found: {method}"}}

The main loop is trivial: it reads a line, parses it, calls handle, and writes the response if there is one.

Listing 7.3. The server’s main loop.

def main() -> None:
    for line in sys.stdin:
        line = line.strip()
        if not line:
            continue
        try:
            req = json.loads(line)
        except json.JSONDecodeError as exc:
            resp = {"jsonrpc": "2.0", "id": None,
                    "error": {"code": -32700, "message": str(exc)}}
        else:
            resp = handle(req)
        if resp is not None:
            sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
            sys.stdout.flush()

The flush() is not optional. Without it, the client sits waiting for a response that is stuck in the buffer.

Common pitfall

Forgetting the flush() and concluding that “MCP froze”. The symptom is a client stalled indefinitely on the first call, while the server is healthy and has already written the response — into the buffer. Over stdio, every response needs an explicit flush().

7.5 The client

On the other side, the client starts the server as a subprocess and talks to it. This is exactly the role of the harness.

Listing 7.4. MCP client with EOF handling.

class MCPClient:
    def __init__(self, command: list[str]) -> None:
        self.proc = subprocess.Popen(
            command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
            stderr=subprocess.PIPE, text=True, encoding="utf-8", bufsize=1)
        self._id = 0

    def request(self, method: str, params: dict | None = None) -> dict:
        self._id += 1
        self._send({"jsonrpc": "2.0", "id": self._id,
                    "method": method, "params": params or {}})
        line = self.proc.stdout.readline()
        if not line:
            err = self.proc.stderr.read()
            raise RuntimeError(f"server died without responding. "
                               f"stderr={err}")
        resp = json.loads(line)
        if "error" in resp:
            raise RuntimeError(f"JSON-RPC error {resp['error']['code']}: "
                               f"{resp['error']['message']}")
        return resp["result"]

The if not line check is the part people forget. A server that dies in the middle of a call does not return an error — it returns EOF. If you do not handle it, the client hangs forever waiting for a response that never comes.

7.6 The complete conversation

Running client and server together:

Listing 7.5. Output: handshake, discovery, call, error and shutdown.

1. initialize -> {"protocolVersion": "2024-11-05",
                  "capabilities": {"tools": {"listChanged": false}},
                  "serverInfo": {"name": "demo-mcp", "version": "0.1.0"}}
2. notifications/initialized sent (no response expected)
3. tools/list -> ['add', 'list_files']
   - add: Adds two integers.
   - list_files: Lists the workspace files, one per line.
4. tools/call add -> 42 | isError = False
5. tools/call list_files -> probe_agent.py, probe_harness.py, ...
6. invalid method -> JSON-RPC error -32601: Method not found: tools/does_not_exist
7. server shut down, exit = 0

Seven lines, and the whole cycle is covered: handshake, discovery, call, method error, clean shutdown.

7.7 The same tool, two transports

The point that makes MCP worthwhile: the loop does not know the difference. It sees a name, a schema and a function that returns a string.

Listing 7.6. Local function and MCP adapter with the same interface.

# Transport A: local function in the same process
def add_local(a: int, b: int) -> str:
    return str(a + b)

# Transport B: MCP server in another process
with MCPToolAdapter([sys.executable, "probe_mcp_server.py"]) as mcp:
    print(mcp.call("add", {"a": 20, "b": 22}))

Running both:

Listing 7.7. Output: same result, different transports.

A) local tool: 42
B) MCP tools: ['add', 'list_files']
B) tools/call add: 42
B) schema translatable for the model: {"type": "object",
   "properties": {"a": {"type": "integer"}, "b": {"type": "integer"}},
   "required": ["a", "b"]}

This is what makes MCP useful: the transport changes, the loop does not.

7.8 With the official SDK

Writing the protocol by hand is instructive, but in production you use the SDK (Model Context Protocol 2026). It derives the schema from the type hints and the docstring.

Listing 7.8. MCP server with the SDK (mcp 2.x).

from mcp.server.mcpserver import MCPServer

mcp = MCPServer("demo-sdk", version="0.1.0")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Adds two integers."""
    return a + b

@mcp.tool()
def count_lines(path: str) -> int:
    """Counts the lines of a workspace file."""
    return len((Path(__file__).parent / path)
               .read_text(encoding="utf-8").splitlines())

if __name__ == "__main__":
    mcp.run(transport="stdio")

Note the API change: in mcp 2.x, FastMCP was renamed to MCPServer, imported from mcp.server.mcpserver. Old code that does from mcp.server.fastmcp import FastMCP fails with an explicit message asking you to migrate. It is worth knowing about, because half the tutorials on the internet still use the old API.

The schema the SDK generates from the type hints is exactly what the model needs:

Listing 7.9. Schema derived automatically from the type hints.

tool: add | Adds two integers. |
  schema: {"properties": {"a": {"title": "A", "type": "integer"},
                          "b": {"title": "B", "type": "integer"}},
           "required": ["a", "b"], "type": "object"}

And input validation is automatic — sending {"a": "x"} returns is_error: True with the pydantic message, instead of blowing up in your code.

Common pitfall

Publishing an MCP server that writes log messages to stdout. Over stdio, stdout is the protocol channel: a debugging print() breaks the client’s parsing. Logs go to stderr, always.