
    iG             
         U 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
mZ ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZ ddlZddlZdd
l m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z) ddlm*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl.m0Z1 ddl2m3Z3 ddl4m5Z5 ddl6Z6ddl7Z6ddl8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m0Z0 ddl?m@Z@ ddlAmBZB ddlCmDZD ddlEmFZF ddlGmHZHmIZI ddlJmKZK ddlLmMZMmNZNmOZO ddlPmQZQmRZRmSZSmTZT ddlUmVZV ddlWmXZX ddlYmZZZm[Z[ dd l\m]Z]m^Z^m_Z_ dd!l`maZambZb dd"lcmdZd dd#lemfZfmgZg dd$lhmiZi dd%ljmkZkmlZl dd&lmmnZnmoZo dd'lpmqZr dd(lsmtZt dd)lumvZvmwZw dd*lxmyZy dd+lzm{Z{ dd,l|m}Z} dd-l~mZmZmZ dd.lmZ er2dd/lmZ dd0lmZ dd1lmZ dd2lmZmZ dd3lmZ dd4lmZ dd5lmZ dd6lmZ  e}e      Z ed7e
d8ef   9      Zed:   Zqi d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdNdPdNdQdRdSdTdUdVdWdXZdYedZ<   dgd[Zed\   Z ej8                  d]      Ze
d^gee'   f   Zdhd_Zedid`       Z	 	 	 	 djdaZ G db dce      Z G dd deede]e^e_ee'         Z	 	 	 	 	 	 dkdfZy)lz5FastMCP - A more ergonomic interface for MCP servers.    )annotationsN)AsyncIterator	AwaitableCallableSequence)AbstractAsyncContextManagerasynccontextmanager)replace)partial)Path)TYPE_CHECKINGAnyGenericLiteralTypeVarcastoverload)PydanticAdapter)AsyncKeyValue)MemoryStore)LifespanResultT)McpError)AnnotationsAnyFunctionCallToolRequestParamsToolAnnotations)AnyUrl)ValidationError)	BaseRoute)Self)AuthorizationErrorFastMCPErrorNotFoundErrorPromptErrorResourceError	ToolErrorr   )	MCPConfig)Prompt)FunctionPrompt)PromptResult)ResourceResourceResult)ResourceTemplate)	AppConfigapp_config_to_meta_dictresolve_ui_mime_type)	AuthCheckAuthContextAuthProviderrun_auth_checks)Lifespan)LowLevelServer)
MiddlewareMiddlewareContext)LifespanMixinMCPOperationsMixinTransportMixin)LocalProviderProvider)AggregateProvider)
TaskConfigTaskMeta)server_span)ToolTransform	Transform)apply_session_transforms
is_enabled)DuplicateBehavior)FunctionTool)Tool
ToolResult)ToolTransformConfig)FastMCPComponent)
get_logger)FastMCPBaseModelNotSetNotSetT)VersionSpec)Client)FastMCP1Server)SamplingHandler)ClientTransportClientTransportT)ComponentFn)RouteMap)
RouteMapFnFastMCPProxyF.)bound)warnerrorr
   ignorehostz7Pass `host` to `run_http_async()`, or set FASTMCP_HOST.portz7Pass `port` to `run_http_async()`, or set FASTMCP_PORT.sse_pathzKPass `path` to `run_http_async()` or `http_app()`, or set FASTMCP_SSE_PATH.message_pathzSet FASTMCP_MESSAGE_PATH.streamable_http_pathzWPass `path` to `run_http_async()` or `http_app()`, or set FASTMCP_STREAMABLE_HTTP_PATH.json_responsezYPass `json_response` to `run_http_async()` or `http_app()`, or set FASTMCP_JSON_RESPONSE.stateless_httpz[Pass `stateless_http` to `run_http_async()` or `http_app()`, or set FASTMCP_STATELESS_HTTP.debugzSet FASTMCP_DEBUG.	log_levelzAPass `log_level` to `run_http_async()`, or set FASTMCP_LOG_LEVEL.on_duplicate_toolszUse `on_duplicate=` instead.on_duplicate_resourceson_duplicate_promptstool_serializerzgReturn ToolResult from your tools instead. See https://gofastmcp.com/servers/tools#custom-serializationinclude_tagszCUse `server.enable(tags=..., only=True)` after creating the server.exclude_tagsz9Use `server.disable(tags=...)` after creating the server.tool_transformationszIUse `server.add_transform(ToolTransform(...))` after creating the server.zdict[str, str]_REMOVED_KWARGSc                    | D ]"  }|t         v st        d| dt         |           | r$t        ddj                  d | D                     y)z2Raise helpful TypeErrors for kwargs removed in v3.zFastMCP() no longer accepts `z`. z.FastMCP() got unexpected keyword argument(s): z, c              3  2   K   | ]  }t        |        y wN)repr).0ks     e/Users/bowang/.openclaw/workspace/ChatDev/.venv/lib/python3.12/site-packages/fastmcp/server/server.py	<genexpr>z(_check_removed_kwargs.<locals>.<genexpr>   s     F_X^STtAwX^s   N)rp   	TypeErrorjoin)kwargskeys     rw   _check_removed_kwargsr}   ~   si    /!/uC8L7MN  
 <TYYF_X^F_=_<`a
 	
     )stdiohttpssezstreamable-httpz^([^:]+://)(.*?)$FastMCP[LifespanResultT]c                 X    ddl m}  | j                         dk(  }|ryddlm} d |       fS )a@  Get auth context for the current request.

    Returns a tuple of (skip_auth, token) where:
    - skip_auth=True means auth checks should be skipped (STDIO transport)
    - token is the access token for HTTP transports (may be None if unauthenticated)

    Uses late import to avoid circular import with context.py.
    r   )_current_transportr   )TN)get_access_tokenF)fastmcp.server.contextr   getfastmcp.server.dependenciesr   )r   is_stdior   s      rw   _get_auth_contextr      s2     :!%%'72H<#%&&r~   c                  K   i  yw)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 )servers    rw   default_lifespanr      s      Hs   	c                .     t         	 	 	 	 d fd       }|S )Nc                  K   j                   t        u ri  y j                  st        d      j                   y w)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/PrefectHQ/fastmcp/issues.)	_lifespanr   _lifespan_result_setRuntimeError_lifespan_result)low_level_serverfastmcp_servers    rw   wrapz_lifespan_proxy.<locals>.wrap   sJ      ##'77H22^ 
 ---s   A A)r   zLowLevelServer[LifespanResultT]returnzAsyncIterator[LifespanResultT])r	   )r   r   s   ` rw   _lifespan_proxyr      s.    
 .9.	'. . Kr~   c                      e Zd ZU dZded<   y)
StateValuez(Wrapper for stored context state values.r   valueN)__name__
__module____qualname____doc____annotations__r   r~   rw   r   r      s
    2Jr~   r   c                  :    e Zd Z	 	 dCddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dD fdZdEdZedEd       ZedFd       Zej                  dGd       ZedFd	       Z	edFd
       Z
edHd       ZedId       Z	 	 	 	 	 	 dJdZdKdZdddL fdZdM fdZdNdZ	 	 	 	 	 	 dOdZdPdZdddQ fdZ	 dR	 	 	 	 	 dS fdZ	 dR	 	 	 	 	 dS fdZdd	 	 	 dT fdZ	 dR	 	 	 	 	 dU fdZ	 dR	 	 	 	 	 dU fdZdd	 	 	 dV fdZ	 dR	 	 	 	 	 dW fdZ	 dR	 	 	 	 	 dW fdZdddX fd Z	 dR	 	 	 	 	 dY fd!Z	 dR	 	 	 	 	 dY fd"Ze 	 dRdddd#	 	 	 	 	 	 	 	 	 	 	 dZd$       Z!e 	 dRddd%	 	 	 	 	 	 	 	 	 	 	 d[d&       Z!	 dRdddd#	 	 	 	 	 	 	 	 	 	 	 d\d'Z!e dddd#	 	 	 	 	 	 	 	 	 d]d(       Z"e ddd%	 	 	 	 	 	 	 	 	 d^d)       Z"dddd#	 	 	 	 	 	 	 	 	 d_d*Z"e 	 dRdddd#	 	 	 	 	 	 	 	 	 	 	 d`d+       Z#e 	 dRddd%	 	 	 	 	 	 	 	 	 	 	 d[d,       Z#	 dRdddd#	 	 	 	 	 	 	 	 	 	 	 dad-Z#dbd.Z$dRdcd/Z%e dddddde&dddddddd0	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ddd1       Z'e 	 dRdddddde&dddddddd0	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ded2       Z'	 dRdddddde&dddddddd0	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dfd3Z'	 	 	 	 dgd4Z(dhd5Z)ddddddddddddd6	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 did7Z*djd8Z+e dddddddddd9		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dkd:       Z,e 	 dRdddddddddd9		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dld;       Z,	 dRdddddddddd9		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dmd<Z,	 	 	 	 dn	 	 	 	 	 	 	 	 	 	 	 dod=Z-	 dR	 	 	 	 	 dpd>Z.e/	 	 	 	 	 	 	 	 dq	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 drd?       Z0e/	 	 	 	 	 	 	 ds	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dtd@       Z1e/	 	 	 	 	 	 dudA       Z2e/dRdvdB       Z3 xZ4S )wFastMCPNT)versionwebsite_urliconsauth
middleware	providers
transformslifespantoolson_duplicatemask_error_detailsdereference_schemasstrict_input_validationlist_page_sizetaskssession_state_storesampling_handlersampling_handler_behaviorc               J   t        |       t        | 	          |xs d| _        ||nd| _        d | _        d | _        g | _        |xs
 t               | _	        t        t           | j                  t        d      | _        t        | j                        | _        | j                  | j                         |xs g D ]  }| j                  |        |	xs g D ]  }| j!                  |        ||nt"        j$                  j&                  | _        ||dk  rt+        d      || _        |
t/        t0        t2           |
      | _        n t/        t0        t2           t6              | _        d | _        d| _        t=        j>                         | _         tC        t2           | |xs | jE                         |xs t"        jF                  |||tI        |       	      | _%        || _&        |r=|D ]8  }tO        |tP              stQ        jR                  |      }| jU                  |       : ||nt"        j$                  jV                  | _+        tY        |xs g       | _-        |r&dd
l.m/} | jZ                  ja                   |              | jc                          || _2        |xs d| _3        y )Nr]   Ffastmcp_state)	key_valuepydantic_modeldefault_collection)r   r   z)list_page_size must be a positive integer)r   )fastmcpnamer   instructionsr   r   r   )DereferenceRefsMiddlewarefallback)4r}   super__init___on_duplicate_support_tasks_by_default_docket_worker_additional_http_routesr   _state_storager   r   _state_storer<   _local_provideradd_provideradd_transformr   settingsr   _mask_error_details
ValueError_list_page_sizer   LifespanCallabler   r   r   r   r   asyncioEvent_startedr6   generate_name__version__r   _mcp_serverr   
isinstancerH   from_functionadd_toolr   listr   %fastmcp.server.middleware.dereferencer   append_setup_handlersr   r   )selfr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r{   pttoolr   	__class__s                             rw   r   zFastMCP.__init__   s   2 	f% 	7C7Mv 9>8Iuu& 8:$ .A-QKM9H9T))%.:
 /<++/
 	$../bAa  ! !r!Aq! " "- !!44 	  %.A*=HII+9 @D 18ADN ""2?"CEUVDN8<*/!'.}} BPB
 -++-2w22%#$D9
B
 *.	!$---d3Dd#  '2 $!!99 	$ -11Ar,B OO""#<#>? 	8H%3 	&r~   c                L    t        |       j                   d| j                  dS )N())typer   r   r   s    rw   __repr__zFastMCP.__repr__]  s$    t*%%&a		}A66r~   c                .    | j                   j                  S rs   )r   r   r   s    rw   r   zFastMCP.name`  s    $$$r~   c                .    | j                   j                  S rs   r   r   r   s    rw   r   zFastMCP.instructionsd  s    ,,,r~   c                &    || j                   _        y rs   r   )r   r   s     rw   r   zFastMCP.instructionsh  s    (-%r~   c                .    | j                   j                  S rs   )r   r   r   s    rw   r   zFastMCP.versionl  s    '''r~   c                .    | j                   j                  S rs   )r   r   r   s    rw   r   zFastMCP.website_urlp  s    +++r~   c                p    | j                   j                  g S t        | j                   j                        S rs   )r   r   r   r   s    rw   r   zFastMCP.iconst  s0    !!)I((..//r~   c                    | j                   S )a)  The server's local provider, which stores directly-registered components.

        Use this to remove components:

            mcp.local_provider.remove_tool("my_tool")
            mcp.local_provider.remove_resource("data://info")
            mcp.local_provider.remove_prompt("my_prompt")
        )r   r   s    rw   local_providerzFastMCP.local_provider{  s     ###r~   c                   K   |}t        | j                        D ]  }t        ||      }  ||       d{   S 7 w)z)Builds and executes the middleware chain.)	call_nextN)reversedr   r   )r   contextr   chainmws        rw   _run_middlewarezFastMCP._run_middleware  s<      4??+BB%0E ,7^###s   5><>c                :    | j                   j                  |       y rs   )r   r   )r   r   s     rw   add_middlewarezFastMCP.add_middleware  s    z*r~    	namespacec               (    t         |   ||       y)a\  Add a provider for dynamic tools, resources, and prompts.

        Providers are queried in registration order. The first provider to return
        a non-None result wins. Static components (registered via decorators)
        always take precedence over providers.

        Args:
            provider: A Provider instance that will provide components dynamically.
            namespace: Optional namespace prefix. When set:
                - Tools become "namespace_toolname"
                - Resources become "protocol://namespace/path"
                - Prompts become "namespace_promptname"
        r   N)r   r   )r   providerr   r   s      rw   r   zFastMCP.add_provider  s     	X;r~   c                  K   t        t        | 	          d{         }|D cg c]  }t        |t              s| }}|D cg c]  }t        |t
              s| }}|D cg c]  }t        |t              s| }}|D cg c]  }t        |t              s| }}| j                  D ]f  }|j                  |       d{   }|j                  |       d{   }|j                  |       d{   }|j                  |       d{   }h g ||||S 7 c c}w c c}w c c}w c c}w 7 r7 [7 D7 -w)zGet task-eligible components with all transforms applied.

        Overrides AggregateProvider.get_tasks() to apply server-level transforms
        after aggregation. AggregateProvider handles provider-level namespacing.
        N)r   r   	get_tasksr   rH   r+   r-   r(   r   
list_toolslist_resourceslist_resource_templateslist_prompts)	r   
componentscr   	resources	templatesprompts	transformr   s	           rw   r  zFastMCP.get_tasks  sC      1 334
 '>Jq*Q*=J> *F
1jH.EQ
	F *N
1j<L.MQ
	N(BjJq&,A1jB I#..u55E'66yAAI'??	JJI%227;;G	 )


 
 	
 	
 4 ?FNB 6AJ;s   ED"ED%D%ED*D*!E'D/=D/ED4D4!%ED9ED; E8D=9ED?E%E;E=E?Ec                :    | j                   j                  |       y)a  Add a server-level transform.

        Server-level transforms are applied after all providers are aggregated.
        They transform tools, resources, and prompts from ALL providers.

        Args:
            transform: The transform to add.

        Example:
            ```python
            from fastmcp.server.transforms import Namespace

            server = FastMCP("Server")
            server.add_transform(Namespace("api"))
            # All tools from all providers become "api_toolname"
            ```
        N)_transformsr   )r   r  s     rw   r   zFastMCP.add_transform  s    $ 		*r~   c                    t         j                  j                  rt        j                  dt
        d       | j                  t        ||i             y)z}Add a tool transformation.

        .. deprecated::
            Use ``add_transform(ToolTransform({...}))`` instead.
        zladd_tool_transformation is deprecated. Use server.add_transform(ToolTransform({tool_name: config})) instead.   
stacklevelN)r   r   deprecation_warningswarningsr]   DeprecationWarningr   rB   )r   	tool_nametransformations      rw   add_tool_transformationzFastMCP.add_tool_transformation  sE     00MMT"	 	=)^)DEFr~   c                r    t         j                  j                  rt        j                  dt
        d       yy)zRemove a tool transformation.

        .. deprecated::
            Tool transformations are now immutable. Use enable/disable controls instead.
        zremove_tool_transformation is deprecated and has no effect. Transforms are immutable once added. Use server.disable(keys=[...]) to hide tools instead.r  r  N)r   r   r  r  r]   r  )r   
_tool_names     rw   remove_tool_transformationz"FastMCP.remove_tool_transformation  s1     00MM) # 1r~   run_middlewarec               (   K   t         j                  j                  j                         4 d{   }|r]t	        t
        j                  j                  d      ddd|      } j                  | fd	       d{   cddd      d{    S t        t        
 -          d{         }t        |       d{   }|D cg c]  }t        |      s| }}t               \  }}g }|D ]O  }	|s:|	j                  .t!        ||	
      }	 t#        |	j                  |       d{   s>	 |j'                  |	       Q |cddd      d{    S 7 '7 7 7 7 c c}w 7 <# t$        $ r Y w xY w7 &# 1 d{  7  sw Y   yxY ww)a  List all enabled tools from providers.

        Overrides Provider.list_tools() to add visibility filtering, auth filtering,
        and middleware execution. Returns all versions (no deduplication).
        Protocol handlers deduplicate for MCP wire format.
        r   Nz
tools/list)methodclientrequestmessagesourcer   r  fastmcp_contextc                (    j                  d      S NFr  )r  r   r   s    rw   <lambda>z$FastMCP.list_tools.<locals>.<lambda>  s    dooUo.Sr~   r   r   token	component)r   r   r   Contextr8   mcptypesListToolsRequestr   r   r   r  rD   rE   r   r   r2   r4   r!   r   )r   r  ctx
mw_contextr   r   	skip_authr,  
authorizedr   r   s   `         rw   r  zFastMCP.list_tools  sz     >>))11$1??3.II66l6K#"'$'
 "11&S 2   @?? uw1334E2599E %71AQE702Iu%'J TYY%:%ETBC!%4TYY%DDD$  E !!$'  = @?? @ 497  E- ! !7 @???s   /FEFA
E=EE=FEFE=-E!
.E=E#E=E%E%"1E=E,-E*.E,2E=FE;FE=F!E=#E=%E=*E,,	E85E=7E88E=;F=FFFFc                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)ac  Get a tool by name via aggregation from providers.

        Extends AggregateProvider._get_tool() with component-level auth checks.

        Args:
            name: The tool name.
            version: Version filter (None returns highest version).

        Returns:
            The tool if found and authorized, None if not found or unauthorized.
        Nr+  )r   	_get_toolr   r   r2   r4   r!   )r   r   r   r   r4  r,  r2  r   s          rw   r7  zFastMCP._get_tool#  s      W&tW55< -.	5TYY2ET:C,TYY<<< =
 t 6 =% K   A?A,/A?A0 !A."A0 &A?(A?.A0 0	A<9A?;A<<A?c                   K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         sy|d   S 7 17 w)a  Get a tool by name, filtering disabled tools.

        Overrides Provider.get_tool() to add visibility filtering after all
        transforms (including session-level) have been applied. This ensures
        session transforms can override provider-level disables.

        Args:
            name: The tool name.
            version: Version filter (None returns highest version).

        Returns:
            The tool if found and enabled, None otherwise.
        Nr   )r   get_toolrD   rE   )r   r   r   r   r   r   s        rw   r:  zFastMCP.get_toolB  s[       W%dG44< /v66JuQx0Qx 5
 7   AA	AAAAc                  K   t         j                  j                  j                         4 d{   }|r?t	        i ddd|      } j                  | fd       d{   cddd      d{    S t        t        
 !          d{         }t        |       d{   }|D cg c]  }t        |      s| }}t               \  }}g }|D ]O  }	|s:|	j                  .t        ||		      }	 t        |	j                  |       d{   s>	 |j!                  |	       Q |cddd      d{    S 7 	7 7 7 7 c c}w 7 <# t        $ r Y w xY w7 &# 1 d{  7  sw Y   yxY ww)
a  List all enabled resources from providers.

        Overrides Provider.list_resources() to add visibility filtering, auth filtering,
        and middleware execution. Returns all versions (no deduplication).
        Protocol handlers deduplicate for MCP wire format.
        r  Nr   r!  zresources/listr"  c                (    j                  d      S r'  )r  r(  s    rw   r)  z(FastMCP.list_resources.<locals>.<lambda>p  s    d.A.AQV.A.Wr~   r*  r+  )r   r   r   r.  r8   r   r   r   r  rD   rE   r   r   r2   r4   r!   r   )r   r  r2  r3  r  rr4  r,  r5  resourcer   s   `         rw   r  zFastMCP.list_resources\  sh     >>))11$1??3.#"+$'
 "11&W 2   @?? 57#9#;;<I6yAAI$-?IqAII?02Iu)+J% X]]%>%EXFC!%4X]]C%HHH$  I !!(+ & = @?? @ <A?  I- ! !7 @???   /E4D<E4,E#D?$E'E43E4E49EE
E&E'E/E E1E6EEEE*E46E7E4?EE4EEEE	EEEEE4E1%E(&E1-E4c                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)ap  Get a resource by URI via aggregation from providers.

        Extends AggregateProvider._get_resource() with component-level auth checks.

        Args:
            uri: The resource URI.
            version: Version filter (None returns highest version).

        Returns:
            The resource if found and authorized, None if not found or unauthorized.
        Nr+  )r   _get_resourcer   r   r2   r4   r!   )r   urir   r?  r4  r,  r2  r   s          rw   rB  zFastMCP._get_resource  s      .sG<< -.	5X]]6EX>C,X]]C@@@ A
 x = A% r8  c                   K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         sy|d   S 7 17 w)a  Get a resource by URI, filtering disabled resources.

        Overrides Provider.get_resource() to add visibility filtering after all
        transforms (including session-level) have been applied.

        Args:
            uri: The resource URI.
            version: Version filter (None returns highest version).

        Returns:
            The resource if found and enabled, None otherwise.
        Nr   )r   get_resourcerD   rE   )r   rC  r   r?  r  r   s        rw   rE  zFastMCP.get_resource  s]      -c7;; 3H:>>	
9Q< 8| <
 ?r;  c                  K   t         j                  j                  j                         4 d{   }|r?t	        i ddd|      } j                  | fd       d{   cddd      d{    S t        t        
 !          d{         }t        |       d{   }|D cg c]  }t        |      s| }}t               \  }}g }|D ]O  }	|s:|	j                  .t        ||		      }	 t        |	j                  |       d{   s>	 |j!                  |	       Q |cddd      d{    S 7 	7 7 7 7 c c}w 7 <# t        $ r Y w xY w7 &# 1 d{  7  sw Y   yxY ww)
a%  List all enabled resource templates from providers.

        Overrides Provider.list_resource_templates() to add visibility filtering,
        auth filtering, and middleware execution. Returns all versions (no deduplication).
        Protocol handlers deduplicate for MCP wire format.
        r  Nr   r!  zresources/templates/listr"  c                (    j                  d      S r'  )r  r(  s    rw   r)  z1FastMCP.list_resource_templates.<locals>.<lambda>  s    d.J.J', /K /r~   r*  r+  )r   r   r   r.  r8   r   r   r   r  rD   rE   r   r   r2   r4   r!   r   )r   r  r2  r3  r	  r   r4  r,  r5  templater   s   `         rw   r  zFastMCP.list_resource_templates  sl     >>))11$1??3.#"5$'
 "11& 2   @??" 57#B#DDEI6yAAI$-?IqAII?02Iu13J% X]]%>%EXFC!%4X]]C%HHH$  I !!(+ & A @?? @" EA?  I- ! !; @???r@  c                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)a  Get a resource template by URI via aggregation from providers.

        Extends AggregateProvider._get_resource_template() with component-level auth checks.

        Args:
            uri: The template URI to match.
            version: Version filter (None returns highest version).

        Returns:
            The template if found and authorized, None if not found or unauthorized.
        Nr+  )r   _get_resource_templater   r   r2   r4   r!   )r   rC  r   rH  r4  r,  r2  r   s          rw   rJ  zFastMCP._get_resource_template  s      7WEE -.	5X]]6EX>C,X]]C@@@ A
 x F A% r8  c                   K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         sy|d   S 7 17 w)a  Get a resource template by URI, filtering disabled templates.

        Overrides Provider.get_resource_template() to add visibility filtering after
        all transforms (including session-level) have been applied.

        Args:
            uri: The template URI.
            version: Version filter (None returns highest version).

        Returns:
            The template if found and enabled, None otherwise.
        Nr   )r   get_resource_templaterD   rE   )r   rC  r   rH  r	  r   s        rw   rL  zFastMCP.get_resource_template  s^      6sGDD 3H:>>	
9Q< 8| E
 ?r;  c                  K   t         j                  j                  j                         4 d{   }|r?t	        i ddd|      } j                  | fd       d{   cddd      d{    S t        t        
 !          d{         }t        |       d{   }|D cg c]  }t        |      s| }}t               \  }}g }|D ]O  }	|s:|	j                  .t        ||		      }	 t        |	j                  |       d{   s>	 |j!                  |	       Q |cddd      d{    S 7 	7 7 7 7 c c}w 7 <# t        $ r Y w xY w7 &# 1 d{  7  sw Y   yxY ww)
a  List all enabled prompts from providers.

        Overrides Provider.list_prompts() to add visibility filtering, auth filtering,
        and middleware execution. Returns all versions (no deduplication).
        Protocol handlers deduplicate for MCP wire format.
        r  Nr   r!  zprompts/listr"  c                (    j                  d      S r'  )r  r(  s    rw   r)  z&FastMCP.list_prompts.<locals>.<lambda>2  s    d.?.?u.?.Ur~   r*  r+  )r   r   r   r.  r8   r   r   r   r  rD   rE   r   r   r2   r4   r!   r   )r   r  r2  r3  r
  r   r4  r,  r5  promptr   s   `         rw   r  zFastMCP.list_prompts   sh     >>))11$1??3.#")$'
 "11&U 2   @?? !5!778G4W==G");'QZ]q'G;02Iu')J! V[[%<%EVDC!%4V[[#%FFF$  G !!&) " = @?? @ 8=;  G- ! !7 @???r@  c                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)ak  Get a prompt by name via aggregation from providers.

        Extends AggregateProvider._get_prompt() with component-level auth checks.

        Args:
            name: The prompt name.
            version: Version filter (None returns highest version).

        Returns:
            The prompt if found and authorized, None if not found or unauthorized.
        Nr+  )r   _get_promptr   r   r2   r4   r!   )r   r   r   rO  r4  r,  r2  r   s          rw   rQ  zFastMCP._get_promptG  s      w*499> -.	5V[[4EV<C,V[[#>>> ?
 v : ?% r8  c                   K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         sy|d   S 7 17 w)a  Get a prompt by name, filtering disabled prompts.

        Overrides Provider.get_prompt() to add visibility filtering after all
        transforms (including session-level) have been applied.

        Args:
            name: The prompt name.
            version: Version filter (None returns highest version).

        Returns:
            The prompt if found and enabled, None otherwise.
        Nr   )r   
get_promptrD   rE   )r   r   r   rO  r
  r   s        rw   rS  zFastMCP.get_promptf  s\      w)$88> 1&::j4qz 9
 ;r;  r   r  	task_metac                  K   y wrs   r   r   r   	argumentsr   r  rU  s         rw   	call_toolzFastMCP.call_tool  s         )r   r  c                  K   y wrs   r   rW  s         rw   rY  zFastMCP.call_tool        &)rZ  c          	     b   K   t         j                  j                  j                         4 d{   }|rkt	        t
           t        j                  j                  ||xs i       ddd|      } j                  | fd	       d{   cddd      d{    S t        d
| d j                  d|      5 } j                  |       d{   }	|	t        d|      |j                  |	j                                #j                  t!        |	j"                        	 |	j%                  |xs i        d{   cddd       cddd      d{    S 7 87 7 7 7 '7 # t&        $ r t(        j+                  d|        t,        t.        f$ r t(        j+                  d|        t0        $ r}
t(        j+                  d|       t3        |
t4        j6                        r%|
j8                  j:                  dk(  rt=        d      |
t3        |
t4        j>                        rt=        d      |
 j@                  rt=        d|      |
t=        d|d|
       |
d}
~
ww xY w# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  Call a tool by name.

        This is the public API for executing tools. By default, middleware is applied.

        Args:
            name: The tool name
            arguments: Tool arguments (optional)
            version: Specific version to call. If None, calls highest version.
            run_middleware: If True (default), apply the middleware chain.
                Set to False when called from middleware to avoid re-applying.
            task_meta: If provided, execute as a background task and return
                CreateTaskResult. If None (default), execute synchronously and
                return ToolResult.

        Returns:
            ToolResult when task_meta is None.
            CreateTaskResult when task_meta is provided.

        Raises:
            NotFoundError: If tool not found or disabled
            ToolError: If tool execution fails
            ValidationError: If arguments fail validation
        r  Nr   rX  r   r!  z
tools/callr"  c                    j                  | j                  j                  | j                  j                  xs i d      S NFrT  )rY  r#  r   rX  r   r   rU  r   s    rw   r)  z#FastMCP.call_tool.<locals>.<lambda>  s;    dnn,,117R '',"+ /= /r~   r*  ztools/call r   r   zUnknown tool: fn_keyrU  zError calling tool zError validating tool   0Rate limited by upstream API, please retry later(Upstream request timed out, please retry: )!r   r   r   r.  r8   r   r/  r0  r   rA   r   r:  r#   set_attributesget_span_attributesrd  r
   r|   _runr"   logger	exceptionr   PydanticValidationError	Exceptionr   httpxHTTPStatusErrorresponsestatus_coder&   TimeoutExceptionr   )r   r   rX  r   r  rU  r2  r3  spanr   es   `  ` `     rw   rY  zFastMCP.call_tool  s    H >>))11$1??3./DEII;;!Y_" <  $"'$'
 "11& 2 	 	 @??0 dV$lDIIvt!]]4]AA<'.(ABB##D$<$<$>?(Y-=-=-E '	$(( CIP!%9?i!PP 1 @??	 @6 B QE @F $ $$':4(%CD')@A $$'=dX%FG  P$$':4(%CD "!U%:%:;::11S8"+ R##$% "!U%;%;<'F ! //'*=dX(FGQN#&9$A3$GHaO!P# 1 @????s   /J/E,J/AJE/JJ/ E1!J/&JI<E3AI<3E9E5E9	JJ/&E7'J//J1J/3I<5E97J/9AI9
B*I44I99I<<J	JJ/JJ/J, J#!J,(J/c                  K   y wrs   r   r   rC  r   r  rU  s        rw   read_resourcezFastMCP.read_resource  s      rZ  c                  K   y wrs   r   ry  s        rw   rz  zFastMCP.read_resource  s      &)rZ  c          	     r   K   t         j                  j                  j                         4 d{   }|rjt	        |      }t        t        j                  j                  |      ddd|      } j                  | fd	       d{   cddd      d{    S t        d
| d j                  d||      5 } j                  |       d{   }	|	y|j                  |	j                                #j                  t!        |	j"                        	 |	j%                         d{   cddd       cddd      d{    S  jA                  |       d{   }|!tC        d|      tC        d|d      |j                  |j                                |jE                  |      }|J #j                  t!        |j"                        	 |j%                  ||       d{   cddd       cddd      d{    S 7 7 7 7 W7 7 # t&        t(        f$ r t*        j-                  d|        t.        $ r}
t*        j-                  d|       t1        |
t2        j4                        r%|
j6                  j8                  dk(  rt;        d      |
t1        |
t2        j<                        rt;        d      |
 j>                  rt;        d|      |
t;        d|d|
       |
d}
~
ww xY w7 7 7 # t&        t(        f$ r t*        j-                  d|        t.        $ r}
t*        j-                  d|       t1        |
t2        j4                        r%|
j6                  j8                  dk(  rt;        d      |
t1        |
t2        j<                        rt;        d      |
 j>                  rt;        d|      |
t;        d|d|
       |
d}
~
ww xY w# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  Read a resource by URI.

        This is the public API for reading resources. By default, middleware is applied.
        Checks concrete resources first, then templates.

        Args:
            uri: The resource URI
            version: Specific version to read. If None, reads highest version.
            run_middleware: If True (default), apply the middleware chain.
                Set to False when called from middleware to avoid re-applying.
            task_meta: If provided, execute as a background task and return
                CreateTaskResult. If None (default), execute synchronously and
                return ResourceResult.

        Returns:
            ResourceResult when task_meta is None.
            CreateTaskResult when task_meta is provided.

        Raises:
            NotFoundError: If resource not found or disabled
            ResourceError: If resource read fails
        r  N)rC  r   r!  zresources/readr"  c                h    j                  t        | j                  j                        d      S r`  )rz  strr#  rC  ra  s    rw   r)  z'FastMCP.read_resource.<locals>.<lambda>9  s1    d.@.@GOO//0 '',"+	 /A /r~   r*  zresources/read r?  )resource_urirb  rc  re  zError reading resource rf  rg  rh  ri  zUnknown resource: 	 version )#r   r   r   r.  r   r8   r/  r0  ReadResourceRequestParamsr   rA   r   rE  rj  rk  rd  r
   r|   _readr"   r   rm  rn  rp  r   rq  rr  rs  rt  r%   ru  r   rL  r#   matches)r   rC  r   r  rU  r2  	uri_paramr3  rv  r?  rw  rH  paramss   ` ` `        rw   rz  zFastMCP.read_resource  sI    J >>))11$1??3"3K	.II??I?N#"+$'
 "11& 2   @??* !#' 		  !%!2!23!2!HH'''(D(D(FG ,1A1A1I$+Ihll$K	!%-^^i^%HH + @??| "&!;!;C!;!QQ#+.@,HII',SG9WKH  ##H$@$@$BC!))#.)))(Y-=-=-E '	(,, GIW!)Vy!QQm + @?? @< I  II @J )(3 ((+B3')JK$ !((+B3')JK%a)>)>? zz55<&3$V'"'(!) &a)?)?@"/ J##$%  33"/"9# A##$% ,5cWBqcB !#!, R RW @X %h/ $$'>sg%FG  W$$'>sg%FG!!U%:%:;::11S8"/ R##$% "!U%;%;<+F ! //+.EcW,MNTUU'*A#1#(NOUVVWu + @????sE  /P7H(P7AP"H+P"P7H. P7%P"PH1A
P&H8;H4<H8?	P"P7H6P7P0L1B P2L"	L
L"	P"P7"L #P7+P".P71P4H86P780L(B*LLPL" P7"0PB*O<<PPP		P"P7PP7"P4(P+)P40P7c                  K   y wrs   r   rW  s         rw   render_promptzFastMCP.render_prompt  s      rZ  c                  K   y wrs   r   rW  s         rw   r  zFastMCP.render_prompt  r\  rZ  c          	     8   K   t         j                  j                  j                         4 d{   }|r`t	        t
        j                  j                  ||      ddd|      } j                  | fd	       d{   cddd      d{    S t        d
| d j                  d|      5 } j                  |       d{   }	|	t        d|      |j                  |	j                                #j                  t!        |	j"                        	 |	j%                  |       d{   cddd       cddd      d{    S 7 )7 7 7 7 '7 # t&        t(        f$ r t*        j-                  d|        t.        $ rJ}
t*        j-                  d|        j0                  rt3        d|      |
t3        d|d|
       |
d}
~
ww xY w# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  Render a prompt by name.

        This is the public API for rendering prompts. By default, middleware is applied.
        Use get_prompt() to retrieve the prompt definition without rendering.

        Args:
            name: The prompt name
            arguments: Prompt arguments (optional)
            version: Specific version to render. If None, renders highest version.
            run_middleware: If True (default), apply the middleware chain.
                Set to False when called from middleware to avoid re-applying.
            task_meta: If provided, execute as a background task and return
                CreateTaskResult. If None (default), execute synchronously and
                return PromptResult.

        Returns:
            PromptResult when task_meta is None.
            CreateTaskResult when task_meta is provided.

        Raises:
            NotFoundError: If prompt not found or disabled
            PromptError: If prompt rendering fails
        r  Nr^  r   r!  zprompts/getr"  c                    j                  | j                  j                  | j                  j                  d      S r`  )r  r#  r   rX  ra  s    rw   r)  z'FastMCP.render_prompt.<locals>.<lambda>  s9    d.@.@,,11 '',"+ /A /r~   r*  zprompts/get rO  rb  zUnknown prompt: rc  re  zError rendering prompt ri  )r   r   r   r.  r8   r/  r0  GetPromptRequestParamsr   rA   r   rS  r#   rj  rk  rd  r
   r|   _renderr"   r   rm  rn  rp  r   r$   )r   r   rX  r   r  rU  r2  r3  rv  rO  rw  s   `  ` `     rw   r  zFastMCP.render_prompt  s    @ >>))11$1??3.II<<!Y =  $"($'
 "11& 2 	 	 @??0 tf%}dii4#tWEE>'*:4((CDD##F$>$>$@A(Y-=-=-E '	&** EI	V!'	Y!OO 1 @??	 @6 F PE @F %h/ $$'>th%GH  V$$'>th%GH//),CD8*LMSTT%(?xr!&MNTUU	V 1 @????s   /HEHAHE H	HE"HH7G'E$AG'(E*>E&?E*	HHE(H H"H$G'&E*(H*0G$AGG$$G''G0	,H3H>H?HHHHHc                8    | j                   j                  |      S )at  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 or @tool-decorated function to register

        Returns:
            The tool instance that was added to the server.
        )r   r   )r   r   s     rw   r   zFastMCP.add_tool  s     ##,,T22r~   c                   t         j                  j                  rt        j                  dt
        d       	 | j                  j                  ||       y# t        $ r& |t        d|d      dt        d|d|d      dw xY w)ak  Remove tool(s) from the server.

        .. deprecated::
            Use ``mcp.local_provider.remove_tool(name)`` instead.

        Args:
            name: The name of the tool to remove.
            version: If None, removes ALL versions. If specified, removes only that version.

        Raises:
            NotFoundError: If no matching tool is found.
        zNremove_tool() is deprecated. Use mcp.local_provider.remove_tool(name) instead.r  r  NzTool z
 not foundr  )
r   r   r  r  r]   r  r   remove_toolKeyErrorr#   )r   r   r   s      rw   r  zFastMCP.remove_tool  s     00MM@"		  ,,T7; 	#eD8:$>?TIxy:>	s   A /B)r   r   titledescriptionr   tagsoutput_schemar   exclude_argsmetaapptasktimeoutr   c                    y rs   r   r   
name_or_fnr   r   r  r  r   r  r  r   r  r  r  r  r  r   s                   rw   r   zFastMCP.tool  s    & r~   c                    y rs   r   r  s                   rw   r   zFastMCP.tool/  s    & r~   c                   |+|dur'|rt        |      ni }|du rd|d<   nt        |      |d<   | j                  j                  |||||||||	|
|||n| 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
            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.
                Deprecated: Use `Depends()` for dependency injection instead.
            meta: Optional meta information about 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")
            ```
        FTui)r   r   r  r  r   r  r  r   r  r  r  r  r   )dictr/   r   r   r   )r   r  r   r   r  r  r   r  r  r   r  r  r  r  r  r   results                    rw   r   zFastMCP.toolD  s    P ?s%/!%4:2Dd{!T
4S9T
 %%**#'#%)t/M/M + 
" r~   c                8    | j                   j                  |      S )zAdd a resource to the server.

        Args:
            resource: A Resource instance or @resource-decorated function to add

        Returns:
            The resource instance that was added to the server.
        )r   add_resource)r   r?  s     rw   r  zFastMCP.add_resource  s     ##00::r~   c                8    | j                   j                  |      S )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   add_template)r   rH  s     rw   r  zFastMCP.add_template  s     ##00::r~   )r   r   r  r  r   	mime_typer  r   r  r  r  r   c                  t        |t              st        d      t        ||      }t        |t              r.|j
                  t        d      |j                  t        d      |+|dur'|
rt        |
      ni }
|du rd|
d<   nt        |      |
d<   | j                  j                  |||||||||	|
||n| j                  |      }|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
            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}"
            ```
        zThe @resource decorator was used incorrectly. It requires a URI as the first argument. Use @resource('uri') instead of @resourceu   resource_uri cannot be set on resources — the resource itself is the UI. Use resource_uri on tools to point to a UI resource.uC   visibility cannot be set on resources — it only applies to tools.FTr  )r   r   r  r  r   r  r  r   r  r  r   )r   r~  ry   r0   r.   r  r   
visibilityr  r/   r   r?  r   )r   rC  r   r   r  r  r   r  r  r   r  r  r  r   inner_decorators                  rw   r?  zFastMCP.resource  s   J #s#<  )i8	 c9%+ K 
 ~~) Y 
 ?s%/!%4:2Dd{!T
4S9T
 ..77##)t/M/M 8 
 r~   c                8    | j                   j                  |      S )zAdd a prompt to the server.

        Args:
            prompt: A Prompt instance or @prompt-decorated function to add

        Returns:
            The prompt instance that was added to the server.
        )r   
add_prompt)r   rO  s     rw   r  zFastMCP.add_prompt6  s     ##..v66r~   	r   r   r  r  r   r  r  r  r   c       	             y rs   r   r   r  r   r   r  r  r   r  r  r  r   s              rw   rO  zFastMCP.promptA  s     r~   c       	             y rs   r   r  s              rw   rO  zFastMCP.promptQ  s     r~   c       	        t    | j                   j                  |||||||||	|	|

      S | j                  |

      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
            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")
            ```
        r  )r   rO  r   r  s              rw   rO  zFastMCP.prompta  sc    n ##**#) + 
 	
 04/M/M + 
 	
r~   c                   ddl }ddlm} |) |j                  dt        d       ||}nt        d      |B |j                  dt        d       |r'dd	lm} t        ||      st        j                  |      } ||      }	|rG|j                         D 
ci c]  \  }
}|
t        |
       }}
}|	j                  t        |            }	| j                  |	|xs d       yc c}}
w )a	  Mount another FastMCP server on this server with an optional namespace.

        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 namespace:
        - Tools from the mounted server are accessible with namespaced names.
          Example: If server has a tool named "get_weather", it will be available as "namespace_get_weather".
        - Resources are accessible with namespaced URIs.
          Example: If server has a resource with URI "weather://forecast", it will be available as
          "weather://namespace/forecast".
        - Templates are accessible with namespaced URI templates.
          Example: If server has a template with URI "weather://location/{id}", it will be available
          as "weather://namespace/location/{id}".
        - Prompts are accessible with namespaced names.
          Example: If server has a prompt named "weather_prompt", it will be available as
          "namespace_weather_prompt".

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

        The mounted server's lifespan is executed when the parent server starts, and its
        middleware chain is invoked for all operations (tool calls, resource reads, prompts).

        Args:
            server: The FastMCP server to mount.
            namespace: Optional namespace to use for the mounted server's objects. If None,
                the server's objects are accessible with their original names.
            as_proxy: Deprecated. Mounted servers now always have their lifespan and
                middleware invoked. To create a proxy server, use create_proxy()
                explicitly before mounting.
            tool_names: Optional mapping of original tool names to custom names. Use this
                to override namespaced names. Keys are the original tool names from the
                mounted server.
            prefix: Deprecated. Use namespace instead.
        r   N)FastMCPProviderz=The 'prefix' parameter is deprecated, use 'namespace' insteadr  r  z,Cannot specify both 'prefix' and 'namespace'zas_proxy is deprecated and will be removed in a future version. Mounted servers now always have their lifespan and middleware invoked. To create a proxy server, use create_proxy() explicitly.rY   )r   r   r   )r  )fastmcp.server.providers.fastmcp_providerr  r]   r  r   fastmcp.server.providers.proxyrZ   r   r   as_proxyitemsrJ   wrap_transformrB   r   )r   r   r   r  
tool_namesprefixr  r  rZ   r   old_namenew_namer   s                rw   mountzFastMCP.mount  s   ` 	M HMMO"
  "	 !OPPHMMK # G!&,7$--f5F -V4  +5*:*:*<*<&Hh -8<<*<    ..}Z/HIH 	(io2>s   C#c           	     8  K   ddl } |j                  dt        d       dd}|j                          d{   D ]8  }|r#|j	                  d| d	|j
                   i
      }| j                  |       : |j                          d{   D ]E  }|r0 |t        |j                        |      }|j	                  d|i
      }| j                  |       G |j                          d{   D ]<  }|r' ||j                  |      }	|j	                  d|	i
      }| j                  |       > |j                          d{   D ]8  }
|r#|
j	                  d| d	|
j
                   i
      }
| j                  |
       : |j                   t"        k7  rddl m}  |dt$        d       |r4t&        j)                  d| j
                   d|j
                   d| d       yt&        j)                  d| j
                   d|j
                          y7 7 7 +7 ֭w)a  
        Import the MCP objects from another FastMCP server into this one,
        optionally with a given prefix.

        .. deprecated::
            Use :meth:`mount` instead. ``import_server`` will be removed in a
            future version.

        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.
        r   Nz0import_server is deprecated, use mount() insteadr  r  rC  c                l    t         j                  |       }|r|j                         \  }}| | d| S | S )uG   Add prefix to resource URI: protocol://path → protocol://prefix/path./)URI_PATTERNmatchgroups)rC  r  r  protocolpaths        rw   add_resource_prefixz2FastMCP.import_server.<locals>.add_resource_prefixS  s>    %%c*E!&$"F81TF33Jr~   r   _)updateuri_template)r]   zeWhen importing from a server with a lifespan, the lifespan from the imported server will not be used.)r#  categoryr  [z] Imported server z with prefix '')rC  r~  r  r~  r   r~  )r  r]   r  r  
model_copyr   r   r  r~  rC  r  r  r  r  r  r  r   r   RuntimeWarningrm  rg   )r   r   r  r  r  r   r?  new_urirH  new_uri_templaterO  r]   s               rw   import_serverzFastMCP.import_server#  s    P 	>	
	 !++---Dv&499+7N.OPMM$ . %33555H-c(,,.?H#..ug6F.Gh'	 6 %<<>>>H#6x7L7Lf#U #..*,<= /  h' ? #//111F**6fXQv{{m;T2U*VOOF# 2
 //%' LLDII;0^F8STU LL1TYYK'9&++GHQ . 6 ? 2sI   5HHAH
HAH*H+AHHCHHHHc
           
     F    ddl m}  |||||||||	      } | d||gd|
S )a  
        Create a FastMCP server from an OpenAPI specification.

        Args:
            openapi_spec: OpenAPI schema as a dictionary
            client: Optional httpx AsyncClient for making HTTP requests.
                If not provided, a default client is created using the first
                server URL from the OpenAPI spec with a 30-second timeout.
            name: Name for the MCP server
            route_maps: Optional list of RouteMap objects defining route mappings
            route_map_fn: Optional callable for advanced route type mapping
            mcp_component_fn: Optional callable for component customization
            mcp_names: Optional dictionary mapping operationId to component names
            tags: Optional set of tags to add to all components
            validate_output: If True (default), tools use the output schema
                extracted from the OpenAPI spec for response validation. If
                False, a permissive schema is used instead, allowing any
                response structure while still returning structured JSON.
            **settings: Additional settings passed to FastMCP

        Returns:
            A FastMCP server with an OpenAPIProvider attached.
           OpenAPIProvider)openapi_specr   
route_mapsroute_map_fnmcp_component_fn	mcp_namesr  validate_outputr   r   r   )providers.openapir  )clsr  r   r   r  r  r  r  r  r  r   r  r   s                rw   from_openapizFastMCP.from_openapi  sC    J 	7,%!%-+	
 ?
?h??r~   c	           	        ddl m}
 |i }|j                  dd       t        j                  d	dt        j
                  |      i|}|xs |j                  } |
|j                         ||||||      } | d	||gd|	S )
af  
        Create a FastMCP server from a FastAPI application.

        Args:
            app: FastAPI application instance
            name: Name for the MCP server (defaults to app.title)
            route_maps: Optional list of RouteMap objects defining route mappings
            route_map_fn: Optional callable for advanced route type mapping
            mcp_component_fn: Optional callable for component customization
            mcp_names: Optional dictionary mapping operationId to component names
            httpx_client_kwargs: Optional kwargs passed to httpx.AsyncClient.
                Use this to configure timeout and other client settings.
            tags: Optional set of tags to add to all components
            **settings: Additional settings passed to FastMCP

        Returns:
            A FastMCP server with an OpenAPIProvider attached.
        r  r  base_urlzhttp://fastapi	transport)r  )r  r   r  r  r  r  r  r  r   )r  r  
setdefaultrq  AsyncClientASGITransportr  openapi)r  r  r   r  r  r  r  httpx_client_kwargsr  r   r  r   server_namer   s                 rw   from_fastapizFastMCP.from_fastapi  s    > 	7&"$&&z3CD"" 
))c2
!

 'cii,!%-
 FzFXFFr~   c                    t         j                  j                  rt        j                  dt
        d       t        |fi |S )a  Create a FastMCP proxy server for the given backend.

        .. deprecated::
            Use :func:`fastmcp.server.create_proxy` instead.
            This method will be removed in a future version.

        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.
        z{FastMCP.as_proxy() is deprecated. Use create_proxy() from fastmcp.server instead: `from fastmcp.server import create_proxy`r  r  )r   r   r  r  r]   r  create_proxy)r  backendr   s      rw   r  zFastMCP.as_proxy  s=    6 00MMT"	 G0x00r~   c                    | j                   }|| dt        j                  d       S | d| dt        j                  d       S )N-r  )r   secrets	token_hex)r  r   
class_names      rw   r   zFastMCP.generate_name  sP    \\
< \7#4#4Q#7"899 \4&'*;*;A*>)?@@r~   )NN)*r   
str | Noner   r  r   r  r   r  r   list[mcp.types.Icon] | Noner   zAuthProvider | Noner   zSequence[Middleware] | Noner   zSequence[Provider] | Noner   zSequence[Transform] | Noner   z"LifespanCallable | Lifespan | Noner   z*Sequence[Tool | Callable[..., Any]] | Noner   zDuplicateBehavior | Noner   bool | Noner   boolr   r  r   z
int | Noner   r  r   zAsyncKeyValue | Noner   zSamplingHandler | Noner   z$Literal['always', 'fallback'] | Noner{   r   )r   r~  )r   r  )r   r  r   None)r   zlist[mcp.types.Icon])r   r<   )r   zMiddlewareContext[Any]r   z2Callable[[MiddlewareContext[Any]], Awaitable[Any]]r   r   )r   r7   r   r  )r   r=   r   r~  r   r  )r   zSequence[FastMCPComponent])r  rC   r   r  )r  r~  r  rJ   r   r  )r  r~  r   r  )r  r  r   zSequence[Tool]rs   )r   r~  r   VersionSpec | Noner   zTool | None)r  r  r   zSequence[Resource])rC  r~  r   r  r   zResource | None)r  r  r   zSequence[ResourceTemplate])rC  r~  r   r  r   zResourceTemplate | None)r  r  r   zSequence[Prompt])r   r~  r   r  r   zPrompt | None)r   r~  rX  dict[str, Any] | Noner   r  r  r  rU  r  r   rI   )r   r~  rX  r  r   r  r  r  rU  r@   r   mcp.types.CreateTaskResult)r   r~  rX  r  r   r  r  r  rU  TaskMeta | Noner   z'ToolResult | mcp.types.CreateTaskResult)
rC  r~  r   r  r  r  rU  r  r   r,   )
rC  r~  r   r  r  r  rU  r@   r   r  )
rC  r~  r   r  r  r  rU  r  r   z+ResourceResult | mcp.types.CreateTaskResult)r   r~  rX  r  r   r  r  r  rU  r  r   r*   )r   r~  rX  r  r   r  r  r  rU  r  r   z)PromptResult | mcp.types.CreateTaskResult)r   zTool | Callable[..., Any]r   rH   )r   r~  r   r  r   r  ) r  r[   r   r  r   str | int | Noner  r  r  r  r   r  r  set[str] | Noner  dict[str, Any] | NotSetT | Noner   'ToolAnnotations | dict[str, Any] | Noner  list[str] | Noner  r  r  (AppConfig | dict[str, Any] | bool | Noner  bool | TaskConfig | Noner  float | Noner   "AuthCheck | list[AuthCheck] | Noner   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   Callable[[F], F]) r  str | AnyFunction | Noner   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   ztCallable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool])r?  zResource | Callable[..., Any]r   zResource | ResourceTemplate)rH  r-   r   r-   )rC  r~  r   r  r   r  r  r  r  r  r   r  r  r  r  r  r   z#Annotations | dict[str, Any] | Noner  r  r  r  r  r   r   r  r   r  )rO  zPrompt | Callable[..., Any]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  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   z|Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt])NNNN)r   r   r   r  r  r  r  dict[str, str] | Noner  r  r   r  )r   r   r  r  r   r  )NzOpenAPI ServerNNNNNT)r  dict[str, Any]r   zhttpx.AsyncClient | Noner   r~  r  list[RouteMap] | Noner  OpenAPIRouteMapFn | Noner  OpenAPIComponentFn | Noner  r  r  r  r  r  r   r   r   r    )NNNNNNN)r  r   r   r  r  r  r  r  r  r	  r  r  r  r  r  r  r   r   r   r    )r  }Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | strr   r   r   rZ   )r   r  r   r~  )5r   r   r   r   r   propertyr   r   setterr   r   r   r   r   r   r   r  r   r  r  r  r7  r:  r  rB  rE  r  rJ  rL  r  rQ  rS  r   rY  rz  r  r   r  rN   r   r  r  r?  r  rO  r  r  classmethodr  r  r  r   __classcell__)r   s   @rw   r   r      sd     #'@

 #"&-1$(26/3157;<@15*.$(/3%)!4837JN-@
@
 !@

 @
  @
 +@
 "@
 0@
 -@
 /@
 5@
 :@
 /@
 (@
  "!@
" "-#@
$ #%@
& '@
( 2)@
* 1+@
, $H-@
. /@
D7 % % - - . . ( ( , , 0 0 	$ 	$	$'	$ F	$ 
		$+ DF <,
:+(GG.AG	G" :> %P 8<"4	@ 8<"4	6 )-'!%'	'T 7;!3	@ 7;!3	4 )-)!%)	#)X 7;!3	 @ 7;!3	 2 <@ %P 8<"4	@ 8<"4	2  ,0
 '+# )
 $   
   ,0)
 '+#)) ))
 $) ) ) 
$) ) ,0]P
 '+#%)]P]P )]P
 $]P ]P #]P 
1]P~ 
 '+# $	
   
  
 '+#)) $	)
 ) ) 
$) ) '+#%)CWCW $	CW
 CW #CW 
5CWJ  ,0
 '+# )
 $   
   ,0)
 '+#)) ))
 $) ) ) 
$) ) ,0JV
 '+#%)JVJV )JV
 $JV JV #JV 
3JVX3: 
  $( "&-1 $9??C)-&*8<)- $37# 	
 "    +  7 = ' $ 6 '  !" 1#$ 
% (  "&  $( "&-1 $9??C)-&*8<)- $37# 	
 "    +  7 = ' $ 6 '  !" 1#$ 
% , 04a  $( "&-1 $9??C)-&*8<)- $37#a,a 	a
 "a a  a +a a 7a =a 'a $a 6a 'a  !a" 1#a&	H'aF;5;	$;	;  $( "&-1 $ $;?&*8<)-37uu 	u
 "u u  u +u u u 9u $u 6u 'u 1u  
!un	7 
  $( "&-1 $&*)-37 	
 "    +  $ ' 1 
   "&  $( "&-1 $&*)-37 	
 "    +  $ ' 1 
 " 04b
  $( "&-1 $&*)-37b
,b
 	b

 "b
 b
  b
 +b
 b
 $b
 'b
 1b
	Lb
N !% $,0!\?(\? \? 	\?
 *\? \? 
\?B "aI(aI aI 
	aIF  ,0$,0156:+/ $ $0@$0@ )0@ 	0@
 *0@ /0@ 40@ )0@ 0@ 0@ 0@ 
0@ 0@d   ,0156:+/59 $4G4G 4G *	4G
 /4G 44G )4G 34G 4G 4G 
4G 4Gl "1"1 "1 
"1 "1H A Ar~   r   c                6    ddl m}m}  ||       } |dd|i|S )a  Create a FastMCP proxy server for the given target.

    This is the recommended way to create a proxy server. For lower-level control,
    use `FastMCPProxy` or `ProxyProvider` directly from `fastmcp.server.providers.proxy`.

    Args:
        target: The backend to proxy to. Can be:
            - A Client instance (connected or disconnected)
            - A ClientTransport
            - A FastMCP server instance
            - A URL string or AnyUrl
            - A Path to a server script
            - An MCPConfig or dict
        **settings: Additional settings passed to FastMCPProxy (name, etc.)

    Returns:
        A FastMCPProxy server that proxies to the target.

    Example:
        ```python
        from fastmcp.server import create_proxy

        # Create a proxy to a remote server
        proxy = create_proxy("http://remote-server/mcp")

        # Create a proxy to another FastMCP server
        proxy = create_proxy(other_server)
        ```
    r   )rZ   _create_client_factoryclient_factoryr   )r  rZ   r  )targetr   rZ   r  r  s        rw   r  r  $  s1    V
 ,F3N %
 r~   )r{   r  r   r  )r   ztuple[bool, Any])r   r   r   zAsyncIterator[Any])r   r   r   zYCallable[[LowLevelServer[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]])r  r
  r   r   r   rZ   )r   
__future__r   r   rer  r  collections.abcr   r   r   r   
contextlibr   r	   dataclassesr
   	functoolsr   pathlibr   typingr   r   r   r   r   r   r   rq  	mcp.typesr/  key_value.aio.adapters.pydanticr   key_value.aio.protocolsr   key_value.aio.stores.memoryr   mcp.server.lowlevel.serverr   mcp.shared.exceptionsr   r   r   r   r   pydanticr   r   ro  starlette.routingr   typing_extensionsr    r   fastmcp.serverfastmcp.exceptionsr!   r"   r#   r$   r%   r&   fastmcp.mcp_configr'   fastmcp.promptsr(   fastmcp.prompts.function_promptr)   fastmcp.prompts.promptr*   fastmcp.resources.resourcer+   r,   fastmcp.resources.templater-   fastmcp.server.appsr.   r/   r0   fastmcp.server.authr1   r2   r3   r4   fastmcp.server.lifespanr5   fastmcp.server.low_levelr6   fastmcp.server.middlewarer7   r8   fastmcp.server.mixinsr9   r:   r;   fastmcp.server.providersr<   r=   "fastmcp.server.providers.aggregater>   fastmcp.server.tasks.configr?   r@   fastmcp.server.telemetryrA   fastmcp.server.transformsrB   rC   $fastmcp.server.transforms.visibilityrD   rE   fastmcp.settingsrF   DuplicateBehaviorSettingfastmcp.tools.function_toolrG   fastmcp.tools.toolrH   rI   fastmcp.tools.tool_transformrJ   fastmcp.utilities.componentsrK   fastmcp.utilities.loggingrL   fastmcp.utilities.typesrM   rN   rO   fastmcp.utilities.versionsrP   fastmcp.clientrQ   fastmcp.client.clientrR   fastmcp.client.samplingrS   fastmcp.client.transportsrT   rU    fastmcp.server.providers.openapirV   OpenAPIComponentFnrW   rX   OpenAPIRouteMapFnr  rZ   r   rm  r[   rp   r   r}   	Transportcompiler  r   r   r   r   r   r   r  r   r~   rw   <module>rJ     s   ; "  	        P P P   ; 1 3 6 *   ? ' "     ) " : / ? 7 
 V U , 3 C S S < @ < 0 V J 4 / < 9 0 E E %47KR9P;	H	CxS)*@A #
E#
E# ]# /	#
 u# p# s# !# T# 8# <# :#   A# Y# O#  g!# (

 =>	 bjj-.  "=o"NN 
'& 	 	,0! HAOHA`:4	4 4 4r~   