Skip to content

在 Claude 调用中使用 MCP

在 LLM 调用中使用 MCP – 与 Claude 结合

Section titled “在 LLM 调用中使用 MCP – 与 Claude 结合”

大型语言模型(LLM),如 Anthropic 公司的 Claude,功能极其强大,但其知识通常仅限于训练数据,并且通常缺乏对实时信息或私有数据源的直接访问能力。它们本身也无法在外部系统中执行操作。模型上下文协议(Model Context Protocol, MCP)提供了一种标准化的方式,通过将 Claude 连接到外部数据和工具的世界,从而增强 Claude 的能力,使其响应更加准确、相关且可操作。

可以将 MCP 想象成一个通用适配器。Claude 可以(通过你的应用程序)与这个适配器“对话”,以获取最新信息或请求执行任务,而无需了解每个数据源或工具的详细底层细节。

通过 MCP 将 Claude 连接到外部数据

Section titled “通过 MCP 将 Claude 连接到外部数据”

MCP 允许你定义 MCP 服务器上的“资源”(resources)。这些资源可以是文件系统中的文档、数据库中的记录、公司内部 API 提供的信息,或天气更新等实时数据。当你的应用程序与 Claude 交互时,并且需要根据特定、当前或专有数据来构建其响应时,它可以查询一个 MCP 客户端。

流程很简单:你的应用程序在调用 Claude 之前,会判断是否需要上下文数据。它通过 MCP 客户端从 MCP 服务器请求这些数据。MCP 服务器会获取数据(例如,客户最新的支持工单详情)并以结构化格式返回。你的应用程序随后将这些数据整合到发送给 Claude 的提示(prompt)中,使 Claude 能够生成一个基于充分信息的响应。

  • 示例数据源:项目文档、用户资料、产品目录、知识库文章、实时新闻源。

除了获取数据之外,LLM 通常还需要执行动作。MCP 定义了 LLM 可以请求使用的“工具”(tools)。这些工具代表了发送电子邮件、预订会议、查询数据库甚至运行代码片段等能力。当 Claude 在其交互中判断需要执行某个动作时,你的应用程序可以将此意图转换为 MCP 工具执行请求。

例如,如果用户要求 Claude 总结一篇长文档并发送电子邮件,Claude 可能会首先处理该文档(通过 MCP 作为资源提供)。然后,它可能会指示需要使用“电子邮件”(email)工具。你的应用程序随后会使用 MCP 客户端在 MCP 服务器上调用“电子邮件”工具,并传递总结内容和收件人详情。MCP 服务器处理实际的电子邮件发送。工具执行的结果(例如,“电子邮件发送成功”)随后可以传回给 Claude,以向用户确认该操作。

  • 示例工具:发送通知、创建日历事件、执行数据库查询、与版本控制系统交互。

示例场景:MCP 与 Claude 的实际应用

Section titled “示例场景:MCP 与 Claude 的实际应用”

想象一个由 Claude 提供支持的复杂 AI 助手,旨在协助项目管理。以下是 MCP 将如何增强其能力:

  1. 用户请求:用户问道:“Claude,‘凤凰项目’有哪些待处理的任务?你能通知 Alex 关于关键任务吗?”

  2. 数据检索(MCP 资源):应用程序识别出需要项目数据。它使用 MCP 客户端从连接到项目管理系统的 MCP 服务器请求 ‘project_tasks’ 资源。示例 MCP 调用(概念性):mcp_client.get_resource(server_id='project_management_system', resource_path='/projects/Phoenix/tasks?status=pending')。

  3. Claude 的上下文提示:获取到的任务列表(例如,[{'id': 'task1', 'desc': 'Design UI', 'priority': 'high'}, {'id': 'task2', 'desc': 'Backend API', 'priority': 'critical'}])被格式化并包含在发送给 Claude 的提示中:“这是凤凰项目的待处理任务:[…任务列表…]。请识别关键任务并为 Alex 制定一个通知。”

  4. Claude 的处理与工具指示:Claude 处理信息并识别出 ‘task2’ 为关键任务。然后它会生成一个通知消息,并指示需要使用“send_notification”工具。这种指示可能是一个结构化输出,或者是你的应用程序设计用来理解的特定文本提示。

  5. 工具执行(MCP 工具):你的应用程序解析 Claude 的响应。然后它使用 MCP 客户端在与你的通信平台集成的 MCP 服务器上调用“send_notification”工具。示例 MCP 调用(概念性):mcp_client.execute_tool(server_id='communication_hub', tool_id='send_slack_dm', params={'user': 'Alex', 'message': 'Critical task update for Project Phoenix: Backend API needs attention.'})。

  6. 结果与最终响应:MCP 服务器执行工具,并且结果(例如,{'status': 'success', 'message_id': 'slack123'})被返回给应用程序。这个结果可以反馈给 Claude,Claude 随后向用户生成最终响应:“我已找到待处理的任务。关键任务‘后端 API’已识别,我已向 Alex 发送了通知。”

# 应用程序逻辑的 Python 概念性示例
# mcp_client 和 claude_client 假设已初始化
# --- 阶段 1:使用 MCP 为 Claude 获取数据 ---
def get_project_tasks_for_claude(project_name):
try:
tasks = mcp_client.get_resource(
server_id='project_management_system',
resource_path=f'/projects/{project_name}/tasks?status=pending'
)
return f"Here are the pending tasks for {project_name}: {tasks}"
except MCPError as e:
print(f"MCP Error fetching tasks: {e}")
return f"Sorry, I couldn't retrieve tasks for {project_name}."
user_query = "What are the pending tasks for the 'Phoenix Project' and can you notify Alex about the critical ones?"
project_name = "Phoenix Project" # 从 user_query 中提取
context_from_mcp = get_project_tasks_for_claude(project_name)
# claude_response_object = claude_client.complete(
# prompt=f"{context_from_mcp}\n\nUser instruction: {user_query}. Please identify critical tasks and formulate a notification for Alex. If a notification is needed, please indicate to use 'send_notification_tool' with parameters 'user' and 'message'."
# )
# claude_text_response = claude_response_object.completion
# tool_call_request = parse_claude_for_tool_call(claude_text_response) # 假设的解析函数
# --- 阶段 2:Claude 指示工具使用,并通过 MCP 执行 ---
# 假设 claude_response 导致此(应用程序逻辑):
tool_call_request = {
'tool_name': 'send_notification_tool',
'params': {'user': 'Alex', 'message': 'Critical task update for Project Phoenix: Backend API needs attention.'}
}
if tool_call_request and tool_call_request['tool_name'] == 'send_notification_tool':
try:
tool_result = mcp_client.execute_tool(
server_id='communication_hub',
tool_id='send_slack_dm', # 此 ID 由 MCP 服务器定义
params=tool_call_request['params']
)
print(f"Tool execution result: {tool_result}")
# final_prompt_to_claude = f"Notification sent to {tool_call_request['params']['user']} with result: {tool_result}. Please confirm to the user."
# final_user_response = claude_client.complete(prompt=final_prompt_to_claude).completion
# print(final_user_response)
except MCPError as e:
print(f"MCP Tool Error: {e}")
# 通知 Claude 或用户工具执行失败

这个场景展示了 MCP 如何作为一个重要的中间层,允许 Claude 以结构化和安全的方式与外部系统交互,显著扩展了其效用。