MCP服务器示例

提供基于FastMCP 2.0的企业级MCP服务器示例,包括扫雷游戏服务器和多种传输协议支持,适用于AI逻辑推理和实时数据处理场景。

  • by iddv
  • Python
  • 本地部署
  • 9 星标
  • 更新于
在 GitHub 查看 iddv/mcp-example

使用说明

🎯 MCP示例-企业版

🚀 基于FastMCP 2.0的示例,用于构建复杂的模型上下文协议服务器

欢迎来到最终的MCP示例库!使用我们的产品构建企业级AI服务器 扫雷艇实例 以及全面的FastMCP 2.0模板。

✨ 本版新增内容

🎮 生活游戏示例:通过逻辑推理观察LLMs掌握扫雷术
🚀 FastMCP 2.0:具有多种传输协议的企业功能
🏢 生产就绪:身份验证、会话、实时数据、WebSocket支持
🤖 AI代理友好:自动化服务器生成的完整模板和指南

🎯 特色:扫雷器MCP服务器

人工智能逻辑推理的终极演示!

# Start the Minesweeper server
mcp dev examples/servers/minesweeper_server.py

# Or run as HTTP server
python examples/servers/minesweeper_server.py --transport http --port 8000

观看LLM玩扫雷游戏:

# Start a new expert game
new_game("expert")  # 30x16 grid, 99 mines!

# Get AI-powered strategic hints  
get_hint(game_id)   # Returns probability analysis

# Make strategic moves
reveal(game_id, x, y)  # Uncover cells
flag(game_id, x, y)    # Mark mines

# Analyze the board
analyze_board(game_id)  # Full probability matrix

🚀 快速开始

先决条件

  • Python 3.10+ (FastMCP 2.0要求)
  • 诗歌 (推荐)或pip

安装

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

# Install with Poetry (recommended)
poetry install

# Or with pip
pip install -e .

🎮 尝试扫雷服务器

# Development mode with MCP inspector
mcp dev examples/servers/minesweeper_server.py

# HTTP server for web integration
python examples/servers/minesweeper_server.py --transport http --port 8000

# Test with the basic client
python examples/clients/basic_client.py

📁 项目结构

examples/
├── servers/
│   ├── template_server.py       # 📄 Clean template - your starting canvas!
│   ├── minesweeper_server.py    # 🎯 Complex example - learn from this!
│   ├── basic_server.py          # Simple MCP server (official SDK)
│   ├── filesystem_server.py     # File operations server
│   └── comprehensive_server.py  # Full feature showcase
├── clients/
│   └── basic_client.py          # MCP client examples
└── configs/
    ├── claude_desktop_config.json
    └── README.md

# Documentation
├── FASTMCP_AI_AGENT_GUIDE.md    # Complete FastMCP 2.0 guide
├── AI_AGENT_INSTRUCTIONS.md     # Instructions for AI agents
└── CLAUDE.md                    # Project guidelines

🎮 扫雷服务器功能

🧠 AI驱动的游戏

  • 战略工具: new_game(), reveal(), flag(), get_hint()
  • 分析工具: analyze_board(),概率计算
  • 学习资源:策略指南、模式库、教程

🏢 企业功能

  • 多个传输:stdio、HTTP、WebSocket就绪
  • 会话管理:多个并发游戏
  • 实时更新:实时游戏状态流
  • 身份验证就绪:内置OAuth 2.0支持
  • 统计:全球排行榜和分析

📚 教育资源

  • 策略指南:大师级扫雷技术
  • 图案库:常见配置和解决方案
  • AI提示:学习球员的助教
  • 概率分析:决策的数学方法

🔧 服务器示例

🎯 扫雷艇(FastMCP 2.0)

from fastmcp import FastMCP

mcp = FastMCP("🎯 Minesweeper Pro")

@mcp.tool
def new_game(difficulty: str = "beginner") -> dict:
    """🎮 Start a new Minesweeper game!"""
    game_id = game_engine.create_game(difficulty)
    return {"game_id": game_id, "message": "Good luck! 🎯"}

@mcp.resource("game://state/{game_id}")
def get_game_state(game_id: str) -> str:
    """Real-time game state resource."""
    return format_game_display(game_id)

@mcp.prompt
def strategy_guide(situation: str) -> str:
    """Generate strategic analysis for current situation."""
    return f"Strategic guidance for: {situation}..."

🔧 基础服务器(官方SDK)

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("Basic Example Server")

@mcp.tool()
def add_numbers(a: float, b: float) -> float:
    """Add two numbers together."""
    return a + b

@mcp.resource("info://server")
def get_server_info() -> str:
    """Server information resource."""
    return "Basic MCP Server Example..."

🤖 对于AI代理

此存储库已针对AI代理构建MCP服务器进行了优化!

🎯 完美的学习设置

🚀 AI代理的快速入门

# Copy the template and start building
cp examples/servers/template_server.py my_awesome_server.py

# Study the complex example for patterns
cat examples/servers/minesweeper_server.py

# Read the building guides
cat FASTMCP_AI_AGENT_GUIDE.md

📖 完整的文件

🎯 用例

  • 游戏服务器:实时状态互动娱乐
  • 数据处理:具有流式结果的复杂分析
  • API集成:外部服务协调
  • 教育工具:互动学习系统
  • 生产力应用程序:任务管理和自动化

🏢 企业功能(FastMCP 2.0)

🚀 多个传输

# Development: stdio (default)
mcp.run()

# Production: HTTP with streaming
mcp.run(transport="streamable-http", host="0.0.0.0", port=8000)

# WebSocket support ready
mcp.run(transport="websocket", host="127.0.0.1", port=8080)

🔐 身份验证和安全

@mcp.set_auth_config
def auth_config():
    return {
        "authorization_url": "https://your-auth.com/oauth/authorize",
        "token_url": "https://your-auth.com/oauth/token",
        "client_id": os.getenv("CLIENT_ID"),
        "scopes": ["read", "write", "admin"]
    }

📊 实时数据和会话

@mcp.tool
async def create_session(user_id: str, data: dict) -> dict:
    """Create stateful user sessions."""
    session_id = str(uuid.uuid4())
    _sessions[session_id] = {"user": user_id, "data": data}
    return {"session_id": session_id}

@mcp.resource("stream://live-data")
async def live_data() -> str:
    """Streaming real-time data."""
    return f"Live update: {time.time()}"

🔧 开发命令

# Development & Testing
mcp dev examples/servers/minesweeper_server.py
mcp dev examples/servers/basic_server.py

# HTTP Servers
python examples/servers/minesweeper_server.py --transport http --port 8000
python examples/servers/comprehensive_server.py --http --port 8080

# Install for Claude Desktop
mcp install examples/servers/minesweeper_server.py

# Run tests
poetry run pytest
poetry run pytest --cov=examples

# Code quality
poetry run black .
poetry run isort .
poetry run ruff check .
poetry run mypy .

🎯 Claude桌面集成

  1. 复制配置 从 examples/configs/claude_desktop_config.json
  2. 更新服务器路径 要匹配您的设置:
{
  "mcpServers": {
    "minesweeper": {
      "command": "python",
      "args": ["/path/to/examples/servers/minesweeper_server.py"]
    },
    "filesystem": {
      "command": "python", 
      "args": ["/path/to/examples/servers/filesystem_server.py"]
    }
  }
}
  1. 重新启动克劳德桌面 开始玩吧! 🎮

🎮 扫雷游戏示例

🎯 开始播放

# Create a new game
result = new_game("intermediate")  # 16x16, 40 mines
game_id = result["game_id"]

# Make your first move
reveal(game_id, 8, 8)  # Start in the center

# Get strategic advice
hint = get_hint(game_id)
# Returns: {"action": "reveal", "x": 5, "y": 3, "reason": "0% mine probability"}

🧮 高级分析

# Full probability analysis
analysis = analyze_board(game_id)
# Returns probability matrix for all hidden cells

# Strategic guidance
prompt = analyze_strategy(game_id, "stuck on complex constraint")
# Returns step-by-step strategic guidance

📊 统计与学习

# Check your progress
stats = list_games()
# Shows win rate, best times, active games

# Learn from the masters
guide = get_strategy_guide()
# Comprehensive strategy documentation

🧪 测试您的服务器

🔍 MCP检查员

# Test any server interactively
mcp dev examples/servers/minesweeper_server.py
mcp dev examples/servers/basic_server.py

🤖 程序化测试

# Test with FastMCP's built-in testing
from fastmcp.testing import create_test_client

async def test_minesweeper():
    client = create_test_client(mcp)
    
    # Test game creation
    result = await client.call_tool("new_game", {"difficulty": "beginner"})
    assert result["success"] == True
    
    # Test resources
    info = await client.get_resource("stats://global")
    assert "Statistics" in info

🌟 是什么让这个特别

🎮 活生生的例子

  • 互动游戏:观看法学硕士学习和制定战略
  • 实时状态:看到决策过程展开
  • 教育价值:通过游戏理解AI推理

🏢 企业就绪

  • 生产部署:HTTP服务器、身份验证、会话
  • 可扩展体系结构:多种传输方式,支持WebSocket
  • 监控和分析:内置统计数据和性能跟踪

🤖 AI代理优化

  • 完整模板:复制粘贴服务器生成器
  • 综合文档:自主建筑所需的一切
  • 最佳实践:安全性、错误处理、测试模式

📚 了解更多

🤝 贡献

我们欢迎捐款!无论是:

  • 🎮 新游戏示例 (国际象棋、太极拳、数独)
  • 🏢 企业模式 (身份验证、监控、部署)
  • 🤖 AI代理工具 (模板、生成器、测试)
  • 📚 文档 (教程、指南、示例)

指南

  • 保留示例 实用性和教育性
  • 包含 全面的文件
  • 跟随 安全最佳实践
  • 添加 正确的错误处理
  • 使用 类型提示 遍及

🏆 展示

用这些例子构建了一些很酷的东西? 我们很乐意展示它!

  • 企业MCP部署
  • 教育人工智能系统
  • 互动游戏服务器
  • 创意LLM应用程序

📄 许可证

MIT许可证-构建你想要的任何东西!看 许可证 了解详情。

🙏 致谢

  • Anthropic -创建MCP,让AI更好
  • Jeremiah Lowin -对于惊人的FastMCP框架
  • MCP社区 -为了卓越的生态系统
  • 贡献者 -谁让这个仓库变得棒极了

🎯 准备好建造了吗?

# 📄 Start with the clean template (recommended)
cp examples/servers/template_server.py my_server.py
mcp dev my_server.py

# 🎮 Study the complex example
mcp dev examples/servers/minesweeper_server.py

# 📚 Read the building guides
cat FASTMCP_AI_AGENT_GUIDE.md

# 🚀 Test your creation
python my_server.py --transport http --port 8000

🚀 快乐建筑!让我们制作既强大又有趣的MCP服务器! 🎮