Xj >dZddlmZddlZddlZddlmZmZm Z m Z m Z m Z ddl mZmZddlmZmZmZddlZddlZddlmZddlmZdd lmZmZdd lmZdd lm Z dd l!m"Z"dd l#m$Z$ddl%m&Z&ddl'm(Z(m)Z)ddl*m+Z+m,Z,m-Z-ddl.m/Z/ddl0m1Z1m2Z2ddl3m4Z4m5Z5m6Z6ddl7m8Z8ddl9m:Z:m;Z;mZ?ddl@mAZAddlBmCZCmDZDddlEmFZFmGZGmHZHddlImJZJmKZKddlLmMZMddlNmOZOmPZPddlQmRZRddlSmTZTddlSmUZVdd lSmWZXdd!lYmZZZm[Z[dd"l\m]Z]dd#l^m_Z_dd$l`maZadd%lbmcZcdd&ldmeZedd'lfmgZgmhZhmiZidd(ljmkZkmlZlmmZmmnZnmoZompZpdd)ljmCZqdd*ljmrZsdd+ljmGZtdd,ljmuZvdd-ljmJZwePexZyGd.d/eeeTZz d7d0Z{Gd1d2eeTZ|Gd3d4Z}Gd5d6eee[egeifZ~y)8z5FastMCP - A more ergonomic interface for MCP servers.) annotationsN) AsyncIterator AwaitableCallable CollectionIterableSequence)AbstractAsyncContextManagerasynccontextmanager)AnyGenericLiteral) BaseModel)AnyUrl) BaseSettingsSettingsConfigDict) Starlette Middleware)AuthenticationMiddleware)Request)ResponseMountRoute)ReceiveScopeSend)AuthContextMiddleware)BearerAuthBackendRequireAuthMiddleware) OAuthAuthorizationServerProviderProviderTokenVerifier TokenVerifier) AuthSettings)ElicitationResultElicitSchemaModelTUrlElicitationResultelicit_with_validation) elicit_url) ResourceError)Prompt PromptManager)FunctionResourceResourceResourceManager)Tool ToolManager)find_context_parameter)configure_logging get_logger)ReadResourceContents)LifespanResultT)Server)lifespan) ServerSessionServerSessionT)SseServerTransport) stdio_server) EventStore)StreamableHTTPSessionManager)TransportSecuritySettings)LifespanContextTRequestContextRequestT) Annotations AnyFunction ContentBlockGetPromptResultIconToolAnnotations)r,)PromptArgument)r/)ResourceTemplate)r1ceZdZUdZedddddZded <d ed <d ed <ded<d ed<d ed<d ed<d ed<ded<ded< ded<ded<ded<ded< ded< ded<ded <y!)"SettingszFastMCP 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__Tignore) env_prefixenv_fileenv_nested_delimiter#nested_model_default_partial_updateextrabooldebug8Literal['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'] log_levelstrhostintport mount_pathsse_path message_pathstreamable_http_path json_responsestateless_httpwarn_on_duplicate_resourceswarn_on_duplicate_toolswarn_on_duplicate_prompts list[str] dependenciesYCallable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]] | Noner9AuthSettings | Noneauth TransportSecuritySettings | Nonetransport_securityN)__name__ __module__ __qualname____doc__r model_config__annotations__m/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/mcp/server/fastmcp/server.pyrMrMNs &!,0 L KGG I IOMI"&%"! $#FggQ 98rurMc2t dfd }|S)NcK4d{}|dddd{y77#1d{7swYyxYwwNrt)_contextappr9s rvwrapzlifespan_wrapper..wrapsFC=  GM       s8 A+A/ A-AAA8 AA)rzz#MCPServer[LifespanResultT, Request]returnzAsyncIterator[LifespanResultT])r )r|r9r}s`` rvlifespan_wrapperrs. . ' KruceZdZ d-ddddddddd ddd d d d dddd  d.d Zed/dZed0dZed0dZed1dZed2dZ d3 d4dZ d5dZ d6dZ d7dZ d8dZd9dZd:dZd;dZ d< d=dZd>dZ d< d?dZdZd@dZdddddddd  dAd!ZdBd"Z dC dDd#Z dE dFd$Zd5d%ZdGdHd&Zd5d'ZdId(ZdGdJd)ZdKd*Z dLd+Z!dGdMd,Z"y)NFastMCPNFINFO 127.0.0.1i@/z/ssez /messages/z/mcpTrt)toolsrWrYr[r]r^r_r`rarbrcrdrerfrhr9rkrmc  || dvrtdgdgd}tdid| d| d| d | d |d |d |d |d|d|d|d|d|dt|d|d|d||_t |xsd||||jj r t ||jj nt|_t| |jj|_ t|jj|_t|jj |_|jj$|r |r t'd|s|st'd|s|r t'd||_||_|r|st-||_||_||_g|_|jj4|_d|_|j9t;|jj<y) N)r localhostz::1T)z 127.0.0.1:*z localhost:*z[::1]:*)zhttp://127.0.0.1:*zhttp://localhost:*zhttp://[::1]:*)enable_dns_rebinding_protection allowed_hostsallowed_originsrWrYr[r]r^r_r`rarbrcrdrerfrhr9rkrmr)name instructions website_urliconsr9)rre)rd)rfz;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 settingsrt)r@rMlistsettings MCPServerr9rdefault_lifespan _mcp_serverr2re _tool_managerr0rd_resource_managerr-rf_prompt_managerrk ValueError_auth_server_provider_token_verifierr# _event_store_retry_interval_custom_starlette_routesrh_session_manager_setup_handlersr4rY)selfrrrrauth_server_providertoken_verifier event_storeretry_intervalrrWrYr[r]r^r_r`rarbrcrdrerfrhr9rkrms rv__init__zFastMCP.__init__s.>  %$2S*S!:04G ^"  !      "    & "6 ( * )D %< '@ l+  ! " 2#  (%"%#IM H^H^&tT]]-C-CDdt )udmmNsNst!0T]]MvMv!w,t}}GnGno ==   )# !^__' !rss !^jk k%9"- #89M#ND '-57% MM66EI  $--112ruc.|jjSry)rrrs rvrz FastMCP.names$$$ruc.|jjSry)rrrs rvrzFastMCP.instructionss,,,ruc.|jjSry)rrrs rvrzFastMCP.website_urls+++ruc.|jjSry)rrrs rvrz FastMCP.iconss%%%rucH|j td|jS)aGet 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 RuntimeErrorrs rvsession_managerzFastMCP.session_managers0  (7  $$$ruc(td}||jvrtd||xdk(r!tjj yxdk(rtjfdydk(r tjj yy)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 )stdiossestreamable-httpzUnknown transport: rrc&jSry) run_sse_async)r^rsrvzFastMCP.run..*s$"4"4Z"@rurN)r__args__ranyiorunrun_stdio_asyncrun_streamable_http_async)r transportr^ TRANSPORTSs` ` rvrz FastMCP.runss>? J// /29+>? ? $../ @A" $889#rucT|jj|j|jjd|j|jj|j|jj |j|jj |j |jj |j |jj|jy)z"Set up core MCP protocol handlers.F)validate_inputN)r list_tools call_toollist_resources read_resource list_prompts get_promptlist_resource_templatesrs rvrzFastMCP._setup_handlers.s%##%doo6 9""%"8H)'')$*=*=>(&&(););<'%%'(9(9:%##%doo6200243O3OPruc *K|jj}|Dcgc]e}t|j|j|j |j |j|j|j|jgc}Scc}ww)zList all available tools.)rtitle description inputSchema outputSchemarr_meta) rrMCPToolrrr parameters output_schemarrmeta)rrinfos rvrzFastMCP.list_tools;s""--/   YYjj ,, OO!// ,,jjii    BA*B Bcl |jj}t||S#t$rd}YwxYw)z Returns a Context object. Note that the context will only be valid during a request; outside a request, most methods will error. Nrequest_contextfastmcp)rr LookupErrorContext)rrs rv get_contextzFastMCP.get_contextLs=  #"..>>OEE #"O #s % 33c|K|j}|jj|||dd{S7w)z#Call a tool by name with arguments.T)r{convert_resultN)rrr)rr argumentsr{s rvrzFastMCP.call_toolWs;""$''11$ 7cg1hhhhs 3<:<c 2K|jj}|Dcgc]i}t|j|jxsd|j |j |j|j|j|jkc}Scc}ww)zList all available resources.)urirrrmimeTyperrr) rr MCPResourcerrrr mime_typerrr)r resourcesresources rvrzFastMCP.list_resources\s**99; &   LL]](bnn$00!++nn$00mm    sBA.BBc *K|jj}|Dcgc]e}t|j|j|j |j |j|j|j|jgc}Scc}ww)N) uriTemplaterrrrrrr) rlist_templatesMCPResourceTemplate uri_templaterrrrrrr)r templatestemplates rvrzFastMCP.list_resource_templatesns**99; &   $11]]nn$00!++nn$00mm    rcK|j}|jj||d{}|std| |j d{}t ||j |jgS7P7)#t$r1}tjd|tt|d}~wwxYww)zRead a resource by URI.r{NzUnknown resource: )contentrrzError reading resource ) rr get_resourcer+readr6rr Exceptionlogger exceptionrZ)rrr{rres rvrzFastMCP.read_resource~s""$//< 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 :j||S)Nr)r) rrrrrrrrrs rv decoratorzFastMCP.tool..decorators3 MM''"3  IrurrEr~rEcallable TypeError) rrrrrrrrrs ```````` rvtoolz FastMCP.tools/T D>s   ruc6|jjS)aDecorator 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 completionrs rvrzFastMCP.completions **,,ruc:|jj|y)zfAdd a resource to the server. Args: resource: A Resource instance to add N)r add_resource)rrs rvrzFastMCP.add_resources ++H5ru)rrrrrrrc `tr tddf d } | S)a Decorator to register a function as a resource. The function will be called when the resource is read to generate its content. The function can return: - str for text content - bytes for binary content - other types will be converted to JSON 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 meta: Optional metadata dictionary 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  tj|}dvxrdv}t|j}|s|rt |}t t jd}|jjDchc] }||k7s | }}||k7rtd|d|jj|  |Stj|  }j||Scc}w)N{}z{(\w+)}z Mismatch between URI parameters z and function parameters ) rrrrrrrrr) rrrrrrrrr)inspect signaturerVrr3setrefindallkeysrr add_templater. from_functionr)rsighas_uri_paramshas_func_params context_param uri_paramsp func_paramsrrrrrrrrrrs rvrz#FastMCP.resource..decoratorOs0##B'C CZ6C3JN"3>>2O 6r : !J!<= +...*=*=*?VQ1 CUqV V,$::,F_`k_lm &&33!$ +' +4 2I,99 +' + !!(+ICWs C> C>rr) rrrrrrrrrrs ````````` rvrzFastMCP.resources4f C=W  / / bruc:|jj|y)z`Add a prompt to the server. Args: prompt: A Prompt instance to add N)r add_prompt)rprompts rvrzFastMCP.add_prompts ''/rucPtr tddfd }|S)aDecorator 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^tj|}j||S)N)rrrr)r,rr)funcrrrrrrs rvrz!FastMCP.prompt..decorators.))$TT_glmF OOF #Kru)rrEr~rEr)rrrrrrs````` rvrzFastMCP.prompts2T D>N     ruc, dfd }|S)a Decorator to register a custom HTTP route on the FastMCP server. Allows adding arbitrary HTTP endpoints outside the standard MCP protocol, which can be useful for OAuth callbacks, health checks, or admin APIs. The handler function must be an async function that accepts a Starlette Request and returns a Response. Routes using this decorator will not require authorization. It is intended for uses that are either a part of authorization flows or intended to be public such as health check endpoints. 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 Zjjt||S)N)endpointmethodsrinclude_in_schema)rappendr)rr"r!rpathrs rvrz'FastMCP.custom_route..decorators7  ) ) 0 0!#&7  Kru)r(Callable[[Request], Awaitable[Response]]r~r%rt)rr$r!rr"rs````` rv custom_routezFastMCP.custom_routes&@ :  5  rucKt4d{\}}|jj|||jjd{dddd{y7U77 #1d{7swYyxYww)z%Run the server using stdio transport.N)r=rrcreate_initialization_options)r read_stream write_streams rvrzFastMCP.run_stdio_asyncs}>  %@k<""&&  >>@          sVBA'B.handle_sseEs  &&**AJAJ$$BBD  :       : sVB!A=B!?BA?B# B!.B/B!?BB!B B BB!backendcreate_auth_routesprovider issuer_urlservice_documentation_urlclient_registration_optionsrevocation_optionsbuild_resource_metadata_urlGET)r r!)r|cpK|j|j|jd{S7wry)rArB_send)requestrEs rv sse_endpointz%FastMCP.sse_app..sse_endpoints(' w VVVVs ,646 create_protected_resource_routes resource_urlauthorization_serversscopes_supported)rWroutes middleware)rArrBrrCr)rUrr~r)#starlette.middlewarerstarlette.routingrrrr^r;r`r<rmrkrequired_scopesrrr rrmcp.server.auth.routesrIextendrLrMrNrOresource_server_urlrQr#r_r!handle_post_messagerXrrrW)rr^rrrnormalized_message_endpointr]r^rarIresource_metadata_urlrQrVrXrErs` @@rvr.zFastMCP.sse_app2s32  !'1DMM $'+&:&:4==;S;SUYUbUbUoUo&p#! '"mm>>   ')')  ==  "mm00@@FBO##0 1$2F2F G 45  ))E &!%!;!;#'==#5#5#@#@26--2D2D2^2^48MM4F4F4b4b+/==+=+=+P+P    $( !}}!!dmm&8&8&L&LN)DDMMDVDVDjDj(k% MMMM**2:Pef"G  MMMM..-c.E.EXmn  W MMMM**)"G  MMMM..//  ==  $--"4"4"H"H O MM0!%!3!3!G!G+/==+=+=+H+H*I%)]]%7%7%G%G   d334t}}226jYYruc "ddlm}jptjj j jjjjjj_tj}g}g}g}jjr jjjxsg}jr-|tt!j|t"g}j$rddlm}|j+|j$jjj,jjj.jjj0jjj2jrd}jjrLjjj4r,ddlm}|jjj4}|j9t;jj<t?||| n0|j9t;jj<| jjrjjj4r{dd lm } |j+| jjj4jjj,gjjj |j+jBtEjjF||fd  S)z4Return an instance of the StreamableHTTP server app.rrN)r|rrrb statelessr=rFrHrJrP)r rWrYc8jjSry)rr)r|rs rvrz-FastMCP.streamable_http_app..s!5!5!9!9!;ru)rWr]r^r9)$r_rrr?rrrrrbrcrmStreamableHTTPASGIApprkrarrr rrrbrIrcrLrMrNrOrdrQr#rrar!rXrrrW) rrr6r]r^rarIrgrQrXs ` rvr6zFastMCP.streamable_http_apps3  ($@$$ --#33"mm99--66"&--"B"B %D !4D4I4IJ')')  ==  "mm00@@FBO##0 1$2F2F G45  ))E &!%!;!;#'==#5#5#@#@26--2D2D2^2^48MM4F4F4b4b+/==+=+=+P+P    $( !}}!!dmm&8&8&L&LN)DDMMDVDVDjDj(k% MMMM6623FYno  MMMM660  ==  $--"4"4"H"H O MM0!%!3!3!G!G+/==+=+=+H+H*I%)]]%7%7%G%G   d334--%%!;   rucpK|jj}|Dcgc]}t|j|j|j |j xsgDcgc].}t|j|j |j0c}|jc}}Scc}wcc}}ww)zList all available prompts.)rrrequired)rrrrr) rr MCPPromptrrrrMCPPromptArgumentrmr)rpromptsrargs rvrzFastMCP.list_promptss&&335 "  [[ll"..!' 0 0 6B   & XX$'OO!$ll     s( B6=B03B+B0'B6+B00B6cK |jj|}|std||j||j d{}t |j tj|S7.#t$r1}tjd|tt|d}~wwxYww)z$Get a prompt by name with arguments.zUnknown prompt: rN)rmessageszError getting prompt ) rrrrenderrrGr pydantic_coreto_jsonable_pythonrrrrZ)rrrrrsrs rvrzFastMCP.get_prompt,s %))44T:F #3D6!:;;#]]9d>N>N>P]QQH""..&99(C R  %   4TF; <SV$ $ %s;CABB-BCB B> ,B99B>>C)NNNNNNNN)4r str | Nonerrwrrwrlist[Icon] | Nonerz6OAuthAuthorizationServerProvider[Any, Any, Any] | NonerzTokenVerifier | NonerzEventStore | Nonerz int | Nonerzlist[Tool] | NonerWrVrYrXr[rZr]r\r^rZr_rZr`rZrarZrbrVrcrVrdrVrerVrfrVrhzCollection[str]r9rirkrjrmrlr~rZr~rw)r~rx)r~r?)rN)rz*Literal['stdio', 'sse', 'streamable-http']r^rwr~Noner~r{)r~z list[MCPTool])r~z0Context[ServerSession, LifespanResultT, Request])rrZrzdict[str, Any]r~z'Sequence[ContentBlock] | dict[str, Any])r~zlist[MCPResource])r~zlist[MCPResourceTemplate])rz AnyUrl | strr~Iterable[ReadResourceContents])NNNNNNN)rrErrwrrwrrwrToolAnnotations | Nonerrxrdict[str, Any] | Noner bool | Noner~r{)rrZr~r{)rrwrrwrrwrr~rrxrrrrr~$Callable[[AnyFunction], AnyFunction])rr/r~r{)rrZrrwrrwrrwrrwrrxrzAnnotations | Nonerrr~r)rr,r~r{)NNNN) rrwrrwrrwrrxr~r)NT)r$rZr!rgrrwr"rVry)r^rwr~r{)r^rZr rZr~rZ)r^rwr~r)r~r)r~zlist[MCPPrompt])rrZrrr~rG)#rnrorprpropertyrrrrrrrrrrrrrrrrrrrrrr&rrrr;r.r6rrrtrurvrrsM #'"&#'Y]/3)-%)_3$(NT($*#$,0(,*.(*pt$(?C9_3_3!_3 _3 ! _3 V _3-_3'_3#_3!_3_3L_3_3_3 !_3"#_3$%_3&"'_3()_3*+_3,&*-_3."&/_30$(1_32&3_34m5_36"7_38=9_3B%%--,,&&%%(AH!%:=::  :. Q " Fi  $ ($  "&.2#'&*)-$ $ $  $  $ , $ !$ $$ '$  $ L -  "&.2#'&*)-<<< < , < ! <$<'< .<|-$6  "& $#'*.&*j j j  j  jj!j(j$j .jX0  "&#' 555 5 ! 5 . 5v "& ... .  .`  %4BZH_ B *%rurc eZdZdZddZddZy)rkz@ ASGI application for Streamable HTTP server transport. c||_yry)r)rrs rvrzStreamableHTTPASGIApp.__init__Cs .rucZK|jj|||d{y7wry)rhandle_request)rrArBrCs rv__call__zStreamableHTTPASGIApp.__call__Fs$""11%$GGGs !+)+N)rr?)rArrBrrCrr~r{)rnrorprqrrrtrurvrkrk>s/Hrurkc2eZdZUdZded<ded<ddd dfdZedd Ze dd Zddd Z dd Z d d Z d!dZ dd d"dZ ed#dZed$dZedZd%dZd%dZd&dZd&dZd&dZd&dZxZS)'raContext 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_contextFastMCP | None_fastmcpNrc @t|di|||_||_y)Nrt)superrrr)rrrkwargs __class__s rvrzContext.__init__os$ "6" / rucH|j td|jS)zAccess to the FastMCP server.-Context is not available outside of a request)rrrs rvrzContext.fastmcpzs$ == LM M}}rucH|j td|jS)z)Access to the underlying request context.r)rrrs rvrzContext.request_contexts(  (LM M$$$rucK|jjr |jjjnd}|y|jjj ||||d{y7w)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_tokenprogresstotalmessage)rr progressTokensessionsend_progress_notification)rrrrrs rvreport_progresszContext.report_progresssqEIDXDXD]D]--22@@cg  ! ""**EE) F   sA(A2*A0+A2czK|jJd|jj|d{S7w)zRead a resource by URI. Args: uri: Resource URI to read Returns: The resource content as either text or bytes Nr)rr)rrs rvrzContext.read_resources9}}(Y*YY(]]005555 2;9;cxKt|jj|||jd{S7w)aNElicit 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. )rrschemarelated_request_idN)r)rr request_id)rrrs rvelicitzContext.elicits;6,((00#     s 1:8:czKt|jj||||jd{S7w)aRequest URL mode elicitation from the client. This directs the user to an external URL for out-of-band interactions that must not pass through the MCP client. Use this for: - Collecting sensitive credentials (API keys, passwords) - OAuth authorization flows with third-party services - Payment and subscription flows - Any interaction where data should not pass through the LLM context The response indicates whether the user consented to navigate to the URL. The actual interaction happens out-of-band. When the elicitation completes, call `self.session.send_elicit_complete(elicitation_id)` to notify the client. Args: message: Human-readable explanation of why the interaction is needed url: The URL the user should navigate to elicitation_id: Unique identifier for tracking this elicitation Returns: UrlElicitationResult indicating accept, decline, or cancel )rrurlelicitation_idrN) _elicit_urlrrr)rrrrs rvr*zContext.elicit_urls>6!((00)#     r) logger_namecK|jjj||||jd{y7w)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 )leveldatarrN)rrsend_log_messager)rrrrs rvlogz Context.logsA""**;;# <   s7A?Act|jjr!t|jjddSdS)zGet the client ID if available. Note: this reads from the MCP request's `_meta` params, not the OAuth bearer token. For that, use `get_access_token().client_id`. client_idN)rrgetattrrs rvrzContext.client_ids9FJEYEYE^E^GD((--{D A dh ruc@t|jjS)z#Get the unique ID for this request.)rZrrrs rvrzContext.request_ids4''2233ruc.|jjS)z4Access to the underlying session for advanced usage.)rrrs rvrzContext.sessions##+++rucK|jr:|jjr#|jjd{yyy7w)aClose the SSE stream to trigger client reconnection. This method closes the HTTP connection for the current request, triggering client reconnection. Events continue to be stored in the event store and will be replayed when the client reconnects with Last-Event-ID. Use this to implement polling behavior during long-running operations - client will reconnect after the retry interval specified in the priming event. Note: This is a no-op if not using StreamableHTTP transport with event_store. The callback is only available when event_store is configured. N)rclose_sse_streamrs rvrzContext.close_sse_streamsC  T%:%:%K%K''88: : :&L :AA A A cK|jr:|jjr#|jjd{yyy7w)aClose the standalone GET SSE stream to trigger client reconnection. This method closes the HTTP connection for the standalone GET stream used for unsolicited server-to-client notifications. The client SHOULD reconnect with Last-Event-ID to resume receiving notifications. Note: This is a no-op if not using StreamableHTTP transport with event_store. Currently, client reconnection for standalone GET streams is NOT implemented - this is a known gap. N)rclose_standalone_sse_streamrs rvrz#Context.close_standalone_sse_stream,sC  T%:%:%V%V''CCE E E&W ErcHK|jd|fi|d{y7w)zSend a debug log message.rWNrrrrUs rvrWz Context.debug<!dhhw15111 " "cHK|jd|fi|d{y7w)zSend an info log message.rNrrs rvrz Context.info@s!dhhvw0%000rcHK|jd|fi|d{y7w)zSend a warning log message.warningNrrs rvrzContext.warningDs!dhhy'3U333rcHK|jd|fi|d{y7w)zSend an error log message.errorNrrs rvrz Context.errorHrr)rrrrrr )r~r)r~z:RequestContext[ServerSessionT, LifespanContextT, RequestT])NN)rfloatrz float | Nonerrwr~r{)rz str | AnyUrlr~r})rrZrztype[ElicitSchemaModelT]r~z%ElicitationResult[ElicitSchemaModelT])rrZrrZrrZr~r()rz,Literal['debug', 'info', 'warning', 'error']rrZrrwr~r{rzryr|)rrZrUr r~r{)rnrorprqrsrrrrrrrr*rrrrrrrWrrr __classcell__)rs@rvrrJsYBXW `d"&  \       % C%% ( 6    )   /  D! ! !  !  ! P#'  ;      .  44,,;" F 2142rur)r|zFastMCP[LifespanResultT]r9zRCallable[[FastMCP[LifespanResultT]], AbstractAsyncContextManager[LifespanResultT]]r~z]Callable[[MCPServer[LifespanResultT, Request]], AbstractAsyncContextManager[LifespanResultT]])rq __future__r _annotationsr r collections.abcrrrrrr contextlibr r typingr r rrrupydanticrpydantic.networksrpydantic_settingsrrstarlette.applicationsrr_r#starlette.middleware.authenticationrstarlette.requestsrstarlette.responsesrr`rrstarlette.typesrrr'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(r)r*rmcp.server.fastmcp.exceptionsr+mcp.server.fastmcp.promptsr,r-mcp.server.fastmcp.resourcesr.r/r0mcp.server.fastmcp.toolsr1r2.mcp.server.fastmcp.utilities.context_injectionr3$mcp.server.fastmcp.utilities.loggingr4r5 mcp.server.lowlevel.helper_typesr6mcp.server.lowlevel.serverr7r8rr9rmcp.server.sessionr:r;mcp.server.sser<mcp.server.stdior=mcp.server.streamable_httpr>"mcp.server.streamable_http_managerr?mcp.server.transport_securityr@mcp.shared.contextrArBrC mcp.typesrDrErFrGrHrIrnrJrorrKrrrnrrMrrrkrrtrurvrs?;2 H(( $>,+H&(*00I 2 8<TT6QNA6:C<-)1KCIIdd)9-=% H 39|W_539l  ! ` c i%go&i%X H H@2i1A8!KL@2ru