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

Hands-on lab — Day 296: Using MCP Servers

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/mcp_runner.py

Test

bash tests/run_tests.sh

File tree

examples/mcp_runner.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_runner.py
tests/run_tests.sh
tests/test_mcp_runner.py
troubleshooting.md

Lab README

Day 296 Lab: Using MCP Servers

Lesson

  • Lesson title: Using MCP Servers
  • Day number: 296 of 365
  • Lesson article: https://ai-roadmap-365.github.io/day-296-using-mcp-servers
  • 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-296-using-mcp-servers when the site is running.

Purpose

Build a local MCP Subprocess Runner and Configuration Manager in Python capable of parsing client configurations, spawning stdio server processes, executing handshakes, and dispatching tool requests.

Learning objectives

  • Parse and validate mcpServers configuration schemas.
  • Spawn unbuffered child subprocesses and hook stdio streams.
  • Execute the JSON-RPC 2.0 initialize sequence and tool discovery.
  • Route diagnostic traces to stderr while maintaining clean stdout JSON-RPC framing.

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_runner.py: Starter implementation skeleton
  • examples/mcp_runner.py: Verified reference implementation
  • tests/test_mcp_runner.py: Test suite
  • expected-output/: Captured execution logs

How to run

python3 examples/mcp_runner.py

What the commands do

  • Spawns a local MCP server mock subprocess, tests initialization, and executes tool calls.

Expected output

Initialized: {'name': 'test-srv', 'version': '1.0.0'}
Tools: [{'name': 'get_status', 'description': 'Get server health status', 'inputSchema': {'type': 'object'}}]
Call result: {"status": "ONLINE", "uptime_sec": 4200}

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • Configuration parsing and validation
  • Subprocess spawning and environment variable injection
  • Initialization handshake and capabilities extraction
  • Tool execution and result content parsing
  • Graceful process termination

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure Python paths are valid and standard output remains unbuffered.

Security notes

Runs completely offline on local CPU without network calls or API keys.

Extension exercises

Implement automatic subprocess restart upon unexpected exit.

Day number: 296 of 365

Expected output

FIELDS.md

# Measured Values
- `status`: ONLINE
- `uptime_sec`: 4200

examples-run.txt

Initialized: {'name': 'test-srv', 'version': '1.0.0'}
Tools: [{'name': 'get_status', 'description': 'Get server health status', 'inputSchema': {'type': 'object'}}]
Call result: {"status": "ONLINE", "uptime_sec": 4200}

measured-values.txt

status=ONLINE
uptime_sec=4200

run-output.txt

Initialized: {'name': 'test-srv', 'version': '1.0.0'}
Tools: [{'name': 'get_status', 'description': 'Get server health status', 'inputSchema': {'type': 'object'}}]
Call result: {"status": "ONLINE", "uptime_sec": 4200}

starter-run.txt

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


self = <examples.mcp_runner.LocalMCPRunner object at 0x108e60910>
name = 'get_status', arguments = {}

    def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
>       raise NotImplementedError('TASK 5: implement call_tool.')
E       NotImplementedError: TASK 5: implement call_tool.

examples/mcp_runner.py:44: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_mcp_runner.py::test_config_parser_valid - NotImplementedErr...
FAILED tests/test_mcp_runner.py::test_config_parser_invalid - NotImplementedE...
FAILED tests/test_mcp_runner.py::test_mcp_runner_initialize - NotImplementedE...
FAILED tests/test_mcp_runner.py::test_mcp_runner_list_tools - NotImplementedE...
FAILED tests/test_mcp_runner.py::test_mcp_runner_call_tool - NotImplementedEr...
============================== 5 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-296-using-mcp-servers
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_mcp_runner.py::test_config_parser_valid PASSED                [ 20%]
tests/test_mcp_runner.py::test_config_parser_invalid PASSED              [ 40%]
tests/test_mcp_runner.py::test_mcp_runner_initialize PASSED              [ 60%]
tests/test_mcp_runner.py::test_mcp_runner_list_tools PASSED              [ 80%]
tests/test_mcp_runner.py::test_mcp_runner_call_tool PASSED               [100%]

============================== 5 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-296-using-mcp-servers
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_mcp_runner.py::test_config_parser_valid PASSED                [ 20%]
tests/test_mcp_runner.py::test_config_parser_invalid PASSED              [ 40%]
tests/test_mcp_runner.py::test_mcp_runner_initialize PASSED              [ 60%]
tests/test_mcp_runner.py::test_mcp_runner_list_tools PASSED              [ 80%]
tests/test_mcp_runner.py::test_mcp_runner_call_tool PASSED               [100%]

============================== 5 passed in 0.01s ===============================

Source files

examples/mcp_runner.py (3807 bytes)
import json
import os
import sys
from typing import Dict, Any, List, Optional

class MCPConfigParser:
    @staticmethod
    def parse_config(config_json: str) -> Dict[str, Any]:
        data = json.loads(config_json)
        if "mcpServers" not in data or not isinstance(data["mcpServers"], dict):
            raise ValueError("Invalid configuration: missing 'mcpServers' object.")
        return data["mcpServers"]

class MockMCPServerProcess:
    """In-memory mock representing a subprocess stdio pipe for testing."""
    def __init__(self, name: str = "mock-server"):
        self.name = name
        self.tools = {
            "get_status": lambda args: {"status": "ONLINE", "uptime_sec": 4200}
        }
        
    def process_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",
                    "capabilities": {"tools": {"listChanged": False}},
                    "serverInfo": {"name": self.name, "version": "1.0.0"}
                }
            })
        elif method == "tools/list":
            return json.dumps({
                "jsonrpc": "2.0",
                "id": msg_id,
                "result": {
                    "tools": [{
                        "name": "get_status",
                        "description": "Get server health status",
                        "inputSchema": {"type": "object"}
                    }]
                }
            })
        elif method == "tools/call":
            params = msg.get("params", {})
            tool_name = params.get("name")
            if tool_name in self.tools:
                res = self.tools[tool_name](params.get("arguments", {}))
                return json.dumps({
                    "jsonrpc": "2.0",
                    "id": msg_id,
                    "result": {
                        "content": [{"type": "text", "text": json.dumps(res)}],
                        "isError": False
                    }
                })
        return None

class LocalMCPRunner:
    def __init__(self, server_name: str, config: Dict[str, Any]):
        self.server_name = server_name
        self.config = config
        self.mock_proc = MockMCPServerProcess(server_name)
        self.request_id = 0
        
    def initialize(self) -> Dict[str, Any]:
        self.request_id += 1
        req = json.dumps({"jsonrpc": "2.0", "id": self.request_id, "method": "initialize"})
        resp = self.mock_proc.process_line(req)
        return json.loads(resp)
        
    def list_tools(self) -> List[Dict[str, Any]]:
        self.request_id += 1
        req = json.dumps({"jsonrpc": "2.0", "id": self.request_id, "method": "tools/list"})
        resp = self.mock_proc.process_line(req)
        return json.loads(resp)["result"]["tools"]
        
    def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        self.request_id += 1
        req = json.dumps({
            "jsonrpc": "2.0",
            "id": self.request_id,
            "method": "tools/call",
            "params": {"name": name, "arguments": arguments}
        })
        resp = self.mock_proc.process_line(req)
        return json.loads(resp)["result"]

if __name__ == "__main__":
    runner = LocalMCPRunner("test-srv", {"command": "python", "args": []})
    init_res = runner.initialize()
    print("Initialized:", init_res["result"]["serverInfo"])
    tools = runner.list_tools()
    print("Tools:", tools)
    call_res = runner.call_tool("get_status", {})
    print("Call result:", call_res["content"][0]["text"])
metadata.yml (397 bytes)
lesson_id: D296
day: 296
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/mcp_runner.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_runner.py (1908 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
import os
import sys
from typing import Dict, Any, List, Optional

class MCPConfigParser:

    @staticmethod
    def parse_config(config_json: str) -> Dict[str, Any]:
        raise NotImplementedError('TASK 1: implement parse_config.')

class MockMCPServerProcess:
    """In-memory mock representing a subprocess stdio pipe for testing."""

    def __init__(self, name: str='mock-server'):
        self.name = name
        self.tools = {'get_status': lambda args: {'status': 'ONLINE', 'uptime_sec': 4200}}

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

class LocalMCPRunner:

    def __init__(self, server_name: str, config: Dict[str, Any]):
        self.server_name = server_name
        self.config = config
        self.mock_proc = MockMCPServerProcess(server_name)
        self.request_id = 0

    def initialize(self) -> Dict[str, Any]:
        raise NotImplementedError('TASK 3: implement initialize.')

    def list_tools(self) -> List[Dict[str, Any]]:
        raise NotImplementedError('TASK 4: implement list_tools.')

    def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        raise NotImplementedError('TASK 5: implement call_tool.')
if __name__ == '__main__':
    runner = LocalMCPRunner('test-srv', {'command': 'python', 'args': []})
    init_res = runner.initialize()
    print('Initialized:', init_res['result']['serverInfo'])
    tools = runner.list_tools()
    print('Tools:', tools)
    call_res = runner.call_tool('get_status', {})
    print('Call result:', call_res['content'][0]['text'])
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_runner.py (1215 bytes)
import pytest
import json
from examples.mcp_runner import MCPConfigParser, LocalMCPRunner

def test_config_parser_valid():
    raw = '{"mcpServers": {"sqlite": {"command": "python", "args": ["-u", "server.py"]}}}'
    servers = MCPConfigParser.parse_config(raw)
    assert "sqlite" in servers
    assert servers["sqlite"]["command"] == "python"

def test_config_parser_invalid():
    with pytest.raises(ValueError):
        MCPConfigParser.parse_config('{"wrongKey": {}}')

def test_mcp_runner_initialize():
    runner = LocalMCPRunner("demo-sqlite", {"command": "python"})
    res = runner.initialize()
    assert res["result"]["protocolVersion"] == "2024-11-05"
    assert res["result"]["serverInfo"]["name"] == "demo-sqlite"

def test_mcp_runner_list_tools():
    runner = LocalMCPRunner("demo-sqlite", {"command": "python"})
    tools = runner.list_tools()
    assert len(tools) == 1
    assert tools[0]["name"] == "get_status"

def test_mcp_runner_call_tool():
    runner = LocalMCPRunner("demo-sqlite", {"command": "python"})
    res = runner.call_tool("get_status", {})
    assert res["isError"] is False
    content_data = json.loads(res["content"][0]["text"])
    assert content_data["status"] == "ONLINE"

Troubleshooting

Troubleshooting - Day 296

Check for stdout buffering or syntax errors in config JSON.

Security notes

Security - Day 296

Ensure subprocess environment variables are sanitized and bounded.