MCP Server Hero

MCP Server Hero

A professional Python framework and template for building robust Model Context Protocol (MCP) servers with modular architecture, enterprise features like authentication and rate limiting, and comprehensive tooling. Provides easy-to-use APIs for registering tools, resources, and prompts with full type safety and multiple transport support.

Category
访问服务器

README

MCP Server Hero

A professional Model Context Protocol (MCP) server template and framework for building robust MCP servers in Python.

Features

  • 🏗️ Modular Architecture: Clean separation of tools, resources, prompts, and configuration
  • 🔧 Easy Registration: Simple APIs for registering tools, resources, and prompts
  • 📝 Type Safety: Full type hints and validation throughout
  • 🚀 Multiple Transports: Support for stdio and SSE (Server-Sent Events) transports
  • 📊 Professional Logging: Built-in logging and debugging support
  • 🧪 Testing Ready: Structured for easy testing with pytest
  • 📖 Comprehensive Examples: Both basic and advanced usage examples

Enterprise Features

  • Middleware System: Request/response processing pipeline with validation, logging, timing, and rate limiting
  • 🧩 Plugin System: Dynamic plugin loading with dependency management
  • 🔐 Authentication & Authorization: Flexible auth providers with permission-based access control
  • 💾 Caching System: Multi-layer caching with TTL support and LRU eviction
  • 📊 Metrics & Monitoring: Comprehensive performance metrics and health checks
  • 🛡️ Rate Limiting: Token bucket rate limiting with per-client support

Quick Start

Installation

# Install uv package manager
make install-uv

# Install all dependencies
make install

# Or install production only
make install-prod

Basic Usage

from mcp_server_hero import MCPServerHero
import anyio
from mcp.server.stdio import stdio_server

async def add_numbers(a: int, b: int) -> int:
    """Add two numbers together."""
    return a + b

async def main():
    # Create server instance
    server = MCPServerHero(name="My Server")
    
    # Register a tool
    server.add_tool(
        name="add",
        tool_func=add_numbers,
        description="Add two numbers",
        schema={
            "type": "object",
            "properties": {
                "a": {"type": "integer"},
                "b": {"type": "integer"}
            },
            "required": ["a", "b"]
        }
    )
    
    # Run the server
    async with stdio_server() as streams:
        await server.run(streams[0], streams[1], server.create_initialization_options())

if __name__ == "__main__":
    anyio.run(main)

Enterprise Usage

from mcp_server_hero import MCPServerHero
from mcp_server_hero.middleware.rate_limit import RateLimitMiddleware
from mcp_server_hero.auth.base import SimpleAuthProvider

# Create enterprise server
server = MCPServerHero("Enterprise Server", debug=True)

# Add advanced features
server.add_middleware(RateLimitMiddleware(tool_limit=100))
server.enable_auth_provider(SimpleAuthProvider())
await server.load_plugins_from_directory("plugins/")

# Initialize and run
await server.initialize()

Running Examples

# Run different server examples
make run-basic       # Basic function-based server
make run-advanced    # Class-based server with custom components  
make run-enterprise  # Full-featured enterprise server

# Run with different transports
make run-server      # SSE transport (web-based)
make run-stdio       # Stdio transport (direct communication)
make run-debug       # Debug mode with detailed logging

Development

# Code quality
make check          # Run all quality checks (lint + format + typecheck)
make test           # Run tests
make test-cov       # Run tests with coverage

# Individual quality checks  
make lint           # Code linting
make format         # Code formatting
make typecheck      # Type checking

Architecture

src/mcp_server_hero/
├── core/              # Core server implementation
│   ├── cli.py         # Command-line interface
│   ├── server.py      # Main server class
│   └── version.py     # Version info
├── tools/             # Tool management
├── resources/         # Resource management  
├── prompts/           # Prompt management
├── middleware/        # Middleware system
│   ├── logging.py     # Request/response logging
│   ├── timing.py      # Performance monitoring
│   ├── validation.py  # Input validation
│   └── rate_limit.py  # Rate limiting
├── plugins/           # Plugin system
├── auth/              # Authentication framework
├── cache/             # Caching system
├── metrics/           # Metrics collection
├── config/            # Configuration
├── utils/             # Utilities
└── examples/          # Usage examples

Components

Tools

Tools perform actions and return results:

# Simple function tool
async def my_tool(param: str) -> str:
    return f"Result: {param}"

server.add_tool("my_tool", my_tool, "Description")

# Class-based tool with advanced features
from mcp_server_hero.tools.base import BaseTool

class MyTool(BaseTool):
    async def execute(self, arguments):
        return [TextContent(type="text", text="Result")]

Resources

Resources provide read-only data:

# Simple function resource
async def get_data() -> str:
    return "Resource data"

server.add_resource("data://example", get_data, "Example data")

Prompts

Prompts generate structured messages:

# Simple function prompt
async def create_prompt(topic: str) -> str:
    return f"Please explain {topic}"

server.add_prompt("explain", create_prompt, "Explanation prompt")

Middleware

Process requests through a pipeline:

from mcp_server_hero.middleware import ValidationMiddleware, TimingMiddleware

server.add_middleware(ValidationMiddleware())
server.add_middleware(TimingMiddleware())

Plugins

Extend functionality dynamically:

from mcp_server_hero.plugins.base import BasePlugin

class MyPlugin(BasePlugin):
    async def initialize(self, server):
        server.add_tool("plugin_tool", self.my_tool, "Plugin tool")

Configuration

from mcp_server_hero.config import ServerSettings

settings = ServerSettings(
    name="My Server",
    debug=True,
    log_level="DEBUG",
    timeout=60.0
)

server = MCPServerHero(settings=settings)

Monitoring & Metrics

The server provides comprehensive monitoring:

# Get server statistics
stats = server.get_server_stats()

# Get performance metrics  
metrics = await server.get_metrics()

# Health check
health = await server.health_check()

Project Commands

make help           # Show all available commands
make examples       # List example servers
make stats          # Show project statistics  
make clean          # Clean build artifacts

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Run make check to verify code quality
  5. Add tests if applicable
  6. Submit a pull request

License

MIT License - see LICENSE file for details.

MCP Protocol

This framework implements the Model Context Protocol (MCP), enabling seamless integration between AI models and external data sources and tools.

For more information about MCP, visit the official documentation.

推荐服务器

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

官方
精选