A FastAPI application with MCP (Model Context Protocol) server integration for performing basic math operations. This project exposes addition and subtraction operations both as REST APIs and as MCP tools for AI applications.
MCP/
├── main.py # FastAPI application with routers
├── mcp_server.py # MCP server for AI applications
├── mcp.json # MCP configuration example
├── requirements.txt # Python dependencies
├── README.md # This file
└── api/
├── __init__.py # Python package marker
├── add.py # Addition API endpoint
└── subtract.py # Subtraction API endpoint
- FastAPI REST API: Traditional REST endpoints for math operations
- MCP Server: Expose operations as tools for AI applications (Claude Desktop, etc.)
- Router-based Architecture: Clean, scalable code organization
- Type Safety: Pydantic models for request/response validation
- Python 3.10 or higher
uv
package manager (recommended) orpip
Using uv
:
uv pip install -r requirements.txt
Using pip
:
pip install -r requirements.txt
Start the REST API server:
python main.py
The server will be available at:
- API Base:
http://localhost:8000
- Interactive Docs:
http://localhost:8000/docs
- Add endpoint:
POST http://localhost:8000/api/add
- Subtract endpoint:
POST http://localhost:8000/api/subtract
Add two numbers:
curl -X POST "http://localhost:8000/api/add" \
-H "Content-Type: application/json" \
-d '{"a": 10.5, "b": 5.5}'
Subtract two numbers:
curl -X POST "http://localhost:8000/api/subtract" \
-H "Content-Type: application/json" \
-d '{"a": 20.0, "b": 5.5}'
The MCP server allows AI applications to use the math operations as tools.
You can test the MCP server using the MCP Inspector tool:
-
Install MCP Inspector:
npm install -g @modelcontextprotocol/inspector
-
Run the inspector:
mcp-inspector uv run mcp_server.py
-
Test the tools in the web interface:
- Open the URL provided by the inspector (usually
http://localhost:5173
) - You'll see the available tools:
add
andsubtract
- Click on a tool to test it with sample inputs
- View the responses in real-time
- Open the URL provided by the inspector (usually
You can also test the MCP server directly via stdio:
uv run mcp_server.py
Then send JSON-RPC requests manually. Example:
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 10, "b": 5}}}
-
Locate your Claude Desktop configuration file:
- Windows:
%APPDATA%\Claude\claude_desktop_config.json
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
- Linux:
~/.config/Claude/claude_desktop_config.json
- Windows:
-
Add the MCP server configuration:
{
"mcpServers": {
"math-operations": {
"command": "uv",
"args": [
"run",
"mcp_server.py"
],
"cwd": "d:\\Projects\\MCP",
"env": {}
}
}
}
Important Configuration Notes:
cwd
(Current Working Directory): MUST be the absolute path to your project directory- Windows: Use double backslashes
\\
or forward slashes/
- macOS/Linux: Use absolute path like
/home/user/projects/MCP
- Windows: Use double backslashes
command
: The executable to run (uv
,python
, etc.)args
: Arguments passed to the commandenv
: Optional environment variables (empty object{}
for none)
-
Verify the configuration:
- The
cwd
path must exist and containmcp_server.py
- Ensure
uv
is installed and accessible from your PATH - On Windows, you can verify the path by running:
dir "d:\Projects\MCP\mcp_server.py"
- On macOS/Linux, verify with:
ls -la /path/to/MCP/mcp_server.py
- The
-
Restart Claude Desktop completely:
- Close Claude Desktop entirely (check system tray/menu bar)
- Reopen Claude Desktop
- The math operations tools should now appear
-
Verify the connection:
- In Claude Desktop, check the settings or tools panel
- Look for "math-operations" server status (should show as connected)
- If there's an error, check the logs (see Troubleshooting section)
Most MCP-compatible AI applications use similar configuration. Copy from mcp.json and adapt:
For Cline/VSCode: Add to your VSCode settings or Cline configuration:
{
"cline.mcpServers": {
"math-operations": {
"command": "uv",
"args": ["run", "mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
}
}
For Continue.dev:
Add to ~/.continue/config.json
:
{
"mcpServers": [
{
"name": "math-operations",
"command": "uv",
"args": ["run", "mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
]
}
Adds two numbers together.
Parameters:
a
(number, required): First number to addb
(number, required): Second number to add
Returns:
result
: The sum of a and boperation
: "addition"inputs
: The input values
Example:
{
"a": 10.5,
"b": 5.5
}
Response:
Result: 16.0
Operation: addition
Inputs: a=10.5, b=5.5
Subtracts b from a.
Parameters:
a
(number, required): Number to subtract fromb
(number, required): Number to subtract
Returns:
result
: The difference (a - b)operation
: "subtraction"inputs
: The input values
Example:
{
"a": 20.0,
"b": 5.5
}
Response:
Result: 14.5
Operation: subtraction
Inputs: a=20.0, b=5.5
Using Python requests:
import requests
# Test add endpoint
response = requests.post(
"http://localhost:8000/api/add",
json={"a": 10.5, "b": 5.5}
)
print(response.json())
# Test subtract endpoint
response = requests.post(
"http://localhost:8000/api/subtract",
json={"a": 20.0, "b": 5.5}
)
print(response.json())
Using the interactive docs:
- Navigate to
http://localhost:8000/docs
- Click on an endpoint to expand it
- Click "Try it out"
- Enter test values
- Click "Execute"
Method 1: Using MCP Inspector (Recommended)
# Install inspector globally
npm install -g @modelcontextprotocol/inspector
# Launch inspector with your MCP server
mcp-inspector uv run mcp_server.py
# Open browser to http://localhost:5173
# Test tools interactively
Method 2: Manual stdio Testing
# Run the server
uv run mcp_server.py
# In another terminal, send test requests
echo '{"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05", "capabilities": {}, "clientInfo": {"name": "test", "version": "1.0"}}}' | uv run mcp_server.py
Method 3: Using Python MCP Client
import asyncio
from mcp.client.stdio import stdio_client
async def test_mcp():
async with stdio_client("uv", ["run", "mcp_server.py"]) as (read, write):
# Test listing tools
tools = await read.list_tools()
print("Available tools:", tools)
# Test calling add
result = await read.call_tool("add", {"a": 10, "b": 5})
print("Add result:", result)
asyncio.run(test_mcp())
After configuring Claude Desktop:
-
Check server status:
- Open Claude Desktop settings
- Look for MCP Servers section
- Verify "math-operations" shows as "Connected" (green indicator)
-
Test the tools:
- Start a new conversation in Claude Desktop
- Ask: "Can you add 15 and 25 for me?"
- Claude should use the
add
tool from your MCP server - Check the response includes tool usage indicator
-
View logs:
- Windows:
%APPDATA%\Claude\logs\mcp-*.log
- macOS:
~/Library/Logs/Claude/mcp-*.log
- Linux:
~/.config/Claude/logs/mcp-*.log
- Windows:
To add new math operations (e.g., multiply, divide):
- Create API endpoint in
api/multiply.py
:
from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class MultiplyRequest(BaseModel):
a: float
b: float
class MultiplyResponse(BaseModel):
result: float
operation: str
inputs: dict
@router.post("/multiply", response_model=MultiplyResponse)
def multiply_numbers(request: MultiplyRequest):
result = request.a * request.b
return MultiplyResponse(
result=result,
operation="multiplication",
inputs={"a": request.a, "b": request.b}
)
- Add router to main.py:
from api.multiply import router as multiply_router
app.include_router(multiply_router, prefix="/api", tags=["Math Operations"])
- Add MCP tool in mcp_server.py:
Update list_tools()
:
Tool(
name="multiply",
description="Multiply two numbers together. Returns the product of a and b.",
inputSchema={
"type": "object",
"properties": {
"a": {"type": "number", "description": "First number to multiply"},
"b": {"type": "number", "description": "Second number to multiply"}
},
"required": ["a", "b"]
}
)
Update call_tool()
:
elif name == "multiply":
result = a * b
operation = "multiplication"
logger.info(f"Executing multiply: {a} * {b} = {result}")
- fastapi: Modern web framework for building APIs
- uvicorn: ASGI server for running FastAPI
- pydantic: Data validation using Python type annotations
- mcp: Model Context Protocol SDK for AI integrations
Problem: Server not connecting in Claude Desktop
-
Verify configuration path:
# Windows type "%APPDATA%\Claude\claude_desktop_config.json" # macOS/Linux cat ~/Library/Application\ Support/Claude/claude_desktop_config.json
-
Check the cwd path exists:
# Windows dir "d:\Projects\MCP\mcp_server.py" # macOS/Linux ls -la /path/to/MCP/mcp_server.py
-
Verify uv is installed:
uv --version
-
Test server manually:
cd d:\Projects\MCP uv run mcp_server.py
-
Check Claude Desktop logs:
- Look for error messages in MCP log files
- Common issues: wrong path, missing dependencies, permission errors
Problem: Tools not appearing in Claude Desktop
- Completely quit Claude Desktop (check system tray)
- Verify JSON syntax in config file (use JSONLint.com)
- Ensure no trailing commas in JSON
- Restart Claude Desktop
- Wait 10-30 seconds for server initialization
Problem: "Module not found" errors
# Reinstall dependencies
cd d:\Projects\MCP
uv pip install -r requirements.txt
# Or using pip
pip install -r requirements.txt
Problem: Port 8000 already in use
# Windows - Find and kill process
netstat -ano | findstr :8000
taskkill /PID <PID> /F
# macOS/Linux
lsof -ti:8000 | xargs kill -9
Problem: Import errors
Ensure you're running from the correct directory:
cd d:\Projects\MCP
python main.py
Problem: MCP Inspector won't start
# Update npm and reinstall inspector
npm install -g npm@latest
npm install -g @modelcontextprotocol/inspector --force
Problem: stdio communication hangs
- Check for print statements or logging that might interfere with stdio
- Ensure JSON-RPC messages are properly formatted
- Use
logger.info()
instead ofprint()
for debugging
- Model Context Protocol Documentation
- FastAPI Documentation
- MCP Python SDK
- Claude Desktop MCP Configuration Guide
This project is provided as-is for educational and development purposes.
Feel free to extend this project with additional math operations or features!