MCP Server Boilerplate

MCP Server Boilerplate

A minimal, well-documented MCP server boilerplate providing a reusable baseline with tools, resources, prompts, and extensive documentation for building custom MCP servers.

Category
访问服务器

README

MCP Server Boilerplate

A minimal, well-documented MCP (Model Context Protocol) server implementation designed to serve as a reusable baseline for building custom MCP servers.

What is MCP?

The Model Context Protocol (MCP) is a standardized protocol that enables AI assistants to interact with external servers. MCP servers can provide:

  • Tools: Functions that the AI can call to perform actions
  • Resources: Static or dynamic data that the AI can read
  • Prompts: Reusable prompt templates for consistent AI interactions

Features

This boilerplate provides:

  • Minimal structure: Clean baseline that can be easily extended
  • Extensive documentation: Inline comments and separate documentation files
  • Architecture diagrams: Mermaid diagrams showing component interactions
  • Scaling guide: Best practices for growing your server
  • Type hints: Full type annotations for better IDE support
  • Async/await: Non-blocking I/O for concurrent operations

Reusable Prompt Templates

Prompts are reusable prompt templates that allow you to define structured prompts with placeholders. They enable:

  • Consistency: Standardized prompt formats across different AI interactions
  • Parameterization: Dynamic content insertion through arguments
  • Reusability: Define once, use multiple times with different inputs
  • Type safety: Defined argument schemas with validation

A prompt template consists of:

  • Name: Unique identifier for the prompt
  • Description: What the prompt does
  • Arguments: Optional parameters that can be filled in when using the prompt

Example use cases:

  • Code review templates with configurable severity levels
  • Documentation generation with customizable tone
  • Analysis prompts with variable focus areas
  • Report generation with different output formats

Project Structure

windsurf-project-3/
├── mcp_server.py          # Main server implementation with extensive comments
├── pyproject.toml         # Project configuration for uv
├── ARCHITECTURE.md        # Architecture documentation with Mermaid diagrams
├── SCALING_GUIDE.md       # Scaling patterns and best practices
├── README.md              # This file
├── tools/                 # Placeholder for tool modules (create as needed)
├── resources/             # Placeholder for resource modules (create as needed)
├── prompts/               # Placeholder for prompt modules (create as needed)
└── utils/                 # Placeholder for utility modules (create as needed)

Installation

This project uses uv for fast Python package management.

  1. Install Python 3.10 or higher
  2. Install uv (if not already installed):
curl -LsSf https://astral.sh/uv/install.sh | sh
  1. Install dependencies:
uv sync

Quick Start

1. Add Your First Tool

Edit mcp_server.py and add a tool in the list_tools() function:

@app.list_tools()
async def list_tools() -> list[Tool]:
    return [
        Tool(
            name="echo",
            description="Echo back the input text",
            inputSchema={
                "type": "object",
                "properties": {
                    "text": {"type": "string", "description": "Text to echo"}
                },
                "required": ["text"]
            }
        )
    ]

2. Implement the Tool Handler

Add the tool logic in the call_tool() function:

@app.call_tool()
async def call_tool(name: str, arguments: Any) -> str:
    if name == "echo":
        text = arguments.get("text", "")
        return f"Echo: {text}"
    raise ValueError(f"Unknown tool: {name}")

3. Add a Prompt (Optional)

Add a prompt in the list_prompts() function:

@app.list_prompts()
async def list_prompts() -> list[Prompt]:
    return [
        Prompt(
            name="example_prompt",
            description="An example prompt template",
            arguments=[
                PromptArgument(
                    name="topic",
                    description="The topic to write about",
                    required=True
                )
            ]
        )
    ]

Then implement the handler in get_prompt():

@app.get_prompt()
async def get_prompt(name: str, arguments: dict[str, str] | None) -> str:
    if name == "example_prompt":
        topic = arguments.get("topic") if arguments else None
        if not topic:
            raise ValueError("Argument 'topic' is required")
        return f"Write a detailed explanation about {topic}."
    raise ValueError(f"Unknown prompt: {name}")

3. Run the Server

uv run python mcp_server.py

4. Configure Your MCP Client

Add this to your MCP client's configuration:

{
  "mcpServers": {
    "your-server-name": {
      "command": "uv",
      "args": ["run", "python", "/path/to/mcp_server.py"]
    }
  }
}

Documentation

  • ARCHITECTURE.md: Detailed architecture documentation with Mermaid diagrams showing:

    • Python modules and their purposes
    • Component interactions
    • Request flows (tool invocation, resource reading)
    • Design patterns used
  • SCALING_GUIDE.md: Best practices for scaling your server:

    • Modularization patterns
    • State management strategies
    • Error handling patterns
    • Logging and monitoring
    • Configuration management
    • Testing strategies
    • Performance optimization
    • Security considerations

Code Structure

The main server file (mcp_server.py) is organized into sections:

  1. Server Initialization: Create the MCP server instance
  2. Tool Registration: Define available tools
  3. Tool Handlers: Implement tool execution logic
  4. Resource Registration: Define available resources
  5. Resource Handlers: Implement resource reading logic
  6. Entry Point: Start the server with stdio communication

Each section includes extensive inline comments explaining the purpose and usage of each component.

Extension Points

Adding Tools

  1. Define the tool in list_tools() with its schema
  2. Implement the handler in call_tool()
  3. For larger projects, move to separate module in tools/ directory

Adding Prompts

  1. Define the prompt in list_prompts() with its arguments
  2. Implement the handler in get_prompt()
  3. For larger projects, move to separate module in prompts/ directory

Adding Resources

  1. Define the resource in list_resources() with its metadata
  2. Implement the handler in read_resource()
  3. For larger projects, move to separate module in resources/ directory

Adding Utilities

Extract shared code into the utils/ directory:

  • Validation functions
  • Logging helpers
  • Configuration management
  • Error handling utilities

Using as a Baseline

This boilerplate is designed to be copied and modified for new projects:

  1. Copy the entire project directory
  2. Rename the project in pyproject.toml
  3. Update the server name in mcp_server.py
  4. Add your tools, resources, and prompts
  5. Customize documentation as needed

Python Modules Used

  • mcp.server.Server: Main MCP server class
  • mcp.types.Tool: Tool type definition
  • mcp.types.Resource: Resource type definition
  • mcp.types.Prompt: Prompt type definition
  • mcp.types.PromptArgument: Prompt argument type definition
  • mcp.server.stdio: Stdio communication streams
  • asyncio: Async/await for concurrent operations
  • typing: Type hints for code clarity

See ARCHITECTURE.md for detailed explanations of each module.

Development

Running Tests

# Run with pytest (add tests first)
uv run pytest

Code Style

This project uses Python type hints and follows PEP 8 conventions. Consider using:

  • ruff for linting
  • mypy for type checking

Adding Dependencies

uv add <package-name>

Troubleshooting

  • Import error: Run uv sync to install dependencies
  • Server not responding: Check MCP client configuration
  • Type errors: Ensure Python 3.10+ is installed
  • uv command not found: Install uv from https://github.com/astral-sh/uv

Resources

License

This boilerplate is provided as-is for educational and development purposes. Feel free to use and modify it for your projects.

推荐服务器

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

官方
精选