@@ -107,6 +107,46 @@ class ClientSession(
107107 types .ServerNotification ,
108108 ]
109109):
110+ """A client session for communicating with an MCP server.
111+
112+ This class provides a high-level interface for MCP client operations, including
113+ tool calling, resource management, prompt handling, and protocol initialization.
114+ It manages the bidirectional communication channel with an MCP server and handles
115+ protocol-level concerns like message validation and capability negotiation.
116+
117+ The session supports various MCP capabilities:
118+
119+ - Tool execution with structured output validation
120+ - Resource access and subscription management
121+ - Prompt template retrieval and completion
122+ - Progress notifications and logging
123+ - Custom sampling, elicitation, and root listing callbacks
124+
125+ Args:
126+ read_stream: Stream for receiving messages from the server.
127+ write_stream: Stream for sending messages to the server.
128+ read_timeout_seconds: Optional timeout for read operations.
129+ sampling_callback: Optional callback for handling sampling requests from the server.
130+ elicitation_callback: Optional callback for handling elicitation requests from the server.
131+ list_roots_callback: Optional callback for handling root listing requests from the server.
132+ logging_callback: Optional callback for handling log messages from the server.
133+ message_handler: Optional custom handler for incoming messages and exceptions.
134+ client_info: Optional client implementation information.
135+
136+ Example:
137+ ```python
138+ async with create_client_session() as session:
139+ # Initialize the session
140+ await session.initialize()
141+
142+ # List available tools
143+ tools = await session.list_tools()
144+
145+ # Call a tool
146+ result = await session.call_tool("my_tool", {"arg": "value"})
147+ ```
148+ """
149+
110150 def __init__ (
111151 self ,
112152 read_stream : MemoryObjectReceiveStream [SessionMessage | Exception ],
@@ -135,6 +175,17 @@ def __init__(
135175 self ._tool_output_schemas : dict [str , dict [str , Any ] | None ] = {}
136176
137177 async def initialize (self ) -> types .InitializeResult :
178+ """Initialize the MCP session with the server.
179+
180+ Sends an initialization request to establish capabilities and protocol version.
181+ This must be called before any other operations can be performed.
182+
183+ Returns:
184+ Server's initialization response containing capabilities and metadata
185+
186+ Raises:
187+ McpError: If initialization fails or protocol version is unsupported
188+ """
138189 sampling = types .SamplingCapability () if self ._sampling_callback is not _default_sampling_callback else None
139190 elicitation = (
140191 types .ElicitationCapability () if self ._elicitation_callback is not _default_elicitation_callback else None
@@ -288,7 +339,81 @@ async def call_tool(
288339 read_timeout_seconds : timedelta | None = None ,
289340 progress_callback : ProgressFnT | None = None ,
290341 ) -> types .CallToolResult :
291- """Send a tools/call request with optional progress callback support."""
342+ """Execute a tool on the connected MCP server.
343+
344+ This method sends a tools/call request to execute a specific tool with provided
345+ arguments. The server will validate the arguments against the tool's input schema
346+ and return structured or unstructured content based on the tool's configuration.
347+
348+ For tools that return structured output, the result will be automatically validated
349+ against the tool's output schema if one is defined. Tools may also return various
350+ content types including text, images, and embedded resources.
351+
352+ Args:
353+ name: The name of the tool to execute. Must match a tool exposed by the server.
354+ arguments: Optional dictionary of arguments to pass to the tool. The structure
355+ must match the tool's input schema. Defaults to None for tools that don't
356+ require arguments.
357+ read_timeout_seconds: Optional timeout for the tool execution. If not specified,
358+ uses the session's default read timeout. Useful for long-running tools.
359+ progress_callback: Optional callback function to receive progress updates during
360+ tool execution. The callback receives progress notifications as they're sent
361+ by the server.
362+
363+ Returns:
364+ CallToolResult containing the tool's response. The result includes:
365+ - content: List of content blocks (text, images, embedded resources)
366+ - structuredContent: Validated structured data if the tool has an output schema
367+ - isError: Boolean indicating if the tool execution failed
368+
369+ Raises:
370+ RuntimeError: If the tool returns structured content that doesn't match its
371+ output schema, or if the tool name is not found on the server.
372+ ValidationError: If the provided arguments don't match the tool's input schema.
373+ TimeoutError: If the tool execution exceeds the specified timeout.
374+
375+ Example:
376+ ```python
377+ # Simple tool call without arguments
378+ result = await session.call_tool("ping")
379+
380+ # Tool call with arguments
381+ result = await session.call_tool("add", {"a": 5, "b": 3})
382+
383+ # Access text content
384+ for content in result.content:
385+ if isinstance(content, types.TextContent):
386+ print(content.text)
387+
388+ # Access structured output (if available)
389+ if result.structuredContent:
390+ user_data = result.structuredContent
391+ print(f"Result: {user_data}")
392+
393+ # Handle tool execution errors
394+ if result.isError:
395+ print("Tool execution failed")
396+
397+ # Long-running tool with progress tracking
398+ def on_progress(progress_token, progress, total, message):
399+ percent = (progress / total) * 100 if total else 0
400+ print(f"Progress: {percent:.1f}% - {message}")
401+
402+ result = await session.call_tool(
403+ "long_task",
404+ {"steps": 10},
405+ read_timeout_seconds=timedelta(minutes=5),
406+ progress_callback=on_progress
407+ )
408+ ```
409+
410+ Note:
411+ Tools may return different content types:
412+ - TextContent: Plain text responses
413+ - ImageContent: Generated images with MIME type and binary data
414+ - EmbeddedResource: File contents or external resources
415+ - Structured data via structuredContent when output schema is defined
416+ """
292417
293418 result = await self .send_request (
294419 types .ClientRequest (
0 commit comments