MCP学习项目2025🚀
演示构建和部署的实践项目 模型上下文协议(MCP) 服务器。学习如何创建自定义MCP工具,为AI助手配置它们,并将其与Claude Desktop、Continue和其他兼容MCP的应用程序集成。
🎯 你将学到什么
- 🛠️ 从头开始构建自定义MCP服务器
- 🔌 将MCP工具与AI助手集成
- 🧪 使用MCP Inspector和MCP Studio进行测试和调试
- 📦 使用UV或pip管理依赖关系
- 🚀 部署生产就绪的MCP服务器
- 🎨 使用Pydantic创建类型安全工具
- 🌐 在高级场景中使用流式HTTP传输
🏗️ 技术栈
| 类别 | 技术 | 目的 |
|---|---|---|
| 语言 | Python 3.13+ | 核心编程语言 |
| 协议 | MCP(模型上下文协议) | 标准化AI工具通信 |
| 框架 | FastMCP | 快速MCP服务器开发 |
| 包管理器 | UV或pip+venv | 依赖关系管理 |
| 验证 | Pydantic | 数据验证和类型安全 |
| 服务器 | Uvicorn | MCP的ASGI服务器 |
| 测试 | MCP Inspector和MCP Studio | 交互式测试和调试 |
📋 先决条件
在潜水之前,请确保您有:
- ✅ Python 3.13+ 安装在您的系统上
- ✅ 紫外线 (推荐)或 pip+venv 用于包管理
- ✅ VS代码 (可选,但建议用于MCP配置)
- ✅ Git 用于版本控制
- ✅ 终端 访问权限(PowerShell、CMD或Bash)
🚀 安装
Using UV (Recommended) Using pip + venv
1.安装UV:
# Windows (PowerShell)
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"2.初始化项目:
# Create new project
uv init learn-mcp-2025
cd learn-mcp-2025
# Or in existing directory
uv init3.添加MCP依赖关系:
# Add MCP with CLI tools
uv add "mcp[cli]"
# This creates/updates:
# - pyproject.toml
# - uv.lock4.安装所有依赖项:
uv sync1.导航到项目:
cd learn-mcp-20252.创建虚拟环境:
python -m venv .venv3.激活虚拟环境:
# Windows (PowerShell)
.venv\Scripts\Activate.ps1
# Windows (CMD)
.venv\Scripts\activate.bat4.安装依赖项:
# From requirements.txt
pip install -r requirements.txt
# Or install package in editable mode
pip install -e .生成的文件
| 紫外线 | 点+静脉 |
|---|---|
pyproject.toml -项目元数据和依赖关系 | requirements.txt -固定依赖关系 |
uv.lock -锁定的依赖关系版本 | .venv/ -虚拟环境目录 |
⚙️ MCP服务器配置
要将MCP服务器与AI客户端(如Claude Desktop)集成,请创建一个配置文件:
创建 .vscode/mcp.json
{
"servers": {
"weather-service": {
"command": "python",
"args": ["weather.py"],
"env": {}
}
}
}多服务器配置
{
"servers": {
"weather-service": {
"command": "python",
"args": ["weather.py"],
"env": {}
},
"winget-mcp": {
"type": "stdio",
"command": "C:\\Users\\YourUser\\AppData\\Local\\Microsoft\\WindowsApps\\...\\WindowsPackageManagerMCPServer.exe"
}
}
}配置选项
| 字段 | 描述 | 示例 |
|---|---|---|
command | 可执行文件运行 | python, node, uv |
args | 传递给命令的参数 | ["weather.py"], ["run", "server.py"] |
env | 环境变量 | {"API_KEY": "value"} |
type | 通信类型 | stdio (默认) |
🎮 运行MCP服务器
方法1:快速测试⚡ (直接函数调用)
在不启动整个MCP服务器的情况下测试单个功能:
Using UV Using pip + venv
uv run python -c "from weather import get_weather; print(get_weather('London'))"输出:
The current weather in London is sunny with a temperature of 25°C.# Activate venv first
.venv\Scripts\Activate.ps1
# Then run
python -c "from weather import get_weather; print(get_weather('London'))"输出:
The current weather in London is sunny with a temperature of 25°C.何时使用:
- ✅ 开发过程中的快速迭代
- ✅ 单个工具的单元测试
- ✅ 调试功能逻辑
- ❌ 不适用于MCP客户端
方法2:生产模式🚀 (完整MCP服务器)
作为完整的MCP服务器运行,用于AI助手集成:
Using UV Using pip + venv
# Start MCP server
uv run python weather.py
# The server will start and listen for MCP requests# Activate venv first
.venv\Scripts\Activate.ps1
# Start MCP server
python weather.py何时使用:
- ✅ 与人工智能助手集成(Claude、Continue等)
- ✅ 生产部署
- ✅ 多工具服务器
- ✅ 标准化MCP协议通信
方法3:MCP检查员🔍 (开发与调试)
使用MCP检查器通过web UI交互式测试您的服务器:
Using Python MCP CLI Using Node.js npx (Recommended)
使用紫外线:
# Start MCP dev mode
uv run mcp dev 使用pip+venv:
# Activate venv first
.venv\Scripts\Activate.ps1
# Start MCP dev mode
mcp dev 特征:
- 基于终端的调试
- 控制台中的日志输出
- 快速服务器验证
- ❌ 无web用户界面
使用紫外线:
# No installation needed - npx downloads temporarily
npx @modelcontextprotocol/inspector uv run 使用pip+venv:
# Activate venv first
.venv\Scripts\Activate.ps1
# Run inspector with Python
npx @modelcontextprotocol/inspector python 特征:
- ✅ 交互式web UI
- ✅ 可视化工具资源管理器
- ✅ 请求/响应检查
- ✅ 实时测试
- ✅ 始终为最新版本
MCP检查器功能:
- 🔍 浏览器中的交互式工具测试
- 📊 请求/响应检查
- 🐛 实时调试
- 📝 架构验证
- 🎨 所有MCP工具的可视化界面
访问检查器:
Open browser: http://localhost:5173weather.py示例:
$ npx @modelcontextprotocol/inspector uv run weather.py
MCP Inspector running at http://localhost:5173
Server: Weather Service
Tools available: get_weather方法4:Python客户端🐍 (程序化访问)
使用Python代码以编程方式连接到MCP服务器:
示例1:连接到天气服务(Python服务器)
# Run the weather client
python client.py示例2:连接到Airbnb服务(Node.js服务器)
# Run the Airbnb client (connects to Node.js server via npx)
python client_airbnb.py客户端功能:
- 📡 程序化MCP服务器连接
- 🔄 异步/等待通信模式
- 🌐 跨语言支持(Python↔ Node.js)
- 🛠️ 从代码直接调用工具
- 📋 动态工具发现
list_tools()
何时使用:
- ✅ 构建MCP供电的应用程序
- ✅ 自动化脚本中的工具调用
- ✅ 测试服务器集成
- ✅ 创建自定义MCP工作流
- ✅ 连接到第三方MCP服务器
方法5:MCP工作室🛠️ (高级测试和流式传输)
MCP Studio提供高级调试功能,尤其适用于流式HTTP传输和复杂的服务器集成。
设置MCP工作室
1.安装MCP Studio:
npm install -g @modelcontextprotocol/studio2.在中配置远程服务器 .vscode/mcp.json:
{
"servers": {
"remote-example": {
"command": "npx",
"args": ["mcp-remote", "http://127.0.0.1:8000"]
}
}
}3.运行流媒体服务器:
# Start the streamable server on HTTP transport
uv run python sample_mcp_streamable_server.py
# Server runs on http://127.0.0.1:8000 (or configured port)4.连接MCP工作室:
# Launch MCP Studio and connect to remote server
mcp-studio --remote http://127.0.0.1:8000MCP工作室优势:
- 可视化调试:用于工具调用和响应的交互式UI
- 可简化的运输支持:处理可流式传输服务器的HTTP/SSE连接
- 实时监控:实时日志和错误跟踪
- 多服务器测试:同时测试多个服务器
- 集成测试:模拟AI助手交互
何时使用MCP Studio:
- ✅ 测试可流式传输的HTTP服务器
- ✅ 复杂的多工具集成
- ✅ 类似生产的测试场景
- ✅ 调试连接问题
📁 项目结构
learn-mcp-2025/
├── .github/
│ ├── copilot-instructions.md # AI agent development guidelines
│ └── prompts/ # Reusable prompt templates
├── .vscode/
│ └── mcp.json # MCP server configuration for VS Code/AI assistants
├── .venv/ # Virtual environment (pip only)
│
├── MCP Servers (Tools for AI Assistants)
├── weather__mcp_server.py # 🔧 Weather service tools
├── crypto_mcp_server.py # 🔧 Cryptocurrency price tools
├── local_notes_mcp_server.py # 🔧 Local notes management (add/get)
├── screenshot_tool.py # 🔧 Screenshot capture tool
├── pydantic_schema_person_server.py # 🔧 Person data schema & processing
├── resources_mcp_server.py # 🔧 Resource management (coffee inventory)
├── websearch_mcp_server.py # 🔧 Web search functionality
├── sample_mcp_streamable_server.py # 🔧 Streamable HTTP transport example
│
├── MCP Clients (Test & Integration)
├── weather_mcp_client.py # 🔌 Client for weather server
├── airbnb_mcp_client.py # 🔌 Client for Airbnb server (Node.js)
├── resources_mcp_client.py # 🔌 Client for resources server
│
├── Configuration & Dependencies
├── pyproject.toml # Project metadata & dependencies (UV)
├── requirements.txt # Pinned dependencies (pip)
├── uv.lock # Locked dependency versions (UV)
├── .python-version # Python version specification
├── .gitignore # Git ignore rules
├── notes.txt # Data file for local_notes_mcp_server
├── log.txt # Log file for person data
└── README.md # This file关键文件说明
| 文件 | 类型 | 目的 |
|---|---|---|
weather__mcp_server.py | MCP服务器 | 使用模拟天气数据工具的天气服务 |
crypto_mcp_server.py | MCP服务器 | 加密货币价格查询工具 |
local_notes_mcp_server.py | MCP服务器 | 基于文件的笔记管理(添加/获取) |
screenshot_tool.py | MCP服务器 | 使用Pillow截取屏幕截图 |
pydantic_schema_person_server.py | MCP服务器 | 人员数据模式和处理与验证 |
resources_mcp_server.py | MCP服务器 | 资源管理(咖啡库存示例) |
websearch_mcp_server.py | MCP服务器 | 网络搜索功能 |
sample_mcp_streamable_server.py | MCP服务器 | 流式HTTP传输示例 |
weather_mcp_client.py | MCP客户端 | Python客户端连接到天气服务器 |
airbnb_mcp_client.py | MCP客户端 | Python客户端连接到Node.js Airbnb服务器 |
resources_mcp_client.py | MCP客户端 | 资源服务器的Python客户端 |
pyproject.toml | Config | 现代Python项目配置(PEP 621) |
requirements.txt | Config | 传统pip依赖列表(自动生成) |
uv.lock | Config | UV的确定性依赖锁定文件 |
.vscode/mcp.json | 配置 | VS Code/Claude Desktop的MCP服务器注册表 |
📚 快速命令参考
UV命令🔮
| 命令 | 描述 |
|---|---|
uv init | 初始化新的Python项目 |
| `uv add | |
| ` | 向项目添加依赖关系 |
| `uv remove | |
| ` | 删除依赖关系 |
uv sync | 安装/同步所有依赖项 |
uv run | 在项目环境中运行命令 |
uv pip list | 列出已安装的软件包 |
| `uv pip show | |
| ` | 显示包裹详细信息 |
uv lock | 更新锁文件 |
uv python install | 安装Python版本 |
uv python list | 列出可用的Python版本 |
pip+venv命令🐍
| 命令 | 描述 |
|---|---|
python -m venv .venv | 创建虚拟环境 |
.venv\Scripts\Activate.ps1 | 激活venv(PowerShell) |
.venv\Scripts\activate.bat | 激活venv(CMD) |
pip install -r requirements.txt | 安装依赖项 |
pip install -e . | 以可编辑模式安装软件包 |
| `pip install | |
| ` | 安装单个软件包 |
| `pip uninstall | |
| ` | 删除包 |
pip list | 列出已安装的软件包 |
| `pip show | |
| ` | 显示包裹详细信息 |
pip freeze > requirements.txt | 导出依赖关系 |
deactivate | 停用虚拟环境 |
MCP命令🔧
| 命令 | 描述 |
|---|---|
mcp dev | 启动MCP Inspector进行开发 |
mcp --version | 检查MCP CLI版本 |
python .py | 在生产环境中启动MCP服务器 |
npx @modelcontextprotocol/inspector uv run | 交互式MCP测试 |
mcp-studio --remote | 高级MCP Studio测试 |
💡 开发示例
示例1:添加新的天气工具🌤️
编辑 weather.py:
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather Service")
@mcp.tool()
def get_weather(location: str) -> str:
"""Get current weather for a location."""
return f"The current weather in {location} is sunny with a temperature of 25°C."
@mcp.tool()
def get_forecast(location: str, days: int = 7) -> str:
"""Get weather forecast for the next N days."""
return f"Forecast for {location} for the next {days} days: Mostly sunny"
@mcp.tool()
def get_temperature(location: str, unit: str = "celsius") -> str:
"""Get current temperature in specified unit."""
temp = 25 if unit == "celsius" else 77
return f"Temperature in {location}: {temp}°{unit[0].upper()}"
if __name__ == "__main__":
mcp.run()示例2:测试新工具✅
# Test with UV
uv run python -c "from weather import get_forecast; print(get_forecast('Paris', 5))"
# Test with pip/venv
python -c "from weather import get_forecast; print(get_forecast('Paris', 5))"示例3:添加类型安全🔒
from typing import Literal
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Weather Service")
@mcp.tool()
def get_temperature(
location: str,
unit: Literal["celsius", "fahrenheit"] = "celsius"
) -> str:
"""Get temperature with validated unit parameter."""
temp = 25 if unit == "celsius" else 77
return f"Temperature in {location}: {temp}°{unit[0].upper()}"示例4:构建Python MCP客户端🔌
# client.py
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
import asyncio
server_params = StdioServerParameters(
command="uv",
args=["run", "weather.py"]
)
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# Call a tool
result = await session.call_tool(
"get_weather",
arguments={"location": "Tokyo"}
)
print(result)
# List all available tools
tools = await session.list_tools()
print(f"Available tools: {tools}")
if __name__ == "__main__":
asyncio.run(main())示例5:跨语言MCP集成🌐
将Python客户端连接到Node.js MCP服务器:
# client_airbnb.py
server_params = StdioServerParameters(
command="npx",
args=["-y", "@openbnb/mcp-server-airbnb"]
)
async def main():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# Discover tools from Node.js server
tools = await session.list_tools()
print(f"Airbnb MCP Tools: {tools}")示例6:流式HTTP传输🌐
对于需要基于HTTP通信的高级场景:
# sample_mcp_streamable_server.py
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("Streamable MCP Server")
@mcp.tool()
def greet(name: str) -> str:
"""Greets the user with their name."""
return f"Hello, {name}! Hope you're having a great day! 😊"
if __name__ == "__main__":
# Use streamable HTTP transport for advanced scenarios
mcp.run(transport="streamable-http")测试可流式服务器:
# Start server
uv run python sample_mcp_streamable_server.py
# Test with MCP Studio (in another terminal)
mcp-studio --remote http://127.0.0.1:8000示例7:调试与验证🐛
# List all tools in your server
uv run python -c "from weather import mcp; print(mcp.list_tools())"
# Check Python version
uv run python --version
# Verify MCP package
uv pip show mcp
# Test imports
uv run python -c "from weather import mcp; print('MCP initialized successfully')"
# Run client tests
python client.py
python client_airbnb.py🤝 贡献
这是一个学习项目!请随意:
- 🐛 报告错误或问题
- 💡 建议新的MCP工具
- 📝 改进文档
- 🔀 提交拉取请求
📄 许可证
这个项目是为了学习。
______________________________________________________________________
内置于❤️ 学习MCP
⭐ 如果你觉得这个repo有用,请将其标记为星号!
