-
Notifications
You must be signed in to change notification settings - Fork 2.9k
fix: handle MCP upstream HTTP errors gracefully (fixes #879) #1948
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
608b4cf
f5df76d
ac61ac9
8dca6ff
d035018
1acb62c
1c5999d
78b3305
06b9aa6
3c89d8c
4643519
1cef4d4
a8fb751
46b4624
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -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): | ||||||
| # 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 | ||||||
|
||||||
| # 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 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
McpErrorimport 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.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree with this