Skip to content
Closed
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/agents/mcp/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,25 @@ async def invoke_mcp_tool(
try:
result = await server.call_tool(tool.name, json_data)
except Exception as e:
# Handle MCP errors (HTTP errors from upstream services) gracefully
# by returning a structured error response instead of crashing the run.
# This allows the agent to handle the error and decide how to respond.
# See: https://github.com/openai/openai-agents-python/issues/879
try:
from mcp.shared.exceptions import McpError

if isinstance(e, McpError):
Copy link

Copilot AI Oct 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The McpError import occurs inside the exception handler on every tool invocation error. Move this import to the module level to avoid repeated import overhead during error handling.

Copilot uses AI. Check for mistakes.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with this

# This is an HTTP error from upstream service - return structured error
logger.warning(f"MCP tool {tool.name} encountered upstream error: {e}")
error_response = {
"error": {"message": str(e), "tool": tool.name, "type": "upstream_error"}
}
return json.dumps(error_response)
except ImportError:
# MCP not available (Python < 3.10), fall through to original behavior
Copy link

Copilot AI Oct 21, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment incorrectly states 'MCP not available (Python < 3.10)' when handling ImportError. This is misleading because ImportError could occur for other reasons (missing package, incorrect import path). Consider clarifying that this handles cases where the mcp package or McpError class is unavailable.

Suggested change
# MCP not available (Python < 3.10), fall through to original behavior
# mcp package or McpError class unavailable (e.g., missing package, incorrect import path, or Python version); fall through to original behavior

Copilot uses AI. Check for mistakes.
pass

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

Expand Down