22import logging
33import warnings
44from collections .abc import Awaitable , Callable
5- from typing import Any
5+ from typing import Any , Self
66
77from anyio .streams .memory import MemoryObjectReceiveStream , MemoryObjectSendStream
88from pydantic import AnyUrl
3232 ReadResourceResult ,
3333 Resource ,
3434 ResourceReference ,
35+ ServerCapabilities ,
3536 ServerResult ,
3637 SetLevelRequest ,
3738 SubscribeRequest ,
4041
4142logger = logging .getLogger (__name__ )
4243
43-
4444request_ctx : contextvars .ContextVar [RequestContext ] = contextvars .ContextVar (
4545 "request_ctx"
4646)
@@ -53,6 +53,21 @@ def __init__(self, name: str):
5353 self .notification_handlers : dict [type , Callable [..., Awaitable [None ]]] = {}
5454 logger .info (f"Initializing server '{ name } '" )
5555
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+
5671 @property
5772 def request_context (self ) -> RequestContext :
5873 """If called outside of a request context, this will raise a LookupError."""
@@ -276,13 +291,26 @@ async def handler(req: CompleteRequest):
276291
277292 return decorator
278293
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+
279306 async def run (
280307 self ,
281308 read_stream : MemoryObjectReceiveStream [JSONRPCMessage | Exception ],
282309 write_stream : MemoryObjectSendStream [JSONRPCMessage ],
310+ initialization_options : types .InitializationOptions
283311 ):
284312 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 :
286314 async for message in session .incoming_messages :
287315 logger .debug (f"Received message: { message } " )
288316
0 commit comments