
    Ki(#                       d dl mZ d dl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  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)AsyncExitStack)TYPE_CHECKINGAny)MemoryObjectReceiveStreamMemoryObjectSendStream)McpError)LifespanResultTNotificationOptionsRequestT)Server)InitializationOptions)ServerSession)stdio_server)SessionMessage)RequestResponder)
get_logger)FastMCPc                  F     e Zd ZdZd fdZe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       d/home/jay/workspace/scripts/.codegraph-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                   	
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_respondM   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$   r2   	responderr    s    r%   call_original_handlerzHMiddlewareServerSession._received_request.<locals>.call_original_handlerV   sX      3TLYWWW$0Z%**CII,F,F6 -111 Xs   AAAA)r!   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)r1   zmcp.types.ServerResultreturnNone)r<   r.   rH   z!mcp.types.InitializeResult | None)fastmcp.server.context$fastmcp.server.middleware.middlewarer.   r7   r@   r8   r9   r:   InitializeRequestrespondservercontextContextr!   _apply_middlewarer	   
_completederrorloggerwarningr   r6   )r    r=   r!   r.   r4   r>   fastmcp_ctx
mw_contexter2   r3   r$   s   ``       @@r%   r6   z)MiddlewareServerSession._received_request2   s     	&Ji'',,cii.I.IJ @D(008088 !2I&2  ~~--55 6   .%--22#"'$/
!%!?!?"$9"   > W.y999?     %//& ="+"3"3AGG"<<<= = = W%& ' !    > :s   B$G+D,G/"F+D$1D 2D$5GD"GG G D$"G$	F-F;E)E
E) 	F)E2.FF+FF+G$F'%G+F=1F42F=9G)r!   r   rH   r   )r=   zARequestResponder[mcp.types.ClientRequest, mcp.types.ServerResult])	__name__
__module____qualname____doc__r   propertyr!   r6   __classcell__r$   s   @r%   r   r   !   s5    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 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   r,   r&   c                D    || j                   }t        |   d||d|S )N)rg   experimental_capabilitiesr0   )rg   r   create_initialization_options)r    rg   rj   r#   r$   s       r%   rk   z,LowLevelServer.create_initialization_options   s>      '#'#<#< w4 
!5&?
 
 	
r&   c                T    ddl m} t        |   ||xs 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_capabilities)!fastmcp.server.tasks.capabilitiesrm   r   get_capabilitiestasks)r    rg   rj   rm   capabilitiesr$   s        r%   ro   zLowLevelServer.get_capabilities   s8     	L w/ %+
 34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_exceptionsrs   stacklifespan_contextsessiontgrB   s              r%   runzLowLevelServer.run   s     "# 	 	u%*%>%>t}}T?R%SS!55'LL *' G ..0  B350%,%>%>  'MM,,((#	S%>	    	 	 	 	 	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!)r!   r   r"   r   r#   r   rY   )NN)rg   zNotificationOptions | Nonerj   z dict[str, dict[str, Any]] | Noner#   r   rH   r   )rg   r   rj   zdict[str, dict[str, Any]]rH   zmcp.types.ServerCapabilities)FF)
r{   z5MemoryObjectReceiveStream[SessionMessage | Exception]r|   z&MemoryObjectSendStream[SessionMessage]r}   r   r~   boolrs   r   )
rZ   r[   r\   r   r^   r!   rk   ro   r   r_   r`   s   @r%   rb   rb      s    

   <@FJ
8
 $D
 	

 

1 $= 
&	< "'"J" =" !6	"
 " "r&   rb   )'
__future__r   r   
contextlibr   typingr   r   rv   	mcp.typesr9   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   fastmcp.utilities.loggingr   fastmcp.server.serverr   rZ   rT   r   rb   r0   r&   r%   <module>r      sw    "  % %   R  
 4 , 9 - / 0-	H	^:m ^:B_W_h67 _r&   