The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: keep the write-side outcome-uncertain verdict when no server can reconnect
teknium1081421d838dd
diff --git a/tests/tools/test_mcp_tool_session_expired.py b/tests/tools/test_mcp_tool_session_expired.pyindex a4c068cb5c0..4f078a3a510 100644--- a/tests/tools/test_mcp_tool_session_expired.py+++ b/tests/tools/test_mcp_tool_session_expired.py@@ -337,6 +337,13 @@ def test_session_expired_handler_returns_none_without_loop(monkeypatch):"Without an event loop, session-expired handler must fall ""through to caller's generic error path — not hang or raise.")+ # A write-capable call still gets the outcome-uncertain verdict: a generic "call failed"+ # would invite the model to replay a write that may have landed.+ out = _handle_session_expired_and_retry(+ "srv-noloop", RuntimeError("Invalid or expired session"), lambda: '{"ok": true}',+ "tools/call", call_may_have_side_effects=True,+ )+ assert out is not None and json.loads(out).get("outcome_uncertain") is Truefinally:mcp_tool._servers.pop("srv-noloop", None)diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.pyindex b9e11079e49..65667691ba9 100644--- a/tools/mcp_tool_handlers.py+++ b/tools/mcp_tool_handlers.py@@ -210,11 +210,13 @@ def _handle_session_expired_and_retry(server_name: str, exc: BaseException, retrhealed but the call is never re-run; the model gets an ``outcome_uncertain`` error instead (samecontract as the mid-call stdio death path). Callers pass True unless the tool is positively read-only."""- srv = _lookup_reconnectable_server(server_name, require_loop=True) if _is_session_expired_error(exc) else None- if srv is None:+ if not _is_session_expired_error(exc):return None+ srv = _lookup_reconnectable_server(server_name, require_loop=True)if call_may_have_side_effects:- reconnected = _loop._signal_reconnect_and_wait(+ # Even without a signallable server the outcome is still uncertain: a generic "call failed"+ # would invite the model to re-invoke a write that may already have landed.+ reconnected = srv is not None and _loop._signal_reconnect_and_wait(server_name, srv, op_description=f"{op_description} (write, no auto-retry)", timeout=15)if reconnected: # session state failed, not server health: no breaker strike_core._reset_server_error(server_name)@@ -226,6 +228,8 @@ def _handle_session_expired_and_retry(server_name: str, exc: BaseException, retrreturn tool_error(_SESSION_OUTCOME_UNCERTAIN_MSG.format(s=server_name, state="been re-established" if reconnected else "not recovered yet"),outcome_uncertain=True, server=server_name)+ if srv is None:+ return Nonelogger.info("MCP server '%s': %s failed with session-expired error (%s); signalling transport reconnect ""and retrying once.", server_name, op_description, exc)if not _loop._signal_reconnect_and_wait(server_name, srv, op_description=op_description, timeout=15):@@ -325,7 +329,7 @@ def _dispatch(server_name: str, server: Any, op: str, call, tool_timeout: float,@asynccontextmanager-async def _track_inflight_rpc(server: Any, server_name: str, op: str):+async def _track_inflight_rpc(server: Any, server_name: str, op: str, *, retry_safe: bool = True):"""Register the running RPC so teardown can fail it fast. A deliberate teardown(``_reconnecting`` set first) turns the cancel into a retryable RuntimeError; externalcancels propagate unchanged. Doubles without ``_inflight_tasks`` skip tracking.@@ -333,7 +337,8 @@ async def _track_inflight_rpc(server: Any, server_name: str, op: str):Every user-visible request family wraps its RPC in this context (#48069 salvage). If a deliberatereconnect/shutdown teardown cancels the task (``_fail_inflight_calls`` sets ``_reconnecting`` first),the cancel is converted into a clean retryable RuntimeError instead of a raw CancelledError; external- cancels (caller timeout, user interrupt) propagate unchanged.+ cancels (caller timeout, user interrupt) propagate unchanged. ``retry_safe=False`` (a write-capable+ ``tools/call``) words the error as outcome-uncertain instead of inviting a replay."""inflight, task = getattr(server, "_inflight_tasks", None), asyncio.current_task()tracked = task is not None and inflight is not None@@ -343,8 +348,9 @@ async def _track_inflight_rpc(server: Any, server_name: str, op: str):yieldexcept asyncio.CancelledError:if getattr(server, "_reconnecting", False):- raise RuntimeError(f"MCP {op} on '{server_name}' was aborted by a reconnect teardown; retry the "- f"request on the rebuilt session") from None+ advice = ("retry the request on the rebuilt session" if retry_safe else+ "the request may already have been dispatched, so verify its effect before re-invoking")+ raise RuntimeError(f"MCP {op} on '{server_name}' was aborted by a reconnect teardown; {advice}") from Noneraisefinally:if tracked:@@ -519,9 +525,12 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):server, error = _acquire_call_server(server_name, tool_timeout)if server is None:return error+ # Only a tool annotated readOnlyHint=True is replayed after session expiry; a 401 is always+ # pre-dispatch so the auth recoverer keeps its retry for every tool.+ read_only = _tool_is_read_only(server_name, tool_name)async def _call():- async with server._rpc_lock, _track_inflight_rpc(server, server_name, op):+ async with server._rpc_lock, _track_inflight_rpc(server, server_name, op, retry_safe=read_only):server._pending_call_context = contextvars.copy_context() # for the elicitation callbacktry:result = await _call_tool_racing_stdio_death(server, server_name, tool_name, args)@@ -534,10 +543,7 @@ def _make_tool_handler(server_name: str, tool_name: str, tool_timeout: float):def _on_failure(exc):_core._bump_server_error(server_name)logger.error("MCP tool %s/%s call failed: %s", server_name, tool_name, exc)- # Only a tool annotated readOnlyHint=True is replayed after session expiry; a 401 is always- # pre-dispatch so the auth recoverer keeps its retry for every tool.- session_expired = partial(_handle_session_expired_and_retry,- call_may_have_side_effects=not _tool_is_read_only(server_name, tool_name))+ session_expired = partial(_handle_session_expired_and_retry, call_may_have_side_effects=not read_only)return _dispatch(server_name, server, op, _call, tool_timeout,(_handle_stdio_child_exited_and_retry, _handle_auth_error_and_retry, session_expired),diff --git a/website/docs/reference/mcp-config-reference.md b/website/docs/reference/mcp-config-reference.mdindex 103fcbc2f50..21ca8ec2b08 100644--- a/website/docs/reference/mcp-config-reference.md+++ b/website/docs/reference/mcp-config-reference.md@@ -67,7 +67,7 @@ mcp_servers:| `auth` | string | HTTP | Authentication method. Set to `oauth` to enable OAuth 2.1 with PKCE || `sampling` | mapping | both | Server-initiated LLM request policy (see MCP guide) || `elicitation` | mapping | both | Server-initiated user-input requests. `enabled` (default `true`) and `timeout` in seconds (default `300`). Form-mode requests route through the approval surface; URL-mode is declined (see MCP guide) |-| `trust` | string | both | Trust tier: `full` (default) or `untrusted`. On an `untrusted` server, every write-capable tool call (any tool without a `readOnlyHint: true` annotation) requires user approval through the standard approval surface before it runs. `readOnlyHint` is a server-supplied *hint* — a lying server can at most skip approval for tools it claims are read-only, never gain extra access — so mark any server you don't fully control as `untrusted`. Unrecognized values are treated as `untrusted` (fail-closed) |+| `trust` | string | both | Trust tier: `full` (default) or `untrusted`. On an `untrusted` server, every write-capable tool call (any tool without a `readOnlyHint: true` annotation) requires user approval through the standard approval surface before it runs. `readOnlyHint` is a server-supplied *hint* — a lying server can at most skip approval for tools it claims are read-only, never gain extra access — so mark any server you don't fully control as `untrusted`. The same hint decides whether a call is transparently retried after the transport session expires mid-call: only `readOnlyHint: true` tools are replayed, while unannotated (write-capable) tools return an `outcome_uncertain` error — on a Streamable-HTTP server that expires idle sessions this means the first unannotated call after an idle period may fail and must be verified before re-invoking. Unrecognized values are treated as `untrusted` (fail-closed) |## Environment variable references