
    $jzu             
         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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/m0Z0 ddl/m1Z2 ddl3m4Z4 ddl5m6Z6 ddl7Z7ddl8Z7ddl9m:Z:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDm1Z1 ddlEmFZF ddlGmHZH ddlImJZJ ddlKmLZL ddlMmNZNmOZO ddlPmQZQ ddlRmSZSmTZTmUZUmVZV ddlWmXZX ddlYmZZZ ddl[m\Z\m]Z] dd l^m_Z_m`Z`maZa dd!lbmcZcmdZd dd"lemfZf dd#lgmhZhmiZi dd$ljmkZk dd%llmmZmmnZn dd&lompZpmqZq dd'lrmsZt dd(lumvZvmwZw dd)lxmyZy dd*lzm{Z{ dd+l|m}Z}m~Z~ dd,lmZ dd-lmZmZmZ dd.lmZmZ er2dd/lmZ dd0lmZ dd1lmZ dd2lmZmZ dd3lmZ dd4lmZ dd5lmZ dd6lmZ  ee          Z G d7 d8ej                  Z ej        d9                               e                        ed:ed;ef         <          Zed=         Zsi d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdQdSdQdTdUdVdWdXdYdZd[Zd\ed]<   d}dbZedc         Z ej        dd          Zedegee(         f         Zd~dgZddkZddlZeddo            ZddrZ G ds dte          Z G du dvefe_e`eaee(                   Zdd|ZdS )z5FastMCP - 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)	AppConfigapp_config_to_meta_dictresolve_ui_mime_type)AuthorizationErrorFastMCPDeprecationWarningFastMCPErrorNotFoundErrorPromptErrorResourceError	ToolErrorr   )	MCPConfig)Prompt)PromptResult)FunctionPrompt)ResourceResourceResult)ResourceTemplate)	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)Tool
ToolResult)FunctionToolToolTransformConfig)FastMCPComponent_coerce_version)
get_logger)FastMCPBaseModelNotSetNotSetT)VersionSpecversion_sort_key)Client)FastMCP1Server)SamplingHandler)ClientTransportClientTransportT)ComponentFn)RouteMap)
RouteMapFnFastMCPProxyc                      e Zd ZddZdS )_SuppressUnlistedToolWarningrecordlogging.LogRecordreturnboolc                .    d|                                 vS )Nznot listed, no validation)
getMessage)selfra   s     ]/home/rurouni/.hermes/hermes-agent/venv/lib/python3.11/site-packages/fastmcp/server/server.pyfilterz#_SuppressUnlistedToolWarning.filterm   s    *&2C2C2E2EEE    N)ra   rb   rc   rd   )__name__
__module____qualname__ri    rj   rh   r`   r`   l   s.        F F F F F Frj   r`   zmcp.server.lowlevel.server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_KWARGSkwargsdict[str, Any]rc   Nonec                    | D ]+}|t           v r t          d| dt           |                    ,| r/t          dd                    d | D                                  dS )z2Raise helpful TypeErrors for kwargs removed in v3.zFastMCP() no longer accepts `z`. z.FastMCP() got unexpected keyword argument(s): z, c              3  4   K   | ]}t          |          V  d S N)repr).0ks     rh   	<genexpr>z(_check_removed_kwargs.<locals>.<genexpr>   s)      F_F_STtAwwF_F_F_F_F_F_rj   N)r   	TypeErrorjoin)r   keys     rh   _check_removed_kwargsr      s      /!!NNN8LNN   "  
aTYYF_F_X^F_F_F_=_=_aa
 
 	

 
rj   )stdiohttpssezstreamable-httpz^([^:]+://)(.*?)$FastMCP[LifespanResultT]tuple[bool, Any]c                 j    ddl m}  |                                 dk    }|rdS 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      rh   _get_auth_contextr      s`     :99999!%%''72H |<<<<<<##%%&&rj   toolrH   rd   c                    | j         }|sdS |                    d          }t          |t                    sdS |                    d          }t          |t                    sdS d|v S )u'  Check whether a tool should be visible to the model.

    Tools registered via ``@app.tool()`` (without ``model=True``) have
    ``meta["ui"]["visibility"] == ["app"]`` — they are callable by app UIs
    but should not appear in the model's tool list.

    Returns True (visible) when:
    - The tool has no ``meta.ui.visibility`` (normal tools).
    - ``"model"`` is in the visibility list (e.g. ``["model"]`` or ``["app", "model"]``).

    Returns False when the visibility list exists and does not contain ``"model"``
    (e.g. ``["app"]``).
    Tui
visibilitymodelmetar   
isinstancedictlistr   r   r   r   s       rh   _is_model_visibler      sq     9D t	$Bb$ t%%Jj$'' tj  rj   c                    | j         }|sdS |                    d          }t          |t                    sdS |                    d          }t          |t                    sdS d|v S )ul  Check whether a tool has explicitly opted into app-callable visibility.

    Gates the dispatcher's hashed-name routing path: only tools whose
    ``meta.ui.visibility`` list contains ``"app"`` can be reached via
    ``<hash>_<local_name>`` calls. Tools without an explicit visibility
    declaration are NOT app-callable — they must be reached by their
    display name through the normal transform-aware resolution path.

    This is the inverse of the "everything is dot-callable" trap: the
    hashed-name path is an opt-in mechanism for FastMCPApp backend tools,
    not a general bypass for arbitrary tools.
    Fr   r   appr   r   s       rh   _is_app_visibler      sq     9D u	$Bb$ u%%Jj$'' uJrj   serverAsyncIterator[Any]c                  K   i W 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.
    Nrn   )r   s    rh   default_lifespanr      s       HHHHHHrj   fastmcp_serverYCallable[[LowLevelServer[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]]c                .     t           d fd            }|S )Nlow_level_serverLowLevelServer[LifespanResultT]rc   AsyncIterator[LifespanResultT]c               v   K   j         t          u ri W V  d S j        st          d          j        W 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/PrefectHQ/fastmcp/issues.)	_lifespanr   _lifespan_result_setRuntimeError_lifespan_result)r   r   s    rh   wrapz_lifespan_proxy.<locals>.wrap   se       #'777HHHHF2 	\  
 -------rj   )r   r   rc   r   )r	   )r   r   s   ` rh   _lifespan_proxyr      s5    
 . . . . . . Krj   c                      e Zd ZU dZded<   dS )
StateValuez(Wrapper for stored context state values.r   valueN)rk   rl   rm   __doc____annotations__rn   rj   rh   r   r     s         22JJJJJrj   r   c                  `    e Zd Z	 	 ddddddddddddddddddddddو fd,Zdd/Zedd0            Zedd1            Zej        dd4            Zedd5            Z	edd6            Z
edd8            Zedd:            Zdd?ZddAZdBdCd fdGZddIZd fdKZddNZddRZddTZddUd fdXZ	 dd fd[Z	 dd fd\ZddUd fd^Z	 dd fdaZ	 dd fdbZddUd fddZ	 dd fdfZ	 dd fdgZddUd fdiZ	 dd fdkZ	 dd fdlZ e!	 dddddmddr            Z"e!	 ddddsddv            Z"	 dddddmddyZ"e!ddddmdd{            Z#e!dddsdd|            Z#ddddmdd~Z#e!	 dddddmdd            Z$e!	 ddddsdd            Z$	 dddddmddZ$ddZ%dddZ&e!dddddde'dddddddddd            Z(e!	 ddddddde'dddddddddd            Z(	 ddddddde'ddddddddddZ(ddZ)ddZ*dddddddddddddddZ+d dZ,e!dddddddddd	dd            Z-e!	 ddddddddddd	dd            Z-	 ddddddddddd	ddZ-	 	 	 	 dddZ.	 dddZ/e0	 	 	 	 	 	 	 	 dddЄ            Z1e0	 	 	 	 	 	 	 d	d
d҄            Z2e0ddք            Z3e0dddׄ            Z4 xZ5S (  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_behaviorclient_log_levelname
str | Noneinstructionsr   str | int | float | Noner   r   list[mcp.types.Icon] | Noner   AuthProvider | Noner   Sequence[Middleware] | Noner   Sequence[Provider] | Noner   Sequence[Transform] | Noner   "LifespanCallable | Lifespan | Noner   *Sequence[Tool | Callable[..., Any]] | Noner   DuplicateBehavior | Noner   bool | Noner   rd   r   r   
int | Noner   r   AsyncKeyValue | Noner   SamplingHandler | Noner   $Literal['always', 'fallback'] | Noner   mcp.types.LoggingLevel | Noner   r   c               :   t          |           t                                                       |pd| _        ||nd| _        d | _        d | _        g | _        |pt                      | _	        t          t                   | j	        t          d          | _        t          | j                  | _        |                     | j                   |pg D ]}|                     |           |	pg D ]}|                     |           ||nt"          j        j        | _        ||dk    rt+          d          || _        |
&t/          t0          t2                   |
          | _        n*t/          t0          t2                   t6                    | _        d | _        d| _        d| _        t?          j                     | _!        t?          j"                    | _#        tI          t2                   | |p| %                                tM          |          pt"          j'        |||tQ          |           	          | _)        || _*        |rC|D ]@}tW          |tX                    stY          j-        |          }| .                    |           A||nt"          j        j/        | _/        ||nt"          j        j0        | _0        tc          |pg           | _2        |r(dd
l3m4} | j2        5                     |                       | 6                                 || _7        |pd| _8        d S )Nrq   Ffastmcp_state)	key_valuepydantic_modeldefault_collection)r   r   z)list_page_size must be a positive integer)r   )fastmcpr   r   r   r   r   r   )DereferenceRefsMiddlewarefallback)9r   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   _lifespan_ref_countasyncioLock_lifespan_lockEvent_startedr7   generate_namerN   __version__r   _mcp_serverr   r   rH   from_functionadd_toolr   r   r   r   %fastmcp.server.middleware.dereferencer   append_setup_handlersr   r   )rg   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   ptr   r   	__class__s                              rh   r   zFastMCP.__init__  s~   4 	f%%% 	7C7Mv 9>8Iuuu& 8:$ .A-QKMM9H9T)%.:
 :
 :
 /<+/
 /
 /
 	$.///b 	! 	!Aa    !r 	" 	"Aq!!!!
 "- !4 	  %.A*=*=HIII+9 @D 18A ADNN ""2?"CEUVVDN8<*/!() ,3LNN'.} BPB
 -++--#G,,C0C%#$D999
B
 
B
 
B
 *.	 	$ $ $!$-- 4-d33Dd#### '2 $#!9 	$  + !2 	 -11Ar,B,B 	@      O""#<#<#>#>??? 	8H%3 	&&&rj   rc   strc                @    t          |           j         d| j        dS )N())typerk   r   rg   s    rh   __repr__zFastMCP.__repr__  s$    t**%66	6666rj   c                    | j         j        S r   )r  r   r  s    rh   r   zFastMCP.name  s    $$rj   c                    | j         j        S r   r  r   r  s    rh   r   zFastMCP.instructions  s    ,,rj   r   r   c                    || j         _        d S r   r  )rg   r   s     rh   r   zFastMCP.instructions  s    (-%%%rj   c                    | j         j        S r   )r  r   r  s    rh   r   zFastMCP.version  s    ''rj   c                    | j         j        S r   )r  r   r  s    rh   r   zFastMCP.website_url  s    ++rj   list[mcp.types.Icon]c                P    | j         j        g S t          | j         j                  S r   )r  r   r   r  s    rh   r   zFastMCP.icons  s'    !)I(.///rj   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    rh   local_providerzFastMCP.local_provider  s     ##rj   contextMiddlewareContext[Any]	call_next2Callable[[MiddlewareContext[Any]], Awaitable[Any]]c                |   K   |}t          | j                  D ]}t          ||          } ||           d{V S )z)Builds and executes the middleware chain.)r)  N)reversedr   r   )rg   r'  r)  chainmws        rh   _run_middlewarezFastMCP._run_middleware  sZ       4?++ 	1 	1BB%000EEU7^^#######rj   r8   c                :    | j                             |           d S r   )r   r  )rg   r   s     rh   add_middlewarezFastMCP.add_middleware  s    z*****rj    	namespaceproviderr>   r4  c               N    t                                          ||           dS )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"
        r3  N)r   r   )rg   r5  r4  r  s      rh   r   zFastMCP.add_provider  s(     	X;;;;;rj   
list[Tool]c                4    ddl mm fd|D             S )u  Replace placeholder Prefab URIs with per-tool hashed ones.

        For each tool whose ``meta.ui.resourceUri`` is the placeholder,
        reads the tool's stored hash from ``meta.fastmcp._tool_hash``
        and rewrites the URI to the per-tool form. Also strips CSP from
        tool meta (it belongs on the resource). Produces ``model_copy``
        views — originals are untouched.
        r   )_is_prefab_toolrewrite_tool_meta_for_wirec                @    g | ]} |          r |          n|S rn   rn   )r   r  r9  r:  s     rh   
<listcomp>z0FastMCP._rewrite_prefab_uris.<locals>.<listcomp>  sF     
 
 
KL__Q-?-?F&&q)))Q
 
 
rj   ))fastmcp.server.providers.prefab_synthesisr9  r:  )rg   r   r9  r:  s     @@rh   _rewrite_prefab_uriszFastMCP._rewrite_prefab_uris  s\    	
 	
 	
 	
 	
 	
 	
 	


 
 
 
 
PU
 
 
 	
rj   Sequence[FastMCPComponent]c                  K   t          t                                                       d{V           }d |D             }d |D             }d |D             }d |D             }| j        D ]n}|                    |           d{V }|                    |           d{V }|                    |           d{V }|                    |           d{V }og ||||S )zGet task-eligible components with all transforms applied.

        Overrides AggregateProvider.get_tasks() to apply server-level transforms
        after aggregation. AggregateProvider handles provider-level namespacing.
        Nc                <    g | ]}t          |t                    |S rn   )r   rH   r   cs     rh   r<  z%FastMCP.get_tasks.<locals>.<listcomp>  s'    >>>q*Q*=*=>>>>rj   c                <    g | ]}t          |t                    |S rn   )r   r/   rB  s     rh   r<  z%FastMCP.get_tasks.<locals>.<listcomp>  s'    FFF1jH.E.EFQFFFrj   c                <    g | ]}t          |t                    |S rn   )r   r1   rB  s     rh   r<  z%FastMCP.get_tasks.<locals>.<listcomp>  s(    NNN1j<L.M.MNQNNNrj   c                <    g | ]}t          |t                    |S rn   )r   r,   rB  s     rh   r<  z%FastMCP.get_tasks.<locals>.<listcomp>  s'    BBBJq&,A,AB1BBBrj   )r   r   	get_tasksr   
list_toolslist_resourceslist_resource_templateslist_prompts)rg   
componentsr   	resources	templatesprompts	transformr  s          rh   rG  zFastMCP.get_tasks	  s]       1 1 3 333333344
 ?>J>>>FF
FFF	NN
NNN	BBjBBB  	< 	<I#..u55555555E'66yAAAAAAAAI'??	JJJJJJJJI%227;;;;;;;;GG


 
 	
 	
rj   rP  rD   c                :    | j                             |           dS )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  )rg   rP  s     rh   r   zFastMCP.add_transform&  s!    $ 		*****rj   	tool_nametransformationrL   c                    t           j        j        rt          j        dt
          d           |                     t          ||i                     dS )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warningsrq   r%   r   rC   )rg   rS  rT  s      rh   add_tool_transformationzFastMCP.add_tool_transformation:  s`     0 	MT)	    	=)^)DEEFFFFFrj   
_tool_namec                d    t           j        j        rt          j        dt
          d           dS dS )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.rV  rW  N)r   r   rY  rZ  rq   r%   )rg   r\  s     rh   remove_tool_transformationz"FastMCP.remove_tool_transformationK  sL     0 	M) *     	 	rj   run_middlewarer`  Sequence[Tool]c               8   K   t           j        j                                       4 d{V }|rdt	          t
          j                            d          ddd|          }                     | fd	           d{V cddd          d{V  S t          t                                                       d{V           }t          |           d{V }d
 |D             }                     |          }t                      \  }}g }|D ]_}|sF|j        ?t!          ||          }	 t#          |j        |           d{V s9n# t$          $ r Y Fw xY w|                    |           `|cddd          d{V  S # 1 d{V swxY w Y   dS )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  rd  fastmcp_contextc                0                         d          S NFr_  )rH  r'  rg   s    rh   <lambda>z$FastMCP.list_tools.<locals>.<lambda>l  s    dooUo.S.S rj   r'  r)  c                N    g | ]"}t          |          t          |           |#S rn   rF   r   r   r  s     rh   r<  z&FastMCP.list_tools.<locals>.<listcomp>s  s1    PPP1AP;LQ;O;OPQPPPrj   token	component)r   r   r'  Contextr9   mcptypesListToolsRequestr/  r   r   rH  rE   r>  r   r   r3   r5   r$   r  )
rg   r`  ctx
mw_contextr   	skip_authrt  
authorizedr   r  s
   `        rh   rH  zFastMCP.list_toolsZ  s      >)11$1?? &	 &	 &	 &	 &	 &	 &	3 .I66l6KK#"'$'  
 "11&SSSS 2        &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	  uww113333333344E2599999999EPPPPPE --e44E022Iu%'J ( (  !TY%:%ETBBBC!%4TY%D%DDDDDDD %$%- ! ! ! !!!$''''M&	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	 &	s=   AF	BF	2EF	
EF	EF		
FFVersionSpec | NoneTool | Nonec                  K   t                                          ||           d{V }|dS t                      \  }}|sH|j        At	          ||          }	 t          |j        |           d{V sdS n# t          $ r Y dS w xY w|S )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.
        Nrs  )r   	_get_toolr   r   r3   r5   r$   )rg   r   r   r   r|  rt  rz  r  s          rh   r  zFastMCP._get_tool  s       WW&&tW55555555<4 -..	5 	TY2ET:::C,TY<<<<<<<<  4 %   tt    A: :
BBc                  K   t                                          |           d{V }|dS t          |g           d{V }|r2t          |d                   rt	          |d                   r|d         S |dS fdt                                                       d{V D             }t          t          |           d{V           }d |D             }t                      \  }}g }	|D ]_}
|sF|
j        ?t          ||
          }	 t          |
j        |           d{V s9n# t          $ r Y Fw xY w|	                    |
           `|	sdS t          t          t          |	t                               S )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.

        When the highest version is disabled and no explicit version was
        requested, falls back to the next-highest enabled version.

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

        Returns:
            The tool if found and enabled, None otherwise.
        Nr   c                *    g | ]}|j         k    |S rn   r   )r   r  r   s     rh   r<  z$FastMCP.get_tool.<locals>.<listcomp>  s     MMM1afnnQnnnrj   c                N    g | ]"}t          |          t          |           |#S rn   rq  rr  s     rh   r<  z$FastMCP.get_tool.<locals>.<listcomp>  s1    RRR:a==R=Nq=Q=QR1RRRrj   rs  r   )r   get_toolrE   rF   r   rH  r   r   r   r3   r5   r$   r  r   rH   maxrT   )rg   r   r   r   r   	all_toolsenabledr|  rt  r}  r  rz  r  s    `          rh   r  zFastMCP.get_tool  s     & WW%%dG44444444<4 /v66666666 	Za)) 	.?a.I.I 	8O
 4MMMMegg&8&8&:&: : : : : : :MMM	7	BBBBBBBBCC	RRiRRR,..	5!#
 	! 	!A !3!;;;!0!=!======= ! !)   Ha     	4D#j.>???@@@s   D..
D;:D;Sequence[Resource]c               &   K   t           j        j                                       4 d{V }|rFt	          i ddd|          }                     | fd           d{V cddd          d{V  S t          t                                                       d{V           }t          |           d{V }d	 |D             }d
dl
m} |                     |            d{V            t                      \  }}g }|D ]_}	|sF|	j        ?t          ||	          }	 t!          |	j        |           d{V s9n# t"          $ r Y Fw xY w|                    |	           `|cddd          d{V  S # 1 d{V swxY w Y   dS )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.
        rc  Nre  rf  zresources/listrg  c                0                         d          S rl  )rI  rm  s    rh   rn  z(FastMCP.list_resources.<locals>.<lambda>  s    d.A.AQV.A.W.W rj   ro  c                0    g | ]}t          |          |S rn   rF   r   rs     rh   r<  z*FastMCP.list_resources.<locals>.<listcomp>  #    ???qA????rj   r   )synthesize_prefab_resourcesrs  )r   r   r'  rv  r9   r/  r   r   rI  rE   r=  r  extendr   r   r3   r5   r$   r  )rg   r`  rz  r{  rM  r  r|  rt  r}  resourcer  s   `         rh   rI  zFastMCP.list_resources  s      >)11$1?? '	 '	 '	 '	 '	 '	 '	3 .#"+$'  
 "11&WWWW 2        '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 577#9#9#;#;;;;;;;<<I6yAAAAAAAAI??I???I
      #>#>t#D#DDDDDDDEEE022Iu)+J% , ,  !X]%>%EXFFFC!%4X]C%H%HHHHHHH %$%- ! ! ! !!!(++++O'	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	 '	s<   6F 9B/F )EF 
EF EF  
F
F
uriResource | Nonec                  K   t                                          ||           d{V }|dS t                      \  }}|sH|j        At	          ||          }	 t          |j        |           d{V sdS n# t          $ r Y dS w xY w|S )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.
        Nrs  )r   _get_resourcer   r   r3   r5   r$   )rg   r  r   r  r|  rt  rz  r  s          rh   r  zFastMCP._get_resource  s       ..sG<<<<<<<<4 -..	5 	X]6EX>>>C,X]C@@@@@@@@  4 %   tt r  c                  K   t                                          |           d{V }|dS t          |g           d{V }|rt          |d                   r|d         S |dS fdt                                                       d{V D             }t          t          |           d{V           }d |D             }t                      \  }}g }	|D ]_}
|sF|
j        ?t          ||
          }	 t          |
j        |           d{V s9n# t          $ r Y Fw xY w|	                    |
           `|	sdS t          t          t          |	t                              S )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.

        When the highest version is disabled and no explicit version was
        requested, falls back to the next-highest enabled version.

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

        Returns:
            The resource if found and enabled, None otherwise.
        Nr   c                D    g | ]}t          |j                  k    |S rn   )r  r  )r   r  r  s     rh   r<  z(FastMCP.get_resource.<locals>.<listcomp>M  s,    XXXqc!%jjTWFWFWFWFWFWrj   c                0    g | ]}t          |          |S rn   r  r  s     rh   r<  z(FastMCP.get_resource.<locals>.<listcomp>O  #    ===z!}}=1===rj   rs  r  )r   get_resourcerE   rF   rI  r   r   r   r3   r5   r$   r  r   r/   r  rT   )rg   r  r   r  rM  all_resourcesr  r|  rt  r}  r  rz  r  s    `          rh   r  zFastMCP.get_resource/  s     $ --c7;;;;;;;;4 3H:>>>>>>>>	 	 IaL11 	 Q<4XXXX%''*@*@*B*B$B$B$B$B$B$BXXX#;M#J#JJJJJJJKK==m===,..	5%'
 	! 	!A !3!;;;!0!=!======= ! !)   Ha     	4Hc*2BCCCDDD   <D
D&%D&Sequence[ResourceTemplate]c                  K   t           j        j                                       4 d{V }|rFt	          i ddd|          }                     | fd           d{V cddd          d{V  S t          t                                                       d{V           }t          |           d{V }d	 |D             }t                      \  }}g }|D ]_}|sF|j        ?t          ||
          }	 t          |j        |           d{V s9n# t          $ r Y Fw xY w|                    |           `|cddd          d{V  S # 1 d{V swxY w Y   dS )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.
        rc  Nre  rf  zresources/templates/listrg  c                0                         d          S rl  )rJ  rm  s    rh   rn  z1FastMCP.list_resource_templates.<locals>.<lambda>u  s     d.J.J', /K / / rj   ro  c                0    g | ]}t          |          |S rn   r  rr  s     rh   r<  z3FastMCP.list_resource_templates.<locals>.<listcomp>}  r  rj   rs  )r   r   r'  rv  r9   r/  r   r   rJ  rE   r   r   r3   r5   r$   r  )
rg   r`  rz  r{  rN  r|  rt  r}  templater  s
   `        rh   rJ  zFastMCP.list_resource_templatesa  s      >)11$1??  	  	  	  	  	  	  	3 .#"5$'  
 "11&    2         	  	  	  	  	  	  	  	  	  	  	  	  	  	" 577#B#B#D#DDDDDDDEEI6yAAAAAAAAI??I???I022Iu13J% , ,  !X]%>%EXFFFC!%4X]C%H%HHHHHHH %$%- ! ! ! !!!(++++A 	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	  	<   6E9BE?DE
D)&E(D))E
E #E ResourceTemplate | Nonec                  K   t                                          ||           d{V }|dS t                      \  }}|sH|j        At	          ||          }	 t          |j        |           d{V sdS n# t          $ r Y dS w xY w|S )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.
        Nrs  )r   _get_resource_templater   r   r3   r5   r$   )rg   r  r   r  r|  rt  rz  r  s          rh   r  zFastMCP._get_resource_template  s       77WEEEEEEEE4 -..	5 	X]6EX>>>C,X]C@@@@@@@@  4 %   tt r  c                  K   t                                          |           d{V }|dS t          |g           d{V }|rt          |d                   r|d         S |dS fdt                                                       d{V D             }t          t          |           d{V           }d |D             }t                      \  }}g }	|D ]_}
|sF|
j        ?t          ||
          }	 t          |
j        |           d{V s9n# t          $ r Y Fw xY w|	                    |
           `|	sdS t          t          t          |	t                              S )a4  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.

        When the highest version is disabled and no explicit version was
        requested, falls back to the next-highest enabled version.

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

        Returns:
            The template if found and enabled, None otherwise.
        Nr   c                >    g | ]}|                               |S r   )matches)r   r  r  s     rh   r<  z1FastMCP.get_resource_template.<locals>.<listcomp>  s3     
 
 
yy~~) )))rj   c                0    g | ]}t          |          |S rn   r  rr  s     rh   r<  z1FastMCP.get_resource_template.<locals>.<listcomp>  r  rj   rs  r  )r   get_resource_templaterE   rF   rJ  r   r   r   r3   r5   r$   r  r   r1   r  rT   )rg   r  r   r  rN  all_templatesr  r|  rt  r}  r  rz  r  s    `          rh   r  zFastMCP.get_resource_template  s     $ 66sGDDDDDDDD4 3H:>>>>>>>>	 	 IaL11 	 Q<4
 
 
 
 77::<<<<<<<<
 
 

 #;M#J#JJJJJJJKK==m===,..	5-/
 	! 	!A !3!;;;!0!=!======= ! !)   Ha     	4$c*:J&K&K&KLLLr  Sequence[Prompt]c                  K   t           j        j                                       4 d{V }|rFt	          i ddd|          }                     | fd           d{V cddd          d{V  S t          t                                                       d{V           }t          |           d{V }d	 |D             }t                      \  }}g }|D ]_}|sF|j        ?t          ||
          }	 t          |j        |           d{V s9n# t          $ r Y Fw xY w|                    |           `|cddd          d{V  S # 1 d{V swxY w Y   dS )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.
        rc  Nre  rf  zprompts/listrg  c                0                         d          S rl  )rK  rm  s    rh   rn  z&FastMCP.list_prompts.<locals>.<lambda>  s    d.?.?u.?.U.U rj   ro  c                0    g | ]}t          |          |S rn   r  r   r  s     rh   r<  z(FastMCP.list_prompts.<locals>.<listcomp>  s#    ;;;QZ]];q;;;rj   rs  )r   r   r'  rv  r9   r/  r   r   rK  rE   r   r   r3   r5   r$   r  )
rg   r`  rz  r{  rO  r|  rt  r}  promptr  s
   `        rh   rK  zFastMCP.list_prompts  s      >)11$1?? 	 	 	 	 	 	 	3 .#")$'  
 "11&UUUU 2        	 	 	 	 	 	 	 	 	 	 	 	 	 	 !5!5!7!777777788G4W========G;;';;;G022Iu')J! * *  !V[%<%EVDDDC!%4V[#%F%FFFFFFF %$%- ! ! ! !!!&))))=	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	r  Prompt | Nonec                  K   t                                          ||           d{V }|dS t                      \  }}|sH|j        At	          ||          }	 t          |j        |           d{V sdS n# t          $ r Y dS w xY w|S )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.
        Nrs  )r   _get_promptr   r   r3   r5   r$   )rg   r   r   r  r|  rt  rz  r  s          rh   r  zFastMCP._get_prompt  s       ww**499999999>4 -..	5 	V[4EV<<<C,V[#>>>>>>>>  4 %   tt r  c                  K   t                                          |           d{V }|dS t          |g           d{V }|rt          |d                   r|d         S |dS fdt                                                       d{V D             }t          t          |           d{V           }d |D             }t                      \  }}g }	|D ]_}
|sF|
j        ?t          ||
          }	 t          |
j        |           d{V s9n# t          $ r Y Fw xY w|	                    |
           `|	sdS t          t          t          |	t                              S )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.

        When the highest version is disabled and no explicit version was
        requested, falls back to the next-highest enabled version.

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

        Returns:
            The prompt if found and enabled, None otherwise.
        Nr   c                *    g | ]}|j         k    |S rn   r  )r   r  r   s     rh   r<  z&FastMCP.get_prompt.<locals>.<listcomp>E  s     QQQQ!&D..q...rj   c                0    g | ]}t          |          |S rn   r  r  s     rh   r<  z&FastMCP.get_prompt.<locals>.<listcomp>G  s#    ;;;Z]];1;;;rj   rs  r  )r   
get_promptrE   rF   rK  r   r   r   r3   r5   r$   r  r   r,   r  rT   )rg   r   r   r  rO  all_promptsr  r|  rt  r}  r  rz  r  s    `          rh   r  zFastMCP.get_prompt'  s     $ ww))$88888888>4 1&:::::::: 	z'!*-- 	1:4QQQQ(<(<(>(>">">">">">">QQQ!9+!F!FFFFFFFGG;;k;;;,..	5#%
 	! 	!A !3!;;;!0!=!======= ! !)   Ha     	4FC
0@AAABBBr  r   r`  	task_meta	argumentsdict[str, Any] | Noner  rI   c               
   K   d S r   rn   rg   r   r  r   r`  r  s         rh   	call_toolzFastMCP.call_toolY  s       Srj   )r   r`  rA   mcp.types.CreateTaskResultc               
   K   d S r   rn   r  s         rh   r  zFastMCP.call_toold         &)Srj   TaskMeta | None'ToolResult | mcp.types.CreateTaskResultc          	        K   ddl m} t          j        j                                       4 d{V }|rtt          t                   t          j	                            ||pi           ddd|	          } 
                    | fd
           d{V cddd          d{V  S t          d| d j        d|          5 }	                     |           d{V }
|
 ||          }||\  }}                     ||           d{V }
|
{t                      \  }}|sh|
j        a	 t#          ||
          }t%          |
j        |           d{V st'          d|          n!# t(          $ r t'          d|          dw xY w|
t'          d|          |	                    |
                                           j        t1          |
j                  	 |
                    |pi            d{V 	 cddd           cddd          d{V  S # t6          $ r t8                              d|            t<          t>          f$ r t8                              d|            t@          $ r}t8                              d|           tC          |tD          j#                  r |j$        j%        dk    rtM          d          |tC          |tD          j'                  rtM          d          | j(        rtM          d|          |tM          d|d|           |d}~ww xY w# 1 swxY w Y   	 ddd          d{V  dS # 1 d{V swxY w Y   dS )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   )parse_hashed_backend_namerc  Nr   r  re  rf  z
tools/callrg  c                d                         | j        j        | j        j        pi d          S NFr  )r  rh  r   r  r'  rg   r  r   s    rh   rn  z#FastMCP.call_tool.<locals>.<lambda>  s8    dnn,17R '',"+ /= / / rj   ro  ztools/call r   r   rs  zUnknown tool: fn_keyr  zError calling tool zError validating tool   0Rate limited by upstream API, please retry later(Upstream request timed out, please retry: ))#fastmcp.server.providers.addressingr  r   r   r'  rv  r9   r   rw  rx  r/  rB   r   r  get_tool_by_hashr   r   r3   r5   r'   r$   set_attributesget_span_attributesr  r
   r   _runr&   logger	exceptionr   PydanticValidationError	Exceptionr   httpxHTTPStatusErrorresponsestatus_coder*   TimeoutExceptionr  )rg   r   r  r   r`  r  r  rz  r{  spanr   hasheddigest
local_namer|  rt  auth_ctxes   `  ` `            rh   r  zFastMCP.call_toolo  ss     H	
 	
 	
 	
 	
 	
 >)11$1?? P	P P	P P	P P	P P	P P	P P	P3 ./DEI;;!Y_" <   $"'$'  
 "11&      2 	 	 	 	 	 	 	 	P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P. $d$$lDIvt  9P*.--g-*N*N$N$N$N$N$N$N <66t<<F)-3*
%)%:%:6:%N%NNNNNNN+/@/B/B,Iu#, 01F!0/:RV/W/W/WH1@H1U1U+U+U+U+U+U+U %W.;<UT<U<U.V.V(V%W'9 !0 !0 !0*7(A(A(A+& +&+/%0!0
 <'(A(A(ABBB##D$<$<$>$>???(Y-=-E '	$( C C CIP!%9?i!P!PPPPPPPPE9P 9P 9P 9P 9P 9P 9P/P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	Pt $   $$%C4%C%CDDD')@A   $$%Fd%F%FGGG  P P P$$%C4%C%CDDD "!U%:;; %:1S88"+ R# ##$% "!U%;<< !'F  ! / O'(Fd(F(FGGQN#$G$$G$GA$G$GHHaO!PS9P 9P 9P 9P 9P 9P 9P 9P 9P/P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	P P	Psv   A$M$.M$	A*M4>E32M3FAM/H-M$-AMB1L==MMM			M$M		M$$
M.1M.r0   c               
   K   d S r   rn   rg   r  r   r`  r  s        rh   read_resourcezFastMCP.read_resource  s       rj   c               
   K   d S r   rn   r  s        rh   r  zFastMCP.read_resource  s       &)Srj   +ResourceResult | mcp.types.CreateTaskResultc          	     	   K   t           j        j                                       4 d{V }|rut	          |          }t          t          j                            |          ddd|          } 	                    | fd	           d{V cddd          d{V  S t          d
| d j        d||          5 }ddlm}	  |	 |           d{V }
|
a|                    |
                                           |
                               d{V cddd           cddd          d{V  S                      |           d{V }|s|                    |                                           j        t'          |j                  	 |                               d{V 	 cddd           cddd          d{V  S # t*          t,          f$ r t.                              d|            t2          $ r}t.                              d|           t5          |t6          j                  r |j        j        dk    rt?          d          |t5          |t6          j                   rt?          d          | j!        rt?          d|          |t?          d|d|           |d}~ww xY w "                    |           d{V }|)tG          d|          tG          d|d          |                    |                                           |$                    |          }|J j        t'          |j                  	 |                    ||           d{V 	 cddd           cddd          d{V  S # t*          t,          f$ r t.                              d|            t2          $ r}t.                              d|           t5          |t6          j                  r |j        j        dk    rt?          d          |t5          |t6          j                   rt?          d          | j!        rt?          d|          |t?          d|d|           |d}~ww xY w# 1 swxY w Y   	 ddd          d{V  dS # 1 d{V swxY w Y   dS )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
        rc  N)r  re  rf  zresources/readrg  c                d                         t          | j        j                  d          S r  )r  r  rh  r  r  s    rh   rn  z'FastMCP.read_resource.<locals>.<lambda>6  s6    d.@.@GO/00 '',"+	 /A / / rj   ro  zresources/read r  )resource_urir   )!synthesize_prefab_resource_by_urir  r  r  zError reading resource r  r  r  r  zUnknown resource: 	 version )%r   r   r'  rv  r   r9   rw  rx  ReadResourceRequestParamsr/  rB   r   r=  r  r  r  _readr  r  r
   r   r&   r   r  r  r  r   r  r  r  r  r)   r  r  r  r'   r  )rg   r  r   r`  r  rz  	uri_paramr{  r  r  synthesizedr  r  r  paramss   ` ` `          rh   r  zFastMCP.read_resource  s
	     J >)11$1?? j	W j	W j	W j	W j	W j	W j	W3 "3KK	.I??I?NN#"+$'  
 "11&      2        j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W* '#'' 	    UW       %F$EdC$P$PPPPPPP*''(G(G(I(IJJJ!,!2!2Y!2!G!GGGGGGG%UW UW UW UW UW UW UW+j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	WT "&!2!23!2!H!HHHHHHH'''(D(D(F(FGGG ,1A1I$+Ihl$K$K$K	!%-^^i^%H%HHHHHHHH7UW UW UW UW UW UW UW+j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	Wb )(3   (()J3)J)JKKK$ ! ! !(()J3)J)JKKK%a)>?? ) z5<<&3$V'" '"'(!) &a)?@@ %"/ J# ##$%  3 %"/ A# A A# ##$% ,BcBBqBB  !#!, "&!;!;C!;!Q!QQQQQQQ#+,H,H,HIII'HSHHWHH   ##H$@$@$B$BCCC!))#..)))(Y-=-E '	(, G G GIW!)Vy!Q!QQQQQQQQEUW UW UW UW UW UW UW+j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	Wp %h/   $$%Fs%F%FGGG  W W W$$%Fs%F%FGGG!!U%:;; %:1S88"/ R# ##$% "!U%;<< !+F  ! / V+,Mc,M,MNNTUU'(N#(N(N1(N(NOOUVVWMUW UW UW UW UW UW UW UW UW+j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	W j	Ws   A%S
)S
AR+#S
A&R+)G$S
$8KB1KKB*R+=N:S
:8R(2B1R##R((R++R/	/S
2R/	3S


SSr-   c               
   K   d S r   rn   r  s         rh   render_promptzFastMCP.render_prompt  s       srj   c               
   K   d S r   rn   r  s         rh   r  zFastMCP.render_prompt  r  rj   )PromptResult | mcp.types.CreateTaskResultc          	     T   K   t           j        j                                       4 d{V }|rgt	          t
          j                            ||          ddd|          }                     | fd	           d{V cddd          d{V  S t          d
| d j
        d|          5 }                     |           d{V }	|	t          d|          |                    |	                                           j        t!          |	j                  	 |	                    |           d{V 	 cddd           cddd          d{V  S # t&          t(          f$ r t*                              d|            t.          $ rR}
t*                              d|            j        rt3          d|          |
t3          d|d|
           |
d}
~
ww xY w# 1 swxY w Y   	 ddd          d{V  dS # 1 d{V swxY w Y   dS )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
        rc  Nr  re  rf  zprompts/getrg  c                `                         | j        j        | j        j        d          S r  )r  rh  r   r  r  s    rh   rn  z'FastMCP.render_prompt.<locals>.<lambda>  s6    d.@.@,1 '',"+ /A / / rj   ro  zprompts/get r  r  zUnknown prompt: r  r  zError rendering prompt r  )r   r   r'  rv  r9   rw  rx  GetPromptRequestParamsr/  rB   r   r  r'   r  r  r  r
   r   _renderr&   r   r  r  r  r  r(   )rg   r   r  r   r`  r  rz  r{  r  r  r  s   `  ` `     rh   r  zFastMCP.render_prompt  sW     @ >)11$1?? *	V *	V *	V *	V *	V *	V *	V3 .I<<!Y =   $"($'  
 "11&      2 	 	 	 	 	 	 	 	*	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V0 %t%%}di4  V#tWEEEEEEEE>'(C4(C(CDDD##F$>$>$@$@AAA(Y-=-E '	&* E E EI	V!'	Y!O!OOOOOOOOV V V V V V V1*	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	VF %h/   $$%Gt%G%GHHH  V V V$$%Gt%G%GHHH/ U)*LD*L*LMMSTT%&M&M&M!&M&MNNTUU	VV V V V V V V V V1*	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	V *	Vs\   AHH6A8G8/E+H+8G5#AG00G55G88G<	<H?G<	 H
H!$H!r   Tool | Callable[..., Any]rH   c                6    | 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  )rg   r   s     rh   r  zFastMCP.add_tool  s     #,,T222rj   c                   t           j        j        rt          j        dt
          d           	 | j                            ||           dS # 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.rV  rW  NzTool z
 not foundr  )
r   r   rY  rZ  rq   r%   r   remove_toolKeyErrorr'   )rg   r   r   s      rh   r  zFastMCP.remove_tool  s     0 	M@)	   	 ,,T7;;;;; 	 	 	#$>D$>$>$>??TI>>>>>> 	s   A 8B)r   r   titledescriptionr   tagsoutput_schemar   exclude_argsr   r   tasktimeoutr   
name_or_fnro   str | int | Noner	  r
  r  set[str] | Noner  dict[str, Any] | NotSetT | Noner   'ToolAnnotations | dict[str, Any] | Noner  list[str] | Noner   r   (AppConfig | dict[str, Any] | bool | Noner  bool | TaskConfig | Noner  float | None"AuthCheck | list[AuthCheck] | Nonec                   d S r   rn   rg   r  r   r   r	  r
  r   r  r  r   r  r   r   r  r  r   s                   rh   r   zFastMCP.tool#  s	    & Crj   Callable[[F], F]c                   d S r   rn   r  s                   rh   r   zFastMCP.tool8  s	    & 3rj   str | AnyFunction | NonetCallable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool]c                   |3|dur/|rt          |          ni }|du rd|d<   nt          |          |d<   | 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")
            ```
        NFTr   )r   r   r	  r
  r   r  r  r   r  r   r  r  r   )r   r"   r   r   r   )rg   r  r   r   r	  r
  r   r  r  r   r  r   r   r  r  r   results                    rh   r   zFastMCP.toolM  s    P ?s%//!%-4:::2Dd{{!T

4S99T
 %**#'#%)t/M + 
 
" rj   r  Resource | Callable[..., Any]Resource | ResourceTemplatec                6    | 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)rg   r  s     rh   r%  zFastMCP.add_resource  s     #00:::rj   r  r1   c                6    | 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)rg   r  s     rh   r'  zFastMCP.add_template  s     #00:::rj   )r   r   r	  r
  r   	mime_typer  r   r   r   r  r   r(  #Annotations | dict[str, Any] | Nonec                  t          |t                    st          d          t          ||          }t          |t                    r,|j        t          d          |j        t          d          |3|dur/|
rt          |
          ni }
|du rd|
d<   nt          |          |
d<   | 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 @resourceNu   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  r   r#   r!   r  r  r   r   r"   r   r  r   )rg   r  r   r   r	  r
  r   r(  r  r   r   r   r  r   inner_decorators                  rh   r  zFastMCP.resource  s4   J #s## 	<   )i88	 c9%% 
	+ K  
 ~) Y  
 ?s%//!%-4:::2Dd{{!T

4S99T
 .77##)t/M 8 
 
 rj   r  Prompt | Callable[..., Any]r,   c                6    | 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)rg   r  s     rh   r.  zFastMCP.add_prompt?  s     #..v666rj   	r   r   r	  r
  r   r  r   r  r   c       	            d S r   rn   rg   r  r   r   r	  r
  r   r  r   r  r   s              rh   r  zFastMCP.promptJ  s	     Crj   c       	            d S r   rn   r1  s              rh   r  zFastMCP.promptZ  s	     3rj   |Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt]c       	        \    | j                             |||||||||	|	n| 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")
            ```
        Nr/  )r   r  r   r1  s              rh   r  zFastMCP.promptj  sO    n #**#)t/M + 
 
 	
rj   r   r   as_proxy
tool_namesdict[str, str] | Noneprefixc           	     \   ddl }ddlm} |, |j        dt          d           ||}nt          d          |J |j        dt          d           |r0dd	lm} t          ||          st          
                    |          }| j        r:|j        s3t                              d
| j        d|j        d|j        d            ||          }	|r@d |                                D             }
|	                    t#          |
                    }	|                     |	|pd           dS )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' insteadrV  rW  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.r]   zParent server z0 has mask_error_details=True but mounted server z does not. Error details from z^ may leak through to clients. Set mask_error_details=True on the child server to prevent this.c                6    i | ]\  }}|t          |           S )r  rK   )r   old_namenew_names      rh   
<dictcomp>z!FastMCP.mount.<locals>.<dictcomp>,  s:       &Hh -8<<<  rj   r2  r3  )rZ  )fastmcp.server.providers.fastmcp_providerr:  rq   r%   r  fastmcp.server.providers.proxyr^   r   r   r5  r  r  warningr   itemswrap_transformrC   r   )rg   r   r4  r5  r6  r8  rZ  r:  r^   r5  r   s              rh   mountzFastMCP.mount  s   ` 	MMMMMM HMO)   
  "		 !OPPPHMK *     6GGGGGG!&,77 6$--f55F # 	F,F 	NNP P P"(+P P;P P P   -_V44  	J *4*:*:*<*<  J  ..}Z/H/HIIH 	(io2>>>>>rj   c           	     :  K   ddl } |j        dt          d           dd
}|                                 d{V D ];}|r"|                    d| d|j         i          }|                     |           <|                                 d{V D ]O}|r6 |t          |j	                  |          }|                    d|i          }| 
                    |           P|                                 d{V D ]B}|r) ||j        |          }	|                    d|	i          }|                     |           C|                                 d{V D ];}
|r"|
                    d| d|
j         i          }
|                     |
           <|j        t"          k    rddl m}  |dt$          d           |r0t&                              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.

        .. 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() insteadrV  rW  r  r  r8  rc   c                ~    t                               |           }|r |                                \  }}| | d| S | S )uG   Add prefix to resource URI: protocol://path → protocol://prefix/path./)URI_PATTERNmatchgroups)r  r8  rI  protocolpaths        rh   add_resource_prefixz2FastMCP.import_server.<locals>.add_resource_prefixe  sL    %%c**E 4!&$"3F33T333Jrj   r   _)updateuri_template)rq   zeWhen importing from a server with a lifespan, the lifespan from the imported server will not be used.)rh  categoryrX  [z] Imported server z with prefix '')r  r  r8  r  rc   r  )rZ  rq   r%   rH  
model_copyr   r  rI  r  r  r%  rJ  rP  r'  rK  r.  r   r   RuntimeWarningr  r{   )rg   r   r8  rZ  rM  r   r  new_urir  new_uri_templater  rq   s               rh   import_serverzFastMCP.import_server5  s     P 	>%	
 	
 	
 	
	 	 	 	 !++-------- 	  	 D Qv&7N7N497N7N.OPPMM$ %3355555555 	( 	(H H--c(,.?.?HH#..ug6F.GGh''''$<<>>>>>>>> 	( 	(H #6#6x7Lf#U#U #..*,<= /   h'''' #//11111111 	$ 	$F W**6f;T;Tv{;T;T2U*VVOOF####///%%%%%%D'     	ILLUDIUUUUFUUU     LLGTYGG&+GGHHHHHrj   OpenAPI Serveropenapi_specr   re  httpx.AsyncClient | None
route_mapslist[RouteMap] | Noneroute_map_fnOpenAPIRouteMapFn | Nonemcp_component_fnOpenAPIComponentFn | None	mcp_namesvalidate_outputr   r    c
           
     L    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)rZ  re  r\  r^  r`  rb  r  rc  r   r   rn   )providers.openapirg  )clsrZ  re  r   r\  r^  r`  rb  r  rc  r   rg  r5  s                rh   from_openapizFastMCP.from_openapi  sf    J 	766666,_%!%-+	
 	
 	
 s?
??h???rj   httpx_client_kwargsc	           	         ddl m}
 |i }|                    dd           t          j        d
dt          j        |          i|}|p|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.
        re  rf  Nbase_urlzhttp://fastapi	transport)r   )rZ  re  r\  r^  r`  rb  r  rh  rn   )ri  rg  
setdefaultr  AsyncClientASGITransportr	  openapi)rj  r   r   r\  r^  r`  rb  rl  r  r   rg  re  server_namer5  s                 rh   from_fastapizFastMCP.from_fastapi  s    > 	766666&"$&&z3CDDD" 
 
)c222
!
 

 'ci,_!%-
 
 
 sFzFFXFFFrj   backend}Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | strr^   c                v    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`rV  rW  )r   r   rY  rZ  rq   r%   create_proxy)rj  rv  r   s      rh   r5  zFastMCP.as_proxy	  sO    6 0 	MT)	    G00x000rj   c                ~    | j         }|| dt          j        d           S | d| dt          j        d           S )N-rV  )rk   secrets	token_hex)rj  r   
class_names      rh   r  zFastMCP.generate_name'	  sT    \
< 997#4Q#7#7999 @@4@@'*;A*>*>@@@rj   )NN),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   rd   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   )rc   r  )rc   r   )r   r   rc   r   )rc   r#  )rc   r=   )r'  r(  r)  r*  rc   r   )r   r8   rc   r   )r5  r>   r4  r  rc   r   )r   r7  rc   r7  )rc   r?  )rP  rD   rc   r   )rS  r  rT  rL   rc   r   )r\  r  rc   r   )r`  rd   rc   ra  r   )r   r  r   r~  rc   r  )r`  rd   rc   r  )r  r  r   r~  rc   r  )r`  rd   rc   r  )r  r  r   r~  rc   r  )r`  rd   rc   r  )r   r  r   r~  rc   r  )r   r  r  r  r   r~  r`  rd   r  r   rc   rI   )r   r  r  r  r   r~  r`  rd   r  rA   rc   r  )r   r  r  r  r   r~  r`  rd   r  r  rc   r  )
r  r  r   r~  r`  rd   r  r   rc   r0   )
r  r  r   r~  r`  rd   r  rA   rc   r  )
r  r  r   r~  r`  rd   r  r  rc   r  )r   r  r  r  r   r~  r`  rd   r  r   rc   r-   )r   r  r  r  r   r~  r`  rd   r  r  rc   r  )r   r  rc   rH   )r   r  r   r   rc   r   ) r  ro   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  rc   ro   ) 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  rc   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  rc   r  )r  r"  rc   r#  )r  r1   rc   r1   )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  rc   r  )r  r,  rc   r,   )r  ro   r   r   r   r  r	  r   r
  r   r   r   r  r  r   r  r  r  r   r  rc   ro   )r  r   r   r   r   r  r	  r   r
  r   r   r   r  r  r   r  r  r  r   r  rc   r  )r  r  r   r   r   r  r	  r   r
  r   r   r   r  r  r   r  r  r  r   r  rc   r3  )NNNN)r   r   r4  r   r5  r   r6  r7  r8  r   rc   r   )r   r   r8  r   rc   r   )NrY  NNNNNT)rZ  r   re  r[  r   r  r\  r]  r^  r_  r`  ra  rb  r7  r  r  rc  rd   r   r   rc   r    )NNNNNNN)r   r   r   r   r\  r]  r^  r_  r`  ra  rb  r7  rl  r  r  r  r   r   rc   r    )rv  rw  r   r   rc   r^   )r   r   rc   r  )6rk   rl   rm   r   r  propertyr   r   setterr   r   r   r&  r/  r1  r   r>  rG  r   r[  r^  rH  r  r  rI  r  r  rJ  r  r  rK  r  r  r   r  r  r  r  r  rQ   r   r%  r'  r  r.  r  rD  rX  classmethodrk  ru  r5  r  __classcell__)r  s   @rh   r   r     se
         #'I

 -1"&-1$(26/3157;<@15*.$(/3%)!4837JN:>/I
 I
 I
 I
 I
 I
 I
 I
V7 7 7 7 % % % X% - - - X- . . . . ( ( ( X( , , , X, 0 0 0 X0 	$ 	$ 	$ X	$	$ 	$ 	$ 	$+ + + + DF < < < < < < < < 
 
 
 
0
 
 
 
 
 
:+ + + +(G G G G"    :> - - - - - - - -` 8<      @ 8<4A 4A 4A 4A 4A 4A 4An )-0 0 0 0 0 0 0 0f 7;      @ 7;0E 0E 0E 0E 0E 0E 0Ef )-) ) ) ) ) ) ) )X 7;      @ 7;4M 4M 4M 4M 4M 4M 4Ml <@ % % % % % % % %P 8<      @ 8<0C 0C 0C 0C 0C 0C 0Cd  ,0
 '+#     X  ,0)
 '+#) ) ) ) ) X) ,0@P
 '+#%)@P @P @P @P @P @PD 
 '+#     X 
 '+#) ) ) ) ) X) '+#%)OW OW OW OW OW OWb  ,0
 '+#     X  ,0)
 '+#) ) ) ) ) X) ,0JV
 '+#%)JV JV JV JV JV JVX3 3 3 3    : 
  $( "&-1 $9??C)-&*8<)- $37#     X(  "&  $( "&-1 $9??C)-&*8<)- $37#     X, 04a  $( "&-1 $9??C)-&*8<)- $37#a a a a a aF; ; ; ;	; 	; 	; 	;  $( "&-1 $ $;?&*8<)-37u u u u u un	7 	7 	7 	7 
  $( "&-1 $&*)-37     X  "&  $( "&-1 $&*)-37     X" 04b
  $( "&-1 $&*)-37b
 b
 b
 b
 b
 b
N !% $,0!e? e? e? e? e?T "aI aI aI aI aIF  ,0$,0156:+/ $ $0@ 0@ 0@ 0@ [0@d   ,0156:+/59 $4G 4G 4G 4G [4Gl "1 "1 "1 ["1H A A A A [A A A A Arj   r   targetrw  r   r   r^   c                <    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   )r^   _create_client_factoryclient_factoryrn   )r@  r^   r  )r  r   r^   r  r  s        rh   ry  ry  6	  sf    V       
 ,+F33N<  %
  rj   )r   r   rc   r   )rc   r   )r   rH   rc   rd   )r   r   rc   r   )r   r   rc   r   )r  rw  r   r   rc   r^   )r   
__future__r   r  loggingrer|  rZ  collections.abcr   r   r   r   
contextlibr   r	   dataclassesr
   	functoolsr   pathlibr   typingr   r   r   r   r   r   r   r  	mcp.typesrw  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   r  starlette.routingr   typing_extensionsr    r   fastmcp.serverfastmcp.apps.configr!   r"   r#   fastmcp.exceptionsr$   r%   r&   r'   r(   r)   r*   fastmcp.mcp_configr+   fastmcp.promptsr,   fastmcp.prompts.baser-   fastmcp.prompts.function_promptr.   fastmcp.resources.baser/   r0   fastmcp.resources.templater1   fastmcp.server.authr2   r3   r4   r5   fastmcp.server.lifespanr6   fastmcp.server.low_levelr7   fastmcp.server.middlewarer8   r9   fastmcp.server.mixinsr:   r;   r<   fastmcp.server.providersr=   r>   "fastmcp.server.providers.aggregater?   fastmcp.server.tasks.configr@   rA   fastmcp.server.telemetryrB   fastmcp.server.transformsrC   rD   $fastmcp.server.transforms.visibilityrE   rF   fastmcp.settingsrG   DuplicateBehaviorSettingfastmcp.tools.baserH   rI   fastmcp.tools.function_toolrJ   fastmcp.tools.tool_transformrL   fastmcp.utilities.componentsrM   rN   fastmcp.utilities.loggingrO   fastmcp.utilities.typesrP   rQ   rR   fastmcp.utilities.versionsrS   rT   fastmcp.clientrU   fastmcp.client.clientrV   fastmcp.client.samplingrW   fastmcp.client.transportsrX   rY    fastmcp.server.providers.openapirZ   OpenAPIComponentFnr[   r\   OpenAPIRouteMapFnr@  r^   rk   r  Filterr`   	getLogger	addFilterro   r   r   r   	TransportcompilerH  r  r   r   r   r   r   r   r   ry  rn   rj   rh   <module>r     s   ; ; ; " " " " " "   				                                        P P P P P P P P P P P P P P P P P P      ; ; ; ; ; ; 1 1 1 1 1 1 3 3 3 3 3 3 6 6 6 6 6 6 * * * * * *                  ? ? ? ? ? ? ' ' ' ' ' ' " " " " " "              
	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 ) ( ( ( ( ( " " " " " " - - - - - - : : : : : : ; ; ; ; ; ; ; ; 7 7 7 7 7 7 U U U U U U U U U U U U , , , , , , 3 3 3 3 3 3 C C C C C C C C S S S S S S S S S S < < < < < < < < @ @ @ @ @ @ < < < < < < < < 0 0 0 0 0 0        V U U U U U U U J J J J J J / / / / / / / / 4 4 4 4 4 4 < < < < < < J J J J J J J J 0 0 0 0 0 0 E E E E E E E E E E       
  <%%%%%%444444777777KKKKKKKKRRRRRR999999PPPPPP;;;;;;	H		F F F F F7> F F F
  . / / 9 9  ""   GCxS)***@A #
E#
E# ]# /	#
 u# p# s# !# T# 8# <# :#   A# Y# O#  g!#    (

 

 

 

 =>	 bj-..  "=o"NN 
' ' ' '&! ! ! !4   2 	 	 	 	   0    !   W A W A W A W A W AOW A W A W A~@4 4 4 4 4 4rj   