
    ChҸ              	      ,   S r SSKJr  SSKrSSKrSSKJrJrJ	r	J
r
JrJr  SSKJrJr  SSKJrJrJr  SSKrSSKrSSKJr  SSKJr  SS	KJrJr  SS
KJr  SSKJ r   SSK!J"r"  SSK#J$r$  SSK%J&r&  SSK'J(r(J)r)  SSK*J+r+J,r,J-r-  SSK.J/r/  SSK0J1r1J2r2  SSK3J4r4J5r5J6r6  SSK7J8r8  SSK9J:r:J;r;J<r<  SSK=J>r>  SSK?J@r@JArA  SSKBJCrCJDrDJErE  SSKFJGrGJHrH  SSKIJJrJ  SSKKJLrLJMrM  SSKNJOrO  SSKPJQrQ  SSKPJRrS  SSKPJTrU  SS KVJWrWJXrX  SS!KYJZrZ  SS"K[J\r\  SS#K]J^r^  SS$K_J`r`  SS%KaJbrb  SS&KcJdrdJereJfrf  SS'KgJhrhJiriJjrjJkrkJlrl  SS(KgJ@rm  SS)KgJnro  SS*KgJDrp  SS+KgJqrr  SS,KgJGrs  \M" \t5      ru " S- S.\\\Q   5      rv      S6S/ jrw " S0 S1\\Q   5      rx " S2 S35      ry " S4 S5\\\X\d\f4   5      rzg)7z5FastMCP - A more ergonomic interface for MCP servers.    )annotationsN)AsyncIterator	AwaitableCallable
CollectionIterableSequence)AbstractAsyncContextManagerasynccontextmanager)AnyGenericLiteral)	BaseModel)AnyUrl)BaseSettingsSettingsConfigDict)	Starlette
Middleware)AuthenticationMiddleware)Request)ResponseMountRoute)ReceiveScopeSend)AuthContextMiddleware)BearerAuthBackendRequireAuthMiddleware) OAuthAuthorizationServerProviderProviderTokenVerifierTokenVerifier)AuthSettings)ElicitationResultElicitSchemaModelTelicit_with_validation)ResourceError)PromptPromptManager)FunctionResourceResourceResourceManager)ToolToolManager)find_context_parameter)configure_logging
get_logger)ReadResourceContents)LifespanResultT)Server)lifespan)ServerSessionServerSessionT)SseServerTransport)stdio_server)
EventStore)StreamableHTTPSessionManager)TransportSecuritySettings)LifespanContextTRequestContextRequestT)AnyFunctionContentBlockGetPromptResultIconToolAnnotations)r*   )PromptArgument)r-   )ResourceTemplate)r/   c                      \ rS rSr% Sr\" SSSSSS9rS	\S
'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S\S'   S	\S'   S	\S'    S	\S'   S	\S'   S	\S'   S\S'    S\S'    S\S'   S \S!'   S"rg#)$Settings8   zFastMCP server settings.

All settings can be configured via environment variables with the prefix FASTMCP_.
For example, FASTMCP_DEBUG=true will set debug=True.
FASTMCP_z.env__Tignore)
env_prefixenv_fileenv_nested_delimiter#nested_model_default_partial_updateextrabooldebug8Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL']	log_levelstrhostintport
mount_pathsse_pathmessage_pathstreamable_http_pathjson_responsestateless_httpwarn_on_duplicate_resourceswarn_on_duplicate_toolswarn_on_duplicate_prompts	list[str]dependenciesYCallable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]] | Noner7   AuthSettings | Noneauth TransportSecuritySettings | Nonetransport_security N)	__name__
__module____qualname____firstlineno____doc__r   model_config__annotations____static_attributes__rl       S/home/james-whalen/.local/lib/python3.13/site-packages/mcp/server/fastmcp/server.pyrJ   rJ   8   s     &!,0L KGG I
IOM I "&% "!  $# FggQ
 98ru   rJ   c                .   ^ ^ [         SU U4S jj5       nU$ )Nc                  >#    T" T5       IS h  vN nU7v   S S S 5      IS h  vN   g  N N! , IS h  vN  (       d  f       g = f7fNrl   )_contextappr7   s     rv   wraplifespan_wrapper.<locals>.wrapr   s%     C==GM !=====s9   A	+A	/A	-A	A	A8AA	)rz   z#MCPServer[LifespanResultT, Request]returnzAsyncIterator[LifespanResultT])r   )r|   r7   r}   s   `` rv   lifespan_wrapperr   n   s       Kru   c                     \ rS rSr       S/SSSSSSSS	S
SSSSSSSSSS.                                                 S0S jjjr\S1S j5       r\S2S j5       r\S2S j5       r\S3S j5       r	\S4S j5       r
  S5     S6S jjrS7S jrS8S jrS9S jrS:S jrS;S jrS<S jrS=S jr      S>               S?S jjrS@S jr      S>             SAS jjrS rSBS  jrSSSSSS!.             SCS" jjrSDS# jr    SE         SFS$ jjr  SG       SHS% jjrS7S& jrSISJS' jjrS7S( jrSKS) jrSISLS* jjr SMS+ jr!SNS, jr"SISOS- jjr#S.r$g)PFastMCPz   NFINFOz	127.0.0.1i@  /z/ssez
/messages/z/mcpTrl   )toolsrU   rW   rY   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   rf   r7   ri   rk   c          
        [        S0 SU	_SU
_SU_SU_SU_SU_SU_SU_S	U_S
U_SU_SU_SU_S[        U5      _SU_SU_SU_6U l        [        U=(       d    SUUUU R                  R                  (       a  [        X R                  R                  5      O[        S9U l        [        XR                  R                  S9U l
        [        U R                  R                  S9U l        [        U R                  R                  S9U l        U R                  R"                  b3  U(       a  U(       a  [%        S5      eU(       d  U(       d  [%        S5      eOU(       d  U(       a  [%        S5      eXPl        X`l        U(       a  U(       d  [+        U5      U l        Xpl        / U l        U R                  R0                  U l        S U l        U R5                  5         [7        U R                  R8                  5        g )NrU   rW   rY   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   rf   r7   ri   rk   r   )nameinstructionswebsite_urliconsr7   )r   rc   )rb   )rd   z;Cannot specify both auth_server_provider and token_verifierzOMust specify either auth_server_provider or token_verifier when auth is enabledzKCannot specify auth_server_provider or token_verifier without auth settingsrl   )rJ   listsettings	MCPServerr7   r   default_lifespan_mcp_serverr0   rc   _tool_managerr.   rb   _resource_managerr+   rd   _prompt_managerri   
ValueError_auth_server_provider_token_verifierr#   _event_store_custom_starlette_routesrf   _session_manager_setup_handlersr2   rW   )selfr   r   r   r   auth_server_providertoken_verifierevent_storer   rU   rW   rY   r[   r\   r]   r^   r_   r`   ra   rb   rc   rd   rf   r7   ri   rk   s                             rv   __init__FastMCP.__init__{   s   : ! 


 
 	

 "
 
 &
 "6
 (
 *
 )D
 %<
 '@
 l+
 
  !
"  2#
( %"%# IMH^H^&t]]-C-CDdt
 )ummNsNst!0T]]MvMv!w,t}}GnGno==)# !^__' !rss!^jkk%9"-  #89M#ND '57% MM66EI 	 	$--112ru   c                .    U R                   R                  $ ry   )r   r   r   s    rv   r   FastMCP.name   s    $$$ru   c                .    U R                   R                  $ ry   )r   r   r   s    rv   r   FastMCP.instructions   s    ,,,ru   c                .    U R                   R                  $ ry   )r   r   r   s    rv   r   FastMCP.website_url   s    +++ru   c                .    U R                   R                  $ ry   )r   r   r   s    rv   r   FastMCP.icons   s    %%%ru   c                J    U R                   c  [        S5      eU R                   $ )zGet the StreamableHTTP session manager.

This is exposed to enable advanced use cases like mounting multiple
FastMCP servers in a single FastAPI application.

Raises:
    RuntimeError: If called before streamable_http_app() has been called.
zSession manager can only be accessed aftercalling streamable_http_app().The session manager is created lazilyto avoid unnecessary initialization.)r   RuntimeErrorr   s    rv   session_managerFastMCP.session_manager   s0       (7  $$$ru   c                8  ^ ^ [         S   nXR                  ;  a  [        SU 35      eU=S:X  a"    [        R                  " T R
                  5        g=S:X  a    [        R                  " UU 4S j5        gS:X  a!  [        R                  " T R                  5        gg)zRun the FastMCP server. Note this is a synchronous function.

Args:
    transport: Transport protocol to use ("stdio", "sse", or "streamable-http")
    mount_path: Optional mount path for SSE transport
)stdiossestreamable-httpzUnknown transport: r   r   c                 &   > TR                  T 5      $ ry   )run_sse_async)r\   r   s   rv   <lambda>FastMCP.run.<locals>.<lambda>  s    $"4"4Z"@ru   r   N)r   __args__r   anyiorunrun_stdio_asyncrun_streamable_http_async)r   	transportr\   
TRANSPORTSs   ` ` rv   r   FastMCP.run   sq     >?
///29+>??		$../		@A"		$889 #ru   c                N   U R                   R                  5       " U R                  5        U R                   R                  SS9" U R                  5        U R                   R                  5       " U R                  5        U R                   R	                  5       " U R                  5        U R                   R                  5       " U R
                  5        U R                   R                  5       " U R                  5        U R                   R                  5       " U R                  5        g)z"Set up core MCP protocol handlers.F)validate_inputN)r   
list_tools	call_toollist_resourcesread_resourcelist_prompts
get_promptlist_resource_templatesr   s    rv   r   FastMCP._setup_handlers  s    ##%doo6 	""%"8H'')$*=*=>&&(););<%%'(9(9:##%doo600243O3OPru   c                  #    U R                   R                  5       nU Vs/ s HX  n[        UR                  UR                  UR
                  UR                  UR                  UR                  UR                  S9PMZ     sn$ s  snf 7f)zList all available tools.)r   titledescriptioninputSchemaoutputSchemar   r   )
r   r   MCPToolr   r   r   
parametersoutput_schemar   r   )r   r   infos      rv   r   FastMCP.list_tools  s     ""--/ 
  YYjj ,, OO!// ,,jj 
 	
 
s   BAB Bc                f     U R                   R                  n[        XS9$ ! [         a    Sn Nf = f)z
Returns a Context object. Note that the context will only be valid
during a request; outside a request, most methods will error.
Nrequest_contextfastmcp)r   r   LookupErrorContext)r   r   s     rv   get_contextFastMCP.get_context)  s;    
	#"..>>O EE  	#"O	#s   ! 00c                t   #    U R                  5       nU R                  R                  XUSS9I Sh  vN $  N7f)z#Call a tool by name with arguments.T)r{   convert_resultN)r   r   r   )r   r   	argumentsr{   s       rv   r   FastMCP.call_tool4  s8     ""$''11$7cg1hhhhs   /868c                  #    U R                   R                  5       nU Vs/ s HV  n[        UR                  UR                  =(       d    SUR
                  UR                  UR                  UR                  S9PMX     sn$ s  snf 7f)zList all available resources. )urir   r   r   mimeTyper   )	r   r   MCPResourcer   r   r   r   	mime_typer   )r   	resourcesresources      rv   r   FastMCP.list_resources9  s~      **99;	 &

 & LL]](bnn$00!++nn &

 
	
 

s   BAB>Bc                   #    U R                   R                  5       nU Vs/ s HM  n[        UR                  UR                  UR
                  UR                  UR                  UR                  S9PMO     sn$ s  snf 7f)N)uriTemplater   r   r   r   r   )	r   list_templatesMCPResourceTemplateuri_templater   r   r   r   r   )r   	templatestemplates      rv   r   FastMCP.list_resource_templatesI  sy     **99;	 &

 &  $11]]nn$00!++nn &

 
	
 

s   A=AA85A=c                t  #    U R                  5       nU R                  R                  XS9I Sh  vN nU(       d  [        SU 35      e UR	                  5       I Sh  vN n[        XCR                  S9/$  NF N! [         a1  n[        R                  SU 35        [        [        U5      5      eSnAff = f7f)zRead a resource by URI.r{   NzUnknown resource: )contentr   zError reading resource )r   r   get_resourcer)   readr4   r   	Exceptionlogger	exceptionrX   )r   r   r{   r   r   es         rv   r   FastMCP.read_resourceW  s      ""$//<<S<RR"4SE :;;	($MMO+G(DVDVWXX S
 , 	(6se<=A''	(sE   -B8A6B8
A: A8A: 5B88A: :
B5,B00B55B8c           
     B    U R                   R                  UUUUUUUS9  g)a!  Add a tool to the server.

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

Args:
    fn: The function to register as a tool
    name: Optional name for the tool (defaults to function name)
    title: Optional human-readable title for the tool
    description: Optional description of what the tool does
    annotations: Optional ToolAnnotations providing additional tool information
    structured_output: Controls whether the tool's output is structured or unstructured
        - If None, auto-detects based on the function's return type annotation
        - If True, creates a structured tool (return type annotation permitting)
        - If False, unconditionally creates an unstructured tool
r   r   r   r   r   structured_outputN)r   add_tool)r   fnr   r   r   r   r   r   s           rv   r   FastMCP.add_toolf  s2    4 	####/ 	$ 	
ru   c                :    U R                   R                  U5        g)zRemove a tool from the server by name.

Args:
    name: The name of the tool to remove

Raises:
    ToolError: If the tool does not exist
N)r   remove_tool)r   r   s     rv   r   FastMCP.remove_tool  s     	&&t,ru   c                f   ^ ^^^^^^ [        T5      (       a  [        S5      eSUUUUU UU4S jjnU$ )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.

Args:
    name: Optional name for the tool (defaults to function name)
    title: Optional human-readable title for the tool
    description: Optional description of what the tool does
    annotations: Optional ToolAnnotations providing additional tool information
    structured_output: Controls whether the tool's output is structured or unstructured
        - If None, auto-detects based on the function's return type annotation
        - If True, creates a structured tool (return type annotation permitting)
        - If False, unconditionally creates an unstructured tool

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

    @server.tool()
    def tool_with_context(x: int, ctx: Context) -> str:
        ctx.info(f"Processing {x}")
        return str(x)

    @server.tool()
    async def async_tool(x: int, context: Context) -> str:
        await context.report_progress(50, 100)
        return str(x)
zaThe @tool decorator was used incorrectly. Did you forget to call it? Use @tool() instead of @toolc           
     2   > TR                  U TTTTTTS9  U $ )Nr   )r   )r   r   r   r   r   r   r   r   s    rv   	decoratorFastMCP.tool.<locals>.decorator  s0    MM''"3   Iru   r   rB   r   rB   callable	TypeError)r   r   r   r   r   r   r   r  s   ``````` rv   toolFastMCP.tool  s1    R D>>s 
	 
	 ru   c                6    U R                   R                  5       $ )a,  Decorator to register a completion handler.

The completion handler receives:
- ref: PromptReference or ResourceTemplateReference
- argument: CompletionArgument with name and partial value
- context: Optional CompletionContext with previously resolved arguments

Example:
    @mcp.completion()
    async def handle_completion(ref, argument, context):
        if isinstance(ref, ResourceTemplateReference):
            # Return completions based on ref, argument, and context
            return Completion(values=["option1", "option2"])
        return None
)r   
completionr   s    rv   r  FastMCP.completion  s      **,,ru   c                :    U R                   R                  U5        g)zNAdd a resource to the server.

Args:
    resource: A Resource instance to add
N)r   add_resource)r   r   s     rv   r  FastMCP.add_resource  s     	++H5ru   )r   r   r   r   r   c               f   ^ ^^^^^^ [        T5      (       a  [        S5      eSUUUUU UU4S jjnU$ )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

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
    title: Optional human-readable title for the resource
    description: Optional description of the resource
    mime_type: Optional MIME type for the resource

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

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

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

    @server.resource("resource://{city}/weather")
    async def get_weather(city: str) -> str:
        data = await fetch_weather(city)
        return f"Weather for {city}: {data}"
zrThe @resource decorator was used incorrectly. Did you forget to call it? Use @resource('uri') instead of @resourcec           
     "  > [         R                  " U 5      nST;   =(       a    ST;   n[        UR                  5      nU(       d  U(       a  [	        U 5      n[        [        R                  " ST5      5      nUR                  R                  5        Vs1 s H  ofU:w  d  M
  UiM     nnXW:w  a  [        SU SU 35      eTR                  R                  U TTTT	TT
S9  U $ [        R                  " U TTTT	TT
S9nTR                  U5        U $ s  snf )N{}z{(\w+)}z Mismatch between URI parameters z and function parameters )r   r   r   r   r   r   r   )r   r   r   r   r   r   r   )inspect	signaturerT   r   r1   setrefindallkeysr   r   add_templater,   from_functionr  )r   sighas_uri_paramshas_func_paramscontext_param
uri_paramspfunc_paramsr   r   r   r   r   r   r   r   s            rv   r  #FastMCP.resource.<locals>.decorator!  s"   ##B'C CZ6C3JN"3>>2O 6r : !J!<=
 +...*=*=*?V*?QCUq*?V,$::,F_`k_lm 
 &&33!$ +' 4 * I ,99 +' !!(+I; Ws   	D Dr  r  )r   r   r   r   r   r   r   r  s   ``````` rv   r   FastMCP.resource  s5    ` C==W 
+	 +	Z ru   c                :    U R                   R                  U5        g)zHAdd a prompt to the server.

Args:
    prompt: A Prompt instance to add
N)r   
add_prompt)r   prompts     rv   r(  FastMCP.add_promptP  s     	''/ru   c                ^   ^ ^^^^ [        T5      (       a  [        S5      eSUUUU U4S jjnU$ )a  Decorator to register a prompt.

        Args:
            name: Optional name for the prompt (defaults to function name)
            title: Optional human-readable title for the prompt
            description: Optional description of what the prompt does

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

            @server.prompt()
            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
                            }
                        }
                    }
                ]
        zgThe @prompt decorator was used incorrectly. Did you forget to call it? Use @prompt() instead of @promptc                Z   > [         R                  " U TTTTS9nTR                  U5        U $ )N)r   r   r   r   )r*   r  r(  )funcr)  r   r   r   r   r   s     rv   r  !FastMCP.prompt.<locals>.decorator  s.    ))$TT_glmFOOF#Kru   )r-  rB   r   rB   r  )r   r   r   r   r   r  s   ````` rv   r)  FastMCP.promptX  s4    T D>>N 
	 	
 ru   c                0   ^ ^^^^     SUUUUU 4S jjnU$ )a.  
Decorator to register a custom HTTP route on the FastMCP server.

Allows adding arbitrary HTTP endpoints outside the standard MCP protocol,
which can be useful for OAuth callbacks, health checks, or admin APIs.
The handler function must be an async function that accepts a Starlette
Request and returns a Response.

Args:
    path: URL path for the route (e.g., "/oauth/callback")
    methods: List of HTTP methods to support (e.g., ["GET", "POST"])
    name: Optional name for the route (to reference this route with
          Starlette's reverse URL lookup feature)
    include_in_schema: Whether to include in OpenAPI schema, defaults to True

Example:
    @server.custom_route("/health", methods=["GET"])
    async def health_check(request: Request) -> Response:
        return JSONResponse({"status": "ok"})
c           
     T   > TR                   R                  [        TU TTTS95        U $ )N)endpointmethodsr   include_in_schema)r   appendr   )r-  r4  r3  r   pathr   s    rv   r  'FastMCP.custom_route.<locals>.decorator  s7     ))00!#&7 Kru   )r-  (Callable[[Request], Awaitable[Response]]r   r8  rl   )r   r6  r3  r   r4  r  s   ````` rv   custom_routeFastMCP.custom_route  s%    8	:	5	 	 ru   c                  #    [        5        ISh  vN u  pU R                  R                  UUU R                  R                  5       5      I Sh  vN   SSS5      ISh  vN   g NT N N	! , ISh  vN  (       d  f       g= f7f)z%Run the server using stdio transport.N)r;   r   r   create_initialization_options)r   read_streamwrite_streams      rv   r   FastMCP.run_stdio_async  s`     >>%@k""&&  >>@   ">> ">>>sV   BA&B;A,A(A,B A*!B(A,*B,B2A53B?Bc                D  #    SSK nU R                  U5      nUR                  UU R                  R                  U R                  R
                  U R                  R                  R                  5       S9nUR                  U5      nUR                  5       I Sh  vN   g N7f)z#Run the server using SSE transport.r   NrY   r[   rW   )
uvicornsse_appConfigr   rY   r[   rW   lowerr6   serve)r   r\   rB  starlette_appconfigservers         rv   r   FastMCP.run_sse_async  s{     Z0####mm--335	   
 'llns   BB BB c                B  #    SSK nU R                  5       nUR                  UU R                  R                  U R                  R
                  U R                  R                  R                  5       S9nUR                  U5      nUR                  5       I Sh  vN   g N7f)z.Run the server using StreamableHTTP transport.r   NrA  )
rB  streamable_http_apprD  r   rY   r[   rW   rE  r6   rF  )r   rB  rG  rH  rI  s        rv   r   !FastMCP.run_streamable_http_async  s{     002####mm--335	   
 'llns   BBBBc                    US:X  a  U$ UR                  S5      (       a  USS nUR                  S5      (       d  SU-   nX-   $ )z
Combine mount path and endpoint to return a normalized path.

Args:
    mount_path: The mount path (e.g. "/github" or "/")
    endpoint: The endpoint path (e.g. "/messages/")

Returns:
    Normalized path (e.g. "/github/messages/")
r   N)endswith
startswith)r   r\   r2  s      rv   _normalize_pathFastMCP._normalize_path  sV     O s###CRJ ""3''X~H $$ru   c           
       ^ ^^ SSK Jn  SSKJnJn  Ub  UT R
                  l        T R                  T R
                  R                  T R
                  R                  5      n[        UT R
                  R                  S9mSU U4S jjm/ n/ n/ nT R
                  R                  (       Ga  T R
                  R                  R                  =(       d    / nT R                  (       a*  U" [        [        T R                  5      S9U" [         5      /nT R"                  (       a  SSKJn	  UR)                  U	" T R"                  T R
                  R                  R*                  T R
                  R                  R,                  T R
                  R                  R.                  T R
                  R                  R0                  S	95        T R                  (       a  Sn
T R
                  R                  (       aQ  T R
                  R                  R2                  (       a,  SS
KJn  U" T R
                  R                  R2                  5      n
UR7                  U" T R
                  R8                  [;        TX5      S/S95        UR7                  U" T R
                  R                  [;        TR<                  X5      S95        OhSU4S jjnUR7                  U" T R
                  R8                  US/S95        UR7                  U" T R
                  R                  TR<                  S95        T R
                  R                  (       a  T R
                  R                  R2                  (       ax  SSKJn  UR)                  U" T R
                  R                  R2                  T R
                  R                  R*                  /T R
                  R                  R                  S95        UR)                  T R@                  5        [C        T R
                  RD                  XgS9$ )z)Return an instance of the SSE server app.r   r   r   N)security_settingsc                P  >#    TR                  U UU5       IS h  vN nTR                  R                  US   US   TR                  R                  5       5      I S h  vN   S S S 5      IS h  vN   [	        5       $  Na N  N! , IS h  vN  (       d  f       [	        5       $ = f7f)Nr      )connect_sser   r   r<  r   )scopereceivesendstreamsr   r   s       rv   
handle_sse#FastMCP.sse_app.<locals>.handle_sse  s        &&**AJAJ$$BBD    :
   :sV   B&A=B&?BA?B#B&.B/B&?BB&B#	B
B#B&backendcreate_auth_routesprovider
issuer_urlservice_documentation_urlclient_registration_optionsrevocation_optionsbuild_resource_metadata_urlGET)r2  r3  )r|   c                p   >#    T" U R                   U R                  U R                  5      I S h  vN $  N7fry   )rY  rZ  _send)requestr]  s    rv   sse_endpoint%FastMCP.sse_app.<locals>.sse_endpoint]  s'     'wVVVVs   ,646 create_protected_resource_routesresource_urlauthorization_serversscopes_supported)rU   routes
middleware)rY  r   rZ  r   r[  r   )rn  r   r   r   )#starlette.middlewarer   starlette.routingr   r   r   r\   rR  r^   r:   rk   ri   required_scopesr   r   r    r   r   mcp.server.auth.routesrb  extendre  rf  rg  rh  resource_server_urlrj  r5  r]   r!   handle_post_messagerr  r   r   rU   )r   r\   r   r   r   normalized_message_endpointrw  rx  r{  rb  resource_metadata_urlrj  ro  rr  r]  r   s   `             @@rv   rC  FastMCP.sse_app  s   32 !'1DMM$ '+&:&:4==;S;SUYUbUbUoUo&p# !'"mm>>

	 	  ')')
 =="mm00@@FBO ## 0 1$2F2F G 45	
 ))E&!%!;!;#'==#5#5#@#@26--2D2D2^2^48MM4F4F4b4b+/==+=+=+P+P $(!}}!!dmm&8&8&L&LN )DDMMDVDVDjDj(k% MMMM**2:f"G MMMM..-c.E.EnW MMMM**)"G MMMM..// ==$--"4"4"H"HOMM0!%!3!3!G!G+/==+=+=+H+H*I%)]]%7%7%G%G 	d334 t}}226YYru   c           
     >  ^  SSK Jn  T R                  cb  [        T R                  T R
                  T R                  R                  T R                  R                  T R                  R                  S9T l        [        T R                  5      n/ n/ n/ nT R                  R                  (       Ga  T R                  R                  R                  =(       d    / nT R                  (       a*  U" [        [        T R                  5      S9U" [         5      /nT R"                  (       a  SSKJn  UR)                  U" T R"                  T R                  R                  R*                  T R                  R                  R,                  T R                  R                  R.                  T R                  R                  R0                  S95        T R                  (       a  SnT R                  R                  (       aQ  T R                  R                  R2                  (       a,  SSKJn  U" T R                  R                  R2                  5      nUR7                  [9        T R                  R:                  [=        X%U5      S	95        O-UR7                  [9        T R                  R:                  US	95        T R                  R                  (       a  T R                  R                  R2                  (       ax  SS
KJn	  UR)                  U	" T R                  R                  R2                  T R                  R                  R*                  /T R                  R                  R                  S95        UR)                  T R@                  5        [C        T R                  RD                  UUU 4S jS9$ )z4Return an instance of the StreamableHTTP server app.r   r   N)r|   r   r`   	statelessrU  r_  ra  rc  ri  )r2  rq  rs  c                8   > TR                   R                  5       $ ry   )r   r   )r|   r   s    rv   r   -FastMCP.streamable_http_app.<locals>.<lambda>  s    !5!5!9!9!;ru   )rU   rw  rx  r7   )#ry  r   r   r=   r   r   r   r`   ra   rk   StreamableHTTPASGIAppri   r{  r   r   r    r   r   r|  rb  r}  re  rf  rg  rh  r~  rj  r5  r   r_   r!   rr  r   r   rU   )
r   r   rL  rw  rx  r{  rb  r  rj  rr  s
   `         rv   rL  FastMCP.streamable_http_app  s   3   ($@$$ --"mm99--66"&--"B"B%D! 4D4I4IJ ')')
 =="mm00@@FBO ##0 1$2F2F G 45
 ))E&!%!;!;#'==#5#5#@#@26--2D2D2^2^48MM4F4F4b4b+/==+=+=+P+P $(!}}!!dmm&8&8&L&LN )DDMMDVDVDjDj(k%MMMM6623FYno MMMM660 ==$--"4"4"H"HOMM0!%!3!3!G!G+/==+=+=+H+H*I%)]]%7%7%G%G 	d334--%%!;	
 	
ru   c                z  #    U R                   R                  5       nU VVs/ s H  n[        UR                  UR                  UR
                  UR                  =(       d    /  Vs/ s H,  n[        UR                  UR
                  UR                  S9PM.     snUR                  S9PM     snn$ s  snf s  snnf 7f)zList all available prompts.)r   r   required)r   r   r   r   r   )
r   r   	MCPPromptr   r   r   r   MCPPromptArgumentr  r   )r   promptsr)  args       rv   r   FastMCP.list_prompts  s     &&335  "
 " [[ll".. !' 0 0 6B 6 !7 & XX$'OO!$
 !7 ll "
 	


s)    B;AB5%3B0B5,B;0B55B;c                  #     U R                   R                  U5      nU(       d  [        SU 35      eUR                  X R	                  5       S9I Sh  vN n[        UR                  [        R                  " U5      S9$  N,! [         a1  n[        R                  SU 35        [        [        U5      5      eSnAff = f7f)z$Get a prompt by name with arguments.zUnknown prompt: r   N)r   messageszError getting prompt )r   r   r   renderr   rD   r   pydantic_coreto_jsonable_pythonr   r   r   rX   )r   r   r   r)  r  r   s         rv   r   FastMCP.get_prompt  s     	%))44T:F #3D6!:;;#]]9>N>N>P]QQH""..&99(C  R  	%4TF;<SV$$	%s;   CAB B+B  CB 
B>,B99B>>C)r   r   r   r   r   r   r   r   r   rf   r   )NNNNNNN)2r   
str | Noner   r  r   r  r   list[Icon] | Noner   z6OAuthAuthorizationServerProvider[Any, Any, Any] | Noner   zTokenVerifier | Noner   zEventStore | Noner   zlist[Tool] | NonerU   rT   rW   rV   rY   rX   r[   rZ   r\   rX   r]   rX   r^   rX   r_   rX   r`   rT   ra   rT   rb   rT   rc   rT   rd   rT   rf   zCollection[str]r7   rg   ri   rh   rk   rj   r   rX   r   r  )r   r  )r   r=   )r   N)r   z*Literal['stdio', 'sse', 'streamable-http']r\   r  r   None)r   r  )r   zlist[MCPTool])r   z0Context[ServerSession, LifespanResultT, Request])r   rX   r   zdict[str, Any]r   z'Sequence[ContentBlock] | dict[str, Any])r   zlist[MCPResource])r   zlist[MCPResourceTemplate])r   zAnyUrl | strr   Iterable[ReadResourceContents])NNNNNN)r   rB   r   r  r   r  r   r  r   ToolAnnotations | Noner   r  r   bool | Noner   r  )r   rX   r   r  )r   r  r   r  r   r  r   r  r   r  r   r  r   $Callable[[AnyFunction], AnyFunction])r   r-   r   r  )r   rX   r   r  r   r  r   r  r   r  r   r  r   r  )r)  r*   r   r  )NNNN)
r   r  r   r  r   r  r   r  r   r  )NT)r6  rX   r3  re   r   r  r4  rT   ry   )r\   r  r   r  )r\   rX   r2  rX   r   rX   )r\   r  r   r   )r   r   )r   zlist[MCPPrompt])r   rX   r   zdict[str, Any] | Noner   rD   )%rm   rn   ro   rp   r   propertyr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r
  r  r  r   r(  r)  r9  r   r   r   rR  rC  rL  r   r   rt   rl   ru   rv   r   r   z   s     #'"&#'W[/3)-U3 $(NT($*#$,0(,*.(*nr$(?C7U3U3 !U3  	U3
 !U3 UU3 -U3 'U3 !U3 U3 LU3 U3 U3 U3  !U3" #U3$ "%U3& 'U3( )U3* &*+U3, "&-U3. $(/U30 &1U32 l3U34 "5U36 =7U3n % % - - , , & & % %( AH!%:=: : 
	:.Q
 	Fi

 
($   "&.2#')-"
"
 "
 	"

  "
 ,"
 !"
 '"
 
"
H	-   "&.2#')-:: :  	:
 ,: !: ': 
.:x-$6   "& $#'cc 	c
 c  c c !c 
.cJ0   "&#'55 5  	5
 !5 
.5v  "&** * 	*
  *X%4BZH^
@
*% %ru   r   c                  ,    \ rS rSrSrSS jrSS jrSrg)	r  i  z8
ASGI application for Streamable HTTP server transport.
c                    Xl         g ry   r   )r   r   s     rv   r   StreamableHTTPASGIApp.__init__  s    .ru   c                X   #    U R                   R                  XU5      I S h  vN   g  N7fry   )r   handle_request)r   rY  rZ  r[  s       rv   __call__StreamableHTTPASGIApp.__call__  s!     ""11%$GGGs    *(*r  N)r   r=   )rY  r   rZ  r   r[  r   r   r  )rm   rn   ro   rp   rq   r   r  rt   rl   ru   rv   r  r    s    /Hru   r  c                  4  ^  \ rS rSr% SrS\S'   S\S'   SSS.     SU 4S	 jjjr\SS
 j5       r\  SS j5       r	SSS jjr
SS jr      SS jrSS.       S S jjr\S!S j5       r\S"S j5       r\S 5       rS#S jrS#S jrS#S jrS#S jrSrU =r$ )$r   i  a  Context object providing access to MCP capabilities.

This provides a cleaner interface to MCP's RequestContext functionality.
It gets injected into tool and resource functions that request it via type hints.

To use context in a tool function, add a parameter with the Context type annotation:

```python
@server.tool()
def my_tool(x: int, ctx: Context) -> str:
    # Log messages to the client
    ctx.info(f"Processing {x}")
    ctx.debug("Debug info")
    ctx.warning("Warning message")
    ctx.error("Error message")

    # Report progress
    ctx.report_progress(50, 100)

    # Access resources
    data = ctx.read_resource("resource://data")

    # Get request info
    request_id = ctx.request_id
    client_id = ctx.client_id

    return str(x)
```

The context parameter name can be anything as long as it's annotated with Context.
The context is optional - tools that don't need it can omit the parameter.
ARequestContext[ServerSessionT, LifespanContextT, RequestT] | None_request_contextFastMCP | None_fastmcpNr   c               >   > [         TU ]  " S0 UD6  Xl        X l        g )Nrl   )superr   r  r  )r   r   r   kwargs	__class__s       rv   r   Context.__init__8  s      	"6" /ru   c                J    U R                   c  [        S5      eU R                   $ )zAccess to the FastMCP server.-Context is not available outside of a request)r  r   r   s    rv   r   Context.fastmcpC  s$     == LMM}}ru   c                J    U R                   c  [        S5      eU R                   $ )z)Access to the underlying request context.r  )r  r   r   s    rv   r   Context.request_contextJ  s(    
   (LMM$$$ru   c                   #    U R                   R                  (       a   U R                   R                  R                  OSnUc  gU R                   R                  R	                  UUUUS9I Sh  vN   g N7f)zReport progress for the current operation.

Args:
    progress: Current progress value e.g. 24
    total: Optional total value e.g. 100
    message: Optional message e.g. Starting render...
N)progress_tokenprogresstotalmessage)r   metaprogressTokensessionsend_progress_notification)r   r  r  r  r  s        rv   report_progressContext.report_progressS  sp      EIDXDXD]D]--22@@cg!""**EE)	 F 
 	
 	
s   A+A5-A3.A5c                |   #    U R                   c   S5       eU R                   R                  U5      I Sh  vN $  N7f)zxRead a resource by URI.

Args:
    uri: Resource URI to read

Returns:
    The resource content as either text or bytes
Nr  )r  r   )r   r   s     rv   r   Context.read_resourceg  s8      }}(Y*YY(]]005555s   3<:<c                p   #    [        U R                  R                  XU R                  S9I Sh  vN $  N7f)a  Elicit information from the client/user.

This method can be used to interactively ask for additional information from the
client within a tool's execution. The client might display the message to the
user and collect a response according to the provided schema. Or in case a
client is an agent, it might decide how to handle the elicitation -- either by asking
the user or automatically generating a response.

Args:
    schema: A Pydantic model class defining the expected response structure, according to the specification,
            only primive types are allowed.
    message: Optional message to present to the user. If not provided, will use
            a default message based on the schema

Returns:
    An ElicitationResult containing the action taken and the data if accepted

Note:
    Check the result.action to determine if the user accepted, declined, or cancelled.
    The result.data will only be populated if action is "accept" and validation succeeded.
)r  r  schemarelated_request_idN)r(   r   r  
request_id)r   r  r  s      rv   elicitContext.elicits  s8     6 ,((00'eietet
 
 	
 
s   -646)logger_namec                  #    U R                   R                  R                  UUUU R                  S9I Sh  vN   g N7f)zSend a log message to the client.

Args:
    level: Log level (debug, info, warning, error)
    message: Log message
    logger_name: Optional logger name
    **extra: Additional structured data to include
)leveldatar   r  N)r   r  send_log_messager  )r   r  r  r  s       rv   logContext.log  s@      ""**;;#	 < 
 	
 	
s   4><>c                ~    U R                   R                  (       a!  [        U R                   R                  SS5      $ S$ )zGet the client ID if available.	client_idN)r   r  getattrr   s    rv   r  Context.client_id  s5     IMH\H\HaHawt++00+tDkgkkru   c                @    [        U R                  R                  5      $ )z#Get the unique ID for this request.)rX   r   r  r   s    rv   r  Context.request_id  s     4''2233ru   c                .    U R                   R                  $ )z4Access to the underlying session for advanced usage.)r   r  r   s    rv   r  Context.session  s     ##+++ru   c                H   #    U R                   " SU40 UD6I Sh  vN   g N7f)zSend a debug log message.rU   Nr  r   r  rS   s      rv   rU   Context.debug       hhw15111   " "c                H   #    U R                   " SU40 UD6I Sh  vN   g N7f)zSend an info log message.r   Nr  r  s      rv   r   Context.info  s     hhvw0%000r  c                H   #    U R                   " SU40 UD6I Sh  vN   g N7f)zSend a warning log message.warningNr  r  s      rv   r  Context.warning  s     hhy'3U333r  c                H   #    U R                   " SU40 UD6I Sh  vN   g N7f)zSend an error log message.errorNr  r  s      rv   r  Context.error  r  r  )r  r  )r   r  r   r  r  r   )r   r   )r   z:RequestContext[ServerSessionT, LifespanContextT, RequestT])NN)r  floatr  zfloat | Noner  r  r   r  )r   zstr | AnyUrlr   r  )r  rX   r  ztype[ElicitSchemaModelT]r   z%ElicitationResult[ElicitSchemaModelT])r  z,Literal['debug', 'info', 'warning', 'error']r  rX   r  r  r   r  r  r  )r  rX   rS   r   r   r  )rm   rn   ro   rp   rq   rs   r   r  r   r   r  r   r  r  r  r  r  rU   r   r  r  rt   __classcell__)r  s   @rv   r   r     s.   B XW
 `d"&		  \	   		 
 	  	    %	C% %
(
6

 )
 
/	
H #'
;
 

  
 

, l l 4 4 , ,
2142 2ru   r   )r|   zFastMCP[LifespanResultT]r7   zRCallable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]]r   z]Callable[[MCPServer[LifespanResultT, Request]], AbstractAsyncContextManager[LifespanResultT]]){rq   
__future__r   _annotationsr  r  collections.abcr   r   r   r   r   r	   
contextlibr
   r   typingr   r   r   r   r  pydanticr   pydantic.networksr   pydantic_settingsr   r   starlette.applicationsr   ry  r   #starlette.middleware.authenticationr   starlette.requestsr   starlette.responsesr   rz  r   r   starlette.typesr   r   r   'mcp.server.auth.middleware.auth_contextr   &mcp.server.auth.middleware.bearer_authr    r!   mcp.server.auth.providerr"   r#   r$   mcp.server.auth.settingsr%   mcp.server.elicitationr&   r'   r(   mcp.server.fastmcp.exceptionsr)   mcp.server.fastmcp.promptsr*   r+   mcp.server.fastmcp.resourcesr,   r-   r.   mcp.server.fastmcp.toolsr/   r0   .mcp.server.fastmcp.utilities.context_injectionr1   $mcp.server.fastmcp.utilities.loggingr2   r3    mcp.server.lowlevel.helper_typesr4   mcp.server.lowlevel.serverr5   r6   r   r7   r   mcp.server.sessionr8   r9   mcp.server.sser:   mcp.server.stdior;   mcp.server.streamable_httpr<   "mcp.server.streamable_http_managerr=   mcp.server.transport_securityr>   mcp.shared.contextr?   r@   rA   	mcp.typesrB   rC   rD   rE   rF   r  rG   r  r   rH   r   r   rm   r   rJ   r   r   r  r   rl   ru   rv   <module>r     s%   ; 2  	 ^ ^ G ( (    $ > , + H & ( * 0 0 I [ k k 1 ` ` 7 < T T 6 Q N A 6 : C < - ) 1 K C I I W W ) 9 - = %	H	39|W_5 39l		!	`	 c	J%go& J%Z	H 	Hs2i1A8!KL s2ru   