文档API 参考📓 教程🧑‍🍳 食谱🤝 集成💜 Discord🎨 Studio
文档

MCPTool

MCPTool 允许通过模型上下文协议 (MCP) 与外部工具和服务集成。

必需的初始化变量"name": 工具的名称
"server_info": 要连接的 MCP 服务器的信息
API 参考Tools (工具)
GitHub 链接https://github.com/deepset-ai/haystack-core-integrations/tree/main/integrations/mcp

概述

MCPTool 是一个工具,它允许 Haystack 使用 模型上下文协议 (MCP) 与外部工具和服务进行通信。MCP 是一项开放协议,它标准化了应用程序如何为 LLM 提供上下文,类似于 USB-C 为连接设备提供标准化方式。

MCPTool 支持多种传输选项

  • Streamable HTTP 用于连接到 HTTP 服务器,
  • SSE (Server-Sent Events) 用于连接到 HTTP 服务器 (已弃用)
  • StdIO 用于直接执行本地程序。

官方 MCP 网站 上详细了解 MCP 协议及其架构。

参数

  • name必需的,指定工具的名称。
  • server_info必需的,并且需要是一个SSEServerInfo , StreamableHttpServerInfoStdioServerInfo 对象,其中包含连接信息。
  • description可选的,并为 LLM 提供有关工具功能的上下文。

结果

该工具以 JSON 对象列表的形式返回结果,代表TextContent, ImageContent,或EmbeddedResource 来自 mcp-sdk 的类型。

用法

安装 MCP-Haystack 集成以使用MCPTool:

pip install mcp-haystack

使用 Streamable HTTP 传输

您可以创建一个MCPTool,它使用 streamable-http 传输连接到外部 HTTP 服务器

from haystack_integrations.tools.mcp import MCPTool, StreamableHttpServerInfo

# Create an MCP tool that connects to an HTTP server
server_info = StreamableHttpServerInfo(url="https://:8000/mcp")
tool = MCPTool(name="my_tool", server_info=server_info)

# Use the tool
result = tool.invoke(param1="value1", param2="value2")

使用 SSE 传输 (已弃用)

您可以创建一个MCPTool,它使用 SSE 传输连接到外部 HTTP 服务器

from haystack_integrations.tools.mcp import MCPTool, SSEServerInfo

# Create an MCP tool that connects to an HTTP server
server_info = SSEServerInfo(url="https://:8000/sse")
tool = MCPTool(name="my_tool", server_info=server_info)

# Use the tool
result = tool.invoke(param1="value1", param2="value2")

使用 StdIO 传输

您还可以创建一个MCPTool,它直接执行本地程序并通过 stdio 传输进行连接

from haystack_integrations.tools.mcp import MCPTool, StdioServerInfo

# Create an MCP tool that uses stdio transport
server_info = StdioServerInfo(command="uvx", args=["mcp-server-time", "--local-timezone=Europe/Berlin"])
tool = MCPTool(name="get_current_time", server_info=server_info)

# Get the current time in New York
result = tool.invoke(timezone="America/New_York")

在 pipeline 中

您可以将一个MCPTool 集成到具有ChatGenerator 的管道中,以及一个ToolInvoker:

from haystack import Pipeline
from haystack.components.converters import OutputAdapter
from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.components.tools import ToolInvoker
from haystack.dataclasses import ChatMessage

from haystack_integrations.tools.mcp import MCPTool, StdioServerInfo


time_tool = MCPTool(
    name="get_current_time",
    server_info=StdioServerInfo(command="uvx", args=["mcp-server-time", "--local-timezone=Europe/Berlin"]),
)
pipeline = Pipeline()
pipeline.add_component("llm", OpenAIChatGenerator(model="gpt-4o-mini", tools=[time_tool]))
pipeline.add_component("tool_invoker", ToolInvoker(tools=[time_tool]))
pipeline.add_component(
    "adapter",
    OutputAdapter(
        template="{{ initial_msg + initial_tool_messages + tool_messages }}",
        output_type=list[ChatMessage],
        unsafe=True,
    ),
)
pipeline.add_component("response_llm", OpenAIChatGenerator(model="gpt-4o-mini"))
pipeline.connect("llm.replies", "tool_invoker.messages")
pipeline.connect("llm.replies", "adapter.initial_tool_messages")
pipeline.connect("tool_invoker.tool_messages", "adapter.tool_messages")
pipeline.connect("adapter.output", "response_llm.messages")

user_input = "What is the time in New York? Be brief."  # can be any city
user_input_msg = ChatMessage.from_user(text=user_input)

result = pipeline.run({"llm": {"messages": [user_input_msg]}, "adapter": {"initial_msg": [user_input_msg]}})

print(result["response_llm"]["replies"][0].text)
# The current time in New York is 1:57 PM.

与 Agent 组件集成

您可以使用MCPToolAgent 组件。在内部,Agent 组件包含一个ToolInvoker 和您选择的 ChatGenerator 来执行工具调用并处理工具结果。

from haystack.components.generators.chat import OpenAIChatGenerator
from haystack.dataclasses import ChatMessage
from haystack.components.agents import Agent

from haystack_integrations.tools.mcp import MCPTool, StdioServerInfo


time_tool = MCPTool(
    name="get_current_time",
    server_info=StdioServerInfo(command="uvx", args=["mcp-server-time", "--local-timezone=Europe/Berlin"]),
)

# Agent Setup
agent = Agent(
    chat_generator=OpenAIChatGenerator(),
    tools=[time_tool],
    exit_conditions=["text"]
)

# Run the Agent
agent.warm_up()
response = agent.run(messages=[ChatMessage.from_user("What is the time in New York? Be brief.")])

# Output
print(response["messages"][-1].text)