Skip to content

Commit 608b4cf

Browse files
committed
fix: handle MCP upstream HTTP errors gracefully (fixes #879)
When MCP tools receive non-2xx HTTP responses from upstream services (e.g., 422, 404, 500), catch McpError and return structured JSON error instead of raising AgentsException. This allows agents to handle errors gracefully and decide how to respond (retry, inform user, etc.) instead of crashing the entire run. Backward compatible: programming errors still raise AgentsException. Fixes #879
1 parent 748ac80 commit 608b4cf

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/agents/mcp/util.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,25 @@ async def invoke_mcp_tool(
202202
try:
203203
result = await server.call_tool(tool.name, json_data)
204204
except Exception as e:
205+
# Handle MCP errors (HTTP errors from upstream services) gracefully
206+
# by returning a structured error response instead of crashing the run.
207+
# This allows the agent to handle the error and decide how to respond.
208+
# 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
222+
223+
# For other exceptions (programming errors, etc.), raise as before
205224
logger.error(f"Error invoking MCP tool {tool.name}: {e}")
206225
raise AgentsException(f"Error invoking MCP tool {tool.name}: {e}") from e
207226

0 commit comments

Comments
 (0)