Skip to content

Commit ac61ac9

Browse files
committed
refactor: Move McpError import to module level
Address review feedback from @seratch and Copilot AI. Previously, McpError was imported inside the exception handler on every tool invocation error, causing repeated import overhead. This change moves the import to module level with proper fallback for Python < 3.10 (where mcp package is not available).
1 parent f5df76d commit ac61ac9

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/agents/mcp/util.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,14 @@
1515
from ..tracing import FunctionSpanData, get_current_span, mcp_tools_span
1616
from ..util._types import MaybeAwaitable
1717

18+
# Import McpError if available (requires Python >= 3.10)
19+
# This allows us to distinguish MCP HTTP errors from programming errors.
20+
# See: https://github.com/openai/openai-agents-python/issues/879
21+
try:
22+
from mcp.shared.exceptions import McpError
23+
except ImportError:
24+
McpError = None # type: ignore
25+
1826
if TYPE_CHECKING:
1927
from mcp.types import Tool as MCPTool
2028

@@ -206,19 +214,13 @@ async def invoke_mcp_tool(
206214
# by returning a structured error response instead of crashing the run.
207215
# This allows the agent to handle the error and decide how to respond.
208216
# See: https://github.com/openai/openai-agents-python/issues/879
209-
try:
210-
from mcp.shared.exceptions import McpError
211-
212-
if isinstance(e, McpError):
213-
# This is an HTTP error from upstream service - return structured error
214-
logger.warning(f"MCP tool {tool.name} encountered upstream error: {e}")
215-
error_response = {
216-
"error": {"message": str(e), "tool": tool.name, "type": "upstream_error"}
217-
}
218-
return json.dumps(error_response)
219-
except ImportError:
220-
# MCP not available (Python < 3.10), fall through to original behavior
221-
pass
217+
if McpError is not None and isinstance(e, McpError):
218+
# This is an HTTP error from upstream service - return structured error
219+
logger.warning(f"MCP tool {tool.name} encountered upstream error: {e}")
220+
error_response = {
221+
"error": {"message": str(e), "tool": tool.name, "type": "upstream_error"}
222+
}
223+
return json.dumps(error_response)
222224

223225
# For other exceptions (programming errors, etc.), raise as before
224226
logger.error(f"Error invoking MCP tool {tool.name}: {e}")

0 commit comments

Comments
 (0)