# MCP Calculator Server
A comprehensive Model Context Protocol (MCP) server implementation using Python SDK featuring calculator tools, resources, and prompt templates. This server demonstrates how to build an MCP server with multiple capabilities including mathematical operations, resource access, and reusable prompt templates.
## Features
- **8 Calculator Tools**: Addition, subtraction, multiplication, division, power, square root, modulo, and expression evaluation
- **Resources**: Access to external documentation files
- **Prompts**: Reusable prompt templates (e.g., meeting summary template)
- **Dual Transport Support**: Works with both stdio (for Claude Desktop) and Streamable HTTP transports
- **Async Support**: Built with async/await for better performance
## Prerequisites
- **Python 3.10 or higher** - Required for the MCP SDK
- **uv package manager** (recommended) or pip - For package management
## Quick Start
### 1. Clone the Repository
```bash
git clone <your-repo-url>
cd newmcpsdk
```
### 2. Install Dependencies
**Using uv (Recommended):**
```bash
# Install uv if you don't have it
# Windows:
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
# macOS/Linux:
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create virtual environment and install dependencies
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\Activate.ps1
uv pip install "mcp[cli]"
```
**Using pip:**
```bash
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\Activate.ps1
pip install "mcp[cli]"
```
### 3. Run the Server
**For stdio transport (default, used by Claude Desktop):**
```bash
python server.py
```
**For Streamable HTTP transport:**
```bash
TRANSPORT=streamable-http HOST=0.0.0.0 PORT=8000 python server.py
```
## Installation
### Step 1: Verify Python Installation
```bash
python --version # Should be 3.10 or higher
```
### Step 2: Install uv Package Manager
**Windows (PowerShell):**
```powershell
powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"
```
**macOS/Linux:**
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
**Or using pip:**
```bash
pip install uv
```
### Step 3: Create Virtual Environment
```bash
uv venv
```
### Step 4: Activate Virtual Environment
**Windows (PowerShell):**
```powershell
.venv\Scripts\Activate.ps1
```
**Windows (Command Prompt):**
```cmd
.venv\Scripts\activate.bat
```
**macOS/Linux:**
```bash
source .venv/bin/activate
```
### Step 5: Install MCP SDK
```bash
uv pip install "mcp[cli]"
```
### Step 6: Verify Installation
```bash
python -c "from mcp.server.fastmcp import FastMCP; print('MCP installed successfully')"
```
## Configuration
### Claude Desktop Configuration
To use this server with Claude Desktop, add the following to your Claude Desktop config file:
**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
**Linux:** `~/.config/Claude/claude_desktop_config.json`
```json
{
"mcpServers": {
"calculator-server": {
"command": "C:\\path\\to\\your\\project\\.venv\\Scripts\\python.exe",
"args": ["C:\\path\\to\\your\\project\\server.py"],
"env": {}
}
}
}
```
**Important:** Replace the paths with your actual project paths.
### Environment Variables
The server supports the following environment variables:
- `TRANSPORT`: Transport type (`stdio` or `streamable-http`). Default: `stdio`
- `HOST`: Host address for Streamable HTTP transport. Default: `0.0.0.0`
- `PORT`: Port number for Streamable HTTP transport. Default: `8000`
- `TYPESDK_PATH`: Path to TypeScript SDK documentation file (optional). Default: `typesdk.md` in project directory
## Server Features
### Tools
The server provides 8 calculator tools:
#### 1. **add** - Addition
Adds two numbers together.
- Parameters: `a` (float), `b` (float)
- Example: `add(5, 3)` → `8`
#### 2. **subtract** - Subtraction
Subtracts the second number from the first.
- Parameters: `a` (float), `b` (float)
- Example: `subtract(10, 4)` → `6`
#### 3. **multiply** - Multiplication
Multiplies two numbers.
- Parameters: `a` (float), `b` (float)
- Example: `multiply(7, 6)` → `42`
#### 4. **divide** - Division
Divides the first number by the second.
- Parameters: `a` (float), `b` (float)
- Example: `divide(20, 4)` → `5`
- Error handling: Prevents division by zero
#### 5. **power** - Exponentiation
Raises a base number to an exponent.
- Parameters: `base` (float), `exponent` (float)
- Example: `power(2, 8)` → `256`
#### 6. **square_root** - Square Root
Calculates the square root of a number.
- Parameters: `number` (float, must be non-negative)
- Example: `square_root(16)` → `4.0`
- Error handling: Prevents square root of negative numbers
#### 7. **modulo** - Modulo Operation
Calculates the remainder when dividing two numbers.
- Parameters: `a` (float), `b` (float)
- Example: `modulo(17, 5)` → `2`
- Error handling: Prevents modulo by zero
#### 8. **calculate** - Expression Evaluator
Evaluates complex mathematical expressions.
- Parameters: `expression` (string)
- Supports: `+`, `-`, `*`, `/`, `**`, parentheses, and math functions
- Example: `calculate("(3 + 4) * 2")` → `"Result: 14"`
- Functions available: `sqrt`, `sin`, `cos`, `tan`, `log`, `log10`, `exp`, `abs`, `round`, `min`, `max`, `sum`, `pow`
- Constants: `pi`, `e`
### Resources
#### **typesdk://documentation**
Provides access to TypeScript SDK documentation.
- **URI**: `typesdk://documentation`
- **Type**: Read-only resource
- **Configuration**: Set `TYPESDK_PATH` environment variable or place `typesdk.md` in the project directory
### Prompts
#### **meeting_summary**
Generates a formatted meeting summary prompt using a template.
- **Parameters**:
- `meeting_date` (string, optional): The date of the meeting
- `meeting_title` (string, optional): The title or subject of the meeting
- `transcript` (string, optional): The meeting transcript or notes
- **Template Source**: Based on [mikeskarl/mcp-prompt-templates](https://github.com/mikeskarl/mcp-prompt-templates)
- **Usage**: The prompt template includes sections for:
- Overview (purpose, participants, topics)
- Key Decisions
- Action Items
- Follow-up Required
## Project Structure
```
newmcpsdk/
├── server.py # Main MCP server implementation
├── pyproject.toml # Project dependencies and configuration
├── README.md # This documentation file
├── meeting_summary_template.md # Meeting summary prompt template
├── claude_desktop_config.json # Example Claude Desktop configuration
├── .venv/ # Virtual environment (created by uv venv)
└── .gitignore # Git ignore file
```
## Transport Options
### stdio Transport (Default)
Used by Claude Desktop and other local MCP clients. The server communicates via standard input/output.
```bash
python server.py
# or
TRANSPORT=stdio python server.py
```
### Streamable HTTP Transport
For HTTP-based clients using Streamable HTTP. The server runs as an HTTP server.
```bash
TRANSPORT=streamable-http HOST=0.0.0.0 PORT=8000 python server.py
```
## Testing
### Using MCP Inspector
1. **Install MCP Inspector:**
```bash
npx -y @modelcontextprotocol/inspector
```
2. **Run the server:**
```bash
python server.py
```
3. **In another terminal, run the inspector:**
```bash
npx -y @modelcontextprotocol/inspector
```
4. Connect to your server and test the tools, resources, and prompts.
### Example Tool Usage
```python
# Addition
add(a=10, b=5) # Returns: 15
# Subtraction
subtract(a=10, b=3) # Returns: 7
# Multiplication
multiply(a=6, b=7) # Returns: 42
# Division
divide(a=20, b=4) # Returns: 5.0
# Power
power(base=2, exponent=10) # Returns: 1024.0
# Square Root
square_root(number=25) # Returns: 5.0
# Modulo
modulo(a=17, b=5) # Returns: 2.0
# Calculate Expression
calculate(expression="2 + 2") # Returns: "Result: 4"
calculate(expression="(3 + 4) * 2") # Returns: "Result: 14"
calculate(expression="sqrt(16) + pow(2, 3)") # Returns: "Result: 12.0"
```
## Development
### Adding New Tools
1. Open `server.py`
2. Add a new tool function with the `@mcp.tool()` decorator:
```python
@mcp.tool()
def your_tool_name(param1: float, param2: float) -> float:
"""
Description of what your tool does.
Args:
param1: Description of param1
param2: Description of param2
Returns:
Description of return value
"""
# Your tool logic here
result = param1 + param2 # Example
return result
```
3. Save the file and restart the server
The tool will be automatically registered and available to MCP clients.
### Adding New Resources
1. Add a resource handler with the `@mcp.resource()` decorator:
```python
@mcp.resource("your-resource://uri")
def get_your_resource() -> str:
"""
Description of the resource.
Returns:
The resource content as a string
"""
# Read and return your resource content
with open("path/to/resource.md", "r", encoding="utf-8") as f:
return f.read()
```
### Adding New Prompts
1. Create a prompt template file (e.g., `my_prompt_template.md`)
2. Add a prompt handler with the `@mcp.prompt()` decorator:
```python
@mcp.prompt()
def my_prompt(param1: str = "", param2: str = "") -> str:
"""
Generate a prompt using the template.
Args:
param1: Description of param1
param2: Description of param2
Returns:
A formatted prompt string
"""
with open("my_prompt_template.md", "r", encoding="utf-8") as f:
template = f.read()
# Replace template variables
formatted = template.replace("{{ param1 }}", param1)
formatted = formatted.replace("{{ param2 }}", param2)
return formatted
```
## Troubleshooting
### Python Version Issues
**Problem:** Python version is too old or not found.
**Solution:**
```bash
# Check Python version
python --version
# If using uv, specify Python version when creating venv
uv venv --python 3.11
# Or install Python using uv
uv python install 3.11
```
### Virtual Environment Not Activating
**Windows PowerShell - Execution Policy Error:**
```powershell
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
.venv\Scripts\Activate.ps1
```
**Windows Command Prompt:**
```cmd
.venv\Scripts\activate.bat
```
**macOS/Linux:**
```bash
source .venv/bin/activate
```
### Import Errors
**Problem:** Import errors when running the server.
**Solution:**
1. Ensure virtual environment is activated
2. Verify package is installed: `uv pip list | grep mcp`
3. Reinstall if needed: `uv pip install --force-reinstall "mcp[cli]"`
### Server Not Starting
**Problem:** Server exits immediately or shows errors.
**Solution:**
1. Check Python version: `python --version` (should be 3.10+)
2. Verify server.py syntax: `python -m py_compile server.py`
3. Test imports: `python -c "from mcp.server.fastmcp import FastMCP; print('OK')"`
4. Run with error output: `python server.py 2>&1`
### Streamable HTTP Connection Refused (ECONNREFUSED)
**Problem:** Getting `ECONNREFUSED` error when trying to connect via Streamable HTTP.
**Solution:**
1. **Verify the server is running with Streamable HTTP transport:**
```bash
TRANSPORT=streamable-http HOST=0.0.0.0 PORT=8000 python server.py
```
You should see: `Starting Streamable HTTP server on 0.0.0.0:8000`
2. **Check if the server is actually listening:**
```bash
# Windows
netstat -an | findstr 8000
# macOS/Linux
lsof -i :8000
# or
netstat -an | grep 8000
```
3. **Verify the client is connecting to the correct URL:**
- The server should be accessible at: `http://localhost:8000` or `http://0.0.0.0:8000`
- Make sure the client is using the same host and port
4. **Check firewall settings:**
- Ensure port 8000 (or your configured port) is not blocked by firewall
- On Windows, you may need to allow Python through the firewall
5. **Try a different port:**
```bash
TRANSPORT=streamable-http PORT=8080 python server.py
```
6. **For Claude Desktop, use stdio transport instead:**
- Claude Desktop uses stdio transport by default
- Don't set `TRANSPORT=streamable-http` when using with Claude Desktop
- Just run: `python server.py` (stdio is the default)
### Resource Not Found
**Problem:** `typesdk://documentation` resource not found.
**Solution:**
1. Place `typesdk.md` in the project directory, or
2. Set `TYPESDK_PATH` environment variable to the full path of your documentation file
### Prompt Template Not Found
**Problem:** Meeting summary prompt fails with "Template file not found".
**Solution:**
Ensure `meeting_summary_template.md` exists in the project directory. The file is automatically downloaded when you clone the repository, or you can download it from [mikeskarl/mcp-prompt-templates](https://github.com/mikeskarl/mcp-prompt-templates).
## Version Verification Checklist
- [ ] Python 3.10+ installed: `python --version`
- [ ] uv installed: `uv --version`
- [ ] Virtual environment created: `ls .venv` or `dir .venv`
- [ ] Virtual environment activated: `(.venv)` in prompt
- [ ] MCP package installed: `uv pip list | grep mcp`
- [ ] MCP imports work: `python -c "from mcp.server.fastmcp import FastMCP; print('OK')"`
- [ ] Server runs: `python server.py`
## Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## License
This project is provided as-is for educational purposes.
## Resources
- [MCP Python SDK Documentation](https://github.com/modelcontextprotocol/python-sdk)
- [MCP Python SDK GitHub](https://github.com/modelcontextprotocol/python-sdk)
- [Model Context Protocol](https://modelcontextprotocol.io/)
- [uv Documentation](https://github.com/astral-sh/uv)
- [Meeting Summary Template Source](https://github.com/mikeskarl/mcp-prompt-templates)
## Support
If you encounter issues not covered in this README:
1. Check the [Troubleshooting](#troubleshooting) section
2. Review the [MCP Python SDK documentation](https://github.com/modelcontextprotocol/python-sdk)
3. Check [uv documentation](https://github.com/astral-sh/uv) for package management issues
4. Verify all versions meet requirements (Python 3.10+, latest uv)
---
**Last Updated:** 2024
**Python Version Required:** 3.10+
**MCP SDK Version:** Latest (installed via `uv pip install "mcp[cli]"`)