README.md•12.8 kB
# Math Operations API & MCP Server
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.
## Project Structure
```
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
```
## Features
- **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
## Installation
### Prerequisites
- Python 3.10 or higher
- `uv` package manager (recommended) or `pip`
### Install Dependencies
Using `uv`:
```bash
uv pip install -r requirements.txt
```
Using `pip`:
```bash
pip install -r requirements.txt
```
## Usage
### 1. Running the FastAPI Server
Start the REST API server:
```bash
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`
#### Example API Requests
**Add two numbers:**
```bash
curl -X POST "http://localhost:8000/api/add" \
-H "Content-Type: application/json" \
-d '{"a": 10.5, "b": 5.5}'
```
**Subtract two numbers:**
```bash
curl -X POST "http://localhost:8000/api/subtract" \
-H "Content-Type: application/json" \
-d '{"a": 20.0, "b": 5.5}'
```
### 2. Running the MCP Server
The MCP server allows AI applications to use the math operations as tools.
#### Testing MCP Server Locally
You can test the MCP server using the MCP Inspector tool:
1. **Install MCP Inspector:**
```bash
npm install -g @modelcontextprotocol/inspector
```
2. **Run the inspector:**
```bash
mcp-inspector uv run mcp_server.py
```
3. **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` and `subtract`
- Click on a tool to test it with sample inputs
- View the responses in real-time
#### Alternative Testing with stdio
You can also test the MCP server directly via stdio:
```bash
uv run mcp_server.py
```
Then send JSON-RPC requests manually. Example:
```json
{"jsonrpc": "2.0", "id": 1, "method": "tools/list"}
{"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "add", "arguments": {"a": 10, "b": 5}}}
```
#### Integration with AI Applications
##### For Claude Desktop:
1. **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`
2. **Add the MCP server configuration:**
```json
{
"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`
- **`command`**: The executable to run (`uv`, `python`, etc.)
- **`args`**: Arguments passed to the command
- **`env`**: Optional environment variables (empty object `{}` for none)
3. **Verify the configuration:**
- The `cwd` path must exist and contain `mcp_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`
4. **Restart Claude Desktop completely:**
- Close Claude Desktop entirely (check system tray/menu bar)
- Reopen Claude Desktop
- The math operations tools should now appear
5. **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)
##### For Other AI Applications:
Most MCP-compatible AI applications use similar configuration. Copy from [mcp.json](mcp.json) and adapt:
**For Cline/VSCode:**
Add to your VSCode settings or Cline configuration:
```json
{
"cline.mcpServers": {
"math-operations": {
"command": "uv",
"args": ["run", "mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
}
}
```
**For Continue.dev:**
Add to `~/.continue/config.json`:
```json
{
"mcpServers": [
{
"name": "math-operations",
"command": "uv",
"args": ["run", "mcp_server.py"],
"cwd": "/absolute/path/to/MCP"
}
]
}
```
## MCP Tools Documentation
### Tool: `add`
Adds two numbers together.
**Parameters:**
- `a` (number, required): First number to add
- `b` (number, required): Second number to add
**Returns:**
- `result`: The sum of a and b
- `operation`: "addition"
- `inputs`: The input values
**Example:**
```json
{
"a": 10.5,
"b": 5.5
}
```
**Response:**
```
Result: 16.0
Operation: addition
Inputs: a=10.5, b=5.5
```
### Tool: `subtract`
Subtracts b from a.
**Parameters:**
- `a` (number, required): Number to subtract from
- `b` (number, required): Number to subtract
**Returns:**
- `result`: The difference (a - b)
- `operation`: "subtraction"
- `inputs`: The input values
**Example:**
```json
{
"a": 20.0,
"b": 5.5
}
```
**Response:**
```
Result: 14.5
Operation: subtraction
Inputs: a=20.0, b=5.5
```
## Testing & Validation
### 1. Testing FastAPI Endpoints
**Using Python requests:**
```python
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:**
1. Navigate to `http://localhost:8000/docs`
2. Click on an endpoint to expand it
3. Click "Try it out"
4. Enter test values
5. Click "Execute"
### 2. Testing MCP Server
**Method 1: Using MCP Inspector (Recommended)**
```bash
# 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**
```bash
# 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**
```python
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())
```
### 3. Validating Claude Desktop Integration
After configuring Claude Desktop:
1. **Check server status:**
- Open Claude Desktop settings
- Look for MCP Servers section
- Verify "math-operations" shows as "Connected" (green indicator)
2. **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
3. **View logs:**
- **Windows**: `%APPDATA%\Claude\logs\mcp-*.log`
- **macOS**: `~/Library/Logs/Claude/mcp-*.log`
- **Linux**: `~/.config/Claude/logs/mcp-*.log`
## Development
### Adding New Operations
To add new math operations (e.g., multiply, divide):
1. **Create API endpoint** in `api/multiply.py`:
```python
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}
)
```
2. **Add router to main.py**:
```python
from api.multiply import router as multiply_router
app.include_router(multiply_router, prefix="/api", tags=["Math Operations"])
```
3. **Add MCP tool in mcp_server.py**:
Update `list_tools()`:
```python
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()`:
```python
elif name == "multiply":
result = a * b
operation = "multiplication"
logger.info(f"Executing multiply: {a} * {b} = {result}")
```
### Project Dependencies
- **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
## Troubleshooting
### MCP Server Issues
**Problem: Server not connecting in Claude Desktop**
1. **Verify configuration path:**
```bash
# Windows
type "%APPDATA%\Claude\claude_desktop_config.json"
# macOS/Linux
cat ~/Library/Application\ Support/Claude/claude_desktop_config.json
```
2. **Check the cwd path exists:**
```bash
# Windows
dir "d:\Projects\MCP\mcp_server.py"
# macOS/Linux
ls -la /path/to/MCP/mcp_server.py
```
3. **Verify uv is installed:**
```bash
uv --version
```
4. **Test server manually:**
```bash
cd d:\Projects\MCP
uv run mcp_server.py
```
5. **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**
1. Completely quit Claude Desktop (check system tray)
2. Verify JSON syntax in config file (use JSONLint.com)
3. Ensure no trailing commas in JSON
4. Restart Claude Desktop
5. Wait 10-30 seconds for server initialization
**Problem: "Module not found" errors**
```bash
# Reinstall dependencies
cd d:\Projects\MCP
uv pip install -r requirements.txt
# Or using pip
pip install -r requirements.txt
```
### FastAPI Server Issues
**Problem: Port 8000 already in use**
```bash
# 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:
```bash
cd d:\Projects\MCP
python main.py
```
### Testing Issues
**Problem: MCP Inspector won't start**
```bash
# 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 of `print()` for debugging
## Resources
- [Model Context Protocol Documentation](https://modelcontextprotocol.io/)
- [FastAPI Documentation](https://fastapi.tiangolo.com/)
- [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk)
- [Claude Desktop MCP Configuration Guide](https://docs.anthropic.com/claude/docs/model-context-protocol)
## License
This project is provided as-is for educational and development purposes.
## Contributing
Feel free to extend this project with additional math operations or features!