o
    i                    @  s  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Zddlm	Z	m
Z
mZ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 dd	lmZ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$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.m/Z/m0Z0m1Z1 ddl"m2Z3 ddl"m4Z5 ddl"m6Z7 ddl"m8Z9 ddl:m;Z; ddl<m=Z> ddl?m@Z@ ddlAmBZB ddlCmDZDmEZE ddlFZFddlGZFddlHmIZImJZJ ddlKmLZL ddlMm2Z2 ddlNmOZO ddlPmQZQ ddlRm4Z4 ddlSmTZT ddlUm6Z6 ddlVmWZW ddlXmYZYmZZZm[Z[ ddl\m]Z] ddl^m=Z=m_Z_ dd l`maZa dd!lbmcZcm8Z8mdZd dd"lemfZf dd#lgmhZh dd$limjZj dd%lkmlZl dd&lmmnZnmoZo dd'lpmqZqmrZr erdd(lsmtZt dd)lumvZv dd*lwmxZxmyZy dd+lzm{Z| dd,l}m~Z dd-l}mZ dd.l}mZ dd,lm~Z dd/lm{Z{mZ dd.lmZ dd0lmZ dd1lmZ dd2lbmZ eneZed3 Zed4 Zed5Zed6gee( f ZedPd:d;ZdQd>d?ZG d@dA dAee( ZeG dBdC dCZ	dRdSdIdJZ	dRdSdKdLZ	dRdTdNdOZdS )Uz5FastMCP - A more ergonomic interface for MCP servers.    )annotationsN)AsyncIterator	AwaitableCallable
CollectionMappingSequence)AbstractAsyncContextManagerAsyncExitStackasynccontextmanager)	dataclass)partial)Path)TYPE_CHECKINGAnyGenericLiteralcastoverload)ReadResourceContents)LifespanResultTNotificationOptions)stdio_server)AnnotationsAnyFunctionCallToolRequestParamsContentBlockGetPromptResultToolAnnotations)Prompt)Resource)ResourceTemplate)Tool)AnyUrl)
Middleware)Request)Response)	BaseRouteRoute)DisabledErrorNotFoundError)	MCPConfig)FunctionPrompt)PromptManager)ResourceManager)AuthProvider)StarletteWithLifespancreate_sse_appcreate_streamable_http_app)LowLevelServer)r$   MiddlewareContext)Settings)FunctionToolr"   
ToolResult)ToolManager)ToolTransformConfig)log_server_banner)FastMCPComponent)
get_loggertemporary_log_level)NotSetNotSetTClient)FastMCP1Server)ClientTransportClientTransportTFastMCPOpenAPI)ComponentFn)RouteMap)
RouteMapFn)rF   rH   FastMCPProxy)ServerSamplingHandler)ToolResultSerializerType)warnerrorreplaceignore)stdiohttpssestreamable-httpz^([^:]+://)(.*?)$FastMCP[LifespanResultT]serverreturnAsyncIterator[Any]c                 C s   i V  dS )zDefault lifespan context manager that does nothing.

    Args:
        server: The server instance this lifespan is managing

    Returns:
        An empty dictionary as the lifespan result.
    N )rW   rZ   rZ   [/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/fastmcp/server/server.pydefault_lifespanp   s   

r\   fastmcp_serverYCallable[[LowLevelServer[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]]c                   s   t d fdd}|S )Nlow_level_serverLowLevelServer[LifespanResultT]rX   AsyncIterator[LifespanResultT]c                  s0    j tu ri V  d S  jstd jV  d S )Na  FastMCP server has a lifespan defined but no lifespan result is set, which means the server's context manager was not entered.  Are you running the server in a way that supports lifespans? If so, please file an issue at https://github.com/jlowin/fastmcp/issues.)	_lifespanr\   _lifespan_result_setRuntimeError_lifespan_result)r_   r]   rZ   r[   wrap   s   
z_lifespan_proxy.<locals>.wrap)r_   r`   rX   ra   )r   )r]   rg   rZ   rf   r[   _lifespan_proxy}   s   rh   c                    @  s  e Zd Z		dEdddeddddddddddddddddddddddddddddFd3d4ZdGd7d8ZdHd:d;ZedId=d>ZedGd?d@Z	edJdAdBZ
e
jdKdDdBZ
edJdEdFZedJdGdHZedLdJdKZedMdMdNZ		OdNdOdVdWZ		OdNdOdXdYZdPdZd[ZdQd`daZdRdcddZdSdfdgZdTdjdkZdUdmdnZdVdpdqZdWdsdtZdXdvdwZdYdydzZdZd|d}Z		OdNd[ddZd\ddZd]ddZ d^ddZ!d_ddZ"d`ddZ#daddZ$dbddZ%dcddZ&ddddZ'deddZ(dfddZ)dgddZ*dhddZ+diddZ,djddZ-dkddZ.dlddZ/dlddZ0dmddZ1	dndoddÄZ2	dndoddńZ3dpddȄZ4dqdd˄Z5drdd̈́Z6dsdd҄Z7dtddԄZ8e9dddddeddddd՜
duddZ:e9	dndddddeddddd՜
dvddZ:	dndddddeddddd՜
dwddZ:dxddZ;dyddZ<				dzd{ddZ=dddddddddd	d|ddZ>d}ddZ?e9ddddddddd~dd Z@e9	dnddddddddddd Z@	dnddddddddddd Z@	ddddZA	O									ddddZB					ddddZC			ddddZD		dEdddZE					ddddZF					ddddZG		dEdddddd d!ZH				dzdd"d#ZIeJ					ddd1d2ZKeJ							ddd5d6ZLeJdd:d;ZMeJdd=d>ZNddAdBZOeJdnddCdDZPdS (  FastMCPN)versionwebsite_urliconsauth
middlewarelifespandependenciesresource_prefix_formatmask_error_detailstoolstool_transformationstool_serializerinclude_tagsexclude_tagsinclude_fastmcp_metaon_duplicate_toolson_duplicate_resourceson_duplicate_promptsstrict_input_validation	log_leveldebughostportsse_pathmessage_pathstreamable_http_pathjson_responsestateless_httpsampling_handlersampling_handler_behaviorname
str | Noneinstructionsrj   rk   rl   list[mcp.types.Icon] | Nonerm   AuthProvider | NotSetT | Nonern   Sequence[Middleware] | Nonero   LifespanCallable | Nonerp   list[str] | Nonerq   "Literal['protocol', 'path'] | Nonerr   bool | Noners   *Sequence[Tool | Callable[..., Any]] | Nonert   (Mapping[str, ToolTransformConfig] | Noneru   ToolResultSerializerType | Nonerv   Collection[str] | Nonerw   rx   ry   DuplicateBehavior | Nonerz   r{   r|   r}   r~   r   r   
int | Noner   r   r   r   r   r   -ServerSamplingHandler[LifespanResultT] | Noner   $Literal['always', 'fallback'] | Nonec          #      C  s  |
pt jj| _g | _g | _t|||d| _t||d| _t	||d| _
|| _|p)t| _d | _d| _tt | |p:|  |p>t j|||t| dd| _|tu r[t jjd urYt j }nd }ttd B || _|r||D ]}!t|!tsvtj|!| jd}!| |! qg|d urt |nd | _!|d urt |nd | _"|d ur|nt jj#| _#t$|pg | _%| &  |	d urdd l'}"|"j(dt)*|	 d	t+d
d |	pt jj,| _-|| _.| pd| _/|d ur|nt jj0| _0| j1|||||||||d	 d S )N)duplicate_behaviorrr   transformations)r   rr   Frf   )fastmcpr   rj   r   rk   rl   ro   )
serializerr   zThe 'dependencies' parameter is deprecated as of FastMCP 2.11.4 and will be removed in a future version. Please specify dependencies in a fastmcp.json configuration file instead:
{
  "entrypoint": "your_server.py",
  "environment": {
    "dependencies": z[
  }
}
See https://gofastmcp.com/docs/deployment/server-configuration for more information.   
stacklevelfallback)	r}   r~   r   r   r   r   r   r   r   )2r   settingsrq   _additional_http_routes_mounted_serversr8   _tool_managerr.   _resource_managerr-   _prompt_manager_tool_serializerr\   rb   re   rc   r3   r   generate_name__version__rh   _mcp_serverr>   server_authserver_auth_classr   r/   rm   
isinstancer"   from_functionadd_toolsetrv   rw   r|   listrn   _setup_handlerswarningsrN   jsondumpsDeprecationWarningserver_dependenciesrp   r   r   rx   _handle_deprecated_settings)#selfr   r   rj   rk   rl   rm   rn   ro   rp   rq   rr   rs   rt   ru   rv   rw   rx   ry   rz   r{   r|   r}   r~   r   r   r   r   r   r   r   r   r   toolr   rZ   rZ   r[   __init__   s   
*





zFastMCP.__init__rX   strc                 C  s   t | j d| jdS )N())type__name__r   r   rZ   rZ   r[   __repr__2  s   zFastMCP.__repr__Nonec
              
   C  s   i }
d|fd|fd|fd|fd|fd|fd|fd|fd	|	ff	D ]\}}|d
ur;t jjr7tjd| dtdd ||
|< qt j |
B }tdi || _d
S )z0Handle deprecated settings. Deprecated in 2.8.0.r}   r~   r   r   r   r   r   r   r   NzProviding `ze` when creating a server is deprecated. Provide it when calling `run` or as a global setting instead.r   r   rZ   )	r   r   deprecation_warningsr   rN   r   
model_dumpr5   _deprecated_settings)r   r}   r~   r   r   r   r   r   r   r   deprecated_settingsr   argcombined_settingsrZ   rZ   r[   r   5  s,   
z#FastMCP._handle_deprecated_settingsr5   c                 C  s   t jjrtjdtdd | jS )NzeAccessing `.settings` on a FastMCP instance is deprecated. Use the global `fastmcp.settings` instead.r   r   )r   r   r   r   rN   r   r   r   rZ   rZ   r[   r   \  s   zFastMCP.settingsc                 C     | j jS N)r   r   r   rZ   rZ   r[   r   g     zFastMCP.namec                 C  r   r   r   r   r   rZ   rZ   r[   r   k  r   zFastMCP.instructionsvaluec                 C  s   || j _d S r   r   )r   r   rZ   rZ   r[   r   o  s   c                 C  r   r   )r   rj   r   rZ   rZ   r[   rj   s  r   zFastMCP.versionc                 C  r   r   )r   rk   r   rZ   rZ   r[   rk   w  r   zFastMCP.website_urllist[mcp.types.Icon]c                 C  s   | j jd u rg S t| j jS r   )r   rl   r   r   rZ   rZ   r[   rl   {  s   zFastMCP.iconsAsyncIterator[None]c              
   C s   | j r	d V  d S | | 4 I d H G}|| _d| _ ttd B   4 I d H  }| jD ]}|j|j dI d H  q(d V  W d   I d H  n1 I d H sJw   Y  W d   I d H  n1 I d H s_w   Y  d| _ d | _d S )NT)cmF)	rc   rb   re   r
   boolr   enter_async_contextrW   _lifespan_manager)r   lifespan_resultstackrW   rZ   rZ   r[   r     s"   
*(
zFastMCP._lifespan_managerT	transportTransport | Noneshow_bannerr   transport_kwargsr   c                   s   |du rd}|dvrt d| |dkr%| jdd|i|I dH  dS |dv r9| jd||d|I dH  dS t d| )	zRun the FastMCP server asynchronously.

        Args:
            transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
        NrR   >   rT   rS   rR   rU   zUnknown transport: r   >   rT   rS   rU   )r   r   rZ   )
ValueErrorrun_stdio_asyncrun_http_asyncr   r   r   r   rZ   rZ   r[   	run_async  s&   zFastMCP.run_asyncc                 K  s"   t t| j|fd|i| dS )zRun the FastMCP server. Note this is a synchronous function.

        Args:
            transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
        r   N)anyiorunr   r   r   rZ   rZ   r[   r     s   zFastMCP.runc                 C  sz   | j  | j | j  | j | j  | j | j  | j | j j	| j
d| j | j  | j | j  | j dS )z"Set up core MCP protocol handlers.)validate_inputN)r   
list_tools_list_tools_mcplist_resources_list_resources_mcplist_resource_templates_list_resource_templates_mcplist_prompts_list_prompts_mcp	call_toolr|   _call_tool_mcpread_resource_read_resource_mcp
get_prompt_get_prompt_mcpr   rZ   rZ   r[   r     s   zFastMCP._setup_handlerscontextMiddlewareContext[Any]	call_next2Callable[[MiddlewareContext[Any]], Awaitable[Any]]c                   s0   |}t | jD ]}t||d}q||I dH S )z)Builds and executes the middleware chain.)r   N)reversedrn   r   )r   r   r   chainmwrZ   rZ   r[   _apply_middleware  s
   zFastMCP._apply_middlewarer$   c                 C  s   | j | d S r   )rn   append)r   rn   rZ   rZ   r[   add_middleware  s   zFastMCP.add_middlewaredict[str, Tool]c                      t | j I dH }| jD ]N}z(|j I dH }| D ]\}}|jr,|j d| n|}|j|d||< qW q ty\ } zt	
d|jjd|  tjjrR W Y d}~qd}~ww |S )zFGet all tools (unfiltered), including mounted servers, indexed by key.N_keyz(Failed to get tools from mounted server : )dictr   	get_toolsr   rW   itemsprefix
model_copy	Exceptionloggerwarningr   r   r   &mounted_components_raise_on_load_error)r   	all_toolsmountedchild_toolsr   r   new_keyerZ   rZ   r[   r    &   
zFastMCP.get_toolsr   r"   c                   .   |   I d H }||vrtd| || S )NUnknown tool: )r  r*   )r   r   rs   rZ   rZ   r[   get_tool  
   zFastMCP.get_tooldict[str, Resource]c           	           t | j I dH }| jD ]b}z<|j I dH }| D ]-\}}|jr,t||j|jn|}|jr?|j	r?d|j d|j	 ini }|j
||d||< qW q typ } ztd|jj	d|  tjjrf W Y d}~qd}~ww |S )zJGet all resources (unfiltered), including mounted servers, indexed by key.Nr   r   r   updatez,Failed to get resources from mounted server r  )r  r   get_resourcesr   rW   r  r  add_resource_prefixrq   r   r  r  r  r	  r   r   r
  )	r   all_resourcesr  child_resourcesr   resourcer  r  r  rZ   rZ   r[   r    @   

	zFastMCP.get_resourcesr    c                   r  )NUnknown resource: )r  r*   )r   r   	resourcesrZ   rZ   r[   get_resource  r  zFastMCP.get_resourcedict[str, ResourceTemplate]c           	        r  )zSGet all resource templates (unfiltered), including mounted servers, indexed by key.Nr   r   r  z5Failed to get resource templates from mounted server r  )r  r   get_resource_templatesr   rW   r  r  r  rq   r   r  r  r  r	  r   r   r
  )	r   all_templatesr  child_templatesr   templater  r  r  rZ   rZ   r[   r#  %  r  zFastMCP.get_resource_templatesr!   c                   s.   |   I dH }||vrtd| || S )z*Get a registered resource template by key.NzUnknown resource template: )r#  r*   )r   r   	templatesrZ   rZ   r[   get_resource_templateF  s
   zFastMCP.get_resource_templatedict[str, Prompt]c                   r   )zHGet all prompts (unfiltered), including mounted servers, indexed by key.Nr   r   z*Failed to get prompts from mounted server r  )r  r   get_promptsr   rW   r  r  r  r  r  r	  r   r   r   r
  )r   all_promptsr  child_promptsr   promptr  r  rZ   rZ   r[   r*  M  r  zFastMCP.get_promptsr   c                   r  )NUnknown prompt: )r*  r*   )r   r   promptsrZ   rZ   r[   r   a  r  zFastMCP.get_promptpathmethods	list[str]include_in_schema^Callable[[Callable[[Request], Awaitable[Response]]], Callable[[Request], Awaitable[Response]]]c                   s   d fd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]]rX   c              	     s   j t|  d | S )N)endpointr1  r   r3  )r   r   r(   )r5  r3  r1  r   r0  r   rZ   r[   	decorator  s   	z'FastMCP.custom_route.<locals>.decoratorN)r5  r6  rX   r6  rZ   )r   r0  r1  r   r3  r9  rZ   r8  r[   custom_routeg  s   "zFastMCP.custom_routelist[BaseRoute]c                 C  s.   t | j}| jD ]}|j }|| q|S )zGet all additional HTTP routes including from mounted servers.

        Returns a list of all custom HTTP routes from this server and
        recursively from all mounted servers.

        Returns:
            List of Starlette BaseRoute objects
        )r   r   r   rW   _get_additional_http_routesextend)r   routesmounted_servermounted_routesrZ   rZ   r[   r<    s
   
	

z#FastMCP._get_additional_http_routeslist[MCPTool]c              	     ~   t d j d tjjj d4 I dH    I dH } fdd|D W  d  I dH  S 1 I dH s8w   Y  dS )zg
        List all available tools, in the format expected by the low-level MCP
        server.
        [z] Handler called: list_toolsr   Nc                      g | ]}|j |j jd qS )r   rx   )to_mcp_toolr   rx   .0r   r   rZ   r[   
<listcomp>      z+FastMCP._list_tools_mcp.<locals>.<listcomp>)r  r~   r   r   rW   r   Context_list_tools_middleware)r   rs   rZ   r   r[   r        
0zFastMCP._list_tools_mcp
list[Tool]c              	        t jjj| d4 I dH &}ttjjddddd|d}t| j	|| j
dI dH W  d  I dH  S 1 I dH s9w   Y  dS )	zD
        List all available tools, applying MCP middleware.
        rD  Nz
tools/listmethodclientrequestmessagesourcer   rR  fastmcp_contextr   r   )r   rW   r   rL  r4   mcptypesListToolsRequestr   r   _list_toolsr   fastmcp_ctx
mw_contextrZ   rZ   r[   rM    s   	
0zFastMCP._list_tools_middleware-MiddlewareContext[mcp.types.ListToolsRequest]c                      j  I dH } fdd| D }dd |D } jD ]^}z.|j I dH }|D ]!} |s3q+|j}|jrH|j d|j }|j	|d}|||< q+W q t
y| }	 z"tt|ddd	t|}
td
|
d|	  tjjrr W Y d}	~	qd}	~	ww t| S )z+
        List all available tools.
        Nc                      g | ]	}  |r|qS rZ   _should_enable_componentrH  r   rZ   r[   rJ    s
    
z'FastMCP._list_tools.<locals>.<listcomp>c                 S     i | ]}|j |qS rZ   r   rH  rZ   rZ   r[   
<dictcomp>  s    z'FastMCP._list_tools.<locals>.<dictcomp>r   r   rW   r   z)Failed to list tools from mounted server r  )r   r  valuesr   rW   rM  re  r   r  r  r  getattrreprr  r	  r   r   r
  r   )r   r   local_toolsfiltered_localr  r  r  r   r   r  server_namerZ   r   r[   r]    s>   



zFastMCP._list_toolslist[MCPResource]c              	     rB  )zk
        List all available resources, in the format expected by the low-level MCP
        server.
        rC  z ] Handler called: list_resourcesrD  Nc                   rE  ))urirx   )to_mcp_resourcer   rx   rI  r  r   rZ   r[   rJ    rK  z/FastMCP._list_resources_mcp.<locals>.<listcomp>)r  r~   r   r   rW   r   rL  _list_resources_middleware)r   r   rZ   r   r[   r     rN  zFastMCP._list_resources_mcplist[Resource]c              	     v   t jjj| d4 I dH !}ti ddd|d}t| j|| jdI dH W  d  I dH  S 1 I dH s4w   Y  dS )zH
        List all available resources, applying MCP middleware.
        rD  NrS  rT  zresources/listrU  rY  )r   rW   r   rL  r4   r   r   _list_resourcesr^  rZ   rZ   r[   rr    s   	
0z"FastMCP._list_resources_middleware!MiddlewareContext[dict[str, Any]]c                      j  I dH } fdd| D }dd |D } jD ]h}z8|j I dH }|D ]+} |s3q+|j}|jrRt	|j|j|j
}|j|d|j d|j id}|||< q+W q ty }	 z"tt|d	ddt|}
td
|
d|	  tjjr| W Y d}	~	qd}	~	ww t| S )z/
        List all available resources.
        Nc                   rc  rZ   rd  rq  r   rZ   r[   rJ  /      z+FastMCP._list_resources.<locals>.<listcomp>c                 S  rf  rZ   r   rq  rZ   rZ   r[   rg  8      z+FastMCP._list_resources.<locals>.<dictcomp>r   r   r  rW   zFailed to list resources from r  )r   r  rh  r   rW   rr  re  r   r  r  rq   r  r   r  ri  rj  r  r	  r   r   r
  r   )r   r   local_resourcesrl  r  r  r  r  r   r  rm  rZ   r   r[   ru  &  sL   
	


	zFastMCP._list_resourceslist[MCPResourceTemplate]c              	     rB  )zt
        List all available resource templates, in the format expected by the low-level MCP
        server.
        rC  z)] Handler called: list_resource_templatesrD  Nc                   rE  ))uriTemplaterx   )to_mcp_templater   rx   rI  r&  r   rZ   r[   rJ  e  rK  z8FastMCP._list_resource_templates_mcp.<locals>.<listcomp>)r  r~   r   r   rW   r   rL  #_list_resource_templates_middleware)r   r'  rZ   r   r[   r   \  rN  z$FastMCP._list_resource_templates_mcplist[ResourceTemplate]c              	     rt  )zR
        List all available resource templates, applying MCP middleware.

        rD  NrS  rT  zresources/templates/listrU  rY  )r   rW   r   rL  r4   r   r   _list_resource_templatesr^  rZ   rZ   r[   r  m  s   	
0z+FastMCP._list_resource_templates_middlewarec                   rw  )z8
        List all available resource templates.
        Nc                   rc  rZ   rd  r~  r   rZ   r[   rJ    rx  z4FastMCP._list_resource_templates.<locals>.<listcomp>c                 S  rf  rZ   r   r~  rZ   rZ   r[   rg    ry  z4FastMCP._list_resource_templates.<locals>.<dictcomp>r   r   r  rW   z'Failed to list resource templates from r  )r   r#  rh  r   rW   r  re  r   r  r  rq   r  r   r  ri  rj  r  r	  r   r   r
  r   )r   r   local_templatesrl  r$  r  r%  r&  r   r  rm  rZ   r   r[   r    sR   
	


z FastMCP._list_resource_templateslist[MCPPrompt]c              	     rB  )zi
        List all available prompts, in the format expected by the low-level MCP
        server.
        rC  z] Handler called: list_promptsrD  Nc                   rE  rF  )to_mcp_promptr   rx   rI  r-  r   rZ   r[   rJ    rK  z-FastMCP._list_prompts_mcp.<locals>.<listcomp>)r  r~   r   r   rW   r   rL  _list_prompts_middleware)r   r/  rZ   r   r[   r     rN  zFastMCP._list_prompts_mcplist[Prompt]c              	     rP  )	zG
        List all available prompts, applying MCP middleware.

        rD  Nzprompts/listrQ  rS  rT  rU  rY  )r   rW   r   rL  r4   rZ  r[  ListPromptsRequestr   r   _list_promptsr^  rZ   rZ   r[   r    s   	
0z FastMCP._list_prompts_middleware/MiddlewareContext[mcp.types.ListPromptsRequest]c                   rb  )z-
        List all available prompts.
        Nc                   rc  rZ   rd  r  r   rZ   r[   rJ    rx  z)FastMCP._list_prompts.<locals>.<listcomp>c                 S  rf  rZ   r   r  rZ   rZ   r[   rg    ry  z)FastMCP._list_prompts.<locals>.<dictcomp>r   r   rW   r   z+Failed to list prompts from mounted server r  )r   r*  rh  r   rW   r  re  r   r  r  r  ri  rj  r  r	  r   r   r
  r   )r   r   local_promptsrl  r+  r  r,  r-  r   r  rm  rZ   r   r[   r    sB   
	


zFastMCP._list_prompts	argumentsdict[str, Any]Ylist[ContentBlock] | tuple[list[ContentBlock], dict[str, Any]] | mcp.types.CallToolResultc                   s   t d| j d|| tjjj| d4 I dH A z| ||I dH }| W W  d  I dH  S  t	yF } zt
d| |d}~w t
yY } zt
d| |d}~ww 1 I dH s`w   Y  dS )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
        rC  z&] Handler called: call_tool %s with %srD  Nr  )r  r~   r   r   rW   r   rL  _call_tool_middlewareto_mcp_resultr)   r*   )r   r   r  resultr  rZ   rZ   r[   r     s"   zFastMCP._call_tool_mcpr7   c                   sB   t t tjj||ddddtjj d}| j|| j	dI dH S )b
        Applies this server's middleware and delegates the filtered call to the manager.
        r   r  rS  rT  z
tools/callrU  rY  N)
r4   r   rZ  r[  r   rW   rp   get_contextr   
_call_tool)r   r   r  r`  rZ   rZ   r[   r  7  s   	
zFastMCP._call_tool_middleware2MiddlewareContext[mcp.types.CallToolRequestParams]c              	     s  |j j}t| jD ]G}|}|jr&||j dsq
|t|jd d }z"|jj	|I dH }| 
|s8W q
|j||j jpAi I dH W   S  tyQ   Y q
w z | j	|I dH }| 
|rq| jj||j jpji dI dH W S W n	 ty{   Y nw td|)z
        Call a tool
        r      N)r   r  r  )rV  r   r   r   r  
startswithlenrW   r   r  re  r  r  r*   r   )r   r   	tool_namer  try_namer   rZ   rZ   r[   r  K  s:   

zFastMCP._call_toolro  AnyUrl | strlist[ReadResourceContents]c                   s   t d| j d| tjjj| d4 I dH D ztt | 	|I dH W W  d  I dH  S  t
yF } z
tdt||d}~w ty[ } z
tdt||d}~ww 1 I dH sbw   Y  dS )z
        Handle MCP 'readResource' requests.

        Delegates to _read_resource, which should be overridden by FastMCP subclasses.
        rC  z"] Handler called: read_resource %srD  Nr  )r  r~   r   r   rW   r   rL  r   r   _read_resource_middlewarer)   r*   r   )r   ro  r  rZ   rZ   r[   r   u  s    zFastMCP._read_resource_mcpc                   sV   t |tr
t|n|}ttjj|ddddtjj	
 d}t| j|| jdI dH S )r  )ro  rS  rT  zresources/readrU  rY  N)r   r   r#   r4   rZ  r[  ReadResourceRequestParamsr   rW   rp   r  r   r   _read_resource)r   ro  	uri_paramr`  rZ   rZ   r[   r    s   	

z!FastMCP._read_resource_middleware6MiddlewareContext[mcp.types.ReadResourceRequestParams]c              	     s  t |jj}t| jD ]B}|}|jr$t||j|jsqt||j|j}z!|j	j
|I dH }| |s6W qt|j	|I dH }|W   S  tyN   Y qw z"| j
|I dH }| |rp| j
|I dH }t||jdgW S W n	 tyz   Y nw td|)z!
        Read a resource
        N)content	mime_typer  )r   rV  ro  r   r   r  has_resource_prefixrq   remove_resource_prefixrW   r   r!  re  r   r  r*   r   r   r  )r   r   uri_strr  r   r  r  r  rZ   rZ   r[   r    sF   




zFastMCP._read_resourcedict[str, Any] | Noner   c                   s   ddl }td| j d|| |jjj| d4 I dH = z| ||I dH W W  d  I dH  S  tyF } zt	d| |d}~w t	yY } zt	d| |d}~ww 1 I dH s`w   Y  dS )z
        Handle MCP 'getPrompt' requests.

        Delegates to _get_prompt, which should be overridden by FastMCP subclasses.
        r   NrC  z'] Handler called: get_prompt %s with %srD  r.  )
fastmcp.server.contextr  r~   r   rW   r   rL  _get_prompt_middlewarer)   r*   )r   r   r  r   r  rZ   rZ   r[   r     s"   zFastMCP._get_prompt_mcpc                   s>   t tjj||ddddtjj d}| j|| j	dI dH S )r  r  rS  rT  zprompts/getrU  rY  N)
r4   rZ  r[  GetPromptRequestParamsr   rW   rp   r  r   _get_prompt)r   r   r  r`  rZ   rZ   r[   r    s   
zFastMCP._get_prompt_middleware3MiddlewareContext[mcp.types.GetPromptRequestParams]c              	     s   |j j}t| jD ]E}|}|jr&||j dsq
|t|jd d  }z |jj	|I d H }| 
|s8W q
|j||j jI d H W   S  tyO   Y q
w z| j	|I d H }| 
|rm| jj||j jdI d H W S W n	 tyw   Y nw td|)Nr   r  r  r.  )rV  r   r   r   r  r  r  rW   r   r   re  r  r  r*   render_prompt)r   r   r   r  r  r-  rZ   rZ   r[   r    s:   

zFastMCP._get_promptr   c                 C  B   | j | zddlm} | }|  W |S  ty    Y |S w )aX  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

        Returns:
            The tool instance that was added to the server.
        r   r  )r   r   fastmcp.server.dependenciesr  _queue_tool_list_changedrd   )r   r   r  r   rZ   rZ   r[   r   !  s   
zFastMCP.add_toolc                 C  sB   | j | zddlm} | }|  W dS  ty    Y dS w )zRemove a tool from the server.

        Args:
            name: The name of the tool to remove

        Raises:
            NotFoundError: If the tool is not found
        r   r  N)r   remove_toolr  r  r  rd   )r   r   r  r   rZ   rZ   r[   r  :  s   	zFastMCP.remove_toolr  transformationr9   c                 C  s   | j || dS )zAdd a tool transformation.N)r   add_tool_transformation)r   r  r  rZ   rZ   r[   r  N  s   zFastMCP.add_tool_transformationc                 C  s   | j | dS )zRemove a tool transformation.N)r   remove_tool_transformation)r   r  rZ   rZ   r[   r  T  s   z"FastMCP.remove_tool_transformation
r   titledescriptionrl   tagsoutput_schemar   exclude_argsmetaenabled
name_or_fnr   r  r  r  set[str] | Noner  dict[str, Any] | NotSetT | Noner   'ToolAnnotations | dict[str, Any] | Noner  r  r  r6   c       
         C     d S r   rZ   r   r  r   r  r  rl   r  r  r   r  r  r  rZ   rZ   r[   r   X     zFastMCP.tool%Callable[[AnyFunction], FunctionTool]c       
         C  r  r   rZ   r  rZ   rZ   r[   r   i  r  str | AnyFunction | None4Callable[[AnyFunction], FunctionTool] | FunctionToolc       
         C  s   t |trtd	i |}t |trttdt|r:|}|}tj	|||||||||	|
| j
|d}| | |S t |trQ|durNtd| d| d|}n|du rX|}n	tdt| t| j||||||||	|
|d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
            output_schema: Optional JSON schema for the tool's output
            annotations: Optional annotations about the tool's behavior
            exclude_args: Optional list of argument names to exclude from the tool schema
            meta: Optional meta information about the tool
            enabled: Optional boolean to enable or disable the tool

        Examples:
            Register a tool with a custom name:
            ```python
            @server.tool
            def my_tool(x: int) -> str:
                return str(x)

            # Register a tool with a custom name
            @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  rl   r  r  r   r  r  r   r  NzXCannot 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  rZ   )r   r  r   classmethodr   inspectcleandoc	isroutiner"   r   r   r   r   	TypeErrorr   r   r   )r   r  r   r  r  rl   r  r  r   r  r  r  r5  r  r   rZ   rZ   r[   r   z  sn   
?



r  c                 C  r  )zAdd a resource to the server.

        Args:
            resource: A Resource instance to add

        Returns:
            The resource instance that was added to the server.
        r   r  )r   add_resourcer  r  _queue_resource_list_changedrd   )r   r  r  r   rZ   rZ   r[   r        	
zFastMCP.add_resourcer&  c                 C  r  )zAdd a resource template to the server.

        Args:
            template: A ResourceTemplate instance to add

        Returns:
            The template instance that was added to the server.
        r   r  )r   add_templater  r  r  rd   )r   r&  r  r   rZ   rZ   r[   r    r  zFastMCP.add_templater5  r  c                 C  s4   t jjrtjdtdd | jj||||||d dS )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   )r5  ro  r   r  r  r  N)r   r   r   r   rN   r   r    add_resource_or_template_from_fn)r   r5  ro  r   r  r  r  rZ   rZ   r[   add_resource_fn,  s   
zFastMCP.add_resource_fn)	r   r  r  rl   r  r  r  r   r  #Annotations | dict[str, Any] | None4Callable[[AnyFunction], Resource | ResourceTemplate]c       	           sP   t  trtd	i   t
rtdd
 	
fd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
            annotations: Optional annotations about the resource's behavior
            meta: Optional meta information about the resource

        Examples:
            Register a resource with a custom name:
            ```python
            @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")
            async def get_weather_with_context(city: str, ctx: Context) -> str:
                await 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 @resourcer5  r   rX   Resource | ResourceTemplatec                   s   ddl m  t| trttddv odv }t fddt| j	
 D }|s/|rFtj| 
	d}| |S |sa|satj| 
	d	}| |S td
)Nr   rL  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  s    | ]
}|j  ur|V  qd S r   )
annotation)rI  pr  rZ   r[   	<genexpr>  s    
z6FastMCP.resource.<locals>.decorator.<locals>.<genexpr>)r5  uri_templater   r  r  rl   r  r  r  r   r  )r5  ro  r   r  r  rl   r  r  r  r   r  ziInvalid resource or template definition due to a mismatch between URI parameters and function parameters.)r  rL  r   r  r   r  r  any	signature
parametersrh  r!   r   r  r    r  )r5  has_uri_paramshas_func_paramsr&  r  r   r  r  rl   r  r  r   r   r  r  ro  r  r[   r9    s\   


z#FastMCP.resource.<locals>.decoratorNrZ   )r5  r   rX   r  )r   r  r   r  r  r  )r   ro  r   r  r  rl   r  r  r  r   r  r9  rZ   r  r[   r  R  s   
B
">zFastMCP.resourcer-  c                 C  r  )zAdd a prompt to the server.

        Args:
            prompt: A Prompt instance to add

        Returns:
            The prompt instance that was added to the server.
        r   r  )r   
add_promptr  r  _queue_prompt_list_changedrd   )r   r-  r  r   rZ   rZ   r[   r    r  zFastMCP.add_promptr   r  r  rl   r  r  r  r,   c          	      C  r  r   rZ   	r   r  r   r  r  rl   r  r  r  rZ   rZ   r[   r-       zFastMCP.prompt'Callable[[AnyFunction], FunctionPrompt]c          	      C  r  r   rZ   r  rZ   rZ   r[   r-    r  8Callable[[AnyFunction], FunctionPrompt] | FunctionPromptc             
   C  s   t |trttdt|r)|}	|}
tj|	|
||||||d}| | |S t |t	r@|dur=t
d| d| d|}
n|du rG|}
n	t
dt| t| j|
||||||dS )	a
  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
            meta: Optional meta information about the prompt

        Examples:

            ```python
            @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()
            async def analyze_with_context(table_name: str, ctx: Context) -> list[Message]:
                await 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")
            async 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.
                    )r5  r   r  r  rl   r  r  r  NzZCannot specify both a name as first argument and as keyword argument. Use either @prompt('z') or @prompt(name='r  zCFirst argument to @prompt must be a function, string, or None, got r  )r   r  r   r  r  r  r   r   r  r   r  r   r   r-  )r   r  r   r  r  rl   r  r  r  r5  prompt_namer-  rZ   rZ   r[   r-    s\   
R



c                   s  |r	t | dd t|j |  4 I dH F t 4 I dH )\}}td| jd | j||| j	t
ddI dH  W d  I dH  n1 I dH sMw   Y  W d  I dH  n1 I dH sbw   Y  W d   dS W d   dS 1 szw   Y  dS )zRun the server using stdio transport.

        Args:
            show_banner: Whether to display the server banner
            log_level: Log level for the server
        rR   )rW   r   NStarting MCP server z with transport 'stdio'T)tools_changed)r:   r=   r   r   r  infor   r   r   create_initialization_optionsr   )r   r   r}   read_streamwrite_streamrZ   rZ   r[   r     s0   

**"zFastMCP.run_stdio_asyncrS   )Literal['http', 'streamable-http', 'sse']uvicorn_configlist[ASGIMiddleware] | Nonec                   s  |p| j j}|p| j j}|p| j j }| j||||	|
d}t|dr1t|jdr1|jj	dn|p4d}|r@t
| ||||d |pCi }ddd	d
}|| d|vr[d|vr[||d< t|c |  4 I dH ? tj|f||d|}t|}|jj	d}td| jd|d| d| d| 
 | I dH  W d  I dH  n1 I dH sw   Y  W d   dS W d   dS 1 sw   Y  dS )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
            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)
        )r0  r   rn   r   r   stater0  / )rW   r   r   r   r0  r   onzwebsockets-sansio)timeout_graceful_shutdownro   ws
log_configr}   N)r   r   r  z with transport z on http://:)r   r   r   r}   lowerhttp_apphasattrr  r0  lstripr:   r  r=   r   uvicornConfigServerr  r  r   serve)r   r   r   r   r   r}   r0  r  rn   r   r   default_log_level_to_useappserver_pathuvicorn_config_from_userconfig_kwargsconfigrW   rZ   rZ   r[   r     s`   




"*"zFastMCP.run_http_asyncc                   s:   t jjrtjdtdd | jd|||||dI dH  dS )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   rT   r   r   r   r}   r0  r  Nr   r   r   r   rN   r   r   r   r   r   r}   r0  r  rZ   rZ   r[   run_sse_async  s   zFastMCP.run_sse_asyncr0   c                 C  sB   t jjrtjdtdd t| |p| jj|p| jj	| j
| jj|d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   rW   r   r   rm   r~   rn   )r   r   r   r   rN   r   r1   r   r   r   rm   r~   )r   r0  r   rn   rZ   rZ   r[   sse_app)  s   

zFastMCP.sse_appc                 C  s&   t jjrtjdtdd | j||d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   )r0  rn   )r   r   r   r   rN   r   r  )r   r0  rn   rZ   rZ   r[   streamable_http_appH  s   zFastMCP.streamable_http_appc              
   C  s   |dv r't | |p| jjd| j|dur|n| jj|dur|n| jj| jj|dS |dkr>t| | jj|p5| jj	| j| jj|dS dS )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
        )rU   rS   N)rW   r   event_storerm   r   r   r~   rn   rT   r  )
r2   r   r   rm   r   r   r~   r1   r   r   )r   r0  rn   r   r   r   rZ   rZ   r[   r  ]  s4   
zFastMCP.http_appc                   s:   t jjrtjdtdd | jd|||||dI d H  d S )Nz]The run_streamable_http_async method is deprecated (as of 2.3.2). Use run_http_async instead.r   r   rS   r  r  r  rZ   rZ   r[   run_streamable_http_async  s   	z!FastMCP.run_streamable_http_async)tool_separatorresource_separatorprompt_separatorrW   rV   r  as_proxyr  r  r  c          	      C  s   ddl m} t|tr!tjjrtjdt	dd t
tt ||}}|dur1tjjr1tjdt	dd |durAtjjrAtjdt	dd |durQtjjrQtjd	t	dd |du rZ|jtk}|rft||sft|}t||| jd
}| j| dS )a  Mount another FastMCP server on this server with an optional 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 with a prefix:
        - 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".

        When a server is mounted without a prefix (prefix=None), its tools, resources, templates,
        and prompts are accessible with their original names. Multiple servers can be mounted
        without prefixes, and they will be tried in order until a match is found.

        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:
            server: The FastMCP server to mount.
            prefix: Optional prefix to use for the mounted server's objects. If None,
                the server's objects are accessible with their original names.
            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   rJ   ziMount prefixes are now optional and the first positional argument should be the server you want to mount.r   r   NThe tool_separator parameter is deprecated and will be removed in a future version. Tools are now prefixed using 'prefix_toolname' format.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  rW   rq   )fastmcp.server.proxyrK   r   r   r   r   r   r   rN   r   r   ri   r   rb   r\   r  MountedServerrq   r   r   )	r   rW   r  r  r  r  r  rK   r?  rZ   rZ   r[   mount  sP   9
	

zFastMCP.mountc              	     s:  t |trtjjrtjdtdd tt	t
 ||}}|dur,tjjr,tjdtdd |dur<tjjr<tjdtdd |durLtjjrLtjdtdd | I dH  D ]\}}|rf|j| d| d	}| j| qU| I dH  D ]"\}}|rt||| j}	|jd
| d|j i|	d}| j| qv| I dH  D ]"\}}
|rt||| j}|
jd
| d|
j i|d}
| j|
 q| I dH  D ]\}}|r|j| d| d	}| j| q|jtkrddlm} |dtdd |rtd| j d|j d| d dS td| j d|j  dS )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 with a prefix:
        - 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"

        When a server is imported without a prefix (prefix=None), its tools, resources,
        templates, and prompts are imported with their original names.

        Args:
            server: The FastMCP server to import
            prefix: Optional prefix to use for the imported server's objects. If None,
                objects are imported with their original names.
            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.
        zkImport prefixes are now optional and the first positional argument should be the server you want to import.r   r   Nr  r  r  r   r   r   )r  r   r   )rN   zeWhen importing from a server with a lifespan, the lifespan from the imported server will not be used.)rV  categoryr   rC  z] Imported server z with prefix '') r   r   r   r   r   r   rN   r   r   ri   r   r  r  r  r   r   r  r  rq   r   r   r  r#  r  r*  r   r  rb   r\   RuntimeWarningr  r~   )r   rW   r  r  r  r  r   r   r  resource_keyr&  template_keyr-  rN   rZ   rZ   r[   import_server	  s   
0
zFastMCP.import_serveropenapi_specrS  httpx.AsyncClient
route_maps)list[RouteMap] | list[RouteMapNew] | Noneroute_map_fn/OpenAPIRouteMapFn | OpenAPIRouteMapFnNew | Nonemcp_component_fn1OpenAPIComponentFn | OpenAPIComponentFnNew | None	mcp_namesdict[str, str] | Noner   "FastMCPOpenAPI | FastMCPOpenAPINewc           
   
   K  s   t jjjr#ddlm}	 |	d||tt|tt|tt|||d|S t	d ddl
m}	 |	d||tt|tt|tt|||d|S )zH
        Create a FastMCP server from an OpenAPI specification.
        r   rE   )r%  rS  r'  r)  r+  r-  r  Using legacy OpenAPI parser. To use the new parser, set FASTMCP_EXPERIMENTAL_ENABLE_NEW_OPENAPI_PARSER=true. The new parser was introduced for testing in 2.11 and will become the default soon.r  NrZ   )r   r   experimentalenable_new_openapi_parser#fastmcp.experimental.server.openapirF   r   r   r  r  openapi)
clsr%  rS  r'  r)  r+  r-  r  r   rF   rZ   rZ   r[   from_openapi	  s8   
zFastMCP.from_openapir  httpx_client_kwargsc	                 K  s   |du ri }| dd tjddtj|di|}
|p|j}tjjjrEddl	m
} |d| |
|tt|tt|tt|||d|	S td	 d
dlm
} |d| |
|tt|tt|tt|||d|	S )zE
        Create a FastMCP server from a FastAPI application.
        Nbase_urlzhttp://fastapir   )r  r   rE   )r%  rS  r   r'  r)  r+  r-  r  r0  r  rZ   )
setdefaulthttpxAsyncClientASGITransportr  r   r   r1  r2  r3  rF   r4  r   r   r  r  )r5  r  r   r'  r)  r+  r-  r7  r  r   rS  rF   rZ   rZ   r[   from_fastapi	  sN   


		zFastMCP.from_fastapibackend}Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | strrK   c                   s   ddl m} ddlm}m} t||r4| r+tt}|	d fdd}|}nfdd}	|	}n||  fd	d
}
|
}|dd|i|S )aG  Create a FastMCP proxy server for the given backend.

        The `backend` argument can be either an existing `fastmcp.client.Client`
        instance or any value accepted as the `transport` argument of
        `fastmcp.client.Client`. This mirrors the convenience of the
        `fastmcp.client.Client` constructor.
        r   r@   )rK   ProxyClientzProxy detected connected client - reusing existing session for all requests. This may cause context mixing in concurrent scenarios.c                     s    S r   rZ   rZ   rS  rZ   r[   reuse_client_factory>
  s   z.FastMCP.as_proxy.<locals>.reuse_client_factoryc                           S r   newrZ   rA  rZ   r[   fresh_client_factoryD
     z.FastMCP.as_proxy.<locals>.fresh_client_factoryc                     rC  r   rD  rZ   )base_clientrZ   r[   proxy_client_factoryL
  rG  z.FastMCP.as_proxy.<locals>.proxy_client_factoryclient_factoryNrZ   )
fastmcp.client.clientrA   r  rK   r@  r   is_connectedr<   r   r  )r5  r>  r   rA   rK   r@  proxy_loggerrB  rJ  rF  rI  rZ   )rH  rS  r[   r  
  s"   
zFastMCP.as_proxyClient[ClientTransportT]c                 K  s*   t jjrtjdtd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   r   r   r   rN   r   r  )r5  rS  r   rZ   rZ   r[   from_clientS
  s   zFastMCP.from_client	componentr;   c                   sr    j sdS | jdu r| jdu rdS | jdur$t fdd| jD r$dS | jdur7tt fdd| jD S dS )a  
        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.
        FNTc                 3      | ]}| j v V  qd S r   r  )rI  etagrP  rZ   r[   r  |
      z3FastMCP._should_enable_component.<locals>.<genexpr>c                 3  rQ  r   rR  )rI  itagrT  rZ   r[   r  
  rU  )r  rv   rw   r  r   )r   rP  rZ   rT  r[   re  d
  s   

z FastMCP._should_enable_componentc                 C  s<   | j }|d u r| dtd S | d| dtd S )N-r   )r   secrets	token_hex)r5  r   
class_namerZ   rZ   r[   r   
  s   zFastMCP.generate_name)NN)@r   r   r   r   rj   r   rk   r   rl   r   rm   r   rn   r   ro   r   rp   r   rq   r   rr   r   rs   r   rt   r   ru   r   rv   r   rw   r   rx   r   ry   r   rz   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   )rX   r   )r}   r   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rX   r   )rX   r5   )rX   r   )r   r   rX   r   )rX   r   )rX   r   )NT)r   r   r   r   r   r   rX   r   )rX   r   )r   r   r   r   rX   r   )rn   r$   rX   r   )rX   r   )r   r   rX   r"   )rX   r  )r   r   rX   r    )rX   r"  )r   r   rX   r!   )rX   r)  )r   r   rX   r   )
r0  r   r1  r2  r   r   r3  r   rX   r4  )rX   r;  )rX   rA  )rX   rO  )r   ra  rX   rO  )rX   rn  )rX   rs  )r   rv  rX   rs  )rX   r{  )rX   r  )r   rv  rX   r  )rX   r  )rX   r  )r   r  rX   r  )r   r   r  r  rX   r  )r   r   r  r  rX   r7   )r   r  rX   r7   )ro  r  rX   r  )r   r  rX   r  r   )r   r   r  r  rX   r   )r   r  rX   r   )r   r"   rX   r"   )r   r   rX   r   )r  r   r  r9   rX   r   )r  r   rX   r   )r  r   r   r   r  r   r  r   rl   r   r  r  r  r  r   r  r  r   r  r  r  r   rX   r6   )r  r   r   r   r  r   r  r   rl   r   r  r  r  r  r   r  r  r   r  r  r  r   rX   r  )r  r  r   r   r  r   r  r   rl   r   r  r  r  r  r   r  r  r   r  r  r  r   rX   r  )r  r    rX   r    )r&  r!   rX   r!   )NNNN)r5  r   ro  r   r   r   r  r   r  r   r  r  rX   r   )ro  r   r   r   r  r   r  r   rl   r   r  r   r  r  r  r   r   r  r  r  rX   r  )r-  r   rX   r   )r  r   r   r   r  r   r  r   rl   r   r  r  r  r   r  r  rX   r,   )r  r   r   r   r  r   r  r   rl   r   r  r  r  r   r  r  rX   r  )r  r  r   r   r  r   r  r   rl   r   r  r  r  r   r  r  rX   r  )TN)r   r   r}   r   rX   r   )
TrS   NNNNNNNN)r   r   r   r  r   r   r   r   r}   r   r0  r   r  r  rn   r  r   r   r   r   rX   r   )NNNNN)r   r   r   r   r}   r   r0  r   r  r  rX   r   )NNN)r0  r   r   r   rn   r  rX   r0   )r0  r   rn   r  rX   r0   )NNNNrS   )r0  r   rn   r  r   r   r   r   r   r  rX   r0   )rW   rV   r  r   r  r   r  r   r  r   r  r   rX   r   )rW   rV   r  r   r  r   r  r   r  r   rX   r   )r%  r  rS  r&  r'  r(  r)  r*  r+  r,  r-  r.  r  r  r   r   rX   r/  )NNNNNNN)r  r   r   r   r'  r(  r)  r*  r+  r,  r-  r.  r7  r  r  r  r   r   rX   r/  )r>  r?  r   r   rX   rK   )rS  rN  r   r   rX   rK   )rP  r;   rX   r   )r   r   rX   r   )Qr   
__module____qualname__r>   r   r   r   propertyr   r   r   setterrj   rk   rl   r   r   r   r   r   r   r   r  r  r  r!  r#  r(  r*  r   r:  r<  r   rM  r]  r   rr  ru  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   r   r  r  r  r  r  r  r$  r  r6  r=  r  rO  re  r   rZ   rZ   rZ   r[   ri      s    '
 !!
2-6:1 *1& *   Q!3z 
0>; ri   c                   @  s*   e Zd ZU ded< ded< dZded< dS )r  r   r  zFastMCP[Any]rW   Nr   rq   )r   r[  r\  __annotations__rq   rZ   rZ   rZ   r[   r  
  s   
 r  ro  r   r  prefix_formatr   c                 C  s   |s| S |du rt jj}|dkr| d|  S |dkr9t| }|s*td|  d| \}}| | 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:
        With new style:
        ```python
        add_resource_prefix("resource://path/to/resource", "prefix")
        "resource://prefix/path/to/resource"
        ```
        With legacy style:
        ```python
        add_resource_prefix("resource://path/to/resource", "prefix")
        "prefix+resource://path/to/resource"
        ```
        With absolute path:
        ```python
        add_resource_prefix("resource:///absolute/path", "prefix")
        "resource://prefix//absolute/path"
        ```

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    Nprotocol+r0  Invalid URI format: ". Expected protocol://path format.r  Invalid prefix format: )r   r   rq   URI_PATTERNmatchr   groups)ro  r  r`  rg  ra  r0  rZ   rZ   r[   r  
  s    

r  c           	      C  s   |s| S |du rt jj}|dkr$| d}| |r"| t|d S | S |dkrYt| }|s7td|  d| \}}dt	
| d}t	||}|sP| S | |d	 S td
| )an  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:
        With new style:
        ```python
        remove_resource_prefix("resource://prefix/path/to/resource", "prefix")
        "resource://path/to/resource"
        ```
        With legacy style:
        ```python
        remove_resource_prefix("prefix+resource://path/to/resource", "prefix")
        "resource://path/to/resource"
        ```
        With absolute path:
        ```python
        remove_resource_prefix("resource://prefix//absolute/path", "prefix")
        "resource:///absolute/path"
        ```

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    Nra  rb  r0  rc  rd  ^z/(.*?)$r  re  )r   r   rq   r  r  rf  rg  r   rh  reescapegroup)	ro  r  r`  legacy_prefixrg  ra  r0  prefix_pattern
path_matchrZ   rZ   r[   r  
  s,    



r  r   c                 C  s   |sdS |du rt jj}|dkr| d}| |S |dkrDt| }|s-td|  d| \}}dt	| d	}t
t||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:
        With new style:
        ```python
        has_resource_prefix("resource://prefix/path/to/resource", "prefix")
        True
        ```
        With legacy style:
        ```python
        has_resource_prefix("prefix+resource://path/to/resource", "prefix")
        True
        ```
        With other path:
        ```python
        has_resource_prefix("resource://other/path/to/resource", "prefix")
        False
        ```

    Raises:
        ValueError: If the URI doesn't match the expected protocol://path format
    FNra  rb  r0  rc  rd  ri  r  re  )r   r   rq   r  rf  rg  r   rh  rj  rk  r   )ro  r  r`  rm  rg  r   r0  rn  rZ   rZ   r[   r    s"    



r  )rW   rV   rX   rY   )r]   rV   rX   r^   r   )ro  r   r  r   r`  r   rX   r   )ro  r   r  r   r`  r   rX   r   )__doc__
__future__r   r  r   rj  rX  r   collections.abcr   r   r   r   r   r   
contextlibr	   r
   r   dataclassesr   	functoolsr   pathlibr   typingr   r   r   r   r   r   r   r:  	mcp.typesrZ  r   mcp.server.lowlevel.helper_typesr   mcp.server.lowlevel.serverr   r   mcp.server.stdior   r   r   r   r   r   r   r   	MCPPromptr    MCPResourcer!   MCPResourceTemplater"   MCPToolpydanticr#   starlette.middlewarer$   ASGIMiddlewarestarlette.requestsr%   starlette.responsesr&   starlette.routingr'   r(   r   fastmcp.serverfastmcp.exceptionsr)   r*   fastmcp.mcp_configr+   fastmcp.promptsfastmcp.prompts.promptr,   fastmcp.prompts.prompt_managerr-   fastmcp.resources.resource"fastmcp.resources.resource_managerr.   fastmcp.resources.templatefastmcp.server.authr/   fastmcp.server.httpr0   r1   r2   fastmcp.server.low_levelr3   fastmcp.server.middlewarer4   fastmcp.settingsr5   fastmcp.tools.toolr6   r7   fastmcp.tools.tool_managerr8   fastmcp.tools.tool_transformr9   fastmcp.utilities.clir:   fastmcp.utilities.componentsr;   fastmcp.utilities.loggingr<   r=   fastmcp.utilities.typesr>   r?   fastmcp.clientrA   rK  rB   fastmcp.client.transportsrC   rD   r3  rF   FastMCPOpenAPINew+fastmcp.experimental.server.openapi.routingrG   OpenAPIComponentFnNewrH   RouteMapNewrI   OpenAPIRouteMapFnNewfastmcp.server.openapiOpenAPIComponentFnOpenAPIRouteMapFnr  rK   fastmcp.server.sampling.handlerrL   rM   r   r  DuplicateBehavior	Transportcompilerf  LifespanCallabler\   rh   ri   r  r  r  r  rZ   rZ   rZ   r[   <module>   s       

                    =D