
    $j8                    N   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& ddl'm(Z( ddl)m*Z* ddl+m,Z,m-Z- e	rddl.m/Z/m0Z0  e,e1          Z2 G d d          Z3dS )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)Provider)FastMCPProvider)_WrappedProvider)log_server_banner)
get_loggertemporary_log_level)FastMCP	Transportc                      e Zd ZdZ	 	 d1d2dZ	 	 d1d2dZ	 	 d3d4dZd5dZ	 	 	 d6d7dZ	 	 	 	 	 	 	 	 	 	 	 d8d9d+Z		 	 	 	 	 	 	 d:d;d0Z
dS )<TransportMixinzMixin providing transport-related methods for FastMCP.

    Includes HTTP/stdio/SSE transport handling and custom HTTP routes.
    Nselfr   	transportTransport | Noneshow_bannerbool | Nonetransport_kwargsr   returnNonec                  K   |t           j        j        }|t           j        j        }|dvrt	          d|           |dk    r | j        dd|i| d{V  dS |dv r | j        d||d| d{V  dS t	          d|           )	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*   r"   >   r(   r)   r+   )r    r"    )fastmcpsettingsshow_server_bannerr    
ValueErrorrun_stdio_asyncrun_http_asyncr   r    r"   r$   s       g/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/fastmcp/server/mixins/transport.py	run_asynczTransportMixin.run_async+   s,      !*=K(2IGGG>9>>???&$&  '"           <<<%$% #'  #           >9>>???    c                T    t          j        t          | j        |fd|i|           dS )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   r6   r4   s       r5   r:   zTransportMixin.runM   sP     		  ( #	 	
 	
 	
 	
 	
r7   Tpathstrmethods	list[str]name
str | Noneinclude_in_schemabool^Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]]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"})
            ```
        fn(Callable[[Request], Awaitable[Response]]r%   c           	     `    j                             t          |                      | S )N)endpointr=   r?   rA   )_additional_http_routesappendr   )rE   rA   r=   r?   r;   r   s    r5   	decoratorz.TransportMixin.custom_route.<locals>.decorator   sH     (//#&7     Ir7   )rE   rF   r%   rF   r-   )r   r;   r=   r?   rA   rK   s   ````` r5   custom_routezTransportMixin.custom_routed   sB    D	 	 	 	 	 	 	 	 	 	 r7   list[BaseRoute]c                    t          | j                  }dd}| j        D ]N} ||          }t          |t                    r,|                    |j                                                   O|S )a  Get all additional HTTP routes including from mounted servers.

        Collects custom HTTP routes registered via ``@server.custom_route()``
        from this server **and** from any FastMCP servers reachable through
        mounted providers (recursively).  This ensures that routes defined on
        a child server are forwarded to the parent's HTTP app when using
        ``server.mount(child)``.

        Note:
            When path collisions occur between a parent and a mounted child,
            the parent's routes take precedence because they appear first in
            the returned list.

        Returns:
            List of Starlette Route objects
        providerr   r%   c                h    t          | t                    r| j        } t          | t                    | S )z:Unwrap _WrappedProvider layers to find the inner provider.)
isinstancer   _inner)rO   s    r5   _unwrap_providerzDTransportMixin._get_additional_http_routes.<locals>._unwrap_provider   s6    X'788 +#? X'788 +Or7   )rO   r   r%   r   )listrI   	providersrQ   r   extendserver_get_additional_http_routes)r   routesrS   rO   inners        r5   rX   z*TransportMixin._get_additional_http_routes   s    " #'t'C"D"D	 	 	 	  	J 	JH$$X..E%11 J elFFHHIIIr7   F	log_level	statelessc                  K   ddl m}m} |rt          |             |d          }	 t	          |          5  |                                 4 d{V  t                      4 d{V \  }}|rdnd}	t                              d| j	        d	|	            | j
                            ||| j
                            t          d
                    |           d{V  ddd          d{V  n# 1 d{V swxY w Y   ddd          d{V  n# 1 d{V swxY w Y   ddd           n# 1 swxY w Y    ||           dS #  ||           w xY 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rW   r*   N (stateless) Starting MCP server z with transport 'stdio'T)tools_changed)notification_options)r\   )fastmcp.server.contextr^   r_   r   r   _lifespan_managerr   loggerinfor?   _mcp_serverr:   create_initialization_optionsr
   )
r   r"   r[   r\   r^   r_   tokenread_streamwrite_streammodes
             r5   r2   zTransportMixin.run_stdio_async   s      	JIIIIIII  	+T****g&&	#$Y//  1133        +~~       1L+|1:B~~]49]]W[]]   #.22'( ,JJ5H266" 6" 6" K  
 '0 3 	 	 	 	 	 	 	 	 	                                                                  & OE"""""OOE""""sw   E D4D(A:C4"D4
C>>DC>DD4
D!	!D4$D!	%D4(E 4D88E ;D8<E Er)   )Literal['http', 'streamable-http', 'sse']hostport
int | Noneuvicorn_configdict[str, Any] | None
middlewarelist[ASGIMiddleware] | Nonejson_responsestateless_httpc                  K   ||
|}
|
t           j        j        }
|
r|dk    rt          d          ||nt           j        j        }||nt           j        j        }||nt           j        j                                        }|                     ||||	|
          }|rt          |            |pi }dddd	}|
                    |           d
|vr	d|vr||d<   t          |          5  |                                 4 d{V  t          j        |f||d|}t          j        |          }t!          |j        dd                              d          }|
rdnd}t&                              d| j        d|| d| d| d|            |                                 d{V  ddd          d{V  n# 1 d{V swxY w Y   ddd           dS # 1 swxY w Y   dS )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    rv   rx   ry   r`      onzwebsockets-sansio)timeout_graceful_shutdownlifespanws
log_configr[   )rq   rr   r;   rb   /ra   rc   z with transport z on http://:)r.   r/   ry   r1   rq   rr   r[   lowerhttp_appr   updater   rg   uvicornConfigServergetattrstatelstriprh   ri   r?   serve)r   r"   r    rq   rr   r[   r;   rt   rv   rx   ry   r\   default_log_level_to_useappuvicorn_config_from_userconfig_kwargsconfigrW   ro   s                      r5   r3   zTransportMixin.run_http_async   s0     :  ^%;&N !$-<N  	Ni500LMMM'ttW-=-B'ttW-=-B".IIG4D4N
%'' 	! mm!')  
 
  	+T****#1#7R  *+%)
 )

 	5666},,M1Q1Q)AM+& ++ 
	% 
	%--// 	% 	% 	% 	% 	% 	% 	% 	% S$TSS]SS //sy&"55<<SAA)7?~~Rz49zz	zUYzzfjzzmqzztxzz   llnn$$$$$$$	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	% 	%
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	% 
	%s7   +GB#F;)G;
G	GG		GG Gevent_storeEventStore | Noneretry_intervalr   c                   |dv ret          | ||nt          j        j        ||| j        ||nt          j        j        ||nt          j        j        t          j        j        |	  	        S |dk    rKt          | t          j        j	        ||n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)   N)	rW   streamable_http_pathr   r   authrx   ry   debugrv   r(   )rW   message_pathsse_pathr   r   rv   r,   )r   r.   r/   r   r   rx   ry   r   r   r   r   r1   )r   r;   rv   rx   ry   r    r   r   s           r5   r   zTransportMixin.http_app3  s    < 333-# &*T%:'-Y %0 "M )7 &1 #N )8&,%'   * %!$-:!%!1w7G7PY&,%    >9>>???r7   )NN)
r   r   r    r!   r"   r#   r$   r   r%   r&   )NT)r   r   r;   r<   r=   r>   r?   r@   rA   rB   r%   rC   )r   r   r%   rM   )TNF)
r   r   r"   rB   r[   r@   r\   rB   r%   r&   )Tr)   NNNNNNNNN)r   r   r"   rB   r    rp   rq   r@   rr   rs   r[   r@   r;   r@   rt   ru   rv   rw   rx   r#   ry   r#   r\   r#   r%   r&   )NNNNr)   NN)r   r   r;   r@   rv   rw   rx   r#   ry   r#   r    rp   r   r   r   rs   r%   r   )__name__
__module____qualname____doc__r6   r:   rL   rX   r2   r3   r   r-   r7   r5   r   r   %   s;         '+#' @  @  @  @  @H '+#'
 
 
 
 
6  "&0 0 0 0 0d       H ! $	(# (# (# (# (#X !?E $0426%)&*!%O% O% O% O% O%f  26%)&*?E)-%)>@ >@ >@ >@ >@ >@ >@r7   r   )4r   
__future__r   collections.abcr   r   	functoolsr   typingr   r   r	   r9   r   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.server.providers.baser   )fastmcp.server.providers.fastmcp_providerr   )fastmcp.server.providers.wrapped_providerr   fastmcp.utilities.clir   fastmcp.utilities.loggingr   r   fastmcp.server.serverr   r   r   rh   r   r-   r7   r5   <module>r      s   3 3 " " " " " " / / / / / / / /       . . . . . . . . . .   : : : : : : ) ) ) ) ) ) = = = = = = & & & & & & ( ( ( ( ( ( . . . . . . . .  1 1 1 1 1 1         
 3 2 2 2 2 2 E E E E E E F F F F F F 3 3 3 3 3 3 E E E E E E E E 988888888	H		L@ L@ L@ L@ L@ L@ L@ L@ L@ L@r7   