Movatterモバイル変換


[0]ホーム

URL:


Skip to content

MCP Servers

MCPServer

Bases:ABC

Base class for Model Context Protocol servers.

Source code insrc/agents/mcp/server.py
classMCPServer(abc.ABC):"""Base class for Model Context Protocol servers."""def__init__(self,use_structured_content:bool=False,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""        Args:            use_structured_content: Whether to use `tool_result.structured_content` when calling an                MCP tool.Defaults to False for backwards compatibility - most MCP servers still                include the structured content in the `tool_result.content`, and using it by                default will cause duplicate content. You can set this to True if you know the                server will not duplicate the structured content in the `tool_result.content`.            require_approval: Approval policy for tools on this server. Accepts "always"/"never",                a dict of tool names to those values, a boolean, or an object with always/never                tool lists (mirroring TS requireApproval). Normalized into a needs_approval policy.            failure_error_function: Optional function used to convert MCP tool failures into                a model-visible error message. If explicitly set to None, tool errors will be                raised instead of converted. If left unset, the agent-level configuration (or                SDK default) will be used.            tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for                tool calls. It is invoked by the Agents SDK before calling `call_tool`.        """self.use_structured_content=use_structured_contentself._needs_approval_policy=self._normalize_needs_approval(require_approval=require_approval)self._failure_error_function=failure_error_functionself.tool_meta_resolver=tool_meta_resolver@abc.abstractmethodasyncdefconnect(self):"""Connect to the server. For example, this might mean spawning a subprocess or        opening a network connection. The server is expected to remain connected until        `cleanup()` is called.        """pass@property@abc.abstractmethoddefname(self)->str:"""A readable name for the server."""pass@abc.abstractmethodasyncdefcleanup(self):"""Cleanup the server. For example, this might mean closing a subprocess or        closing a network connection.        """pass@abc.abstractmethodasyncdeflist_tools(self,run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[MCPTool]:"""List the tools available on the server."""pass@abc.abstractmethodasyncdefcall_tool(self,tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult:"""Invoke a tool on the server."""pass@propertydefcached_tools(self)->list[MCPTool]|None:"""Return the most recently fetched tools list, if available.        Implementations may return `None` when tools have not been fetched yet or caching is        disabled.        """returnNone@abc.abstractmethodasyncdeflist_prompts(self,)->ListPromptsResult:"""List the prompts available on the server."""pass@abc.abstractmethodasyncdefget_prompt(self,name:str,arguments:dict[str,Any]|None=None)->GetPromptResult:"""Get a specific prompt from the server."""pass@staticmethoddef_normalize_needs_approval(*,require_approval:RequireApprovalSetting,)->(bool|dict[str,bool]|Callable[[RunContextWrapper[Any],AgentBase,MCPTool],MaybeAwaitable[bool]]):"""Normalize approval inputs to booleans or a name->bool map."""ifrequire_approvalisNone:returnFalsedef_to_bool(value:str)->bool:returnvalue=="always"def_is_tool_list_schema(value:object)->bool:ifnotisinstance(value,dict):returnFalseforkeyin("always","never"):ifkeynotinvalue:continueentry=value.get(key)ifisinstance(entry,dict)and"tool_names"inentry:returnTruereturnFalseifisinstance(require_approval,dict)and_is_tool_list_schema(require_approval):always_entry:RequireApprovalToolList|Any=require_approval.get("always",{})never_entry:RequireApprovalToolList|Any=require_approval.get("never",{})always_names=(always_entry.get("tool_names",[])ifisinstance(always_entry,dict)else[])never_names=never_entry.get("tool_names",[])ifisinstance(never_entry,dict)else[]tool_list_mapping:dict[str,bool]={}fornameinalways_names:tool_list_mapping[str(name)]=Truefornameinnever_names:tool_list_mapping[str(name)]=Falsereturntool_list_mappingifisinstance(require_approval,dict):tool_mapping:dict[str,bool]={}forname,valueinrequire_approval.items():ifisinstance(value,bool):tool_mapping[str(name)]=valueelifisinstance(value,str)andvaluein("always","never"):tool_mapping[str(name)]=_to_bool(value)returntool_mappingifisinstance(require_approval,bool):returnrequire_approvalreturn_to_bool(require_approval)def_get_needs_approval_for_tool(self,tool:MCPTool,agent:AgentBase|None,)->bool|Callable[[RunContextWrapper[Any],dict[str,Any],str],Awaitable[bool]]:"""Return a FunctionTool.needs_approval value for a given MCP tool."""policy=self._needs_approval_policyifcallable(policy):ifagentisNone:returnFalseasyncdef_needs_approval(run_context:RunContextWrapper[Any],_args:dict[str,Any],_call_id:str)->bool:result=policy(run_context,agent,tool)ifinspect.isawaitable(result):result=awaitresultreturnbool(result)return_needs_approvalifisinstance(policy,dict):returnbool(policy.get(tool.name,False))returnbool(policy)def_get_failure_error_function(self,agent_failure_error_function:ToolErrorFunction|None)->ToolErrorFunction|None:"""Return the effective error handler for MCP tool failures."""ifself._failure_error_functionis_UNSET:returnagent_failure_error_functionreturncast(ToolErrorFunction|None,self._failure_error_function)

nameabstractmethodproperty

name:str

A readable name for the server.

cached_toolsproperty

cached_tools:list[Tool]|None

Return the most recently fetched tools list, if available.

Implementations may returnNone when tools have not been fetched yet or caching isdisabled.

__init__

__init__(use_structured_content:bool=False,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,)

Parameters:

NameTypeDescriptionDefault
use_structured_contentbool

Whether to usetool_result.structured_content when calling anMCP tool.Defaults to False for backwards compatibility - most MCP servers stillinclude the structured content in thetool_result.content, and using it bydefault will cause duplicate content. You can set this to True if you know theserver will not duplicate the structured content in thetool_result.content.

False
require_approvalRequireApprovalSetting

Approval policy for tools on this server. Accepts "always"/"never",a dict of tool names to those values, a boolean, or an object with always/nevertool lists (mirroring TS requireApproval). Normalized into a needs_approval policy.

None
failure_error_functionToolErrorFunction | None |_UnsetType

Optional function used to convert MCP tool failures intoa model-visible error message. If explicitly set to None, tool errors will beraised instead of converted. If left unset, the agent-level configuration (orSDK default) will be used.

_UNSET
tool_meta_resolverMCPToolMetaResolver | None

Optional callable that produces MCP request metadata (_meta) fortool calls. It is invoked by the Agents SDK before callingcall_tool.

None
Source code insrc/agents/mcp/server.py
def__init__(self,use_structured_content:bool=False,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""    Args:        use_structured_content: Whether to use `tool_result.structured_content` when calling an            MCP tool.Defaults to False for backwards compatibility - most MCP servers still            include the structured content in the `tool_result.content`, and using it by            default will cause duplicate content. You can set this to True if you know the            server will not duplicate the structured content in the `tool_result.content`.        require_approval: Approval policy for tools on this server. Accepts "always"/"never",            a dict of tool names to those values, a boolean, or an object with always/never            tool lists (mirroring TS requireApproval). Normalized into a needs_approval policy.        failure_error_function: Optional function used to convert MCP tool failures into            a model-visible error message. If explicitly set to None, tool errors will be            raised instead of converted. If left unset, the agent-level configuration (or            SDK default) will be used.        tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for            tool calls. It is invoked by the Agents SDK before calling `call_tool`.    """self.use_structured_content=use_structured_contentself._needs_approval_policy=self._normalize_needs_approval(require_approval=require_approval)self._failure_error_function=failure_error_functionself.tool_meta_resolver=tool_meta_resolver

connectabstractmethodasync

connect()

Connect to the server. For example, this might mean spawning a subprocess oropening a network connection. The server is expected to remain connected untilcleanup() is called.

Source code insrc/agents/mcp/server.py
@abc.abstractmethodasyncdefconnect(self):"""Connect to the server. For example, this might mean spawning a subprocess or    opening a network connection. The server is expected to remain connected until    `cleanup()` is called.    """pass

cleanupabstractmethodasync

cleanup()

Cleanup the server. For example, this might mean closing a subprocess orclosing a network connection.

Source code insrc/agents/mcp/server.py
@abc.abstractmethodasyncdefcleanup(self):"""Cleanup the server. For example, this might mean closing a subprocess or    closing a network connection.    """pass

list_toolsabstractmethodasync

list_tools(run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[Tool]

List the tools available on the server.

Source code insrc/agents/mcp/server.py
@abc.abstractmethodasyncdeflist_tools(self,run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[MCPTool]:"""List the tools available on the server."""pass

call_toolabstractmethodasync

call_tool(tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult

Invoke a tool on the server.

Source code insrc/agents/mcp/server.py
@abc.abstractmethodasyncdefcall_tool(self,tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult:"""Invoke a tool on the server."""pass

list_promptsabstractmethodasync

list_prompts()->ListPromptsResult

List the prompts available on the server.

Source code insrc/agents/mcp/server.py
@abc.abstractmethodasyncdeflist_prompts(self,)->ListPromptsResult:"""List the prompts available on the server."""pass

get_promptabstractmethodasync

get_prompt(name:str,arguments:dict[str,Any]|None=None)->GetPromptResult

Get a specific prompt from the server.

Source code insrc/agents/mcp/server.py
@abc.abstractmethodasyncdefget_prompt(self,name:str,arguments:dict[str,Any]|None=None)->GetPromptResult:"""Get a specific prompt from the server."""pass

MCPServerStdioParams

Bases:TypedDict

Mirrorsmcp.client.stdio.StdioServerParameters, but lets you pass params without anotherimport.

Source code insrc/agents/mcp/server.py
classMCPServerStdioParams(TypedDict):"""Mirrors `mcp.client.stdio.StdioServerParameters`, but lets you pass params without another    import.    """command:str"""The executable to run to start the server. For example, `python` or `node`."""args:NotRequired[list[str]]"""Command line args to pass to the `command` executable. For example, `['foo.py']` or    `['server.js', '--port', '8080']`."""env:NotRequired[dict[str,str]]"""The environment variables to set for the server. ."""cwd:NotRequired[str|Path]"""The working directory to use when spawning the process."""encoding:NotRequired[str]"""The text encoding used when sending/receiving messages to the server. Defaults to `utf-8`."""encoding_error_handler:NotRequired[Literal["strict","ignore","replace"]]"""The text encoding error handler. Defaults to `strict`.    See https://docs.python.org/3/library/codecs.html#codec-base-classes for    explanations of possible values.    """

commandinstance-attribute

command:str

The executable to run to start the server. For example,python ornode.

argsinstance-attribute

args:NotRequired[list[str]]

Command line args to pass to thecommand executable. For example,['foo.py'] or['server.js', '--port', '8080'].

envinstance-attribute

env:NotRequired[dict[str,str]]

The environment variables to set for the server. .

cwdinstance-attribute

cwd:NotRequired[str|Path]

The working directory to use when spawning the process.

encodinginstance-attribute

encoding:NotRequired[str]

The text encoding used when sending/receiving messages to the server. Defaults toutf-8.

encoding_error_handlerinstance-attribute

encoding_error_handler:NotRequired[Literal["strict","ignore","replace"]]

The text encoding error handler. Defaults tostrict.

See https://docs.python.org/3/library/codecs.html#codec-base-classes forexplanations of possible values.

MCPServerStdio

Bases:_MCPServerWithClientSession

MCP server implementation that uses the stdio transport. See the [spec](https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio) fordetails.

Source code insrc/agents/mcp/server.py
classMCPServerStdio(_MCPServerWithClientSession):"""MCP server implementation that uses the stdio transport. See the [spec]    (https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio) for    details.    """def__init__(self,params:MCPServerStdioParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""Create a new MCP server based on the stdio transport.        Args:            params: The params that configure the server. This includes the command to run to                start the server, the args to pass to the command, the environment variables to                set for the server, the working directory to use when spawning the process, and                the text encoding used when sending/receiving messages to the server.            cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be                cached and only fetched from the server once. If `False`, the tools list will be                fetched from the server on each call to `list_tools()`. The cache can be                invalidated by calling `invalidate_tools_cache()`. You should set this to `True`                if you know the server will not change its tools list, because it can drastically                improve latency (by avoiding a round-trip to the server every time).            name: A readable name for the server. If not provided, we'll create one from the                command.            client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.            tool_filter: The tool filter to use for filtering tools.            use_structured_content: Whether to use `tool_result.structured_content` when calling an                MCP tool. Defaults to False for backwards compatibility - most MCP servers still                include the structured content in the `tool_result.content`, and using it by                default will cause duplicate content. You can set this to True if you know the                server will not duplicate the structured content in the `tool_result.content`.            max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.                Defaults to no retries.            retry_backoff_seconds_base: The base delay, in seconds, for exponential                backoff between retries.            message_handler: Optional handler invoked for session messages as delivered by the                ClientSession.            require_approval: Approval policy for tools on this server. Accepts "always"/"never",                a dict of tool names to those values, or an object with always/never tool lists.            failure_error_function: Optional function used to convert MCP tool failures into                a model-visible error message. If explicitly set to None, tool errors will be                raised instead of converted. If left unset, the agent-level configuration (or                SDK default) will be used.            tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for                tool calls. It is invoked by the Agents SDK before calling `call_tool`.        """super().__init__(cache_tools_list=cache_tools_list,client_session_timeout_seconds=client_session_timeout_seconds,tool_filter=tool_filter,use_structured_content=use_structured_content,max_retry_attempts=max_retry_attempts,retry_backoff_seconds_base=retry_backoff_seconds_base,message_handler=message_handler,require_approval=require_approval,failure_error_function=failure_error_function,tool_meta_resolver=tool_meta_resolver,)self.params=StdioServerParameters(command=params["command"],args=params.get("args",[]),env=params.get("env"),cwd=params.get("cwd"),encoding=params.get("encoding","utf-8"),encoding_error_handler=params.get("encoding_error_handler","strict"),)self._name=nameorf"stdio:{self.params.command}"defcreate_streams(self,)->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]:"""Create the streams for the server."""returnstdio_client(self.params)@propertydefname(self)->str:"""A readable name for the server."""returnself._name

nameproperty

name:str

A readable name for the server.

__init__

__init__(params:MCPServerStdioParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,)

Create a new MCP server based on the stdio transport.

Parameters:

NameTypeDescriptionDefault
paramsMCPServerStdioParams

The params that configure the server. This includes the command to run tostart the server, the args to pass to the command, the environment variables toset for the server, the working directory to use when spawning the process, andthe text encoding used when sending/receiving messages to the server.

required
cache_tools_listbool

Whether to cache the tools list. IfTrue, the tools list will becached and only fetched from the server once. IfFalse, the tools list will befetched from the server on each call tolist_tools(). The cache can beinvalidated by callinginvalidate_tools_cache(). You should set this toTrueif you know the server will not change its tools list, because it can drasticallyimprove latency (by avoiding a round-trip to the server every time).

False
namestr | None

A readable name for the server. If not provided, we'll create one from thecommand.

None
client_session_timeout_secondsfloat | None

the read timeout passed to the MCP ClientSession.

5
tool_filterToolFilter

The tool filter to use for filtering tools.

None
use_structured_contentbool

Whether to usetool_result.structured_content when calling anMCP tool. Defaults to False for backwards compatibility - most MCP servers stillinclude the structured content in thetool_result.content, and using it bydefault will cause duplicate content. You can set this to True if you know theserver will not duplicate the structured content in thetool_result.content.

False
max_retry_attemptsint

Number of times to retry failed list_tools/call_tool calls.Defaults to no retries.

0
retry_backoff_seconds_basefloat

The base delay, in seconds, for exponentialbackoff between retries.

1.0
message_handlerMessageHandlerFnT | None

Optional handler invoked for session messages as delivered by theClientSession.

None
require_approvalRequireApprovalSetting

Approval policy for tools on this server. Accepts "always"/"never",a dict of tool names to those values, or an object with always/never tool lists.

None
failure_error_functionToolErrorFunction | None |_UnsetType

Optional function used to convert MCP tool failures intoa model-visible error message. If explicitly set to None, tool errors will beraised instead of converted. If left unset, the agent-level configuration (orSDK default) will be used.

_UNSET
tool_meta_resolverMCPToolMetaResolver | None

Optional callable that produces MCP request metadata (_meta) fortool calls. It is invoked by the Agents SDK before callingcall_tool.

None
Source code insrc/agents/mcp/server.py
def__init__(self,params:MCPServerStdioParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""Create a new MCP server based on the stdio transport.    Args:        params: The params that configure the server. This includes the command to run to            start the server, the args to pass to the command, the environment variables to            set for the server, the working directory to use when spawning the process, and            the text encoding used when sending/receiving messages to the server.        cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be            cached and only fetched from the server once. If `False`, the tools list will be            fetched from the server on each call to `list_tools()`. The cache can be            invalidated by calling `invalidate_tools_cache()`. You should set this to `True`            if you know the server will not change its tools list, because it can drastically            improve latency (by avoiding a round-trip to the server every time).        name: A readable name for the server. If not provided, we'll create one from the            command.        client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.        tool_filter: The tool filter to use for filtering tools.        use_structured_content: Whether to use `tool_result.structured_content` when calling an            MCP tool. Defaults to False for backwards compatibility - most MCP servers still            include the structured content in the `tool_result.content`, and using it by            default will cause duplicate content. You can set this to True if you know the            server will not duplicate the structured content in the `tool_result.content`.        max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.            Defaults to no retries.        retry_backoff_seconds_base: The base delay, in seconds, for exponential            backoff between retries.        message_handler: Optional handler invoked for session messages as delivered by the            ClientSession.        require_approval: Approval policy for tools on this server. Accepts "always"/"never",            a dict of tool names to those values, or an object with always/never tool lists.        failure_error_function: Optional function used to convert MCP tool failures into            a model-visible error message. If explicitly set to None, tool errors will be            raised instead of converted. If left unset, the agent-level configuration (or            SDK default) will be used.        tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for            tool calls. It is invoked by the Agents SDK before calling `call_tool`.    """super().__init__(cache_tools_list=cache_tools_list,client_session_timeout_seconds=client_session_timeout_seconds,tool_filter=tool_filter,use_structured_content=use_structured_content,max_retry_attempts=max_retry_attempts,retry_backoff_seconds_base=retry_backoff_seconds_base,message_handler=message_handler,require_approval=require_approval,failure_error_function=failure_error_function,tool_meta_resolver=tool_meta_resolver,)self.params=StdioServerParameters(command=params["command"],args=params.get("args",[]),env=params.get("env"),cwd=params.get("cwd"),encoding=params.get("encoding","utf-8"),encoding_error_handler=params.get("encoding_error_handler","strict"),)self._name=nameorf"stdio:{self.params.command}"

create_streams

create_streams()->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]

Create the streams for the server.

Source code insrc/agents/mcp/server.py
defcreate_streams(self,)->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]:"""Create the streams for the server."""returnstdio_client(self.params)

connectasync

connect()

Connect to the server.

Source code insrc/agents/mcp/server.py
asyncdefconnect(self):"""Connect to the server."""connection_succeeded=Falsetry:transport=awaitself.exit_stack.enter_async_context(self.create_streams())# streamablehttp_client returns (read, write, get_session_id)# sse_client returns (read, write)read,write,*_=transportsession=awaitself.exit_stack.enter_async_context(ClientSession(read,write,timedelta(seconds=self.client_session_timeout_seconds)ifself.client_session_timeout_secondselseNone,message_handler=self.message_handler,))server_result=awaitsession.initialize()self.server_initialize_result=server_resultself.session=sessionconnection_succeeded=TrueexceptExceptionase:# Try to extract HTTP error from exception or ExceptionGrouphttp_error=self._extract_http_error_from_exception(e)ifhttp_error:self._raise_user_error_for_http_error(http_error)# For CancelledError, preserve cancellation semantics - don't wrap it.# If it's masking an HTTP error, cleanup() will extract and raise UserError.ifisinstance(e,asyncio.CancelledError):raise# For HTTP-related errors, wrap themifisinstance(e,(httpx.HTTPStatusError,httpx.ConnectError,httpx.TimeoutException)):self._raise_user_error_for_http_error(e)# For other errors, re-raise as-is (don't wrap non-HTTP errors)raisefinally:# Always attempt cleanup on error, but suppress cleanup errors that mask the originalifnotconnection_succeeded:try:awaitself.cleanup()exceptUserError:# Re-raise UserError from cleanup (contains the real HTTP error)raiseexceptExceptionascleanup_error:# Suppress RuntimeError about cancel scopes during cleanup - this is a known# issue with the MCP library's async generator cleanup and shouldn't mask the# original errorifisinstance(cleanup_error,RuntimeError)and"cancel scope"instr(cleanup_error):logger.debug(f"Ignoring cancel scope error during cleanup of MCP server "f"'{self.name}':{cleanup_error}")else:# Log other cleanup errors but don't raise - original error is more# importantlogger.warning(f"Error during cleanup of MCP server '{self.name}':{cleanup_error}")

cleanupasync

cleanup()

Cleanup the server.

Source code insrc/agents/mcp/server.py
asyncdefcleanup(self):"""Cleanup the server."""asyncwithself._cleanup_lock:# Only raise HTTP errors if we're cleaning up after a failed connection.# During normal teardown (via __aexit__), log but don't raise to avoid# masking the original exception.is_failed_connection_cleanup=self.sessionisNonetry:awaitself.exit_stack.aclose()exceptasyncio.CancelledErrorase:logger.debug(f"Cleanup cancelled for MCP server '{self.name}':{e}")raiseexceptBaseExceptionGroupaseg:# Extract HTTP errors from ExceptionGroup raised during cleanup# This happens when background tasks fail (e.g., HTTP errors)http_error=Noneconnect_error=Nonetimeout_error=Noneerror_message=f"Failed to connect to MCP server '{self.name}': "forexcineg.exceptions:ifisinstance(exc,httpx.HTTPStatusError):http_error=excelifisinstance(exc,httpx.ConnectError):connect_error=excelifisinstance(exc,httpx.TimeoutException):timeout_error=exc# Only raise HTTP errors if we're cleaning up after a failed connection.# During normal teardown, log them instead.ifhttp_error:ifis_failed_connection_cleanup:error_message+=f"HTTP error{http_error.response.status_code} ({http_error.response.reason_phrase})"# noqa: E501raiseUserError(error_message)fromhttp_errorelse:# Normal teardown - log but don't raiselogger.warning(f"HTTP error during cleanup of MCP server '{self.name}':{http_error}")elifconnect_error:ifis_failed_connection_cleanup:error_message+="Could not reach the server."raiseUserError(error_message)fromconnect_errorelse:logger.warning(f"Connection error during cleanup of MCP server '{self.name}':{connect_error}"# noqa: E501)eliftimeout_error:ifis_failed_connection_cleanup:error_message+="Connection timeout."raiseUserError(error_message)fromtimeout_errorelse:logger.warning(f"Timeout error during cleanup of MCP server '{self.name}':{timeout_error}"# noqa: E501)else:# No HTTP error found, suppress RuntimeError about cancel scopeshas_cancel_scope_error=any(isinstance(exc,RuntimeError)and"cancel scope"instr(exc)forexcineg.exceptions)ifhas_cancel_scope_error:logger.debug(f"Ignoring cancel scope error during cleanup:{eg}")else:logger.error(f"Error cleaning up server:{eg}")exceptExceptionase:# Suppress RuntimeError about cancel scopes - this is a known issue with the MCP# library when background tasks fail during async generator cleanupifisinstance(e,RuntimeError)and"cancel scope"instr(e):logger.debug(f"Ignoring cancel scope error during cleanup:{e}")else:logger.error(f"Error cleaning up server:{e}")finally:self.session=None

list_toolsasync

list_tools(run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[Tool]

List the tools available on the server.

Source code insrc/agents/mcp/server.py
asyncdeflist_tools(self,run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[MCPTool]:"""List the tools available on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")session=self.sessionassertsessionisnotNonetry:# Return from cache if caching is enabled, we have tools, and the cache is not dirtyifself.cache_tools_listandnotself._cache_dirtyandself._tools_list:tools=self._tools_listelse:# Fetch the tools from the serverresult=awaitself._run_with_retries(lambda:session.list_tools())self._tools_list=result.toolsself._cache_dirty=Falsetools=self._tools_list# Filter tools based on tool_filterfiltered_tools=toolsifself.tool_filterisnotNone:filtered_tools=awaitself._apply_tool_filter(filtered_tools,run_context,agent)returnfiltered_toolsexcepthttpx.HTTPStatusErrorase:status_code=e.response.status_coderaiseUserError(f"Failed to list tools from MCP server '{self.name}': HTTP error{status_code}")fromeexcepthttpx.ConnectErrorase:raiseUserError(f"Failed to list tools from MCP server '{self.name}': Connection lost. "f"The server may have disconnected.")frome

call_toolasync

call_tool(tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult

Invoke a tool on the server.

Source code insrc/agents/mcp/server.py
asyncdefcall_tool(self,tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult:"""Invoke a tool on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")session=self.sessionassertsessionisnotNonetry:ifmetaisNone:returnawaitself._run_with_retries(lambda:session.call_tool(tool_name,arguments))returnawaitself._run_with_retries(lambda:session.call_tool(tool_name,arguments,meta=meta))excepthttpx.HTTPStatusErrorase:status_code=e.response.status_coderaiseUserError(f"Failed to call tool '{tool_name}' on MCP server '{self.name}': "f"HTTP error{status_code}")fromeexcepthttpx.ConnectErrorase:raiseUserError(f"Failed to call tool '{tool_name}' on MCP server '{self.name}': Connection lost. "f"The server may have disconnected.")frome

list_promptsasync

list_prompts()->ListPromptsResult

List the prompts available on the server.

Source code insrc/agents/mcp/server.py
asyncdeflist_prompts(self,)->ListPromptsResult:"""List the prompts available on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")returnawaitself.session.list_prompts()

get_promptasync

get_prompt(name:str,arguments:dict[str,Any]|None=None)->GetPromptResult

Get a specific prompt from the server.

Source code insrc/agents/mcp/server.py
asyncdefget_prompt(self,name:str,arguments:dict[str,Any]|None=None)->GetPromptResult:"""Get a specific prompt from the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")returnawaitself.session.get_prompt(name,arguments)

invalidate_tools_cache

invalidate_tools_cache()

Invalidate the tools cache.

Source code insrc/agents/mcp/server.py
definvalidate_tools_cache(self):"""Invalidate the tools cache."""self._cache_dirty=True

MCPServerSseParams

Bases:TypedDict

Mirrors the params inmcp.client.sse.sse_client.

Source code insrc/agents/mcp/server.py
classMCPServerSseParams(TypedDict):"""Mirrors the params in`mcp.client.sse.sse_client`."""url:str"""The URL of the server."""headers:NotRequired[dict[str,str]]"""The headers to send to the server."""timeout:NotRequired[float]"""The timeout for the HTTP request. Defaults to 5 seconds."""sse_read_timeout:NotRequired[float]"""The timeout for the SSE connection, in seconds. Defaults to 5 minutes."""

urlinstance-attribute

url:str

The URL of the server.

headersinstance-attribute

headers:NotRequired[dict[str,str]]

The headers to send to the server.

timeoutinstance-attribute

timeout:NotRequired[float]

The timeout for the HTTP request. Defaults to 5 seconds.

sse_read_timeoutinstance-attribute

sse_read_timeout:NotRequired[float]

The timeout for the SSE connection, in seconds. Defaults to 5 minutes.

MCPServerSse

Bases:_MCPServerWithClientSession

MCP server implementation that uses the HTTP with SSE transport. See the [spec](https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse)for details.

Source code insrc/agents/mcp/server.py
classMCPServerSse(_MCPServerWithClientSession):"""MCP server implementation that uses the HTTP with SSE transport. See the [spec]    (https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse)    for details.    """def__init__(self,params:MCPServerSseParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""Create a new MCP server based on the HTTP with SSE transport.        Args:            params: The params that configure the server. This includes the URL of the server,                the headers to send to the server, the timeout for the HTTP request, and the                timeout for the SSE connection.            cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be                cached and only fetched from the server once. If `False`, the tools list will be                fetched from the server on each call to `list_tools()`. The cache can be                invalidated by calling `invalidate_tools_cache()`. You should set this to `True`                if you know the server will not change its tools list, because it can drastically                improve latency (by avoiding a round-trip to the server every time).            name: A readable name for the server. If not provided, we'll create one from the                URL.            client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.            tool_filter: The tool filter to use for filtering tools.            use_structured_content: Whether to use `tool_result.structured_content` when calling an                MCP tool. Defaults to False for backwards compatibility - most MCP servers still                include the structured content in the `tool_result.content`, and using it by                default will cause duplicate content. You can set this to True if you know the                server will not duplicate the structured content in the `tool_result.content`.            max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.                Defaults to no retries.            retry_backoff_seconds_base: The base delay, in seconds, for exponential                backoff between retries.            message_handler: Optional handler invoked for session messages as delivered by the                ClientSession.            require_approval: Approval policy for tools on this server. Accepts "always"/"never",                a dict of tool names to those values, or an object with always/never tool lists.            failure_error_function: Optional function used to convert MCP tool failures into                a model-visible error message. If explicitly set to None, tool errors will be                raised instead of converted. If left unset, the agent-level configuration (or                SDK default) will be used.            tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for                tool calls. It is invoked by the Agents SDK before calling `call_tool`.        """super().__init__(cache_tools_list=cache_tools_list,client_session_timeout_seconds=client_session_timeout_seconds,tool_filter=tool_filter,use_structured_content=use_structured_content,max_retry_attempts=max_retry_attempts,retry_backoff_seconds_base=retry_backoff_seconds_base,message_handler=message_handler,require_approval=require_approval,failure_error_function=failure_error_function,tool_meta_resolver=tool_meta_resolver,)self.params=paramsself._name=nameorf"sse:{self.params['url']}"defcreate_streams(self,)->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]:"""Create the streams for the server."""returnsse_client(url=self.params["url"],headers=self.params.get("headers",None),timeout=self.params.get("timeout",5),sse_read_timeout=self.params.get("sse_read_timeout",60*5),)@propertydefname(self)->str:"""A readable name for the server."""returnself._name

nameproperty

name:str

A readable name for the server.

__init__

__init__(params:MCPServerSseParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,)

Create a new MCP server based on the HTTP with SSE transport.

Parameters:

NameTypeDescriptionDefault
paramsMCPServerSseParams

The params that configure the server. This includes the URL of the server,the headers to send to the server, the timeout for the HTTP request, and thetimeout for the SSE connection.

required
cache_tools_listbool

Whether to cache the tools list. IfTrue, the tools list will becached and only fetched from the server once. IfFalse, the tools list will befetched from the server on each call tolist_tools(). The cache can beinvalidated by callinginvalidate_tools_cache(). You should set this toTrueif you know the server will not change its tools list, because it can drasticallyimprove latency (by avoiding a round-trip to the server every time).

False
namestr | None

A readable name for the server. If not provided, we'll create one from theURL.

None
client_session_timeout_secondsfloat | None

the read timeout passed to the MCP ClientSession.

5
tool_filterToolFilter

The tool filter to use for filtering tools.

None
use_structured_contentbool

Whether to usetool_result.structured_content when calling anMCP tool. Defaults to False for backwards compatibility - most MCP servers stillinclude the structured content in thetool_result.content, and using it bydefault will cause duplicate content. You can set this to True if you know theserver will not duplicate the structured content in thetool_result.content.

False
max_retry_attemptsint

Number of times to retry failed list_tools/call_tool calls.Defaults to no retries.

0
retry_backoff_seconds_basefloat

The base delay, in seconds, for exponentialbackoff between retries.

1.0
message_handlerMessageHandlerFnT | None

Optional handler invoked for session messages as delivered by theClientSession.

None
require_approvalRequireApprovalSetting

Approval policy for tools on this server. Accepts "always"/"never",a dict of tool names to those values, or an object with always/never tool lists.

None
failure_error_functionToolErrorFunction | None |_UnsetType

Optional function used to convert MCP tool failures intoa model-visible error message. If explicitly set to None, tool errors will beraised instead of converted. If left unset, the agent-level configuration (orSDK default) will be used.

_UNSET
tool_meta_resolverMCPToolMetaResolver | None

Optional callable that produces MCP request metadata (_meta) fortool calls. It is invoked by the Agents SDK before callingcall_tool.

None
Source code insrc/agents/mcp/server.py
def__init__(self,params:MCPServerSseParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""Create a new MCP server based on the HTTP with SSE transport.    Args:        params: The params that configure the server. This includes the URL of the server,            the headers to send to the server, the timeout for the HTTP request, and the            timeout for the SSE connection.        cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be            cached and only fetched from the server once. If `False`, the tools list will be            fetched from the server on each call to `list_tools()`. The cache can be            invalidated by calling `invalidate_tools_cache()`. You should set this to `True`            if you know the server will not change its tools list, because it can drastically            improve latency (by avoiding a round-trip to the server every time).        name: A readable name for the server. If not provided, we'll create one from the            URL.        client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.        tool_filter: The tool filter to use for filtering tools.        use_structured_content: Whether to use `tool_result.structured_content` when calling an            MCP tool. Defaults to False for backwards compatibility - most MCP servers still            include the structured content in the `tool_result.content`, and using it by            default will cause duplicate content. You can set this to True if you know the            server will not duplicate the structured content in the `tool_result.content`.        max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.            Defaults to no retries.        retry_backoff_seconds_base: The base delay, in seconds, for exponential            backoff between retries.        message_handler: Optional handler invoked for session messages as delivered by the            ClientSession.        require_approval: Approval policy for tools on this server. Accepts "always"/"never",            a dict of tool names to those values, or an object with always/never tool lists.        failure_error_function: Optional function used to convert MCP tool failures into            a model-visible error message. If explicitly set to None, tool errors will be            raised instead of converted. If left unset, the agent-level configuration (or            SDK default) will be used.        tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for            tool calls. It is invoked by the Agents SDK before calling `call_tool`.    """super().__init__(cache_tools_list=cache_tools_list,client_session_timeout_seconds=client_session_timeout_seconds,tool_filter=tool_filter,use_structured_content=use_structured_content,max_retry_attempts=max_retry_attempts,retry_backoff_seconds_base=retry_backoff_seconds_base,message_handler=message_handler,require_approval=require_approval,failure_error_function=failure_error_function,tool_meta_resolver=tool_meta_resolver,)self.params=paramsself._name=nameorf"sse:{self.params['url']}"

create_streams

create_streams()->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]

Create the streams for the server.

Source code insrc/agents/mcp/server.py
defcreate_streams(self,)->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]:"""Create the streams for the server."""returnsse_client(url=self.params["url"],headers=self.params.get("headers",None),timeout=self.params.get("timeout",5),sse_read_timeout=self.params.get("sse_read_timeout",60*5),)

connectasync

connect()

Connect to the server.

Source code insrc/agents/mcp/server.py
asyncdefconnect(self):"""Connect to the server."""connection_succeeded=Falsetry:transport=awaitself.exit_stack.enter_async_context(self.create_streams())# streamablehttp_client returns (read, write, get_session_id)# sse_client returns (read, write)read,write,*_=transportsession=awaitself.exit_stack.enter_async_context(ClientSession(read,write,timedelta(seconds=self.client_session_timeout_seconds)ifself.client_session_timeout_secondselseNone,message_handler=self.message_handler,))server_result=awaitsession.initialize()self.server_initialize_result=server_resultself.session=sessionconnection_succeeded=TrueexceptExceptionase:# Try to extract HTTP error from exception or ExceptionGrouphttp_error=self._extract_http_error_from_exception(e)ifhttp_error:self._raise_user_error_for_http_error(http_error)# For CancelledError, preserve cancellation semantics - don't wrap it.# If it's masking an HTTP error, cleanup() will extract and raise UserError.ifisinstance(e,asyncio.CancelledError):raise# For HTTP-related errors, wrap themifisinstance(e,(httpx.HTTPStatusError,httpx.ConnectError,httpx.TimeoutException)):self._raise_user_error_for_http_error(e)# For other errors, re-raise as-is (don't wrap non-HTTP errors)raisefinally:# Always attempt cleanup on error, but suppress cleanup errors that mask the originalifnotconnection_succeeded:try:awaitself.cleanup()exceptUserError:# Re-raise UserError from cleanup (contains the real HTTP error)raiseexceptExceptionascleanup_error:# Suppress RuntimeError about cancel scopes during cleanup - this is a known# issue with the MCP library's async generator cleanup and shouldn't mask the# original errorifisinstance(cleanup_error,RuntimeError)and"cancel scope"instr(cleanup_error):logger.debug(f"Ignoring cancel scope error during cleanup of MCP server "f"'{self.name}':{cleanup_error}")else:# Log other cleanup errors but don't raise - original error is more# importantlogger.warning(f"Error during cleanup of MCP server '{self.name}':{cleanup_error}")

cleanupasync

cleanup()

Cleanup the server.

Source code insrc/agents/mcp/server.py
asyncdefcleanup(self):"""Cleanup the server."""asyncwithself._cleanup_lock:# Only raise HTTP errors if we're cleaning up after a failed connection.# During normal teardown (via __aexit__), log but don't raise to avoid# masking the original exception.is_failed_connection_cleanup=self.sessionisNonetry:awaitself.exit_stack.aclose()exceptasyncio.CancelledErrorase:logger.debug(f"Cleanup cancelled for MCP server '{self.name}':{e}")raiseexceptBaseExceptionGroupaseg:# Extract HTTP errors from ExceptionGroup raised during cleanup# This happens when background tasks fail (e.g., HTTP errors)http_error=Noneconnect_error=Nonetimeout_error=Noneerror_message=f"Failed to connect to MCP server '{self.name}': "forexcineg.exceptions:ifisinstance(exc,httpx.HTTPStatusError):http_error=excelifisinstance(exc,httpx.ConnectError):connect_error=excelifisinstance(exc,httpx.TimeoutException):timeout_error=exc# Only raise HTTP errors if we're cleaning up after a failed connection.# During normal teardown, log them instead.ifhttp_error:ifis_failed_connection_cleanup:error_message+=f"HTTP error{http_error.response.status_code} ({http_error.response.reason_phrase})"# noqa: E501raiseUserError(error_message)fromhttp_errorelse:# Normal teardown - log but don't raiselogger.warning(f"HTTP error during cleanup of MCP server '{self.name}':{http_error}")elifconnect_error:ifis_failed_connection_cleanup:error_message+="Could not reach the server."raiseUserError(error_message)fromconnect_errorelse:logger.warning(f"Connection error during cleanup of MCP server '{self.name}':{connect_error}"# noqa: E501)eliftimeout_error:ifis_failed_connection_cleanup:error_message+="Connection timeout."raiseUserError(error_message)fromtimeout_errorelse:logger.warning(f"Timeout error during cleanup of MCP server '{self.name}':{timeout_error}"# noqa: E501)else:# No HTTP error found, suppress RuntimeError about cancel scopeshas_cancel_scope_error=any(isinstance(exc,RuntimeError)and"cancel scope"instr(exc)forexcineg.exceptions)ifhas_cancel_scope_error:logger.debug(f"Ignoring cancel scope error during cleanup:{eg}")else:logger.error(f"Error cleaning up server:{eg}")exceptExceptionase:# Suppress RuntimeError about cancel scopes - this is a known issue with the MCP# library when background tasks fail during async generator cleanupifisinstance(e,RuntimeError)and"cancel scope"instr(e):logger.debug(f"Ignoring cancel scope error during cleanup:{e}")else:logger.error(f"Error cleaning up server:{e}")finally:self.session=None

list_toolsasync

list_tools(run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[Tool]

List the tools available on the server.

Source code insrc/agents/mcp/server.py
asyncdeflist_tools(self,run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[MCPTool]:"""List the tools available on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")session=self.sessionassertsessionisnotNonetry:# Return from cache if caching is enabled, we have tools, and the cache is not dirtyifself.cache_tools_listandnotself._cache_dirtyandself._tools_list:tools=self._tools_listelse:# Fetch the tools from the serverresult=awaitself._run_with_retries(lambda:session.list_tools())self._tools_list=result.toolsself._cache_dirty=Falsetools=self._tools_list# Filter tools based on tool_filterfiltered_tools=toolsifself.tool_filterisnotNone:filtered_tools=awaitself._apply_tool_filter(filtered_tools,run_context,agent)returnfiltered_toolsexcepthttpx.HTTPStatusErrorase:status_code=e.response.status_coderaiseUserError(f"Failed to list tools from MCP server '{self.name}': HTTP error{status_code}")fromeexcepthttpx.ConnectErrorase:raiseUserError(f"Failed to list tools from MCP server '{self.name}': Connection lost. "f"The server may have disconnected.")frome

call_toolasync

call_tool(tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult

Invoke a tool on the server.

Source code insrc/agents/mcp/server.py
asyncdefcall_tool(self,tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult:"""Invoke a tool on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")session=self.sessionassertsessionisnotNonetry:ifmetaisNone:returnawaitself._run_with_retries(lambda:session.call_tool(tool_name,arguments))returnawaitself._run_with_retries(lambda:session.call_tool(tool_name,arguments,meta=meta))excepthttpx.HTTPStatusErrorase:status_code=e.response.status_coderaiseUserError(f"Failed to call tool '{tool_name}' on MCP server '{self.name}': "f"HTTP error{status_code}")fromeexcepthttpx.ConnectErrorase:raiseUserError(f"Failed to call tool '{tool_name}' on MCP server '{self.name}': Connection lost. "f"The server may have disconnected.")frome

list_promptsasync

list_prompts()->ListPromptsResult

List the prompts available on the server.

Source code insrc/agents/mcp/server.py
asyncdeflist_prompts(self,)->ListPromptsResult:"""List the prompts available on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")returnawaitself.session.list_prompts()

get_promptasync

get_prompt(name:str,arguments:dict[str,Any]|None=None)->GetPromptResult

Get a specific prompt from the server.

Source code insrc/agents/mcp/server.py
asyncdefget_prompt(self,name:str,arguments:dict[str,Any]|None=None)->GetPromptResult:"""Get a specific prompt from the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")returnawaitself.session.get_prompt(name,arguments)

invalidate_tools_cache

invalidate_tools_cache()

Invalidate the tools cache.

Source code insrc/agents/mcp/server.py
definvalidate_tools_cache(self):"""Invalidate the tools cache."""self._cache_dirty=True

MCPServerStreamableHttpParams

Bases:TypedDict

Mirrors the params inmcp.client.streamable_http.streamablehttp_client.

Source code insrc/agents/mcp/server.py
classMCPServerStreamableHttpParams(TypedDict):"""Mirrors the params in`mcp.client.streamable_http.streamablehttp_client`."""url:str"""The URL of the server."""headers:NotRequired[dict[str,str]]"""The headers to send to the server."""timeout:NotRequired[timedelta|float]"""The timeout for the HTTP request. Defaults to 5 seconds."""sse_read_timeout:NotRequired[timedelta|float]"""The timeout for the SSE connection, in seconds. Defaults to 5 minutes."""terminate_on_close:NotRequired[bool]"""Terminate on close"""httpx_client_factory:NotRequired[HttpClientFactory]"""Custom HTTP client factory for configuring httpx.AsyncClient behavior."""

urlinstance-attribute

url:str

The URL of the server.

headersinstance-attribute

headers:NotRequired[dict[str,str]]

The headers to send to the server.

timeoutinstance-attribute

timeout:NotRequired[timedelta|float]

The timeout for the HTTP request. Defaults to 5 seconds.

sse_read_timeoutinstance-attribute

sse_read_timeout:NotRequired[timedelta|float]

The timeout for the SSE connection, in seconds. Defaults to 5 minutes.

terminate_on_closeinstance-attribute

terminate_on_close:NotRequired[bool]

Terminate on close

httpx_client_factoryinstance-attribute

httpx_client_factory:NotRequired[HttpClientFactory]

Custom HTTP client factory for configuring httpx.AsyncClient behavior.

MCPServerStreamableHttp

Bases:_MCPServerWithClientSession

MCP server implementation that uses the Streamable HTTP transport. See the [spec](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)for details.

Source code insrc/agents/mcp/server.py
classMCPServerStreamableHttp(_MCPServerWithClientSession):"""MCP server implementation that uses the Streamable HTTP transport. See the [spec]    (https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)    for details.    """def__init__(self,params:MCPServerStreamableHttpParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""Create a new MCP server based on the Streamable HTTP transport.        Args:            params: The params that configure the server. This includes the URL of the server,                the headers to send to the server, the timeout for the HTTP request, the                timeout for the Streamable HTTP connection, whether we need to                terminate on close, and an optional custom HTTP client factory.            cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be                cached and only fetched from the server once. If `False`, the tools list will be                fetched from the server on each call to `list_tools()`. The cache can be                invalidated by calling `invalidate_tools_cache()`. You should set this to `True`                if you know the server will not change its tools list, because it can drastically                improve latency (by avoiding a round-trip to the server every time).            name: A readable name for the server. If not provided, we'll create one from the                URL.            client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.            tool_filter: The tool filter to use for filtering tools.            use_structured_content: Whether to use `tool_result.structured_content` when calling an                MCP tool. Defaults to False for backwards compatibility - most MCP servers still                include the structured content in the `tool_result.content`, and using it by                default will cause duplicate content. You can set this to True if you know the                server will not duplicate the structured content in the `tool_result.content`.            max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.                Defaults to no retries.            retry_backoff_seconds_base: The base delay, in seconds, for exponential                backoff between retries.            message_handler: Optional handler invoked for session messages as delivered by the                ClientSession.            require_approval: Approval policy for tools on this server. Accepts "always"/"never",                a dict of tool names to those values, or an object with always/never tool lists.            failure_error_function: Optional function used to convert MCP tool failures into                a model-visible error message. If explicitly set to None, tool errors will be                raised instead of converted. If left unset, the agent-level configuration (or                SDK default) will be used.            tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for                tool calls. It is invoked by the Agents SDK before calling `call_tool`.        """super().__init__(cache_tools_list=cache_tools_list,client_session_timeout_seconds=client_session_timeout_seconds,tool_filter=tool_filter,use_structured_content=use_structured_content,max_retry_attempts=max_retry_attempts,retry_backoff_seconds_base=retry_backoff_seconds_base,message_handler=message_handler,require_approval=require_approval,failure_error_function=failure_error_function,tool_meta_resolver=tool_meta_resolver,)self.params=paramsself._name=nameorf"streamable_http:{self.params['url']}"defcreate_streams(self,)->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]:"""Create the streams for the server."""# Only pass httpx_client_factory if it's providedif"httpx_client_factory"inself.params:returnstreamablehttp_client(url=self.params["url"],headers=self.params.get("headers",None),timeout=self.params.get("timeout",5),sse_read_timeout=self.params.get("sse_read_timeout",60*5),terminate_on_close=self.params.get("terminate_on_close",True),httpx_client_factory=self.params["httpx_client_factory"],)else:returnstreamablehttp_client(url=self.params["url"],headers=self.params.get("headers",None),timeout=self.params.get("timeout",5),sse_read_timeout=self.params.get("sse_read_timeout",60*5),terminate_on_close=self.params.get("terminate_on_close",True),)@propertydefname(self)->str:"""A readable name for the server."""returnself._name

nameproperty

name:str

A readable name for the server.

__init__

__init__(params:MCPServerStreamableHttpParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,)

Create a new MCP server based on the Streamable HTTP transport.

Parameters:

NameTypeDescriptionDefault
paramsMCPServerStreamableHttpParams

The params that configure the server. This includes the URL of the server,the headers to send to the server, the timeout for the HTTP request, thetimeout for the Streamable HTTP connection, whether we need toterminate on close, and an optional custom HTTP client factory.

required
cache_tools_listbool

Whether to cache the tools list. IfTrue, the tools list will becached and only fetched from the server once. IfFalse, the tools list will befetched from the server on each call tolist_tools(). The cache can beinvalidated by callinginvalidate_tools_cache(). You should set this toTrueif you know the server will not change its tools list, because it can drasticallyimprove latency (by avoiding a round-trip to the server every time).

False
namestr | None

A readable name for the server. If not provided, we'll create one from theURL.

None
client_session_timeout_secondsfloat | None

the read timeout passed to the MCP ClientSession.

5
tool_filterToolFilter

The tool filter to use for filtering tools.

None
use_structured_contentbool

Whether to usetool_result.structured_content when calling anMCP tool. Defaults to False for backwards compatibility - most MCP servers stillinclude the structured content in thetool_result.content, and using it bydefault will cause duplicate content. You can set this to True if you know theserver will not duplicate the structured content in thetool_result.content.

False
max_retry_attemptsint

Number of times to retry failed list_tools/call_tool calls.Defaults to no retries.

0
retry_backoff_seconds_basefloat

The base delay, in seconds, for exponentialbackoff between retries.

1.0
message_handlerMessageHandlerFnT | None

Optional handler invoked for session messages as delivered by theClientSession.

None
require_approvalRequireApprovalSetting

Approval policy for tools on this server. Accepts "always"/"never",a dict of tool names to those values, or an object with always/never tool lists.

None
failure_error_functionToolErrorFunction | None |_UnsetType

Optional function used to convert MCP tool failures intoa model-visible error message. If explicitly set to None, tool errors will beraised instead of converted. If left unset, the agent-level configuration (orSDK default) will be used.

_UNSET
tool_meta_resolverMCPToolMetaResolver | None

Optional callable that produces MCP request metadata (_meta) fortool calls. It is invoked by the Agents SDK before callingcall_tool.

None
Source code insrc/agents/mcp/server.py
def__init__(self,params:MCPServerStreamableHttpParams,cache_tools_list:bool=False,name:str|None=None,client_session_timeout_seconds:float|None=5,tool_filter:ToolFilter=None,use_structured_content:bool=False,max_retry_attempts:int=0,retry_backoff_seconds_base:float=1.0,message_handler:MessageHandlerFnT|None=None,require_approval:RequireApprovalSetting=None,failure_error_function:ToolErrorFunction|None|_UnsetType=_UNSET,tool_meta_resolver:MCPToolMetaResolver|None=None,):"""Create a new MCP server based on the Streamable HTTP transport.    Args:        params: The params that configure the server. This includes the URL of the server,            the headers to send to the server, the timeout for the HTTP request, the            timeout for the Streamable HTTP connection, whether we need to            terminate on close, and an optional custom HTTP client factory.        cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be            cached and only fetched from the server once. If `False`, the tools list will be            fetched from the server on each call to `list_tools()`. The cache can be            invalidated by calling `invalidate_tools_cache()`. You should set this to `True`            if you know the server will not change its tools list, because it can drastically            improve latency (by avoiding a round-trip to the server every time).        name: A readable name for the server. If not provided, we'll create one from the            URL.        client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.        tool_filter: The tool filter to use for filtering tools.        use_structured_content: Whether to use `tool_result.structured_content` when calling an            MCP tool. Defaults to False for backwards compatibility - most MCP servers still            include the structured content in the `tool_result.content`, and using it by            default will cause duplicate content. You can set this to True if you know the            server will not duplicate the structured content in the `tool_result.content`.        max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.            Defaults to no retries.        retry_backoff_seconds_base: The base delay, in seconds, for exponential            backoff between retries.        message_handler: Optional handler invoked for session messages as delivered by the            ClientSession.        require_approval: Approval policy for tools on this server. Accepts "always"/"never",            a dict of tool names to those values, or an object with always/never tool lists.        failure_error_function: Optional function used to convert MCP tool failures into            a model-visible error message. If explicitly set to None, tool errors will be            raised instead of converted. If left unset, the agent-level configuration (or            SDK default) will be used.        tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for            tool calls. It is invoked by the Agents SDK before calling `call_tool`.    """super().__init__(cache_tools_list=cache_tools_list,client_session_timeout_seconds=client_session_timeout_seconds,tool_filter=tool_filter,use_structured_content=use_structured_content,max_retry_attempts=max_retry_attempts,retry_backoff_seconds_base=retry_backoff_seconds_base,message_handler=message_handler,require_approval=require_approval,failure_error_function=failure_error_function,tool_meta_resolver=tool_meta_resolver,)self.params=paramsself._name=nameorf"streamable_http:{self.params['url']}"

create_streams

create_streams()->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]

Create the streams for the server.

Source code insrc/agents/mcp/server.py
defcreate_streams(self,)->AbstractAsyncContextManager[tuple[MemoryObjectReceiveStream[SessionMessage|Exception],MemoryObjectSendStream[SessionMessage],GetSessionIdCallback|None,]]:"""Create the streams for the server."""# Only pass httpx_client_factory if it's providedif"httpx_client_factory"inself.params:returnstreamablehttp_client(url=self.params["url"],headers=self.params.get("headers",None),timeout=self.params.get("timeout",5),sse_read_timeout=self.params.get("sse_read_timeout",60*5),terminate_on_close=self.params.get("terminate_on_close",True),httpx_client_factory=self.params["httpx_client_factory"],)else:returnstreamablehttp_client(url=self.params["url"],headers=self.params.get("headers",None),timeout=self.params.get("timeout",5),sse_read_timeout=self.params.get("sse_read_timeout",60*5),terminate_on_close=self.params.get("terminate_on_close",True),)

connectasync

connect()

Connect to the server.

Source code insrc/agents/mcp/server.py
asyncdefconnect(self):"""Connect to the server."""connection_succeeded=Falsetry:transport=awaitself.exit_stack.enter_async_context(self.create_streams())# streamablehttp_client returns (read, write, get_session_id)# sse_client returns (read, write)read,write,*_=transportsession=awaitself.exit_stack.enter_async_context(ClientSession(read,write,timedelta(seconds=self.client_session_timeout_seconds)ifself.client_session_timeout_secondselseNone,message_handler=self.message_handler,))server_result=awaitsession.initialize()self.server_initialize_result=server_resultself.session=sessionconnection_succeeded=TrueexceptExceptionase:# Try to extract HTTP error from exception or ExceptionGrouphttp_error=self._extract_http_error_from_exception(e)ifhttp_error:self._raise_user_error_for_http_error(http_error)# For CancelledError, preserve cancellation semantics - don't wrap it.# If it's masking an HTTP error, cleanup() will extract and raise UserError.ifisinstance(e,asyncio.CancelledError):raise# For HTTP-related errors, wrap themifisinstance(e,(httpx.HTTPStatusError,httpx.ConnectError,httpx.TimeoutException)):self._raise_user_error_for_http_error(e)# For other errors, re-raise as-is (don't wrap non-HTTP errors)raisefinally:# Always attempt cleanup on error, but suppress cleanup errors that mask the originalifnotconnection_succeeded:try:awaitself.cleanup()exceptUserError:# Re-raise UserError from cleanup (contains the real HTTP error)raiseexceptExceptionascleanup_error:# Suppress RuntimeError about cancel scopes during cleanup - this is a known# issue with the MCP library's async generator cleanup and shouldn't mask the# original errorifisinstance(cleanup_error,RuntimeError)and"cancel scope"instr(cleanup_error):logger.debug(f"Ignoring cancel scope error during cleanup of MCP server "f"'{self.name}':{cleanup_error}")else:# Log other cleanup errors but don't raise - original error is more# importantlogger.warning(f"Error during cleanup of MCP server '{self.name}':{cleanup_error}")

cleanupasync

cleanup()

Cleanup the server.

Source code insrc/agents/mcp/server.py
asyncdefcleanup(self):"""Cleanup the server."""asyncwithself._cleanup_lock:# Only raise HTTP errors if we're cleaning up after a failed connection.# During normal teardown (via __aexit__), log but don't raise to avoid# masking the original exception.is_failed_connection_cleanup=self.sessionisNonetry:awaitself.exit_stack.aclose()exceptasyncio.CancelledErrorase:logger.debug(f"Cleanup cancelled for MCP server '{self.name}':{e}")raiseexceptBaseExceptionGroupaseg:# Extract HTTP errors from ExceptionGroup raised during cleanup# This happens when background tasks fail (e.g., HTTP errors)http_error=Noneconnect_error=Nonetimeout_error=Noneerror_message=f"Failed to connect to MCP server '{self.name}': "forexcineg.exceptions:ifisinstance(exc,httpx.HTTPStatusError):http_error=excelifisinstance(exc,httpx.ConnectError):connect_error=excelifisinstance(exc,httpx.TimeoutException):timeout_error=exc# Only raise HTTP errors if we're cleaning up after a failed connection.# During normal teardown, log them instead.ifhttp_error:ifis_failed_connection_cleanup:error_message+=f"HTTP error{http_error.response.status_code} ({http_error.response.reason_phrase})"# noqa: E501raiseUserError(error_message)fromhttp_errorelse:# Normal teardown - log but don't raiselogger.warning(f"HTTP error during cleanup of MCP server '{self.name}':{http_error}")elifconnect_error:ifis_failed_connection_cleanup:error_message+="Could not reach the server."raiseUserError(error_message)fromconnect_errorelse:logger.warning(f"Connection error during cleanup of MCP server '{self.name}':{connect_error}"# noqa: E501)eliftimeout_error:ifis_failed_connection_cleanup:error_message+="Connection timeout."raiseUserError(error_message)fromtimeout_errorelse:logger.warning(f"Timeout error during cleanup of MCP server '{self.name}':{timeout_error}"# noqa: E501)else:# No HTTP error found, suppress RuntimeError about cancel scopeshas_cancel_scope_error=any(isinstance(exc,RuntimeError)and"cancel scope"instr(exc)forexcineg.exceptions)ifhas_cancel_scope_error:logger.debug(f"Ignoring cancel scope error during cleanup:{eg}")else:logger.error(f"Error cleaning up server:{eg}")exceptExceptionase:# Suppress RuntimeError about cancel scopes - this is a known issue with the MCP# library when background tasks fail during async generator cleanupifisinstance(e,RuntimeError)and"cancel scope"instr(e):logger.debug(f"Ignoring cancel scope error during cleanup:{e}")else:logger.error(f"Error cleaning up server:{e}")finally:self.session=None

list_toolsasync

list_tools(run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[Tool]

List the tools available on the server.

Source code insrc/agents/mcp/server.py
asyncdeflist_tools(self,run_context:RunContextWrapper[Any]|None=None,agent:AgentBase|None=None,)->list[MCPTool]:"""List the tools available on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")session=self.sessionassertsessionisnotNonetry:# Return from cache if caching is enabled, we have tools, and the cache is not dirtyifself.cache_tools_listandnotself._cache_dirtyandself._tools_list:tools=self._tools_listelse:# Fetch the tools from the serverresult=awaitself._run_with_retries(lambda:session.list_tools())self._tools_list=result.toolsself._cache_dirty=Falsetools=self._tools_list# Filter tools based on tool_filterfiltered_tools=toolsifself.tool_filterisnotNone:filtered_tools=awaitself._apply_tool_filter(filtered_tools,run_context,agent)returnfiltered_toolsexcepthttpx.HTTPStatusErrorase:status_code=e.response.status_coderaiseUserError(f"Failed to list tools from MCP server '{self.name}': HTTP error{status_code}")fromeexcepthttpx.ConnectErrorase:raiseUserError(f"Failed to list tools from MCP server '{self.name}': Connection lost. "f"The server may have disconnected.")frome

call_toolasync

call_tool(tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult

Invoke a tool on the server.

Source code insrc/agents/mcp/server.py
asyncdefcall_tool(self,tool_name:str,arguments:dict[str,Any]|None,meta:dict[str,Any]|None=None,)->CallToolResult:"""Invoke a tool on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")session=self.sessionassertsessionisnotNonetry:ifmetaisNone:returnawaitself._run_with_retries(lambda:session.call_tool(tool_name,arguments))returnawaitself._run_with_retries(lambda:session.call_tool(tool_name,arguments,meta=meta))excepthttpx.HTTPStatusErrorase:status_code=e.response.status_coderaiseUserError(f"Failed to call tool '{tool_name}' on MCP server '{self.name}': "f"HTTP error{status_code}")fromeexcepthttpx.ConnectErrorase:raiseUserError(f"Failed to call tool '{tool_name}' on MCP server '{self.name}': Connection lost. "f"The server may have disconnected.")frome

list_promptsasync

list_prompts()->ListPromptsResult

List the prompts available on the server.

Source code insrc/agents/mcp/server.py
asyncdeflist_prompts(self,)->ListPromptsResult:"""List the prompts available on the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")returnawaitself.session.list_prompts()

get_promptasync

get_prompt(name:str,arguments:dict[str,Any]|None=None)->GetPromptResult

Get a specific prompt from the server.

Source code insrc/agents/mcp/server.py
asyncdefget_prompt(self,name:str,arguments:dict[str,Any]|None=None)->GetPromptResult:"""Get a specific prompt from the server."""ifnotself.session:raiseUserError("Server not initialized. Make sure you call `connect()` first.")returnawaitself.session.get_prompt(name,arguments)

invalidate_tools_cache

invalidate_tools_cache()

Invalidate the tools cache.

Source code insrc/agents/mcp/server.py
definvalidate_tools_cache(self):"""Invalidate the tools cache."""self._cache_dirty=True

[8]ページ先頭

©2009-2026 Movatter.jp