88from contextlib import AbstractAsyncContextManager , AsyncExitStack
99from datetime import timedelta
1010from pathlib import Path
11- from typing import TYPE_CHECKING , Any , Callable , Literal , TypeVar
11+ from typing import TYPE_CHECKING , Any , Callable , Literal , TypeVar , cast
1212
1313import httpx
1414
2626from ..exceptions import UserError
2727from ..logger import logger
2828from ..run_context import RunContextWrapper
29+ from ..tool import ToolErrorFunction
2930from ..util ._types import MaybeAwaitable
3031from .util import HttpClientFactory , ToolFilter , ToolFilterContext , ToolFilterStatic
3132
@@ -48,6 +49,13 @@ class RequireApprovalObject(TypedDict, total=False):
4849
4950T = TypeVar ("T" )
5051
52+
53+ class _UnsetType :
54+ pass
55+
56+
57+ _UNSET = _UnsetType ()
58+
5159if TYPE_CHECKING :
5260 from ..agent import AgentBase
5361
@@ -59,6 +67,7 @@ def __init__(
5967 self ,
6068 use_structured_content : bool = False ,
6169 require_approval : RequireApprovalSetting = None ,
70+ failure_error_function : ToolErrorFunction | None | _UnsetType = _UNSET ,
6271 ):
6372 """
6473 Args:
@@ -70,11 +79,16 @@ def __init__(
7079 require_approval: Approval policy for tools on this server. Accepts "always"/"never",
7180 a dict of tool names to those values, a boolean, or an object with always/never
7281 tool lists (mirroring TS requireApproval). Normalized into a needs_approval policy.
82+ failure_error_function: Optional function used to convert MCP tool failures into
83+ a model-visible error message. If explicitly set to None, tool errors will be
84+ raised instead of converted. If left unset, the agent-level configuration (or
85+ SDK default) will be used.
7386 """
7487 self .use_structured_content = use_structured_content
7588 self ._needs_approval_policy = self ._normalize_needs_approval (
7689 require_approval = require_approval
7790 )
91+ self ._failure_error_function = failure_error_function
7892
7993 @abc .abstractmethod
8094 async def connect (self ):
@@ -207,6 +221,14 @@ async def _needs_approval(
207221
208222 return bool (policy )
209223
224+ def _get_failure_error_function (
225+ self , agent_failure_error_function : ToolErrorFunction | None
226+ ) -> ToolErrorFunction | None :
227+ """Return the effective error handler for MCP tool failures."""
228+ if self ._failure_error_function is _UNSET :
229+ return agent_failure_error_function
230+ return cast (ToolErrorFunction | None , self ._failure_error_function )
231+
210232
211233class _MCPServerWithClientSession (MCPServer , abc .ABC ):
212234 """Base class for MCP servers that use a `ClientSession` to communicate with the server."""
@@ -221,6 +243,7 @@ def __init__(
221243 retry_backoff_seconds_base : float = 1.0 ,
222244 message_handler : MessageHandlerFnT | None = None ,
223245 require_approval : RequireApprovalSetting = None ,
246+ failure_error_function : ToolErrorFunction | None | _UnsetType = _UNSET ,
224247 ):
225248 """
226249 Args:
@@ -247,10 +270,15 @@ def __init__(
247270 require_approval: Approval policy for tools on this server. Accepts "always"/"never",
248271 a dict of tool names to those values, a boolean, or an object with always/never
249272 tool lists.
273+ failure_error_function: Optional function used to convert MCP tool failures into
274+ a model-visible error message. If explicitly set to None, tool errors will be
275+ raised instead of converted. If left unset, the agent-level configuration (or
276+ SDK default) will be used.
250277 """
251278 super ().__init__ (
252279 use_structured_content = use_structured_content ,
253280 require_approval = require_approval ,
281+ failure_error_function = failure_error_function ,
254282 )
255283 self .session : ClientSession | None = None
256284 self .exit_stack : AsyncExitStack = AsyncExitStack ()
@@ -682,6 +710,7 @@ def __init__(
682710 retry_backoff_seconds_base : float = 1.0 ,
683711 message_handler : MessageHandlerFnT | None = None ,
684712 require_approval : RequireApprovalSetting = None ,
713+ failure_error_function : ToolErrorFunction | None | _UnsetType = _UNSET ,
685714 ):
686715 """Create a new MCP server based on the stdio transport.
687716
@@ -713,6 +742,10 @@ def __init__(
713742 ClientSession.
714743 require_approval: Approval policy for tools on this server. Accepts "always"/"never",
715744 a dict of tool names to those values, or an object with always/never tool lists.
745+ failure_error_function: Optional function used to convert MCP tool failures into
746+ a model-visible error message. If explicitly set to None, tool errors will be
747+ raised instead of converted. If left unset, the agent-level configuration (or
748+ SDK default) will be used.
716749 """
717750 super ().__init__ (
718751 cache_tools_list ,
@@ -723,6 +756,7 @@ def __init__(
723756 retry_backoff_seconds_base ,
724757 message_handler = message_handler ,
725758 require_approval = require_approval ,
759+ failure_error_function = failure_error_function ,
726760 )
727761
728762 self .params = StdioServerParameters (
@@ -788,6 +822,7 @@ def __init__(
788822 retry_backoff_seconds_base : float = 1.0 ,
789823 message_handler : MessageHandlerFnT | None = None ,
790824 require_approval : RequireApprovalSetting = None ,
825+ failure_error_function : ToolErrorFunction | None | _UnsetType = _UNSET ,
791826 ):
792827 """Create a new MCP server based on the HTTP with SSE transport.
793828
@@ -821,6 +856,10 @@ def __init__(
821856 ClientSession.
822857 require_approval: Approval policy for tools on this server. Accepts "always"/"never",
823858 a dict of tool names to those values, or an object with always/never tool lists.
859+ failure_error_function: Optional function used to convert MCP tool failures into
860+ a model-visible error message. If explicitly set to None, tool errors will be
861+ raised instead of converted. If left unset, the agent-level configuration (or
862+ SDK default) will be used.
824863 """
825864 super ().__init__ (
826865 cache_tools_list ,
@@ -831,6 +870,7 @@ def __init__(
831870 retry_backoff_seconds_base ,
832871 message_handler = message_handler ,
833872 require_approval = require_approval ,
873+ failure_error_function = failure_error_function ,
834874 )
835875
836876 self .params = params
@@ -899,6 +939,7 @@ def __init__(
899939 retry_backoff_seconds_base : float = 1.0 ,
900940 message_handler : MessageHandlerFnT | None = None ,
901941 require_approval : RequireApprovalSetting = None ,
942+ failure_error_function : ToolErrorFunction | None | _UnsetType = _UNSET ,
902943 ):
903944 """Create a new MCP server based on the Streamable HTTP transport.
904945
@@ -933,6 +974,10 @@ def __init__(
933974 ClientSession.
934975 require_approval: Approval policy for tools on this server. Accepts "always"/"never",
935976 a dict of tool names to those values, or an object with always/never tool lists.
977+ failure_error_function: Optional function used to convert MCP tool failures into
978+ a model-visible error message. If explicitly set to None, tool errors will be
979+ raised instead of converted. If left unset, the agent-level configuration (or
980+ SDK default) will be used.
936981 """
937982 super ().__init__ (
938983 cache_tools_list ,
@@ -943,6 +988,7 @@ def __init__(
943988 retry_backoff_seconds_base ,
944989 message_handler = message_handler ,
945990 require_approval = require_approval ,
991+ failure_error_function = failure_error_function ,
946992 )
947993
948994 self .params = params
0 commit comments