2
2
import logging
3
3
import warnings
4
4
from collections .abc import Awaitable , Callable
5
- from typing import Any
5
+ from typing import Any , Self
6
6
7
7
from anyio .streams .memory import MemoryObjectReceiveStream , MemoryObjectSendStream
8
8
from pydantic import AnyUrl
32
32
ReadResourceResult ,
33
33
Resource ,
34
34
ResourceReference ,
35
+ ServerCapabilities ,
35
36
ServerResult ,
36
37
SetLevelRequest ,
37
38
SubscribeRequest ,
40
41
41
42
logger = logging .getLogger (__name__ )
42
43
43
-
44
44
request_ctx : contextvars .ContextVar [RequestContext ] = contextvars .ContextVar (
45
45
"request_ctx"
46
46
)
@@ -53,6 +53,21 @@ def __init__(self, name: str):
53
53
self .notification_handlers : dict [type , Callable [..., Awaitable [None ]]] = {}
54
54
logger .info (f"Initializing server '{ name } '" )
55
55
56
+ def create_initialization_options (self ) -> types .InitializationOptions :
57
+ """Create initialization options from this server instance."""
58
+ def pkg_version (package : str ) -> str :
59
+ try :
60
+ from importlib .metadata import version
61
+ return version (package )
62
+ except Exception :
63
+ return "unknown"
64
+
65
+ return types .InitializationOptions (
66
+ server_name = self .name ,
67
+ server_version = pkg_version ("mcp_python" ),
68
+ capabilities = self .get_capabilities (),
69
+ )
70
+
56
71
@property
57
72
def request_context (self ) -> RequestContext :
58
73
"""If called outside of a request context, this will raise a LookupError."""
@@ -276,13 +291,26 @@ async def handler(req: CompleteRequest):
276
291
277
292
return decorator
278
293
294
+ def get_capabilities (self ) -> ServerCapabilities :
295
+ """Convert existing handlers to a ServerCapabilities object."""
296
+ def get_capability (req_type : type ) -> dict [str , Any ] | None :
297
+ return {} if req_type in self .request_handlers else None
298
+
299
+ return ServerCapabilities (
300
+ prompts = get_capability (ListPromptsRequest ),
301
+ resources = get_capability (ListResourcesRequest ),
302
+ tools = get_capability (ListPromptsRequest ),
303
+ logging = get_capability (SetLevelRequest )
304
+ )
305
+
279
306
async def run (
280
307
self ,
281
308
read_stream : MemoryObjectReceiveStream [JSONRPCMessage | Exception ],
282
309
write_stream : MemoryObjectSendStream [JSONRPCMessage ],
310
+ initialization_options : types .InitializationOptions
283
311
):
284
312
with warnings .catch_warnings (record = True ) as w :
285
- async with ServerSession (read_stream , write_stream ) as session :
313
+ async with ServerSession (read_stream , write_stream , initialization_options ) as session :
286
314
async for message in session .incoming_messages :
287
315
logger .debug (f"Received message: { message } " )
288
316
0 commit comments