
    )`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l0m1Z1m2Z2 ddl3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9  ej:        e;          Z< ede          Z= ede          Z>e?e@ef         ZAdeBd<   ee!jC                 ZDdeBd<   eEeDeAf         ZFdeBd<    ejG        d          ZHdeBd<    G d d          ZIed+d$            ZJ G d% d&ee=e>f                   ZKd,d*ZLd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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dS )
NotificationOptionsFprompts_changedboolresources_changedtools_changedc                0    || _         || _        || _        d S N)r)   r+   r,   )selfr)   r+   r,   s       n/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/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__r1    r2   r0   r(   r(   p   s8         !&"'#	+ + + + + + +r2   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
    Nr6   )r7   s    r0   lifespanr<   |   s       HHHHHHr2   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?   rA   rC   rD   rE   r<   typesPingRequest_ping_handlerrequest_handlersnotification_handlers_tool_cache_experimental_handlersloggerdebug)r/   r?   rA   rC   rD   rE   r<   s          r0   r1   zServer.__init__   sz     	(&
 }[
 RT"24CG#-t44444r2   notification_optionsNotificationOptions | Noneexperimental_capabilities dict[str, dict[str, Any]] | Noner9   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@   r9   c                J    	 ddl m}  ||           S # t          $ r Y nw xY wdS )Nr   )rA   unknown)importlib.metadatarA   	Exception)rW   rA   s     r0   pkg_versionz9Server.create_initialization_options.<locals>.pkg_version   sP    666666ww'''    9s    
  mcp)server_nameserver_versioncapabilitiesrC   rD   rE   )rW   r@   r9   r@   )r   r?   rA   get_capabilitiesr(   rC   rD   rE   )r/   rR   rT   r\   s       r0   create_initialization_optionsz$Server.create_initialization_options   s    	 	 	 	 %	+/<O4<<[[=O=O..$=(;(=(=)/R  *(*

 

 

 
	
r2   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)	subscriberf   )prompts	resourcestoolsloggingexperimentalcompletions)rI   ListPromptsRequestrL   PromptsCapabilityr)   ListResourcesRequestResourcesCapabilityr+   ListToolsRequestToolsCapabilityr,   SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilitiesrO   update_capabilities)	r/   rR   rT   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilityr`   s	            r0   ra   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r2   8RequestContext[ServerSession, LifespanResultT, RequestT]c                4    t                                           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   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.
        )rO   r   rL   rM   r   s    r0   rl   zServer.experimental   s1     &.*>tTEZ\`\v*w*wD'**r2   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)rh   )
isinstancerI   ListPromptsResultServerResultr   resultwrappers     r0   handlerz7Server.list_prompts.<locals>.decorator.<locals>.handler  sn      &ws||++++++fe&=>> W -f555 !-e.Ef.U.U.UVVVr2   )r   r   )rP   rQ   r   rI   rn   rL   r   r   r   r/   s     @r0   	decoratorz&Server.list_prompts.<locals>.decorator  sg     LLDEEE)$0HIIGW W W W W W ?FD!%":;Kr2   )r   r   r6   r/   r   s   ` r0   list_promptszServer.list_prompts  )    	 	 	 	 	 	( r2   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?   	argumentsrI   r   )r   
prompt_getr   s     r0   r   z5Server.get_prompt.<locals>.decorator.<locals>.handler  sD      #'4
9M#N#NNNNNNN
)*555r2   )r   r   )rP   rQ   rL   rI   GetPromptRequestr   r   r/   s   ` r0   r   z$Server.get_prompt.<locals>.decorator  sO     LLCDDD6 6 6 6 6 6 =DD!%"89Kr2   )r   r   r6   r   s   ` r0   
get_promptzServer.get_prompt  s)    
	 
	 
	 
	 
	 
	 r2   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)ri   )r   rI   ListResourcesResultr   r   s     r0   r   z9Server.list_resources.<locals>.decorator.<locals>.handler1  so      &ws||++++++fe&?@@ [ -f555 !-e.GRX.Y.Y.YZZZr2   )r   r   )rP   rQ   r   rI   rp   rL   r   s     @r0   r   z(Server.list_resources.<locals>.decorator)  sh     LLGHHH)$0JKKG[ [ [ [ [ [ AHD!%"<=Kr2   )r   r   r6   r   s   ` r0   list_resourceszServer.list_resources(  r   r2   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 ListResourceTemplatesRequestr7   r   c                v   K                 d {V }t          j        t          j        |                    S )N)resourceTemplates)rI   r   ListResourceTemplatesResult)r7   	templatesr   s     r0   r   zBServer.list_resource_templates.<locals>.decorator.<locals>.handlerC  s>      "&$&&LLLLLL	)%*K^g*h*h*hiiir2   )r7   r   )rP   rQ   rL   rI   ListResourceTemplatesRequestr   s   ` r0   r   z1Server.list_resource_templates.<locals>.decorator@  sT    LLOPPPj j j j j j IPD!%"DEKr2   )r   r   r6   r   s   ` r0   list_resource_templateszServer.list_resource_templates?  )    	 	 	 	 	 	 r2   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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_typerB   metadict[str, Any] | Nonec                *   |d|ini }| xxt           d x%\   }  t          j        dj        j        | |pdd|S   xt
          d xH\   } t          j        dj        j        t          j        |           	                                |pdd|S   d S )N_metar6   z
text/plain)uritextmimeTypezapplication/octet-stream)r   blobr   )
r@   rI   TextResourceContentsr   r   bytesBlobResourceContentsbase64	b64encodedecode)r   r   r   meta_kwargsr   s       r0   create_contentzPServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.create_contentU  s    EIEU7D//[]K*]SUUUUUUU#(#= $$'JN%))2)Bl$ $ #.	$ $  +] -UWWWWWW#(#= $$'JN%+%5d%;%;%B%B%D%D)2)P6P$ $ #.	$ $  -___r2   r6   zdReturning str or bytes from read_resource is deprecated. Use Iterable[ReadResourceContents] instead.   )
stacklevelc                \    g | ](} |j         |j        t          |d d                    )S )r   N)contentr   getattr).0content_itemr   s     r0   
<listcomp>zLServer.read_resource.<locals>.decorator.<locals>.handler.<locals>.<listcomp>r  sS     ) ) ) !- +N , 4l6LgVbdjlpNqNq ) ) )r2   )contentsz+Unexpected return type from read_resource: r.   )r   r   r   rB   r   r   )r   r   r@   r   warningswarnDeprecationWarningr   rI   r   ReadResourceResult
ValueErrortype)r   r   r   r   r   contents_listr   r   s   `     @r0   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) ) ) ) 19	) ) )  %1!4)6       0/ ()eW[\bWcWc)e)efff),")    r2   )r   r   )rP   rQ   rL   rI   ReadResourceRequestr   s   ` r0   r   z'Server.read_resource.<locals>.decoratorM  sQ     LLFGGG2 2 2 2 2 2h @GD!%";<Kr2   )r   r   r6   r   s   ` r0   read_resourcezServer.read_resourceL  s*    :	 :	 :	 :	 :	 :	x r2   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   levelrI   r   EmptyResultr   r   s    r0   r   z<Server.set_logging_level.<locals>.decorator.<locals>.handler  sH      d3:+,,,,,,,,,)%*;*=*=>>>r2   )r   r   )rP   rQ   rL   rI   rt   r   s   ` r0   r   z+Server.set_logging_level.<locals>.decorator  sM    LLBCCC? ? ? ? ? ? <CD!%"78Kr2   )r   r   r6   r   s   ` r0   set_logging_levelzServer.set_logging_level  r   r2   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   rI   r   r   r   s    r0   r   z=Server.subscribe_resource.<locals>.decorator.<locals>.handler  G      d3:>*********)%*;*=*=>>>r2   )r   r   )rP   rQ   rL   rI   SubscribeRequestr   s   ` r0   r   z,Server.subscribe_resource.<locals>.decorator  sM    LLCDDD? ? ? ? ? ? =DD!%"89Kr2   r   r   r6   r   s   ` r0   subscribe_resourcezServer.subscribe_resource  r   r2   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    r0   r   z?Server.unsubscribe_resource.<locals>.decorator.<locals>.handler  r   r2   )r   r   )rP   rQ   rL   rI   UnsubscribeRequestr   s   ` r0   r   z.Server.unsubscribe_resource.<locals>.decorator  sM    LLEFFF? ? ? ? ? ? ?FD!%":;Kr2   r   r6   r   s   ` r0   unsubscribe_resourcezServer.unsubscribe_resource  r   r2   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)rj   )	r   rI   ListToolsResultrj   r   r?   rN   r   clear)r   r   toolr/   r   s      r0   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Rr2   )r   r   )rP   rQ   r   rI   rr   rL   r   s     @r0   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Kr2   )r   r   r6   r   s   ` r0   
list_toolszServer.list_tools  s)    	 	 	 	 	 	< r2   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)rI   r   CallToolResultTextContent)r/   r   s     r0   _make_error_resultzServer._make_error_result  sE    ! *]KKKL  
 
 	
r2   	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)rN   rI   rr   rL   rP   rQ   r   warning)r/   r  r   s      r0   _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]^^^r2   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>          $ r,}	                    tA          |                    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   rI   r  r   CreateTaskResulttuplelenr   r%   dictr#   r  jsondumpshasattrr$   r   r3   outputSchemalistr   r[   r@   )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 :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$)     3      ; ; ;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  )rP   rQ   rL   rI   CallToolRequest)r   r   r/   r  s   ` r0   r   z#Server.call_tool.<locals>.decorator  sZ     LLBCCC?; ?; ?; ?; ?; ?; ?; ?;B <CD!%"78Kr2   )r   r  r6   )r/   r  r   s   `` r0   	call_toolzServer.call_tool  s7    P	 P	 P	 P	 P	 P	 P	d r2   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    r0   r   z@Server.progress_notification.<locals>.decorator.<locals>.handlerU  sc      dJ,J'J$J&	          r2   )r   r/  )rP   rQ   rM   rI   ProgressNotificationr   s   ` r0   r   z/Server.progress_notification.<locals>.decoratorP  sP     LLGHHH      FMD&u'ABKr2   )r   r-  r6   r   s   ` r0   progress_notificationzServer.progress_notificationO  s)    	 	 	 	 	 	  r2   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)valuesr3  hasMore)
completion)r   refargumentcontextrI   r   CompleteResult
Completion)r   r=  r   s     r0   r   z5Server.completion.<locals>.decorator.<locals>.handlerq  s      #'4

8KSZM_#`#```````
)(%1 $.:"-RtTRRR    r2   )r   r9  )rP   rQ   rL   rI   rv   r   s   ` r0   r   z$Server.completion.<locals>.decoratore  sO     LLBCCC      <CD!%"78Kr2   )r   r7  r6   r   s   ` r0   r=  zServer.completionb  s)    	 	 	 	 	 	2 r2   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)rI  zReceived message: %s)r	   enter_async_contextr<   r   rO   task_supportconfigure_sessionrunanyiocreate_task_groupincoming_messagesrP   rQ   
start_soon_handle_message)r/   rC  rE  rG  rH  rI  stacklifespan_contextsessionrL  tgr  s               r0   rN  z
Server.run  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 | ExceptionrV  r   rU  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)rootr6   z Received exception from stream: errorzInternal Server Errorzmcp.server.exception_handler)r   r   rP   zWarning: %s: %s)r   catch_warningsr   rI   ClientRequest_handle_requestClientNotification_handle_notificationr[   rP   r^  send_log_messageinfocategoryr3   r  )
r/   r  rV  rU  rH  wr   	respondernotifyr  s
             r0   rS  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)r\  close_sse_streamclose_standalone_sse_streamz4Request %s cancelled - duplicate response suppressedr   )coder  r   zMethod not found)rt  r  zResponse sent)%rP   re  r   r3   rL   r   rQ   message_metadatar   r   r   rr  rs  client_paramsr`   rO   rL  r#  r   r   r&   setr   
request_idrequest_metar   r   r^  rO  get_cancelled_exc_classresetr[   rI   	ErrorDatar@   respondMETHOD_NOT_FOUND)r/   r  r   rV  rU  rH  r   tokenrequest_dataclose_sse_stream_cbclose_standalone_sse_stream_cbclient_capabilitiesrL  rn  responseerrs                   r0   ra  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ri  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)rM   r   r   rP   rQ   r3   r[   	exception)r/   ri  r   s      r0   rc  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@   rA   rB   rC   rB   rD   rB   rE   rF   r<   rG   )NN)rR   rS   rT   rU   r9   r   )rR   r(   rT   rc   r9   rd   )r9   r   )r9   r   )r   r@   r9   r  )r  r@   r9   r	  )r  r*   )FF)
rC  rD  rE  rF  rG  r   rH  r*   rI  r*   )F)r  rX  rV  r   rU  r    rH  r*   )
r  rj  r   rk  rV  r   rU  r    rH  r*   )ri  r   )r3   r4   r5   r<   r1   rb   ra   propertyr   rl   r   r   r   r   r   r   r   r   r   r  r  r+  r5  r=  rN  rS  ra  rc  r6   r2   r0   r>   r>      s+        ##'"&)- 5 5 5 5 58 <@FJ
 
 
 
 
:, , , ,\ ! ! ! X! 	+ 	+ 	+ X	+  .    .  = = =~        B
 
 
 
     37 a a a a a aF  &  N "'
  + + + + +d "'[ [ [ [ [6N& N& N& N&`O O O O O Or2   r>   r\  types.PingRequestr  c                P   K   t          j        t          j                              S r.   )rI   r   r   r[  s    r0   rK   rK   "  s       e/11222r2   )r7   r8   r9   r:   )r\  r  r9   r  )M__doc__
__future__r   _annotationsr   contextvarsr!  rk   r   collections.abcr   r   r   r   
contextlibr   r	   r
   typingr   r   r   r   rO  r  anyio.streams.memoryr   r   pydanticr   typing_extensionsr   	mcp.typesrI   '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   rP   r    r"   r   r@   r#   __annotations__ContentBlockr$   r  r%   
ContextVarr&   r(   r<   r>   rK   r6   r2   r0   <module>r     sU  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 , , , , , , - - - - - - G G G G G G G G 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	+ 	+ 	+ 	+ 	+ 	+ 	+ 	+ 	 	 	 	V
O V
O V
O V
O V
OW_h./ V
O V
O V
Or3 3 3 3 3 3r2   