
    ~h-                    >   U d dl mZ d dlmZmZmZ d dlmZ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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% d dl&m'Z'm(Z(m)Z) d dl*m+Z+m,Z,m-Z-m.Z. d dl/m0Z0 d dl1m2Z2 erd dl3m4Z4  e2e5      Z6 e
dd      Z7de8d<    G d de      Z9ed%d       Z: G d d       Z;	 	 	 	 d&d!Z<	 	 d'	 	 	 	 	 	 	 	 	 d(d"Z=	 	 	 	 d)	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d*d#Z>	 	 	 	 	 	 	 d+	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d,d$Z?y)-    )annotations)AsyncGeneratorCallable	Generator)asynccontextmanagercontextmanager)
ContextVar)TYPE_CHECKING)AuthContextMiddleware)BearerAuthBackendRequireAuthMiddleware)create_auth_routes)LifespanResultT)SseServerTransport)
EventStore)StreamableHTTPSessionManager)	Starlette)
Middleware)AuthenticationMiddleware)Request)Response)	BaseRouteMountRoute)LifespanReceiveScopeSend)OAuthProvider)
get_logger)FastMCPhttp_requestN)defaultzContextVar[Request | None]_current_http_requestc                      e Zd Zedd       Zy)StarletteWithLifespanc                .    | j                   j                  S N)routerlifespan_context)selfs    O/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/fastmcp/server/http.pylifespanzStarletteWithLifespan.lifespan*   s    {{+++    N)returnr   )__name__
__module____qualname__propertyr-    r.   r,   r&   r&   )   s    , ,r.   r&   c              #     K   t         j                  |       }	 |  t         j                  |       y # t         j                  |       w xY wwr(   )r$   setreset)requesttokens     r,   set_http_requestr:   /   s=     !%%g.E+##E*##E*s   A3 AA

Ac                      e Zd ZdZd Zd Zy)RequestContextMiddlewarez=
    Middleware that stores each request in a ContextVar
    c                    || _         y r(   app)r+   r?   s     r,   __init__z!RequestContextMiddleware.__init__=   s	    r.   c                   K   |d   dk(  r9t        t        |            5  | j                  |||       d {    d d d        y | j                  |||       d {    y 7 )# 1 sw Y   y xY w7 w)Ntypehttp)r:   r   r?   )r+   scopereceivesends       r,   __call__z!RequestContextMiddleware.__call__@   sq     =F"!'%.1 5hhugt4445 5 ((5'4000 55 5 1s7   A0A"A A"A0A.A0 A""A+'A0N)r0   r1   r2   __doc__r@   rG   r4   r.   r,   r<   r<   8   s    1r.   r<   c           	        g }g }g }t        t        t        |             t        t              g}| j                  xs g }|j                  t        | | j                  | j                  | j                  | j                               |||fS )zSet up authentication middleware and routes if auth is enabled.

    Args:
        auth: The OAuthProvider authorization server provider

    Returns:
        Tuple of (middleware, auth_routes, required_scopes)
    )provider)backend)rJ   
issuer_urlservice_documentation_urlclient_registration_optionsrevocation_options)r   r   r   r   required_scopesextendr   rL   rM   rN   rO   )auth
middlewareauth_routesrP   s       r,    setup_auth_middleware_and_routesrU   H   s     $&J#%K!#O 	$%t4	
 	()J **0bO&*&D&D(,(H(H#66	
 {O33r.   c                \    |j                  t        t                     t        | |||      S )aR  Create a base Starlette app with common middleware and routes.

    Args:
        routes: List of routes to include in the app
        middleware: List of middleware to include in the app
        debug: Whether to enable debug mode
        lifespan: Optional lifespan manager for the app

    Returns:
        A Starlette application
    routesrS   debugr-   )appendr   r<   r&   rW   s       r,   create_base_appr[   n   s1    $ j!9:; 	 r.   c           	         g }g }t        |      d fd|rt        |      \  }	}
}|j                  |
       |j                  |	       |j                  t	        |t        |      dg             |j                  t        |t        j                  |                   nJdfd}|j                  t	        ||dg             |j                  t        |j                               |r|j                  |       |j                   j                         |r|j                  |       t        |||      } |j                  _        ||j                  _        |S )	a  Return an instance of the SSE server app.

    Args:
        server: The FastMCP server instance
        message_path: Path for SSE messages
        sse_path: Path for SSE connections
        auth: Optional auth provider
        debug: Whether to enable debug mode
        routes: Optional list of custom routes
        middleware: Optional list of middleware
    Returns:
        A Starlette application with RequestContextMiddleware
    c                F  K   j                  | ||      4 d {   }j                  j                  |d   |d   j                  j                                d {    d d d       d {    t	               S 7 a7  7 # 1 d {  7  sw Y   t	               S xY ww)Nr      )connect_sse_mcp_serverruncreate_initialization_optionsr   )rD   rE   rF   streamsserversses       r,   
handle_ssez"create_sse_app.<locals>.handle_sse   s     ??5'48 	 	G$$((

""@@B  	 	 z		 	 	 	 zsV   B!A=B!?BA?B#B!.B/B!?BB!B	B
BB!GET)endpointmethodsr>   c                p   K    | j                   | j                  | j                         d {   S 7 wr(   )rD   rE   _send)r8   rf   s    r,   sse_endpointz$create_sse_app.<locals>.sse_endpoint   s(     #GMM7??GMMRRRRs   ,646)rX   rS   rY   )rD   r   rE   r   rF   r   r/   r   )r8   r   r/   r   )r   rU   rQ   rZ   r   r   r   handle_post_message_additional_http_routesr[   statefastmcp_serverpath)rd   message_pathsse_pathrR   rY   rX   rS   server_routesserver_middlewareauth_middlewarerT   rP   rl   r?   rf   re   s   `             @@r,   create_sse_apprw      sd   . &(M*, \
*C ,T2 	6o 	[)  1.z?K	
 	)#*A*A?S	
	S 	%	
 	++	
 V$778   , $C  &CIICIINJr.   c	           	     L   g }	g }
t        | j                  |||      	 	 	 	 	 	 	 	 dfd}|rXt        |      \  }}}|	j                  |       |
j                  |       |	j	                  t        |t        ||                   n|	j	                  t        ||             |r|	j                  |       |	j                  | j                         |r|
j                  |       t        dfd       }t        |	|
||      }| |j                  _        ||j                  _        |S )az  Return an instance of the StreamableHTTP server app.

    Args:
        server: The FastMCP server instance
        streamable_http_path: Path for StreamableHTTP connections
        event_store: Optional event store for session management
        auth: Optional auth provider
        json_response: Whether to use JSON response format
        stateless_http: Whether to use stateless mode (new transport per request)
        debug: Whether to enable debug mode
        routes: Optional list of custom routes
        middleware: Optional list of middleware

    Returns:
        A Starlette application with StreamableHTTP support
    )r?   event_storejson_response	statelessc                   K   	 j                  | ||       d {    y 7 # t        $ rA}t        |      dk(  r-t        j	                  d| d       d}t        | d|       | d }~ww xY ww)Nz6Task group is not initialized. Make sure to use run().z(Original RuntimeError from mcp library: T)exc_infoa  FastMCP's StreamableHTTPSessionManager task group was not initialized. This commonly occurs when the FastMCP application's lifespan is not passed to the parent ASGI application (e.g., FastAPI or Starlette). Please ensure you are setting `lifespan=mcp_app.lifespan` in your parent app's constructor, where `mcp_app` is the application instance returned by `fastmcp_instance.http_app()`. \nFor more details, see the FastMCP ASGI integration documentation: https://gofastmcp.com/deployment/asgiz\nOriginal error: )handle_requestRuntimeErrorstrloggererror)rD   rE   rF   enew_error_messagesession_managers        r,   handle_streamable_httpz:create_streamable_http_app.<locals>.handle_streamable_http  s     	!00FFF 	1vQQ>qcBT  < " #&7%88KA3#OPVWW )	s0   A0# !# A0# 	A-<A((A--A0r>   c                  K   j                         4 d {    d  d d d       d {    y 7 7 # 1 d {  7  sw Y   y xY wwr(   )ra   )r?   r   s    r,   r-   z,create_streamable_http_app.<locals>.lifespanW  sE     "&&( 	 		 	 	 	 	 	 	s:   A3A7A5AAA	A A	ArW   )rD   r   rE   r   rF   r   r/   None)r?   r   r/   zAsyncGenerator[None, None])r   r`   rU   rQ   rZ   r   r   rn   r   r[   ro   rp   rq   )rd   streamable_http_pathry   rR   rz   stateless_httprY   rX   rS   rt   ru   r   rv   rT   rP   r-   r?   r   s                    @r,   create_streamable_http_appr      sQ   6 &(M*, 3# 	O&.2	8 ,T2 	6o 	[)  1 	$)*@/R	
 	$*	
 V$778   ,  
 $	C  &CII)CIINJr.   )r8   r   r/   zGenerator[Request, None, None])rR   r   r/   z3tuple[list[Middleware], list[BaseRoute], list[str]])FN)
rX   zlist[BaseRoute]rS   zlist[Middleware]rY   boolr-   zCallable | Noner/   r&   )NFNN)rd   FastMCP[LifespanResultT]rr   r   rs   r   rR   OAuthProvider | NonerY   r   rX   list[BaseRoute] | NonerS   list[Middleware] | Noner/   r&   )NNFFFNN)rd   r   r   r   ry   zEventStore | NonerR   r   rz   r   r   r   rY   r   rX   r   rS   r   r/   r&   )@
__future__r   collections.abcr   r   r   
contextlibr   r   contextvarsr	   typingr
   'mcp.server.auth.middleware.auth_contextr   &mcp.server.auth.middleware.bearer_authr   r   mcp.server.auth.routesr   mcp.server.lowlevel.serverr   mcp.server.sser   mcp.server.streamable_httpr   "mcp.server.streamable_http_managerr   starlette.applicationsr   starlette.middlewarer   #starlette.middleware.authenticationr   starlette.requestsr   starlette.responsesr   starlette.routingr   r   r   starlette.typesr   r   r   r   fastmcp.server.auth.authr   fastmcp.utilities.loggingr    fastmcp.server.serverr!   r0   r   r$   __annotations__r&   r:   r<   rU   r[   rw   r   r4   r.   r,   <module>r      s   " ? ? : "   I 6 6 - 1 K , + H & ( 5 5 : : 2 0-	H	 5?5 1 ,I , + +1 1 #4
#48#4R  $	   	
 @ "&%)*.e$ee e 	e
 e #e (e eV &*!% %)*.v$vv #v 	v
 v v v #v (v vr.   