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

Hands-on lab — Day 297: Building an MCP Server

Commands

Setup

pip install -r requirements/requirements.txt

Run

python examples/custom_mcp_server.py

Test

bash tests/run_tests.sh

File tree

examples/custom_mcp_server.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/custom_mcp_server.py
tests/run_tests.sh
tests/test_custom_mcp_server.py
troubleshooting.md

Lab README

Day 297 Lab: Building an MCP Server

Lesson

  • Lesson title: Building an MCP Server
  • Day number: 297 of 365
  • Lesson article: https://ai-roadmap-365.github.io/day-297-building-an-mcp-server
  • 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-297-building-an-mcp-server when the site is running.

Purpose

Build a custom FastMCP-style Model Context Protocol server engine in Python featuring decorator registration, automated JSON Schema generation from type annotations, and structured error propagation.

Learning objectives

  • Construct an MCP server using FastMCP/Python decorator abstractions.
  • Generate JSON Schema parameter specifications automatically from Python type hints and docstrings.
  • Implement type validation, boundary enforcement, and structured error responses.
  • Expose real-world database and file utility tools over a standard stdio event loop.

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

How to run

python3 examples/custom_mcp_server.py

What the commands do

  • Registers custom tools with type hints and verifies JSON Schema reflection and execution.

Expected output

Registered tools: [{'name': 'calculate_tax', 'description': 'Calculate total amount including tax.', 'inputSchema': {'type': 'object', 'properties': {'amount': {'type': 'number'}, 'rate': {'type': 'number'}}, 'required': ['amount']}}]
Execution result: {'content': [{'type': 'text', 'text': '110.00000000000001'}], 'isError': False}

Validation steps

Run test runner:

bash tests/run_tests.sh

Tests

The test suite validates:

  • @tool decorator registration and tool catalog listing
  • Automatic JSON Schema property type mapping (str, int, float, bool)
  • Required parameter detection from function signatures
  • Successful execution returning formatted text content
  • Exception handling and error response formatting with isError: True

Cleanup

rm -rf .pytest_cache __pycache__ .venv

Troubleshooting

Ensure function signatures include type annotations for all parameters.

Security notes

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

Extension exercises

Add support for Pydantic BaseModel schemas.

Day number: 297 of 365

Expected output

FIELDS.md

# Measured Values
- `registered_tools`: 1
- `result_status`: success

examples-run.txt

Registered tools: [{'name': 'calculate_tax', 'description': 'Calculate total amount including tax.', 'inputSchema': {'type': 'object', 'properties': {'amount': {'type': 'number'}, 'rate': {'type': 'number'}}, 'required': ['amount']}}]
Execution result: {'content': [{'type': 'text', 'text': '110.00000000000001'}], 'isError': False}

measured-values.txt

registered_tools=1
result_status=success

run-output.txt

Registered tools: [{'name': 'calculate_tax', 'description': 'Calculate total amount including tax.', 'inputSchema': {'type': 'object', 'properties': {'amount': {'type': 'number'}, 'rate': {'type': 'number'}}, 'required': ['amount']}}]
Execution result: {'content': [{'type': 'text', 'text': '110.00000000000001'}], 'isError': False}

starter-run.txt

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


self = <examples.custom_mcp_server.CustomMCPServer object at 0x10b12e780>
name = 'nonexistent', arguments = {}

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

examples/custom_mcp_server.py:25: NotImplementedError
=========================== short test summary info ============================
FAILED tests/test_custom_mcp_server.py::test_tool_registration_and_schema - N...
FAILED tests/test_custom_mcp_server.py::test_tool_call_success - NotImplement...
FAILED tests/test_custom_mcp_server.py::test_tool_call_missing_arg_error - No...
FAILED tests/test_custom_mcp_server.py::test_tool_call_runtime_exception - No...
FAILED tests/test_custom_mcp_server.py::test_unknown_tool_call - NotImplement...
============================== 5 failed in 0.04s ===============================

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-297-building-an-mcp-server
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_custom_mcp_server.py::test_tool_registration_and_schema PASSED [ 20%]
tests/test_custom_mcp_server.py::test_tool_call_success PASSED           [ 40%]
tests/test_custom_mcp_server.py::test_tool_call_missing_arg_error PASSED [ 60%]
tests/test_custom_mcp_server.py::test_tool_call_runtime_exception PASSED [ 80%]
tests/test_custom_mcp_server.py::test_unknown_tool_call 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-297-building-an-mcp-server
plugins: cov-7.1.0, anyio-4.14.2
collecting ... collected 5 items

tests/test_custom_mcp_server.py::test_tool_registration_and_schema PASSED [ 20%]
tests/test_custom_mcp_server.py::test_tool_call_success PASSED           [ 40%]
tests/test_custom_mcp_server.py::test_tool_call_missing_arg_error PASSED [ 60%]
tests/test_custom_mcp_server.py::test_tool_call_runtime_exception PASSED [ 80%]
tests/test_custom_mcp_server.py::test_unknown_tool_call PASSED           [100%]

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

Source files

examples/custom_mcp_server.py (3236 bytes)
import inspect
import json
from typing import Dict, Any, Callable, get_type_hints, List, Optional

class CustomMCPServer:
    def __init__(self, name: str = "custom-mcp-server"):
        self.name = name
        self.tools: Dict[str, Dict[str, Any]] = {}
        
    def tool(self, name: Optional[str] = None, description: Optional[str] = None):
        def decorator(fn: Callable):
            tool_name = name or fn.__name__
            tool_desc = description or (inspect.getdoc(fn) or "No description provided.")
            
            sig = inspect.signature(fn)
            type_hints = get_type_hints(fn)
            
            properties = {}
            required = []
            
            for param_name, param in sig.parameters.items():
                p_type = type_hints.get(param_name, str)
                json_type = "string"
                if p_type == int:
                    json_type = "integer"
                elif p_type == float:
                    json_type = "number"
                elif p_type == bool:
                    json_type = "boolean"
                elif p_type == list:
                    json_type = "array"
                    
                properties[param_name] = {"type": json_type}
                if param.default == inspect.Parameter.empty:
                    required.append(param_name)
                    
            input_schema = {
                "type": "object",
                "properties": properties,
                "required": required
            }
            
            self.tools[tool_name] = {
                "name": tool_name,
                "description": tool_desc,
                "inputSchema": input_schema,
                "handler": fn
            }
            return fn
        return decorator
        
    def list_tools(self) -> List[Dict[str, Any]]:
        return [
            {
                "name": t["name"],
                "description": t["description"],
                "inputSchema": t["inputSchema"]
            }
            for t in self.tools.values()
        ]
        
    def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        if name not in self.tools:
            return {
                "content": [{"type": "text", "text": f"Tool '{name}' not found."}],
                "isError": True
            }
            
        tool = self.tools[name]
        fn = tool["handler"]
        
        try:
            res = fn(**arguments)
            return {
                "content": [{"type": "text", "text": str(res)}],
                "isError": False
            }
        except Exception as e:
            return {
                "content": [{"type": "text", "text": f"Error executing {name}: {str(e)}"}],
                "isError": True
            }

if __name__ == "__main__":
    server = CustomMCPServer("retail-tools")
    
    @server.tool()
    def calculate_tax(amount: float, rate: float = 0.08) -> float:
        """Calculate total amount including tax."""
        return amount * (1.0 + rate)
        
    print("Registered tools:", server.list_tools())
    res = server.call_tool("calculate_tax", {"amount": 100.0, "rate": 0.10})
    print("Execution result:", res)
metadata.yml (404 bytes)
lesson_id: D297
day: 297
kind: python
languages:
- python
setup_commands:
- pip install -r requirements/requirements.txt
run_commands:
- python examples/custom_mcp_server.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/custom_mcp_server.py (1419 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 inspect
import json
from typing import Dict, Any, Callable, get_type_hints, List, Optional

class CustomMCPServer:

    def __init__(self, name: str='custom-mcp-server'):
        self.name = name
        self.tools: Dict[str, Dict[str, Any]] = {}

    def tool(self, name: Optional[str]=None, description: Optional[str]=None):
        raise NotImplementedError('TASK 2: implement tool.')

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

    def call_tool(self, name: str, arguments: Dict[str, Any]) -> Dict[str, Any]:
        raise NotImplementedError('TASK 4: implement call_tool.')
if __name__ == '__main__':
    server = CustomMCPServer('retail-tools')

    @server.tool()
    def calculate_tax(amount: float, rate: float=0.08) -> float:
        """Calculate total amount including tax."""
        raise NotImplementedError('TASK 5: implement calculate_tax. Calculate total amount including tax.')
    print('Registered tools:', server.list_tools())
    res = server.call_tool('calculate_tax', {'amount': 100.0, 'rate': 0.1})
    print('Execution result:', res)
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_custom_mcp_server.py (1828 bytes)
import pytest
from examples.custom_mcp_server import CustomMCPServer

def test_tool_registration_and_schema():
    server = CustomMCPServer("test-server")
    
    @server.tool()
    def add_numbers(a: int, b: int = 10) -> int:
        """Add two numbers together."""
        return a + b
        
    tools = server.list_tools()
    assert len(tools) == 1
    t = tools[0]
    assert t["name"] == "add_numbers"
    assert t["description"] == "Add two numbers together."
    assert t["inputSchema"]["properties"]["a"]["type"] == "integer"
    assert t["inputSchema"]["properties"]["b"]["type"] == "integer"
    assert t["inputSchema"]["required"] == ["a"]

def test_tool_call_success():
    server = CustomMCPServer("calc")
    
    @server.tool()
    def multiply(x: float, y: float) -> float:
        return x * y
        
    res = server.call_tool("multiply", {"x": 3.5, "y": 2.0})
    assert res["isError"] is False
    assert res["content"][0]["text"] == "7.0"

def test_tool_call_missing_arg_error():
    server = CustomMCPServer("calc")
    
    @server.tool()
    def divide(a: float, b: float) -> float:
        return a / b
        
    res = server.call_tool("divide", {"a": 10.0}) # missing b
    assert res["isError"] is True
    assert "missing" in res["content"][0]["text"].lower()

def test_tool_call_runtime_exception():
    server = CustomMCPServer("calc")
    
    @server.tool()
    def divide(a: float, b: float) -> float:
        return a / b
        
    res = server.call_tool("divide", {"a": 10.0, "b": 0.0})
    assert res["isError"] is True
    assert "division by zero" in res["content"][0]["text"]

def test_unknown_tool_call():
    server = CustomMCPServer("calc")
    res = server.call_tool("nonexistent", {})
    assert res["isError"] is True
    assert "not found" in res["content"][0]["text"]

Troubleshooting

Troubleshooting - Day 297

Verify type annotations match expected JSON schema types.

Security notes

Security - Day 297

Sanitize all tool parameters and enforce type safety.