
    ~h                   ~   d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	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mZmZmZmZ ddlZddlZddl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&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl%m,Z- ddl%m.Z/ ddl%m0Z1 ddl%m2Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?Z?ddl@Z?ddlAmBZBmCZC ddlDm,Z,mEZE ddlFmGZG ddlHm.Z.mIZI ddlJm0Z0 ddlKmLZL ddlMmNZN ddlOmPZPmQZQmRZR ddlSmTZT ddlUmVZV dd lWmXZXm2Z2 dd!lYmZZZ dd"l[m\Z\ dd#l]m^Z^ dd$l_m`Z` er(dd%lambZb dd&lcmdZdmeZe dd'lfmgZh dd(lfmiZimjZj dd)lfmkZl dd*lmmnZn  e^eo      Zped+   Zq ej                  d,      Zsed6d-       Zt	 	 	 	 	 	 d7d.Zu G d/ d0ee         Zv G d1 d2      Zw	 d8	 	 	 	 	 	 	 d9d3Zx	 d8	 	 	 	 	 	 	 d9d4Zy	 d8	 	 	 	 	 	 	 d:d5Zzy);z5FastMCP - A more ergonomic interface for MCP servers.    )annotationsN)AsyncIterator	AwaitableCallable)AbstractAsyncContextManagerAsyncExitStackasynccontextmanager)partial)Path)TYPE_CHECKINGAnyGenericLiteraloverload)ReadResourceContents)LifespanResultTNotificationOptions)Server)stdio_server)AnyFunctionEmbeddedResourceGetPromptResultImageContentTextContentToolAnnotations)Prompt)Resource)ResourceTemplate)Tool)AnyUrl)
Middleware)Request)Response)	BaseRouteRoute)DisabledErrorNotFoundError)r   PromptManager)FunctionPrompt)r   ResourceManager)OAuthProvider)EnvBearerAuthProvider)StarletteWithLifespancreate_sse_appcreate_streamable_http_app)Settings)ToolManager)FunctionToolr   )
TimedCache)FastMCPComponent)
get_logger)	MCPConfigClient)ClientTransportClientTransportT)ComponentFn)FastMCPOpenAPIRouteMap)
RouteMapFnFastMCPProxy)warnerrorreplaceignorez^([^:]+://)(.*?)$c                  K   i  yw)zDefault lifespan context manager that does nothing.

    Args:
        server: The server instance this lifespan is managing

    Returns:
        An empty context object
    N )servers    Q/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/fastmcp/server/server.pydefault_lifespanrI   Q   s      Hs   	c                *     t         d fd       }|S )Nc                  K   t               4 d {   }|j                                d {   }| d d d       d {    y 7 97 7 	# 1 d {  7  sw Y   y xY wwN)r   enter_async_context)sstackcontextapplifespans      rH   wrapz_lifespan_wrapper.<locals>.wrapf   s^     !# 	 	u!55hsmDDGM	 	 	D	 	 	 	sS   A'AA'AA	AA'AA'AA'A$AA$ A')rN   zMCPServer[LifespanResultT]returnzAsyncIterator[LifespanResultT])r	   )rQ   rR   rS   s   `` rH   _lifespan_wrapperrU   ^   s      
 K    c            	         e Zd Z	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d=	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d>dZd?dZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d@dZed?d       ZedAd       Z	 dB	 	 	 	 	 dCdZ		 dB	 	 	 	 	 dCdZ
dDd	ZdEd
ZdFdZdGdZdHdZdIdZdJdZdKdZdLdZ	 	 dM	 	 	 	 	 	 	 dNdZdOdZdPdZdQdZdRdZ	 	 	 	 	 	 dSdZ	 	 	 	 	 	 dSdZdTdZdTdZ	 dB	 	 	 	 	 dUdZ	 dB	 	 	 	 	 dUdZdVdZdWdZ e!ddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dXd        Z"e!	 dBddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dYd!       Z"	 dBddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dZd"Z"dBd[d#Z#dBd\d$Z$	 	 	 	 d]	 	 	 	 	 	 	 	 	 	 	 	 	 d^d%Z%dddddd&	 	 	 	 	 	 	 	 	 	 	 	 	 d_d'Z&d`d(Z'e!ddddd)	 	 	 	 	 	 	 	 	 	 	 dad*       Z(e!	 dBddddd)	 	 	 	 	 	 	 	 	 	 	 dbd+       Z(	 dBddddd)	 	 	 	 	 	 	 	 	 	 	 dcd,Z(dDd-Z)	 	 	 	 	 	 	 dd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ded.Z*	 	 	 	 	 	 df	 	 	 	 	 	 	 	 	 	 	 	 	 dgd/Z+	 	 	 dh	 	 	 	 	 	 	 did0Z,	 	 dj	 	 	 	 	 dkd1Z-	 	 	 	 	 dl	 	 	 	 	 	 	 	 	 	 	 dmd2Z.	 	 	 	 	 dn	 	 	 	 	 	 	 	 	 	 	 dod3Z/	 dBdddd4	 	 	 	 	 	 	 	 	 	 	 	 	 dpd5Z0dqd6Z1	 	 	 dh	 	 	 	 	 	 	 	 	 	 	 drd7Z2e3	 	 	 	 	 dn	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dsd8       Z4e3	 	 	 	 	 	 	 dt	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dud9       Z5e3	 	 	 	 	 	 dvd:       Z6e3	 	 	 	 	 	 dwd;       Z7	 	 	 	 dxd<Z8y)yFastMCPNc                \   |
xs t         j                  j                  | _        t        t	        j
                  |xs d            | _        i | _        g | _        t        ||      | _
        t        ||      | _        t        |	|      | _        || _        |d| _        t"        }nd| _        t%        t&           |xs d|t)        | |            | _        |'t         j                  j,                  d	k(  r
t/               }|| _        |rI|D ]D  }t3        |t4              s!t5        j6                  || j                  
      }| j9                  |       F || _        || _        | j?                          |xs t         j                  j@                  | _!        | jE                  |||||||||	       y )Nr   )seconds)
expiration)duplicate_behaviormask_error_detailsFTrX   )nameinstructionsrR   
bearer_env)
serializer)		log_leveldebughostportsse_pathmessage_pathstreamable_http_pathjson_responsestateless_http)#fastmcpsettingsresource_prefix_formatr3   datetime	timedelta_cache_mounted_servers_additional_http_routesr1   _tool_managerr*   _resource_managerr(   _prompt_manager_tool_serializer_has_lifespanrI   	MCPServerr   rU   _mcp_serverdefault_auth_providerr,   auth
isinstancer   from_functionadd_toolinclude_tagsexclude_tags_setup_handlersserver_dependenciesdependencies_handle_deprecated_settings)selfr^   r_   r{   rR   tool_serializercache_expiration_secondson_duplicate_toolson_duplicate_resourceson_duplicate_promptsrm   r]   toolsr   r   r   rb   rc   rd   re   rf   rg   rh   ri   rj   tools                             rH   __init__zFastMCP.__init__p   s   N #Mg&6&6&M&M 	# !))2J2OaP
 ;=8:$(11
 "151"
  -31 
 !0!&D'H!%D$_5"%&tX6
 <G,,BBlR(*D	 $!$---dt?T?TUDd#$
 )( 	(PG,<,<,P,P 	((%!5') 	) 
	
rV   c                L    t        |       j                   d| j                  dS )N())type__name__r^   r   s    rH   __repr__zFastMCP.__repr__   s$    t*%%&a		}A66rV   c
           
        i }
d|fd|fd|fd|fd|fd|fd|fd|fd	|	ff	D ]-  \  }}|	t        j                  d| dt        d       ||
|<   / t        j                  j                         |
z  }t        di || _        y
)z0Handle deprecated settings. Deprecated in 2.8.0.rb   rc   rd   re   rf   rg   rh   ri   rj   NzProviding `ze` when creating a server is deprecated. Provide it when calling `run` or as a global setting instead.   
stacklevelrF   )warningsrA   DeprecationWarningrk   rl   
model_dumpr0   _deprecated_settings)r   rb   rc   rd   re   rf   rg   rh   ri   rj   deprecated_settingsr^   argcombined_settingss                 rH   r   z#FastMCP._handle_deprecated_settings   s     /1 )$eTNTN"\*#%9:m,~.

 	0ID# !$  (M  N& 
 -0#D)%	0( $,,779<OO$,$A/@$A!rV   c                .    | j                   j                  S rL   )ry   r^   r   s    rH   r^   zFastMCP.name   s    $$$rV   c                .    | j                   j                  S rL   )ry   r_   r   s    rH   r_   zFastMCP.instructions  s    ,,,rV   c                   K   |d}|dvrt        d|       |dk(  r | j                  di | d{    y|dv r | j                  dd|i| d{    yt        d|       7 47 w)zRun the FastMCP server asynchronously.

        Args:
            transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
        Nstdio>   sser   streamable-httpzUnknown transport: >   r   r   	transportrF   )
ValueErrorrun_stdio_asyncrun_http_asyncr   r   transport_kwargss      rH   	run_asynczFastMCP.run_async  s      I??29+>??&$&&:)9:::44%$%%N	N=MNNN29+>??	 ;Ns!   1A,A( A,A*A,*A,c                X    t        j                  t        | j                  |fi |       y)zRun the FastMCP server. Note this is a synchronous function.

        Args:
            transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
        N)anyiorunr
   r   r   s      rH   r   zFastMCP.run  s!     			'$..)H7GHIrV   c                P    | j                   j                         | j                          | j                   j                         | j                          | j                   j                         | j                          | j                   j                         | j                          | j                   j                         | j                          | j                   j                         | j                          | j                   j                         | j                         y)z"Set up core MCP protocol handlers.N)ry   
list_tools_mcp_list_toolslist_resources_mcp_list_resourceslist_resource_templates_mcp_list_resource_templateslist_prompts_mcp_list_prompts	call_tool_mcp_call_toolread_resource_mcp_read_resource
get_prompt_mcp_get_promptr   s    rH   r   zFastMCP._setup_handlers*  s    %##%d&:&:;)'')$*B*BC200243T3TU'%%'(>(>?$""$T%8%89(&&()@)@A%##%d&:&:;rV   c                   K   | j                   j                  d      x}| j                   j                  u ri }| j                  j	                         D ]/  \  }}	 |j                          d{   }|j                  |       1 |j                  | j                  j                                | j                   j                  d|       |S 7 ^# t        $ r%}t        j                  d| d|        Y d}~d}~ww xY ww)z4Get all registered tools, indexed by registered key.r   Nz)Failed to get tools from mounted server '': )rp   get	NOT_FOUNDrq   items	get_toolsupdate	Exceptionloggerwarningrs   set)r   r   prefixrG   server_toolses         rH   r   zFastMCP.get_tools4  s     [[__W--E$++2G2GG%'E"&"7"7"="="? )/)9)9);#;LLL. LL++5578KKOOGU+ $<  NNCF83qcR 	C   AC>C,C-CA	C>C	C;C61C>6C;;C>c                l   K   | j                          d {   }||vrt        d|       ||   S 7 w)NUnknown tool: )r   r'   )r   keyr   s      rH   get_toolzFastMCP.get_toolE  s>     nn&&e. 677Sz '   424c                   K   | j                   j                  d      x}| j                   j                  u ri }| j                  j	                         D ]/  \  }}	 |j                          d{   }|j                  |       1 |j                  | j                  j                                | j                   j                  d|       |S 7 ^# t        $ r%}t        j                  d| d|        Y d}~d}~ww xY ww)z8Get all registered resources, indexed by registered key.	resourcesNz-Failed to get resources from mounted server 'r   )rp   r   r   rq   r   get_resourcesr   r   r   r   rt   r   )r   r   r   rG   server_resourcesr   s         rH   r   zFastMCP.get_resourcesK  s     55I$++:O:OO-/I"&"7"7"="="? -3-A-A-C'C$$$%56 T33AACDKKOOK3 (D  NNGxsSTRUV 	r   c                l   K   | j                          d {   }||vrt        d|       ||   S 7 w)NUnknown resource: )r   r'   )r   r   r   s      rH   get_resourcezFastMCP.get_resource\  sA     ,,..	i"4SE :;;~ /r   c                   K   | j                   j                  d      x}| j                   j                  u ri }| j                  j	                         D ]/  \  }}	 |j                          d{   }|j                  |       1 |j                  | j                  j                                | j                   j                  d|       |S 7 ^# t        $ r%}t        j                  d| d|        Y d}~d}~ww xY ww)zAGet all registered resource templates, indexed by registered key.resource_templatesNz6Failed to get resource templates from mounted server 'r   )rp   r   r   rq   r   get_resource_templatesr   r   r   r   rt   get_templatesr   )r   	templatesr   rG   server_templatesr   s         rH   r   zFastMCP.get_resource_templatesb  s      )=>>I[[""# 68I"&"7"7"="="? 	-3-J-J-L'L$$$%56	 T33AACDKKOO0)< (M  NN"83qc+ r   c                l   K   | j                          d {   }||vrt        d|       ||   S 7 w)NzUnknown resource template: )r   r'   )r   r   r   s      rH   get_resource_templatezFastMCP.get_resource_templatev  sA     5577	i"=cU CDD~ 8r   c                   K   | j                   j                  d      x}| j                   j                  u ri }| j                  j	                         D ]/  \  }}	 |j                          d{   }|j                  |       1 |j                  | j                  j                                | j                   j                  d|       |S 7 ^# t        $ r%}t        j                  d| d|        Y d}~d}~ww xY ww)z-
        List all available prompts.
        promptsNz+Failed to get prompts from mounted server 'r   )rp   r   r   rq   r   get_promptsr   r   r   r   ru   r   )r   r   r   rG   server_promptsr   s         rH   r   zFastMCP.get_prompts|  s      {{y11Gdkk6K6KK)+G"&"7"7"="="? +1+=+=+?%?NNN>2 NN4//;;=>KKOOIw/ &@  NNEfXSQRPST 	r   c                l   K   | j                          d {   }||vrt        d|       ||   S 7 w)NUnknown prompt: )r   r'   )r   r   r   s      rH   r   zFastMCP.get_prompt  sA     ((**g"23% 899s| +r   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., "/oauth/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:
            @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methodsr^   include_in_schema)rr   appendr%   )fnr   r   r^   pathr   s    rH   	decoratorz'FastMCP.custom_route.<locals>.decorator  s7     ((//#&7 IrV   )r   (Callable[[Request], Awaitable[Response]]rT   r   rF   )r   r   r   r^   r   r   s   ````` rH   custom_routezFastMCP.custom_route  s%    8	8	5	 	 rV   c                   K   | j                          d{   }g }|j                         D ]8  \  }}| j                  |      s|j                  |j	                  |             : |S 7 Sw)zh
        List all available tools, in the format expected by the low-level MCP
        server.

        Nr^   )r   r   _should_enable_componentr   to_mcp_tool)r   r   	mcp_toolsr   r   s        rH   r   zFastMCP._mcp_list_tools  sl      nn&&#%	 	=IC,,T2  !1!1s!1!;<	=  '   A,A*-A,&A,c                   K   | j                          d{   }g }|j                         D ]8  \  }}| j                  |      s|j                  |j	                  |             : |S 7 Sw)zl
        List all available resources, in the format expected by the low-level MCP
        server.

        N)uri)r   r   r   r   to_mcp_resource)r   r   mcp_resourcesr   resources        rH   r   zFastMCP._mcp_list_resources  sq      ,,..	+-&__. 	HMC,,X6$$X%=%=#%=%FG	H  /r   c                   K   | j                          d{   }g }|j                         D ]8  \  }}| j                  |      s|j                  |j	                  |             : |S 7 Sw)zu
        List all available resource templates, in the format expected by the low-level
        MCP server.

        N)uriTemplate)r   r   r   r   to_mcp_template)r   r   mcp_templatesr   templates        rH   r   z$FastMCP._mcp_list_resource_templates  sq      5577	35&__. 	PMC,,X6$$X%=%=#%=%NO	P  8r   c                   K   | j                          d{   }g }|j                         D ]8  \  }}| j                  |      s|j                  |j	                  |             : |S 7 Sw)zj
        List all available prompts, in the format expected by the low-level MCP
        server.

        Nr   )r   r   r   r   to_mcp_prompt)r   r   mcp_promptsr   prompts        rH   r   zFastMCP._mcp_list_prompts  sp      ((**')"==? 	CKC,,V4""6#7#7S#7#AB	C  +r   c                T  K   t         j                  d||       t        j                  j                  j                  |       5  	 | j                  ||       d{   cddd       S 7 # t        $ r t        d|       t        $ r t        d|       w xY w# 1 sw Y   yxY ww)aM  
        Handle MCP 'callTool' requests.

        Delegates to _call_tool, which should be overridden by FastMCP subclasses.

        Args:
            key: The name of the tool to call
            arguments: Arguments to pass to the tool

        Returns:
            List of MCP Content objects containing the tool results
        zCall tool: %s with %srk   Nr   )	r   rc   rk   rG   rP   Context
_call_toolr&   r'   )r   r   	argumentss      rH   r   zFastMCP._mcp_call_tool  s      	,c9= ^^##++D+9 	<<!__S)<<	< 	<<  <#nSE$:;;  <#nSE$:;;<	< 	<B   AB(BA+A)A+
B()A++.BBB%!B(c                  K   | j                   j                  |      r_| j                   j                  |      }| j                  |      st	        d|d      | j                   j                  ||       d{   S | j                  j                         D ]J  }|j                  |      s|j                  |      }|j                  j                  ||       d{   c S  t        d|      7 y7 w)aI  
        Call a tool with raw MCP arguments. FastMCP subclasses should override
        this method, not _mcp_call_tool.

        Args:
            key: The name of the tool to call arguments: Arguments to pass to
            the tool

        Returns:
            List of MCP Content objects containing the tool results
        zTool  is disabledNr   )rs   has_toolr   r   r&   r   rq   values
match_toolstrip_tool_prefixrG   r
  r'   )r   r   r  r   rG   tool_keys         rH   r
  zFastMCP._call_tool  s       &&s+%%..s3D006#eC7,$?@@++55c9EEE ++224 	KF  %!33C8#]]55h	JJJ	K
 nSG455 F Ks*   A6C68C292C6,0C6C4C64C6c                t  K   t         j                  d|       t        j                  j                  j                  |       5  	 | j                  |       d{   cddd       S 7 # t        $ r t        dt        |            t        $ r t        dt        |            w xY w# 1 sw Y   yxY ww)z
        Handle MCP 'readResource' requests.

        Delegates to _read_resource, which should be overridden by FastMCP subclasses.
        zRead resource: %sr  Nr   )
r   rc   rk   rG   rP   r	  _read_resourcer&   r'   str)r   r   s     rH   r   zFastMCP._mcp_read_resource1  s      	(#.^^##++D+9 	GG!0055	G 	G5  G#&8S$EFF  G#&8S$EFFG	G 	GsC   AB8B,A)A'A)
B8'A))A B))B,,B51B8c                f  K   | j                   j                  |      r| j                   j                  |       d{   }| j                  |      st	        dt        |      d      | j                   j                  |       d{   }t        ||j                        gS | j                  j                         D ][  }|j                  t        |            s|j                  t        |            }|j                  j                  |       d{   c S  t        d|       7 7 7 w)ze
        Read a resource by URI, in the format expected by the low-level MCP
        server.
        Nz	Resource r  )content	mime_typer   )rt   has_resourcer   r   r&   r  r   r   r  rq   r  match_resourcestrip_resource_prefixrG   r   r'   )r   r   r   r  rG   new_uris         rH   r  zFastMCP._read_resourceC  s    
 !!..s3!33@@EEH00:#iC|<$HII 22@@EEG$#&00  //668 @((S2$::3s8DG!'!A!A'!JJJ@
 $&8$>??! F F Ks;   :D1D+AD1D-	AD18D1D/D1-D1/D1c                T  K   t         j                  d||       t        j                  j                  j                  |       5  	 | j                  ||       d{   cddd       S 7 # t        $ r t        d|       t        $ r t        d|       w xY w# 1 sw Y   yxY ww)z
        Handle MCP 'getPrompt' requests.

        Delegates to _get_prompt, which should be overridden by FastMCP subclasses.
        Get prompt: %s with %sr  Nr   )	r   rc   rk   rG   rP   r	  _get_promptr&   r'   )r   r^   r  s      rH   r   zFastMCP._mcp_get_prompt[  s      	-tY?^^##++D+9 	??!--dI>>	? 	?>  ?#&6tf$=>>  ?#&6tf$=>>?	? 	?r  c                  K   t         j                  d||       | j                  j                  |      r_| j                  j	                  |      }| j                  |      st        d|d      | j                  j                  ||       d{   S | j                  j                         D ]J  }|j                  |      s|j                  |      }|j                  j                  ||       d{   c S  t        d|       7 y7 w)zHandle MCP 'getPrompt' requests.

        Args:
            name: The name of the prompt to render
            arguments: Arguments to pass to the prompt

        Returns:
            GetPromptResult containing the rendered prompt messages
        r  zPrompt r  Nr   )r   rc   ru   
has_promptr   r   r&   render_promptrq   r  match_promptstrip_prompt_prefixrG   r   r'   )r   r^   r  r  rG   prompt_names         rH   r   zFastMCP._get_prompto  s      	-tY? **40))44T:F008#gdX\$BCC--;;D)LLL ++224 	SF""4($88>#]]::;	RRR	S
 .tf566 M Ss*   BDD	2D0D3D4DDc                n    | j                   j                  |       | j                  j                          y)a
  Add a tool to the server.

        The tool function can optionally request a Context object by adding a parameter
        with the Context type annotation. See the @tool decorator for examples.

        Args:
            tool: The Tool instance to register
        N)rs   r~   rp   clear)r   r   s     rH   r~   zFastMCP.add_tool  s(     	##D)rV   c                n    | j                   j                  |       | j                  j                          y)zRemove a tool from the server.

        Args:
            name: The name of the tool to remove

        Raises:
            NotFoundError: If the tool is not found
        N)rs   remove_toolrp   r(  )r   r^   s     rH   r*  zFastMCP.remove_tool  s(     	&&t,rV   r^   descriptiontagsr   exclude_argsenabledc                    y rL   rF   r   
name_or_fnr^   r,  r-  r   r.  r/  s           rH   r   zFastMCP.tool  s     rV   c                    y rL   rF   r1  s           rH   r   zFastMCP.tool  s     14rV   c          
        t        |t              rt        di |}t        |t              rt	        t        j                  d            t        j                  |      r>|}|}	t        j                  ||	||||| j                  |      }
| j                  |
       |
S t        |t              r|t        d| d| d      |}	n||}	nt        dt        |             t        | j                   |	|||||      S )	a  Decorator to register a tool.

        Tools can optionally request a Context object by adding a parameter with the
        Context type annotation. The context provides access to MCP capabilities like
        logging, progress reporting, and resource access.

        This decorator supports multiple calling patterns:
        - @server.tool (without parentheses)
        - @server.tool (with empty parentheses)
        - @server.tool("custom_name") (with name as first argument)
        - @server.tool(name="custom_name") (with name as keyword argument)
        - server.tool(function, name="custom_name") (direct function call)

        Args:
            name_or_fn: Either a function (when used as @tool), a string name, or None
            name: Optional name for the tool (keyword-only, alternative to name_or_fn)
            description: Optional description of what the tool does
            tags: Optional set of tags for categorizing the tool
            annotations: Optional annotations about the tool's behavior (e.g. {"is_async": True})
            exclude_args: Optional list of argument names to exclude from the tool schema
            enabled: Optional boolean to enable or disable the tool

        Example:
            @server.tool
            def my_tool(x: int) -> str:
                return str(x)

            @server.tool
            def my_tool(x: int) -> str:
                return str(x)

            @server.tool("custom_name")
            def my_tool(x: int) -> str:
                return str(x)

            @server.tool(name="custom_name")
            def my_tool(x: int) -> str:
                return str(x)

            # Direct function call
            server.tool(my_function, name="custom_name")
        aA  
                    To decorate a classmethod, first define the method and then call
                    tool() directly on the method instead of using it as a
                    decorator. See https://gofastmcp.com/patterns/decorating-methods
                    for examples and more information.
                    )r^   r,  r-  r   r.  ra   r/  zXCannot specify both a name as first argument and as keyword argument. Use either @tool('z') or @tool(name=''), not both.zAFirst argument to @tool must be a function, string, or None, got r+  rF   )r|   dictr   classmethodr   inspectcleandoc	isroutiner   r}   rv   r~   r  	TypeErrorr   r
   r   )r   r2  r^   r,  r-  r   r.  r/  r   	tool_namer   s              rH   r   zFastMCP.tool  s4   j k4()8K8Kj+.  	 	 Z( BI %%'')00	D MM$K
C())34FtfM[  #IISTXYcTdSef 
 II##%
 	
rV   c                r    | j                   j                  ||       | j                  j                          y)zfAdd a resource to the server.

        Args:
            resource: A Resource instance to add
        r   N)rt   add_resourcerp   r(  )r   r   r   s      rH   r?  zFastMCP.add_resource2  s-     	++H#+>rV   c                >    | j                   j                  ||       y)zwAdd a resource template to the server.

        Args:
            template: A ResourceTemplate instance to add
        r>  N)rt   add_template)r   r  r   s      rH   rA  zFastMCP.add_template<  s     	++H#+>rV   c                    t        j                  dt        d       | j                  j	                  ||||||       | j
                  j                          y)a;  Add a resource or template to the server from a function.

        If the URI contains parameters (e.g. "resource://{param}") or the function
        has parameters, it will be registered as a template resource.

        Args:
            fn: The function to register as a resource
            uri: The URI for the resource
            name: Optional name for the resource
            description: Optional description of the resource
            mime_type: Optional MIME type for the resource
            tags: Optional set of tags for categorizing the resource
        zMThe add_resource_fn method is deprecated. Use the resource decorator instead.r   r   )r   r   r^   r,  r  r-  N)r   rA   r   rt    add_resource_or_template_from_fnrp   r(  )r   r   r   r^   r,  r  r-  s          rH   add_resource_fnzFastMCP.add_resource_fnD  sY    . 	[	

 	??# 	@ 	
 	rV   )r^   r,  r  r-  r/  c               l     t        j                        rt        d      d fd}|S )a  Decorator to register a function as a resource.

        The function will be called when the resource is read to generate its content.
        The function can return:
        - str for text content
        - bytes for binary content
        - other types will be converted to JSON

        Resources can optionally request a Context object by adding a parameter with the
        Context type annotation. The context provides access to MCP capabilities like
        logging, progress reporting, and session information.

        If the URI contains parameters (e.g. "resource://{param}") or the function
        has parameters, it will be registered as a template resource.

        Args:
            uri: URI for the resource (e.g. "resource://my-resource" or "resource://{param}")
            name: Optional name for the resource
            description: Optional description of the resource
            mime_type: Optional MIME type for the resource
            tags: Optional set of tags for categorizing the resource
            enabled: Optional boolean to enable or disable the resource

        Example:
            @server.resource("resource://my-resource")
            def get_data() -> str:
                return "Hello, world!"

            @server.resource("resource://my-resource")
            async get_data() -> str:
                data = await fetch_data()
                return f"Hello, world! {data}"

            @server.resource("resource://{city}/weather")
            def get_weather(city: str) -> str:
                return f"Weather for {city}"

            @server.resource("resource://{city}/weather")
            def get_weather_with_context(city: str, ctx: Context) -> str:
                ctx.info(f"Fetching weather for {city}")
                return f"Weather for {city}"

            @server.resource("resource://{city}/weather")
            async def get_weather(city: str) -> str:
                data = await fetch_weather(city)
                return f"Weather for {city}: {data}"
        zrThe @resource decorator was used incorrectly. Did you forget to call it? Use @resource('uri') instead of @resourcec           	        ddl m t        | t              rt	        t        j                  d            dv xr dv }t        fdt        j                  |       j                  j                         D              }|s|r/t        j                  | 	      }
j                  |       |S |s1|s/t        j                  | 	      }
j                  |       |S t	        d	      )
Nr   )r	  aY  
                        To decorate a classmethod, first define the method and then call
                        resource() directly on the method instead of using it as a
                        decorator. See https://gofastmcp.com/patterns/decorating-methods
                        for examples and more information.
                        {}c              3  >   K   | ]  }|j                   ur|  y wrL   )
annotation).0pr	  s     rH   	<genexpr>z6FastMCP.resource.<locals>.decorator.<locals>.<genexpr>  s%      "<<w. "s   )r   uri_templater^   r,  r  r-  r/  )r   r   r^   r,  r  r-  r/  ziInvalid resource or template definition due to a mismatch between URI parameters and function parameters.)fastmcp.server.contextr	  r|   r7  r   r8  r9  any	signature
parametersr  r   r}   rA  r   r?  )r   has_uri_paramshas_func_paramsr  r   r	  r,  r/  r  r^   r   r-  r   s        @rH   r   z#FastMCP.resource.<locals>.decorator  s   6"k* $$	 	 !CZ6C3JN! " **2.99@@B" O +99!$ +'# !!(+#O#11 +'# !!(+ O rV   )r   r   rT   zResource | ResourceTemplate)r8  r:  r;  )r   r   r^   r,  r  r-  r/  r   s   ``````` rH   r   zFastMCP.resourcej  s:    t S!W 
4	 4	l rV   c                n    | j                   j                  |       | j                  j                          y)z`Add a prompt to the server.

        Args:
            prompt: A Prompt instance to add
        N)ru   
add_promptrp   r(  )r   r  s     rH   rV  zFastMCP.add_prompt  s(     	''/rV   r^   r,  r-  r/  c                    y rL   rF   r   r2  r^   r,  r-  r/  s         rH   r  zFastMCP.prompt  s     rV   c                    y rL   rF   rY  s         rH   r  zFastMCP.prompt  s     36rV   c                  t        |t              rt        t        j                  d            t        j
                  |      r1|}|}t        j                  |||||      }| j                  |       |S t        |t              r|t        d| d| d      |}n||}nt        dt        |             t        | j                  ||||      S )am
  Decorator to register a prompt.

        Prompts can optionally request a Context object by adding a parameter with the
        Context type annotation. The context provides access to MCP capabilities like
        logging, progress reporting, and session information.

        This decorator supports multiple calling patterns:
        - @server.prompt (without parentheses)
        - @server.prompt() (with empty parentheses)
        - @server.prompt("custom_name") (with name as first argument)
        - @server.prompt(name="custom_name") (with name as keyword argument)
        - server.prompt(function, name="custom_name") (direct function call)

        Args:
            name_or_fn: Either a function (when used as @prompt), a string name, or None
            name: Optional name for the prompt (keyword-only, alternative to name_or_fn)
            description: Optional description of what the prompt does
            tags: Optional set of tags for categorizing the prompt
            enabled: Optional boolean to enable or disable the prompt

        Example:
            @server.prompt
            def analyze_table(table_name: str) -> list[Message]:
                schema = read_table_schema(table_name)
                return [
                    {
                        "role": "user",
                        "content": f"Analyze this schema:
{schema}"
                    }
                ]

            @server.prompt()
            def analyze_with_context(table_name: str, ctx: Context) -> list[Message]:
                ctx.info(f"Analyzing table {table_name}")
                schema = read_table_schema(table_name)
                return [
                    {
                        "role": "user",
                        "content": f"Analyze this schema:
{schema}"
                    }
                ]

            @server.prompt("custom_name")
            def analyze_file(path: str) -> list[Message]:
                content = await read_file(path)
                return [
                    {
                        "role": "user",
                        "content": {
                            "type": "resource",
                            "resource": {
                                "uri": f"file://{path}",
                                "text": content
                            }
                        }
                    }
                ]

            @server.prompt(name="custom_name")
            def another_prompt(data: str) -> list[Message]:
                return [{"role": "user", "content": data}]

            # Direct function call
            server.prompt(my_function, name="custom_name")
        aC  
                    To decorate a classmethod, first define the method and then call
                    prompt() directly on the method instead of using it as a
                    decorator. See https://gofastmcp.com/patterns/decorating-methods
                    for examples and more information.
                    )r   r^   r,  r-  r/  zZCannot specify both a name as first argument and as keyword argument. Use either @prompt('z') or @prompt(name='r5  zCFirst argument to @prompt must be a function, string, or None, got rW  )r|   r7  r   r8  r9  r:  r   r}   rV  r  r;  r   r
   r  )	r   r2  r^   r,  r-  r/  r   r&  r  s	            rH   r  zFastMCP.prompt  s	   V j+.  	 	 Z( BK )) 'F OOF#M
C(++5,6J4&P]_  %KKUVZ[eVfUgh 
 KK#
 	
rV   c           
     d  K   t               4 d{   \  }}t        j                  d| j                  d       | j                  j                  ||| j                  j                  t        d                   d{    ddd      d{    y7 7 7 	# 1 d{  7  sw Y   yxY ww)z%Run the server using stdio transport.NStarting MCP server z with transport 'stdio'T)tools_changed)r   r   infor^   ry   r   create_initialization_optionsr   )r   read_streamwrite_streams      rH   r   zFastMCP.run_stdio_async  s     > 	 	%@k<KK.tyym;RST""&&  >>'d;  	 	 		 	 	 	sW   B0BB0A*B?B BB0BB0BB0B-!B$"B-)B0c                t  K   |xs | j                   j                  }|xs | j                   j                  }|xs | j                   j                  j	                         }| j                  |||      }	|xs i }
ddd}|j                  |
       d|vr	d|vr||d<   t        j                  |	f||d|}t        j                  |      }|	j                  j                  j                  d      }t        j                  d	| j                  d
|d| d| d| 
       |j!                          d{    y7 w)a%  Run the server using HTTP transport.

        Args:
            transport: Transport protocol to use - either "streamable-http" (default) 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
        )r   r   
middlewarer   on)timeout_graceful_shutdownrR   
log_configrb   )rd   re   /r]  z with transport z on http://:N)r   rd   re   rb   lowerhttp_appr   uvicornConfigr   stater   lstripr   r_  r^   serve)r   r   rd   re   rb   r   uvicorn_configrd  default_log_level_to_userQ   _uvicorn_config_from_userconfig_kwargsconfigrG   s                 rH   r   zFastMCP.run_http_async  s:    ( 5t00555t0055<22<<
%' 	! mmzmR$2$8b! *+)
 	67},M1Q)AM+&K$TK]K'yy~~$$S)"499-/?	}KX\W]]^_c^ddefjekl	
 llns   D.D80D61D8c                   K   t        j                  dt        d       | j                  d|||||       d{    y7 w)z#Run the server using SSE transport.zThe run_sse_async method is deprecated (as of 2.3.2). Use run_http_async for a modern (non-SSE) alternative, or create an SSE app with `fastmcp.server.http.create_sse_app` and run it directly.r   r   r   r   rd   re   rb   r   rq  Nr   rA   r   r   )r   rd   re   rb   r   rg   rq  s          rH   run_sse_asynczFastMCP.run_sse_async  sS      	H 	
 !!) " 
 	
 	
   7A?Ac                    t        j                  dt        d       t        | |xs | j                  j
                  |xs | j                  j                  | j                  | j                  j                  |      S )z
        Create a Starlette app for the SSE server.

        Args:
            path: The path to the SSE endpoint
            message_path: The path to the message endpoint
            middleware: A list of middleware to apply to the app
        zThe sse_app method is deprecated (as of 2.3.2). Use http_app as a modern (non-SSE) alternative, or call `fastmcp.server.http.create_sse_app` directly.r   r   rG   rg   rf   r{   rc   rd  )	r   rA   r   r.   r   rg   rf   r{   rc   )r   r   rg   rd  s       rH   sse_appzFastMCP.sse_app  so     	R		
 %O)B)B)O)O?T66??++11!
 	
rV   c                `    t        j                  dt        d       | j                  ||      S )z
        Create a Starlette app for the StreamableHTTP server.

        Args:
            path: The path to the StreamableHTTP endpoint
            middleware: A list of middleware to apply to the app
        zSThe streamable_http_app method is deprecated (as of 2.3.2). Use http_app() instead.r   r   )r   rd  )r   rA   r   rk  )r   r   rd  s      rH   streamable_http_appzFastMCP.streamable_http_app  s.     	a	

 }}$:}>>rV   c           
        |dk(  rqt        | |xs | j                  j                  d| j                  | j                  j                  | j                  j
                  | j                  j                  |      S |dk(  r[t        | | j                  j                  |xs | j                  j                  | j                  | j                  j                  |      S y)a  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
            transport: Transport protocol to use - either "streamable-http" (default) or "sse"

        Returns:
            A Starlette application configured with the specified transport
        r   N)rG   rh   event_storer{   ri   rj   rc   rd  r   r|  )
r/   r   rh   r{   ri   rj   rc   r.   rg   rf   )r   r   rd  ri   rj   r   s         rH   rk  zFastMCP.http_app  s    & ))-%) &B,,AA YY"77EE#88GG//55%
 
 %!!66CCC!:!:!C!CYY//55%   rV   c                   K   t        j                  dt        d       | j                  d|||||       d {    y 7 w)Nz]The run_streamable_http_async method is deprecated (as of 2.3.2). Use run_http_async instead.r   r   r   rw  rx  )r   rd   re   rb   r   rq  s         rH   run_streamable_http_asyncz!FastMCP.run_streamable_http_async6  sP      	*		
 !!') " 
 	
 	
rz  )tool_separatorresource_separatorprompt_separatorc                  ddl m} ddlm} ddlm}	 |t        j                  dt        d       |t        j                  d	t        d       |t        j                  d
t        d       ||j                  }|r!t        ||	      s |	 | ||                  }t        ||      }
|
| j                  |<   | j                  j                          y)a
  Mount another FastMCP server on this server with the given prefix.

        Unlike importing (with import_server), mounting establishes a dynamic connection
        between servers. When a client interacts with a mounted server's objects through
        the parent server, requests are forwarded to the mounted server in real-time.
        This means changes to the mounted server are immediately reflected when accessed
        through the parent.

        When a server is mounted:
        - Tools from the mounted server are accessible with prefixed names.
          Example: If server has a tool named "get_weather", it will be available as "prefix_get_weather".
        - Resources are accessible with prefixed URIs.
          Example: If server has a resource with URI "weather://forecast", it will be available as
          "weather://prefix/forecast".
        - Templates are accessible with prefixed URI templates.
          Example: If server has a template with URI "weather://location/{id}", it will be available
          as "weather://prefix/location/{id}".
        - Prompts are accessible with prefixed names.
          Example: If server has a prompt named "weather_prompt", it will be available as
          "prefix_weather_prompt".

        There are two modes for mounting servers:
        1. Direct mounting (default when server has no custom lifespan): The parent server
           directly accesses the mounted server's objects in-memory for better performance.
           In this mode, no client lifecycle events occur on the mounted server, including
           lifespan execution.

        2. Proxy mounting (default when server has a custom lifespan): The parent server
           treats the mounted server as a separate entity and communicates with it via a
           Client transport. This preserves all client-facing behaviors, including lifespan
           execution, but with slightly higher overhead.

        Args:
            prefix: Prefix to use for the mounted server's objects.
            server: The FastMCP server to mount.
            as_proxy: Whether to treat the mounted server as a proxy. If None (default),
                automatically determined based on whether the server has a custom lifespan
                (True if it has a custom lifespan, False otherwise).
            tool_separator: Deprecated. Separator character for tool names.
            resource_separator: Deprecated. Separator character for resource URIs.
            prompt_separator: Deprecated. Separator character for prompt names.
        r   r7   )FastMCPTransportr?   NThe tool_separator parameter is deprecated and will be removed in a future version. Tools are now prefixed using 'prefix_toolname' format.r   r   The resource_separator parameter is deprecated and ignored. Resource prefixes are now added using the protocol://prefix/path format.The prompt_separator parameter is deprecated and will be removed in a future version. Prompts are now prefixed using 'prefix_promptname' format.)r   rG   r   )rk   r8   fastmcp.client.transportsr  fastmcp.server.proxyr@   r   rA   r   rw   r|   MountedServerrq   rp   r(  )r   r   rG   as_proxyr  r  r  r8   r  r@   mounted_servers              rH   mountzFastMCP.mountN  s    h 	#>5%MMI"	 )MM["	 'MMM"	 ++HJv|<!&3CF3K"LMF&
 )7f%rV   c                n    | j                   j                  |       | j                  j                          y rL   )rq   poprp   r(  )r   r   s     rH   unmountzFastMCP.unmount  s&    !!&)rV   c                  K   |t        j                  dt        d       |t        j                  dt        d       |t        j                  dt        d       | d}|j                          d{   j	                         D ]&  \  }}| j
                  j                  || |        ( |j                          d{   j	                         D ]9  \  }}	t        ||| j                        }
| j                  j                  |	|
       ; |j                          d{   j	                         D ]9  \  }}t        ||| j                        }
| j                  j                  ||
       ; | d}|j                          d{   j	                         D ]&  \  }}| j                  j!                  || |        ( t"        j%                  d	|j&                   d
| d       t"        j)                  d| d       t"        j)                  d| d       t"        j)                  d| d       | j*                  j-                          y7 7 7 57 Эw)a~  
        Import the MCP objects from another FastMCP server into this one,
        optionally with a given prefix.

        Note that when a server is *imported*, its objects are immediately
        registered to the importing server. This is a one-time operation and
        future changes to the imported server will not be reflected in the
        importing server. Server-level configurations and lifespans are not imported.

        When a server is imported:
        - The tools are imported with prefixed names
          Example: If server has a tool named "get_weather", it will be
          available as "prefix_get_weather"
        - The resources are imported with prefixed URIs using the new format
          Example: If server has a resource with URI "weather://forecast", it will
          be available as "weather://prefix/forecast"
        - The templates are imported with prefixed URI templates using the new format
          Example: If server has a template with URI "weather://location/{id}", it will
          be available as "weather://prefix/location/{id}"
        - The prompts are imported with prefixed names
          Example: If server has a prompt named "weather_prompt", it will be available as
          "prefix_weather_prompt"

        Args:
            prefix: The prefix to use for the imported server
            server: The FastMCP server to import
            tool_separator: Deprecated. Separator for tool names.
            resource_separator: Deprecated and ignored. Prefix is now
              applied using the protocol://prefix/path format
            prompt_separator: Deprecated. Separator for prompt names.
        Nr  r   r   r  r  _r>  zImported server z with prefix ''zImported tools with prefix 'z.Imported resources and templates with prefix 'z/'zImported prompts with prefix ')r   rA   r   r   r   rs   r~   r   add_resource_prefixrm   rt   r?  r   rA  r   ru   rV  r   r_  r^   rc   rp   r(  )r   r   rG   r  r  r  tool_prefixr   r   r   prefixed_keyr  prompt_prefixr  s                 rH   import_serverzFastMCP.import_server  sW    N %MMI"	 )MM["	 'MMM"	  l & 0 0 2299; 	IIC''[M#2G'H	I %+$8$8$::AAC 	LMC.sFD<W<WXL""//l/K	L %+$A$A$CCJJL 	LMC.sFD<W<WXL""//l/K	L
 "(!"("4"4"66==? 	QKC  ++F=/#8O+P	Q 	&v{{m>&KL3K=BCEfXRPQ5m_AFG- 3 ; D 7sL   A3I 5I6AI IA!I &I'A&I ICI I I I c                .    ddl m}	  |	d|||||||d|S )zH
        Create a FastMCP server from an OpenAPI specification.
           r<   )openapi_specclient
route_mapsroute_map_fnmcp_component_fn	mcp_namesr-  rF   )openapir<   )
clsr  r  r  r  r  r  r-  rl   r<   s
             rH   from_openapizFastMCP.from_openapi  s8     	, 	
%!%-	
 	
 		
rV   c	                    ddl m}
 |i }|j                  dd       t        j                  ddt        j
                  |      i|}|xs |j                  } |
d|j                         |||||||d|	S )	zE
        Create a FastMCP server from a FastAPI application.
        r  r  base_urlzhttp://fastapir   )rQ   )r  r  r^   r  r  r  r  r-  rF   )r  r<   
setdefaulthttpxAsyncClientASGITransporttitle)r  rQ   r^   r  r  r  r  httpx_client_kwargsr-  rl   r<   r  s               rH   from_fastapizFastMCP.from_fastapi,  s    " 	,&"$&&z3CD"" 
))c2
!

  syy 

!%-

 

 
	
rV   c                \    ddl m} ddlm} t	        ||      r|}n ||      } |dd|i|S )aN  Create a FastMCP proxy server for the given backend.

        The ``backend`` argument can be either an existing :class:`~fastmcp.client.Client`
        instance or any value accepted as the ``transport`` argument of
        :class:`~fastmcp.client.Client`. This mirrors the convenience of the
        ``Client`` constructor.
        r   r7   r?   r  rF   )fastmcp.client.clientr8   r  r@   r|   )r  backendrl   r8   r@   r  s         rH   r  zFastMCP.as_proxyV  s5    ( 	15gv&FG_F666X66rV   c                `    t        j                  dt        d        | j                  |fi |S )zF
        Create a FastMCP proxy server from a FastMCP client.
        zDFastMCP.from_client() is deprecated; use FastMCP.as_proxy() instead.r   r   )r   rA   r   r  )r  r  rl   s      rH   from_clientzFastMCP.from_clientt  s1     	R	
 s||F/h//rV   c                    j                   sy| j                  | j                  y| j                  t        fd| j                  D              ry| j                   t        fd| j                  D              ryyy)u!  
        Given a component, determine if it should be enabled. Returns True if it should be enabled; False if it should not.

        Rules:
            • If the component's enabled property is False, always return False.
            • If both include_tags and exclude_tags are None, return True.
            • If exclude_tags is provided, check each exclude tag:
                - If the exclude tag is a string, it must be present in the input tags to exclude.
            • If include_tags is provided, check each include tag:
                - If the include tag is a string, it must be present in the input tags to include.
            • If include_tags is provided and none of the include tags match, return False.
            • If include_tags is not provided, return True.
        FTc              3  :   K   | ]  }|j                   v   y wrL   r-  )rK  etag	components     rH   rM  z3FastMCP._should_enable_component.<locals>.<genexpr>       Hd49>>)H   c              3  :   K   | ]  }|j                   v   y wrL   r  )rK  itagr  s     rH   rM  z3FastMCP._should_enable_component.<locals>.<genexpr>  r  r  )r/  r   r   rP  )r   r  s    `rH   r   z FastMCP._should_enable_component  sw    "   $):):)B(Hd6G6GHH(Hd6G6GHHrV   )NNNNNNNNNNNNNNNNNNNNNNNN)0r^   
str | Noner_   r  r{   zOAuthProvider | NonerR   zYCallable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]] | Noner   zCallable[[Any], str] | Noner   zfloat | Noner   DuplicateBehavior | Noner   r  r   r  rm   "Literal['protocol', 'path'] | Noner]   bool | Noner   z&list[Tool | Callable[..., Any]] | Noner   list[str] | Noner   set[str] | Noner   r  rb   r  rc   r  rd   r  re   
int | Nonerf   r  rg   r  rh   r  ri   r  rj   r  )rT   r  )rb   r  rc   r  rd   r  re   r  rf   r  rg   r  rh   r  ri   r  rj   r  rT   None)rT   r  rL   )r   z1Literal['stdio', 'streamable-http', 'sse'] | Noner   r   rT   r  )rT   r  rT   zdict[str, Tool])r   r  rT   r   rT   zdict[str, Resource])r   r  rT   r   rT   zdict[str, ResourceTemplate])r   r  rT   r   rT   zdict[str, Prompt])r   r  rT   r   )NT)r   r  r   z	list[str]r^   r  r   bool)rT   zlist[MCPTool])rT   zlist[MCPResource])rT   zlist[MCPResourceTemplate])rT   zlist[MCPPrompt])r   r  r  dict[str, Any]rT   z3list[TextContent | ImageContent | EmbeddedResource])r   zAnyUrl | strrT   zlist[ReadResourceContents])r^   r  r  dict[str, Any] | NonerT   r   )r   r   rT   r  )r^   r  rT   r  )r2  r   r^   r  r,  r  r-  r  r   'ToolAnnotations | dict[str, Any] | Noner.  r  r/  r  rT   r2   )r2  r  r^   r  r,  r  r-  r  r   r  r.  r  r/  r  rT   z%Callable[[AnyFunction], FunctionTool])r2  str | AnyFunction | Noner^   r  r,  r  r-  r  r   r  r.  r  r/  r  rT   z4Callable[[AnyFunction], FunctionTool] | FunctionTool)r   r   r   r  rT   r  )r  r   r   r  rT   r  )NNNN)r   r   r   r  r^   r  r,  r  r  r  r-  r  rT   r  )r   r  r^   r  r,  r  r  r  r-  r  r/  r  rT   z4Callable[[AnyFunction], Resource | ResourceTemplate])r  r   rT   r  )r2  r   r^   r  r,  r  r-  r  r/  r  rT   r)   )r2  r  r^   r  r,  r  r-  r  r/  r  rT   z'Callable[[AnyFunction], FunctionPrompt])r2  r  r^   r  r,  r  r-  r  r/  r  rT   z8Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt)r   NNNNNN)r   !Literal['streamable-http', 'sse']rd   r  re   r  rb   r  r   r  rq  r  rd  list[Middleware] | NonerT   r  )NNNNNN)rd   r  re   r  rb   r  r   r  rg   r  rq  r  rT   r  )NNN)r   r  rg   r  rd  r  rT   r-   )NN)r   r  rd  r  rT   r-   )NNNNr   )r   r  rd  r  ri   r  rj   r  r   r  rT   r-   )NNNNN)rd   r  re   r  rb   r  r   r  rq  r  rT   r  )r   r  rG   FastMCP[LifespanResultT]r  r  r  r  r  r  r  r  rT   r  )r   r  rT   r  )r   r  rG   r  r  r  r  r  r  r  rT   r  )r  r  r  zhttpx.AsyncClientr  list[RouteMap] | Noner  OpenAPIRouteMapFn | Noner  OpenAPIComponentFn | Noner  dict[str, str] | Noner-  r  rl   r   rT   r<   )NNNNNNN)rQ   r   r^   r  r  r  r  r  r  r  r  r  r  r  r-  r  rl   r   rT   r<   )r  zlClient[ClientTransportT] | ClientTransport | FastMCP[Any] | AnyUrl | Path | MCPConfig | dict[str, Any] | strrl   r   rT   r@   )r  zClient[ClientTransportT]rl   r   rT   r@   )r  r4   rT   r  )9r   
__module____qualname__r   r   r   propertyr^   r_   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r
  r   r  r   r   r~   r*  r   r   r?  rA  rD  r   rV  r  r   r   ry  r}  r  rk  r  r  r  r  r7  r  r  r  r  r   rF   rV   rH   rX   rX   o   s
     #'%) 7;157;;?9=EI*.8<)-(,(, !%!##'+/%)&*Id
d
 !d
 #	d
d
 5d
 #/d
 5d
 !9d
  7!d
" !C#d
$ (%d
& 6'd
( ')d
* &+d
, &-d
8 9d
: ;d
< =d
> ?d
@ Ad
B !Cd
D )Ed
F #Gd
H $Id
L7$B$B $B 	$B
 $B $B !$B )$B #$B $$B 
$BL % % - -
 HL@D@  @ 
	@0 HLJDJ  J 
	J<""(&  "&** * 	*
  *X<<#1<	<<866#16	<6<G$@2 =A??$9?	?* =A77$97	7:

 
  "& $?C)-#

 	

  
 
 =
 '
 
 

 
  "&
4  "& $?C)-#
4
4 	
4
  
4 
4 =
4 '
4 
4 
/
4 
4 04r
  "& $?C)-#r
,r
 	r

  r
 r
 =r
 'r
 r
 
>r
h?  "& $ $$$ $ 	$
  $ $ $ 
$T  "& $ $#vv 	v
  v v v v 
>vp 
  "& $# 	
     
   "&6  "& $#66 	6
  6 6 6 
16 6 04A
  "& $#A
,A
 	A

  A
 A
 A
 
BA
F
 8I $04.2-4- - 	-
 - - .- ,- 
-b   $#'04

 
 	

 
 !
 .
 

<  #'.2	

 !
 ,	

 

@  .2?? ,? 
	?,  .2%)&*7H'' ,' #	'
 $' 5' 
'V   $04

 
 	

 
 .
 

8 !%	` &*)-'+`` )` 	` #` '` %` 
`D &*)-'+ZZ )Z #	Z
 'Z %Z 
Zx 
 -1156:+/ $
$
 "
 *	

 /
 4
 )
 
 
 

 
6   ,0156:+/59 $'
'
 '
 *	'

 /'
 4'
 )'
 3'
 '
 '
 
'
 '
R 77 7 
7 7: 0-0;>0	0 0!#! 
!rV   rX   c                  l    e Zd Z	 	 	 	 ddZddZddZddZddZddZddZ	ddZ
dd	Zdd
ZddZy)r  c                     || _         || _        y rL   r  )r   r   rG   s      rH   r   zMountedServer.__init__  s    
 rV   c                   K   | j                   j                          d {   }|j                         D ci c]  \  }}| j                   d| | c}}S 7 7c c}}w wNr  )rG   r   r   r   )r   r   r   r   s       rH   r   zMountedServer.get_tools  sR     kk++-->CkkmLd4;;-q&,LL .L    A AA AA A c           	        K   | j                   j                          d {   }|j                         D ci c]1  \  }}t        || j                  | j                   j
                        |3 c}}S 7 Qc c}}w wrL   )rG   r   r   r  r   rm   )r   r   r   r   s       rH   r   zMountedServer.get_resources  sq     ++3355	
 "+!2	
 X  T[[$++"D"D
 	
 6
    A:A2A:6A4.A:4A:c           	        K   | j                   j                          d {   }|j                         D ci c]1  \  }}t        || j                  | j                   j
                        |3 c}}S 7 Qc c}}w wrL   )rG   r   r   r  r   rm   )r   r   r   r  s       rH   r   z$MountedServer.get_resource_templates  sq     ++<<>>	
 "+!2	
 X  T[[$++"D"D
 	
 ?
r  c                   K   | j                   j                          d {   }|j                         D ci c]  \  }}| j                   d| | c}}S 7 7c c}}w wr  )rG   r   r   r   )r   r   r   r  s       rH   r   zMountedServer.get_prompts  sR     //11BI--/R;34;;-q&.RR 2Rr  c                >    |j                  | j                   d      S r  
startswithr   r   r   s     rH   r  zMountedServer.match_tool      ~~Q/00rV   c                >    |j                  | j                   d      S r  removeprefixr   r  s     rH   r  zMountedServer.strip_tool_prefix      4;;-q 122rV   c                X    t        || j                  | j                  j                        S rL   )has_resource_prefixr   rG   rm   r  s     rH   r  zMountedServer.match_resource  s    "3T[[5W5WXXrV   c                X    t        || j                  | j                  j                        S rL   )remove_resource_prefixr   rG   rm   r  s     rH   r  z#MountedServer.strip_resource_prefix  s$    %dkk@@
 	
rV   c                >    |j                  | j                   d      S r  r  r  s     rH   r$  zMountedServer.match_prompt  r  rV   c                >    |j                  | j                   d      S r  r  r  s     rH   r%  z!MountedServer.strip_prompt_prefix  r  rV   N)r   r  rG   r  r  r  r  r  )r   r  rT   r  )r   r  rT   r  )r   r  r  r   r   r   r   r   r  r  r  r  r$  r%  rF   rV   rH   r  r    sN     )M

S13Y

13rV   r  c                   |s| S |t         j                  j                  }|dk(  r| d|  S |dk(  rBt        j	                  |       }|st        d|  d      |j                         \  }}| | d| S t        d|       )a  Add a prefix to a resource URI.

    Args:
        uri: The original resource URI
        prefix: The prefix to add

    Returns:
        The resource URI with the prefix added

    Examples:
        >>> add_resource_prefix("resource://path/to/resource", "prefix")
        "resource://prefix/path/to/resource"  # with new style
        >>> add_resource_prefix("resource://path/to/resource", "prefix")
        "prefix+resource://path/to/resource"  # with legacy style
        >>> add_resource_prefix("resource:///absolute/path", "prefix")
        "resource://prefix//absolute/path"  # with new style

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    protocol+r   Invalid URI format: ". Expected protocol://path format.rh  Invalid prefix format: )rk   rl   rm   URI_PATTERNmatchr   groups)r   r   prefix_formatr  r  r   s         rH   r  r    s    . 
 ((??
"3%  	&	  !!#&&se+MN  $ F81TF++2=/BCCrV   c                   |s| S |t         j                  j                  }|dk(  r&| d}| j                  |      r| t	        |      d S | S |dk(  rt
        j                  |       }|st        d|  d      |j                         \  }}dt        j                  |       d}t        j                  ||      }|s| S | |j                  d	       S t        d
|       )a
  Remove a prefix from a resource URI.

    Args:
        uri: The resource URI with a prefix
        prefix: The prefix to remove
        prefix_format: The format of the prefix to remove
    Returns:
        The resource URI with the prefix removed

    Examples:
        >>> remove_resource_prefix("resource://prefix/path/to/resource", "prefix")
        "resource://path/to/resource"  # with new style
        >>> remove_resource_prefix("prefix+resource://path/to/resource", "prefix")
        "resource://path/to/resource"  # with legacy style
        >>> remove_resource_prefix("resource://prefix//absolute/path", "prefix")
        "resource:///absolute/path"  # with new style

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    Nr  r  r   r  r  ^z/(.*?)$r  r  )rk   rl   rm   r  lenr  r  r   r  reescapegroup)	r   r   r  legacy_prefixr  r  r   prefix_pattern
path_matchs	            rH   r  r    s   . 
((??
"!(!>>-(s=)+,,
	&	  !!#&&se+MN  $ RYYv./w7XXnd3
J J,,Q/0112=/BCCrV   c                ~   |sy|t         j                  j                  }|dk(  r| d}| j                  |      S |dk(  rqt        j                  |       }|st        d|  d      |j                         \  }}dt        j                  |       d}t        t        j
                  ||            S t        d	|       )
a  Check if a resource URI has a specific prefix.

    Args:
        uri: The resource URI to check
        prefix: The prefix to look for

    Returns:
        True if the URI has the specified prefix, False otherwise

    Examples:
        >>> has_resource_prefix("resource://prefix/path/to/resource", "prefix")
        True  # with new style
        >>> has_resource_prefix("prefix+resource://path/to/resource", "prefix")
        True  # with legacy style
        >>> has_resource_prefix("resource://other/path/to/resource", "prefix")
        False

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    Fr  r  r   r  r  r  rh  r  )rk   rl   rm   r  r  r  r   r  r  r  r  )r   r   r  r  r  r  r   r  s           rH   r  r  M  s    .  ((??
"!(!~~m,,	&	  !!#&&se+MN  ,,.4 RYYv./q1BHH^T2332=/BCCrV   )rG   r  rT   zAsyncIterator[Any])rQ   r  rR   zRCallable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]]rT   zTCallable[[MCPServer[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]]rL   )r   r  r   r  r  r  rT   r  )r   r  r   r  r  r  rT   r  ){__doc__
__future__r   rn   r8  r  r   collections.abcr   r   r   
contextlibr   r   r	   	functoolsr
   pathlibr   typingr   r   r   r   r   r   r  rl   mcp.server.lowlevel.helper_typesr   mcp.server.lowlevel.serverr   r   r   rx   mcp.server.stdior   	mcp.typesr   r   r   r   r   r   r   	MCPPromptr   MCPResourcer   MCPResourceTemplater   MCPToolpydanticr    starlette.middlewarer!   starlette.requestsr"   starlette.responsesr#   starlette.routingr$   r%   rk   fastmcp.serverfastmcp.exceptionsr&   r'   fastmcp.promptsr(   fastmcp.prompts.promptr)   fastmcp.resourcesr*   fastmcp.resources.templatefastmcp.server.auth.authr+   (fastmcp.server.auth.providers.bearer_envr,   fastmcp.server.httpr-   r.   r/   fastmcp.settingsr0   fastmcp.toolsr1   fastmcp.tools.toolr2   fastmcp.utilities.cacher3   fastmcp.utilities.componentsr4   fastmcp.utilities.loggingr5   fastmcp.utilities.mcp_configr6   fastmcp.clientr8   r  r9   r:   fastmcp.server.openapir;   OpenAPIComponentFnr<   r=   r>   OpenAPIRouteMapFnr  r@   r   r   DuplicateBehaviorcompiler  rI   rU   rX   r  r  r  r  rF   rV   rH   <module>r2     s   ; "   	  > > 
   A A    A K : )  * - = %  + & ( .   ; 1 1 7 7 2 J 
 & % 1 . 9 0 2%KH?F1	H	@A  bjj-. 	 		!
"vgo& vr153 53r PT0D	0D0D*L0D0Dh PT7D	7D7D*L7D7Dv PT2D	2D2D*L2D	2DrV   