Sample MCP Python is a modern, container-ready MCP (Model Context Protocol) server built with FastMCP and FastAPI. It provides simple arithmetic tools and is designed for easy extension and cloud deployment.
- FastMCP Server: Implements MCP protocol for agent communication.
- Arithmetic Tools: Includes
add
andsubtract
as MCP tools. - Custom Middleware: Logging middleware for all MCP operations.
- FastAPI Exception Handling: Handles session and route errors gracefully.
- Docker Support: Ready for containerized deployment.
- Configurable Logging: Debug and info logs for all operations.
sample-mcp-python/
├── server.py # Main MCP server with tools and middleware
├── test_server.py # (Empty) Placeholder for tests
├── Dockerfile # Container build instructions
├── pyproject.toml # Python project metadata and dependencies
├── uv.lock # Dependency lock file
├── .gitignore # Git ignore rules
├── .dockerignore # Docker ignore rules
- Python 3.12+
- Docker (optional, for container deployment)
-
Install dependencies:
uv sync
-
Run the server:
uv run server.py
-
Build the image:
docker build -t sample-mcp-python .
-
Run the container:
docker run -p 3000:3000 sample-mcp-python
add(a: int, b: int) -> int
: Adds two numbers.subtract(a: int, b: int) -> int
: Subtracts the second number from the first.
- Port: Set the
PORT
environment variable to change the server port (default: 3000). - Logging: Controlled via
fastmcp.settings.log_level
and Python logging config.
Add new MCP tools by decorating functions with @mcp.tool()
in server.py
.
Custom middleware can be added for logging, authentication, etc.
Tests are written in test_server.py
using pytest and pytest-asyncio for async support.
Then, run the tests:
uv run pytest
Example async test:
import pytest
from fastmcp import Client
from server import mcp
client = Client(mcp)
@pytest.mark.asyncio
async def test_add_tool():
async with client:
result = await client.call_tool("add", {"a": 3, "b": 5})
assert result == 8
fastmcp==2.10.6
fastapi>=0.116.1
To test with MCP inspector, run it with npx
: npx @modelcontextprotocol/inspector
MIT License (add your license file if needed)
Made with ❤️ using FastMCP and Python.