
    i/4                    F   d dl mZ d dlZd dlmZmZ d dlmZ d dlm	Z	m
Z
 d dlZd dlZd dlmZmZ d dlmZ d dlmZ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' e	rd dl(m)Z)  e'e*      Z+ G d de      Z, G d deeef         Z-y)    )annotationsN)	AwaitableCallable)AsyncExitStack)TYPE_CHECKINGAny)MemoryObjectReceiveStreamMemoryObjectSendStream)McpError)LifespanResultTNotificationOptionsRequestT)Server)InitializationOptions)ServerSession)stdio_server)SessionMessage)RequestResponder)AnyUrl)UI_EXTENSION_ID)
get_logger)FastMCPc                  N     e Zd ZdZd fdZedd       ZddZ	 	 d	 fdZ xZ	S )
MiddlewareServerSessionzMServerSession that routes initialization requests through FastMCP middleware.c                f    t        |   |i | t        j                  |      | _        d | _        y N)super__init__weakrefref_fastmcp_ref_subscription_task_groupselffastmcpargskwargs	__class__s       h/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/server/low_level.pyr   z MiddlewareServerSession.__init__'   s.    $)&)29++g2F@D%    c                @    | j                         }|t        d      |S zGet the FastMCP instance.z'FastMCP instance is no longer availabler!   RuntimeErrorr$   r%   s     r)   r%   zMiddlewareServerSession.fastmcp-   (     ##%?HIIr*   c                    | j                   }|y|j                  }|y|j                  xs i }|j                  d      }|sy||v S )zCheck if the connected client supports a given MCP extension.

        Inspects the ``extensions`` extra field on ``ClientCapabilities``
        sent by the client during initialization.
        F
extensions)_client_paramscapabilitiesmodel_extraget)r$   extension_idclient_paramscapsextrasr2   s         r)   client_supports_extensionz1MiddlewareServerSession.client_supports_extension5   sZ     ++ ))<!!'R,2JJ|,D
z))r*   c                   	
K   ddl }ddlm} t        j                  j
                  t        j                  j                        rd	j                  
	 	 	 	 d	
fd}|_	        	 	 	 	 d	 fd}|j                  j                  j                   j                         4 d{   } |j                  j
                  ddd	|
      }	  j                  j                  ||       d{   cddd      d{    S t(         U         d{   S 7 r7 .7  # t        $ ri}j                   s<5  j                  |j"                         d{  7   ddd       n## 1 sw Y   nxY wt$        j'                  d|       Y d}~nd}~ww xY wddd      d{  7   # 1 d{  7  sw Y   xY w7 w)z
        Override the _received_request method to route special requests
        through FastMCP middleware.

        Handles initialization requests and SEP-1686 task methods.
        r   N)MiddlewareContextc                4   K   |  |        d {   S 7 wr    )responsecaptured_responseoriginal_responds    r)   capturing_respondzDMiddlewareServerSession._received_request.<locals>.capturing_respondc   s       %-!-h7777s   c                   K   t         t                 d {    :t        j                  t
        j                  j                        rj                  S y 7 Awr   )r   r   _received_request
isinstancerootmcptypesInitializeResult)ctxr(   rA   	responderr$   s    r)   call_original_handlerzHMiddlewareServerSession._received_request.<locals>.call_original_handlerl   sX      3TLYWWW$0Z%**CII,F,F6 -111 Xs   AAAA)r%   sessionclientrequest
initialize)messagesourcetypemethodfastmcp_contextznReceived McpError but responder is already completed. Cannot send error response as response was already sent.)exc_info)r@   mcp.types.ServerResultreturnNone)rK   r=   rY   z!mcp.types.InitializeResult | None)fastmcp.server.context$fastmcp.server.middleware.middlewarer=   rF   rP   rG   rH   rI   InitializeRequestrespondservercontextContextr%   _run_middlewarer   
_completederrorloggerwarningr   rE   )r$   rL   r%   r=   rC   rM   fastmcp_ctx
mw_contexterA   rB   r(   s   ``       @@r)   rE   z)MiddlewareServerSession._received_requestH   s     	&Ji'',,cii.I.IJ @D(008088 !2I&2  ~~--55d 6  .%--22#"'$/
!%!=!="$9"   > W.y999?     %//&"+"3"3AGG"<<< 'YY W%& ' !    > :s   B%G,D-G0"F,D%2D!3D%6GD#GGG!D%#G%	F.F<E*E
E*!	F*E3/FF,FF,G%F(&G,F>2F53F>:G)r%   r   rY   r   )r7   strrY   bool)rL   zARequestResponder[mcp.types.ClientRequest, mcp.types.ServerResult])
__name__
__module____qualname____doc__r   propertyr%   r;   rE   __classcell__r(   s   @r)   r   r   $   s:    WE  *&M:TM: M:r*   r   c                       e Zd Zd fdZed	d       Z	 	 d
	 	 	 	 	 	 	 d fdZ	 	 	 	 	 	 d fdZ	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 ddZ		 	 ddZ
 xZS )LowLevelServerc                ~    t        |   |i | t        j                  |      | _        t        ddd      | _        y )NT)prompts_changedresources_changedtools_changed)r   r   r   r    r!   r   notification_optionsr#   s       r)   r   zLowLevelServer.__init__   s>    $)&)29++g2F %8 "%
!r*   c                @    | j                         }|t        d      |S r,   r-   r/   s     r)   r%   zLowLevelServer.fastmcp   r0   r*   c                D    || j                   }t        |   d||d|S )N)rz   experimental_capabilitiesr?   )rz   r   create_initialization_options)r$   rz   r}   r'   r(   s       r)   r~   z,LowLevelServer.create_initialization_options   s>      '#'#<#< w4 
!5&?
 
 	
r*   c                    ddl m} t        |   ||xs i       } |       |_        t        |dd      xs i }i |t        i i|_        |S )a=  Override to set capabilities.tasks as a first-class field per SEP-1686.

        This ensures task capabilities appear in capabilities.tasks instead of
        capabilities.experimental.tasks, which is required by the MCP spec and
        enables proper task detection by clients like VS Code Copilot 1.107+.
        r   )get_task_capabilitiesr2   N)!fastmcp.server.tasks.capabilitiesr   r   get_capabilitiestasksgetattrr   r2   )r$   rz   r}   r   r4   existing_extensionsr(   s         r)   r   zLowLevelServer.get_capabilities   sh     	L w/ %+
 34 L,5; 	 #O%8"N/2"Nr*   c           
     F  K   t               4 d{   }|j                  | j                  |              d{   }|j                  t        | j                  ||||             d{   }t        j                         4 d{   }	|	|_        |j                  2 3 d{   }
|	j                  | j                  |
|||       )7 7 7 a7 F7 ,6 ddd      d{  7   n# 1 d{  7  sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)zN
        Overrides the run method to use the MiddlewareServerSession.
        N)	stateless)r   enter_async_contextlifespanr   r%   anyiocreate_task_groupr"   incoming_messages
start_soon_handle_message)r$   read_streamwrite_streaminitialization_optionsraise_exceptionsr   stacklifespan_contextrN   tgrR   s              r)   runzLowLevelServer.run   s      "##u%*%>%>t}}T?R%SS!55'LL *' G ..00B350%,%>%> 'MM,,((# $S 1%>	 10000 $####s   D!CD!$DC
0D*C+DCDC%C#C
$C'!C%D!
DDDCC%DC!D%C7	+C.,C7	3D:D!DD!DDDD!c                     	 	 	 	 d fd}|S )a  
        Decorator for registering a read_resource handler with CreateTaskResult support.

        The MCP SDK's read_resource decorator does not support returning CreateTaskResult
        for background task execution. This decorator wraps the result in ServerResult.

        This decorator can be removed once the MCP SDK adds native CreateTaskResult support
        for resources.
        c                l     	 	 	 	 d fd}|j                   t        j                  j                  <    S )Nc                   K    | j                   j                         d {   }t        j                  j	                  |      S 7 #wr   )paramsurirH   rI   ServerResultreqresultfuncs     r)   handlerz@LowLevelServer.read_resource.<locals>.decorator.<locals>.handler#  s8       $CJJNN33yy--f55 4s    A	A$A	)r   zmcp.types.ReadResourceRequestrY   rX   )request_handlersrH   rI   ReadResourceRequestr   r   r$   s   ` r)   	decoratorz/LowLevelServer.read_resource.<locals>.decorator  s;    626'6 DKD!!#))"?"?@Kr*   )r   XCallable[[AnyUrl], Awaitable[mcp.types.ReadResourceResult | mcp.types.CreateTaskResult]]rY   r   r?   r$   r   s   ` r)   read_resourcezLowLevelServer.read_resource  $    0		

	$ r*   c                     	 	 	 	 d fd}|S )a  
        Decorator for registering a get_prompt handler with CreateTaskResult support.

        The MCP SDK's get_prompt decorator does not support returning CreateTaskResult
        for background task execution. This decorator wraps the result in ServerResult.

        This decorator can be removed once the MCP SDK adds native CreateTaskResult support
        for prompts.
        c                l     	 	 	 	 d fd}|j                   t        j                  j                  <    S )Nc                   K    | j                   j                  | j                   j                         d {   }t        j                  j                  |      S 7 #wr   )r   name	argumentsrH   rI   r   r   s     r)   r   z=LowLevelServer.get_prompt.<locals>.decorator.<locals>.handlerO  sE       $CJJOOSZZ5I5IJJyy--f55 Ks   5AA$A)r   zmcp.types.GetPromptRequestrY   rX   )r   rH   rI   GetPromptRequestr   s   ` r)   r   z,LowLevelServer.get_prompt.<locals>.decoratorF  s;    6/6'6 AHD!!#))"<"<=Kr*   )r   iCallable[[str, dict[str, Any] | None], Awaitable[mcp.types.GetPromptResult | mcp.types.CreateTaskResult]]rY   r   r?   r   s   ` r)   
get_promptzLowLevelServer.get_prompt.  r   r*   )r%   r   r&   r   r'   r   rj   )NN)rz   zNotificationOptions | Noner}   z dict[str, dict[str, Any]] | Noner'   r   rY   r   )rz   r   r}   zdict[str, dict[str, Any]]rY   zmcp.types.ServerCapabilities)FF)
r   z5MemoryObjectReceiveStream[SessionMessage | Exception]r   z&MemoryObjectSendStream[SessionMessage]r   r   r   rl   r   rl   )rY   zCallable[[Callable[[AnyUrl], Awaitable[mcp.types.ReadResourceResult | mcp.types.CreateTaskResult]]], Callable[[AnyUrl], Awaitable[mcp.types.ReadResourceResult | mcp.types.CreateTaskResult]]])rY   zCallable[[Callable[[str, dict[str, Any] | None], Awaitable[mcp.types.GetPromptResult | mcp.types.CreateTaskResult]]], Callable[[str, dict[str, Any] | None], Awaitable[mcp.types.GetPromptResult | mcp.types.CreateTaskResult]]])rm   rn   ro   r   rq   r%   r~   r   r   r   r   rr   rs   s   @r)   ru   ru      s    

   <@FJ
8
 $D
 	

 

 1  $=  
&	 N "'"J" =" !6	"
 " "H*
*X*
*r*   ru   ).
__future__r   r   collections.abcr   r   
contextlibr   typingr   r   r   	mcp.typesrH   anyio.streams.memoryr	   r
   r   mcp.server.lowlevel.serverr   r   r   r   _Servermcp.server.modelsr   mcp.server.sessionr   mcp.server.stdior   mcp.shared.messager   mcp.shared.sessionr   pydanticr   fastmcp.server.appsr   fastmcp.utilities.loggingr   fastmcp.server.serverr   rm   re   r   ru   r?   r*   r)   <module>r      s    "  / % %   R  
 4 , 9 - /  / 0-	H	q:m q:h@W_h67 @r*   