liveBook · Manning

Session()

As explained in Build a Multi-Agent System (from Scratch)

session() is an MCPToolProvider method that returns an established MCP session, creating it if necessary.

When an agent needs tools from an MCP server, MCPToolProvider.session() supplies the connection used to communicate with it. This asynchronous method returns an established mcp.ClientSession, creating and initializing one if necessary. Later calls reuse the persistent session. section 5.2.1 section 5.1.3

The session lifecycle coordinates connection setup and cleanup:

  • On a first call, session() starts _create_session() as an asyncio task. Concurrent first-time callers reuse an in-flight creation task. section 5.2.1
  • The creation task opens the configured transport, initializes a ClientSession, stores it, and signals readiness. It then waits for a shutdown signal to keep the connection alive. section 5.2.1
  • session() waits for readiness or completion of the creation task. Once ready, callers can reuse the stored session. section 5.2.1
  • close() signals shutdown, awaits the creation task, and clears the stored session, task, and events. section 5.2.1
Listing 5.3 Implementing MCPToolProvider: session()
# llm_agents_from_scratch/tools/mcp/provider.py
… #A
 
 
class MCPToolProvider:
    """MCP Tool Provider class."""
    … #B
 
    async def session(self) -> ClientSession:
        """Get the persistent session.""" #C
 
        if not self._session_ready.is_set(): #D
            # Reuse an in-flight creation task so that concurrent first-time
            # callers share one session instead of each starting their own.
            if self._session_task is None or self._session_task.done(): #E
                self._session_task = asyncio.create_task(self._create_session())
            session_task = self._session_task
            session_ready_task = asyncio.create_task(self._session_ready.wait())
 
            # Wait for the first of these two tasks to complete.
            # If session_ready_task completes first, then everything is
            # good and the session was created successfully. Otherwise, the
            # session_ready event was never set, meaning an error occurred.
            done, _pending = await asyncio.wait( #F
                [session_task, session_ready_task],
                return_when=asyncio.FIRST_COMPLETED,
            )
 
            if session_task in done: #G
                session_ready_task.cancel()  # clean-up session ready task
                session_task.result()  # re-raises the encountered error
        return self._session  #H

Inspect the asynchronous session() implementation and its coordination of concurrent callers. section 5.2.1

Discover tools through a session

For a Hailstone stdio server, configure MCPToolProvider with mcp.StdioServerParameters and call await provider.get_tools(). The provider obtains a session with await self.session(), calls session.list_tools(), and wraps the returned definitions as MCPTool instances. Call await provider.close() when the connection is no longer needed. section 5.2.1

The provider supports stdio and streamable HTTP connections. Although the described MCP 2.0 protocol revision removes sessions from the protocol, the mcp Python library version 2.0 still represents connections with client sessions. section 5.1.3 section 5.2.1

How Build a Multi-Agent System (from Scratch) covers it

How deep it goes
Implements asynchronous creation, concurrent-call coordination, readiness signaling, reuse, and shutdown.
Examples
Demonstrates a Hailstone stdio server, compares first and cached session calls, and discovers its tool.
What it assumes
Assumes working knowledge of the mcp library and asyncio tasks while introducing asyncio events for coroutine signaling.
What you can do after
Builds it from scratch as part of an MCPToolProvider that manages a persistent client connection.
How it connects
Connects MCP clients, tool discovery, asyncio tasks and events, and stdio and streamable HTTP transports.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build a Multi-Agent System (from Scratch). The section links point to the parts of the book it draws on.