
    !<i                       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l0m1Z1 ddl2m3Z3m4Z4 ddl5m6Z6 ddl7m8Z8  ej9        e:          Z; ede          Z< ede          Z=e>e?ef         Z@deAd<   ee!jB                 ZCdeAd<   eDeCe@f         ZEdeAd<    ejF        d          ZGdeAd<    G d d          ZHed+d$            ZI G d% d&ee<e=f                   ZJd,d*ZKdS )-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)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dS )
NotificationOptionsFprompts_changedboolresources_changedtools_changedc                0    || _         || _        || _        d S N)r(   r*   r+   )selfr(   r*   r+   s       /Users/kimhansen/Desktop/03 Workspace/ceo-agents/chl-effectiveness/mcp-servers/whoop/.venv/lib/python3.11/site-packages/mcp/server/lowlevel/server.py__init__zNotificationOptions.__init__q   s"      /!2*    N)FFF)r(   r)   r*   r)   r+   r)   )__name__
__module____qualname__r0    r1   r/   r'   r'   p   s8         !&"'#	+ + + + + + +r1   r'   _!Server[LifespanResultT, RequestT]returnAsyncIterator[dict[str, Any]]c                  K   i W V  dS )zDefault lifespan context manager that does nothing.

    Args:
        server: The server instance this lifespan is managing

    Returns:
        An empty context object
    Nr5   )r6   s    r/   lifespanr;   |   s       HHHHHHr1   c                      e Zd ZddddefdIdZ	 	 dJdKdZdLdZedMd            ZedNd            Z	d Z
d Zd Zd Zd  Zd! Zd" Zd# Zd$ ZdOd'ZdPd*Zd+d,dQd/Zd0 Zd1 Z	 	 dRdSd:Z	 dTdUdAZdVdEZdWdHZdS )XServerNnamestrversion
str | Noneinstructionswebsite_urliconslist[types.Icon] | Noner;   [Callable[[Server[LifespanResultT, RequestT]], AbstractAsyncContextManager[LifespanResultT]]c                    || _         || _        || _        || _        || _        || _        t          j        t          i| _	        i | _
        i | _        d | _        t                              d|           d S )NzInitializing server %r)r>   r@   rB   rC   rD   r;   typesPingRequest_ping_handlerrequest_handlersnotification_handlers_tool_cache_experimental_handlersloggerdebug)r.   r>   r@   rB   rC   rD   r;   s          r/   r0   zServer.__init__   sz     	(&
 }[
 RT"24CG#-t44444r1   notification_optionsNotificationOptions | Noneexperimental_capabilities dict[str, dict[str, Any]] | Noner8   r   c                    dd}t          | j        | j        r| j        n
 |d          |                     |pt	                      |pi           | j        | j        | j                  S )z8Create initialization options from this server instance.packager?   r8   c                J    	 ddl m}  ||           S # t          $ r Y nw xY wdS )Nr   )r@   unknown)importlib.metadatar@   	Exception)rV   r@   s     r/   pkg_versionz9Server.create_initialization_options.<locals>.pkg_version   sP    666666ww'''    9s    
  mcp)server_nameserver_versioncapabilitiesrB   rC   rD   )rV   r?   r8   r?   )r   r>   r@   get_capabilitiesr'   rB   rC   rD   )r.   rQ   rS   r[   s       r/   create_initialization_optionsz$Server.create_initialization_options   s    	 	 	 	 %	+/<O4<<[[=O=O..$=(;(=(=)/R  *(*

 

 

 
	
r1   r'   dict[str, dict[str, Any]]types.ServerCapabilitiesc                8   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                            |           |S )z9Convert existing handlers to a ServerCapabilities object.N)listChangedF)	subscribere   )prompts	resourcestoolsloggingexperimentalcompletions)rH   ListPromptsRequestrK   PromptsCapabilityr(   ListResourcesRequestResourcesCapabilityr*   ListToolsRequestToolsCapabilityr+   SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilitiesrN   update_capabilities)	r.   rQ   rS   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilityr_   s	            r/   r`   zServer.get_capabilities   sD    "#!!% #t'<<<!&!8EYEi!j!j!j %)>>>#(#<-A-S$ $ $ 
 !T%:::$4AUAcddd  D$999!&!8!:!:  D$999%*%@%B%B"/&*"&2.
 
 
 & 	J';;LIIIr1   8RequestContext[ServerSession, LifespanResultT, RequestT]c                4    t                                           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   r   c                ^    | j          t          | | j        | j                  | _         | j         S )zExperimental APIs for tasks and other features.

        WARNING: These APIs are experimental and may change without notice.
        )rN   r   rK   rL   r   s    r/   rk   zServer.experimental   s1     &.*>tTEZ\`\v*w*wD'**r1   c                     d fd}|S )NfuncvCallable[[], Awaitable[list[types.Prompt]]] | Callable[[types.ListPromptsRequest], Awaitable[types.ListPromptsResult]]c                    t                               d           t          | t          j                  dfd}|j        t          j        <   | S )Nz)Registering handler for PromptListRequestreqtypes.ListPromptsRequestc                   K    |            d {V }t          |t          j                  rt          j        |          S t          j        t          j        |                    S )N)rg   )
isinstancerH   ListPromptsResultServerResultr   resultwrappers     r/   handlerz7Server.list_prompts.<locals>.decorator.<locals>.handler  sn      &ws||++++++fe&=>> W -f555 !-e.Ef.U.U.UVVVr1   )r   r   )rO   rP   r   rH   rm   rK   r   r   r   r.   s     @r/   	decoratorz&Server.list_prompts.<locals>.decorator  sg     LLDEEE)$0HIIGW W W W W W ?FD!%":;Kr1   )r   r   r5   r.   r   s   ` r/   list_promptszServer.list_prompts  )    	 	 	 	 	 	( r1   c                     d fd}|S )Nr   HCallable[[str, dict[str, str] | None], Awaitable[types.GetPromptResult]]c                r     t                               d           d fd}|j        t          j        <    S )Nz(Registering handler for GetPromptRequestr   types.GetPromptRequestc                |   K    | j         j        | j         j                   d {V }t          j        |          S r-   )paramsr>   	argumentsrH   r   )r   
prompt_getr   s     r/   r   z5Server.get_prompt.<locals>.decorator.<locals>.handler  sD      #'4
9M#N#NNNNNNN
)*555r1   )r   r   )rO   rP   rK   rH   GetPromptRequestr   r   r.   s   ` r/   r   z$Server.get_prompt.<locals>.decorator  sO     LLCDDD6 6 6 6 6 6 =DD!%"89Kr1   )r   r   r5   r   s   ` r/   
get_promptzServer.get_prompt  s)    
	 
	 
	 
	 
	 
	 r1   c                     d fd}|S )Nr   |Callable[[], Awaitable[list[types.Resource]]] | Callable[[types.ListResourcesRequest], Awaitable[types.ListResourcesResult]]c                    t                               d           t          | t          j                  dfd}|j        t          j        <   | S )Nz,Registering handler for ListResourcesRequestr   types.ListResourcesRequestc                   K    |            d {V }t          |t          j                  rt          j        |          S t          j        t          j        |                    S )N)rh   )r   rH   ListResourcesResultr   r   s     r/   r   z9Server.list_resources.<locals>.decorator.<locals>.handler1  so      &ws||++++++fe&?@@ [ -f555 !-e.GRX.Y.Y.YZZZr1   )r   r   )rO   rP   r   rH   ro   rK   r   s     @r/   r   z(Server.list_resources.<locals>.decorator)  sh     LLGHHH)$0JKKG[ [ [ [ [ [ AHD!%"<=Kr1   )r   r   r5   r   s   ` r/   list_resourceszServer.list_resources(  r   r1   c                     d fd}|S )Nr   5Callable[[], Awaitable[list[types.ResourceTemplate]]]c                r     t                               d           d fd}|j        t          j        <    S )Nz4Registering handler for ListResourceTemplatesRequestr6   r   c                v   K                 d {V }t          j        t          j        |                    S )N)resourceTemplates)rH   r   ListResourceTemplatesResult)r6   	templatesr   s     r/   r   zBServer.list_resource_templates.<locals>.decorator.<locals>.handlerC  s>      "&$&&LLLLLL	)%*K^g*h*h*hiiir1   )r6   r   )rO   rP   rK   rH   ListResourceTemplatesRequestr   s   ` r/   r   z1Server.list_resource_templates.<locals>.decorator@  sT    LLOPPPj j j j j j IPD!%"DEKr1   )r   r   r5   r   s   ` r/   list_resource_templateszServer.list_resource_templates?  )    	 	 	 	 	 	 r1   c                     d fd}|S )Nr   KCallable[[AnyUrl], Awaitable[str | bytes | Iterable[ReadResourceContents]]]c                r     t                               d           d fd}|j        t          j        <    S )Nz+Registering handler for ReadResourceRequestr   types.ReadResourceRequestc                   K     j         j                   d {V }d fd|xxxt          d x\   n xt          d x\   n  n, } t	          j        dt          d	            |d           }nf xt          d x8\   }fd
|D             }t          j	        t          j
        |                    S   	 t          dt          |                     t          j	        t          j
        |g                    S )Ndatastr | bytes	mime_typerA   c                "   | xxt           d x'\   }  t          j        j        j        | |pd          S   xt
          d xJ\   } t          j        j        j        t          j        |           	                                |pd          S   d S )Nr5   z
text/plain)uritextmimeTypezapplication/octet-stream)r   blobr   )
r?   rH   TextResourceContentsr   r   bytesBlobResourceContentsbase64	b64encodedecode)r   r   r   s     r/   create_contentzPServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.create_contentU  s    *]SUUUUUUU#(#=$'JN%))2)Bl$ $ $  +] -UWWWWWW#(#=$'JN%+%5d%;%;%B%B%D%D)2)P6P$ $ $  -___r1   r5   zdReturning str or bytes from read_resource is deprecated. Use Iterable[ReadResourceContents] instead.   )
stacklevelc                <    g | ]} |j         |j                  S r5   )contentr   ).0content_itemr   s     r/   
<listcomp>zLServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.<listcomp>n  s8     ) ) )]iNN<+?AWXX) ) )r1   )contentsz+Unexpected return type from read_resource: )r   r   r   rA   )r   r   r?   r   warningswarnDeprecationWarningr   rH   r   ReadResourceResult
ValueErrortype)r   r   r   r   r   contents_listr   r   s   `     @r/   r   z8Server.read_resource.<locals>.decorator.<locals>.handlerR  s     #tCJN33333333      00 J.'(	    #1.t"<"< 1 0) ) ) )mu) ) )  %1!4)6      	 0/ ()eW[\bWcWc)e)efff),")    r1   )r   r   )rO   rP   rK   rH   ReadResourceRequestr   s   ` r/   r   z'Server.read_resource.<locals>.decoratorM  sQ     LLFGGG+ + + + + +Z @GD!%";<Kr1   )r   r   r5   r   s   ` r/   read_resourcezServer.read_resourceL  s*    3	 3	 3	 3	 3	 3	j r1   c                     d fd}|S )Nr   /Callable[[types.LoggingLevel], Awaitable[None]]c                r     t                               d           d fd}|j        t          j        <    S )Nz'Registering handler for SetLevelRequestr   types.SetLevelRequestc                   K    | j         j                   d {V  t          j        t          j                              S r-   )r   levelrH   r   EmptyResultr   r   s    r/   r   z<Server.set_logging_level.<locals>.decorator.<locals>.handler  sH      d3:+,,,,,,,,,)%*;*=*=>>>r1   )r   r   )rO   rP   rK   rH   rs   r   s   ` r/   r   z+Server.set_logging_level.<locals>.decorator  sM    LLBCCC? ? ? ? ? ? <CD!%"78Kr1   )r   r   r5   r   s   ` r/   set_logging_levelzServer.set_logging_level  r   r1   c                     d fd}|S )Nr   #Callable[[AnyUrl], Awaitable[None]]c                r     t                               d           d fd}|j        t          j        <    S )Nz(Registering handler for SubscribeRequestr   types.SubscribeRequestc                   K    | j         j                   d {V  t          j        t          j                              S r-   r   r   rH   r   r   r   s    r/   r   z=Server.subscribe_resource.<locals>.decorator.<locals>.handler  G      d3:>*********)%*;*=*=>>>r1   )r   r   )rO   rP   rK   rH   SubscribeRequestr   s   ` r/   r   z,Server.subscribe_resource.<locals>.decorator  sM    LLCDDD? ? ? ? ? ? =DD!%"89Kr1   r   r   r5   r   s   ` r/   subscribe_resourcezServer.subscribe_resource  r   r1   c                     d fd}|S )Nr   r   c                r     t                               d           d fd}|j        t          j        <    S )Nz*Registering handler for UnsubscribeRequestr   types.UnsubscribeRequestc                   K    | j         j                   d {V  t          j        t          j                              S r-   r   r   s    r/   r   z?Server.unsubscribe_resource.<locals>.decorator.<locals>.handler  r   r1   )r   r   )rO   rP   rK   rH   UnsubscribeRequestr   s   ` r/   r   z.Server.unsubscribe_resource.<locals>.decorator  sM    LLEFFF? ? ? ? ? ? ?FD!%":;Kr1   r   r5   r   s   ` r/   unsubscribe_resourcezServer.unsubscribe_resource  r   r1   c                     d fd}|S )Nr   pCallable[[], Awaitable[list[types.Tool]]] | Callable[[types.ListToolsRequest], Awaitable[types.ListToolsResult]]c                    t                               d           t          | t          j                  dfd}|j        t          j        <   | S )Nz(Registering handler for ListToolsRequestr   types.ListToolsRequestc                  K    |            d {V }t          |t          j                  rA|j        D ]%}t	          |j                   |j        |j        <   &t          j        |          S j                                         |D ]%}t	          |j                   |j        |j        <   &t          j        t          j        |                    S )N)ri   )	r   rH   ListToolsResultri   r   r>   rM   r   clear)r   r   toolr.   r   s      r/   r   z5Server.list_tools.<locals>.decorator.<locals>.handler  s      &ws||++++++ fe&;<< S & ; ;3DI>>>6:(33 -f555 $**,,, & ; ;3DI>>>6:(33 -e.C&.Q.Q.QRRRr1   )r   r   )rO   rP   r   rH   rq   rK   r   s     @r/   r   z$Server.list_tools.<locals>.decorator  sm     LLCDDD)$0FGGGS S S S S S S& =DD!%"89Kr1   )r   r   r5   r   s   ` r/   
list_toolszServer.list_tools  s)    	 	 	 	 	 	< r1   error_messagetypes.ServerResultc                |    t          j        t          j        t          j        d|          gd                    S )z3Create a ServerResult with an error CallToolResult.r   r   r   T)r   isError)rH   r   CallToolResultTextContent)r.   r   s     r/   _make_error_resultzServer._make_error_result  sE    ! *]KKKL  
 
 	
r1   	tool_nametypes.Tool | Nonec                2  K   || j         vrTt          j        | j        v rAt                              d|            | j        t          j                 d           d{V  | j                             |          }|t                              d|           |S )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)rM   rH   rq   rK   rO   rP   r   warning)r.   r  r   s      r/   _get_cached_tool_definitionz"Server._get_cached_tool_definition  s      
 D,,,%)>>>GSSSCd+E,BCDIIIIIIIII##I..<NNRT]^^^r1   T)validate_inputr  r)   c                    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.
        r   Callable[..., Awaitable[UnstructuredContent | StructuredContent | CombinationContent | types.CallToolResult | types.CreateTaskResult]]c                v     t                               d           d fd}|j        t          j        <    S )Nz'Registering handler for CallToolRequestr   types.CallToolRequestc                  K   	 | j         j        }| j         j        pi }	                    |           d {V }
rX|rV	 t	          j        ||j                   n9# t          j        $ r'}	                    d|j	                   cY d }~S d }~ww xY w ||           d {V }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&                    rAt#          t(          |          }t          j        dt-          j        |d                    g}nRt1          |d          rt#          t2          |          }d }n*	                    dt5          |          j                   S |rt|j        m|	                    d	          S 	 t	          j        ||j                   n9# t          j        $ r'}	                    d
|j	                   cY d }~S d }~ww xY wt          j        t          j        t;          |          |d                    S # t<          $ r,}	                    t?          |                    cY d }~S d }~ww xY 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   rH   r   r   CreateTaskResulttuplelenr   r$   dictr"   r   jsondumpshasattrr#   r   r2   outputSchemalistrZ   r?   )r   r  r   r   eresultsunstructured_contentmaybe_structured_contentr   r.   r  s           r/   r   z4Server.call_tool.<locals>.decorator.<locals>.handler  sg     :; #
I #
 4 :I!%!A!A)!L!LLLLLLLD & c$ cc&/4K[\\\\\)9 c c c#'#:#:;aVWV_;a;a#b#bbbbbbbc %)DI$>$>>>>>>>G
 "'5+?@@ v$1':::#GU-CDD v$1':::#GU33 vG8I8IIMN`biIjIjF,.F.F#GT22 	v378I73S3S0050AvTXT^_fopTqTqTq0r0r0r/s,, *55 v/34G/Q/Q,3700#667t\`ah\i\i\r7t7tuuu  	h 1 =3;#'#:#: q$ $ h * 3=U^b^o p p p p p#-#= h h h'+'>'>?f[\[d?f?f'g'g g g g g g gh !-,$()=$>$>.F$)     ! ; ; ;223q66::::::::;s   9J A J B*BBJ BAJ -J C(J +J H( 'J (I7IIJ I8J 
K!!KKK)r   r  )rO   rP   rK   rH   CallToolRequest)r   r   r.   r  s   ` r/   r   z#Server.call_tool.<locals>.decorator  sZ     LLBCCC;; ;; ;; ;; ;; ;; ;; ;;z <CD!%"78Kr1   )r   r	  r5   )r.   r  r   s   `` r/   	call_toolzServer.call_tool  s7    L	 L	 L	 L	 L	 L	 L	\ r1   c                     d fd}|S )Nr   GCallable[[str | int, float, float | None, str | None], Awaitable[None]]c                r     t                               d           d fd}|j        t          j        <    S )Nz,Registering handler for ProgressNotificationr   types.ProgressNotificationc                   K    | j         j        | j         j        | j         j        | j         j                   d {V  d S r-   )r   progressTokenprogresstotalr  r   s    r/   r   z@Server.progress_notification.<locals>.decorator.<locals>.handlerJ  sc      dJ,J'J$J&	          r1   )r   r)  )rO   rP   rL   rH   ProgressNotificationr   s   ` r/   r   z/Server.progress_notification.<locals>.decoratorE  sP     LLGHHH      FMD&u'ABKr1   )r   r'  r5   r   s   ` r/   progress_notificationzServer.progress_notificationD  s)    	 	 	 	 	 	  r1   c                     d fd}|S )z7Provides completions for prompts and resource templatesr   Callable[[types.PromptReference | types.ResourceTemplateReference, types.CompletionArgument, types.CompletionContext | None], Awaitable[types.Completion | None]]c                r     t                               d           d fd}|j        t          j        <    S )Nz'Registering handler for CompleteRequestr   types.CompleteRequestc           	        K    | j         j        | j         j        | j         j                   d {V }t	          j        t	          j        ||nt	          j        g d d                               S )N)valuesr-  hasMore)
completion)r   refargumentcontextrH   r   CompleteResult
Completion)r   r7  r   s     r/   r   z5Server.completion.<locals>.decorator.<locals>.handlerf  s      #'4

8KSZM_#`#```````
)(%1 $.:"-RtTRRR    r1   )r   r3  )rO   rP   rK   rH   ru   r   s   ` r/   r   z$Server.completion.<locals>.decoratorZ  sO     LLBCCC      <CD!%"78Kr1   )r   r1  r5   r   s   ` r/   r7  zServer.completionW  s)    	 	 	 	 	 	2 r1   Fread_stream5MemoryObjectReceiveStream[SessionMessage | Exception]write_stream&MemoryObjectSendStream[SessionMessage]initialization_optionsraise_exceptions	statelessc           
       K   t                      4 d {V }|                    |                     |                      d {V }|                    t          ||||                     d {V }| j        r| j        j        nd }	|	B|	                    |           |                    |	                                           d {V  t          j	                    4 d {V }
|j
        2 3 d {V }t                              d|           |
                    | j        ||||           A6 	 d d d           d {V  n# 1 d {V swxY w Y   d d d           d {V  d S # 1 d {V swxY w Y   d S )N)rC  zReceived message: %s)r	   enter_async_contextr;   r   rN   task_supportconfigure_sessionrunanyiocreate_task_groupincoming_messagesrO   rP   
start_soon_handle_message)r.   r=  r?  rA  rB  rC  stacklifespan_contextsessionrF  tgr  s               r/   rH  z
Server.runu  s       "## 	 	 	 	 	 	 	u%*%>%>t}}T?R?R%S%SSSSSSS!55 *'	         G HLGbl46CChlL'..w777//0@0@0B0BCCCCCCCCC.00 
 
 
 
 
 
 
B%,%> 	 	 	 	 	 	 	'LL!7AAAMM,((    &?%>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
#	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	sB   CE%$E,D-2<E/E%
E	E%E	E%%
E/2E/r  `RequestResponder[types.ClientRequest, types.ServerResult] | types.ClientNotification | ExceptionrP  r   rO  r   c           	       K   t          j        d          5 }|xxt          d xP\  t          j        d x?\  }} |5  |                     |||||           d {V  d d d            n# 1 swxY w Y   n  xt          j        d x \  } |                     |           d {V  nN t          d xB\   t          
                    d|            |                    ddd	
           d {V  |r|n |D ]-}	t                              d|	j        j        |	j                   .	 d d d            d S # 1 swxY w Y   d S )NT)recordrequest)rootr5   z Received exception from stream: errorzInternal Server Errorzmcp.server.exception_handler)r   r   rO   zWarning: %s: %s)r   catch_warningsr   rH   ClientRequest_handle_requestClientNotification_handle_notificationrZ   rO   rX  send_log_messageinfocategoryr2   r  )
r.   r  rP  rO  rB  wr   	respondernotifyr  s
             r/   rM  zServer._handle_message  sv      $D111 	[QYY%LLLLLe.A.K.K.K.K.Ksss" n n"227CJZ\lmmmmmmmmmn n n n n n n n n n n n n n n ZY ;U-:::::6633F;;;;;;;;;; ;[[[[[LL!MG!M!MNNN!22%4= 3         
 ( &%& !  [ [-w/?/H'/ZZZZ[#	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[ 	[s5   &D4 A*D4*A.	.D41A.	2B4D44D8;D89RequestResponder[types.ClientRequest, types.ServerResult]r   types.ClientRequestTypec                  K   t                               dt          |          j                   | j                            t          |                    x}r9t                               dt          |          j                   d }	 d }d }	d }
|j        >t          |j        t                    r$|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(                              t-          |j        |j        ||t3          ||||          ||	|
                    } ||           d {V }n# t4          $ r}|j        }Y d }~nd }~wt9          j                    $ rB t                               d|j                   Y |t(                              |           d S d S t>          $ r2}|r|tA          j!        dtE          |          d 	          }Y d }~nd }~ww xY w|t(                              |           n"# |t(                              |           w w xY w|#                    |           d {V  n9|#                    tA          j!        t@          j$        d
                     d {V  t                               d           d S )NzProcessing request of type %szDispatching request of type %sr   task)task_metadata_client_capabilities_session_task_support)rV  close_sse_streamclose_standalone_sse_streamz4Request %s cancelled - duplicate response suppressedr   )coder  r   zMethod not found)rn  r  zResponse sent)%rO   r_  r   r2   rK   r   rP   message_metadatar   r   r   rl  rm  client_paramsr_   rN   rF  r  r   getattrr%   setr   
request_idrequest_metar   r   rX  rI  get_cancelled_exc_classresetrZ   rH   	ErrorDatar?   respondMETHOD_NOT_FOUND)r.   r  r   rP  rO  rB  r   tokenrequest_dataclose_sse_stream_cbclose_standalone_sse_stream_cbclient_capabilitiesrF  rh  responseerrs                   r/   r[  zServer._handle_request  sw      	3T#YY5GHHH+//S		:::7 B	LL9499;MNNNE5-#&*#15.+7J,.C= =7 $+#;#KL*1*B*S'5<5M5i2 MTLa&kg&;&H&Hgk#KOKfpt:GGlp $3)) Fcj.D$+CJ$E$EM#"*,($*71D%,*6	   !-)<4R   " ")------ % % %9022   J&    $%%e,,,,, %$  P P P# I ?3s88$OOOP $%%e,,, $%%e,,,, % //(++++++++++///.           	_%%%%%sO   
C?F
 	I 

H5F I  9H5I :	H5(H0+I 0H55I I4rc  r   c                4  K   | j                             t          |                    x}rlt                              dt          |          j                   	  ||           d {V  d S # t          $ r t                              d           Y d S w xY wd S )Nz#Dispatching notification of type %sz*Uncaught exception in notification handler)rL   r   r   rO   rP   r2   rZ   	exception)r.   rc  r   s      r/   r]  zServer._handle_notification  s      044T&\\BBB7 	OLL>V@UVVVOgfoo%%%%%%%%% O O O  !MNNNNNNO	O 	Os   A- -$BB)r>   r?   r@   rA   rB   rA   rC   rA   rD   rE   r;   rF   )NN)rQ   rR   rS   rT   r8   r   )rQ   r'   rS   rb   r8   rc   )r8   r~   )r8   r   )r   r?   r8   r   )r  r?   r8   r  )r  r)   )FF)
r=  r>  r?  r@  rA  r   rB  r)   rC  r)   )F)r  rR  rP  r   rO  r   rB  r)   )
r  rd  r   re  rP  r   rO  r   rB  r)   )rc  r   )r2   r3   r4   r;   r0   ra   r`   propertyr   rk   r   r   r   r   r   r   r   r   r   r  r  r%  r/  r7  rH  rM  r[  r]  r5   r1   r/   r=   r=      s+        ##'"&)- 5 5 5 5 58 <@FJ
 
 
 
 
:, , , ,\ ! ! ! X! 	+ 	+ 	+ X	+  .    .  6 6 6p        B
 
 
 
     37 ] ] ] ] ] ]~  &  N "'
  + + + + +d "'[ [ [ [ [6N& N& N& N&`O O O O O Or1   r=   rV  types.PingRequestr   c                P   K   t          j        t          j                              S r-   )rH   r   r   rU  s    r/   rJ   rJ     s       e/11222r1   )r6   r7   r8   r9   )rV  r  r8   r   )L__doc__
__future__r   _annotationsr   contextvarsr  rj   r   collections.abcr   r   r   r   
contextlibr   r	   r
   typingr   r   r   r   rI  r  anyio.streams.memoryr   r   pydanticr   typing_extensionsr   	mcp.typesrH   '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   mcp.shared.messager   r   mcp.shared.sessionr   mcp.shared.tool_name_validationr   	getLoggerr2   rO   r   r!   r  r?   r"   __annotations__ContentBlockr#   r  r$   
ContextVarr%   r'   r;   r=   rJ   r5   r1   r/   <module>r     sO  A A AF 3 2 2 2 2 2         H H H H H H H H H H H H W W W W W W W W W W 0 0 0 0 0 0 0 0 0 0 0 0      R R R R R R R R       % % % % % %       @ @ @ @ @ @ A A A A A A C C C C C C A A A A A A 3 3 3 3 3 3 , , , , , , - - - - - - * * * * * * D D D D D D D D / / / / / / G G G G G G		8	$	$'+S9997:s+++  $CH~  - - - -!)%*<!=  = = = = %&9;L&L M  M M M M Pf{OefsOtOt t t t t	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	 	 	 	K
O K
O K
O K
O K
OW_h./ K
O K
O K
O\3 3 3 3 3 3r1   