
    Gj                    n   % S r SSKJr  SSKrSSKrSSKrSSKrSSKrSSK	J
r
JrJrJr  SSKJrJrJr  SSKJrJrJrJr  SSKrSSKrSSKJrJr  SSKJr  SS	KJrJ r   SSK!J"r"  SS
K#J$r$  SSK%J&r&  SSK'J(r(  SSK)J*r*  SSK+J,r,  SSK-J.r.  SSK/J0r0  SSK1J2r2J3r3  SSK4J5r5J6r6  SSK7J8r8  SSK9J:r:  \Rv                  " \<5      r=\" S\S9r>\" S\S9r?\@\A\4   rBS\CS'   \\"R                     rES\CS'   \F\E\B4   rGS\CS'   \R                  " S5      rIS\CS'    " S S5      rJ\S$S  j5       rK " S! S"\\>\?4   5      rLS%S# jrMg)&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                  2    \ rS rSr   S     SS jjrSrg)NotificationOptionsp   c                (    Xl         X l        X0l        g Nprompts_changedresources_changedtools_changed)selfr.   r/   r0   s       \/Users/admin/workspace/tools/venv/lib/python3.13/site-packages/mcp/server/lowlevel/server.py__init__NotificationOptions.__init__q   s      /!2*    r-   N)FFF)r.   boolr/   r6   r0   r6   )__name__
__module____qualname____firstlineno__r3   __static_attributes__ r5   r2   r)   r)   p   s3     !&"'#	++  + 	+ +r5   r)   c                  #    0 7v   g7f)zDefault lifespan context manager that does nothing.

Args:
    server: The server instance this lifespan is managing

Returns:
    An empty context object
Nr<   )_s    r2   lifespanr?   |   s      Hs   	c                     \ rS rSrSSSS\4           SS jjr  S     S S jjr      S!S jr\  S"S j5       r	\\
" S5      S#S j5       5       rS	 rS
 rS rS rS rS rS rS rS rS$S jrS%S jrSS.S&S jjrS rS r  S'         S(S jjr S)       S*S jjr          S+S jrS,S jrSrg)-Server   Nc                    Xl         X l        X0l        X@l        XPl        X`l        [        R                  [        0U l	        0 U l
        0 U l        S U l        [        R                  SU5        g )NzInitializing server %r)nameversioninstructionswebsite_urliconsr?   typesPingRequest_ping_handlerrequest_handlersnotification_handlers_tool_cache_experimental_handlersloggerdebug)r1   rD   rE   rF   rG   rH   r?   s          r2   r3   Server.__init__   se     	(&
 }[
 RT"24CG#-t4r5   c           	        SS jn[        U R                  U R                  (       a  U R                  OU" S5      U R                  U=(       d
    [	        5       U=(       d    0 5      U R
                  U R                  U R                  S9$ )z8Create initialization options from this server instance.c                @     SSK Jn  U" U 5      $ ! [         a     gf = f)Nr   )rE   unknown)importlib.metadatarE   	Exception)packagerE   s     r2   pkg_version9Server.create_initialization_options.<locals>.pkg_version   s*    6w'' s    
mcp)server_nameserver_versioncapabilitiesrF   rG   rH   )rX   strreturnr_   )r   rD   rE   get_capabilitiesr)   rF   rG   rH   )r1   notification_optionsexperimental_capabilitiesrY   s       r2   create_initialization_options$Server.create_initialization_options   sn    	 %		+/<<4<<[=O..$=(;(=)/R **((**

 
	
r5   c           	        SnSnSnSnSn[         R                  U R                  ;   a  [         R                  " UR                  S9n[         R
                  U R                  ;   a  [         R                  " SUR                  S9n[         R                  U R                  ;   a  [         R                  " UR                  S9n[         R                  U R                  ;   a  [         R                  " 5       n[         R                  U R                  ;   a  [         R                  " 5       n[         R                  " UUUUUUS9nU R                   (       a  U R                   R#                  U5        U$ )z9Convert existing handlers to a ServerCapabilities object.N)listChangedF)	subscriberg   )prompts	resourcestoolsloggingexperimentalcompletions)rI   ListPromptsRequestrL   PromptsCapabilityr.   ListResourcesRequestResourcesCapabilityr/   ListToolsRequestToolsCapabilityr0   SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilitiesrO   update_capabilities)	r1   rb   rc   prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilityr^   s	            r2   ra   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r5   c                *    [         R                  5       $ )zFIf called outside of a request context, this will raise a LookupError.)r'   getr1   s    r2   request_contextServer.request_context   s    
   r5   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                ~    U R                   c%  [        X R                  U R                  5      U l         U R                   $ )zExperimental 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.
)rO   r   rL   rM   r   s    r2   rm   Server.experimental   s8     &&.*>tEZEZ\`\v\v*wD'***r5   c                   ^    SU 4S jjnU$ )Nc                   >^ [         R                  S5        [        U [        R                  5      mSU4S jjnUTR
                  [        R                  '   U $ )Nz)Registering handler for PromptListRequestc                   >#    T" U 5      I S h  vN n[        U[        R                  5      (       a  [        R                  " U5      $ [        R                  " [        R                  " US95      $  Na7f)N)ri   )
isinstancerI   ListPromptsResultServerResultreqresultwrappers     r2   handler7Server.list_prompts.<locals>.decorator.<locals>.handler  sY     &s|+fe&=&=>> --f55 !--e.E.Ef.UVV ,   A3A1A"A3)r   ztypes.ListPromptsRequest)rP   rQ   r   rI   ro   rL   funcr   r   r1   s     @r2   	decorator&Server.list_prompts.<locals>.decorator	  sH     LLDE)$0H0HIGW ?FD!!%":":;Kr5   )r   zvCallable[[], Awaitable[list[types.Prompt]]] | Callable[[types.ListPromptsRequest], Awaitable[types.ListPromptsResult]]r<   r1   r   s   ` r2   list_promptsServer.list_prompts  s    	W	( r5   c                   ^    SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz(Registering handler for GetPromptRequestc                   >#    T" U R                   R                  U R                   R                  5      I S h  vN n[        R                  " U5      $  N7fr,   )paramsrD   	argumentsrI   r   )r   
prompt_getr   s     r2   r   5Server.get_prompt.<locals>.decorator.<locals>.handler%  s>     #'

9M9M#NN
))*55 Os   5AAA)r   ztypes.GetPromptRequest)rP   rQ   rL   rI   GetPromptRequestr   r   r1   s   ` r2   r   $Server.get_prompt.<locals>.decorator   s5     LLCD6 =DD!!%"8"89Kr5   )r   zHCallable[[str, dict[str, str] | None], Awaitable[types.GetPromptResult]]r<   r   s   ` r2   
get_promptServer.get_prompt  s    
	Z
	 r5   c                   ^    SU 4S jjnU$ )Nc                   >^ [         R                  S5        [        U [        R                  5      mSU4S jjnUTR
                  [        R                  '   U $ )Nz,Registering handler for ListResourcesRequestc                   >#    T" U 5      I S h  vN n[        U[        R                  5      (       a  [        R                  " U5      $ [        R                  " [        R                  " US95      $  Na7f)N)rj   )r   rI   ListResourcesResultr   r   s     r2   r   9Server.list_resources.<locals>.decorator.<locals>.handler7  sZ     &s|+fe&?&?@@ --f55 !--e.G.GRX.YZZ ,r   )r   ztypes.ListResourcesRequest)rP   rQ   r   rI   rq   rL   r   s     @r2   r   (Server.list_resources.<locals>.decorator/  sI     LLGH)$0J0JKG[ AHD!!%"<"<=Kr5   )r   z|Callable[[], Awaitable[list[types.Resource]]] | Callable[[types.ListResourcesRequest], Awaitable[types.ListResourcesResult]]r<   r   s   ` r2   list_resourcesServer.list_resources.  s    	[	( r5   c                   ^  SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz4Registering handler for ListResourceTemplatesRequestc                ~   >#    T" 5       I S h  vN n[         R                  " [         R                  " US95      $  N,7f)N)resourceTemplates)rI   r   ListResourceTemplatesResult)r>   	templatesr   s     r2   r   BServer.list_resource_templates.<locals>.decorator.<locals>.handlerI  s1     "&&L	))%*K*K^g*hii )s   =;-=)r>   r   )rP   rQ   rL   rI   ListResourceTemplatesRequestr   s   ` r2   r   1Server.list_resource_templates.<locals>.decoratorF  s5    LLOPj IPD!!%"D"DEKr5   )r   z5Callable[[], Awaitable[list[types.ResourceTemplate]]]r<   r   s   ` r2   list_resource_templatesServer.list_resource_templatesE      	 r5   c                   ^    SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz+Registering handler for ReadResourceRequestc                t  >^ #    T" T R                   R                  5      I S h  vN nS	S
U 4S jjjnU===[        S` =b  u   O  =[        S` =b  u   O    O'  n  [        R
                  " S[        SS9  U" US 5      nO  =[        S` =bd  u   nU Vs/ s H,  nU" UR                  UR                  [        USS 5      5      PM.     nn[        R                  " [        R                  " US95      $      [        S[        U5       35      e[        R                  " [        R                  " U/S95      $  GNs  snf 7f)Nmetac                ~  > Ub  SU0O0 nU ==[         S` =b;  u   n   [        R                  " STR                  R                  U U=(       d    SS.UD6$     =[
        S` =b\  u   n [        R                  " STR                  R                  [        R                  " U 5      R                  5       U=(       d    SS.UD6$     g )N_metar<   z
text/plain)uritextmimeTypezapplication/octet-stream)r   blobr   )
r_   rI   TextResourceContentsr   r   bytesBlobResourceContentsbase64	b64encodedecode)data	mime_typer   meta_kwargsr   s       r2   create_contentPServer.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$ #.	$  -r5   r<   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   r_   r   warningswarnDeprecationWarningr   contentr   getattrrI   r   ReadResourceResult
ValueErrortype)	r   r   r   r   r   r   content_itemcontents_listr   s	   `       r2   r   8Server.read_resource.<locals>.decorator.<locals>.handlerX  s?    #CJJNN33 & 00 J.'(	 #1t"< 1 0/
 19	) 19 + , 4 4l6L6LgVbdjlpNq 19	 & )  %11!44)6   0 (+VW[\bWcVd)eff)),,") [ 4>)s#    D8D0A+D83D3A.D83D8)r   ztypes.ReadResourceRequest)rP   rQ   rL   rI   ReadResourceRequestr   s   ` r2   r   'Server.read_resource.<locals>.decoratorS  s7     LLFG2h @GD!!%";";<Kr5   )r   zKCallable[[AnyUrl], Awaitable[str | bytes | Iterable[ReadResourceContents]]]r<   r   s   ` r2   read_resourceServer.read_resourceR  s    :	]:	x r5   c                   ^  SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz'Registering handler for SetLevelRequestc                   >#    T" U R                   R                  5      I S h  vN   [        R                  " [        R                  " 5       5      $  N-7fr,   )r   levelrI   r   EmptyResultr   r   s    r2   r   <Server.set_logging_level.<locals>.decorator.<locals>.handler  s=     3::++,,,))%*;*;*=>> -    AA.A)r   ztypes.SetLevelRequest)rP   rQ   rL   rI   ru   r   s   ` r2   r   +Server.set_logging_level.<locals>.decorator  s3    LLBC? <CD!!%"7"78Kr5   )r   z/Callable[[types.LoggingLevel], Awaitable[None]]r<   r   s   ` r2   set_logging_levelServer.set_logging_level  r   r5   c                   ^  SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz(Registering handler for SubscribeRequestc                   >#    T" U R                   R                  5      I S h  vN   [        R                  " [        R                  " 5       5      $  N-7fr,   r   r   rI   r   r   r   s    r2   r   =Server.subscribe_resource.<locals>.decorator.<locals>.handler  ;     3::>>***))%*;*;*=>> +r   )r   ztypes.SubscribeRequest)rP   rQ   rL   rI   SubscribeRequestr   s   ` r2   r   ,Server.subscribe_resource.<locals>.decorator  s3    LLCD? =DD!!%"8"89Kr5   r   z#Callable[[AnyUrl], Awaitable[None]]r<   r   s   ` r2   subscribe_resourceServer.subscribe_resource  r   r5   c                   ^  SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz*Registering handler for UnsubscribeRequestc                   >#    T" U R                   R                  5      I S h  vN   [        R                  " [        R                  " 5       5      $  N-7fr,   r   r   s    r2   r   ?Server.unsubscribe_resource.<locals>.decorator.<locals>.handler  r   r   )r   ztypes.UnsubscribeRequest)rP   rQ   rL   rI   UnsubscribeRequestr   s   ` r2   r   .Server.unsubscribe_resource.<locals>.decorator  s3    LLEF? ?FD!!%":":;Kr5   r   r<   r   s   ` r2   unsubscribe_resourceServer.unsubscribe_resource  r   r5   c                   ^    SU 4S jjnU$ )Nc                   >^ [         R                  S5        [        U [        R                  5      mSUU4S jjnUTR
                  [        R                  '   U $ )Nz(Registering handler for ListToolsRequestc                  >#    T" U 5      I S h  vN n[        U[        R                  5      (       aW  UR                   H1  n[	        UR
                  5        UTR                  UR
                  '   M3     [        R                  " U5      $ TR                  R                  5         U H1  n[	        UR
                  5        UTR                  UR
                  '   M3     [        R                  " [        R                  " US95      $  N7f)N)rk   )	r   rI   ListToolsResultrk   r    rD   rN   r   clear)r   r   toolr1   r   s      r2   r   5Server.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   DDC4D)r   ztypes.ListToolsRequest)rP   rQ   r   rI   rs   rL   r   s     @r2   r   $Server.list_tools.<locals>.decorator  sN     LLCD)$0F0FGGS S& =DD!!%"8"89Kr5   )r   zpCallable[[], Awaitable[list[types.Tool]]] | Callable[[types.ListToolsRequest], Awaitable[types.ListToolsResult]]r<   r   s   ` r2   
list_toolsServer.list_tools  s    	S	< r5   c           	     |    [         R                  " [         R                  " [         R                  " SUS9/SS95      $ )z3Create a ServerResult with an error CallToolResult.r   r   r   T)r   isError)rI   r   CallToolResultTextContent)r1   error_messages     r2   _make_error_resultServer._make_error_result  s9    !!  **]KL
 	
r5   c                V  #    XR                   ;  a_  [        R                  U R                  ;   aA  [        R                  SU5        U R                  [        R                     " S5      I Sh  vN   U R                   R                  U5      nUc  [        R                  SU5        U$  N:7f)zlGet 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   rs   rL   rP   rQ   r   warning)r1   	tool_namer  s      r2   _get_cached_tool_definition"Server._get_cached_tool_definition  s     
 ,,,%%)>)>>GS++E,B,BCDIII##I.<NNRT]^ Js   A*B),B'-;B)T)validate_inputc                   ^ ^   SU U4S jjnU$ )a7  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                   >^  [         R                  S5        SU UU4S jjnUTR                  [        R                  '   T $ )Nz'Registering handler for CallToolRequestc                  >#     U R                   R                  nU R                   R                  =(       d    0 nT	R                  U5      I S h  vN nT
(       a&  U(       a   [        R
                  " X#R                  S9  T" X5      I S h  vN n[        U[        R                  5      (       a  [        R                  " U5      $ [        U[        R                  5      (       a  [        R                  " U5      $ [        U[        5      (       a"  [!        U5      S:X  a  [#        [$        U5      u  pgO[        U[&        5      (       a:  [#        [(        U5      n[        R*                  " S[,        R.                  " USS9S9/nOK[1        US5      (       a  [#        [2        U5      nS nO'T	R                  S[5        U5      R6                   35      $ U(       a@  UR8                  b3  Uc  T	R                  S	5      $  [        R
                  " XsR8                  S9  [        R                  " [        R                  " [;        U5      USS95      $  GN! [        R                   a(  nT	R                  SUR                   35      s S nA$ S nAff = f GN! [        R                   a(  nT	R                  S
UR                   35      s S nA$ S nAff = f! [<         a    e [>         a$  nT	R                  [A        U5      5      s S nA$ S nAff = f7f)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   rD   r   r  
jsonschemavalidateinputSchemaValidationErrorr  messager   rI   r  r   CreateTaskResulttuplelenr   r&   dictr$   r  jsondumpshasattrr%   r   r7   outputSchemalistr   rW   r_   )r   r  r   r  eresultsunstructured_contentmaybe_structured_contentr   r1   r  s           r2   r   4Server.call_tool.<locals>.decorator.<locals>.handler  s    >; #

I #

 4 4 :I!%!A!A)!LLD &$c&//K[K[\
 %)$>>G
 "'5+?+?@@$11'::#GU-C-CDD$11'::#GU33G8IIMN`biIjF,.F#GT22378I73S0050A0AvTXT^T^_fopTq0r/s, *55/34G/Q,370#669[\`ah\i\r\r[s7tuu  1 1 =3;#'#:#: q$ h * 3 3=U^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   LA	K	 IK	 "I  K	 J8K	 L4K	 9L:CK	 
L'K	 2L4J
 2K	 LK	 JI?9J:K	 >L?JK	 
KK;K<K	  LKK	 	LK<6L7L<LL)r   ztypes.CallToolRequest)rP   rQ   rL   rI   CallToolRequest)r   r   r1   r  s   ` r2   r   #Server.call_tool.<locals>.decorator  s;     LLBC?; ?;B <CD!!%"7"78Kr5   )r   zCallable[..., Awaitable[UnstructuredContent | StructuredContent | CombinationContent | types.CallToolResult | types.CreateTaskResult]]r<   )r1   r  r   s   `` r2   	call_toolServer.call_tool  s#    P		P	 P	d r5   c                   ^    SU 4S jjnU$ )Nc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz,Registering handler for ProgressNotificationc                   >#    T" U R                   R                  U R                   R                  U R                   R                  U R                   R                  5      I S h  vN   g  N7fr,   )r   progressTokenprogresstotalr&  r   s    r2   r   @Server.progress_notification.<locals>.decorator.<locals>.handler[  sL     JJ,,JJ''JJ$$JJ&&	  s   AA*"A(#A*)r   ztypes.ProgressNotification)rP   rQ   rM   rI   ProgressNotificationr   s   ` r2   r   /Server.progress_notification.<locals>.decoratorV  s6     LLGH FMD&&u'A'ABKr5   )r   zGCallable[[str | int, float, float | None, str | None], Awaitable[None]]r<   r   s   ` r2   progress_notificationServer.progress_notificationU  s    	Y	  r5   c                   ^    SU 4S jjnU$ )z7Provides completions for prompts and resource templatesc                ~   >^  [         R                  S5        SU 4S jjnUTR                  [        R                  '   T $ )Nz'Registering handler for CompleteRequestc           
     :  >#    T" U R                   R                  U R                   R                  U R                   R                  5      I S h  vN n[        R
                  " [        R                  " Ub  US95      $ [        R                  " / S S S9S95      $  NK7f)N)valuesr>  hasMore)
completion)r   refargumentcontextrI   r   CompleteResult
Completion)r   rI  r   s     r2   r   5Server.completion.<locals>.decorator.<locals>.handlerw  s     #'



8K8KSZZM_M_#``
))((%1 $.  #--RtTR  as   A
BBAB)r   ztypes.CompleteRequest)rP   rQ   rL   rI   rw   r   s   ` r2   r   $Server.completion.<locals>.decoratork  s5     LLBC <CD!!%"7"78Kr5   )r   zCallable[[types.PromptReference | types.ResourceTemplateReference, types.CompletionArgument, types.CompletionContext | None], Awaitable[types.Completion | None]]r<   r   s   ` r2   rI  Server.completionh  s    		2 r5   c           
       #    [        5        IS h  vN nUR                  U R                  U 5      5      I S h  vN nUR                  [        UUUUS95      I S h  vN nU R                  (       a  U R                  R
                  OS n	U	b6  U	R                  XS9  UR                  U	R                  5       5      I S h  vN   [        R                  " 5        IS h  vN n
 UR                    S h  vN n[        R                  SU5        U
R                  U R                  UUUU5        M@   GN N N Nv NZ NF
 U
R                  R!                  5         O! U
R                  R!                  5         f = fS S S 5      IS h  vN    O! , IS h  vN  (       d  f       O= fS S S 5      IS h  vN    g ! , IS h  vN  (       d  f       g = f7f)N)	statelessz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cancel_scopecancel)r1   read_streamwrite_streaminitialization_optionsraise_exceptionsrS  stacklifespan_contextsessionrU  tgr&  s               r2   rW  
Server.run  sl      "##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0B-)0)B)B 	g%;WE 00##,,- $S D0	)B OO**,BOO**,# 100000# $#####s   GD.G$F4D1"F4D3A!F4>D5?F4D7F4 F"E.D;2D9
3D;68E.G1F43F45F47F49D;;E<FE33F6F4FF4F	FF	F4"G-F0.G4G:F=;GGc           	       #    [         R                  " SS9 nU==[        S` =bA  u  [        R                  S` =b+  u  pg  U   U R                  XX#U5      I S h  vN   S S S 5        O}    =[        R                  S` =b  u  n  U R                  U5      I S h  vN   OH  [        S` =b<  u   [        R                  SU 35        UR                  SSS	S
9I S h  vN   U(       a  Ue  U H8  n	[        R                  SU	R                  R                  U	R                  5        M:     S S S 5        g  N! , (       d  f       MX  = f N Nk! , (       d  f       g = f7f)NT)recordrequest)rootr<   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_notificationrW   rP   rm  send_log_messageinfocategoryr7   r&  )
r1   r&  re  rd  rb  wr   	respondernotifyr  s
             r2   r\  Server._handle_message  s)     $$D1QY%Le.A.A.KY""227\lmmm # Z ;U--::33F;;; ;[LL#CG9!MN!22%4= 3   
 (% ! -w/?/?/H/H'//Z # 21 n # < 21sk   E*ED,D*D,8ED>>EE 	E AE!	E*D,,
D;	6	E E
EEc                  #    [         R                  S[        U5      R                  5        U R                  R                  [        U5      5      =n(       Ga  [         R                  S[        U5      R                  5        S n S nS n	S n
UR                  ba  [        UR                  [        5      (       aB  UR                  R                  nUR                  R                  n	UR                  R                  n
UR                  (       a  UR                  R                  OS nU R                  (       a  U R                  R                   OS nS n[#        US5      (       a$  UR$                  b  ['        UR$                  SS 5      n[(        R+                  [-        UR.                  UR0                  UU[3        UUUUS9UU	U
S95      nU" U5      I S h  vN nUb  [(        R?                  U5        O#[B        RD                  " [B        RH                  S
S9n URK                  U5      I S h  vN   [         R                  S5        g  Np! [4         a  nUR6                  n S nANS nAf[8        R:                  " 5        aN    UR<                  (       a;  [         R                  SUR.                  5         Ub  [(        R?                  U5        g g e [@         a3  nU(       a  Ue[B        RD                  " S[G        U5      S S	9n S nAGN)S nAff = f! Ub  [(        R?                  U5        f f = f N! [8        RL                  [8        RN                  4 a#    [         R                  SUR.                  5         g f = f7f)NzProcessing request of type %szDispatching request of type %sr   task)task_metadata_client_capabilities_session_task_support)rk  close_sse_streamclose_standalone_sse_streamz4Request %s cancelled - duplicate response suppressedr   )coder&  r   zMethod not found)r  r&  z*Response for %s dropped - transport closedzResponse sent)(rP   rt  r   r7   rL   r   rQ   message_metadatar   r   r   r  r  client_paramsr^   rO   rU  r-  r   r   r'   setr   
request_idrequest_metar   r   rm  rX  get_cancelled_exc_class	cancelledresetrW   rI   	ErrorDatar_   METHOD_NOT_FOUNDrespondBrokenResourceErrorClosedResourceError)r1   r&  r   re  rd  rb  r   tokenrequest_dataclose_sse_stream_cbclose_standalone_sse_stream_cbclient_capabilitiesrU  r|  responseerrs                   r2   rp  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   BM-E	I  H>I  <M-L# #L!$L# (M->I   
L 
IL AL (L )M-
L (K;5L ;L  L LM-!L# #AM*'M-)M**M-c                &  #    U R                   R                  [        U5      5      =n(       a;  [        R	                  S[        U5      R
                  5         U" U5      I S h  vN   g g  N! [         a    [        R                  S5         g f = f7f)Nz#Dispatching notification of type %sz*Uncaught exception in notification handler)rM   r   r   rP   rQ   r7   rW   	exception)r1   rx  r   s      r2   rr  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)
rO   rN   rH   rF   r?   rD   rM   rL   rE   rG   )rD   r_   rE   r   rF   r   rG   r   rH   zlist[types.Icon] | Noner?   z[Callable[[Server[LifespanResultT, RequestT]], AbstractAsyncContextManager[LifespanResultT]])NN)rb   zNotificationOptions | Nonerc   z dict[str, dict[str, Any]] | Noner`   r   )rb   r)   rc   zdict[str, dict[str, Any]]r`   ztypes.ServerCapabilities)r`   z8RequestContext[ServerSession, LifespanResultT, RequestT])r`   r   )r  r_   r`   types.ServerResult)r  r_   r`   ztypes.Tool | None)r  r6   )FF)
r_  z5MemoryObjectReceiveStream[SessionMessage | Exception]r`  z&MemoryObjectSendStream[SessionMessage]ra  r   rb  r6   rS  r6   )F)r&  z`RequestResponder[types.ClientRequest, types.ServerResult] | types.ClientNotification | Exceptionre  r   rd  r!   rb  r6   )
r&  z9RequestResponder[types.ClientRequest, types.ServerResult]r   ztypes.ClientRequestTypere  r   rd  r!   rb  r6   )rx  r   )r7   r8   r9   r:   r?   r3   rd   ra   propertyr   r   rm   r   r   r   r   r   r   r   r   r
  r  r  r7  rB  rI  rW  r\  rp  rr  r;   r<   r5   r2   rA   rA      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r5   rA   c                \   #    [         R                  " [         R                  " 5       5      $ 7fr,   )rI   r   r   rj  s    r2   rK   rK   =  s     e//122s   *,)r>   z!Server[LifespanResultT, RequestT]r`   zAsyncIterator[dict[str, Any]])rk  ztypes.PingRequestr`   r  )N__doc__
__future__r   _annotationsr   contextvarsr+  rl   r   collections.abcr   r   r   r   
contextlibr   r	   r
   typingr   r   r   r   rX  r"  anyio.streams.memoryr   r   pydanticr   typing_extensionsr   r   	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    	getLoggerr7   rP   r!   r#   r*  r_   r$   __annotations__ContentBlockr%   r(  r&   
ContextVarr'   r)   r?   rA   rK   r<   r5   r2   <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[OeOefsOtL t	+ 	+ 	 	q
OW_h./ q
Oh3r5   