|
| 1 | +""" |
| 2 | +ServerSession Module |
| 3 | +
|
| 4 | +This module provides the ServerSession class, which manages communication between the |
| 5 | +server and client in the MCP (Model Context Protocol) framework. It is most commonly |
| 6 | +used in MCP servers to interact with the client. |
| 7 | +
|
| 8 | +Common usage pattern: |
| 9 | +``` |
| 10 | + server = Server(name) |
| 11 | +
|
| 12 | + @server.call_tool() |
| 13 | + async def handle_tool_call(ctx: RequestContext, arguments: dict[str, Any]) -> Any: |
| 14 | + # Check client capabilities before proceeding |
| 15 | + if ctx.session.check_client_capability( |
| 16 | + types.ClientCapabilities(experimental={"advanced_tools": True}) |
| 17 | + ): |
| 18 | + # Perform advanced tool operations |
| 19 | + result = await perform_advanced_tool_operation(arguments) |
| 20 | + else: |
| 21 | + # Fall back to basic tool operations |
| 22 | + result = await perform_basic_tool_operation(arguments) |
| 23 | +
|
| 24 | + return result |
| 25 | +
|
| 26 | + @server.list_prompts() |
| 27 | + async def handle_list_prompts(ctx: RequestContext) -> list[types.Prompt]: |
| 28 | + # Access session for any necessary checks or operations |
| 29 | + if ctx.session.client_params: |
| 30 | + # Customize prompts based on client initialization parameters |
| 31 | + return generate_custom_prompts(ctx.session.client_params) |
| 32 | + else: |
| 33 | + return default_prompts |
| 34 | +``` |
| 35 | +
|
| 36 | +The ServerSession class is typically used internally by the Server class and should not |
| 37 | +be instantiated directly by users of the MCP framework. |
| 38 | +""" |
| 39 | + |
1 | 40 | from enum import Enum
|
2 | 41 | from typing import Any
|
3 | 42 |
|
@@ -72,8 +111,10 @@ def check_client_capability(self, capability: types.ClientCapabilities) -> bool:
|
72 | 111 | return False
|
73 | 112 | # Check each experimental capability
|
74 | 113 | for exp_key, exp_value in capability.experimental.items():
|
75 |
| - if (exp_key not in client_caps.experimental or |
76 |
| - client_caps.experimental[exp_key] != exp_value): |
| 114 | + if ( |
| 115 | + exp_key not in client_caps.experimental |
| 116 | + or client_caps.experimental[exp_key] != exp_value |
| 117 | + ): |
77 | 118 | return False
|
78 | 119 |
|
79 | 120 | return True
|
@@ -117,7 +158,6 @@ async def _received_notification(
|
117 | 158 | "Received notification before initialization was complete"
|
118 | 159 | )
|
119 | 160 |
|
120 |
| - |
121 | 161 | async def send_log_message(
|
122 | 162 | self, level: types.LoggingLevel, data: Any, logger: str | None = None
|
123 | 163 | ) -> None:
|
|
0 commit comments