
    kKj             
      j   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 ddlmZmZ ddlmZ ddlmZ ddlmZ dd	lmZmZmZmZmZmZmZ ddlZddlZdd
l m!Z! ddl"m#Z# ddl$m%Z% ddl&m'Z' ddl(m)Z) ddlm*Z*m+Z+m,Z,m-Z- ddl.m/Z/ ddl.m0Z1 ddl2m3Z3 ddl4m5Z5 ddl6Z6ddl7Z6ddl8m9Z9m:Z:m;Z; ddl<m=Z=m>Z>m?Z?m@Z@mAZAmBZBmCZCm0Z0 ddlDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZMmNZN ddlOmPZP ddlQmRZRmSZSmTZTmUZU ddlVmWZW ddlXmYZY ddlZm[Z[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	 	 	 	 dmd7Z G d8 d9ej8                        Z ej<                  d:      j?                   e               ed;e
d<ef   =      Zed>   Zsi d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdRdTdRdUdVdWdXdYdZd[d\Zd]ed^<   dnd_Zed`   Z ejJ                  da      Ze
dbgee'   f   ZdodcZdpddZdpdeZedqdf       Z	 	 	 	 drdgZ G dh die      Z G dj dkefe_e`eaee'         Z	 	 	 	 	 	 dsdlZy)tz5FastMCP - A more ergonomic interface for MCP servers.    )annotationsN)AsyncIterator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)CallNext
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                x   | y | j                   %| j                  | j                  | j                   }nG| j                  | j                  | j                   dj                         D ci c]
  \  }}||| }}}|sy t        j
                  j                  j                  j                  dd|ii      S c c}}w )N)gtelteqfastmcpversion)	ra   r_   r`   itemsmcptypesRequestParamsMetamodel_validate)rc   version_valuekeyvalues       f/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/server/server.py_version_request_metarn   h   s     zz'++"5'**:L.5jj
 {{jjjj eg	

U
   J 	 
 99""''66	Y./ 
s   *B6c                      e Zd ZddZy)_SuppressUnlistedToolWarningc                &    d|j                         vS )Nznot listed, no validation)
getMessage)selfrecords     rm   filterz#_SuppressUnlistedToolWarning.filter   s    *&2C2C2EEE    N)rt   zlogging.LogRecordreturnbool)__name__
__module____qualname__ru    rv   rm   rp   rp      s    Frv   rp   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_KWARGSc                    | D ]"  }|t         v st        d| dt         |           | r$t        ddj                  d | D                     y)z2Raise helpful TypeErrors for kwargs removed in v3.zFastMCP() no longer accepts `z`. z.FastMCP() got unexpected keyword argument(s): z, c              3  2   K   | ]  }t        |        y wN)repr).0ks     rm   	<genexpr>z(_check_removed_kwargs.<locals>.<genexpr>   s     F_X^STtAwX^s   N)r   	TypeErrorjoin)kwargsrk   s     rm   _check_removed_kwargsr      si    /!/uC8L7MN  
 <TYYF_X^F_=_<`a
 	
 rv   )stdiohttpssezstreamable-httpz^([^:]+://)(.*?)$FastMCP[LifespanResultT]c                 X    ddl m}  | j                         dk(  }|ryddlm} d |       fS )a@  Get auth context for the current request.

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

    Uses late import to avoid circular import with context.py.
    r   )_current_transportr   )TN)get_access_tokenF)fastmcp.server.contextr   getfastmcp.server.dependenciesr   )r   is_stdior   s      rm   _get_auth_contextr      s2     :!%%'72H<#%&&rv   c                B   | j                   }|sy|j                  d      }t        |t              sy |j                  d      y|j                  d      }t        |t              sy|j                  d      }t        |t              syt        |      dk(  xr |d   dk(  S )u  Check whether a tool is handled specially as backend tool

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

    They are handled specially for in various ways - e.g. they are looked
    up via get_app_tool(), and don't appear in the tools/list output.
    (FIXME: the latter isn't correct behavior according to the mcp-apps spec.)

    Returns True (a backend tool) when:
    - The tool has ``meta.fastmcp.app``.
    - The tool has ``meta.ui.visibility``.
    - The visibility is precisely ``["app"]``.

    Returns False otherwise.
    Frb   appui
visibility   r   )metar   
isinstancedictlistlen)toolr   rb   r   r   s        rm   _is_backend_toolr      s    $ 99Dhhy!Ggt$w{{5!	$Bb$%Jj$'z?a:JqMU$::rv   c                    | j                   }|sy|j                  d      }t        |t              sy|j                  d      }t        |t              sy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   r   )r   r   r   r   r   )r   r   r   r   s       rm   _is_app_visibler      sS     99D	$Bb$%Jj$'Jrv   c                  K   i  yw)zDefault lifespan context manager that does nothing.

    Args:
        server: The server instance this lifespan is managing

    Returns:
        An empty dictionary as the lifespan result.
    Nr|   )servers    rm   default_lifespanr     s      Hs   	c                .     t         	 	 	 	 d fd       }|S )Nc                  K   j                   t        u ri  y j                  st        d      j                   y w)Na  FastMCP server has a lifespan defined but no lifespan result is set, which means the server's context manager was not entered.  Are you running the server in a way that supports lifespans? If so, please file an issue at https://github.com/PrefectHQ/fastmcp/issues.)	_lifespanr   _lifespan_result_setRuntimeError_lifespan_result)low_level_serverfastmcp_servers    rm   wrapz_lifespan_proxy.<locals>.wrap!  sJ      ##'77H22\ 
 ---s   A A)r   zLowLevelServer[LifespanResultT]rw   zAsyncIterator[LifespanResultT])r   )r   r   s   ` rm   _lifespan_proxyr     s.    
 .9.	'. . Krv   c                      e Zd ZU dZded<   y)
StateValuez(Wrapper for stored context state values.r   rl   N)ry   rz   r{   __doc____annotations__r|   rv   rm   r   r   4  s
    2Jrv   r   c                  `    e Zd Z	 	 dDddddddddddddddddddddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dE fdZdFdZedFd       ZedGd       Zej                  dHd       ZedGd	       Z	edGd
       Z
edId       ZedJd       Z	 	 	 	 	 	 dKdZdLdZdddM fdZdNdZdO fdZdPdZ	 	 	 	 	 	 dQdZdRdZdddS fdZ	 dT	 	 	 	 	 dU fdZ	 dT	 	 	 	 	 dU fdZdd	 	 	 dV fdZ	 dT	 	 	 	 	 dW fdZ	 dT	 	 	 	 	 dW fdZdd	 	 	 dX fdZ	 dT	 	 	 	 	 dY fdZ	 dT	 	 	 	 	 dY fd ZdddZ fd!Z	 dT	 	 	 	 	 d[ fd"Z	 dT	 	 	 	 	 d[ fd#Z e!	 dTdddd$	 	 	 	 	 	 	 	 	 	 	 d\d%       Z"e!	 dTddd&	 	 	 	 	 	 	 	 	 	 	 d]d'       Z"	 dTdddd$	 	 	 	 	 	 	 	 	 	 	 d^d(Z"e!dddd$	 	 	 	 	 	 	 	 	 d_d)       Z#e!ddd&	 	 	 	 	 	 	 	 	 d`d*       Z#dddd$	 	 	 	 	 	 	 	 	 dad+Z#e!	 dTdddd$	 	 	 	 	 	 	 	 	 	 	 dbd,       Z$e!	 dTddd&	 	 	 	 	 	 	 	 	 	 	 d]d-       Z$	 dTdddd$	 	 	 	 	 	 	 	 	 	 	 dcd.Z$ddd/Z%dTded0Z&e!dddddde'ddddddddd1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dfd2       Z(e!	 dTdddddde'ddddddddd1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dgd3       Z(	 dTdddddde'ddddddddd1	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dhd4Z(	 	 	 	 did5Z)djd6Z*ddddddddddddd7	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dkd8Z+dld9Z,e!dddddddddd:		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dmd;       Z-e!	 dTdddddddddd:		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dnd<       Z-	 dTdddddddddd:		 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dod=Z-	 	 	 	 dp	 	 	 	 	 	 	 	 	 	 	 dqd>Z.	 dT	 	 	 	 	 drd?Z/e0	 	 	 	 	 	 	 	 ds	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dtd@       Z1e0	 	 	 	 	 	 	 du	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dvdA       Z2e0	 	 	 	 	 	 dwdB       Z3e0dTdxdC       Z4 xZ5S )yFastMCPNT)rc   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experimental_capabilitiesc                  t        |       t        | 	          |xs d| _        ||nd| _        d | _        d | _        g | _        |xs
 t               | _	        t        t           | j                  t        d      | _        t        | j                        | _        | j                  | j                         |xs g D ]  }| j                  |        |	xs g D ]  }| j!                  |        ||nt"        j$                  j&                  | _        ||dk  rt+        d      || _        |
t/        t0        t2           |
      | _        n t/        t0        t2           t6              | _        d | _        d| _        d| _        t?        j@                         | _!        t?        jD                         | _#        tI        t2           | |xs | jK                         tM        |      xs t"        jN                  |||tQ        |       	      | _)        || _*        |r=|D ]8  }tW        |tX              stY        jZ                  |      }| j]                  |       : ||nt"        j$                  j^                  | _/        ||nt"        j$                  j`                  | _0        |xs i | _1        te        |xs g       | _3        |r&dd
l4m5} | jf                  jm                   |              | jo                          || _8        |xs d| _9        y )Nr   Ffastmcp_state)	key_valuepydantic_modeldefault_collection)r   r   z)list_page_size must be a positive integer)r   )rb   namerc   instructionsr   r   r   )DereferenceRefsMiddlewarefallback):r   super__init___on_duplicate_support_tasks_by_default_docket_worker_additional_http_routesr   _state_storager   r   _state_storer=   _local_provideradd_provideradd_transformrb   settingsr   _mask_error_details
ValueError_list_page_sizer   LifespanCallabler   r   r   r   r   _lifespan_ref_countasyncioLock_lifespan_lockEvent_startedr6   generate_namerM   __version__r   _mcp_serverr   r   rH   from_functionadd_toolr   r   r   r   r   %fastmcp.server.middleware.dereferencer   append_setup_handlersr   r   )rs   r   r   rc   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                               rm   r   zFastMCP.__init__A  s   6 	f% 	7C7Mv 9>8Iuu& 8:$ .A-QKM9H9T))%.:
 /<++/
 	$../bAa  ! !r!Aq! " "- !!44 	  %.A*=HII+9 @D 18ADN ""2?"CEUVDN8<*/!() ,3LLN'.}} BPB
 -++-#G,C0C0C%#$D9
B
 *.	!$---d3Dd#  '2 $!!99 	$  + !!22 	 &+ 	& -11Ar,B OO""#<#>? 	8H%3 	&rv   c                L    t        |       j                   d| j                  dS )N())typery   r   rs   s    rm   __repr__zFastMCP.__repr__  s$    t*%%&a		}A66rv   c                .    | j                   j                  S r   )r   r   r  s    rm   r   zFastMCP.name  s    $$$rv   c                .    | j                   j                  S r   r   r   r  s    rm   r   zFastMCP.instructions  s    ,,,rv   c                &    || j                   _        y r   r  )rs   rl   s     rm   r   zFastMCP.instructions  s    (-%rv   c                .    | j                   j                  S r   )r   rc   r  s    rm   rc   zFastMCP.version  s    '''rv   c                .    | j                   j                  S r   )r   r   r  s    rm   r   zFastMCP.website_url  s    +++rv   c                p    | j                   j                  g S t        | j                   j                        S r   )r   r   r   r  s    rm   r   zFastMCP.icons  s0    !!)I((..//rv   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    rm   local_providerzFastMCP.local_provider  s     ###rv   c                   K   |}t        | j                        D ]/  }|}||f	 	 	 	 	 	 	 dd}t        t        t        t        f   |      }1  ||       d{   S 7 w)z)Builds and executes the middleware chain.c                0   K    || |       d {   S 7 wr   r|   )contextmw	call_nexts      rm   wrappedz(FastMCP._run_middleware.<locals>.wrapped  s     
  3333s   N)r  MiddlewareContext[Any]r  r8   r  CallNext[Any, Any]rw   r   )reversedr   r   r7   r   )rs   r  r  chainr  
next_chainr  s          rm   _run_middlewarezFastMCP._run_middleware  s      4??+B-2J "$0:4/44 .4 	4 #s(+W5E , 7^###s   AAAAc                :    | j                   j                  |       y r   )r   r  )rs   r   s     rm   add_middlewarezFastMCP.add_middleware  s    z*rv    	namespacec               (    t         |   ||       y)a\  Add a provider for dynamic tools, resources, and prompts.

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

        Args:
            provider: A Provider instance that will provide components dynamically.
            namespace: Optional namespace prefix. When set:
                - Tools become "namespace_toolname"
                - Resources become "protocol://namespace/path"
                - Prompts become "namespace_promptname"
        r'  N)r   r   )rs   providerr(  r  s      rm   r   zFastMCP.add_provider  s     	X;rv   c                \    ddl m}m} |D cg c]  } ||      r ||      n| c}S c c}w )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_wire))fastmcp.server.providers.prefab_synthesisr,  r-  )rs   r   r,  r-  r  s        rm   _rewrite_prefab_uriszFastMCP._rewrite_prefab_uris"  s?    	
 QV
PU1_Q-?&q)QFPU
 	
 
s   )c                  K   t        t        | 	          d{         }|D cg c]  }t        |t              s| }}|D cg c]  }t        |t
              s| }}|D cg c]  }t        |t              s| }}|D cg c]  }t        |t              s| }}| j                  D ]f  }|j                  |       d{   }|j                  |       d{   }|j                  |       d{   }|j                  |       d{   }h g ||||S 7 c c}w c c}w c c}w c c}w 7 r7 [7 D7 -w)zGet task-eligible components with all transforms applied.

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

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

        Args:
            transform: The transform to add.

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

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

        .. deprecated::
            Use ``add_transform(ToolTransform({...}))`` instead.
        zladd_tool_transformation is deprecated. Use server.add_transform(ToolTransform({tool_name: config})) instead.   
stacklevelN)rb   r   deprecation_warningswarningsr   r$   r   rC   )rs   	tool_nametransformations      rm   add_tool_transformationzFastMCP.add_tool_transformationk  sE     00MMT)	 	=)^)DEFrv   c                r    t         j                  j                  rt        j                  dt
        d       yy)zRemove a tool transformation.

        .. deprecated::
            Tool transformations are now immutable. Use enable/disable controls instead.
        zremove_tool_transformation is deprecated and has no effect. Transforms are immutable once added. Use server.disable(keys=[...]) to hide tools instead.r?  r@  N)rb   r   rB  rC  r   r$   )rs   
_tool_names     rm   remove_tool_transformationz"FastMCP.remove_tool_transformation|  s1     00MM) * 1rv   run_middlewarec                  K   t         j                  j                  j                         4 d{   }|r]t	        t
        j                  j                  d      ddd|      } j                  | fd	       d{   cddd      d{    S t        dd j                  d
d      5  t        t        
 5          d{         }t        |       d{   }|D cg c]  }t        |      st!        |      r| }} j#                  |      }t%               \  }}g }|D ]O  }	|s:|	j&                  .t)        ||	      }	 t+        |	j&                  |       d{   s>	 |j/                  |	       Q |cddd       cddd      d{    S 7 g7 7 7 7 c c}w 7 G# t,        $ r Y w xY w7 (# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  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.
        rb   Nz
tools/list)methodclientrequestmessagesourcer  rN  fastmcp_contextc                (    j                  d      S NFrJ  )r2  r  rs   s    rm   <lambda>z$FastMCP.list_tools.<locals>.<lambda>  s    dooUo.Srv   r  r  r   r&  token	component)rb   r   r  Contextr9   re   rf   ListToolsRequestr#  rB   r   r   r   r2  rE   rF   r   r/  r   r   r2   r4   r#   r  )rs   rK  ctx
mw_contextr   r  	skip_authr[  
authorizedr   r  s   `         rm   r2  zFastMCP.list_tools  s     >>))11$1??3.II66l6K#"'$'
 "11&S 2   @?? \<FBO 57#5#7786u==$)WEqZ]CSTUCVEW 11%8#4#6 	5)+
!D$)>)F%)8C)H#H#H ( $I %%d+ " "3 PO @?? @$ 8=W $I1 %$%K @ PO @????s  /G2FG2A
GFGG2F G2G0F?F#F?F%F?'F'8F'F'AF?F.$F,
%F.)F??	GG2F=G2G G2#F?%F?'F?,F..	F:	7F?9F:	:F?=G2?G	GG2GG2G/#G&$G/+G2c                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)ac  Get a tool by name via aggregation from providers.

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

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

        Returns:
            The tool if found and authorized, None if not found or unauthorized.
        NrZ  )r   	_get_toolr   r   r2   r4   r#   )rs   r   rc   r   ra  r[  r_  r  s          rm   rd  zFastMCP._get_tool  s      W&tW55< -.	5TYY2ET:C,TYY<<< =
 t 6 =% K   A?A,/A?A0 !A."A0 &A?(A?.A0 0	A<9A?;A<<A?c                  K   t         |   ||       d{   }|yt        |g       d{   }|r!t        |d         rt	        |d         s|d   S |yt         |           d{   D cg c]  }|j                  |k(  s| }}t        t        |       d{         }|D cg c]  }t        |      st	        |      r| }}t               \  }}	g }
|D ]O  }|s:|j                  .t        |	|      }	 t        |j                  |       d{   s>	 |
j                  |       Q |
syt        |
t              S 7 /7 7 c c}w 7 c c}w 7 A# t        $ r Y w xY ww)a_  Get a tool by name, filtering disabled tools.

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

        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   rZ  rk   )r   get_toolrE   rF   r   r2  r   r   r   r   r2   r4   r#   r  maxrS   )rs   r   rc   r   r   r  	all_toolsenabledra  r[  rb  r_  r  s               rm   rh  zFastMCP.get_tool  st    & W%dG44< /v66Za)2B582L8O
 &+g&8&: : :M :1affnQ :	M7	BBC	'Ui:a=AQRSAT1iU,.	5!#
A!3!;!0!===  > a   :#344C 5
 7 !;MBU >) s   E+EE+E	;E+*E+E+1EE
E+E E+,E=E	E1E+?EEE*E+	E+E+E+E+E	E(%E+'E((E+c                  K   t         j                  j                  j                         4 d{   }|r?t	        i ddd|      } j                  | fd       d{   cddd      d{    S t        dd j                  d	d
      5  t        t         )          d{         }t        |       d{   }|D cg c]  }t        |      s| }}ddlm} |j                   |        d{          t!               \  }}g }	|D ]O  }
|s:|
j"                  .t%        ||
      }	 t'        |
j"                  |       d{   s>	 |	j+                  |
       Q |	cddd       cddd      d{    S 7 Q7 $7 7 7 c c}w 7 7 I# t(        $ r Y w xY w7 *# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  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.
        rM  NrO  rP  zresources/listrQ  c                (    j                  d      S rV  )r3  rW  s    rm   rX  z(FastMCP.list_resources.<locals>.<lambda>%  s    d.A.AQV.A.Wrv   rY  resourcer&  r   )synthesize_prefab_resourcesrZ  )rb   r   r  r]  r9   r#  rB   r   r   r   r3  rE   rF   r.  ro  extendr   r   r2   r4   r#   r  )rs   rK  r_  r`  r8  rro  ra  r[  rb  rn  r  s   `          rm   r3  zFastMCP.list_resources  s     >>))11$1??3.#"+$'
 "11&W 2   @??  "2DIIz2 !uw'='?!?@	":9"EE	(1C	1Z]Q		C
   'B4'H!HI#4#6 	5-/
 )H$)B)J%)8)L#L#L ( $M %%h/ !* "9  @?? @& "@EC "I $M1 %$%Q @  @????s  /GFG,G	#F$G	'G3F
4G9G	F+)F*F+ FF+	FFF+<F=7F+5FF
FF+)	G	2G>F)?GG	
GF+F+F+F	F&	#F+%F&	&F+)G+F4	0G	7GGG	GGGGc                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)ap  Get a resource by URI via aggregation from providers.

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

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

        Returns:
            The resource if found and authorized, None if not found or unauthorized.
        NrZ  )r   _get_resourcer   r   r2   r4   r#   )rs   urirc   rn  ra  r[  r_  r  s          rm   rs  zFastMCP._get_resourceG  s      .sG<< -.	5X]]6EX>C,X]]C@@@ A
 x = A% re  c                  K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         r|d   S |yt         |           d{   D cg c]  }t        |j                        |k(  s| }}t        t        |       d{         }|D cg c]  }t        |      s| }}t               \  }}	g }
|D ]O  }|s:|j                  .t        |	|      }	 t        |j                  |       d{   s>	 |
j                  |       Q |
syt        |
t              S 7 7 
7 c c}w 7 c c}w 7 A# t        $ r Y w xY ww)a"  Get a resource by URI, filtering disabled resources.

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

        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   rZ  rg  )r   get_resourcerE   rF   r3  strrt  r   r   r   r2   r4   r#   r  ri  rS   )rs   rt  rc   rn  r8  rq  all_resourcesrk  ra  r[  rb  r_  r  s               rm   rv  zFastMCP.get_resourcef  se    $ -c7;; 3H:>>	IaL1Q<*/'*@*B$B$BX$Bqc!%%jTWFW$BX#;M#JJK+=mz!}1m=,.	5%'
A!3!;!0!===  > a   :#344= <
 ? %CXJ= >) s   ED5ED8-ED;E#D=D=EEE'E8E<1E.EE	E*E8E;E=EE	E	EEEEc               n   K   t         j                  j                  j                         4 d{   }|r?t	        i ddd|      } j                  | fd       d{   cddd      d{    S t        dd j                  d	d
      5  t        t        
 )          d{         }t        |       d{   }|D cg c]  }t        |      s| }}t               \  }}g }|D ]O  }	|s:|	j                  .t        ||	      }	 t!        |	j                  |       d{   s>	 |j%                  |	       Q |cddd       cddd      d{    S 7 ,7 7 7 7 c c}w 7 E# t"        $ r Y w xY w7 &# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a%  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.
        rM  NrO  rP  zresources/templates/listrQ  c                (    j                  d      S rV  )r4  rW  s    rm   rX  z1FastMCP.list_resource_templates.<locals>.<lambda>  s    d.J.J', /K /rv   rY  resource_templater&  rZ  )rb   r   r  r]  r9   r#  rB   r   r   r   r4  rE   rF   r   r   r2   r4   r#   r  )rs   rK  r_  r`  r9  r  ra  r[  rb  templater  s   `         rm   r4  zFastMCP.list_resource_templates  s     >>))11$1??3.#"5$'
 "11& 2   @??" **		# !uw'F'H!HI	":9"EE	(1C	1Z]Q		C#4#6 	557
 )H$)B)J%)8)L#L#L ( $M %%h/ !* "/ # @?? @2 "IEC $M1 %$%K @" # @????  /F5EF5,F #E"$F 'F53E$4F59F F)E&*F E(F	E*E*1FE1)E/
*E1.F	F F5F F5"F $F5&F(F*F/E11	E=	:F<E=	=F F5F	F F5FF5 F2&F)'F2.F5c                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)a  Get a resource template by URI via aggregation from providers.

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

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

        Returns:
            The template if found and authorized, None if not found or unauthorized.
        NrZ  )r   _get_resource_templater   r   r2   r4   r#   )rs   rt  rc   r|  ra  r[  r_  r  s          rm   r  zFastMCP._get_resource_template  s      7WEE -.	5X]]6EX>C,X]]C@@@ A
 x F A% re  c                  K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         r|d   S |yt         |           d{   D cg c]  }|j                  |      | }}t        t        |       d{         }|D cg c]  }t        |      s| }}t               \  }}	g }
|D ]O  }|s:|j                  .t        |	|      }	 t        |j                  |       d{   s>	 |
j                  |       Q |
syt        |
t              S 7 7 7 c c}w 7 c c}w 7 A# t        $ r Y w xY ww)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   rZ  rg  )r   get_resource_templaterE   rF   r4  matchesr   r   r   r2   r4   r#   r  ri  rS   )rs   rt  rc   r|  r9  r  all_templatesrk  ra  r[  rb  r_  r  s               rm   r  zFastMCP.get_resource_template  sw    $ 6sGDD 3H:>>	IaL1Q< !7:<<<
<yy~) < 	 

 #;M#JJK+=mz!}1m=,.	5-/
A!3!;!0!===  > a   :#344E E
 ? =

 K= >) s   ED-ED0-ED3E#D5=ED:ED<0D<41E&E?E E*E0E3E5E<EE	EEEEc               n   K   t         j                  j                  j                         4 d{   }|r?t	        i ddd|      } j                  | fd       d{   cddd      d{    S t        dd j                  d	d
      5  t        t        
 )          d{         }t        |       d{   }|D cg c]  }t        |      s| }}t               \  }}g }|D ]O  }	|s:|	j                  .t        ||	      }	 t!        |	j                  |       d{   s>	 |j%                  |	       Q |cddd       cddd      d{    S 7 ,7 7 7 7 c c}w 7 E# t"        $ r Y w xY w7 &# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  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.
        rM  NrO  rP  zprompts/listrQ  c                (    j                  d      S rV  )r5  rW  s    rm   rX  z&FastMCP.list_prompts.<locals>.<lambda>2  s    d.?.?u.?.Urv   rY  promptr&  rZ  )rb   r   r  r]  r9   r#  rB   r   r   r   r5  rE   rF   r   r   r2   r4   r#   r  )rs   rK  r_  r`  r:  r  ra  r[  rb  r  r  s   `         rm   r5  zFastMCP.list_prompts   s     >>))11$1??3.#")$'
 "11&U 2   @?? ^^TYYRTUUW%9%;;< 8 AA&-?gA1g?#4#6 	5+-
%F$)@)H%)8c)J#J#J ( $K %%f- & "# VU @?? @"  <A? $K1 %$%; @ VU @????r}  c                  K   t         |   ||       d{   }|yt               \  }}|s<|j                  0t	        ||      }	 t        |j                  |       d{   sy	 |S |S 7 T7 # t        $ r Y yw xY ww)ak  Get a prompt by name via aggregation from providers.

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

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

        Returns:
            The prompt if found and authorized, None if not found or unauthorized.
        NrZ  )r   _get_promptr   r   r2   r4   r#   )rs   r   rc   r  ra  r[  r_  r  s          rm   r  zFastMCP._get_promptI  s      w*499> -.	5V[[4EV<C,V[[#>>> ?
 v : ?% re  c                  K   t         |   ||       d{   }|yt        |g       d{   }|rt        |d         r|d   S |yt         |           d{   D cg c]  }|j
                  |k(  s| }}t        t        |       d{         }|D cg c]  }t        |      s| }}t               \  }}	g }
|D ]O  }|s:|j                  .t        |	|      }	 t        |j                  |       d{   s>	 |
j                  |       Q |
syt        |
t              S 7 7 7 c c}w 7 c c}w 7 A# t        $ r Y w xY ww)a  Get a prompt by name, filtering disabled prompts.

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

        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   rZ  rg  )r   
get_promptrE   rF   r5  r   r   r   r   r2   r4   r#   r  ri  rS   )rs   r   rc   r  r:  r  all_promptsrk  ra  r[  rb  r_  r  s               rm   r  zFastMCP.get_prompth  s]    $ w)$88> 1&::z'!*-1:(-(<(>">">Q">Q!&&D.q">Q!9+!FFG);kZ]1k;,.	5#%
A!3!;!0!===  > a   :#344= 9
 ; #?QF; >) s   ED,ED/-ED2E#D48D4<ED9ED;/D;31E%E>E ?E*E/E2E4E;E E	EEEErc   rK  	task_metac                  K   y wr   r|   rs   r   	argumentsrc   rK  r  s         rm   	call_toolzFastMCP.call_tool  s         )rc   rK  c                  K   y wr   r|   r  s         rm   r  zFastMCP.call_tool        &)r  c          
        K   ddl m} t        j                  j                  j                         4 d{   }|rut        t           t        j                  j                  ||xs i t                    ddd|	      } j                  | fd
       d{   cddd      d{    S t        d| d j                  d||      5 }	 j                  |       d{   }
|
 ||      }|w|\  }} j                  ||       d{   }
|
Vt!               \  }}|sG|
j"                  ;	 t%        ||
      }t'        |
j"                  |       d{   st)        d|      	 |
t)        d|      |	j-                  |
j/                                #j0                  t3        |
j4                        	 |
j7                  |xs i        d{   cddd       cddd      d{    S 7 7 d7 W7 7 7 # t*        $ r t)        d|      dw xY w7 J7 3# t8        $ rV}|j:                  }t=        |t>              r|jA                  d      n
tC        |      }tD        jG                  d||        d}~wtH        $ r+}tD        jK                  |jL                  d|d        d}~wt>        $ r-}tD        jG                  d||jA                  d              d}~wtN        $ r}tD        jQ                  d|       t=        |tR        jT                        r%|jV                  jX                  dk(  rt[        d      |t=        |tR        j\                        rt[        d      | j^                  rt[        d|      |t[        d|d|       |d}~ww xY w# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  Call a tool by name.

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

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

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

        Raises:
            NotFoundError: If tool not found or disabled
            ToolError: If tool execution fails
            ValidationError: If arguments fail validation
        r   )parse_hashed_backend_namerM  Nr   r  _metarO  rP  z
tools/callrQ  c                    j                  | j                  j                  | j                  j                  xs i d      S NFr  )r  rR  r   r  r  rs   r  rc   s    rm   rX  z#FastMCP.call_tool.<locals>.<lambda>  s;    dnn,,117R '',"+ /= /rv   rY  ztools/call r   )rD  rc   rZ  zUnknown tool: fn_keyr  F)include_urlz!Invalid arguments for tool %r: %szError calling tool exc_info  0Rate limited by upstream API, please retry later(Upstream request timed out, please retry: )0#fastmcp.server.providers.addressingr  rb   r   r  r]  r9   r   re   rf   rn   r#  rB   r   rh  get_tool_by_hashr   r   r2   r4   r&   r#   set_attributesget_span_attributesr  r	   rk   _runr   	__cause__r   PydanticValidationErrorerrorsrw  loggerwarningr%   logr   	Exception	exceptionhttpxHTTPStatusErrorresponsestatus_coder)   TimeoutExceptionr   )rs   r   r  rc   rK  r  r  r_  r`  spanr   hasheddigest
local_namera  r[  auth_ctxecausedetails   `  ` `              rm   r  zFastMCP.call_tool  s    H	
 >>))11$1??3./DEII;;!"+/r3G< < 
 $"'$'

 "11& 2 	 	 @??2 dV$		 *.--g-*N$N <6t<F)-3*
%)%:%:6:%NN+/@/B,Iu#,1F!0/:RV/WH1@H1U+U+U.;nTH<U.V(V ,V <'.(ABB##D$<$<$>?(Y-=-=-E '	$(( CI/P!%9?i!PPO 3 @??	 @D %O  O ,V'9 !0*7*8(A+&+/%0!0 QA @B '  KKE &e-DE 7 V 
 NN#FfU# JJ':4(%Ce   . 	 NN;U3
   P$$':4(%CD "!U%:%:;::11S8"+ R##$% "!U%;%;<'F ! //'*=dX(FGQN#&9$A3$GHaO!PK 3 @????sD  5O"HO"A"O H!O$O"0H1O"6ON/+H
,*N/H!N/9&HH H2AN/H1"H-#H1&	O/O";H/<O"OO"
N/N/HH**N/-H1/O"1	N,:AJN,&J==N,	(K11N,=B*N''N,,N//N8	4O;O"O	O"OOOO"c                  K   y wr   r|   rs   rt  rc   rK  r  s        rm   read_resourcezFastMCP.read_resourceP  s      r  c                  K   y wr   r|   r  s        rm   r  zFastMCP.read_resourceZ  s      &)r  c          	     
   K   t         j                  j                  j                         4 d{   }|rtt	        |      }t        t        j                  j                  |t                    ddd|      } j                  | fd	       d{   cddd      d{    S t        dd j                  d
||      5 }ddlm}	  |	 |       d{   }
|
S|j                  |
j!                                |
j#                         d{   cddd       cddd      d{    S  j%                  |       d{   }|y|j                  |j!                                #j&                  t)        |j*                        	 |j#                         d{   cddd       cddd      d{    S  jK                  |       d{   }|!tM        d|      tM        d|d      |j                  |j!                                |jO                  |      }|J #j&                  t)        |j*                        	 |j#                  ||       d{   cddd       cddd      d{    S 7 g7 7 7 7 7 y7 `7 7 # t,        $ r+}t.        j1                  |j2                  d|d        d}~wt4        $ r t.        j7                  d|        t8        $ r}t.        j7                  d|       t;        |t<        j>                        r%|j@                  jB                  dk(  rtE        d      |t;        |t<        jF                        rtE        d      | jH                  rtE        d|      |tE        d|d|       |d}~ww xY w7 7 J7 4# t,        $ r+}t.        j1                  |j2                  d|d        d}~wt4        $ r t.        j7                  d|        t8        $ r}t.        j7                  d|       t;        |t<        j>                        r%|j@                  jB                  dk(  rtE        d      |t;        |t<        jF                        rtE        d      | jH                  rtE        d|      |tE        d|d|       |d}~ww xY w# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  Read a resource by URI.

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

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

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

        Raises:
            NotFoundError: If resource not found or disabled
            ResourceError: If resource read fails
        rM  N)rt  r  rO  rP  zresources/readrQ  c                h    j                  t        | j                  j                        d      S r  )r  rw  rR  rt  r  s    rm   rX  z'FastMCP.read_resource.<locals>.<lambda>  s1    d.@.@GOO//0 '',"+	 /A /rv   rY  rn  )resource_urir   )!synthesize_prefab_resource_by_urir  r  r  zError reading resource Tr  r  r  r  r  zUnknown resource: 	 version )(rb   r   r  r]  r   r9   re   rf   ReadResourceRequestParamsrn   r#  rB   r   r.  r  r  r  _readrv  r  r	   rk   r%   r  r  r   r   r  r  r   r  r  r  r  r(   r  r   r  r&   r  )rs   rt  rc   rK  r  r_  	uri_paramr`  r  r  synthesizedrn  r  r|  paramss   ` ` `          rm   r  zFastMCP.read_resourced  s'    J >>))11$1??3"3K	.II??%3G< @  $"+$'	
 "11& 2   @??0   		   %FdC$PP*''(G(G(IJ!,!2!2Y!2!GG% 1 @??Z "&!2!23!2!HH'''(D(D(FG ,1A1A1I$+Ihll$K	!%-^^i^%HH7 1 @??h "&!;!;C!;!QQ#+.@,HII',SG9WKH  ##H$@$@$BC!))#.)))(Y-=-=-E '	(,, GIW!)Vy!QQS 1 @?? @N Q HU @Z I  Ig @h ( 

KK5cW=%) # 
 # ((+B3')JK$ !((+B3')JK%a)>)>? zz55<&3$V'"'(!) &a)?)?@"/ J##$%  33"/"9# A##$% ,5cWBqcB !#!, R RC @D $ JJ'>sg%FQU    $$'>sg%FG  W$$'>sg%FG!!U%:%:;::11S8"/ R##$% "!U%;%;<+F ! //+.EcW,MNTUU'*A#1#(NOUVVWe 1 @????s  /TJTA!S8JS8T)J!*T/S8
SJ$:SJ'S	S8%T1J*2T7SJ-A
SJ5.J0/J52	S8;TJ3TS#O$B S%O<O=O 	S8	TO	TS8!T$S'S*T-S0J53T5	O >&K$$-O B*N;;O  SO	T	S&O;;-S(B*SSSS#	S8&T1S42T8T
>T?T
Tc                  K   y wr   r|   r  s         rm   render_promptzFastMCP.render_prompt  s      r  c                  K   y wr   r|   r  s         rm   r  zFastMCP.render_prompt  r  r  c          
        K   t         j                  j                  j                         4 d{   }|rjt	        t
        j                  j                  ||t                    ddd|      } j                  | fd	       d{   cddd      d{    S t        d
| d j                  d||      5 } j                  |       d{   }	|	t        d|      |j                  |	j                                #j                   t#        |	j$                        	 |	j'                  |       d{   cddd       cddd      d{    S 7 57 7 7 7 '7 # t(        $ r+}
t*        j-                  |
j.                  d|d        d}
~
wt0        $ r t*        j3                  d|        t4        $ rJ}
t*        j3                  d|        j6                  rt9        d|      |
t9        d|d|
       |
d}
~
ww xY w# 1 sw Y   nxY wddd      d{  7   y# 1 d{  7  sw Y   yxY ww)a  Render a prompt by name.

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

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

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

        Raises:
            NotFoundError: If prompt not found or disabled
            PromptError: If prompt rendering fails
        rM  Nr  rO  rP  zprompts/getrQ  c                    j                  | j                  j                  | j                  j                  d      S r  )r  rR  r   r  r  s    rm   rX  z'FastMCP.render_prompt.<locals>.<lambda>I  s9    d.@.@,,11 '',"+ /A /rv   rY  zprompts/get r  )prompt_namer  zUnknown prompt: r  r  zError rendering prompt Tr  r  )rb   r   r  r]  r9   re   rf   GetPromptRequestParamsrn   r#  rB   r   r  r&   r  r  r  r	   rk   _renderr%   r  r  r   r   r  r  r   r'   )rs   r   r  rc   rK  r  r_  r`  r  r  r  s   `  ` `     rm   r  zFastMCP.render_prompt  sS    @ >>))11$1??3.II<<!"+3G< = 
 $"($'

 "11& 2 	 	 @??4 tf%		  #tWEE>'*:4((CDD##F$>$>$@A(Y-=-=-E '	&** EIV!'	Y!OO 5 @??	 @D F PS @T $ JJ'>th%GRV    $$'>th%GH  V$$'>th%GH//),CD8*LMSTT%(?xr!&MNTUU	V1 5 @????s   /IE)IAH=E,H=IE. I%H=HE0AH4E6
E2E6	H=I#E4$I,H=.I0H2E64I6	H?&F%%-HAHHHH(	$H=+I6H97I=IIIIc                8    | j                   j                  |      S )at  Add a tool to the server.

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

        Args:
            tool: The Tool instance or @tool-decorated function to register

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

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

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

        Raises:
            NotFoundError: If no matching tool is found.
        zNremove_tool() is deprecated. Use mcp.local_provider.remove_tool(name) instead.r?  r@  NzTool z
 not foundr  )
rb   r   rB  rC  r   r$   r   remove_toolKeyErrorr&   )rs   r   rc   s      rm   r  zFastMCP.remove_tool  s     00MM@)		  ,,T7; 	#eD8:$>?TIxy:>	s   A /B)r   rc   titledescriptionr   tagsoutput_schemar   exclude_argsr   r   tasktimeoutr   run_in_threadc                    y r   r|   rs   
name_or_fnr   rc   r  r  r   r  r  r   r  r   r   r  r  r   r  s                    rm   r   zFastMCP.tool  s    ( rv   c                    y r   r|   r  s                    rm   r   zFastMCP.tool  s    ( rv   c                   |+|dur'|rt        |      ni }|du rd|d<   nt        |      |d<   | j                  j                  |||||||||	|
|||n| j                  |||      }|S )a  Decorator to register a tool.

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

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

        Args:
            name_or_fn: Either a function (when used as @tool), a string name, or None
            name: Optional name for the tool (keyword-only, alternative to name_or_fn)
            description: Optional description of what the tool does
            tags: Optional set of tags for categorizing the tool
            output_schema: Optional JSON schema for the tool's output
            annotations: Optional annotations about the tool's behavior
            exclude_args: Optional list of argument names to exclude from the tool schema.
                Deprecated: Use `Depends()` for dependency injection instead.
            meta: Optional meta information about the tool

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

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

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

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

            # Direct function call
            server.tool(my_function, name="custom_name")
            ```
        FTr   )r   rc   r  r  r   r  r  r   r  r   r  r  r   r  )r   r!   r   r   r   )rs   r  r   rc   r  r  r   r  r  r   r  r   r   r  r  r   r  results                     rm   r   zFastMCP.tool  s    R ?s%/!%4:2Dd{!T
4S9T
 %%**#'#%)t/M/M' + 
$ rv   c                8    | j                   j                  |      S )zAdd a resource to the server.

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

        Returns:
            The resource instance that was added to the server.
        )r   add_resource)rs   rn  s     rm   r  zFastMCP.add_resource.  s     ##00::rv   c                8    | j                   j                  |      S )zAdd a resource template to the server.

        Args:
            template: A ResourceTemplate instance to add

        Returns:
            The template instance that was added to the server.
        )r   add_template)rs   r|  s     rm   r  zFastMCP.add_template;  s     ##00::rv   )r   rc   r  r  r   	mime_typer  r   r   r   r  r   c                  t        |t              st        d      t        ||      }t        |t              r.|j
                  t        d      |j                  t        d      |+|dur'|
rt        |
      ni }
|du rd|
d<   nt        |      |
d<   | j                  j                  |||||||||	|
||n| j                  |      }|S )a  Decorator to register a function as a resource.

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

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

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

        Args:
            uri: URI for the resource (e.g. "resource://my-resource" or "resource://{param}")
            name: Optional name for the resource
            description: Optional description of the resource
            mime_type: Optional MIME type for the resource
            tags: Optional set of tags for categorizing the resource
            annotations: Optional annotations about the resource's behavior
            meta: Optional meta information about the resource

        Examples:
            Register a resource with a custom name:
            ```python
            @server.resource("resource://my-resource")
            def get_data() -> str:
                return "Hello, world!"

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

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

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

            @server.resource("resource://{city}/weather")
            async def get_weather(city: str) -> str:
                data = await fetch_weather(city)
                return f"Weather for {city}: {data}"
            ```
        zThe @resource decorator was used incorrectly. It requires a URI as the first argument. Use @resource('uri') instead of @resourceu   resource_uri cannot be set on resources — the resource itself is the UI. Use resource_uri on tools to point to a UI resource.uC   visibility cannot be set on resources — it only applies to tools.FTr   )r   rc   r  r  r   r  r  r   r   r  r   )r   rw  r   r"   r    r  r   r   r   r!   r   rn  r   )rs   rt  r   rc   r  r  r   r  r  r   r   r   r  r   inner_decorators                  rm   rn  zFastMCP.resourceF  s   J #s#<  )i8	 c9%+ K 
 ~~) Y 
 ?s%/!%4:2Dd{!T
4S9T
 ..77##)t/M/M 8 
 rv   c                8    | j                   j                  |      S )zAdd a prompt to the server.

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

        Returns:
            The prompt instance that was added to the server.
        )r   
add_prompt)rs   r  s     rm   r  zFastMCP.add_prompt  s     ##..v66rv   	r   rc   r  r  r   r  r   r  r   c       	             y r   r|   rs   r  r   rc   r  r  r   r  r   r  r   s              rm   r  zFastMCP.prompt  s     rv   c       	             y r   r|   r  s              rm   r  zFastMCP.prompt  s     rv   c       	        t    | j                   j                  |||||||||	|	|

      S | j                  |

      S )a
  Decorator to register a prompt.

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

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

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

        Examples:

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

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

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

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

            # Direct function call
            server.prompt(my_function, name="custom_name")
            ```
        r  )r   r  r   r  s              rm   r  zFastMCP.prompt  sc    n ##**#) + 
 	
 04/M/M + 
 	
rv   c           	        ddl }ddlm} || u rt        d      |) |j                  dt
        d       ||}nt        d      |B |j                  d	t
        d       |r'dd
lm} t        ||      st        j                  |      }| j                  rI|j                  s=t        j                  d| j                  d|j                  d|j                  d        ||      }	|rG|j                         D 
ci c]  \  }
}|
t!        |       }}
}|	j#                  t%        |            }	| j'                  |	|xs d       yc c}}
w )a	  Mount another FastMCP server on this server with an optional namespace.

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

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

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

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

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

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

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

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

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

        Args:
            server: The FastMCP server to import
            prefix: Optional prefix to use for the imported server's objects. If None,
                objects are imported with their original names.
        r   Nz0import_server is deprecated, use mount() insteadr?  r@  rt  c                l    t         j                  |       }|r|j                         \  }}| | d| S | S )uG   Add prefix to resource URI: protocol://path → protocol://prefix/path./)URI_PATTERNmatchgroups)rt  r  r  protocolpaths        rm   add_resource_prefixz2FastMCP.import_server.<locals>.add_resource_prefix  s>    %%c*E!&$"F81TF33Jrv   r   _)updateuri_template)r   zeWhen importing from a server with a lifespan, the lifespan from the imported server will not be used.)rR  categoryrA  [z] Imported server z with prefix '')rt  rw  r  rw  rw   rw  )rC  r   r$   r2  
model_copyr   r  r3  rw  rt  r  r4  r  r  r5  r  r   r   RuntimeWarningr  r   )rs   r   r  rC  r
  r   rn  new_urir|  new_uri_templater  r   s               rm   import_serverzFastMCP.import_server  s    P 	>%	
	 !++---Dv&499+7N.OPMM$ . %33555H-c(,,.?H#..ug6F.Gh'	 6 %<<>>>H#6x7L7Lf#U #..*,<= /  h' ? #//111F**6fXQv{{m;T2U*VOOF# 2
 //%' LLDII;0^F8STU LL1TYYK'9&++GHQ . 6 ? 2sI   5HHAH
HAH*H+AHHCHHHHc
           
     F    ddl m}  |||||||||	      } | d||gd|
S )a  
        Create a FastMCP server from an OpenAPI specification.

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

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

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

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

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

        The `backend` argument can be either an existing `fastmcp.client.Client`
        instance or any value accepted as the `transport` argument of
        `fastmcp.client.Client`. This mirrors the convenience of the
        `fastmcp.client.Client` constructor.
        z{FastMCP.as_proxy() is deprecated. Use create_proxy() from fastmcp.server instead: `from fastmcp.server import create_proxy`r?  r@  )rb   r   rB  rC  r   r$   create_proxy)r!  backendr   s      rm   r  zFastMCP.as_proxy	  s=    6 00MMT)	 G0x00rv   c                    | j                   }|| dt        j                  d       S | d| dt        j                  d       S )N-r?  )ry   secrets	token_hex)r!  r   
class_names      rm   r   zFastMCP.generate_name	  sP    \\
< \7#4#4Q#7"899 \4&'*;*;A*>)?@@rv   )NN).r   
str | Noner   r5  rc   zstr | int | float | Noner   r5  r   list[mcp.types.Icon] | Noner   zAuthProvider | Noner   zSequence[Middleware] | Noner   zSequence[Provider] | Noner   zSequence[Transform] | Noner   z"LifespanCallable | Lifespan | Noner   z*Sequence[Tool | Callable[..., Any]] | Noner   zDuplicateBehavior | Noner   bool | Noner   rx   r   r7  r   z
int | Noner   r7  r   zAsyncKeyValue | Noner   zSamplingHandler | Noner   z$Literal['always', 'fallback'] | Noner   zmcp.types.LoggingLevel | Noner   z dict[str, dict[str, Any]] | Noner   r   )rw   rw  )rw   r5  )rl   r5  rw   None)rw   zlist[mcp.types.Icon])rw   r=   )r  r  r  r  rw   r   )r   r8   rw   r8  )r*  r>   r(  rw  rw   r8  )r   
list[Tool]rw   r9  )rw   zSequence[FastMCPComponent])r;  rD   rw   r8  )rD  rw  rE  rK   rw   r8  )rH  rw  rw   r8  )rK  rx   rw   zSequence[Tool]r   )r   rw  rc   VersionSpec | Nonerw   zTool | None)rK  rx   rw   zSequence[Resource])rt  rw  rc   r:  rw   zResource | None)rK  rx   rw   zSequence[ResourceTemplate])rt  rw  rc   r:  rw   zResourceTemplate | None)rK  rx   rw   zSequence[Prompt])r   rw  rc   r:  rw   zPrompt | None)r   rw  r  dict[str, Any] | Nonerc   r:  rK  rx   r  r8  rw   rI   )r   rw  r  r;  rc   r:  rK  rx   r  rA   rw   mcp.types.CreateTaskResult)r   rw  r  r;  rc   r:  rK  rx   r  TaskMeta | Nonerw   z'ToolResult | mcp.types.CreateTaskResult)
rt  rw  rc   r:  rK  rx   r  r8  rw   r/   )
rt  rw  rc   r:  rK  rx   r  rA   rw   r<  )
rt  rw  rc   r:  rK  rx   r  r=  rw   z+ResourceResult | mcp.types.CreateTaskResult)r   rw  r  r;  rc   r:  rK  rx   r  r8  rw   r,   )r   rw  r  r;  rc   r:  rK  rx   r  r=  rw   z)PromptResult | mcp.types.CreateTaskResult)r   zTool | Callable[..., Any]rw   rH   )r   rw  rc   r5  rw   r8  )"r  r}   r   r5  rc   str | int | Noner  r5  r  r5  r   r6  r  set[str] | Noner  dict[str, Any] | NotSetT | Noner   'ToolAnnotations | dict[str, Any] | Noner  list[str] | Noner   r;  r   (AppConfig | dict[str, Any] | bool | Noner  bool | TaskConfig | Noner  float | Noner   "AuthCheck | list[AuthCheck] | Noner  rx   rw   r}   )"r  r5  r   r5  rc   r>  r  r5  r  r5  r   r6  r  r?  r  r@  r   rA  r  rB  r   r;  r   rC  r  rD  r  rE  r   rF  r  rx   rw   Callable[[F], F])"r  str | AnyFunction | Noner   r5  rc   r>  r  r5  r  r5  r   r6  r  r?  r  r@  r   rA  r  rB  r   r;  r   rC  r  rD  r  rE  r   rF  r  rx   rw   ztCallable[[AnyFunction], FunctionTool] | FunctionTool | partial[Callable[[AnyFunction], FunctionTool] | FunctionTool])rn  zResource | Callable[..., Any]rw   zResource | ResourceTemplate)r|  r0   rw   r0   )rt  rw  r   r5  rc   r>  r  r5  r  r5  r   r6  r  r5  r  r?  r   z#Annotations | dict[str, Any] | Noner   r;  r   rC  r  rD  r   rF  rw   rG  )r  zPrompt | Callable[..., Any]rw   r+   )r  r}   r   r5  rc   r>  r  r5  r  r5  r   r6  r  r?  r   r;  r  rD  r   rF  rw   r}   )r  r5  r   r5  rc   r>  r  r5  r  r5  r   r6  r  r?  r   r;  r  rD  r   rF  rw   rG  )r  rH  r   r5  rc   r>  r  r5  r  r5  r   r6  r  r?  r   r;  r  rD  r   rF  rw   z|Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt | partial[Callable[[AnyFunction], FunctionPrompt] | FunctionPrompt])NNNN)r   r   r(  r5  r  r7  r  dict[str, str] | Noner  r5  rw   r8  )r   r   r  r5  rw   r8  )NzOpenAPI ServerNNNNNT)r  dict[str, Any]rO  zhttpx.AsyncClient | Noner   rw  r  list[RouteMap] | Noner  OpenAPIRouteMapFn | Noner  OpenAPIComponentFn | Noner  rI  r  r?  r  rx   r   r   rw   r   )NNNNNNN)r   r   r   r5  r  rK  r  rL  r  rM  r  rI  r*  r;  r  r?  r   r   rw   r   )r/  }Client[ClientTransportT] | ClientTransport | FastMCP[Any] | FastMCP1Server | AnyUrl | Path | MCPConfig | dict[str, Any] | strr   r   rw   r]   )r   r5  rw   rw  )6ry   rz   r{   r   r  propertyr   r   setterrc   r   r   r  r#  r%  r   r/  r1  r   rF  rI  r2  rd  rh  r3  rs  rv  r4  r  r  r5  r  r  r   r  r  r  r  r  rP   r   r  r  rn  r  r  r  r  classmethodr"  r,  r  r   __classcell__)r  s   @rm   r   r   :  s     #'N

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

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

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

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

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

    Returns:
        A FastMCPProxy server that proxies to the target.

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

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

        # Create a proxy to another FastMCP server
        proxy = create_proxy(other_server)
        ```
    r   )r]   _create_client_factoryclient_factoryr|   )r  r]   rT  )targetr   r]   rT  rU  s        rm   r.  r.  	  s1    V
 ,F3N %
 rv   )rc   r:  rw   z#mcp.types.RequestParams.Meta | None)r   rJ  rw   r8  )rw   ztuple[bool, Any])r   rH   rw   rx   )r   r   rw   zAsyncIterator[Any])r   r   rw   zYCallable[[LowLevelServer[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]])rV  rN  r   r   rw   r]   )r   
__future__r   r   loggingrer2  rC  collections.abcr   r   r   
contextlibr   r   dataclassesr	   	functoolsr
   pathlibr   typingr   r   r   r   r   r   r   r  	mcp.typesre   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   rb   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.   r/   fastmcp.resources.templater0   fastmcp.server.authr1   r2   r3   r4   fastmcp.server.lifespanr5   fastmcp.server.low_levelr6   fastmcp.server.middlewarer7   r8   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_transformrK   fastmcp.utilities.componentsrL   rM   fastmcp.utilities.loggingrN   fastmcp.utilities.typesrO   rP   rQ   fastmcp.utilities.versionsrR   rS   fastmcp.clientrT   fastmcp.client.clientrU   fastmcp.client.samplingrV   fastmcp.client.transportsrW   rX    fastmcp.server.providers.openapirY   OpenAPIComponentFnrZ   r[   OpenAPIRouteMapFnr  r]   ry   r  rn   Filterrp   	getLogger	addFilterr}   r   r   r   	Transportcompiler  r   r   r   r   r   r   r   r   r.  r|   rv   rm   <module>r     s-   ; "   	   
     P P P   ; 1 3 6 *   ? ' "   
	 	 	 ) " - : ; 7 U U , 3 M M S S < @ < 0 V J / 4 < J 0 E E
 %47KR9P;	H	(<F7>> F
   . / 9 9 " CxS)*@A #
E#
E# ]# /	#
 u# p# s# !# T# 8# <# :#   A# Y# O#  g!# (

 =>	 bjj-.  "=o"NN 
'& ;F2 	 	,0! u!AOu!AzC4	4 4 4rv   