
    [ǻiۂ                    r   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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/ ddl0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9  ejt                  e;      Z< ede      Z= ede      Z>e?e@ef   ZAdeBd<   ee!j                     ZDdeBd<   eEeDeAf   ZFdeBd<    ej                  d      ZHdeBd<    G d d      ZIed$d        ZJ G d! d"ee=e>f         ZKd%d#ZLy)&ay  
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(request: types.ListPromptsRequest) -> types.ListPromptsResult:
       # 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(request: types.ListToolsRequest) -> types.ListToolsResult:
       # 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)Experimental)ExperimentalHandlers)create_call_wrapper)ReadResourceContents)InitializationOptions)ServerSession)RequestContext)McpErrorUrlElicitationRequiredError)ServerMessageMetadataSessionMessage)RequestResponder)validate_and_warn_tool_name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       X/opt/lhia/marcimex/agent/venv/lib/python3.12/site-packages/mcp/server/lowlevel/server.py__init__zNotificationOptions.__init__q   s      /!2*    N)FFF)r+   boolr,   r2   r-   r2   )__name__
__module____qualname__r0    r1   r/   r(   r(   p   s.     !&"'#	++  + 	+r1   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
    Nr6   )_s    r/   lifespanr9   |   s      Hs   	c                  H   e Zd Zddddef	 	 	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 ddZ	 	 	 	 	 	 ddZe	 	 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 | _        d | _        t        j                  d|       y )NzInitializing server %r)nameversioninstructionswebsite_urliconsr9   typesPingRequest_ping_handlerrequest_handlersnotification_handlers_tool_cache_experimental_handlersloggerdebug)r.   r=   r>   r?   r@   rA   r9   s          r/   r0   zServer.__init__   sq     	(&
 }[
 RT"24CG#-t4r1   c           	         dd}t        | j                  | j                  r| j                  n |d      | j                  |xs
 t	               |xs i       | j
                  | j                  | 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?   r@   rA   )rP   strreturnrV   )r   r=   r>   get_capabilitiesr(   r?   r@   rA   )r.   notification_optionsexperimental_capabilitiesrQ   s       r/   create_initialization_optionsz$Server.create_initialization_options   sn    	 %		+/<<4<<[=O..$=(;(=)/R **((**

 
	
r1   c                   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                  ||||||      }| j                   r| j                   j#                  |       |S )z9Convert existing handlers to a ServerCapabilities object.N)listChangedF)	subscriber]   )prompts	resourcestoolsloggingexperimentalcompletions)rB   ListPromptsRequestrE   PromptsCapabilityr+   ListResourcesRequestResourcesCapabilityr,   ListToolsRequestToolsCapabilityr-   SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilitiesrH   update_capabilities)	r.   rY   rZ   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilityrU   s	            r/   rX   zServer.get_capabilities   sB    "#!!% ##t'<'<<!&!8!8EYEiEi!j %%)>)>>#(#<#<-A-S-S$ 
 !!T%:%::$44AUAcAcd   D$9$99!&!8!8!:   D$9$99%*%@%@%B"//&*"&2.
 &&'';;LIr1   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    
   r1   c                ~    | j                   &t        | | j                  | j                        | _         | j                   S )zExperimental APIs for tasks and other features.

        WARNING: These APIs are experimental and may change without notice.
        )rH   r   rE   rF   rx   s    r/   rc   zServer.experimental   s:     &&.*>tTEZEZ\`\v\v*wD'***r1   c                     	 	 d fd}|S )Nc                    t         j                  d       t        | t        j                        dfd}|j
                  t        j                  <   | S )Nz)Registering handler for PromptListRequestc                   K    |        d {   }t        |t        j                        rt        j                  |      S t        j                  t        j                  |            S 7 \w)N)r_   )
isinstancerB   ListPromptsResultServerResultreqresultwrappers     r/   handlerz7Server.list_prompts.<locals>.decorator.<locals>.handler  sW     &s|+fe&=&=> --f55 !--e.E.Ef.UVV ,   A.A,AA.)r   ztypes.ListPromptsRequest)rI   rJ   r   rB   re   rE   funcr   r   r.   s     @r/   	decoratorz&Server.list_prompts.<locals>.decorator  sH     LLDE)$0H0HIGW ?FD!!%":":;Kr1   )r   zvCallable[[], Awaitable[list[types.Prompt]]] | Callable[[types.ListPromptsRequest], Awaitable[types.ListPromptsResult]]r6   r.   r   s   ` r/   list_promptszServer.list_prompts  s    	W	( r1   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*   )paramsr=   	argumentsrB   r   )r   
prompt_getr   s     r/   r   z5Server.get_prompt.<locals>.decorator.<locals>.handler  s?     #'

9M9M#NN
))*55 Os   5AAA)r   ztypes.GetPromptRequest)rI   rJ   rE   rB   GetPromptRequestr   r   r.   s   ` r/   r   z$Server.get_prompt.<locals>.decorator  s5     LLCD6 =DD!!%"8"89Kr1   )r   zHCallable[[str, dict[str, str] | None], Awaitable[types.GetPromptResult]]r6   r   s   ` r/   
get_promptzServer.get_prompt  s    
	Z
	 r1   c                     	 	 d fd}|S )Nc                    t         j                  d       t        | t        j                        dfd}|j
                  t        j                  <   | S )Nz,Registering handler for ListResourcesRequestc                   K    |        d {   }t        |t        j                        rt        j                  |      S t        j                  t        j                  |            S 7 \w)N)r`   )r~   rB   ListResourcesResultr   r   s     r/   r   z9Server.list_resources.<locals>.decorator.<locals>.handler1  sX     &s|+fe&?&?@ --f55 !--e.G.GRX.YZZ ,r   )r   ztypes.ListResourcesRequest)rI   rJ   r   rB   rg   rE   r   s     @r/   r   z(Server.list_resources.<locals>.decorator)  sI     LLGH)$0J0JKG[ AHD!!%"<"<=Kr1   )r   z|Callable[[], Awaitable[list[types.Resource]]] | Callable[[types.ListResourcesRequest], Awaitable[types.ListResourcesResult]]r6   r   s   ` r/   list_resourceszServer.list_resources(  s    	[	( r1   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)rB   r   ListResourceTemplatesResult)r8   	templatesr   s     r/   r   zBServer.list_resource_templates.<locals>.decorator.<locals>.handlerC  s2     "&&L	))%*K*K^g*hii )s   ><.>)r8   r   )rI   rJ   rE   rB   ListResourceTemplatesRequestr   s   ` r/   r   z1Server.list_resource_templates.<locals>.decorator@  s5    LLOPj IPD!!%"D"DEKr1   )r   z5Callable[[], Awaitable[list[types.ResourceTemplate]]]r6   r   s   ` r/   list_resource_templateszServer.list_resource_templates?      	 r1   c                     	 	 d fd}|S )Nc                z     t         j                  d       d fd}|j                  t        j                  <    S )Nz+Registering handler for ReadResourceRequestc                j   K     j                   j                         d {   }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b\   }|D cg c]+  } ||j                  |j                  t        |dd             - }}t        j                  t        j                  |            S   	 t        dt        |             t        j                  t        j                  |g            S 7 c c}w w)Nmetac                ^   |d|ini }| xxt         d x5\   }  t        j                  dj                  j                  | |xs dd|S   xt
        d xU\   } t        j                  dj                  j                  t        j                  |       j                         |xs dd|S   y )N_metar6   z
text/plain)uritextmimeTypezapplication/octet-stream)r   blobr   )
rV   rB   TextResourceContentsr   r   bytesBlobResourceContentsbase64	b64encodedecode)data	mime_typer   meta_kwargsr   s       r/   create_contentzPServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.create_contentU  s    EIEU7D/[]K*SU]#(#=#= $$'JJNN%))2)Bl$ #.	$  + -UW_#(#=#= $$'JJNN%+%5%5d%;%B%B%D)2)P6P$ #.	$  -r1   r6   zdReturning str or bytes from read_resource is deprecated. Use Iterable[ReadResourceContents] instead.   )
stacklevel)contentsz+Unexpected return type from read_resource: r*   )r   zstr | bytesr   
str | Noner   zdict[str, Any] | None)r   r   rV   r   warningswarnDeprecationWarningr   contentr   getattrrB   r   ReadResourceResult
ValueErrortype)	r   r   r   r   r   r   content_itemcontents_listr   s	   `       r/   r   z8Server.read_resource.<locals>.decorator.<locals>.handlerR  s2    #CJJNN33& 00 J.'(	 #1t"< 1 0/
 19	) !- + , 4 4l6L6LgVbdjlpNq) )  %11!44)6   0 (+VW[\bWcVd)eff)),,") [ 4>)s#    D3D+A'D30D.<A0D3.D3)r   ztypes.ReadResourceRequest)rI   rJ   rE   rB   ReadResourceRequestr   s   ` r/   r   z'Server.read_resource.<locals>.decoratorM  s7     LLFG2h @GD!!%";";<Kr1   )r   zKCallable[[AnyUrl], Awaitable[str | bytes | Iterable[ReadResourceContents]]]r6   r   s   ` r/   read_resourcezServer.read_resourceL  s    :	]:	x r1   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   levelrB   r   EmptyResultr   r   s    r/   r   z<Server.set_logging_level.<locals>.decorator.<locals>.handler  s>     3::++,,,))%*;*;*=>> -    AA,A)r   ztypes.SetLevelRequest)rI   rJ   rE   rB   rk   r   s   ` r/   r   z+Server.set_logging_level.<locals>.decorator  s3    LLBC? <CD!!%"7"78Kr1   )r   z/Callable[[types.LoggingLevel], Awaitable[None]]r6   r   s   ` r/   set_logging_levelzServer.set_logging_level  r   r1   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   rB   r   r   r   s    r/   r   z=Server.subscribe_resource.<locals>.decorator.<locals>.handler  <     3::>>***))%*;*;*=>> +r   )r   ztypes.SubscribeRequest)rI   rJ   rE   rB   SubscribeRequestr   s   ` r/   r   z,Server.subscribe_resource.<locals>.decorator  s3    LLCD? =DD!!%"8"89Kr1   r   z#Callable[[AnyUrl], Awaitable[None]]r6   r   s   ` r/   subscribe_resourcezServer.subscribe_resource  r   r1   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/   r   z?Server.unsubscribe_resource.<locals>.decorator.<locals>.handler  r   r   )r   ztypes.UnsubscribeRequest)rI   rJ   rE   rB   UnsubscribeRequestr   s   ` r/   r   z.Server.unsubscribe_resource.<locals>.decorator  s3    LLEF? ?FD!!%":":;Kr1   r   r6   r   s   ` r/   unsubscribe_resourcezServer.unsubscribe_resource  r   r1   c                     	 	 d fd}|S )Nc                    t         j                  d       t        | t        j                        dfd}|j
                  t        j                  <   | S )Nz(Registering handler for ListToolsRequestc                  K    |        d {   }t        |t        j                        rT|j                  D ]0  }t	        |j
                         |j                  |j
                  <   2 t        j                  |      S j                  j                          |D ]0  }t	        |j
                         |j                  |j
                  <   2 t        j                  t        j                  |            S 7 w)N)ra   )	r~   rB   ListToolsResultra   r   r=   rG   r   clear)r   r   toolr.   r   s      r/   r   z5Server.list_tools.<locals>.decorator.<locals>.handler  s     &s|+ fe&;&;< & ;3DII>6:((3; !--f55 $$**, & ;3DII>6:((3; !--e.C.C&.QRR! ,s   C<C:C+C<)r   ztypes.ListToolsRequest)rI   rJ   r   rB   ri   rE   r   s     @r/   r   z$Server.list_tools.<locals>.decorator  sH     LLCD)$0F0FGGS& =DD!!%"8"89Kr1   )r   zpCallable[[], Awaitable[list[types.Tool]]] | Callable[[types.ListToolsRequest], Awaitable[types.ListToolsResult]]r6   r   s   ` r/   
list_toolszServer.list_tools  s    	S	< r1   c                    t        j                  t        j                  t        j                  d|      gd            S )z3Create a ServerResult with an error CallToolResult.r   r   r   T)r   isError)rB   r   CallToolResultTextContent)r.   error_messages     r/   _make_error_resultzServer._make_error_result  s9    !!  **]KL
 	
r1   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)rG   rB   ri   rE   rI   rJ   rw   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        j                        rt        j                  |      S t        |t        j                        rt        j                  |      S t        |t              r"t!        |      dk(  rt#        t$        |      \  }}nt        |t&              r>t#        t(        |      }t        j*                  dt-        j.                  |d            g}nFt1        |d      rt#        t2        |      }d }n'	j                  dt5        |      j6                         S |rA|j8                  5|	j                  d	      S 	 t	        j
                  ||j8                         t        j                  t        j                  t;        |      |d            S 7 # 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  t>        $ r$}	j                  tA        |            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   r=   r   r   
jsonschemavalidateinputSchemaValidationErrorr   messager~   rB   r   r   CreateTaskResulttuplelenr   r%   dictr#   r   jsondumpshasattrr$   r   r3   outputSchemalistr   rO   rV   )r   r   r   r   eresultsunstructured_contentmaybe_structured_contentr   r.   r   s           r/   r   z4Server.call_tool.<locals>.decorator.<locals>.handler	  s    >; #

I #

 4 4 :I!%!A!A)!LLD &$c&//4K[K[\
 %)I$>>G
 "'5+?+?@$11'::#GU-C-CD$11'::#GU3G8IIMN`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$) _ M  *99 c#'#:#:=UVWV_V_U`;a#bbc ?B $.#=#= h'+'>'>AZ[\[d[dZe?f'g gh 3    ;223q6::;s   KAJ" 	H 
J" !H# 4J"  I!2J" 3K4.J" "K#CJ" (K) J" 	K!I$ ,3J" K J" #I6IIJ" KIJ" $J7JJJ" KJJ" "K4KKKKK)r   ztypes.CallToolRequest)rI   rJ   rE   rB   CallToolRequest)r   r   r.   r   s   ` r/   r   z#Server.call_tool.<locals>.decorator  s6     LLBC?;B <CD!!%"7"78Kr1   )r   zCallable[..., Awaitable[UnstructuredContent | StructuredContent | CombinationContent | types.CallToolResult | types.CreateTaskResult]]r6   )r.   r   r   s   `` r/   	call_toolzServer.call_tool  s    P		P	d r1   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/   r   z@Server.progress_notification.<locals>.decorator.<locals>.handlerU  sM     JJ,,JJ''JJ$$JJ&&	  s   AA*"A(#A*)r   ztypes.ProgressNotification)rI   rJ   rF   rB   ProgressNotificationr   s   ` r/   r   z/Server.progress_notification.<locals>.decoratorP  s6     LLGH FMD&&u'A'ABKr1   )r   zGCallable[[str | int, float, float | None, str | None], Awaitable[None]]r6   r   s   ` r/   progress_notificationzServer.progress_notificationO  s    	Y	  r1   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contextrB   r   CompleteResult
Completion)r   r  r   s     r/   r   z5Server.completion.<locals>.decorator.<locals>.handlerq  s     #'



8K8KSZZM_M_#``
))((%1 $.  #--RtTR  as   A
B BAB )r   ztypes.CompleteRequest)rI   rJ   rE   rB   rm   r   s   ` r/   r   z$Server.completion.<locals>.decoratore  s5     LLBC <CD!!%"7"78Kr1   )r   zCallable[[types.PromptReference | types.ResourceTemplateReference, types.CompletionArgument, types.CompletionContext | None], Awaitable[types.Completion | None]]r6   r   s   ` r/   r  zServer.completionb  s    		2 r1   c           
       K   t               4 d {   }|j                  | j                  |              d {   }|j                  t        ||||             d {   }| j                  r| j                  j
                  nd }	|	8|	j                  |       |j                  |	j                                d {    t        j                         4 d {   }
|j                  2 3 d {   }t        j                  d|       |
j                  | j                  ||||       ?7 7 7 7 s7 X7 E6 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_contextr9   r   rH   task_supportconfigure_sessionrunanyiocreate_task_groupincoming_messagesrI   rJ   
start_soon_handle_message)r.   read_streamwrite_streaminitialization_optionsraise_exceptionsr  stacklifespan_contextsessionr!  tgr   s               r/   r#  z
Server.run  sg      "# 	 	u%*%>%>t}}T?R%SS!55 *'	 G HLGbGb466CChlL'..w7//0@0@0BCCC..0 
 
B%,%>%> 	 	'LL!7AMM,,((+	S D
	%>
 
 
 
 
#	 	 	 	 	s   FD*F$E1D-%E1D/ AE1=D1>E1D3E1E
+D7/D5
0D737E
*F-E1/E11E13E15D77E
8E1EE1
E	EE	E1F*E-+F1F7E:8F?Fc           	       K   t        j                  d      5 }|xxt        d xC\  t        j                  d x.\  }} |5  | j                  |||||       d {    d d d        ny  xt        j                  d x\  } | j                  |       d {    nE t        d x:\   t        j                  d|        |j                  ddd	
       d {    |r| |D ]7  }	t        j                  d|	j                  j                  |	j                         9 	 d d d        y 7 # 1 sw Y   QxY w7 7 _# 1 sw Y   y xY ww)NT)recordrequest)rootr6   z Received exception from stream: errorzInternal Server Errorzmcp.server.exception_handler)r   r   rI   zWarning: %s: %s)r   catch_warningsr   rB   ClientRequest_handle_requestClientNotification_handle_notificationrO   rI   r6  send_log_messageinfocategoryr3   r   )
r.   r   r/  r.  r,  wr   	respondernotifyr   s
             r/   r(  zServer._handle_message  sT     $$D1 	[QY%Le.A.A.KY" n"227CJZ\lmmmn n Z ;U--:33F;;; ;[LL#CG9!MN!22%4= 3   
 (% !  [-w/?/?/H/H'//Z[#	[ 	[ nn n <	[ 	[sf   E)D:D*D(D* 7D:D6A D:D8AD:	E(D**D3	/D:8D::E?Ec                   K   t         j                  dt        |      j                         | j                  j                  t        |            x}rt         j                  dt        |      j                         d }	 d }d }	d }
|j                  \t        |j                  t              rB|j                  j                  }|j                  j                  }	|j                  j                  }
|j                  r|j                  j                  nd }| j                  r| j                  j                   nd }d }t#        |d      r#|j$                  t'        |j$                  dd       }t(        j+                  t-        |j.                  |j0                  ||t3        ||||      ||	|
            } ||       d {   }|t(        j=                  |       	 |jG                  |       d {    n<|jG                  tA        jB                  t@        jH                  d
             d {    t         j                  d       y 7 # t4        $ r}|j6                  }Y d }~d }~wt9        j:                         $ r; t         j                  d|j.                         Y |t(        j=                  |       y y t>        $ r0}|r|tA        jB                  dtE        |      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   task)task_metadata_client_capabilities_session_task_support)r4  close_sse_streamclose_standalone_sse_streamz4Request %s cancelled - duplicate response suppressedr   )coder   r   zMethod not found)rJ  r   zResponse sent)%rI   r=  r   r3   rE   rw   rJ   message_metadatar~   r   ry   rH  rI  client_paramsrU   rH   r!  r  r   r   r&   setr   
request_idrequest_metar   r   r6  r$  get_cancelled_exc_classresetrO   rB   	ErrorDatarV   respondMETHOD_NOT_FOUND)r.   r   r   r/  r.  r,  r   tokenrequest_dataclose_sse_stream_cbclose_standalone_sse_stream_cbclient_capabilitiesr!  rD  responseerrs                   r/   r9  zServer._handle_request  s     	3T#Y5G5GH++//S	::7:LL949;M;MNE5-#&*#15.++7J,,.C= $+#;#;#K#KL*1*B*B*S*S'5<5M5M5i5i2 MTLaLag&;&;&H&Hgk#KOKfKft::GGlp $3)cjj.D$+CJJ$EM#"**,,($*71D%,*6	 !-)<4R" ")- $%%e,//(+++////.   	_%7 . %99002 J&&  $%%e, %  P#I ??3s8$OP $%%e, % ,s   A<L?D9I 8I9I =,L)L	*<L&L'LI 	K)IK, :K)K, L1K)9%K$K, $K))K, ,LLL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)rF   rw   r   rI   rJ   r3   rO   	exception)r.   rA  r   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)r=   rV   r>   r   r?   r   r@   r   rA   zlist[types.Icon] | Noner9   z[Callable[[Server[LifespanResultT, RequestT]], AbstractAsyncContextManager[LifespanResultT]])NN)rY   zNotificationOptions | NonerZ   z dict[str, dict[str, Any]] | NonerW   r   )rY   r(   rZ   zdict[str, dict[str, Any]]rW   ztypes.ServerCapabilities)rW   z8RequestContext[ServerSession, LifespanResultT, RequestT])rW   r   )r   rV   rW   types.ServerResult)r   rV   rW   ztypes.Tool | None)r   r2   )FF)
r)  z5MemoryObjectReceiveStream[SessionMessage | Exception]r*  z&MemoryObjectSendStream[SessionMessage]r+  r   r,  r2   r  r2   )F)r   z`RequestResponder[types.ClientRequest, types.ServerResult] | types.ClientNotification | Exceptionr/  r   r.  r    r,  r2   )
r   z9RequestResponder[types.ClientRequest, types.ServerResult]r   ztypes.ClientRequestTyper/  r   r.  r    r,  r2   )rA  r   )r3   r4   r5   r9   r0   r[   rX   propertyry   rc   r   r   r   r   r   r   r   r   r   r   r   r
  r  r  r#  r(  r9  r;  r6   r1   r/   r;   r;      s    ##'"&)- 55 5 !	5
  5 '5
58 <@FJ
8
 $D
 
	
:,1, $=, 
"	,\ !	A! ! 	+ 	+..=~B
  37 aF&N "'
  +J+ =+ !6	+ + +d "'[q[ [ *	[
 [6N&JN& %N& 	N&
 *N& N&`Or1   r;   c                X   K   t        j                  t        j                               S wr*   )rB   r   r   r3  s    r/   rD   rD   "  s      e//122s   (*)r8   z!Server[LifespanResultT, RequestT]rW   zAsyncIterator[dict[str, Any]])r4  ztypes.PingRequestrW   r^  )M__doc__
__future__r   _annotationsr   contextvarsr   rb   r   collections.abcr   r   r   r   
contextlibr   r	   r
   typingr   r   r   r   r$  r   anyio.streams.memoryr   r   pydanticr   typing_extensionsr   	mcp.typesrB   'mcp.server.experimental.request_contextr    mcp.server.lowlevel.experimentalr   #mcp.server.lowlevel.func_inspectionr    mcp.server.lowlevel.helper_typesr   mcp.server.modelsr   mcp.server.sessionr   mcp.shared.contextr   mcp.shared.exceptionsr   r   mcp.shared.messager   r   mcp.shared.sessionr   mcp.shared.tool_name_validationr   	getLoggerr3   rI   r    r"   r   rV   r#   __annotations__ContentBlockr$   r   r%   
ContextVarr&   r(   r9   r;   rD   r6   r1   r/   <module>r{     s-  AF 3      H H W W 0 0   R  %  @ A C A 3 , - G D / G			8	$+S9:s+  $CH~ 9 -!)%*<*<!= Y = %&9;L&L M I M Pf{OeOefsOtL t	+ 	+ 	 	V
OW_h./ V
Or3r1   