Streamable HTTP 전송
Streamable HTTP 전송 (Streamable HTTP Transport)
Streamable HTTP 전송은 원격 MCP 서버에 연결할 수 있는 유연한 방법이에요. 종종 HTTP 위에 구축되며 요청-응답과 스트리밍을 포함한 다양한 통신 패턴을 지원해요. 때로는 더 넓은 HTTP 상호작용 안에서 서버-클라이언트 스트림에 SSE(Server-Sent Events)를 활용하기도 해요.
출처: 문서
본문
Overview (개요)
Key Concepts (핵심 개념)
- Remote Servers — 원격으로 호스팅되는 MCP 서버를 위해 설계됐어요.
- Flexibility — 일반 SSE보다 더 복잡한 상호작용 패턴을 지원할 수 있어요. 서버가 구현한다면 양방향 통신도 가능해요.
- MCPServerAdapter Configuration — MCP 통신을 위한 서버의 base URL을 제공하고 전송 유형에
"streamable-http"를 지정하면 돼요.
Connecting via Streamable HTTP
Streamable HTTP MCP 서버와의 연결 수명주기를 관리하는 두 가지 기본 방법이 있어요.
1. 완전 관리형 연결 (권장)
Python 컨텍스트 매니저(with 문)를 사용하는 것이 권장돼요. 연결의 수립과 종료를 자동으로 처리해 줘요.
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 연결을 수동으로 관리할 수 있어요.
완료 후 연결을 닫고 리소스를 해제하려면 mcp_server_adapter.stop()을 호출하는 것이 **중요(critical)**해요. 이를 보장하는 가장 안전한 방법은 try...finally 블록이에요.
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.")
Security Considerations (보안 고려 사항)
Streamable HTTP 전송을 사용할 때는 일반적인 웹 보안 모범 사례가 매우 중요해요:
- HTTPS 사용 — 전송 중 데이터를 암호화하려면 MCP 서버 URL에 항상 HTTPS(HTTP Secure)를 사용하세요.
- 인증(Authentication) — MCP 서버가 민감한 툴이나 데이터를 노출한다면 견고한 인증 메커니즘을 구현하세요.
- 입력 검증(Input Validation) — MCP 서버가 들어오는 모든 요청과 파라미터를 검증하도록 하세요.
MCP 통합 보안에 대한 종합적인 가이드는 보안 고려 사항 페이지와 공식 MCP Transport Security 문서를 참조하세요.