🛠️ 用Python构建自定义MCP客户端
______________________________________________________________________
📌 项目概述
该项目演示了如何构建 最小,功能齐全 从头开始模型上下文协议(MCP)客户端 使用Python。
它提供了MCP核心通信的实践实施 模式——通过以下方式连接到MCP服务器 STDIO传输 和 与所有三个MCP原语交互: 工具、资源、, 和提示 --通过干净的命令行界面。
域名: 代理AI——MCP客户端开发\ 语言: Python 3.11\ 运输: STDIO(标准输入/输出)\ 接口: 交互式CLI
______________________________________________________________________
🏗️ 建筑
┌─────────────────────────────────────────────┐
│ Host Process │
│ Orchestrates client & manages security │
└──────────────────┬──────────────────────────┘
│
┌──────────────────▼──────────────────────────┐
│ MCP Client (mcp_client.py) │
│ │
│ MCPClient Class │
│ ├── connect() → Initialize session │
│ ├── list_tools() → Discover tools │
│ ├── call_tool() → Execute tools │
│ ├── list_resources() → Discover resources │
│ ├── read_resource() → Read by URI │
│ ├── list_prompts() → Discover prompts │
│ └── get_prompt() → Render template │
│ │
│ CLI Commands: tools | call | resources │
│ read | prompts | prompt | quit│
└──────────────────┬──────────────────────────┘
│ STDIO Transport
┌──────────────────▼──────────────────────────┐
│ MCP Server (mcp_server.py) │
│ │
│ 🔧 Tools │
│ ├── echo(text) → Echo input text │
│ └── write_file(path, content) → Save file │
│ │
│ 📦 Resources │
│ └── file://resources/{filename} │
│ │
│ 💬 Prompts │
│ └── review_file(filename) │
└─────────────────────────────────────────────┘______________________________________________________________________
📂 项目结构
mcp-client-lab/
│
├── mcp_client.py # Full MCP client with CLI interface
├── mcp_server.py # FastMCP server — tools, resources, prompts
│
├── resources/ # Resource files accessible via MCP
│ ├── test.txt # Sample test file
│ ├── notes.txt # Lab notes on MCP concepts
│ └── project_info.txt # Project metadata
│
└── README.md______________________________________________________________________
🛠️ 技术栈
| 组件 | 技术 |
|---|---|
| 语言 | Python 3.11 |
| MCP协议 | 模型上下文协议1.16.0 |
| MCP框架 | FastMCP |
| 传输 | stdio(stdioserver参数) |
| 会话 | 客户端会话(JSON-RPC 2.0) |
| async | 异步+异步堆栈 |
| 界面 | 交互式CLI |
______________________________________________________________________
🔧 MCP服务器功能
工具(共2个)
| 工具 | 参数 | 描述 |
|---|---|---|
echo | text: str | 回显输入文本 |
write_file | path: str, content: str | 将内容写入文件 |
资源
| URI模板 | 描述 |
|---|---|
file://resources/{filename} | 从资源目录读取任何文件 |
提示
| 提示 | 参数 | 描述 |
|---|---|---|
review_file | filename: str | 生成文件审查提示 |
______________________________________________________________________
🚀 MCP客户端-CLI命令
=== MCP Client ===
Commands: tools | call | resources | read | prompts | prompt | help | quit
> tools # List all available tools with descriptions
> call # Invoke a tool with JSON arguments
> resources # List all resource URI templates
> read # Read a resource by URI
> prompts # List all prompt templates
> prompt # Get a rendered prompt
> help # Show all commands
> quit # Exit client______________________________________________________________________
⚙️ 如何跑步
步骤1——创建虚拟环境:
python3.11 -m venv mcp_client_env
source mcp_client_env/bin/activate # Linux/Mac
mcp_client_env\Scripts\activate # Windows步骤2——安装依赖项:
pip install mcp==1.16.0 fastmcp步骤3——启动客户端(自动连接到服务器):
python mcp_client.py mcp_server.py步骤4--尝试以下命令:
> tools
• echo: Echo back the input text
• write_file: Write content to a file
> call
Tool name: echo
Arguments: {"text": "Hello MCP!"}
Result: Echo: Hello MCP!
> resources
• file://resources/{filename}
> read
URI: file://resources/notes.txt
Lab Notes
- MCP uses JSON-RPC 2.0
...______________________________________________________________________
🔄 MCP生命周期实施
该项目严格遵循 三个强制性MCP阶段:
Phase 1 — INITIALIZATION
client.connect(server_script)
→ stdio_client() establishes STDIO transport
→ ClientSession created
→ session.initialize() completes handshake
Phase 2 — OPERATION
→ list_tools() / call_tool()
→ list_resources() / read_resource()
→ list_prompts() / get_prompt()
Phase 3 — SHUTDOWN
→ client.cleanup()
→ exit_stack.aclose()
→ All connections gracefully closed______________________________________________________________________
📝 关键概念演示
| 概念 | 实施 |
|---|---|
| STDIO传输 | StdioServerParameters + stdio_client() |
| 会话管理 | ClientSession 随着 AsyncExitStack |
| 工具发现 | session.list_tools() |
| 工具调用 | session.call_tool(name, args) |
| 资源模板 | URI模式 file://resources/{filename} |
| 资源阅读 | session.read_resource(uri) |
| 快速发现 | session.list_prompts() |
| 快速渲染 | session.get_prompt(name, args) |
| JSON-RPC 2.0 | 由ClientSession内部处理 |
______________________________________________________________________
🎓 技能展示
- 从头开始实现模型上下文协议(MCP)客户端
- STDIO传输通信模式
- MCP会话生命周期管理(Init→ 操作→ 关机)
- 通过JSON-RPC 2.0发现和调用工具
- 资源模板URI模式处理
- 快速发现和呈现模板
- 异步Python——异步、异步堆栈
- 交互式CLI应用程序开发
- 带工具、资源和提示的FastMCP服务器
- MCP协议操作的错误处理
______________________________________________________________________
📜 认证
| 认证 | 发卡机构 | 平台 |
|---|---|---|
| IBM数据科学专业证书 | IBM | Coursera |
| IBM生成人工智能专业证书 | IBM | Coursera |
| IBM代理人工智能与RAG证书 | IBM | Coursera |
| IBM RAG和代理人工智能专业证书 | IBM | Coursera |
______________________________________________________________________
🤝 与我联系
  ](https://github.com/Leelaissakattaota)
