XjvUdZddlmZddlZddlZddlZddlZddlZddl m Z m Z m Z m Z ddlmZmZmZddlmZmZmZmZddlZddlZddlmZmZddlmZdd lmZm Z ddl!m"Z"dd l#m$Z$dd l%m&Z&dd l'm(Z(dd l)m*Z*ddl+m,Z,ddl-m.Z.ddl/m0Z0ddl1m2Z2m3Z3ddl4m5Z5m6Z6ddl7m8Z8ddl9m:Z:ejve<Z=edeZ>edeZ?e@eAefZBdeCd<e e"jZEdeCd<eFeEeBfZGdeCd<ejdZIdeCd<GddZJed$d ZKGd!d"ee>e?fZLd%d#ZMy)&ay MCP Server Module This module provides a framework for creating an MCP (Model Context Protocol) server. It allows you to easily define and handle various types of requests and notifications in an asynchronous manner. Usage: 1. Create a Server instance: server = Server("your_server_name") 2. Define request handlers using decorators: @server.list_prompts() async def handle_list_prompts(request: types.ListPromptsRequest) -> types.ListPromptsResult: # Implementation @server.get_prompt() async def handle_get_prompt( name: str, arguments: dict[str, str] | None ) -> types.GetPromptResult: # Implementation @server.list_tools() async def handle_list_tools(request: types.ListToolsRequest) -> types.ListToolsResult: # Implementation @server.call_tool() async def handle_call_tool( name: str, arguments: dict | None ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: # Implementation @server.list_resource_templates() async def handle_list_resource_templates() -> list[types.ResourceTemplate]: # Implementation 3. Define notification handlers if needed: @server.progress_notification() async def handle_progress( progress_token: str | int, progress: float, total: float | None, message: str | None ) -> None: # Implementation 4. Run the server: async def main(): async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): await server.run( read_stream, write_stream, InitializationOptions( server_name="your_server_name", server_version="your_version", capabilities=server.get_capabilities( notification_options=NotificationOptions(), experimental_capabilities={}, ), ), ) asyncio.run(main()) The Server class provides methods to register handlers for various MCP requests and notifications. It automatically manages the request context and handles incoming messages from the client. ) annotationsN) AsyncIterator AwaitableCallableIterable)AbstractAsyncContextManagerAsyncExitStackasynccontextmanager)AnyGeneric TypeAliascast)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl)TypeVar deprecated) Experimental)ExperimentalHandlers)create_call_wrapper)ReadResourceContents)InitializationOptions) ServerSession)RequestContext)McpErrorUrlElicitationRequiredError)ServerMessageMetadataSessionMessage)RequestResponder)validate_and_warn_tool_nameLifespanResultT)defaultRequestTr StructuredContentUnstructuredContentCombinationContent request_ctxz?contextvars.ContextVar[RequestContext[ServerSession, Any, Any]]c&eZdZ d ddZy)NotificationOptionsc.||_||_||_yN)prompts_changedresources_changed tools_changed)selfr,r-r.s n/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/mcp/server/lowlevel/server.py__init__zNotificationOptions.__init__qs /!2*N)FFF)r,boolr-r3r.r3)__name__ __module__ __qualname__r1r2r0r)r)ps.!&"'# ++ + +r2r)cKiyw)zDefault lifespan context manager that does nothing. Args: server: The server instance this lifespan is managing Returns: An empty context object Nr7)_s r0lifespanr:|s  Hs c^eZdZddddef ddZ d ddZ ddZe d dZee dd!dZ dZ d Z d Z d Zd Zd ZdZdZdZd"dZd#dZddd$dZdZdZ d% d&dZ d' d(dZ d)dZd*dZy)+ServerNc||_||_||_||_||_||_t jti|_ i|_ i|_ d|_ tjd|y)NzInitializing server %r)nameversion instructions website_urliconsr:types PingRequest _ping_handlerrequest_handlersnotification_handlers _tool_cache_experimental_handlersloggerdebug)r/r>r?r@rArBr:s r0r1zServer.__init__sq  (&     }[ RT"24CG# -t4r2c dd}t|j|jr |jn|d|j|xs t |xsi|j |j |jS)z8Create initialization options from this server instance.c> ddlm}||S#t$rYywxYw)Nr)r?unknown)importlib.metadatar? Exception)packager?s r0 pkg_versionz9Server.create_initialization_options..pkg_versions* 6w''  s  mcp) server_nameserver_version capabilitiesr@rArB)rQstrreturnrW)rr>r?get_capabilitiesr)r@rArB)r/notification_optionsexperimental_capabilitiesrRs r0create_initialization_optionsz$Server.create_initialization_optionssn % +/<<4<<[=O..$=(;(=)/R**((**  r2cd}d}d}d}d}tj|jvr tj|j}tj |jvr!tj d|j}tj|jvr tj|j}tj|jvrtj}tj|jvrtj}tj||||||}|j r|j j#||S)z9Convert existing handlers to a ServerCapabilities object.N) listChangedF) subscriber^)prompts resourcestoolslogging experimental completions)rCListPromptsRequestrFPromptsCapabilityr,ListResourcesRequestResourcesCapabilityr-ListToolsRequestToolsCapabilityr.SetLevelRequestLoggingCapabilityCompleteRequestCompletionsCapabilityServerCapabilitiesrIupdate_capabilities) r/rZr[prompts_capabilityresources_capabilitytools_capabilitylogging_capabilitycompletions_capabilityrVs r0rYzServer.get_capabilitiessB "#!!%  # #t'<'< )> >#(#<#<-A-S-S$  ! !T%:%: :$44AUAcAcd   D$9$9 9!&!8!8!:   D$9$9 9%*%@%@%B "//&*"&2.    & &  ' ' ; ;L Ir2c*tjS)zFIf called outside of a request context, this will raise a LookupError.)r'getr/s r0request_contextzServer.request_contexts   r2zThe experimental tasks API is deprecated and will be removed in mcp 2.0: tasks (SEP-1686) were removed from the MCP specification and are expected to return as a separate MCP extension.c~|j&t||j|j|_|jS)aExperimental APIs for tasks and other features. Deprecated: the experimental tasks API will be removed in mcp 2.0. Tasks (SEP-1686) were removed from the MCP specification and are expected to return as a separate MCP extension. )rIrrFrGrys r0rdzServer.experimentals:  & & .*>tTEZEZ\`\v\v*wD '***r2c dfd }|S)Nctjdt|tjdfd }|j tj<|S)Nz)Registering handler for PromptListRequestcK|d{}t|tjrtj|Stjtj|S7\w)N)r`) isinstancerCListPromptsResult ServerResultreqresultwrappers r0handlerz7Server.list_prompts..decorator..handlersW&s|+fe&=&=> --f55!--e.E.Ef.UVV , A.A,AA.)rztypes.ListPromptsRequest)rJrKrrCrfrFfuncrrr/s @r0 decoratorz&Server.list_prompts..decorator sH LLD E)$0H0HIG W?FD ! !%":": ;Kr2)rzvCallable[[], Awaitable[list[types.Prompt]]] | Callable[[types.ListPromptsRequest], Awaitable[types.ListPromptsResult]]r7r/rs` r0 list_promptszServer.list_promptss W (r2c dfd }|S)Ncztjddfd }|jtj<S)Nz(Registering handler for GetPromptRequestcK|jj|jjd{}tj|S7wr+)paramsr> argumentsrCr)r prompt_getrs r0rz5Server.get_prompt..decorator..handler%s?#' 9M9M#NN ))*55Os5AAA)rztypes.GetPromptRequest)rJrKrFrCGetPromptRequestrrr/s` r0rz$Server.get_prompt..decorator s5 LLC D 6=DD ! !%"8"8 9Kr2)rzHCallable[[str, dict[str, str] | None], Awaitable[types.GetPromptResult]]r7rs` r0 get_promptzServer.get_prompts Z r2c dfd }|S)Nctjdt|tjdfd }|j tj<|S)Nz,Registering handler for ListResourcesRequestcK|d{}t|tjrtj|Stjtj|S7\w)N)ra)rrCListResourcesResultrrs r0rz9Server.list_resources..decorator..handler7sX&s|+fe&?&?@ --f55!--e.G.GRX.YZZ ,r)rztypes.ListResourcesRequest)rJrKrrCrhrFrs @r0rz(Server.list_resources..decorator/sI LLG H)$0J0JKG [AHD ! !%"<"< =Kr2)rz|Callable[[], Awaitable[list[types.Resource]]] | Callable[[types.ListResourcesRequest], Awaitable[types.ListResourcesResult]]r7rs` r0list_resourceszServer.list_resources.s [ (r2cdfd }|S)Ncztjddfd }|jtj<S)Nz4Registering handler for ListResourceTemplatesRequestcKd{}tjtj|S7-w)N)resourceTemplates)rCrListResourceTemplatesResult)r9 templatesrs r0rzBServer.list_resource_templates..decorator..handlerIs2"&&L ))%*K*K^g*hii)s ><.>)r9r )rJrKrFrCListResourceTemplatesRequestrs` r0rz1Server.list_resource_templates..decoratorFs5 LLO P jIPD ! !%"D"D EKr2)rz5Callable[[], Awaitable[list[types.ResourceTemplate]]]r7rs` r0list_resource_templateszServer.list_resource_templatesE r2c dfd }|S)Ncztjddfd }|jtj<S)Nz+Registering handler for ReadResourceRequestc jKjjd{}d d fd }|xxxtdx\nxtdx\nn)}t j dt d||d}nxtdxb\}|Dcgc]+}||j|jt|dd-}}tjtj|S tdt|tjtj|gS7cc}ww) Nmetac^|d|ini}|xxtdx5\}tjdjj||xsdd|Sxt dxU\}tj djjtj|j|xsdd|Sy)N_metar7z text/plain)uritextmimeTypezapplication/octet-stream)rblobr) rWrCTextResourceContentsrrbytesBlobResourceContentsbase64 b64encodedecode)data mime_typer meta_kwargsrs r0create_contentzPServer.read_resource..decorator..handler..create_content[sEIEU7D/[]K*SU]#(#=#=$$'JJNN%))2)Bl$#. $+-UW_#(#=#=$$'JJNN%+%5%5d%;%B%B%D)2)P6P$#. $-r2r7zdReturning str or bytes from read_resource is deprecated. Use Iterable[ReadResourceContents] instead.) stacklevel)contentsz+Unexpected return type from read_resource: r+)rz str | bytesr str | Nonerzdict[str, Any] | None)rrrWrwarningswarnDeprecationWarningrcontentrgetattrrCrReadResourceResult ValueErrortype) rrrrrr content_item contents_listrs ` r0rz8Server.read_resource..decorator..handlerXs2#CJJNN33&00 J.'(  #1t"<10/ 19 )!-+ , 4 4l6L6LgVbdjlpNq) ) %11!44)6 0(+VW[\bWcVd)eff)),,")[4>)s# D3D+A'D3 0D..decoratorSs7 LLF G2 h@GD ! !%";"; <Kr2)rzKCallable[[AnyUrl], Awaitable[str | bytes | Iterable[ReadResourceContents]]]r7rs` r0 read_resourcezServer.read_resourceRs: ]: xr2cdfd }|S)Ncztjddfd }|jtj<S)Nz'Registering handler for SetLevelRequestcK|jjd{tjtjS7+wr+)rlevelrCr EmptyResultrrs r0rz.decorator..handlers>3::++,,,))%*;*;*=>>- AA,A)rztypes.SetLevelRequest)rJrKrFrCrlrs` r0rz+Server.set_logging_level..decorators3 LLB C ?.decorator..handler<3::>>***))%*;*;*=>>+r)rztypes.SubscribeRequest)rJrKrFrCSubscribeRequestrs` r0rz,Server.subscribe_resource..decorators3 LLC D ?=DD ! !%"8"8 9Kr2rz#Callable[[AnyUrl], Awaitable[None]]r7rs` r0subscribe_resourcezServer.subscribe_resourcerr2cdfd }|S)Ncztjddfd }|jtj<S)Nz*Registering handler for UnsubscribeRequestcK|jjd{tjtjS7+wr+rrs r0rz?Server.unsubscribe_resource..decorator..handlerrr)rztypes.UnsubscribeRequest)rJrKrFrCUnsubscribeRequestrs` r0rz.Server.unsubscribe_resource..decorators3 LLE F ??FD ! !%":": ;Kr2rr7rs` r0unsubscribe_resourcezServer.unsubscribe_resourcerr2c dfd }|S)Nctjdt|tjdfd }|j tj<|S)Nz(Registering handler for ListToolsRequestcK|d{}t|tjrT|jD]0}t |j |j |j <2tj|Sj j|D]0}t |j |j |j <2tjtj|S7w)N)rb) rrCListToolsResultrbr r>rHrclear)rrtoolr/rs r0rz5Server.list_tools..decorator..handlers&s|+fe&;&;< & ;3DII>6:((3;!--f55$$**, &;3DII>6:((3;!--e.C.C&.QRR!,s C<C:C+C<)rztypes.ListToolsRequest)rJrKrrCrjrFrs @r0rz$Server.list_tools..decoratorsH LLC D)$0F0FGG S&=DD ! !%"8"8 9Kr2)rzpCallable[[], Awaitable[list[types.Tool]]] | Callable[[types.ListToolsRequest], Awaitable[types.ListToolsResult]]r7rs` r0 list_toolszServer.list_toolss S <r2ctjtjtjd|gdS)z3Create a ServerResult with an error CallToolResult.rrrT)risError)rCrCallToolResult TextContent)r/ error_messages r0_make_error_resultzServer._make_error_results9!!  **]KL   r2cNK||jvr]tj|jvrAtj d||jtjdd{|jj |}|tjd||S79w)z|Get tool definition from cache, refreshing if necessary. Returns the Tool object if found, None otherwise. z(Tool cache miss for %s, refreshing cacheNz5Tool '%s' not listed, no validation will be performed)rHrCrjrFrJrKrxwarning)r/ tool_namers r0_get_cached_tool_definitionz"Server._get_cached_tool_definitions D,, ,%%)>)>> GSCd++E,B,BCDIII##I. < NNRT] ^ JsA'B%)B#*:B%T)validate_inputc dfd }|S)aRegister a tool call handler. Args: validate_input: If True, validates input against inputSchema. Default is True. The handler validates input against inputSchema (if validate_input=True), calls the tool function, and builds a CallToolResult with the results: - Unstructured content (iterable of ContentBlock): returned in content - Structured content (dict): returned in structuredContent, serialized JSON text returned in content - Both: returned in content and structuredContent If outputSchema is defined, validates structuredContent or errors if missing. c~tjddfd }|jtj<S)Nz'Registering handler for CallToolRequestcK |jj}|jjxsi} j|d{} r$|r" t j ||j ||d{}t|tjrtj|St|tjrtj|St|tr"t!|dk(rt#t$|\}}nt|t&r>t#t(|}tj*dt-j.|dg}nFt1|drt#t2|}d}n' jdt5|j6S|rA|j85| jd S t j ||j8tjtjt;||d S7#tj$r(} jd|jcYd}~Sd}~wwxYw7#tj$r(} jd |jcYd}~Sd}~wwxYw#t<$rt>$r$} jtA|cYd}~Sd}~wwxYww) N)instanceschemazInput validation error: rr)indentr__iter__z"Unexpected return type from tool: zOOutput validation error: outputSchema defined but no structured output returnedzOutput validation error: F)rstructuredContentr)!rr>rr jsonschemavalidate inputSchemaValidationErrorrmessagerrCrrCreateTaskResulttuplelenrr&dictr$rjsondumpshasattrr%rr4 outputSchemalistrrPrW) rrrreresultsunstructured_contentmaybe_structured_contentrr/rs r0rz4Server.call_tool..decorator..handlers>; # I # 4 4 :I!%!A!A)!LLD&$c&//4K[K[\ %)I$>>G "'5+?+?@$11'::#GU-C-CD$11'::#GU3G 8IIMN`biIjF,.F#GT2378I73S0050A0AvTXT^T^_fopTq0r/s, *5/34G/Q,370#669[\`ah\i\r\r[s7tuu 1 1 =3;#'#:#: q$h * 3 3=U^b^o^o p !--,,$()=$>.F$)_M *99c#'#:#:=UVWV_V_U`;a#bbc?B$.#=#=h'+'>'>AZ[\[d[dZe?f'g gh3 ;223q6::;sKAJ" H  J"!H#4 J"I!2J"3K4.J""K#CJ"(K) J" K !I$,3J"K J"#I6IIJ"KIJ"$J7JJJ"KJJ""K4K KKKK)rztypes.CallToolRequest)rJrKrFrCCallToolRequest)rrr/rs` r0rz#Server.call_tool..decorators6 LLB C? ;B.decorator..handler[sMJJ,,JJ''JJ$$JJ&& sAA*"A(#A*)rztypes.ProgressNotification)rJrKrGrCProgressNotificationrs` r0rz/Server.progress_notification..decoratorVs6 LLG H FMD & &u'A'A BKr2)rzGCallable[[str | int, float, float | None, str | None], Awaitable[None]]r7rs` r0progress_notificationzServer.progress_notificationUs Y  r2c dfd }|S)z7Provides completions for prompts and resource templatescztjddfd }|jtj<S)Nz'Registering handler for CompleteRequestc DK|jj|jj|jjd{}t j t j | |St jgddS7Pw)N)valuesrhasMore) completion)rrefargumentcontextrCrCompleteResult Completion)rrrs r0rz5Server.completion..decorator..handlerws#'  8K8KSZZM_M_#`` ))((%1$.#--RtTRasA B  BAB )rztypes.CompleteRequest)rJrKrFrCrnrs` r0rz$Server.completion..decoratorks5 LLB C %>t}}T?R%SS !55 *' GHLGbGb466CChlL'..w).L// 0@0@0BCCC..0 - -B-)0)B)B  g %;WE  00##,, -" -SD - )BOO**,BOO**,# - - - - -#" -" -" -" -" -sGD-G$F/D0%F/D2 AF/?D4F/D6F/ F" E.D:2D8 3D:67E-G0F/2F/4F/6F/8D::E<FE33F6 F/FF/F FF F/ G(F+)G/G5F8 6G=Gc Ktjd5}|xxtdxC\tjdx.\}}|5|j |||||d{dddnyxtj dx\}|j|d{nEtdx:\tjd||jddd d{|r||D]7} tjd | jj| j9 dddy7#1swYQxYw77_#1swYyxYww) NT)recordrequest)rootr7z Received exception from stream: errorzInternal Server Errorzmcp.server.exception_handler)rrrJzWarning: %s: %s)rcatch_warningsrrC ClientRequest_handle_requestClientNotification_handle_notificationrPrJr9send_log_messageinfocategoryr4r) r/rr2r1r/wr respondernotifyrs r0r)zServer._handle_messagesT $ $D 1 [QY%Le.A.A.KY"n"227CJZ\lmmmnnZ;U--:33F;;;;[LL#CG9!MN!22%4=3 (% ! [ -w/?/?/H/H'//Z [# [ [nnn< [ [sfE)D:D*D(D* 7D:D6AD:D8AD: E(D**D3 /D:8D::E?EcKtjdt|j|jj t|x}rtj dt|jd} d}d} d} |j\t|jtrB|jj}|jj} |jj} |jr|jjnd} |jr|jj nd} d} t#|dr#|j$t'|j$dd} t(j+t-|j.|j0||t3| | || || | }||d{}|;t(j?|n%tCjDtBjHd } |jK|d{tj d y7q#t4$r}|j6}Yd}~d}~wt9j:$rH|j<r:tjd|j.Y|t(j?|yyt@$r0}|r|tCjDdtG|d }Yd}~d}~wwxYw#|t(j?|wwxYw7#t8jLt8jNf$r#tj d |j.YywxYww)NzProcessing request of type %szDispatching request of type %srtask) task_metadata_client_capabilities_session _task_support)r7close_sse_streamclose_standalone_sse_streamz4Request %s cancelled - duplicate response suppressedr)coderrzMethod not found)rMrz*Response for %s dropped - transport closedz Response sent)(rJr@rr4rFrxrKmessage_metadatarrrzrKrL client_paramsrVrIr"rrrr'setr request_id request_metarrr9r%get_cancelled_exc_class cancelledresetrPrC ErrorDatarWMETHOD_NOT_FOUNDrespondBrokenResourceErrorClosedResourceError)r/rrr2r1r/rtoken request_dataclose_sse_stream_cbclose_standalone_sse_stream_cbclient_capabilitiesr"rGresponseerrs r0r<zServer._handle_requests  3T#Y5G5GH++//S : :7 : LL949;M;M NE; -# &*#15.++7J,,.C=$+#;#;#K#KL*1*B*B*S*S'5<5M5M5i5i2MTLaLag&;&;&H&Hgk#KOKfKft::GGlp $ 3)cjj.D$+CJJ$EM#"**,,($*71D%,*6  !-)<4R"")-*$%%e,++*H //(+ + +  _%S. %99002 $$KKN**$%%e,% P#I ??3s8$O P $%%e,% ,))5+D+DE  LLEwGYGY Z  sAzServer._handle_notification3s|0044T&\B B7 B LL>V @U@U V Ofo%% C& O  !MN Os<AB  A'A%A'#B %A''BB BB ) r>rWr?rr@rrArrBzlist[types.Icon] | Noner:z[Callable[[Server[LifespanResultT, RequestT]], AbstractAsyncContextManager[LifespanResultT]])NN)rZzNotificationOptions | Noner[z dict[str, dict[str, Any]] | NonerXr)rZr)r[zdict[str, dict[str, Any]]rXztypes.ServerCapabilities)rXz8RequestContext[ServerSession, LifespanResultT, RequestT])rXr)rrWrXtypes.ServerResult)rrWrXztypes.Tool | None)rr3)FF) r,z5MemoryObjectReceiveStream[SessionMessage | Exception]r-z&MemoryObjectSendStream[SessionMessage]r.rr/r3r r3)F)rz`RequestResponder[types.ClientRequest, types.ServerResult] | types.ClientNotification | Exceptionr2rr1r!r/r3) rz9RequestResponder[types.ClientRequest, types.ServerResult]rztypes.ClientRequestTyper2rr1r!r/r3)rDr )r4r5r6r:r1r\rYpropertyrzrrdrrrrrrrrrrrr rrr$r)r<r>r7r2r0r<r<s##'"&)- 555! 5  5 ' 5 58<@FJ 8 $D    :,1,$=, " ,\! A!!  ^ +  +. . =~   B  37aF&N"'  2-J2-=2-!6 2-2-2-r"' [q[[* [  [6\&J\&%\& \& * \&  \&|Or2r<cXKtjtjSwr+)rCrrr6s r0rErE=s   e//1 22s(*)r9z!Server[LifespanResultT, RequestT]rXzAsyncIterator[dict[str, Any]])r7ztypes.PingRequestrXrd)N__doc__ __future__r _annotationsr contextvarsrrcrcollections.abcrrrr contextlibrr r typingr r r rr%ranyio.streams.memoryrrpydanticrtyping_extensionsrr mcp.typesrC'mcp.server.experimental.request_contextr mcp.server.lowlevel.experimentalr#mcp.server.lowlevel.func_inspectionr mcp.server.lowlevel.helper_typesrmcp.server.modelsrmcp.server.sessionrmcp.shared.contextrmcp.shared.exceptionsrrmcp.shared.messagerrmcp.shared.sessionrmcp.shared.tool_name_validationr getLoggerr4rJr!r#rrWr$__annotations__ ContentBlockr%rr& ContextVarr'r)r:r<rEr7r2r0rs-AF3  HHWW00 R1@ACA3,-GD/G   8 $+S9 :s + $CH~9-!)%*<*