
    {hh                    B   U d Z ddlmZ ddlZddlZddlZddlZddlm	Z	m
Z
mZmZ ddlmZmZmZ ddlmZmZmZmZ ddlZddlZddlmZmZ ddlmZ dd	lmZ ddlm Z  dd
l!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z.m/Z/ ddl0m1Z1  ejd                  e3      Z4 ede      Z5 ede      Z6e7e8ef   Z9de:d<   ee jv                     Z<de:d<   e=e<e9f   Z>de:d<    ej~                  d      Z@de:d<    G d d      ZAed!d       ZB G d dee5e6f         ZCd"d ZDy)#a/  
MCP Server Module

This module provides a framework for creating an MCP (Model Context Protocol) server.
It allows you to easily define and handle various types of requests and notifications
in an asynchronous manner.

Usage:
1. Create a Server instance:
   server = Server("your_server_name")

2. Define request handlers using decorators:
   @server.list_prompts()
   async def handle_list_prompts() -> list[types.Prompt]:
       # Implementation

   @server.get_prompt()
   async def handle_get_prompt(
       name: str, arguments: dict[str, str] | None
   ) -> types.GetPromptResult:
       # Implementation

   @server.list_tools()
   async def handle_list_tools() -> list[types.Tool]:
       # Implementation

   @server.call_tool()
   async def handle_call_tool(
       name: str, arguments: dict | None
   ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
       # Implementation

   @server.list_resource_templates()
   async def handle_list_resource_templates() -> list[types.ResourceTemplate]:
       # Implementation

3. Define notification handlers if needed:
   @server.progress_notification()
   async def handle_progress(
       progress_token: str | int, progress: float, total: float | None,
       message: str | None
   ) -> None:
       # Implementation

4. Run the server:
   async def main():
       async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
           await server.run(
               read_stream,
               write_stream,
               InitializationOptions(
                   server_name="your_server_name",
                   server_version="your_version",
                   capabilities=server.get_capabilities(
                       notification_options=NotificationOptions(),
                       experimental_capabilities={},
                   ),
               ),
           )

   asyncio.run(main())

The Server class provides methods to register handlers for various MCP requests and
notifications. It automatically manages the request context and handles incoming
messages from the client.
    )annotationsN)AsyncIterator	AwaitableCallableIterable)AbstractAsyncContextManagerAsyncExitStackasynccontextmanager)AnyGeneric	TypeAliascast)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl)TypeVar)ReadResourceContents)InitializationOptions)ServerSession)stdio_server)RequestContext)McpError)ServerMessageMetadataSessionMessage)RequestResponderLifespanResultT)defaultRequestTr   StructuredContentUnstructuredContentCombinationContentrequest_ctxz?contextvars.ContextVar[RequestContext[ServerSession, Any, Any]]c                  &    e Zd Z	 	 	 d	 	 	 	 	 ddZy)NotificationOptionsc                .    || _         || _        || _        y N)prompts_changedresources_changedtools_changed)selfr'   r(   r)   s       [/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/mcp/server/lowlevel/server.py__init__zNotificationOptions.__init__m   s      /!2*    N)FFF)r'   boolr(   r.   r)   r.   )__name__
__module____qualname__r,    r-   r+   r$   r$   l   s.     !&"'#	++  + 	+r-   r$   c                  K   i  yw)zDefault lifespan context manager that does nothing.

    Args:
        server: The server instance this lifespan is managing

    Returns:
        An empty context object
    Nr2   )_s    r+   lifespanr5   x   s      Hs   	c                  *   e Zd Zddef	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 ddZ	 	 	 	 	 	 ddZe	 	 dd       Zd Z	d Z
d Zd	 Zd
 Zd Zd Zd Zd ZddZd dZddd!dZd Zd Z	 	 d"	 	 	 	 	 	 	 	 	 d#dZ	 d$	 	 	 	 	 	 	 d%dZ	 	 	 	 	 	 	 	 	 	 d&dZd'dZy)(ServerNc                    || _         || _        || _        || _        t        j
                  t        i| _        i | _        i | _	        t        j                  d|       y )NzInitializing server %r)nameversioninstructionsr5   typesPingRequest_ping_handlerrequest_handlersnotification_handlers_tool_cacheloggerdebug)r*   r9   r:   r;   r5   s        r+   r,   zServer.__init__   sZ     	( }[
 RT"24-t4r-   c           	         dd}t        | j                  | j                  r| j                  n |d      | j                  |xs
 t	               |xs i       | j
                        S )z8Create initialization options from this server instance.c                >    	 ddl m}  ||       S # t        $ r Y yw xY w)Nr   )r:   unknown)importlib.metadatar:   	Exception)packager:   s     r+   pkg_versionz9Server.create_initialization_options.<locals>.pkg_version   s*    6w'' s    	mcp)server_nameserver_versioncapabilitiesr;   )rI   strreturnrO   )r   r9   r:   get_capabilitiesr$   r;   )r*   notification_optionsexperimental_capabilitiesrJ   s       r+   create_initialization_optionsz$Server.create_initialization_options   s^    	 %		+/<<4<<[=O..$=(;(=)/R **
 	
r-   c                v   d}d}d}d}d}t         j                  | j                  v r t        j                  |j                        }t         j
                  | j                  v r!t        j                  d|j                        }t         j                  | j                  v r t        j                  |j                        }t         j                  | j                  v rt        j                         }t         j                  | j                  v rt        j                         }t        j                  ||||||      S )z9Convert existing handlers to a ServerCapabilities object.N)listChangedF)	subscriberV   )prompts	resourcestoolsloggingexperimentalcompletions)r<   ListPromptsRequestr?   PromptsCapabilityr'   ListResourcesRequestResourcesCapabilityr(   ListToolsRequestToolsCapabilityr)   SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilities)r*   rR   rS   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilitys           r+   rQ   zServer.get_capabilities   s     "#!!% ##t'<'<<!&!8!8EYEiEi!j %%)>)>>#(#<#<-A-S-S$ 
 !!T%:%::$44AUAcAcd   D$9$99!&!8!8!:   D$9$99%*%@%@%B"''&*"&2.
 	
r-   c                *    t         j                         S )zFIf called outside of a request context, this will raise a LookupError.)r"   get)r*   s    r+   request_contextzServer.request_context   s    
   r-   c                     d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz)Registering handler for PromptListRequestc                   K            d {   }t        j                  t        j                  |            S 7 -w)N)rX   )r<   ServerResultListPromptsResult)r4   rX   funcs     r+   handlerz7Server.list_prompts.<locals>.decorator.<locals>.handler   s1      $,))%*A*A'*RSS '   ><.>r4   r   )rB   rC   r?   r<   r^   rv   rw   r*   s   ` r+   	decoratorz&Server.list_prompts.<locals>.decorator   s4    LLDET ?FD!!%":":;Kr-   )rv   z+Callable[[], Awaitable[list[types.Prompt]]]r2   r*   r{   s   ` r+   list_promptszServer.list_prompts       	 r-   c                     	 	 d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz(Registering handler for GetPromptRequestc                   K    | j                   j                  | j                   j                         d {   }t        j                  |      S 7 wr&   )paramsr9   	argumentsr<   rt   )req
prompt_getrv   s     r+   rw   z5Server.get_prompt.<locals>.decorator.<locals>.handler   s?     #'

9M9M#NN
))*55 Os   5AAA)r   ztypes.GetPromptRequest)rB   rC   r?   r<   GetPromptRequestrz   s   ` r+   r{   z$Server.get_prompt.<locals>.decorator   s5     LLCD6 =DD!!%"8"89Kr-   )rv   zHCallable[[str, dict[str, str] | None], Awaitable[types.GetPromptResult]]r2   r|   s   ` r+   
get_promptzServer.get_prompt   s    
	Z
	 r-   c                     d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz,Registering handler for ListResourcesRequestc                   K            d {   }t        j                  t        j                  |            S 7 -w)N)rY   )r<   rt   ListResourcesResult)r4   rY   rv   s     r+   rw   z9Server.list_resources.<locals>.decorator.<locals>.handler  s1     "&&L	))%*C*Ci*XYY )rx   ry   )rB   rC   r?   r<   r`   rz   s   ` r+   r{   z(Server.list_resources.<locals>.decorator  s5    LLGHZ AHD!!%"<"<=Kr-   )rv   z-Callable[[], Awaitable[list[types.Resource]]]r2   r|   s   ` r+   list_resourceszServer.list_resources  r~   r-   c                     d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz4Registering handler for ListResourceTemplatesRequestc                   K            d {   }t        j                  t        j                  |            S 7 -w)N)resourceTemplates)r<   rt   ListResourceTemplatesResult)r4   	templatesrv   s     r+   rw   zBServer.list_resource_templates.<locals>.decorator.<locals>.handler  s2     "&&L	))%*K*K^g*hii )rx   ry   )rB   rC   r?   r<   ListResourceTemplatesRequestrz   s   ` r+   r{   z1Server.list_resource_templates.<locals>.decorator  s5    LLOPj IPD!!%"D"DEKr-   )rv   z5Callable[[], Awaitable[list[types.ResourceTemplate]]]r2   r|   s   ` r+   list_resource_templateszServer.list_resource_templates  r~   r-   c                     	 	 d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz+Registering handler for ReadResourceRequestc                N   K     j                   j                         d {   }d fd}|xxxt        d x\   n xt        d x\   n  n) } t	        j
                  dt        d        ||d       }n{ xt        d xV\   }|D cg c]  } ||j                  |j                        ! }}t        j                  t        j                  |            S   	 t        dt        |             t        j                  t        j                  |g            S 7 c c}w w)	Nc                J   | xxt         d x4\   }  t        j                  j                  j                  | |xs d      S   xt
        d xT\   } dd l}t        j                  j                  j                  |j                  |       j                         |xs d      S   y )Nr2   z
text/plain)uritextmimeTyper   zapplication/octet-stream)r   blobr   )
rO   r<   TextResourceContentsr   r   bytesbase64BlobResourceContents	b64encodedecode)data	mime_typer   r   s      r+   create_contentzPServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.create_content'  s    *SU]#(#=#=$'JJNN%))2)Bl$  + -UW_)#(#=#=$'JJNN%+%5%5d%;%B%B%D)2)P6P$  -r-   r2   zdReturning str or bytes from read_resource is deprecated. Use Iterable[ReadResourceContents] instead.   )
stacklevel)contentsz+Unexpected return type from read_resource: )r   zstr | bytesr   
str | None)r   r   rO   r   warningswarnDeprecationWarningr   contentr   r<   rt   ReadResourceResult
ValueErrortype)	r   resultr   r   r   r   content_itemcontents_listrv   s	   `       r+   rw   z8Server.read_resource.<locals>.decorator.<locals>.handler$  s    #CJJNN33" 00 J.'(	 #1t"< 1 0/mu)]iN<+?+?AWAWX) )  %11!44)6  	 0 (+VW[\bWcVd)eff)),,") Q 4:)s#    D%DA&D%$D /A0D% D%)r   ztypes.ReadResourceRequest)rB   rC   r?   r<   ReadResourceRequestrz   s   ` r+   r{   z'Server.read_resource.<locals>.decorator  s7     LLFG-^ @GD!!%";";<Kr-   )rv   zKCallable[[AnyUrl], Awaitable[str | bytes | Iterable[ReadResourceContents]]]r2   r|   s   ` r+   read_resourcezServer.read_resource  s    5	]5	n r-   c                     d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz'Registering handler for SetLevelRequestc                   K    | j                   j                         d {    t        j                  t        j                               S 7 +wr&   )r   levelr<   rt   EmptyResultr   rv   s    r+   rw   z<Server.set_logging_level.<locals>.decorator.<locals>.handler\  s>     3::++,,,))%*;*;*=>> -    AA,A)r   ztypes.SetLevelRequest)rB   rC   r?   r<   rd   rz   s   ` r+   r{   z+Server.set_logging_level.<locals>.decoratorY  s3    LLBC? <CD!!%"7"78Kr-   )rv   z/Callable[[types.LoggingLevel], Awaitable[None]]r2   r|   s   ` r+   set_logging_levelzServer.set_logging_levelX  r~   r-   c                     d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz(Registering handler for SubscribeRequestc                   K    | j                   j                         d {    t        j                  t        j                               S 7 +wr&   r   r   r<   rt   r   r   s    r+   rw   z=Server.subscribe_resource.<locals>.decorator.<locals>.handleri  <     3::>>***))%*;*;*=>> +r   )r   ztypes.SubscribeRequest)rB   rC   r?   r<   SubscribeRequestrz   s   ` r+   r{   z,Server.subscribe_resource.<locals>.decoratorf  s3    LLCD? =DD!!%"8"89Kr-   rv   z#Callable[[AnyUrl], Awaitable[None]]r2   r|   s   ` r+   subscribe_resourcezServer.subscribe_resourcee  r~   r-   c                     d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz*Registering handler for UnsubscribeRequestc                   K    | j                   j                         d {    t        j                  t        j                               S 7 +wr&   r   r   s    r+   rw   z?Server.unsubscribe_resource.<locals>.decorator.<locals>.handlerv  r   r   )r   ztypes.UnsubscribeRequest)rB   rC   r?   r<   UnsubscribeRequestrz   s   ` r+   r{   z.Server.unsubscribe_resource.<locals>.decorators  s3    LLEF? ?FD!!%":":;Kr-   r   r2   r|   s   ` r+   unsubscribe_resourcezServer.unsubscribe_resourcer  r~   r-   c                     d fd}|S )Nc                |     t         j                  d       d fd}|j                  t        j                  <    S )Nz(Registering handler for ListToolsRequestc                   K            d {   }j                   j                          |D ]  }|j                   |j                  <    t        j                  t        j
                  |            S 7 gw)N)rZ   )rA   clearr9   r<   rt   ListToolsResult)r4   rZ   toolrv   r*   s      r+   rw   z5Server.list_tools.<locals>.decorator.<locals>.handler  sf     "f  &&(! 7D26D$$TYY/7))%*?*?e*LMM %s   A8A6A(A8ry   )rB   rC   r?   r<   rb   rz   s   ` r+   r{   z$Server.list_tools.<locals>.decorator  s4    LLCDN =DD!!%"8"89Kr-   )rv   z)Callable[[], Awaitable[list[types.Tool]]]r2   r|   s   ` r+   
list_toolszServer.list_tools  s    	 r-   c                    t        j                  t        j                  t        j                  d|      gd            S )z3Create a ServerResult with an error CallToolResult.r   r   r   T)r   isError)r<   rt   CallToolResultTextContent)r*   error_messages     r+   _make_error_resultzServer._make_error_result  s9    !!  **]KL
 	
r-   c                N  K   || j                   vr]t        j                  | j                  v rAt        j                  d|        | j                  t        j                     d       d{    | j                   j                  |      }|t        j                  d|       |S 7 9w)z|Get tool definition from cache, refreshing if necessary.

        Returns the Tool object if found, None otherwise.
        z(Tool cache miss for %s, refreshing cacheNz5Tool '%s' not listed, no validation will be performed)rA   r<   rb   r?   rB   rC   ro   warning)r*   	tool_namer   s      r+   _get_cached_tool_definitionz"Server._get_cached_tool_definition  s     
 D,,,%%)>)>>GSCd++E,B,BCDIII##I.<NNRT]^ Js   A'B%)B#*:B%T)validate_inputc                    	 	 d fd}|S )a  Register a tool call handler.

        Args:
            validate_input: If True, validates input against inputSchema. Default is True.

        The handler validates input against inputSchema (if validate_input=True), calls the tool function,
        and builds a CallToolResult with the results:
        - Unstructured content (iterable of ContentBlock): returned in content
        - Structured content (dict): returned in structuredContent, serialized JSON text returned in content
        - Both: returned in content and structuredContent

        If outputSchema is defined, validates structuredContent or errors if missing.
        c                ~     t         j                  d       d fd}|j                  t        j                  <    S )Nz'Registering handler for CallToolRequestc                  K   	 | j                   j                  }| j                   j                  xs i }	j                  |       d {   }
r$|r"	 t	        j
                  ||j                          ||       d {   }t        |t              r"t        |      dk(  rt        t        |      \  }}nt        |t              r>t        t         |      }t#        j$                  dt'        j(                  |d            g}nFt+        |d      rt        t,        |      }d }n'	j                  dt/        |      j0                         S |rA|j2                  5|	j                  d	      S 	 t	        j
                  ||j2                         t#        j4                  t#        j6                  t9        |      |d            S 7 y# t        j                  $ r(}	j                  d|j                         cY d }~S d }~ww xY w7 # t        j                  $ r(}	j                  d
|j                         cY d }~S d }~ww xY w# t:        $ r$}	j                  t=        |            cY d }~S d }~ww xY ww)N)instanceschemazInput validation error: r   r   )indentr   __iter__z"Unexpected return type from tool: zOOutput validation error: outputSchema defined but no structured output returnedzOutput validation error: F)r   structuredContentr   )r   r9   r   r   
jsonschemavalidateinputSchemaValidationErrorr   message
isinstancetuplelenr   r!   dictr   r<   r   jsondumpshasattrr    r   r/   outputSchemart   r   listrH   rO   )r   r   r   r   eresultsunstructured_contentmaybe_structured_contentrv   r*   r   s           r+   rw   z4Server.call_tool.<locals>.decorator.<locals>.handler  sF    5; #

I #

 4 4 :I!%!A!A)!LLD &$c&//4K[K[\
 %)I$>>G
 "'51c'la6GIMN`biIjF,.F#GT2378I73S0050A0AvTXT^T^_fopTq0r/s, *5/34G/Q,370#669[\`ah\i\r\r[s7tuu  1 1 =3;#'#:#: q$ h * 3 3=U^b^o^o p
 !--,,$()=$>.F$) U M  *99 c#'#:#:=UVWV_V_U`;a#bbc ?8 $.#=#= h'+'>'>AZ[\[d[dZe?f'g gh ! ;223q6::;s   I4AI 	G
I !G 4I  HC	I 
I4 I +I4-!H 3I I4I H G;5H 6I :I4;H  I IH<6I7I ;I4<II 	I1I,&I1'I4,I11I4)r   ztypes.CallToolRequest)rB   rC   r?   r<   CallToolRequest)rv   rw   r*   r   s   ` r+   r{   z#Server.call_tool.<locals>.decorator  s6     LLBC6;p <CD!!%"7"78Kr-   )rv   zVCallable[..., Awaitable[UnstructuredContent | StructuredContent | CombinationContent]]r2   )r*   r   r{   s   `` r+   	call_toolzServer.call_tool  s    A	A	F r-   c                     	 	 d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz,Registering handler for ProgressNotificationc                   K    | j                   j                  | j                   j                  | j                   j                  | j                   j                         d {    y 7 wr&   )r   progressTokenprogresstotalr   r   s    r+   rw   z@Server.progress_notification.<locals>.decorator.<locals>.handler  sM     JJ,,JJ''JJ$$JJ&&	  s   AA*"A(#A*)r   ztypes.ProgressNotification)rB   rC   r@   r<   ProgressNotificationrz   s   ` r+   r{   z/Server.progress_notification.<locals>.decorator  s6     LLGH FMD&&u'A'ABKr-   )rv   zGCallable[[str | int, float, float | None, str | None], Awaitable[None]]r2   r|   s   ` r+   progress_notificationzServer.progress_notification  s    	Y	  r-   c                     	 	 d fd}|S )z7Provides completions for prompts and resource templatesc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz'Registering handler for CompleteRequestc           	     D  K    | j                   j                  | j                   j                  | j                   j                         d {   }t	        j
                  t	        j                  ||            S t	        j                  g d d                   S 7 Pw)N)valuesr   hasMore)
completion)r   refargumentcontextr<   rt   CompleteResult
Completion)r   r  rv   s     r+   rw   z5Server.completion.<locals>.decorator.<locals>.handler  s     #'



8K8KSZZM_M_#``
))((%1 $.  #--RtTR  as   A
B BAB )r   ztypes.CompleteRequest)rB   rC   r?   r<   rf   rz   s   ` r+   r{   z$Server.completion.<locals>.decorator  s5     LLBC <CD!!%"7"78Kr-   )rv   zCallable[[types.PromptReference | types.ResourceTemplateReference, types.CompletionArgument, types.CompletionContext | None], Awaitable[types.Completion | None]]r2   r|   s   ` r+   r  zServer.completion  s    		2 r-   c           
     N  K   t               4 d {   }|j                  | j                  |              d {   }|j                  t        ||||             d {   }t	        j
                         4 d {   }	|j                  2 3 d {   }
t        j                  d|
       |	j                  | j                  |
|||       ?7 7 7 p7 U7 B6 d d d       d {  7   n# 1 d {  7  sw Y   nxY wd d d       d {  7   y # 1 d {  7  sw Y   y xY ww)N)	statelesszReceived message: %s)r	   enter_async_contextr5   r   anyiocreate_task_groupincoming_messagesrB   rC   
start_soon_handle_message)r*   read_streamwrite_streaminitialization_optionsraise_exceptionsr  stacklifespan_contextsessiontgr   s              r+   runz
Server.run.  s      "# 	 	u%*%>%>t}}T?R%SS!55 *'	 G ..0 
 
B%,%>%> 	 	'LL!7AMM,,((	S
	%>
 
 
 
 
	 	 	 	 	s   D%CD%$DC%DC D<C=D C)CC
C7C)D%DDDCC)D"C%#D)C;	/C20C;	7D>D%	D
D%D"DD"D%c           	        K   t        j                  d      5 }|xxt        d xC\  t        j                  d x.\  }} |5  | j                  |||||       d {    d d d        n3  t        j                  d x\  }| j                  |       d {    n |D ]7  }	t        j                  d|	j                  j                  |	j                         9 	 d d d        y 7 # 1 sw Y   QxY w7 Z# 1 sw Y   y xY ww)NT)recordrequest)rootzWarning: %s: %s)r   catch_warningsr   r<   ClientRequest_handle_requestClientNotification_handle_notificationrB   infocategoryr/   r   )
r*   r   r  r  r  wr   	respondernotifyr   s
             r+   r  zServer._handle_messageU  s      $$D1 
	[QY%Le.A.A.KY" n"227CJZ\lmmmn n Z --:33F;;; ;  [-w/?/?/H/H'//Z[
	[ 
	[
 nn n <
	[ 
	[sS   C>)C2C$C"C$ 5C2C0AC2	C>"C$$C-	)C22C;7C>c           	       K   t         j                  dt        |      j                         | j                  j                  t        |            x}rt         j                  dt        |      j                         d }	 d }|j                  0t        |j                  t              r|j                  j                  }t        j                  t        |j                  |j                  |||            } ||       d {   }	|t        j)                  |       	 |j3                  |	       d {    n<|j3                  t-        j.                  t,        j4                  d             d {    t         j                  d	       y 7 # t         $ r}
|
j"                  }	Y d }
~
d }
~
wt%        j&                         $ r; t         j                  d|j                         Y |t        j)                  |       y y t*        $ r0}
|r|
t-        j.                  dt1        |
      d       }	Y d }
~
'd }
~
ww xY w# |t        j)                  |       w w xY w7  7 w)
NzProcessing request of type %szDispatching request of type %sr   z4Request %s cancelled - duplicate response suppressedr   )coder   r   zMethod not found)r.  r   zResponse sent)rB   r(  r   r/   r?   ro   rC   message_metadatar   r   rp   r"   setr   
request_idrequest_metar   errorr  get_cancelled_exc_classresetrH   r<   	ErrorDatarO   respondMETHOD_NOT_FOUND)r*   r   r   r  r  r  rw   tokenrequest_dataresponseerrs              r+   r%  zServer._handle_requesth  s     	3T#Y5G5GH++//S	::7:LL949;M;MNE!-#++7JwG_G_av<w#*#;#;#K#KL $"**,,( , ")- $%%e,//(+++////.   	_%7 . %99002 J&&  $%%e, %  P#I ??3s8$OP $%%e, % ,s   A;I>B F	 >F?F	 ,I/I0<I,I-IF	 		H/F#H2 #:H/H2 I7H/?%H*$H2 *H//H2 2IIIc                  K   | j                   j                  t        |            x}r;t        j	                  dt        |      j
                         	  ||       d {    y y 7 # t        $ r t        j                  d       Y y w xY ww)Nz#Dispatching notification of type %sz*Uncaught exception in notification handler)r@   ro   r   rB   rC   r/   rH   	exception)r*   r,  rw   s      r+   r'  zServer._handle_notification  s|     0044T&\BB7BLL>V@U@UVOfo%%	 C & O  !MNOs<   ABA' A%A' #B%A' 'BBBB)r9   rO   r:   r   r;   r   r5   z[Callable[[Server[LifespanResultT, RequestT]], AbstractAsyncContextManager[LifespanResultT]])NN)rR   zNotificationOptions | NonerS   z dict[str, dict[str, Any]] | NonerP   r   )rR   r$   rS   zdict[str, dict[str, Any]]rP   ztypes.ServerCapabilities)rP   z8RequestContext[ServerSession, LifespanResultT, RequestT])r   rO   rP   types.ServerResult)r   rO   rP   ztypes.Tool | None)r   r.   )FF)
r  z5MemoryObjectReceiveStream[SessionMessage | Exception]r  z&MemoryObjectSendStream[SessionMessage]r  r   r  r.   r  r.   )F)r   z`RequestResponder[types.ClientRequest, types.ServerResult] | types.ClientNotification | Exceptionr  r   r  r   r  r.   )
r   z9RequestResponder[types.ClientRequest, types.ServerResult]r   r   r  r   r  r   r  r.   )r,  r   )r/   r0   r1   r5   r,   rT   rQ   propertyrp   r}   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r%  r'  r2   r-   r+   r7   r7      s    ##' 55 5 !	5

5. <@FJ
8
 $D
 
	
6)
1)
 $=)
 
"	)
V !	A! !8t"
  37 Rh&N "'
  %J% =% !6	% % %X "'[q[ [ *	[
 [&9&J9& 9& 	9&
 *9& 9&vOr-   r7   c                X   K   t        j                  t        j                               S wr&   )r<   rt   r   r   s    r+   r>   r>     s      e//122s   (*)r4   z!Server[LifespanResultT, RequestT]rP   zAsyncIterator[dict[str, Any]])r!  ztypes.PingRequestrP   r?  )E__doc__
__future__r   _annotationscontextvarsr   r[   r   collections.abcr   r   r   r   
contextlibr   r	   r
   typingr   r   r   r   r  r   anyio.streams.memoryr   r   pydanticr   typing_extensionsr   	mcp.typesr<    mcp.server.lowlevel.helper_typesr   mcp.server.modelsr   mcp.server.sessionr   mcp.server.stdior   mcp.shared.contextr   mcp.shared.exceptionsr   mcp.shared.messager   r   mcp.shared.sessionr   	getLoggerr/   rB   r   r   r   rO   r   __annotations__ContentBlockr    r   r!   
ContextVarr"   r$   r5   r7   r>   r2   r-   r+   <module>rY     s!  AF 3     H H W W 0 0   R  %  A 3 , 9 - * D /			8	$+S9:s+  $CH~ 9 -!)%*<*<!= Y = %&9;L&L M I M Pf{OeOefsOtL t	+ 	+ 	 	eOW_h./ eOP3r-   