🛠️ 用Python构建增强型MCP服务器
______________________________________________________________________
📌 项目概述
该项目构建了一个 增强型生产级MCP服务器 具有基本工具调用之外的高级功能,包括 实时进度报告, 上下文感知日志记录, 基于启发的用户输入,以及 Claude Sonnet集成 通过Anthropic API。
它演示了如何构建可以交互的MCP服务器 使用Claude智能地安全地处理文件操作, 并通过启发工作流收集结构化用户输入。
域名: Agent AI——增强型MCP服务器开发\ 语言: Python 3.11\ LLM 克劳德·十四行诗4.5(claude-sonnet-4-5-20250929)\ 运输: 工作室
______________________________________________________________________
🏗️ 建筑
┌──────────────────────────────────────────────────┐
│ MCP Client (client.py) │
│ │
│ MCPClient Class │
│ ├── Anthropic Claude Sonnet 4.5 integration │
│ ├── elicitation_handler → user input dialogs │
│ ├── progress_handler → real-time progress │
│ ├── Tool execution via FastMCP Client │
│ └── Interactive chat loop with Claude │
└─────────────────────┬────────────────────────────┘
│ STDIO Transport
┌─────────────────────▼────────────────────────────┐
│ Enhanced MCP Server (server.py) │
│ │
│ 🔧 Tools (with Context + Progress) │
│ ├── write_file(path, content, ctx) │
│ │ → Chunked writing + progress reporting │
│ └── delete_file(path, ctx) │
│ → Validated deletion with warnings │
│ │
│ 📦 Resources │
│ ├── file:///{file_name} → Read any file │
│ └── dir://. → List directory │
│ │
│ 💬 Prompts (with Elicitation) │
│ ├── code_review(file_path, ctx) │
│ │ → Reads file → generates review prompt │
│ └── documentation_generator(ctx) │
│ → Elicits user input → generates doc prompt │
│ │
│ 🛡️ Security: get_path() — BASE_DIR validation │
└──────────────────────────────────────────────────┘______________________________________________________________________
📂 项目结构
Build-an-Enhanced-MCP-Server/
│
├── server.py # Enhanced FastMCP server
├── client.py # Claude-integrated MCP client
├── requirements.txt # Dependencies
├── .gitignore
└── README.md______________________________________________________________________
🛠️ 技术栈
| 组件 | 技术 | 版本 |
|---|---|---|
| MCP框架 | FastMCP | 2.12.4 |
| MCP协议 | 模型上下文协议 | 1.15.0 |
| 语言 | Python | 3.11+ |
| LLM | 克劳德·十四行诗4.5 | 人择0.69.0 |
| 配置 | python dotenv | 1.1.1 |
| 数据验证 | Pydantic基础模型 | 内置 |
| 传输 | STDIO | stdin/stdout |
______________________________________________________________________
🌟 增强功能(与基本MCP服务器相比)
✅ 1.实时进度报告
工具在长时间操作期间报告实时进度:
await ctx.report_progress(
progress=written,
total=total,
message=f"Writing progress: {written}/{total}"
)✅ 2.上下文感知日志记录
每个操作都以适当的级别记录:
await ctx.info("File written successfully")
await ctx.warning("File not found: path")
await ctx.error("Error creating file: msg")✅ 3.启发式——结构化用户输入
服务器通过Pydantic模式请求结构化用户输入:
class DocumentGeneratorSchema(BaseModel):
file_path: str # File to document
name: str # Output documentation filename
result = await ctx.elicit(
message="Please provide the subject file name and documentation file name",
response_type=DocumentGeneratorSchema
)✅ 4.克劳德十四行诗4.5集成
客户通过MCP工具直接使用Anthropic API:
MODEL_ID = "claude-sonnet-4-5-20250929"
self.anthropic = Anthropic()✅ 5.路径安全(get_Path)
根据BASE_DIR验证的所有文件操作:
def get_path(relative_path: str) -> Path:
rel = Path(relative_path).resolve().relative_to(BASE_DIR)
return rel # Raises ValueError if outside BASE_DIR______________________________________________________________________
🔧 服务器功能
工具
| 工具 | 参数 | 增强功能 |
|---|---|---|
write_file | file_path, content, ctx | 分块写作+进度报告 |
delete_file | file_path, ctx | 验证文件与目录+警告 |
资源
| URI | 描述 |
|---|---|
file:///{file_name} | 读取任何文件--返回内容或错误字典 |
dir://. | 列表目录--返回名称、路径、类型、大小、时间戳 |
提示
| 提示 | 参数 | 特殊功能 |
|---|---|---|
code_review | file_path, ctx | 读取文件+从扩展名检测语言 |
documentation_generator | ctx | 从用户那里获取文件路径+文档名称 |
______________________________________________________________________
⚙️ 如何跑步
步骤1——安装依赖项:
pip install -r requirements.txt步骤2——设置环境变量:
# Create .env file
echo "ANTHROPIC_API_KEY=your-api-key-here" > .env步骤3——运行客户端(自动连接到服务器):
python client.py server.py______________________________________________________________________
🔄 激发工作流程
User asks: "Generate documentation for server.py"
│
▼
Claude calls: documentation_generator prompt
│
▼
Server triggers ctx.elicit():
"Please provide subject file and documentation file name"
│
▼
Client elicitation_handler shows dialog to user
User inputs: {file_path: "server.py", name: "server_docs"}
│
▼
Server reads server.py → builds documentation prompt
│
▼
Claude receives prompt → calls write_file tool
│
▼
Server writes server_docs.md with progress reporting
│
▼
Documentation file created! ✅______________________________________________________________________
🎓 技能展示
- 具有Context(ctx)集成的增强型MCP服务器
- 通过以下方式实时报告进度
ctx.report_progress() - 多级上下文日志记录——信息、警告、错误
- 基于Pydantic的启发式模式设计
- 循环中的用户结构化输入集合
- Claude Sonnet 4.5通过Anthropic API集成
- 带有启发和进度处理程序的MCP客户端
- 带有自定义事件处理程序的FastMCP客户端
- 使用BASE_DIR边界进行安全路径验证
- 使用分块写入的异步文件操作
- 包含完整文件元数据的目录列表
- 从文件扩展名检测语言
- 从文件内容动态生成提示
______________________________________________________________________
📜 认证
| 认证 | 发卡机构 | 平台 |
|---|---|---|
| IBM数据科学专业证书 | IBM | Coursera |
| IBM生成人工智能专业证书 | IBM | Coursera |
| IBM RAG和代理人工智能专业证书 | IBM | Coursera |
______________________________________________________________________
🤝 与我联系
  ](https://github.com/Leelaissakattaota)
