Skip to content

fix: add timeout for MCP ClientSession #364

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

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/google/adk/tools/mcp_tool/mcp_session_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import functools
import sys
from typing import Any, TextIO
from datetime import timedelta
import anyio
from pydantic import BaseModel

Expand Down Expand Up @@ -133,6 +134,7 @@ async def create_session(self) -> ClientSession:
connection_params=self.connection_params,
exit_stack=self.exit_stack,
errlog=self.errlog,

)

@classmethod
Expand All @@ -142,6 +144,7 @@ async def initialize_session(
connection_params: StdioServerParameters | SseServerParams,
exit_stack: AsyncExitStack,
errlog: TextIO = sys.stderr,
timeout: int = 5,
) -> ClientSession:
"""Initializes an MCP client session.

Expand All @@ -150,6 +153,7 @@ async def initialize_session(
exit_stack: AsyncExitStack to manage the session lifecycle.
errlog: (Optional) TextIO stream for error logging. Use only for
initializing a local stdio MCP session.
timeout: (Optional) Timeout for the session communication.

Returns:
ClientSession: The initialized MCP client session.
Expand All @@ -171,6 +175,7 @@ async def initialize_session(
)

transports = await exit_stack.enter_async_context(client)
session = await exit_stack.enter_async_context(ClientSession(*transports))

session = await exit_stack.enter_async_context(ClientSession(*transports, read_timeout_seconds=timedelta(seconds=timeout)))
await session.initialize()
return session