Skip to content

fix(mcp): recognize a 404 session loss reported with the server's own error body - #8500

Open
Koobi33 wants to merge 2 commits into
google:mainfrom
Koobi33:fix/mcp-session-not-found-detection
Open

Koobi33 wants to merge 2 commits into
google:mainfrom
Koobi33:fix/mcp-session-not-found-detection

Conversation

@Koobi33

@Koobi33 Koobi33 commented Dec 3, 2026

Copy link
Copy Markdown

Link to Issue or Description of Change

1. Link to an existing issue (if applicable):

Problem:
_is_session_terminated_error recognises a Streamable HTTP session loss only as INVALID_REQUEST with the exact message "Session terminated", which the 2.x MCP SDK uses when a 404 has no usable body. When the server's 404 carries a JSON-RPC error, the SDK surfaces that error instead: python-sdk servers send -32600 "Session not found" (older releases: "Not Found: Invalid or expired session ID", "Not Found: Session has been terminated"), TypeScript SDK servers send -32001 "Session not found". None of these match, so MCPSessionManager keeps the dead session and the agent loses its MCP tools until the process restarts.

Solution:
Also treat -32600 or -32001 as a session loss when the message says the session was not found, terminated or expired. -32600 for an ordinary bad request and unrelated -32001 errors still don't count.

Testing Plan

Unit Tests:

  • I have added or updated unit tests for my change.
  • All unit tests pass locally.

pytest tests/unittests/tools/mcp_tool: 507 passed. The new cases in TestIsSessionTerminatedError cover the three server spellings and an unrelated -32001 error; the 404-body cases fail without the change.

Manual End-to-End (E2E) Tests:

https://github.com/Koobi33/seams-lab/blob/main/repro/adk-session-not-found/repro.py runs an LlmAgent with a scripted model and an McpToolset against a python-sdk Streamable HTTP server and restarts the server between turns. Before: every turn after the restart gets "The tools you can call are: none". After: both turns call echo and get hello.

Checklist

  • I have read the CONTRIBUTING.md document.
  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • I have added tests that prove my fix is effective or that my feature works.
  • New and existing unit tests pass locally with my changes.
  • I have manually tested my changes end-to-end.
  • Any dependent changes have been merged and published in downstream modules.

Comment on lines +291 to 309
_SESSION_LOST_MESSAGE = re.compile(
r'session (?:not found|has been terminated)|expired session',
re.IGNORECASE,
)


def _reports_session_terminated(exc: McpError) -> bool:
"""Whether this MCP error is the server's own session-terminated report."""
if exc.error.code == _SESSION_TERMINATED_ERROR_CODE:
return True
if exc.error.code == _INVALID_REQUEST_ERROR_CODE and (
exc.error.message == _SESSION_TERMINATED_MESSAGE
):
return True
return bool(
exc.error.code == _INVALID_REQUEST_ERROR_CODE
and exc.error.message == _SESSION_TERMINATED_MESSAGE
exc.error.code
in (_INVALID_REQUEST_ERROR_CODE, _SESSION_NOT_FOUND_ERROR_CODE)
and _SESSION_LOST_MESSAGE.search(exc.error.message or '')
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

.search makes this match any INVALID_REQUEST that mentions a session somewhere, e.g. a tool raising "Browser session not found for tab 3" or "Login failed: expired session cookie". mcp_tool.run_async then drops the pooled session and retries on the assumption the tool never ran, so a non idempotent tool can run twice. Matching only the known transport spellings whole keeps the fix and closes that:

Suggested change
_SESSION_LOST_MESSAGE = re.compile(
r'session (?:not found|has been terminated)|expired session',
re.IGNORECASE,
)
def _reports_session_terminated(exc: McpError) -> bool:
"""Whether this MCP error is the server's own session-terminated report."""
if exc.error.code == _SESSION_TERMINATED_ERROR_CODE:
return True
if exc.error.code == _INVALID_REQUEST_ERROR_CODE and (
exc.error.message == _SESSION_TERMINATED_MESSAGE
):
return True
return bool(
exc.error.code == _INVALID_REQUEST_ERROR_CODE
and exc.error.message == _SESSION_TERMINATED_MESSAGE
exc.error.code
in (_INVALID_REQUEST_ERROR_CODE, _SESSION_NOT_FOUND_ERROR_CODE)
and _SESSION_LOST_MESSAGE.search(exc.error.message or '')
)
# Matched whole: a tool's own INVALID_REQUEST about some other session (a
# browser or chat session, say) must not pass for a lost MCP session, since that
# triggers a retry that assumes the tool never ran.
_SESSION_LOST_MESSAGE = re.compile(
r'session not found'
r'|not found: invalid or expired session id'
r'|not found: session has been terminated',
re.IGNORECASE,
)
def _reports_session_terminated(exc: McpError) -> bool:
"""Whether this MCP error is the server's own session-terminated report."""
if exc.error.code == _SESSION_TERMINATED_ERROR_CODE:
return True
if exc.error.code == _INVALID_REQUEST_ERROR_CODE and (
exc.error.message == _SESSION_TERMINATED_MESSAGE
):
return True
return bool(
exc.error.code
in (_INVALID_REQUEST_ERROR_CODE, _SESSION_NOT_FOUND_ERROR_CODE)
and _SESSION_LOST_MESSAGE.fullmatch((exc.error.message or '').strip())
)

plus a negative test in test_mcp_session_manager.py:

  @pytest.mark.parametrize(
      "message",
      [
          "Browser session not found for tab 3",
          "Chat session not found: abc123",
          "Login failed: expired session cookie",
      ],
  )
  def test_a_tools_own_session_error_is_not_session_terminated(self, message):
    assert not _is_session_terminated_error(make_mcp_error(-32600, message))

have this plus the negative test ready on my side, can put it up as a commit if that helps

…ives

A tool returning an MCP error that mentions "session" in its own message
(e.g., "Browser session not found for tab 3") could be misdetected as a
server session loss, triggering an automatic retry. The retry assumes
the tool never ran, so a non-idempotent call could execute twice.

Switch from .search to .fullmatch and list the exact server spellings.
Add a negative test with tool messages that must not trigger recovery.

Addresses: google#8500 (comment)
@Koobi33

Koobi33 commented Dec 4, 2026

Copy link
Copy Markdown
Author

@its-amann thanks for catching this. Pushed 7e4ead6: the message now has to match one of the known transport spellings whole (.fullmatch), so a tool's own "Browser session not found for tab 3" or "expired session cookie" no longer triggers recovery. Added negative tests for those. Recovery after a server restart still works against both python-sdk (-32600) and TypeScript SDK (-32001) servers.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

McpToolset never recovers from a Streamable HTTP session loss when the server's 404 carries a JSON-RPC error

2 participants