|
15 | 15 | from ..tracing import FunctionSpanData, get_current_span, mcp_tools_span |
16 | 16 | from ..util._types import MaybeAwaitable |
17 | 17 |
|
| 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 | + |
18 | 26 | if TYPE_CHECKING: |
19 | 27 | from mcp.types import Tool as MCPTool |
20 | 28 |
|
@@ -206,19 +214,13 @@ async def invoke_mcp_tool( |
206 | 214 | # by returning a structured error response instead of crashing the run. |
207 | 215 | # This allows the agent to handle the error and decide how to respond. |
208 | 216 | # 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) |
222 | 224 |
|
223 | 225 | # For other exceptions (programming errors, etc.), raise as before |
224 | 226 | logger.error(f"Error invoking MCP tool {tool.name}: {e}") |
|
0 commit comments