MCP Demo Server

MCP Demo Server

A demonstration MCP server showcasing tools (calculator, file operations, weather, timestamp), resources (server config, system info, documentation), and reusable prompt templates for code review, documentation, and debugging.

Category
访问服务器

README

MCP Demo Server

A production-ready demonstration of a Model Context Protocol (MCP) server implemented in Python. This project showcases best practices for building MCP servers with comprehensive examples of tools, resources, and prompts.

What is MCP?

The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). MCP servers expose:

  • Tools: Executable functions that LLMs can call (e.g., calculator, file operations)
  • Resources: Data sources that LLMs can read (e.g., configuration, documentation)
  • Prompts: Reusable prompt templates for common tasks

Features

Tools Implemented

  1. Calculator - Basic mathematical operations

    • Operations: add, subtract, multiply, divide
    • Full input validation and error handling
  2. File Operations - File system interactions

    • Read, write, list directories, check file existence
    • Safe path handling with proper error messages
  3. Weather - Simulated weather information

    • Get weather data for any city
    • Support for Celsius and Fahrenheit
  4. Timestamp - Get current time in various formats

    • ISO format, Unix timestamp, human-readable format

Resources Available

  1. Server Configuration (config://server/settings)

    • Current server settings and metadata
    • JSON formatted configuration
  2. System Information (system://info)

    • OS, Python version, working directory
    • Server process information
  3. Documentation (docs://getting-started)

    • Getting started guide
    • Usage instructions

Prompts Provided

  1. Code Review - Generate code review checklists

    • Customizable by programming language
    • Adjustable complexity level
  2. Documentation - Documentation templates

    • API, User, and Developer documentation types
    • Project-specific customization
  3. Debug Assistant - Debugging guidance

    • Structured debugging approach
    • Common techniques and best practices

Installation

Prerequisites

  • Python 3.10 or higher
  • pip (Python package manager)

Install Dependencies

# Clone the repository
git clone https://github.com/yourusername/mcp-agent.git
cd mcp-agent

# Install the package
pip install -e .

# Or install dependencies directly
pip install -r requirements.txt

Development Setup

# Install development dependencies
pip install -r requirements-dev.txt

# Run tests
pytest

# Format code
black src/

# Lint code
ruff check src/

Usage

Running the Server

The server uses stdio for communication, which is the standard transport for MCP servers:

# Run directly with Python
python -m mcp_demo.server

# Or use the installed script
mcp-demo

Configuration for Claude Desktop

To use this MCP server with Claude Desktop, add it to your Claude configuration file:

macOS: ~/Library/Application Support/Claude/claude_desktop_config.json

Windows: %APPDATA%\Claude\claude_desktop_config.json

{
  "mcpServers": {
    "demo": {
      "command": "python",
      "args": [
        "-m",
        "mcp_demo.server"
      ],
      "env": {}
    }
  }
}

Or using the installed command:

{
  "mcpServers": {
    "demo": {
      "command": "mcp-demo",
      "args": [],
      "env": {}
    }
  }
}

Using with MCP Client

You can also use the included example client:

python examples/client.py

Project Structure

mcp-agent/
├── src/
│   └── mcp_demo/
│       ├── __init__.py          # Package initialization
│       └── server.py            # Main server implementation
├── examples/
│   ├── client.py                # Example MCP client
│   └── claude_config.json       # Example Claude Desktop config
├── tests/
│   ├── __init__.py
│   └── test_server.py           # Server tests
├── pyproject.toml               # Project configuration
├── requirements.txt             # Production dependencies
├── requirements-dev.txt         # Development dependencies
├── README.md                    # This file
└── LICENSE                      # MIT License

Code Architecture

Server Implementation

The server follows a clean, modular architecture:

class MCPDemoServer:
    """Main server class with handler methods"""

    def __init__(self, name: str):
        """Initialize server and register handlers"""

    async def list_tools(self) -> list[Tool]:
        """Return available tools"""

    async def call_tool(self, name: str, arguments: Any) -> list[TextContent]:
        """Execute a tool"""

    async def list_resources(self) -> list[Resource]:
        """Return available resources"""

    async def read_resource(self, uri: AnyUrl) -> str:
        """Read a resource"""

    async def list_prompts(self) -> list[Prompt]:
        """Return available prompts"""

    async def get_prompt(self, name: str, arguments: dict) -> GetPromptResult:
        """Get a prompt with arguments"""

Key Design Patterns

  1. Type Safety: Full type hints with Pydantic models
  2. Error Handling: Comprehensive try-catch with logging
  3. Validation: Input validation using Pydantic schemas
  4. Logging: Structured logging to file and stderr
  5. Async/Await: Proper async patterns throughout
  6. Separation of Concerns: Each tool in its own method

Examples

Example 1: Using the Calculator Tool

# Tool call from LLM client
{
  "name": "calculator",
  "arguments": {
    "operation": "add",
    "a": 15,
    "b": 27
  }
}

# Response
{
  "content": [
    {
      "type": "text",
      "text": "Result: 15 add 27 = 42"
    }
  ]
}

Example 2: Reading a Resource

# Read server configuration
{
  "uri": "config://server/settings"
}

# Response (JSON)
{
  "server_name": "mcp-demo-server",
  "version": "1.0.0",
  "max_connections": 100,
  "features": ["tools", "resources", "prompts"]
}

Example 3: Getting a Prompt

# Get code review prompt
{
  "name": "code-review",
  "arguments": {
    "language": "Python",
    "complexity": "complex"
  }
}

# Response: Detailed code review checklist for Python

Development

Adding a New Tool

  1. Define input schema with Pydantic:
class MyToolInput(BaseModel):
    param1: str = Field(description="Description")
    param2: int = Field(default=0, description="Description")
  1. Add tool to list_tools():
Tool(
    name="my_tool",
    description="What this tool does",
    inputSchema=MyToolInput.model_json_schema(),
)
  1. Implement tool logic:
async def _my_tool(self, arguments: dict) -> list[TextContent]:
    tool_input = MyToolInput(**arguments)
    # Your implementation here
    return [TextContent(type="text", text="Result")]
  1. Add to call_tool() dispatcher:
if name == "my_tool":
    return await self._my_tool(arguments)

Adding a New Resource

  1. Add to list_resources():
Resource(
    uri=AnyUrl("my://resource"),
    name="My Resource",
    description="What this resource provides",
    mimeType="application/json",
)
  1. Add handler in read_resource():
if uri_str == "my://resource":
    data = {"key": "value"}
    return json.dumps(data, indent=2)

Adding a New Prompt

  1. Add to list_prompts():
Prompt(
    name="my-prompt",
    description="What this prompt does",
    arguments=[
        {
            "name": "arg1",
            "description": "Argument description",
            "required": True,
        }
    ],
)
  1. Add handler in get_prompt():
if name == "my-prompt":
    arg1 = arguments.get("arg1")
    message = f"Prompt template with {arg1}"
    return GetPromptResult(
        messages=[
            PromptMessage(
                role="user",
                content=TextContent(type="text", text=message),
            )
        ]
    )

Testing

Run the test suite:

# Run all tests
pytest

# Run with coverage
pytest --cov=mcp_demo --cov-report=html

# Run specific test file
pytest tests/test_server.py

# Run with verbose output
pytest -v

Best Practices Demonstrated

  1. Input Validation: All tool inputs validated with Pydantic
  2. Error Handling: Comprehensive error handling with meaningful messages
  3. Logging: Structured logging for debugging and monitoring
  4. Type Safety: Full type hints throughout the codebase
  5. Documentation: Comprehensive docstrings and comments
  6. Testing: Unit tests for all major functionality
  7. Code Quality: Formatted with Black, linted with Ruff
  8. Async Patterns: Proper use of async/await
  9. Resource Management: Proper cleanup and resource handling
  10. Security: Safe file operations with path validation

Troubleshooting

Common Issues

Issue: Module not found error

# Solution: Install in development mode
pip install -e .

Issue: Server not appearing in Claude Desktop

# Solution: Check configuration file path and JSON syntax
# Restart Claude Desktop after configuration changes

Issue: Import errors for mcp package

# Solution: Install latest MCP SDK
pip install --upgrade mcp

Debug Mode

Enable debug logging:

import logging
logging.basicConfig(level=logging.DEBUG)

Check the log file:

tail -f mcp_server.log

Contributing

Contributions are welcome! Please:

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Resources

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Built with the MCP Python SDK
  • Inspired by the MCP community examples
  • Thanks to Anthropic for developing the Model Context Protocol

Support


Happy MCP Server Building! 🚀

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选