
    AHj                    v   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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/m0Z0 ddl1m2Z2m3Z3 ddl4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z:  ejv                  e<      Z= ede      Z> ede      Z?e@eAef   ZBdeCd<   ee"j                     ZEdeCd<   eFeEeBf   ZGdeCd<    ej                  d      ZIdeCd<    G d d      ZJed$d        ZK G d! d"ee>e?f         ZLd%d#ZMy)&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
deprecated)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       R/root/tools/cai/cai_env/lib/python3.12/site-packages/mcp/server/lowlevel/server.py__init__zNotificationOptions.__init__q   s      /!2*    N)FFF)r,   boolr-   r3   r.   r3   )__name__
__module____qualname__r1    r2   r0   r)   r)   p   s.     !&"'#	++  + 	+r2   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
    Nr7   )_s    r0   lifespanr:   |   s      Hs   	c                  ^   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 e	d      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iconsr:   typesPingRequest_ping_handlerrequest_handlersnotification_handlers_tool_cache_experimental_handlersloggerdebug)r/   r>   r?   r@   rA   rB   r:   s          r0   r1   zServer.__init__   sq     	(&
 }[
 RT"24CG#-t4r2   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     r0   pkg_versionz9Server.create_initialization_options.<locals>.pkg_version   s*    6w'' s    	mcp)server_nameserver_versioncapabilitiesr@   rA   rB   )rQ   strreturnrW   )r   r>   r?   get_capabilitiesr)   r@   rA   rB   )r/   notification_optionsexperimental_capabilitiesrR   s       r0   create_initialization_optionsz$Server.create_initialization_options   sn    	 %		+/<<4<<[=O..$=(;(=)/R **((**

 
	
r2   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)rC   ListPromptsRequestrF   PromptsCapabilityr,   ListResourcesRequestResourcesCapabilityr-   ListToolsRequestToolsCapabilityr.   SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilitiesrI   update_capabilities)	r/   rZ   r[   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilityrV   s	            r0   rY   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r2   c                *    t         j                         S )zFIf called outside of a request context, this will raise a LookupError.)r'   getr/   s    r0   request_contextzServer.request_context   s    
   r2   zThe experimental tasks API is deprecated and will be removed in mcp 2.0: tasks (SEP-1686) were removed from the MCP specification and are expected to return as a separate MCP extension.c                ~    | j                   &t        | | j                  | j                        | _         | j                   S )a  Experimental APIs for tasks and other features.

        Deprecated: the experimental tasks API will be removed in mcp 2.0. Tasks
        (SEP-1686) were removed from the MCP specification and are expected to
        return as a separate MCP extension.
        )rI   r   rF   rG   ry   s    r0   rd   zServer.experimental   s:     &&.*>tTEZEZ\`\v\v*wD'***r2   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`   )
isinstancerC   ListPromptsResultServerResultreqresultwrappers     r0   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)rJ   rK   r   rC   rf   rF   funcr   r   r/   s     @r0   	decoratorz&Server.list_prompts.<locals>.decorator	  sH     LLDE)$0H0HIGW ?FD!!%":":;Kr2   )r   zvCallable[[], Awaitable[list[types.Prompt]]] | Callable[[types.ListPromptsRequest], Awaitable[types.ListPromptsResult]]r7   r/   r   s   ` r0   list_promptszServer.list_prompts  s    	W	( r2   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>   	argumentsrC   r   )r   
prompt_getr   s     r0   r   z5Server.get_prompt.<locals>.decorator.<locals>.handler%  s?     #'

9M9M#NN
))*55 Os   5AAA)r   ztypes.GetPromptRequest)rJ   rK   rF   rC   GetPromptRequestr   r   r/   s   ` r0   r   z$Server.get_prompt.<locals>.decorator   s5     LLCD6 =DD!!%"8"89Kr2   )r   zHCallable[[str, dict[str, str] | None], Awaitable[types.GetPromptResult]]r7   r   s   ` r0   
get_promptzServer.get_prompt  s    
	Z
	 r2   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)ra   )r   rC   ListResourcesResultr   r   s     r0   r   z9Server.list_resources.<locals>.decorator.<locals>.handler7  sX     &s|+fe&?&?@ --f55 !--e.G.GRX.YZZ ,r   )r   ztypes.ListResourcesRequest)rJ   rK   r   rC   rh   rF   r   s     @r0   r   z(Server.list_resources.<locals>.decorator/  sI     LLGH)$0J0JKG[ AHD!!%"<"<=Kr2   )r   z|Callable[[], Awaitable[list[types.Resource]]] | Callable[[types.ListResourcesRequest], Awaitable[types.ListResourcesResult]]r7   r   s   ` r0   list_resourceszServer.list_resources.  s    	[	( r2   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)rC   r   ListResourceTemplatesResult)r9   	templatesr   s     r0   r   zBServer.list_resource_templates.<locals>.decorator.<locals>.handlerI  s2     "&&L	))%*K*K^g*hii )s   ><.>)r9   r   )rJ   rK   rF   rC   ListResourceTemplatesRequestr   s   ` r0   r   z1Server.list_resource_templates.<locals>.decoratorF  s5    LLOPj IPD!!%"D"DEKr2   )r   z5Callable[[], Awaitable[list[types.ResourceTemplate]]]r7   r   s   ` r0   list_resource_templateszServer.list_resource_templatesE      	 r2   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_metar7   z
text/plain)uritextmimeTypezapplication/octet-stream)r   blobr   )
rW   rC   TextResourceContentsr   r   bytesBlobResourceContentsbase64	b64encodedecode)data	mime_typer   meta_kwargsr   s       r0   create_contentzPServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.create_content[  s    EIEU7D/[]K*SU]#(#=#= $$'JJNN%))2)Bl$ #.	$  + -UW_#(#=#= $$'JJNN%+%5%5d%;%B%B%D)2)P6P$ #.	$  -r2   r7   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   rW   r   warningswarnDeprecationWarningr   contentr   getattrrC   r   ReadResourceResult
ValueErrortype)	r   r   r   r   r   r   content_itemcontents_listr   s	   `       r0   r   z8Server.read_resource.<locals>.decorator.<locals>.handlerX  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)rJ   rK   rF   rC   ReadResourceRequestr   s   ` r0   r   z'Server.read_resource.<locals>.decoratorS  s7     LLFG2h @GD!!%";";<Kr2   )r   zKCallable[[AnyUrl], Awaitable[str | bytes | Iterable[ReadResourceContents]]]r7   r   s   ` r0   read_resourcezServer.read_resourceR  s    :	]:	x r2   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   levelrC   r   EmptyResultr   r   s    r0   r   z<Server.set_logging_level.<locals>.decorator.<locals>.handler  s>     3::++,,,))%*;*;*=>> -    AA,A)r   ztypes.SetLevelRequest)rJ   rK   rF   rC   rl   r   s   ` r0   r   z+Server.set_logging_level.<locals>.decorator  s3    LLBC? <CD!!%"7"78Kr2   )r   z/Callable[[types.LoggingLevel], Awaitable[None]]r7   r   s   ` r0   set_logging_levelzServer.set_logging_level  r   r2   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   rC   r   r   r   s    r0   r   z=Server.subscribe_resource.<locals>.decorator.<locals>.handler  <     3::>>***))%*;*;*=>> +r   )r   ztypes.SubscribeRequest)rJ   rK   rF   rC   SubscribeRequestr   s   ` r0   r   z,Server.subscribe_resource.<locals>.decorator  s3    LLCD? =DD!!%"8"89Kr2   r   z#Callable[[AnyUrl], Awaitable[None]]r7   r   s   ` r0   subscribe_resourcezServer.subscribe_resource  r   r2   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    r0   r   z?Server.unsubscribe_resource.<locals>.decorator.<locals>.handler  r   r   )r   ztypes.UnsubscribeRequest)rJ   rK   rF   rC   UnsubscribeRequestr   s   ` r0   r   z.Server.unsubscribe_resource.<locals>.decorator  s3    LLEF? ?FD!!%":":;Kr2   r   r7   r   s   ` r0   unsubscribe_resourcezServer.unsubscribe_resource  r   r2   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)rb   )	r   rC   ListToolsResultrb   r    r>   rH   r   clear)r   r   toolr/   r   s      r0   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)rJ   rK   r   rC   rj   rF   r   s     @r0   r   z$Server.list_tools.<locals>.decorator  sH     LLCD)$0F0FGGS& =DD!!%"8"89Kr2   )r   zpCallable[[], Awaitable[list[types.Tool]]] | Callable[[types.ListToolsRequest], Awaitable[types.ListToolsResult]]r7   r   s   ` r0   
list_toolszServer.list_tools  s    	S	< r2   c                    t        j                  t        j                  t        j                  d|      gd            S )z3Create a ServerResult with an error CallToolResult.r   r   r   T)r   isError)rC   r   CallToolResultTextContent)r/   error_messages     r0   _make_error_resultzServer._make_error_result  s9    !!  **]KL
 	
r2   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)rH   rC   rj   rF   rJ   rK   rx   warning)r/   	tool_namer   s      r0   _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   rC   r   r   CreateTaskResulttuplelenr   r&   dictr$   r   jsondumpshasattrr%   r   r4   outputSchemalistr   rP   rW   )r   r   r   r   eresultsunstructured_contentmaybe_structured_contentr   r/   r   s           r0   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)rJ   rK   rF   rC   CallToolRequest)r   r   r/   r   s   ` r0   r   z#Server.call_tool.<locals>.decorator  s6     LLBC?;B <CD!!%"7"78Kr2   )r   zCallable[..., Awaitable[UnstructuredContent | StructuredContent | CombinationContent | types.CallToolResult | types.CreateTaskResult]]r7   )r/   r   r   s   `` r0   	call_toolzServer.call_tool  s    P		P	d r2   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    r0   r   z@Server.progress_notification.<locals>.decorator.<locals>.handler[  sM     JJ,,JJ''JJ$$JJ&&	  s   AA*"A(#A*)r   ztypes.ProgressNotification)rJ   rK   rG   rC   ProgressNotificationr   s   ` r0   r   z/Server.progress_notification.<locals>.decoratorV  s6     LLGH FMD&&u'A'ABKr2   )r   zGCallable[[str | int, float, float | None, str | None], Awaitable[None]]r7   r   s   ` r0   progress_notificationzServer.progress_notificationU  s    	Y	  r2   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contextrC   r   CompleteResult
Completion)r   r  r   s     r0   r   z5Server.completion.<locals>.decorator.<locals>.handlerw  s     #'



8K8KSZZM_M_#``
))((%1 $.  #--RtTR  as   A
B BAB )r   ztypes.CompleteRequest)rJ   rK   rF   rC   rn   r   s   ` r0   r   z$Server.completion.<locals>.decoratork  s5     LLBC <CD!!%"7"78Kr2   )r   zCallable[[types.PromptReference | types.ResourceTemplateReference, types.CompletionArgument, types.CompletionContext | None], Awaitable[types.Completion | None]]r7   r   s   ` r0   r  zServer.completionh  s    		2 r2   c           
       K   t               4 d {   }|j                  | j                  |              d {   }|j                  t        ||||             d {   }| j                  r| j                  j
                  nd }	|	:|	j                  ||       |j                  |	j                                d {    t        j                         4 d {   }
	 |j                  2 3 d {   }t        j                  d|       |
j                  | j                  ||||       ?7 7 7 7 t7 Y7 E6 	 |
j                  j!                          n# |
j                  j!                          w xY w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_contextr:   r   rI   task_supportconfigure_sessionrunanyiocreate_task_groupincoming_messagesrJ   rK   
start_soon_handle_messagecancel_scopecancel)r/   read_streamwrite_streaminitialization_optionsraise_exceptionsr   stacklifespan_contextsessionr"  tgr   s               r0   r$  z
Server.run  s      "# "	- "	-u%*%>%>t}}T?R%SS!55 *'	 G HLGbGb466CChlL'..w).L//0@0@0BCCC..0 - -B-)0)B)B 	 	g%;WE 00##,,-"	-S D-	)B OO**,BOO**,#- - - - -#"	- "	- "	- "	- "	-s   GD-G$F/D0%F/D2 AF/?D4 F/D6F/ F"E.D:2D8
3D:67E-G0F/2F/4F/6F/8D::E<FE33F6F/FF/F	FF	F/G(F+)G/G5F86G=G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)rootr7   z Received exception from stream: errorzInternal Server Errorzmcp.server.exception_handler)r   r   rJ   zWarning: %s: %s)r   catch_warningsr   rC   ClientRequest_handle_requestClientNotification_handle_notificationrP   rJ   r9  send_log_messageinfocategoryr4   r   )
r/   r   r2  r1  r/  wr   	respondernotifyr   s
             r0   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?                  |       n%tC        jD                  tB        jH                  d
      }	 |jK                  |       d {    t         j                  d       y 7 q# t4        $ r}|j6                  }Y d }~d }~wt9        j:                         $ rH |j<                  r:t         j                  d|j.                         Y |t(        j?                  |       y y  t@        $ r0}|r|tC        jD                  dtG        |      d 	      }Y d }~d }~ww xY w# |t(        j?                  |       w w xY w7 # t8        jL                  t8        jN                  f$ r# t         j                  d|j.                         Y y w xY ww)NzProcessing request of type %szDispatching request of type %sr   task)task_metadata_client_capabilities_session_task_support)r7  close_sse_streamclose_standalone_sse_streamz4Request %s cancelled - duplicate response suppressedr   )coder   r   zMethod not found)rM  r   z*Response for %s dropped - transport closedzResponse sent)(rJ   r@  r   r4   rF   rx   rK   message_metadatar   r   rz   rK  rL  client_paramsrV   rI   r"  r  r   r   r'   setr   
request_idrequest_metar   r   r9  r%  get_cancelled_exc_class	cancelledresetrP   rC   	ErrorDatarW   METHOD_NOT_FOUNDrespondBrokenResourceErrorClosedResourceError)r/   r   r   r2  r1  r/  r   tokenrequest_dataclose_sse_stream_cbclose_standalone_sse_stream_cbclient_capabilitiesr"  rG  responseerrs                   r0   r<  zServer._handle_request  s     	3T#Y5G5GH++//S	::7:LL949;M;MNE;-#&*#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,++*H

	//(+++ 	_%S . %99002 $$ KKN**  $%%e, %  P#I ??3s8$OP $%%e, % ,))5+D+DE 	 LLEwGYGYZ	s   A<M
?D9H, 8H*9H, ==M
;L K?L M
*H, ,	K5IK" AKK" M
&	K/%KK" KK" "K<<M
?L AMM
MM
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)rG   rx   r   rJ   rK   r4   rP   	exception)r/   rD  r   s      r0   r>  zServer._handle_notification3  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>   rW   r?   r   r@   r   rA   r   rB   zlist[types.Icon] | Noner:   z[Callable[[Server[LifespanResultT, RequestT]], AbstractAsyncContextManager[LifespanResultT]])NN)rZ   zNotificationOptions | Noner[   z dict[str, dict[str, Any]] | NonerX   r   )rZ   r)   r[   zdict[str, dict[str, Any]]rX   ztypes.ServerCapabilities)rX   z8RequestContext[ServerSession, LifespanResultT, RequestT])rX   r   )r   rW   rX   types.ServerResult)r   rW   rX   ztypes.Tool | None)r   r3   )FF)
r,  z5MemoryObjectReceiveStream[SessionMessage | Exception]r-  z&MemoryObjectSendStream[SessionMessage]r.  r   r/  r3   r   r3   )F)r   z`RequestResponder[types.ClientRequest, types.ServerResult] | types.ClientNotification | Exceptionr2  r   r1  r!   r/  r3   )
r   z9RequestResponder[types.ClientRequest, types.ServerResult]r   ztypes.ClientRequestTyper2  r   r1  r!   r/  r3   )rD  r   )r4   r5   r6   r:   r1   r\   rY   propertyrz   r   rd   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r$  r)  r<  r>  r7   r2   r0   r<   r<      s    ##'"&)- 55 5 !	5
  5 '5
58 <@FJ
8
 $D
 
	
:,1, $=, 
"	,\ !	A! ! 	^+	 
+..=~B
  37 aF&N "'
  2-J2- =2- !6	2- 2- 2-r "'[q[ [ *	[
 [6\&J\& %\& 	\&
 *\& \&|Or2   r<   c                X   K   t        j                  t        j                               S wr+   )rC   r   r   r6  s    r0   rE   rE   =  s      e//122s   (*)r9   z!Server[LifespanResultT, RequestT]rX   zAsyncIterator[dict[str, Any]])r7  ztypes.PingRequestrX   rd  )N__doc__
__future__r   _annotationsr   contextvarsr  rc   r   collections.abcr   r   r   r   
contextlibr   r	   r
   typingr   r   r   r   r%  r   anyio.streams.memoryr   r   pydanticr   typing_extensionsr   r   	mcp.typesrC   '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    	getLoggerr4   rJ   r!   r#   r   rW   r$   __annotations__ContentBlockr%   r   r&   
ContextVarr'   r)   r:   r<   rE   r7   r2   r0   <module>r     s-  AF 3      H H W W 0 0   R  1  @ 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	+ 	+ 	 	q
OW_h./ q
Oh3r2   