When an asynchronous provider opens an MCP server session, it needs to signal when the session is ready and when to shut it down. asyncio.Event lets coroutines send these signals safely. section 5.2.1
In the provider’s session lifecycle, events:
- Mark readiness with set() after session initialization; callers can wait() for that signal. section 5.2.1
- Signal shutdown with set(); the session coroutine waits for that event before closing. section 5.2.1
Listing 5.2 Implementing MCPToolProvider: _create_session()
# llm_agents_from_scratch/tools/mcp/provider.py
… #A
import httpx2
from mcp.client.stdio import stdio_client
from mcp.client.streamable_http import streamable_http_client
HTTP_TIMEOUT = httpx2.Timeout(30.0, read=300.0)
class MCPToolProvider:
"""MCP Tool Provider class."""
… #B
async def _create_session(self) -> None:
"""Create and maintain persistent session...""" #C
if self.stdio_params: #D
async with stdio_client(self.stdio_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize() #E
self._session = session #F
self._session_ready.set() #G
# Wait for shutdown signal
await self._shutdown_event.wait() #H
else: #I
async with (
httpx2.AsyncClient(
headers=self.streamable_http_headers,
timeout=HTTP_TIMEOUT,
follow_redirects=True,
) as http_client,
streamable_http_client(
str(self.streamable_http_url),
http_client=http_client,
) as (read_stream, write_stream),
):
async with ClientSession(
read_stream,
write_stream,
) as session:
await session.initialize()
self._session = session
self._session_ready.set()
# Wait for shutdown signal
await self._shutdown_event.wait()See the session coroutine set the readiness event and wait for the shutdown signal. section 5.2.1
