Token导航 LogoToken导航TokenDH.com
Py MCP Server logo
AI代理stdio官方级别未说明来源级核验

Py MCP Server

MCP Server

一个基于Python和FastAPI构建的完整Model Context Protocol(MCP)服务器,提供实时天气数据、网页搜索功能和强大的HTTP/SSE传输层。

工具数

5

提示词数

0

GitHub Stars

0

资源数

0
实时天气搜索PythonDockerFastAPI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

作者 / 组织

Joseph1977

提供方

Joseph1977

最后核验

2026/5/17 20:22

运行时

Python

快速接入

先看主来源和安装命令,再打开仓库或文档;下面只保留这个条目的关键接入事实。

命令预览

python -m venv .venv

详细介绍

Python MCP服务器🚀

![Python](https://python.org) ![FastAPI](https://fastapi.tiangolo.com) ![MCP](https://modelcontextprotocol.io) ](https://docker.com)

功能齐全 模型上下文协议(MCP)服务器 使用Python和FastAPI构建,具有实时天气数据、网络搜索功能和强大的HTTP/SSE传输层。此服务器演示了MCP实现的最佳实践,包括适当的异步处理、配置管理和可扩展的工具架构。

现在什么有效

  • 完全可操作的MCP服务器 -在HTTP传输上运行并自动重新加载
  • 实时天气工具 -使用wttr.in API的实时天气数据
  • 网络搜索工具 -Brave搜索和谷歌搜索实施
  • 完整的MCP协议支持 -工具发现、调用、资源和提示
  • 健康监测 - /health/info 监控端点
  • 专业测井 -综合结构化测井
  • 异步会话管理 -正确的FastMCP生命周期管理
  • 包含测试客户端 -即用型MCP客户端进行测试

🌟 主要特点

核心MCP实施

  • 遵从标准:完全遵守模型上下文协议规范
  • HTTP/SSE传输:与服务器发送事件的持久连接
  • 工具发现:动态工具注册和发现
  • 资源管理:完整的资源和及时的处理
  • 会话生命周期:使用FastMCP进行适当的异步会话管理

内置工具

  • 🌤️ 天气工具:来自wttr.in的实时天气数据(不需要API密钥)
  • 🔍 勇敢的搜索:通过Brave search API进行Web搜索(需要API密钥)
  • 🔎 谷歌搜索:通过Google自定义搜索进行Web搜索(需要API密钥)
  • � 文件监视器:使用SSE通知进行实时文件系统监控
  • �📊 系统信息:服务器运行状况和信息端点

生产就绪

  • 自动重装开发:开发过程中的热重新加载
  • 结构化日志记录:适当水平的全面测井
  • 错误处理:跨所有工具的强大异步错误处理
  • 配置管理:基于环境的配置
  • Docker支持:使用Docker Compose完成容器化
  • 健康监测:内置健康检查和服务器信息端点

有关完整的技术概述,请参阅 项目概述 文件。

📁 项目结构

py-mcp-server/
├── app/                           # Main application package
│   ├── __init__.py
│   ├── main.py                    # FastAPI app with FastMCP integration
│   ├── config/                    # Configuration management
│   │   ├── __init__.py
│   │   └── config.py              # Settings and logging configuration
│   ├── core/                      # Core MCP logic
│   │   ├── __init__.py
│   │   └── mcp_core.py            # MCP base classes and utilities
│   ├── tools/                     # Tool implementations
│   │   ├── __init__.py
│   │   ├── weather.py             # Weather tool (wttr.in API)
│   │   ├── web_search.py          # Brave/Google search tools
│   │   ├── file_watcher.py        # File system monitoring core
│   │   └── file_watcher_sse.py    # SSE integration for file events
│   └── transports/                # Transport layer (future expansion)
│       └── __init__.py
├── .env.example                   # Environment configuration template
├── .gitignore                     # Git ignore patterns
├── docker-compose.yml             # Docker Compose configuration
├── Dockerfile                     # Docker build configuration
├── get_mcp_tools_cli.ps1         # PowerShell MCP client (Windows)
├── mcp-flow.md                   # MCP protocol flow documentation
├── requirements.txt               # Python dependencies
├── run.py                         # Server startup script
├── test_mcp_client.py            # Python MCP client for testing
└── README.md                      # This documentation

🚀 快速开始

先决条件

  • Python 3.11+ (建议3.11或更高)
  • 包管理器
  • Git 用于版本控制
  • Docker&Docker编写 (可选,用于容器化部署)

可选API密钥 (用于增强功能)

  • 勇敢搜索API密钥 -网络搜索功能
  • Google自定义搜索API密钥+CX ID -用于Google搜索集成

1.克隆和设置

# Clone the repository
git clone 
cd py-mcp-server

# Create virtual environment (Windows PowerShell)
python -m venv .venv
.\.venv\Scripts\Activate.ps1

# For Linux/macOS
python3 -m venv .venv
source .venv/bin/activate

2.安装依赖项

pip install -r requirements.txt

3.配置环境(可选)

# Copy example environment file
cp .env.example .env

# Edit .env file with your API keys (optional)
# BRAVE_API_KEY=your_brave_api_key_here
# GOOGLE_API_KEY=your_google_api_key_here
# GOOGLE_CX=your_google_custom_search_engine_id

4.启动服务器

python run.py

🎉 就是这样! 您的MCP服务器现在正在运行 http://localhost:8001

5.测试服务器

# Test weather tool (works without API keys)
python test_mcp_client.py

# Check server health
curl http://localhost:8001/health

# View server info
curl http://localhost:8001/info

🛠️ 可用工具

🌤️ 天气工具 *(功能齐全)*

使用wttr.in API获取任何位置的综合天气信息。

用途:

{
  "method": "tools/call",
  "params": {
    "name": "weather",
    "arguments": {
      "location": "San Francisco, CA"
    }
  }
}

特征:

  • 不需要API密钥 -使用免费的wttr.in服务
  • 详细预测 -当前状况、3天预测、每小时数据
  • 全球覆盖 -适用于全球城市
  • 多种格式 -温度、湿度、风、降水

🔍 网络搜索工具 *(需要API密钥)*

勇敢的搜索

{
  "method": "tools/call",
  "params": {
    "name": "brave_search_tool",
    "arguments": {
      "query": "python fastapi tutorial"
    }
  }
}

谷歌搜索

{
  "method": "tools/call",
  "params": {
    "name": "google_search_tool",
    "arguments": {
      "query": "machine learning python"
    }
  }
}

注: 搜索工具需要在您的 .env 文件正常运行。

📁 文件监视工具 *(实时文件监控)*

通过全面的过滤和SSE通知实时监控文件系统更改。

主要特点:

  • 实时监控 -即时文件更改通知
  • 模式过滤 -包含/排除用于目标监控的模式
  • SSE通知 -通过服务器发送事件实时更新
  • 递归监视 -监视目录和子目录
  • 多格式支持 -查看特定文件类型或所有更改

创建文件监视器

{
  "method": "tools/call",
  "params": {
    "name": "create_watcher",
    "arguments": {
      "watcher_id": "project_watcher",
      "watch_path": "/path/to/project",
      "file_patterns": ["*.py", "*.js", "*.ts"],
      "exclude_patterns": ["__pycache__", "*.pyc", "node_modules"],
      "recursive": true,
      "auto_start": true
    }
  }
}

其他文件监视工具

  • start_watcher_tool -启动一个已停止的观察者
  • stop_watcher_tool -停止一个跑步的观察者
  • remove_watcher_tool -完全删除观察者
  • list_watchers_tool -列出所有观察者及其状态
  • get_watcher_status_tool -获取详细的观察者信息

SSE实时通知

连接到实时文件更改事件:

// Connect to SSE stream
const eventSource = new EventSource('http://localhost:8001/file-watcher/sse?watchers=project_watcher');

eventSource.onmessage = function(event) {
  const data = JSON.parse(event.data);
  if (data.type === 'file_change') {
    console.log(`File ${data.event.event_type}: ${data.event.filename}`);
  }
};

测试文件监视器:

# Test file watcher tools
python test_file_watcher.py

# Open SSE test client in browser
# file_watcher_test.html

🔧 服务器端点

端点方法描述
/mcpPOST/SSE主MCP协议端点
/healthGET服务器健康检查
/infoGET服务器信息和功能
/file-watcher/sse文件观察器事件的GETSSE流
/docs获取交互式API文档
/GET欢迎留言

🐳 Docker部署

🚀 优化Docker配置

该项目包括 两种优化的Docker配置:

配置图像大小用例构建时间
标准 (Dockerfile)181MB一般开发~45秒
阿尔卑斯 (Dockerfile.alpine)1.11亿英镑生产(推荐)~40秒

📦 尺寸比较:Alpine版本是 38.7%更小 (减少70MB)

🎯 生产部署(推荐)

# Using optimized Alpine image with Docker Compose
docker-compose up --build

# Run in background (detached mode)
docker-compose up --build -d

# View logs
docker-compose logs -f

# Stop the service
docker-compose down

🛠️ 开发模式

# Start development container with hot reloading
docker-compose --profile development up --build

# This runs on port 8001 with source code mounting

📊 多阶段建筑

两个Dockerfiles都使用 多阶段构建 为了优化:

  • 建设者阶段:编译虚拟环境中的依赖关系
  • 生产阶段:只有必要组件的最小运行时映像
  • 开发阶段:其他调试工具(仅限Alpine)

🔐 安全功能

  • 非root用户 (mcpuser:1001)用于安全
  • 最小攻击面 使用Alpine Linux
  • 健康检查 内置于集装箱内
  • 资源限制 在docker-compose.yml中配置

直接使用Docker

# Build Alpine image (recommended for production)
docker build -f Dockerfile.alpine -t py-mcp-server:alpine .

# Build standard image
docker build -t py-mcp-server:standard .

# Run Alpine container
docker run -p 8001:8001 --env-file .env py-mcp-server:alpine

# Run with resource limits
docker run -p 8001:8001 --env-file .env \
  --memory=512m --cpus=1.0 \
  py-mcp-server:alpine

🔧 Docker配置选项

Docker的环境变量

# Port configuration (original port 8001)
MCP_SERVER_PORT=8001

# Environment mode
ENV=production

# Resource optimization
PYTHONDONTWRITEBYTECODE=1
PYTHONUNBUFFERED=1

卷装载

# Persistent logs
./logs:/app/logs:rw

# Development source mounting
.:/app:rw  # Development only

🏗️ 构建目标

# Production build (default)
docker build -f Dockerfile.alpine --target production -t mcp:prod .

# Development build with additional tools
docker build -f Dockerfile.alpine --target development -t mcp:dev .

🧪 测试服务器

使用包含的测试客户端

Python MCP客户端 *(推荐)*

# Test all tools with comprehensive output (works without API keys)
python test_mcp_client.py

# Expected output:
# Connected to MCP server successfully!
# Available tools: ['weather', 'brave_search_tool', 'google_search_tool']
# Weather result: [Detailed weather information for San Francisco]

PowerShell MCP客户端 *(Windows)*

# Get MCP tools list using PowerShell (Windows users)
powershell -ExecutionPolicy Bypass -File "get_mcp_tools_cli.ps1"

# Expected output:
# === MCP PowerShell Client (CLI-based) ===
# MCP TOOLS LIST:
# Found 3 tools:
# 1. weather
#    Description: Get the current weather for a location...
# 2. brave_search_tool
#    Description: Search the web with Brave Search...
# 3. google_search_tool
#    Description: Search the web with Google Search...

使用curl进行手动测试

# Test server health
curl http://localhost:8001/health

# Get server information
curl http://localhost:8001/info

# Note: Direct MCP protocol testing requires proper SSE handling
# Use the Python or PowerShell clients above for MCP protocol testing

预期的服务器日志

2025-06-09 19:24:01,509 - mcp.server.streamable_http_manager - INFO - StreamableHTTP session manager started
2025-06-09 19:24:01,510 - app.main - INFO - FastMCP session manager started
2025-06-09 19:24:01,511 - app.main - INFO - MCP Server (HTTP/SSE) available at /mcp endpoint on host 0.0.0.0:8001
2025-06-09 19:24:01,512 - app.main - INFO - Registered routes:
2025-06-09 19:24:01,512 - app.main - INFO -   Route: Path='/health', Name='health_check', Methods=['GET']
2025-06-09 19:24:01,512 - app.main - INFO -   Route: Path='/info', Name='server_info', Methods=['GET']

⚙️ 配置

环境变量

创建一个 .env 项目根目录中的文件,具有以下选项:

# API Keys (Optional - Weather tool works without any keys)
BRAVE_API_KEY=your_brave_search_api_key
GOOGLE_API_KEY=your_google_api_key
GOOGLE_CX=your_google_custom_search_engine_id

# Server Configuration
MCP_TRANSPORT_MODE=http          # Transport mode: 'http' or 'stdio'
MCP_SERVER_HOST=0.0.0.0         # Server host address
MCP_SERVER_PORT=8001            # Server port number
LOG_LEVEL=INFO                  # Logging level: DEBUG, INFO, WARNING, ERROR

配置文件

  • app/config/config.py -主要配置管理
  • .env -特定环境变量
  • requirements.txt -Python依赖关系
  • docker-compose.yml -Docker部署配置

🔧 发展

添加新工具

  1. 创建新的工具文件 在……里面 app/tools/:
# app/tools/my_new_tool.py
import asyncio
from typing import Any

async def my_new_tool(param1: str, param2: int = 10) -> dict[str, Any]:
    """Description of what your tool does.
    
    Args:
        param1: Description of parameter 1
        param2: Description of parameter 2 (optional)
    
    Returns:
        Dictionary with tool results
    """
    # Your tool implementation here
    result = {"message": f"Processing {param1} with value {param2}"}
    return result
  1. 在main.py中注册:
# In app/main.py
from app.tools.my_new_tool import my_new_tool

@mcp_server.tool()
async def my_new_tool_endpoint(param1: str, param2: int = 10) -> str:
    """Tool description for MCP clients"""
    result = await my_new_tool(param1, param2)
    return str(result)

项目架构

  • app/main.py -FastAPI应用程序和MCP服务器设置
  • app/config/ -配置和日志管理
  • app/tools/ -单个工具实现
  • app/core/ -核心MCP实用程序和基类
  • app/transports/ -传输层实现(未来)

开发命令

# Start development server with auto-reload
python run.py

# Run with debug logging
LOG_LEVEL=DEBUG python run.py

# Test specific tool
python -c "from app.tools.weather import get_weather; import asyncio; print(asyncio.run(get_weather('London')))"

📊 监测和健康检查

健康检查端点

curl http://localhost:8001/health

答复:

{
  "status": "healthy",
  "server": "MCP Server with FastMCP",
  "version": "1.0.0"
}

服务器信息端点

curl http://localhost:8001/info  

答复:

{
  "name": "Benraz-MCP-Server",
  "description": "An MCP server using FastMCP",
  "transport_mode": "http",
  "endpoints": {
    "mcp": "/mcp",
    "health": "/health", 
    "info": "/info"
  },
  "tools": ["weather", "brave_search_tool", "google_search_tool"]
}

日志记录

服务器提供全面的结构化日志记录:

  • 信息级别:一般操作信息
  • 调试级别:详细的执行跟踪
  • 错误级别:错误条件和异常
  • 工具执行:详细的工具调用记录

🚦 故障排除

常见问题

端口已在使用中

# Error: [Errno 10048] Only one usage of each socket address
# Solution: Change port in .env file
MCP_SERVER_PORT=8002

导入错误

# Error: ModuleNotFoundError
# Solution: Ensure virtual environment is activated
.\.venv\Scripts\Activate.ps1  # Windows
source .venv/bin/activate     # Linux/macOS

API关键问题

# Brave Search returns 422 error
# Solution: Add valid API key to .env file
BRAVE_API_KEY=your_actual_api_key_here

正在检查服务器状态

# Check if server is running  
curl -f http://localhost:8001/health || echo "Server not responding"

# View detailed server logs
tail -f server.log  # If logging to file

# Test MCP protocol
python test_mcp_client.py

📚 API文档

交互式文档

  • Swagger用户界面: http://localhost:8001/docs
  • ReDoc: http://localhost:8001/redoc
  • OpenAPI规范: http://localhost:8001/openapi.json

MCP协议端点

方法端点描述
职位/mcp主MCP协议通信
得到/health服务器运行状况
得到/info服务器功能和信息

🤝 贡献

开发设置

  1. 分叉存储库
  2. 创建要素分支: git checkout -b feature/my-new-tool
  3. 按照现有代码样式进行更改
  4. 添加新功能的测试
  5. 提交拉取请求

代码的风格

  • 遵循PEP 8 Python风格指南
  • 对所有函数参数和返回值使用类型提示
  • 为所有函数添加全面的文档字符串
  • 包括正确的错误处理和日志记录

测试

# Run the test client
python test_mcp_client.py

# Test individual tools
python -m app.tools.weather
python -m app.tools.web_search

📄 许可证

该项目根据MIT许可证获得许可。请参阅 许可证 文件以获取详细信息。

🔗 资源

______________________________________________________________________

🎉 准备好扩展您的MCP服务器了吗? 该架构旨在易于扩展-添加新工具、集成API和构建强大的人工智能辅助工作流程!

🤖 适用于人工智能代理和自动化系统

项目概要

这是一个 生产就绪的MCP服务器 与:

  • 3个工作工具:天气(没有API密钥),勇敢的搜索,谷歌搜索
  • 完整的MCP协议:使用FastMCP完成实施
  • 测试客户端:包括Python和PowerShell客户端
  • Docker就绪:优化了带有健康检查的容器
  • 监控:内置健康和信息端点

理解的关键文件

  1. app/main.py -主要应用入口点
  2. test_mcp_client.py -MCP客户端工作示例
  3. app/config/config.py -配置管理
  4. requirements.txt -Python依赖关系
  5. **** -Docker部署

即时测试命令

# Start server
python run.py

# Test in another terminal
python test_mcp_client.py

# Expected: Weather data for San Francisco + tool discovery

要遵循的代码模式

  • 工具注册:使用 @mcp_server.tool() 装饰器
  • 异步函数:所有工具都是异步的,有适当的错误处理
  • 键入提示:完整键入参数和返回值
  • 日志记录:INFO/DEBUG级别的全面日志记录
  • 配置:环境变量 .env 支持

目录标签

目录标签

实时天气搜索PythonDockerFastAPIMCP协议本地部署网页搜索Docker部署

接入字段

传输方式(transport,传输协议)

stdio

鉴权方式(authType,认证方式)

api-key

运行时(runtime,运行环境)

Python

工具数量(toolCount,工具数)

5

资源数量(resourceCount,资源数)

0

提示词数量(promptCount,提示词数)

0

权限和风险

stdioapi-key部署方式未说明

接入前请确认传输方式、认证方式和部署位置,并根据实际工具能力限制访问范围。

安装前确认

不要直接授予不必要的文件、网络或账号权限;先核对安装命令和配置内容。

来源信息

继续浏览同类 MCP