
    i?3                       d Z ddlm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Zddl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mZ ddl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&m'Z' e	rddl(m)Z)m*Z*  e&e+      Z, G d d      Z-y)z-Transport-related methods for FastMCP Server.    )annotations)	AwaitableCallable)partial)TYPE_CHECKINGAnyLiteralN)NotificationOptions)stdio_server)
Middleware)Request)Response)	BaseRouteRoute)
EventStore)StarletteWithLifespancreate_sse_appcreate_streamable_http_app)log_server_banner)
get_loggertemporary_log_level)FastMCP	Transportc                  *   e Zd ZdZ	 	 d
	 	 	 	 	 	 	 	 	 ddZ	 	 d
	 	 	 	 	 	 	 	 	 ddZ	 	 d	 	 	 	 	 	 	 	 	 	 	 ddZddZ	 	 	 d	 	 	 	 	 	 	 	 	 ddZ	 	 	 	 	 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddZ		 	 	 	 	 	 	 d	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dd	Z
y)TransportMixinzMixin providing transport-related methods for FastMCP.

    Includes HTTP/stdio/SSE transport handling and custom HTTP routes.
    Nc                J  K   |t         j                  j                  }|t         j                  j                  }|dvrt	        d|       |dk(  r | j
                  dd|i| d{    y|dv r | j                  d||d| d{    yt	        d|       7 57 w)	a3  Run the FastMCP server asynchronously.

        Args:
            transport: Transport protocol to use ("stdio", "http", "sse", or "streamable-http")
            show_banner: Whether to display the server banner. If None, uses the
                FASTMCP_SHOW_SERVER_BANNER setting (default: True).
        N>   ssehttpstdiostreamable-httpUnknown transport: r   show_banner>   r   r   r    )	transportr"    )fastmcpsettingsshow_server_bannerr#   
ValueErrorrun_stdio_asyncrun_http_asyncselfr#   r"   transport_kwargss       o/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/server/mixins/transport.py	run_asynczTransportMixin.run_async(   s      !**==K((22IGG29+>??&$&& '"   <<%$%% #' #   29+>??
s$   A'B#)B*!B#B!B#!B#c                \    t        j                  t        | j                  |fd|i|       y)aI  Run the FastMCP server. Note this is a synchronous function.

        Args:
            transport: Transport protocol to use ("http", "stdio", "sse", or "streamable-http")
            show_banner: Whether to display the server banner. If None, uses the
                FASTMCP_SHOW_SERVER_BANNER setting (default: True).
        r"   N)anyiorunr   r/   r+   s       r.   r2   zTransportMixin.runJ   s6     			 ( #		
    c                ,     	 	 	 	 d fd}|S )a  
        Decorator to register a custom HTTP route on the FastMCP server.

        Allows adding arbitrary HTTP endpoints outside the standard MCP protocol,
        which can be useful for OAuth callbacks, health checks, or admin APIs.
        The handler function must be an async function that accepts a Starlette
        Request and returns a Response.

        Args:
            path: URL path for the route (e.g., "/auth/callback")
            methods: List of HTTP methods to support (e.g., ["GET", "POST"])
            name: Optional name for the route (to reference this route with
                Starlette's reverse URL lookup feature)
            include_in_schema: Whether to include in OpenAPI schema, defaults to True

        Example:
            Register a custom HTTP route for a health check endpoint:
            ```python
            @server.custom_route("/health", methods=["GET"])
            async def health_check(request: Request) -> Response:
                return JSONResponse({"status": "ok"})
            ```
        c           	     Z    j                   j                  t        |              | S )N)endpointmethodsnameinclude_in_schema)_additional_http_routesappendr   )fnr9   r7   r8   pathr,   s    r.   	decoratorz.TransportMixin.custom_route.<locals>.decorator   s7     ((//#&7 Ir3   )r<   (Callable[[Request], Awaitable[Response]]returnr?   r$   )r,   r=   r7   r8   r9   r>   s   ````` r.   custom_routezTransportMixin.custom_routea   s&    D	8	5	 	 r3   c                ,    t        | j                        S )a  Get all additional HTTP routes including from providers.

        Returns a list of all custom HTTP routes from this server and
        from all providers that have HTTP routes (e.g., FastMCPProvider).

        Returns:
            List of Starlette BaseRoute objects
        )listr:   )r,   s    r.   _get_additional_http_routesz*TransportMixin._get_additional_http_routes   s     D0011r3   c                  K   ddl m}m} |rt        |         |d      }	 t	        |      5  | j                         4 d{    t               4 d{   \  }}|rdnd}	t        j                  d| j                  d	|	        | j                  j                  ||| j                  j                  t        d
            |       d{    ddd      d{    ddd      d{    ddd        ||       y7 7 7 97 +# 1 d{  7  sw Y   ;xY w7 2# 1 d{  7  sw Y   BxY w# 1 sw Y   FxY w#  ||       w xY ww)zRun the server using stdio transport.

        Args:
            show_banner: Whether to display the server banner
            log_level: Log level for the server
            stateless: Whether to run in stateless mode (no session initialization)
        r   )reset_transportset_transportserverr   N (stateless) Starting MCP server z with transport 'stdio'T)tools_changed)notification_options)	stateless)fastmcp.server.contextrF   rG   r   r   _lifespan_managerr   loggerinfor8   _mcp_serverr2   create_initialization_optionsr
   )
r,   r"   	log_levelrO   rF   rG   tokenread_streamwrite_streammodes
             r.   r)   zTransportMixin.run_stdio_async   s,     	J T*g&	#$Y/1133+~~1L+|1:~2499-?VW[V\] #..22'( ,,JJ5H266" K 
 '0 3 	 	 	  .~ 43 0& E"% 4-	  .~~~ 4333 0/& E"s   EE D8DD8D#D
D#A5DD
DD#D
D##D8.D!/D83E ;	ED8D#D
D#DDDD#!D8#D5	)D,*D5	1D88E=E 
EEc                  K   ||
|}
|
t         j                  j                  }
|
r|dk(  rt        d      |xs t         j                  j                  }|xs t         j                  j
                  }|xs t         j                  j                  j                         }| j                  ||||	|
      }|rt        |        |xs i }dddd	}|j                  |       d
|vr	d|vr||d<   t        |      5  | j                         4 d{    t        j                  |f||d|}t        j                  |      }t!        |j"                  dd      j%                  d      }|
rdnd}t&        j)                  d| j*                  d|| d| d| d|        |j-                          d{    ddd      d{    ddd       y7 7 7 # 1 d{  7  sw Y   !xY w# 1 sw Y   yxY ww)ap  Run the server using HTTP transport.

        Args:
            transport: Transport protocol to use - "http" (default), "streamable-http", or "sse"
            host: Host address to bind to (defaults to settings.host)
            port: Port to bind to (defaults to settings.port)
            log_level: Log level for the server (defaults to settings.log_level)
            path: Path for the endpoint (defaults to settings.streamable_http_path or settings.sse_path)
            uvicorn_config: Additional configuration for the Uvicorn server
            middleware: A list of middleware to apply to the app
            json_response: Whether to use JSON response format (defaults to settings.json_response)
            stateless_http: Whether to use stateless HTTP (defaults to settings.stateless_http)
            stateless: Alias for stateless_http for CLI consistency
        Nr   z-SSE transport does not support stateless mode)r=   r#   
middlewarejson_responsestateless_httprH   r   onzwebsockets-sansio)timeout_graceful_shutdownlifespanws
log_configrV   )hostportr=   rK   /rJ   rL   z with transport z on http://:)r%   r&   r^   r(   rd   re   rV   lowerhttp_appr   updater   rQ   uvicornConfigServergetattrstatelstriprR   rS   r8   serve)r,   r"   r#   rd   re   rV   r=   uvicorn_configr\   r]   r^   rO   default_log_level_to_useappuvicorn_config_from_userconfig_kwargsconfigrI   rZ   s                      r.   r*   zTransportMixin.run_http_async   s    :  ^%;&N !$--<<N i50LMM,w'',,,w'',,$-$K1A1A1K1K#R#R#T mm!')  
 T*#1#7R  *+%)

 	56},M1Q)AM+& +--// S$TS]S /syy&"5<<SA)7~R*499-7G	}UYTZZefjekklmqlrrstxsyz lln$$ 0/ ,+/ % 0/// ,+sy   C6G48G(GG(BG/G0G4G(?G G(	G4G(GG(G%	GG%	!G((G1-G4c                   |dv rt        | |xs t        j                  j                  ||| j                  ||nt        j                  j
                  ||nt        j                  j                  t        j                  j                  |	      S |dk(  rgt        | t        j                  j                  |xs t        j                  j                  | j                  t        j                  j                  |      S t        d|       )a2  Create a Starlette app using the specified HTTP transport.

        Args:
            path: The path for the HTTP endpoint
            middleware: A list of middleware to apply to the app
            json_response: Whether to use JSON response format
            stateless_http: Whether to use stateless mode (new transport per request)
            transport: Transport protocol to use - "http", "streamable-http", or "sse"
            event_store: Optional event store for SSE polling/resumability. When set,
                enables clients to reconnect and resume receiving events after
                server-initiated disconnections. Only used with streamable-http transport.
            retry_interval: Optional retry interval in milliseconds for SSE polling.
                Controls how quickly clients should reconnect after server-initiated
                disconnections. Requires event_store to be set. Only used with
                streamable-http transport.

        Returns:
            A Starlette application configured with the specified transport
        )r    r   )	rI   streamable_http_pathevent_storeretry_intervalauthr]   r^   debugr\   r   )rI   message_pathsse_pathr|   r}   r\   r!   )r   r%   r&   ry   r|   r]   r^   r}   r   r~   r   r(   )r,   r=   r\   r]   r^   r#   rz   r{   s           r.   ri   zTransportMixin.http_app  s    < 33-%)%RW-=-=-R-R'-YY %0 " ))77 &1 # ))88&&,,%# & %!$--:::!1!1!:!:YY&&,,%  29+>??r3   )NN)
r,   r   r#   zTransport | Noner"   bool | Noner-   r   r@   None)NT)r,   r   r=   strr7   z	list[str]r8   
str | Noner9   boolr@   z^Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]])r,   r   r@   zlist[BaseRoute])TNF)
r,   r   r"   r   rV   r   rO   r   r@   r   )Tr   NNNNNNNNN)r,   r   r"   r   r#   )Literal['http', 'streamable-http', 'sse']rd   r   re   
int | NonerV   r   r=   r   rr   zdict[str, Any] | Noner\   list[ASGIMiddleware] | Noner]   r   r^   r   rO   r   r@   r   )NNNNr   NN)r,   r   r=   r   r\   r   r]   r   r^   r   r#   r   rz   zEventStore | Noner{   r   r@   r   )__name__
__module____qualname____doc__r/   r2   rA   rD   r)   r*   ri   r$   r3   r.   r   r   "   s?    '+#' @ @# @ ! @  	 @
 
 @H '+#'

#
 !
  	

 

6  "&000 0 	0
  0
0d	2 ! $	(#(#(# (# 	(#
 
(#X !?E $0426%)&*!%M%M%M% =M% 	M%
 M% M% M% .M% 0M% #M% $M% M% 
M%b  26%)&*?E)-%)<@<@<@ 0<@ #	<@
 $<@ =<@ '<@ #<@ 
<@r3   r   ).r   
__future__r   collections.abcr   r   	functoolsr   typingr   r   r	   r1   rk   mcp.server.lowlevel.serverr
   mcp.server.stdior   starlette.middlewarer   ASGIMiddlewarestarlette.requestsr   starlette.responsesr   starlette.routingr   r   r%   fastmcp.server.event_storer   fastmcp.server.httpr   r   r   fastmcp.utilities.clir   fastmcp.utilities.loggingr   r   fastmcp.server.serverr   r   r   rR   r   r$   r3   r.   <module>r      se    3 " /  . .   : ) = & ( .  1 
 4 E8	H	q@ q@r3   