Skip to content
CrewAI 文档版本 跟随上游 源快照 399e3512 更新于 2026-10-18

Streamable HTTP 传输

了解如何使用灵活的 Streamable HTTP 传输将 CrewAI 连接到远程 MCP 服务器。

概述

Streamable HTTP 传输提供了一种灵活的方式来连接远程 MCP 服务器。它通常构建于 HTTP 之上,可以支持各种通信模式,包括请求-响应和流式传输;有时会在更广泛的 HTTP 交互中利用 Server-Sent Events (SSE) 实现服务器到客户端的流。

关键概念

  • 远程服务器:专为远程托管的 MCP 服务器设计。
  • 灵活性:相比普通 SSE,可支持更复杂的交互模式,如果服务器实现了双向通信,还可能包含这种通信方式。
  • MCPServerAdapter 配置:你需要提供用于 MCP 通信的服务器基础 URL,并指定 "streamable-http" 作为传输类型。

通过 Streamable HTTP 连接

你可以使用两种主要方法来管理与 Streamable HTTP MCP 服务器的连接生命周期:

1. 完全托管的连接(推荐)

推荐方法是使用 Python 上下文管理器(with 语句),它会自动处理连接的建立和拆除。

python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter

server_params = {
    "url": "http://localhost:8001/mcp", # Replace with your actual Streamable HTTP server URL
    "transport": "streamable-http"
}

try:
    with MCPServerAdapter(server_params) as tools:
        print(f"Available tools from Streamable HTTP MCP server: {[tool.name for tool in tools]}")

        http_agent = Agent(
            role="HTTP Service Integrator",
            goal="Utilize tools from a remote MCP server via Streamable HTTP.",
            backstory="An AI agent adept at interacting with complex web services.",
            tools=tools,
            verbose=True,
        )

        http_task = Task(
            description="Perform a complex data query using a tool from the Streamable HTTP server.",
            expected_output="The result of the complex data query.",
            agent=http_agent,
        )

        http_crew = Crew(
            agents=[http_agent],
            tasks=[http_task],
            verbose=True,
            process=Process.sequential
        )
        
        result = http_crew.kickoff() 
        print("\nCrew Task Result (Streamable HTTP - Managed):\n", result)

except Exception as e:
    print(f"Error connecting to or using Streamable HTTP MCP server (Managed): {e}")
    print("Ensure the Streamable HTTP MCP server is running and accessible at the specified URL.")

注意: 将 "http://localhost:8001/mcp" 替换为你的 Streamable HTTP MCP 服务器的实际 URL。

2. 手动管理连接生命周期

对于需要更显式控制的场景,你可以手动管理 MCPServerAdapter 连接。

INFO

完成后,关键是调用 mcp_server_adapter.stop() 来关闭连接并释放资源。try...finally 块是确保这一点的最安全方式。

python
from crewai import Agent, Task, Crew, Process
from crewai_tools import MCPServerAdapter

server_params = {
    "url": "http://localhost:8001/mcp", # Replace with your actual Streamable HTTP server URL
    "transport": "streamable-http"
}

mcp_server_adapter = None 
try:
    mcp_server_adapter = MCPServerAdapter(server_params)
    mcp_server_adapter.start()
    tools = mcp_server_adapter.tools
    print(f"Available tools (manual Streamable HTTP): {[tool.name for tool in tools]}")

    manual_http_agent = Agent(
        role="Advanced Web Service User",
        goal="Interact with an MCP server using manually managed Streamable HTTP connections.",
        backstory="An AI specialist in fine-tuning HTTP-based service integrations.",
        tools=tools,
        verbose=True
    )
    
    data_processing_task = Task(
        description="Submit data for processing and retrieve results via Streamable HTTP.",
        expected_output="Processed data or confirmation.",
        agent=manual_http_agent
    )
    
    data_crew = Crew(
        agents=[manual_http_agent],
        tasks=[data_processing_task],
        verbose=True,
        process=Process.sequential
    )
    
    result = data_crew.kickoff()
    print("\nCrew Task Result (Streamable HTTP - Manual):\n", result)

except Exception as e:
    print(f"An error occurred during manual Streamable HTTP MCP integration: {e}")
    print("Ensure the Streamable HTTP MCP server is running and accessible.")
finally:
    if mcp_server_adapter and mcp_server_adapter.is_connected:
        print("Stopping Streamable HTTP MCP server connection (manual)...")
        mcp_server_adapter.stop()  # **Crucial: Ensure stop is called**
    elif mcp_server_adapter:
        print("Streamable HTTP MCP server adapter was not connected. No stop needed or start failed.")

安全注意事项

使用 Streamable HTTP 传输时,通用 Web 安全最佳实践至关重要:

  • 使用 HTTPS:始终优先为 MCP 服务器 URL 使用 HTTPS(HTTP Secure),以加密传输中的数据。
  • 身份认证:如果你的 MCP 服务器暴露敏感工具或数据,请实施稳健的身份认证机制。
  • 输入验证:确保你的 MCP 服务器验证所有传入请求和参数。

有关保护 MCP 集成的全面指南,请参阅我们的安全注意事项页面和官方 MCP 传输安全文档。

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。