MCP实战案例
本文档提供了多个完整的MCP实战案例,帮助您从零开始构建MCP应用。
案例1:智能文档分析系统
项目概述
构建一个基于MCP协议的智能文档分析系统,能够自动提取文档关键信息、生成摘要、回答文档相关问题。
技术栈
- MCP服务器:Python + FastAPI
- MCP客户端:Claude Desktop / ChatGPT
- 文档处理:PyPDF2, python-docx
- 向量数据库:ChromaDB
- LLM:OpenAI GPT-4 / Claude
实施步骤
步骤1:环境准备
# 创建项目目录
mkdir mcp-document-analyzer
cd mcp-document-analyzer
# 创建虚拟环境
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
# 安装依赖
pip install mcp fastapi uvicorn pypdf2 python-docx chromadb openai
步骤2:创建MCP服务器
创建 server.py:
from mcp import Server, types
from mcp.server import serve
import asyncio
from pathlib import Path
import PyPDF2
from docx import Document
import chromadb
from chromadb.config import Settings
# 初始化向量数据库
client = chromadb.Client(Settings(
chroma_db_impl="duckdb+parquet",
persist_directory="./chroma_db"
))
collection = client.get_or_create_collection(name="documents")
app = Server("document-analyzer")
@app.list_tools()
async def list_tools() -> list[types.Tool]:
return [
types.Tool(
name="analyze_document",
description="分析文档并提取关键信息",
inputSchema={
"type": "object",
"properties": {
"file_path": {
"type": "string",
"description": "文档文件路径"
}
},
"required": ["file_path"]
}
),
types.Tool(
name="query_document",
description="基于文档内容回答问题",
inputSchema={
"type": "object",
"properties": {
"question": {
"type": "string",
"description": "要回答 的问题"
}
},
"required": ["question"]
}
),
]
@app.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
if name == "analyze_document":
file_path = arguments.get("file_path")
# 实现文档分析逻辑
result = analyze_document(file_path)
return [types.TextContent(type="text", text=result)]
elif name == "query_document":
question = arguments.get("question")
# 实现文档查询逻辑
result = query_document(question)
return [types.TextContent(type="text", text=result)]
def analyze_document(file_path: str) -> str:
"""分析文档并提取信息"""
path = Path(file_path)
text = ""
if path.suffix == ".pdf":
with open(path, "rb") as f:
reader = PyPDF2.PdfReader(f)
text = "\n".join([page.extract_text() for page in reader.pages])
elif path.suffix == ".docx":
doc = Document(path)
text = "\n".join([para.text for para in doc.paragraphs])
# 存储到向量数据库
collection.add(
documents=[text],
ids=[str(path)]
)
return f"文档已分析并存储。共提取 {len(text)} 个字符。"
def query_document(question: str) -> str:
"""基于文档内容回答问题"""
results = collection.query(
query_texts=[question],
n_results=3
)
context = "\n".join(results['documents'][0])
# 使用LLM生成答案
# answer = llm.generate(context, question)
return f"基于文档内容:{context[:200]}..."
if __name__ == "__main__":
asyncio.run(serve(app))
步骤3:配置MCP客户端
在Claude Desktop的配置文件中添加:
{
"mcpServers": {
"document-analyzer": {
"command": "python",
"args": ["/path/to/server.py"]
}
}
}
步骤4:测试使用
- 启动MCP服务器
- 在Claude Desktop中,使用工具:
- "分析这个文档:/path/to/document.pdf"
- "文档中提到了什么关键信息?"
项目亮点
- ✅ 支持多种文档格式(PDF、DOCX)
- ✅ 自动提取和存储文档内容
- ✅ 基于向量数据库的智能检索
- ✅ 与LLM无缝集成
案例2:实时数据可视化助手
项目概述
创建一个MCP服务器,能够连接各种数据源(数据库、API),实时获取数据并生成可视化图表。
技术栈
- MCP服务器:Node.js + Express
- 数据源:MySQL, REST API
- 可视化:Chart.js
- MCP客户端:Claude Desktop