MCP Calculator Server

MCP Calculator Server

Provides mathematical calculation tools including basic operations, expressions, and functions, along with TypeScript SDK documentation resources and meeting summary prompt templates.

Category
访问服务器

README

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

git clone <your-repo-url>
cd newmcpsdk

2. Install Dependencies

Using uv (Recommended):

# 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:

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):

python server.py

For Streamable HTTP transport:

TRANSPORT=streamable-http HOST=0.0.0.0 PORT=8000 python server.py

Installation

Step 1: Verify Python Installation

python --version  # Should be 3.10 or higher

Step 2: Install uv Package Manager

Windows (PowerShell):

powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"

macOS/Linux:

curl -LsSf https://astral.sh/uv/install.sh | sh

Or using pip:

pip install uv

Step 3: Create Virtual Environment

uv venv

Step 4: Activate Virtual Environment

Windows (PowerShell):

.venv\Scripts\Activate.ps1

Windows (Command Prompt):

.venv\Scripts\activate.bat

macOS/Linux:

source .venv/bin/activate

Step 5: Install MCP SDK

uv pip install "mcp[cli]"

Step 6: Verify Installation

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

{
  "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

  • 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.

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.

TRANSPORT=streamable-http HOST=0.0.0.0 PORT=8000 python server.py

Testing

Using MCP Inspector

  1. Install MCP Inspector:
npx -y @modelcontextprotocol/inspector
  1. Run the server:
python server.py
  1. In another terminal, run the inspector:
npx -y @modelcontextprotocol/inspector
  1. Connect to your server and test the tools, resources, and prompts.

Example Tool Usage

# 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:

@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
  1. 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:
@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:

@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:

# 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:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
.venv\Scripts\Activate.ps1

Windows Command Prompt:

.venv\Scripts\activate.bat

macOS/Linux:

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:

    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:

    # 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:

    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.

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

Support

If you encounter issues not covered in this README:

  1. Check the Troubleshooting section
  2. Review the MCP Python SDK documentation
  3. Check uv documentation 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]")

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选