Model context protocol (MCP)
TheModel context protocol (MCP)는 애플리케이션이 도구와 컨텍스트를 언어 모델에 노출하는 방식을 표준화합니다. 공식 문서에서 인용:
MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AIapplications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCPprovides a standardized way to connect AI models to different data sources and tools.
Agents Python SDK는 여러 MCP 전송 방식을 이해합니다. 이를 통해 기존 MCP 서버를 재사용하거나 직접 구축하여 파일 시스템, HTTP, 또는 커넥터 기반 도구를 에이전트에 노출할 수 있습니다.
Choosing an MCP integration
에이전트에 MCP 서버를 연결하기 전에 도구 호출이 어디에서 실행될지와 도달 가능한 전송 방식을 결정하세요. 아래 매트릭스는 Python SDK가 지원하는 옵션을 요약합니다.
| What you need | Recommended option |
|---|---|
| Let OpenAI's Responses API call a publicly reachable MCP server on the model's behalf | 호스티드 MCP 서버 도구 viaHostedMCPTool |
| Connect to Streamable HTTP servers that you run locally or remotely | Streamable HTTP MCP servers viaMCPServerStreamableHttp |
| Talk to servers that implement HTTP with Server-Sent Events | HTTP with SSE MCP servers viaMCPServerSse |
| Launch a local process and communicate over stdin/stdout | stdio MCP servers viaMCPServerStdio |
아래 섹션에서는 각 옵션과 설정 방법, 그리고 언제 어떤 전송 방식을 선택해야 하는지 설명합니다.
1. Hosted MCP server tools
호스티드 도구는 전체 도구 라운드 트립을 OpenAI 인프라로 이전합니다. 코드에서 도구를 나열하고 호출하는 대신,HostedMCPTool 이 서버 레이블(및 선택적 커넥터 메타데이터)을 Responses API에 전달합니다. 모델은 원격 서버의 도구를 나열하고 Python 프로세스에 추가 콜백 없이 이를 호출합니다. 호스티드 도구는 현재 Responses API의 호스티드 MCP 통합을 지원하는 OpenAI 모델에서 동작합니다.
Basic hosted MCP tool
에이전트의tools 목록에HostedMCPTool 을 추가하여 호스티드 도구를 생성합니다.tool_configdict는 REST API에 전송할 JSON과 동일합니다:
importasynciofromagentsimportAgent,HostedMCPTool,Runnerasyncdefmain()->None:agent=Agent(name="Assistant",tools=[HostedMCPTool(tool_config={"type":"mcp","server_label":"gitmcp","server_url":"https://gitmcp.io/openai/codex","require_approval":"never",})],)result=awaitRunner.run(agent,"Which language is this repository written in?")print(result.final_output)asyncio.run(main())호스티드 서버는 자신의 도구를 자동으로 노출합니다.mcp_servers 에 추가할 필요가 없습니다.
Streaming hosted MCP results
호스티드 도구는 함수 도구와 동일한 방식으로 스트리밍 결과를 지원합니다.Runner.run_streamed 에stream=True 를 전달하여모델이 아직 작업 중일 때 점진적인 MCP 출력을 소비하세요:
result=Runner.run_streamed(agent,"Summarise this repository's top languages")asyncforeventinresult.stream_events():ifevent.type=="run_item_stream_event":print(f"Received:{event.item}")print(result.final_output)Optional approval flows
서버가 민감한 작업을 수행할 수 있는 경우 각 도구 실행 전에 사람 또는 프로그램적 승인이 필요하도록 할 수 있습니다.tool_config 의require_approval 을 단일 정책("always","never") 또는 도구 이름을 정책에 매핑한 dict로 구성하세요. Python 내에서 결정을 내리려면on_approval_request 콜백을 제공하세요.
fromagentsimportMCPToolApprovalFunctionResult,MCPToolApprovalRequestSAFE_TOOLS={"read_project_metadata"}defapprove_tool(request:MCPToolApprovalRequest)->MCPToolApprovalFunctionResult:ifrequest.data.nameinSAFE_TOOLS:return{"approve":True}return{"approve":False,"reason":"Escalate to a human reviewer"}agent=Agent(name="Assistant",tools=[HostedMCPTool(tool_config={"type":"mcp","server_label":"gitmcp","server_url":"https://gitmcp.io/openai/codex","require_approval":"always",},on_approval_request=approve_tool,)],)콜백은 동기 또는 비동기로 작성할 수 있으며, 모델이 실행을 계속하기 위해 승인 데이터가 필요할 때 호출됩니다.
Connector-backed hosted servers
호스티드 MCP는 OpenAI 커넥터도 지원합니다.server_url 을 지정하는 대신connector_id 와 액세스 토큰을 제공하세요.Responses API가 인증을 처리하고 호스티드 서버가 커넥터의 도구를 노출합니다.
importosHostedMCPTool(tool_config={"type":"mcp","server_label":"google_calendar","connector_id":"connector_googlecalendar","authorization":os.environ["GOOGLE_CALENDAR_AUTHORIZATION"],"require_approval":"never",})스트리밍, 승인, 커넥터를 포함한 완전한 호스티드 도구 샘플은examples/hosted_mcp 에 있습니다.
2. Streamable HTTP MCP servers
네트워크 연결을 직접 관리하려면MCPServerStreamableHttp 를 사용하세요. Streamable HTTP 서버는 전송을 제어하거나, 지연 시간을 낮춘 상태로 자체 인프라 내에서 서버를 실행하려는 경우에 적합합니다.
importasyncioimportosfromagentsimportAgent,Runnerfromagents.mcpimportMCPServerStreamableHttpfromagents.model_settingsimportModelSettingsasyncdefmain()->None:token=os.environ["MCP_SERVER_TOKEN"]asyncwithMCPServerStreamableHttp(name="Streamable HTTP Python Server",params={"url":"http://localhost:8000/mcp","headers":{"Authorization":f"Bearer{token}"},"timeout":10,},cache_tools_list=True,max_retry_attempts=3,)asserver:agent=Agent(name="Assistant",instructions="Use the MCP tools to answer the questions.",mcp_servers=[server],model_settings=ModelSettings(tool_choice="required"),)result=awaitRunner.run(agent,"Add 7 and 22.")print(result.final_output)asyncio.run(main())생성자는 다음과 같은 추가 옵션을 허용합니다:
client_session_timeout_seconds는 HTTP 읽기 타임아웃을 제어합니다use_structured_content는tool_result.structured_content를 텍스트 출력보다 우선시할지 여부를 전환합니다max_retry_attempts와retry_backoff_seconds_base는list_tools()와call_tool()에 자동 재시도를 추가합니다tool_filter를 사용하면 도구의 부분 집합만 노출할 수 있습니다(도구 필터링 참조)
3. HTTP with SSE MCP servers
MCP 서버가 HTTP with SSE 전송을 구현하는 경우MCPServerSse 를 인스턴스화하세요. 전송 방식을 제외하면 API는 Streamable HTTP 서버와 동일합니다.
fromagentsimportAgent,Runnerfromagents.model_settingsimportModelSettingsfromagents.mcpimportMCPServerSseworkspace_id="demo-workspace"asyncwithMCPServerSse(name="SSE Python Server",params={"url":"http://localhost:8000/sse","headers":{"X-Workspace":workspace_id},},cache_tools_list=True,)asserver:agent=Agent(name="Assistant",mcp_servers=[server],model_settings=ModelSettings(tool_choice="required"),)result=awaitRunner.run(agent,"What's the weather in Tokyo?")print(result.final_output)4. stdio MCP servers
로컬 하위 프로세스로 실행되는 MCP 서버의 경우MCPServerStdio 를 사용하세요. SDK는 프로세스를 시작하고 파이프를 열린 상태로 유지하며, 컨텍스트 매니저가 종료될 때 자동으로 닫습니다. 이 옵션은 빠른 개념 증명이나 서버가 커맨드라인 엔트리 포인트만 노출할 때 유용합니다.
frompathlibimportPathfromagentsimportAgent,Runnerfromagents.mcpimportMCPServerStdiocurrent_dir=Path(__file__).parentsamples_dir=current_dir/"sample_files"asyncwithMCPServerStdio(name="Filesystem Server via npx",params={"command":"npx","args":["-y","@modelcontextprotocol/server-filesystem",str(samples_dir)],},)asserver:agent=Agent(name="Assistant",instructions="Use the files in the sample directory to answer questions.",mcp_servers=[server],)result=awaitRunner.run(agent,"List the files available to you.")print(result.final_output)Tool filtering
각 MCP 서버는 에이전트에 필요한 함수만 노출할 수 있도록 도구 필터를 지원합니다. 필터링은 생성 시점 또는 실행마다 동적으로 수행할 수 있습니다.
Static tool filtering
create_static_tool_filter 를 사용하여 간단한 허용/차단 목록을 구성하세요:
frompathlibimportPathfromagents.mcpimportMCPServerStdio,create_static_tool_filtersamples_dir=Path("/path/to/files")filesystem_server=MCPServerStdio(params={"command":"npx","args":["-y","@modelcontextprotocol/server-filesystem",str(samples_dir)],},tool_filter=create_static_tool_filter(allowed_tool_names=["read_file","write_file"]),)allowed_tool_names 와blocked_tool_names 가 모두 제공되면 SDK는 먼저 허용 목록을 적용한 다음 남은 집합에서 차단된 도구를 제거합니다.
Dynamic tool filtering
보다 정교한 로직이 필요한 경우ToolFilterContext 를 받는 callable을 전달하세요. 이 callable은동기 또는 비동기로 작성할 수 있으며, 도구를 노출해야 하면True 를 반환합니다.
frompathlibimportPathfromagents.mcpimportMCPServerStdio,ToolFilterContextsamples_dir=Path("/path/to/files")asyncdefcontext_aware_filter(context:ToolFilterContext,tool)->bool:ifcontext.agent.name=="Code Reviewer"andtool.name.startswith("danger_"):returnFalsereturnTrueasyncwithMCPServerStdio(params={"command":"npx","args":["-y","@modelcontextprotocol/server-filesystem",str(samples_dir)],},tool_filter=context_aware_filter,)asserver:...필터 컨텍스트는 활성run_context, 도구를 요청하는agent, 그리고server_name 을 제공합니다.
Prompts
MCP 서버는 에이전트 instructions를 동적으로 생성하는 프롬프트도 제공할 수 있습니다. 프롬프트를 지원하는 서버는 다음 두 가지메서드를 노출합니다:
list_prompts()는 사용 가능한 프롬프트 템플릿을 나열합니다get_prompt(name, arguments)는 필요 시 매개변수와 함께 구체적인 프롬프트를 가져옵니다
fromagentsimportAgentprompt_result=awaitserver.get_prompt("generate_code_review_instructions",{"focus":"security vulnerabilities","language":"python"},)instructions=prompt_result.messages[0].content.textagent=Agent(name="Code Reviewer",instructions=instructions,mcp_servers=[server],)Caching
모든 에이전트 실행은 각 MCP 서버에서list_tools() 를 호출합니다. 원격 서버는 눈에 띄는 지연을 유발할 수 있으므로 모든 MCP서버 클래스는cache_tools_list 옵션을 제공합니다. 도구 정의가 자주 변경되지 않는다고 확신할 때에만True 로 설정하세요. 나중에 새 목록을 강제로 가져오려면 서버 인스턴스에서invalidate_tools_cache() 를 호출하세요.
Tracing
Tracing 은 MCP 활동을 자동으로 캡처합니다. 포함 내용:
- 도구 목록을 가져오기 위한 MCP 서버 호출
- 도구 호출에 대한 MCP 관련 정보

Further reading
- Model Context Protocol – 사양 및 설계 가이드
- examples/mcp – 실행 가능한 stdio, SSE, Streamable HTTP 샘플
- examples/hosted_mcp – 승인 및 커넥터를 포함한 완전한 호스티드 MCP 데모