AI Engineering: Agents and Applications › The Model Context Protocol › Day 299

Hands-on lab — Day 299: Building an MCP Client

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/mcp_client.py

Test

bash tests/run_tests.sh

File tree

examples/mcp_client.py
expected-output/examples-run.txt
expected-output/FIELDS.md
expected-output/measured-values.txt
expected-output/run-output.txt
expected-output/starter-run.txt
expected-output/test-output.txt
expected-output/test-run.txt
metadata.yml
README.md
requirements/requirements.txt
security.md
starter/mcp_client.py
tests/run_tests.sh
tests/test_mcp_client.py
troubleshooting.md

Lab README

Day 299 Lab: Building an MCP Client

Lesson

  • Lesson title: Building an MCP Client
  • Day number: 299 of 365
  • Lesson article: https://ai-roadmap-365.github.io/day-299-building-an-mcp-client
  • Lab files: everything you need is in this directory — follow “How to run” below.
  • Browse the course locally: from the repository root, this lab also appears in the course website at /labs/day-299-building-an-mcp-client when the site is running.

Purpose

Build an autonomous AI agent host client in Python capable of managing multi-server MCP connections, aggregating tool catalogs, and routing execution requests across stdio pipes.

Learning objectives

  • Construct an MCPClientConnection handling initialization handshakes and tool discovery.
  • Build an AutonomousMCPAgent managing multi-server connection pools.
  • Dispatch dynamic tool calls with automated routing.
  • Verify multi-server coordination and error recovery.

Prerequisites

  • Python 3.10+ installed
  • pytest installed

Supported operating systems

  • macOS, Linux, Windows WSL2

Hardware requirements

  • Standard CPU, 512MB RAM

Required software

  • Python 3.10+, pytest

Free and open-source options

  • Python Standard Library, Pytest

Installation

python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements/requirements.txt

File structure

  • starter/mcp_client.py: Starter implementation skeleton
  • examples/mcp_client.py: Verified reference implementation
  • tests/test_mcp_client.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/mcp_client.py

What the commands do

  • Connects to simulated MCP servers, aggregates tool schemas, and executes routed tool calls.

Expected output

Unified tools: ['query_users', 'read_file']
DB Result: Alice, Bob
FS Result: File contents: OK

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • Multi-server registration and connection
  • Unified tool catalog aggregation
  • Accurate tool dispatch routing
  • Unknown tool error handling
  • Clean connection teardown

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure tool names are unique across registered servers or implement namespacing.

Security notes

Runs completely offline on local CPU.

Extension exercises

Implement namespace prefixing (server_name__tool_name) for collision resolution.

Day number: 299 of 365

Expected output

FIELDS.md

# Measured Values
- `registered_servers`: 2
- `unified_tools`: 2

examples-run.txt

Unified tools: ['query_users', 'read_file']
DB Result: Alice, Bob
FS Result: File contents: OK

measured-values.txt

registered_servers=2
unified_tools=2

run-output.txt

Unified tools: ['query_users', 'read_file']
DB Result: Alice, Bob
FS Result: File contents: OK

starter-run.txt

An untouched starter fails the suite. Captured from a real run:

_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = <examples.mcp_client.MockMCPServerInstance object at 0x10aa66060>
line = '{"jsonrpc": "2.0", "id": 1, "method": "initialize"}'

    def handle_line(self, line: str) -> Optional[str]:
>       raise NotImplementedError('TASK 1: implement handle_line.')
E       NotImplementedError: TASK 1: implement handle_line.

examples/mcp_client.py:18: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_mcp_client.py::test_multi_server_registration - NotImplemen...
FAILED tests/test_mcp_client.py::test_tool_routing_execution - NotImplemented...
FAILED tests/test_mcp_client.py::test_unknown_tool_routing - NotImplementedEr...
FAILED tests/test_mcp_client.py::test_initialization_handshake - NotImplement...
============================== 4 failed in 0.03s ===============================

Implement each TASK in starter/, copy it over examples/, and the same
suite goes green.

test-output.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-299-building-an-mcp-client
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 4 items

tests/test_mcp_client.py::test_multi_server_registration PASSED          [ 25%]
tests/test_mcp_client.py::test_tool_routing_execution PASSED             [ 50%]
tests/test_mcp_client.py::test_unknown_tool_routing PASSED               [ 75%]
tests/test_mcp_client.py::test_initialization_handshake PASSED           [100%]

============================== 4 passed in 0.01s ===============================

test-run.txt

============================= test session starts ==============================
platform darwin -- Python 3.14.0, pytest-9.1.1, pluggy-1.6.0 -- <repo>/.venv-tools/bin/python3.14
cachedir: .pytest_cache
rootdir: <repo>/labs/sections/ai-engineering/day-299-building-an-mcp-client
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 4 items

tests/test_mcp_client.py::test_multi_server_registration PASSED          [ 25%]
tests/test_mcp_client.py::test_tool_routing_execution PASSED             [ 50%]
tests/test_mcp_client.py::test_unknown_tool_routing PASSED               [ 75%]
tests/test_mcp_client.py::test_initialization_handshake PASSED           [100%]

============================== 4 passed in 0.01s ===============================

Source files

examples/mcp_client.py (3617 bytes)
import json
from typing import Dict, Any, List, Optional

class MockMCPServerInstance:
    def __init__(self, name: str, tools_dict: Dict[str, Any]):
        self.name = name
        self.tools_dict = tools_dict
        
    def handle_line(self, line: str) -> Optional[str]:
        msg = json.loads(line.strip())
        method = msg.get("method")
        msg_id = msg.get("id")
        
        if method == "initialize":
            return json.dumps({
                "jsonrpc": "2.0",
                "id": msg_id,
                "result": {"protocolVersion": "2024-11-05", "serverInfo": {"name": self.name}}
            })
        elif method == "tools/list":
            tool_list = [
                {"name": name, "description": f"Tool {name}", "inputSchema": {"type": "object"}}
                for name in self.tools_dict
            ]
            return json.dumps({"jsonrpc": "2.0", "id": msg_id, "result": {"tools": tool_list}})
        elif method == "tools/call":
            params = msg.get("params", {})
            tool_name = params.get("name")
            if tool_name in self.tools_dict:
                handler = self.tools_dict[tool_name]
                res = handler(params.get("arguments", {}))
                return json.dumps({
                    "jsonrpc": "2.0",
                    "id": msg_id,
                    "result": {"content": [{"type": "text", "text": str(res)}], "isError": False}
                })
        return None

class AutonomousMCPAgent:
    def __init__(self):
        self.servers: Dict[str, MockMCPServerInstance] = {}
        self.tool_routing: Dict[str, MockMCPServerInstance] = {}
        self.unified_tools: List[Dict[str, Any]] = []
        self.req_id = 0
        
    def register_server(self, name: str, server_instance: MockMCPServerInstance):
        self.servers[name] = server_instance
        # Handshake
        self.req_id += 1
        init_req = json.dumps({"jsonrpc": "2.0", "id": self.req_id, "method": "initialize"})
        server_instance.handle_line(init_req)
        
        # Tools list
        self.req_id += 1
        list_req = json.dumps({"jsonrpc": "2.0", "id": self.req_id, "method": "tools/list"})
        list_resp = json.loads(server_instance.handle_line(list_req))
        
        tools = list_resp.get("result", {}).get("tools", [])
        for t in tools:
            self.tool_routing[t["name"]] = server_instance
            self.unified_tools.append(t)
            
    def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
        if tool_name not in self.tool_routing:
            return f"Error: Tool '{tool_name}' not found."
        server = self.tool_routing[tool_name]
        self.req_id += 1
        call_req = json.dumps({
            "jsonrpc": "2.0",
            "id": self.req_id,
            "method": "tools/call",
            "params": {"name": tool_name, "arguments": arguments}
        })
        resp = json.loads(server.handle_line(call_req))
        content = resp.get("result", {}).get("content", [])
        return content[0]["text"] if content else ""

if __name__ == "__main__":
    agent = AutonomousMCPAgent()
    srv1 = MockMCPServerInstance("db-srv", {"query_users": lambda args: "Alice, Bob"})
    srv2 = MockMCPServerInstance("fs-srv", {"read_file": lambda args: "File contents: OK"})
    agent.register_server("db-srv", srv1)
    agent.register_server("fs-srv", srv2)
    print("Unified tools:", [t["name"] for t in agent.unified_tools])
    print("DB Result:", agent.execute_tool("query_users", {}))
    print("FS Result:", agent.execute_tool("read_file", {}))
metadata.yml (397 bytes)
lesson_id: D299
day: 299
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/mcp_client.py
test_commands:
- bash tests/run_tests.sh
cleanup_commands:
- rm -rf __pycache__ .pytest_cache
requires_network: false
requires_api_key: false
estimated_minutes: 45
last_executed: '2026-08-30'
executed_on: macOS 15.0 Apple Silicon
requirements/requirements.txt (14 bytes)
pytest>=7.0.0
starter/mcp_client.py (1689 bytes)
"""STARTER -- implement each TASK below, then run the tests.

Every function that raises NotImplementedError is yours to write. The
imports, constants and data structures are given; the logic is not.
Run `bash tests/run_tests.sh` to see which tasks are still outstanding.
"""

import json
from typing import Dict, Any, List, Optional

class MockMCPServerInstance:

    def __init__(self, name: str, tools_dict: Dict[str, Any]):
        self.name = name
        self.tools_dict = tools_dict

    def handle_line(self, line: str) -> Optional[str]:
        raise NotImplementedError('TASK 1: implement handle_line.')

class AutonomousMCPAgent:

    def __init__(self):
        self.servers: Dict[str, MockMCPServerInstance] = {}
        self.tool_routing: Dict[str, MockMCPServerInstance] = {}
        self.unified_tools: List[Dict[str, Any]] = []
        self.req_id = 0

    def register_server(self, name: str, server_instance: MockMCPServerInstance):
        raise NotImplementedError('TASK 2: implement register_server.')

    def execute_tool(self, tool_name: str, arguments: Dict[str, Any]) -> str:
        raise NotImplementedError('TASK 3: implement execute_tool.')
if __name__ == '__main__':
    agent = AutonomousMCPAgent()
    srv1 = MockMCPServerInstance('db-srv', {'query_users': lambda args: 'Alice, Bob'})
    srv2 = MockMCPServerInstance('fs-srv', {'read_file': lambda args: 'File contents: OK'})
    agent.register_server('db-srv', srv1)
    agent.register_server('fs-srv', srv2)
    print('Unified tools:', [t['name'] for t in agent.unified_tools])
    print('DB Result:', agent.execute_tool('query_users', {}))
    print('FS Result:', agent.execute_tool('read_file', {}))
tests/run_tests.sh (253 bytes)
#!/usr/bin/env bash
set -e
export PYTHONPATH=examples:.
if [ -n "$PYTEST" ]; then
    $PYTEST tests/test_*.py -v
elif command -v pytest &> /dev/null; then
    pytest tests/test_*.py -v
else
    python3 -m unittest discover -s tests -p 'test_*.py' -v
fi
tests/test_mcp_client.py (1395 bytes)
import pytest
from examples.mcp_client import MockMCPServerInstance, AutonomousMCPAgent

def test_multi_server_registration():
    agent = AutonomousMCPAgent()
    srv1 = MockMCPServerInstance("db", {"sql_query": lambda args: "10 rows"})
    srv2 = MockMCPServerInstance("fs", {"read_log": lambda args: "log entries"})
    agent.register_server("db", srv1)
    agent.register_server("fs", srv2)
    
    assert len(agent.unified_tools) == 2
    tool_names = [t["name"] for t in agent.unified_tools]
    assert "sql_query" in tool_names
    assert "read_log" in tool_names

def test_tool_routing_execution():
    agent = AutonomousMCPAgent()
    srv1 = MockMCPServerInstance("db", {"sql_query": lambda args: "Result A"})
    srv2 = MockMCPServerInstance("fs", {"read_log": lambda args: "Result B"})
    agent.register_server("db", srv1)
    agent.register_server("fs", srv2)
    
    res1 = agent.execute_tool("sql_query", {})
    assert res1 == "Result A"
    
    res2 = agent.execute_tool("read_log", {})
    assert res2 == "Result B"

def test_unknown_tool_routing():
    agent = AutonomousMCPAgent()
    res = agent.execute_tool("unknown_action", {})
    assert "not found" in res.lower()

def test_initialization_handshake():
    srv = MockMCPServerInstance("test", {})
    res_str = srv.handle_line('{"jsonrpc": "2.0", "id": 1, "method": "initialize"}')
    assert "2024-11-05" in res_str

Troubleshooting

Troubleshooting - Day 299

Verify tool names do not collide across registered servers.

Security notes

Security - Day 299

Audit tool permissions and isolate multi-server execution environments.