AI Engineering: Agents and Applications › The Model Context Protocol › Day 295
Hands-on lab — Day 295: What MCP Is and Why It Exists
- ← Back to the Day 295 lesson
- Open the hands-on files on GitHub — clone or download them from the public labs repository
- Local path in your clone:
labs/sections/ai-engineering/day-295-what-mcp-is-and-why-it/
Commands
Setup
pip install -r requirements/requirements.txt Run
python examples/mcp_protocol.py Test
bash tests/run_tests.sh File tree
examples/mcp_protocol.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_protocol.py tests/run_tests.sh tests/test_mcp_protocol.py troubleshooting.md
Lab README
Day 295 Lab: What MCP Is and Why It Exists
Lesson
- Lesson title: What MCP Is and Why It Exists
- Day number: 295 of 365
- Lesson article: https://ai-roadmap-365.github.io/day-295-what-mcp-is-and-why-it
- 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-295-what-mcp-is-and-why-itwhen the site is running.
Purpose
Construct a standards-compliant JSON-RPC 2.0 Model Context Protocol (MCP) server engine in Python implementing the complete handshake, tool discovery, and execution lifecycle.
Learning objectives
- Deconstruct the N-times-M integration dilemma solved by MCP.
- Implement JSON-RPC 2.0 message parsing and error contract handling.
- Build capability negotiation for the initialize handshake.
- Dispatch dynamic tool executions with structured content responses.
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_protocol.py: Starter implementation skeletonexamples/mcp_protocol.py: Verified reference implementationtests/test_mcp_protocol.py: Test suiteexpected-output/: Captured execution logs
How to run
python3 examples/mcp_protocol.py
What the commands do
- Evaluates JSON-RPC message processing across initialization, discovery, and execution turns.
Expected output
Init response: {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "math-server", "version": "1.0.0"}}}
Validation steps
Run test runner:
bash tests/run_tests.sh
Tests
The test suite validates:
- JSON-RPC 2.0 initialize request and capability response
- Ignored notifications without response emission
- tools/list tool discovery payload
- tools/call execution and structured error handling
- Malformed JSON parse error codes (-32700)
Cleanup
rm -rf .pytest_cache __pycache__ .venv
Troubleshooting
Ensure all JSON strings are valid and tool handlers return stringifiable values.
Security notes
Runs completely offline on local CPU.
Extension exercises
Add support for URI-addressable resources and resource subscriptions.
Navigation
Day number: 295 of 365
Expected output
FIELDS.md
# Measured Values
- `tools_count`: 1
- `protocol_version`: 2024-11-05
examples-run.txt
Init response: {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "math-server", "version": "1.0.0"}}}
measured-values.txt
tools_count=1
protocol_version=2024-11-05
run-output.txt
Init response: {"jsonrpc": "2.0", "id": 1, "result": {"protocolVersion": "2024-11-05", "capabilities": {"tools": {"listChanged": false}}, "serverInfo": {"name": "math-server", "version": "1.0.0"}}}
starter-run.txt
An untouched starter fails the suite. Captured from a real run:
self = <examples.mcp_protocol.MCPProtocolHandler object at 0x1069c68b0>
raw_message = 'INVALID JSON {'
def handle_message(self, raw_message: str) -> Optional[str]:
> raise NotImplementedError('TASK 2: implement handle_message.')
E NotImplementedError: TASK 2: implement handle_message.
examples/mcp_protocol.py:22: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_mcp_protocol.py::test_mcp_initialize - NotImplementedError:...
FAILED tests/test_mcp_protocol.py::test_mcp_notification_ignored - NotImpleme...
FAILED tests/test_mcp_protocol.py::test_mcp_tools_list_and_call - NotImplemen...
FAILED tests/test_mcp_protocol.py::test_mcp_unknown_tool - NotImplementedErro...
FAILED tests/test_mcp_protocol.py::test_mcp_parse_error - NotImplementedError...
============================== 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-295-what-mcp-is-and-why-it
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items
tests/test_mcp_protocol.py::test_mcp_initialize PASSED [ 20%]
tests/test_mcp_protocol.py::test_mcp_notification_ignored PASSED [ 40%]
tests/test_mcp_protocol.py::test_mcp_tools_list_and_call PASSED [ 60%]
tests/test_mcp_protocol.py::test_mcp_unknown_tool PASSED [ 80%]
tests/test_mcp_protocol.py::test_mcp_parse_error 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-295-what-mcp-is-and-why-it
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items
tests/test_mcp_protocol.py::test_mcp_initialize PASSED [ 20%]
tests/test_mcp_protocol.py::test_mcp_notification_ignored PASSED [ 40%]
tests/test_mcp_protocol.py::test_mcp_tools_list_and_call PASSED [ 60%]
tests/test_mcp_protocol.py::test_mcp_unknown_tool PASSED [ 80%]
tests/test_mcp_protocol.py::test_mcp_parse_error PASSED [100%]
============================== 5 passed in 0.01s ===============================
Source files
examples/mcp_protocol.py (4049 bytes)
import json
from typing import Dict, Any, Optional
class MCPProtocolHandler:
def __init__(self, server_name: str = "demo-server", server_version: str = "1.0.0"):
self.server_name = server_name
self.server_version = server_version
self.tools: Dict[str, Dict[str, Any]] = {}
def register_tool(self, name: str, description: str, input_schema: Dict[str, Any], handler_fn):
self.tools[name] = {
"definition": {
"name": name,
"description": description,
"inputSchema": input_schema
},
"handler": handler_fn
}
def handle_message(self, raw_message: str) -> Optional[str]:
try:
msg = json.loads(raw_message.strip())
except Exception:
return json.dumps({
"jsonrpc": "2.0",
"id": None,
"error": {"code": -32700, "message": "Parse error"}
})
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.server_name,
"version": self.server_version
}
}
})
elif method == "notifications/initialized":
return None
elif method == "tools/list":
tool_list = [t["definition"] for t in self.tools.values()]
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")
tool_args = params.get("arguments", {})
if tool_name not in self.tools:
return json.dumps({
"jsonrpc": "2.0",
"id": msg_id,
"error": {"code": -32601, "message": f"Tool not found: {tool_name}"}
})
try:
handler = self.tools[tool_name]["handler"]
result_text = handler(tool_args)
return json.dumps({
"jsonrpc": "2.0",
"id": msg_id,
"result": {
"content": [
{"type": "text", "text": str(result_text)}
],
"isError": False
}
})
except Exception as e:
return json.dumps({
"jsonrpc": "2.0",
"id": msg_id,
"result": {
"content": [
{"type": "text", "text": f"Execution error: {str(e)}"}
],
"isError": True
}
})
if msg_id is not None:
return json.dumps({
"jsonrpc": "2.0",
"id": msg_id,
"error": {"code": -32601, "message": f"Method not found: {method}"}
})
return None
if __name__ == "__main__":
server = MCPProtocolHandler("math-server", "1.0.0")
server.register_tool(
"add",
"Add two numbers",
{"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "number"}}},
lambda args: args["a"] + args["b"]
)
resp = server.handle_message('{"jsonrpc": "2.0", "id": 1, "method": "initialize"}')
print("Init response:", resp)
metadata.yml (399 bytes)
lesson_id: D295
day: 295
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/mcp_protocol.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_protocol.py (1262 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, Optional
class MCPProtocolHandler:
def __init__(self, server_name: str='demo-server', server_version: str='1.0.0'):
self.server_name = server_name
self.server_version = server_version
self.tools: Dict[str, Dict[str, Any]] = {}
def register_tool(self, name: str, description: str, input_schema: Dict[str, Any], handler_fn):
raise NotImplementedError('TASK 1: implement register_tool.')
def handle_message(self, raw_message: str) -> Optional[str]:
raise NotImplementedError('TASK 2: implement handle_message.')
if __name__ == '__main__':
server = MCPProtocolHandler('math-server', '1.0.0')
server.register_tool('add', 'Add two numbers', {'type': 'object', 'properties': {'a': {'type': 'number'}, 'b': {'type': 'number'}}}, lambda args: args['a'] + args['b'])
resp = server.handle_message('{"jsonrpc": "2.0", "id": 1, "method": "initialize"}')
print('Init response:', resp)
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_protocol.py (1902 bytes)
import pytest
import json
from examples.mcp_protocol import MCPProtocolHandler
def test_mcp_initialize():
server = MCPProtocolHandler("test-server", "2.0.0")
res_str = server.handle_message('{"jsonrpc": "2.0", "id": 1, "method": "initialize"}')
assert res_str is not None
res = json.loads(res_str)
assert res["result"]["protocolVersion"] == "2024-11-05"
assert res["result"]["serverInfo"]["name"] == "test-server"
def test_mcp_notification_ignored():
server = MCPProtocolHandler()
res_str = server.handle_message('{"jsonrpc": "2.0", "method": "notifications/initialized"}')
assert res_str is None
def test_mcp_tools_list_and_call():
server = MCPProtocolHandler()
server.register_tool(
"add",
"Add numbers",
{"type": "object"},
lambda args: args["a"] + args["b"]
)
# List
list_str = server.handle_message('{"jsonrpc": "2.0", "id": 2, "method": "tools/list"}')
list_res = json.loads(list_str)
assert len(list_res["result"]["tools"]) == 1
assert list_res["result"]["tools"][0]["name"] == "add"
# Call
call_str = server.handle_message('{"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 10, "b": 32}}}')
call_res = json.loads(call_str)
assert call_res["result"]["content"][0]["text"] == "42"
assert call_res["result"]["isError"] is False
def test_mcp_unknown_tool():
server = MCPProtocolHandler()
call_str = server.handle_message('{"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "nonexistent"}}')
call_res = json.loads(call_str)
assert "error" in call_res
assert call_res["error"]["code"] == -32601
def test_mcp_parse_error():
server = MCPProtocolHandler()
res_str = server.handle_message('INVALID JSON {')
res = json.loads(res_str)
assert res["error"]["code"] == -32700
Troubleshooting
Troubleshooting - Day 295
Verify JSON-RPC 2.0 response format conforms to spec.
Security notes
Security - Day 295
Enforce strict JSON schema parsing and error boundaries.