Skip to content

Commit 79c615e

Browse files
committed
_close_and_recreate_session
Signed-off-by: Denis Tu <dmarshaltu@gmail.com>
1 parent 23f57d3 commit 79c615e

1 file changed

Lines changed: 21 additions & 15 deletions

File tree

python/packages/kagent-adk/src/kagent/adk/_mcp_toolset.py

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,9 @@
1212

1313
logger = logging.getLogger("kagent_adk." + __name__)
1414

15-
_PING_TIMEOUT_SECONDS = 2.0
16-
_SESSION_REVALIDATE_TIMEOUT_SECONDS = 5.0
15+
# Short timeouts to fail fast on the request path; avoid adding latency when session is valid.
16+
_PING_TIMEOUT_SECONDS = 1.0
17+
_SESSION_REVALIDATE_TIMEOUT_SECONDS = 2.0
1718
_JSONRPC_METHOD_NOT_FOUND = -32601
1819

1920

@@ -54,6 +55,17 @@ class KAgentMCPSessionManager(MCPSessionManager):
5455
the session from the cache and create a new one.
5556
"""
5657

58+
async def _close_and_recreate_session(
59+
self, headers: dict[str, str] | None, reason: str
60+
) -> ClientSession:
61+
"""Close the cached session (best-effort) and create a new one."""
62+
logger.warning("%s", reason)
63+
try:
64+
await self.close()
65+
except Exception as close_exc:
66+
logger.debug("Non-fatal error while closing stale session: %s", close_exc)
67+
return await super().create_session(headers)
68+
5769
async def create_session(self, headers: dict[str, str] | None = None) -> ClientSession:
5870
session = await super().create_session(headers)
5971

@@ -63,26 +75,20 @@ async def create_session(self, headers: dict[str, str] | None = None) -> ClientS
6375
if _is_server_alive_error(exc):
6476
pass
6577
else:
66-
logger.warning(
67-
"MCP session failed ping validation, invalidating cached session and creating a fresh one"
78+
return await self._close_and_recreate_session(
79+
headers,
80+
"MCP session failed ping validation, invalidating cached session and creating a fresh one",
6881
)
69-
try:
70-
await self.close()
71-
except Exception as close_exc:
72-
logger.debug("Non-fatal error while closing stale session: %s", close_exc)
73-
return await super().create_session(headers)
7482

7583
try:
7684
await asyncio.wait_for(session.list_tools(), timeout=_SESSION_REVALIDATE_TIMEOUT_SECONDS)
7785
return session
7886
except Exception as exc:
7987
if _is_session_invalid_error(exc):
80-
logger.warning("MCP session invalid (e.g. 404), pruning from cache and creating a fresh one")
81-
try:
82-
await self.close()
83-
except Exception as close_exc:
84-
logger.debug("Non-fatal error while closing stale session: %s", close_exc)
85-
return await super().create_session(headers)
88+
return await self._close_and_recreate_session(
89+
headers,
90+
"MCP session invalid (e.g. 404), pruning from cache and creating a fresh one",
91+
)
8692
raise
8793

8894

0 commit comments

Comments
 (0)