Xjm dZddlmZddlmZmZmZddlZddlZddl m Z m Z ddl m Z ddlmZddlmZddlmZdd lmZdd lmZmZdd lmZdd lmZdd lmZmZddl m!Z!m"Z"ddl#m$Z$GddeZ%eddZ&e"ejNejPfejRze*zZ+Gdde!ejXejZejPejNejRfZ.y)a ServerSession Module This module provides the ServerSession class, which manages communication between the server and client in the MCP (Model Context Protocol) framework. It is most commonly used in MCP servers to interact with the client. Common usage pattern: ``` server = Server(name) @server.call_tool() async def handle_tool_call(ctx: RequestContext, arguments: dict[str, Any]) -> Any: # Check client capabilities before proceeding if ctx.session.check_client_capability( types.ClientCapabilities(experimental={"advanced_tools": dict()}) ): # Perform advanced tool operations result = await perform_advanced_tool_operation(arguments) else: # Fall back to basic tool operations result = await perform_basic_tool_operation(arguments) return result @server.list_prompts() async def handle_list_prompts(ctx: RequestContext) -> list[types.Prompt]: # Access session for any necessary checks or operations if ctx.session.client_params: # Customize prompts based on client initialization parameters return generate_custom_prompts(ctx.session.client_params) else: return default_prompts ``` The ServerSession class is typically used internally by the Server class and should not be instantiated directly by users of the MCP framework. )Enum)AnyTypeVaroverloadN)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrl) deprecated)!ExperimentalServerSessionFeatures)InitializationOptions)validate_sampling_tools!validate_tool_use_result_messages)check_tasks_capability)RELATED_TASK_METADATA_KEY)ServerMessageMetadataSessionMessage) BaseSessionRequestResponder)SUPPORTED_PROTOCOL_VERSIONSceZdZdZdZdZy)InitializationStateN)__name__ __module__ __qualname__NotInitialized Initializing Initializedf/mnt/ssd/data/Dropbox/adrian/vault-secondbrain/venv/lib/python3.12/site-packages/mcp/server/session.pyrr?sNLKr"rServerSessionT ServerSession)boundc eZdZUejZeed<dZejdzed<dZ e dzed< dGde e ezdee deded df fd Zed ejdzfd Zed e fd Zeed d e fdZdej0d efdZdHfd Zdeej8ej:ffdZdej>d dfdZ dIdejBde"de#dzdejHdzd df dZ%de&d dfdZ'e(dddddddddd de)ejTde+d e#dzd!ejXdzd"e-dzd#e)e#dzd$e.e#e"fdzd%ej^dzd&dd'ej`dzdejHdzd ejbfd(Z2e(ddddddddd)de)ejTde+d e#dzd!ejXdzd"e-dzd#e)e#dzd$e.e#e"fdzd%ej^dzd&e)ejfd'ej`dzdejHdzd ejhfd*Z2dddddddddd de)ejTde+d e#dzd!ejXdzd"e-dzd#e)e#dzd$e.e#e"fdzd%ej^dzd&e)ejfdzd'ej`dzdejHdzd ejbejhzfd+Z2d ejjfd,Z6 dJd-e#d.ejndejHdzd ejpfd/Z9 dJd-e#d.ejndejHdzd ejpfd0Z: dJd-e#d1e#d2e#dejHdzd ejpf d3Z;d ejxfd4Z= dKd5e#e+zd6e-d7e-dzd-e#dzde#dzd df d8Z>dHd9Z?dHd:Z@dHd;ZA dJd2e#dejHdzd dfd<ZB dId-e#d.ejnd=e#dzd>ejdzd ejf d?ZE dJd-e#d1e#d2e#d=e#dzd ejf d@ZFdddddddddddA de)ejTde+d e#dzd!ejXdzd"e-dzd#e)e#dzd$e.e#e"fdzd%ej^dzd&e)ejfdzd'ej`dzd=e#dzd>ejdzd ejfdBZGd-e d dfdCZHdDeId dfdEZJed e eIfdFZKxZLS)Lr% _initializedN_client_params_experimental_features read_stream write_stream init_options statelessreturncNt||tjtj|rt j nt j_|_ tjtd\_ _jj!fdy)Nrc8jjSN)_incoming_message_stream_readeracloseselfsr#z(ServerSession.__init__..isT5Y5Y5`5`5br")super__init__types ClientRequestClientNotificationrr r_initialization_state _init_optionsanyiocreate_memory_object_streamServerRequestResponder_incoming_message_stream_writerr3 _exit_stackpush_async_callback)r6r+r,r-r. __class__s` r#r9zServerSession.__init__Ys lE4G4GIaIab/8  + +>Q>`>` "*UZUvUv "V V R,d.R ,,-bcr"c|jSr2)r)r5s r# client_paramszServerSession.client_paramsks"""r"cR|jt||_|jS)zOInternal accessor for experimental features that skips the deprecation warning.)r*r r5s r# _experimentalzServerSession._experimentalos)  & & .*KD*QD '***r"zThe 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|jS)u Experimental APIs for server→client task operations. 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. )rIr5s r# experimentalzServerSession.experimentalvs!!!r" capabilityc|jy|jj}|j:|jy|jjr|jjsy|jg|jy|jj |jj y|jj |jj y|j |jy|jQ|jy|jjD]'\}}||jvs|j||k7s'y|j.|jyt|j|jsyy)z3Check if the client supports a specific capability.FT) r) capabilitiesroots listChangedsamplingcontexttools elicitationrKitemstasksr)r6rL client_capsexp_key exp_values r#check_client_capabilityz%ServerSession.check_client_capabilitysz    &))66    '  (++K4E4E4Q4Q    *##+""**6;;O;O;W;W;_""((49M9M9S9S9[  ! ! -+2I2I2Q  " " .''/&0&=&=&C&C&E !"+":"::k>V>VW^>_cl>l  !    '  ()**:*:KrNImplementation server_nameserver_version website_urlrdrgr PingRequest RuntimeError)r6r]r`requested_versions r#_received_requestzServerSession._received_requestss$$7((77$*$:$:!-@-M-M*&,##++**!22#48S#S1B%*%B%B-1-?-?-L-L+0+?+?)-););)G)G,0,>,>,M,M/3/A/A/M/M*.*<*<*B*B ," .2-?-?-L-L $.A-L-L*-8.""$%--1D1P1PP&'\]]Q-s2AF4C&F(F&F(A F4&F((F1-F4 notificationcKtjjd{|jtj dx\t j|_y |jt jk7r tdy7ew)Nr!z8Received notification before initialization was complete) r?lowlevel checkpointrir:InitializedNotificationrr r=rt)r6rws r#_received_notificationz$ServerSession._received_notificationssnn'')))..0-@-L-L*1--1D1P1PP&'abbQ *s"B B A&B leveldataloggerrelated_request_idc K|jtjtjtj||||d{y7w)z Send a log message notification.)r}r~rr_N)send_notificationr:ServerNotificationLoggingMessageNotification LoggingMessageNotificationParams)r6r}r~rrs r#send_log_messagezServerSession.send_log_messagesX$$  $ $00 AA#!%    sAAAAuric K|jtjtjtj|d{y7w)z%Send a resource updated notification.)rr_N)rr:rResourceUpdatedNotification!ResourceUpdatedNotificationParams)r6rs r#send_resource_updatedz#ServerSession.send_resource_updatedsH$$  $ $11 BBsK    sAAAA) system_promptinclude_context temperaturestop_sequencesmetadatamodel_preferencesrS tool_choicermessages max_tokensrrrrrrrSrc  Kyw)z0Overload: Without tools, returns single content.Nr! r6rrrrrrrrrSrrs r#create_messagezServerSession.create_message " )rrrrrrrrc  Kyw)z4Overload: With tools, returns array-capable content.Nr!rs r#rzServerSession.create_message rrc K|jr|jjnd} t| | | t|t j t j t j||||||||| |  } t| }| *|j| tj|d{S|j| tj|d{S7.7w)aSend a sampling/create_message request. Args: messages: The conversation messages to send. max_tokens: Maximum number of tokens to generate. system_prompt: Optional system prompt. include_context: Optional context inclusion setting. Should only be set to "thisServer" or "allServers" if the client has sampling.context capability. temperature: Optional sampling temperature. stop_sequences: Optional stop sequences. metadata: Optional metadata to pass through to the LLM provider. model_preferences: Optional model selection preferences. tools: Optional list of tools the LLM can use during sampling. Requires client to have sampling.tools capability. tool_choice: Optional control over tool usage behavior. Requires client to have sampling.tools capability. related_request_id: Optional ID of a related request. Returns: The sampling result from the client. Raises: McpError: If tools are provided but client doesn't support them. ValueError: If tool_use or tool_result message structure is invalid. N) r systemPromptincludeContextr maxTokens stopSequencesrmodelPreferencesrS toolChoicer_r)rh result_typer) r)rNr rr: ServerRequestCreateMessageRequestCreateMessageRequestParamsr send_requestCreateMessageResultWithToolsCreateMessageResult)r6rrrrrrrrrSrrrWrh metadata_objs r#rzServerSession.create_messagesR;?:M:Md))66SW  UK@)(3%%  & &77%!.#2 +("0%%6*    -@RS   **!>>%+  &&11!'     s$B6C+8C'9)C+"C)#C+)C+cK|jtjtjtjd{S7w)zSend a roots/list request.N)rr:rListRootsRequestListRootsResultr5s r# list_rootszServerSession.list_rootsjsC&&    6 6 8 9  ! !    A A A AmessagerequestedSchemacDK|j|||d{S7w)aSend a form mode elicitation/create request. Args: message: The message to present to the user requestedSchema: Schema defining the expected response structure related_request_id: Optional ID of the request that triggered this elicitation Returns: The client's response Note: This method is deprecated in favor of elicit_form(). It remains for backward compatibility but new code should use elicit_form(). N) elicit_formr6rrrs r#elicitzServerSession.elicitqs$(%%g@RSSSSs   c K|jtjtjtj||tj t |d{S7w)agSend a form mode elicitation/create request. Args: message: The message to present to the user requestedSchema: Schema defining the expected response structure related_request_id: Optional ID of the request that triggered this elicitation Returns: The client's response with form data )rrr_rrN)rr:r ElicitRequestElicitRequestFormParams ElicitResultrrs r#rzServerSession.elicit_formsn &&   ## 88 '(7    *>PQ'    sA,A5.A3/A5urlelicitation_idc K|jtjtjtj|||tj t |d{S7w)akSend a URL mode elicitation/create request. This directs the user to an external URL for out-of-band interactions like OAuth flows, credential collection, or payment processing. 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 related_request_id: Optional ID of the request that triggered this elicitation Returns: The client's response indicating acceptance, decline, or cancellation rr elicitationIdr_rrN)rr:rrElicitRequestURLParamsrr)r6rrrrs r# elicit_urlzServerSession.elicit_urlsq*&&   ## 77 '&4    *>PQ'    sA-A6/A40A6cK|jtjtjtjd{S7w)zSend a ping request.N)rr:rrs EmptyResultr5s r# send_pingzServerSession.send_pingsC&&    1 1 3 4       rprogress_tokenprogresstotalc K|jtjtjtj|||||d{y7w)zSend a progress notification.) progressTokenrrrr_N)rr:rProgressNotificationProgressNotificationParams)r6rrrrrs r#send_progress_notificationz(ServerSession.send_progress_notifications[$$  $ $** ;;&4!)# '     sAAAAcK|jtjtjd{y7w)z*Send a resource list changed notification.N)rr:rResourceListChangedNotificationr5s r#send_resource_list_changedz(ServerSession.send_resource_list_changeds.$$U%=%=e>c>c>e%fggg:AAAcK|jtjtjd{y7w)z&Send a tool list changed notification.N)rr:rToolListChangedNotificationr5s r#send_tool_list_changedz$ServerSession.send_tool_list_changeds.$$U%=%=e>_>_>a%bcccrcK|jtjtjd{y7w)z(Send a prompt list changed notification.N)rr:rPromptListChangedNotificationr5s r#send_prompt_list_changedz&ServerSession.send_prompt_list_changeds.$$U%=%=e>a>a>c%deeerc K|jtjtjtj||d{y7w)aSend an elicitation completion notification. This should be sent when a URL mode elicitation has been completed out-of-band to inform the client that it may retry any requests that were waiting for this elicitation. Args: elicitation_id: The unique identifier of the completed elicitation related_request_id: Optional ID of the request that triggered this )rr_N)rr:rElicitCompleteNotification ElicitCompleteNotificationParams)r6rrs r#send_elicit_completez"ServerSession.send_elicit_completesP$$  $ $00 AAP^_      sAAAArelated_task_idtaskcntj|||}|jddd}|9d|vri|d<tj|jd|dt<|rd|d t |n |j }||xj d z c_tjd |d | S)aBuild a form mode elicitation request without sending it. Args: message: The message to present to the user requestedSchema: Schema defining the expected response structure related_task_id: If provided, adds io.modelcontextprotocol/related-task metadata task: If provided, makes this a task-augmented request Returns: A JSONRPCRequest ready to be sent or queued )rrrTjsonby_aliasmode exclude_none_metataskIdrtask--r2.0elicitation/createjsonrpcidmethodr`)r:r model_dumpRelatedTaskMetadatarr _request_idJSONRPCRequest)r6rrrrr` params_data request_ids r#_build_elicit_form_requestz(ServerSession._build_elicit_form_request s$..+  ''FQU'V   &k)') G$>C>W>W&?j$j'  !: ;@Ou_-Qr&zl;TXTdTd  "    ! ##'   r"cntj|||}|jddd}|9d|vri|d<tj|jd|dt<|rd|d t |n |j }||xj d z c_tjd |d | S)aBuild a URL mode elicitation request without sending it. 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 related_task_id: If provided, adds io.modelcontextprotocol/related-task metadata Returns: A JSONRPCRequest ready to be sent or queued rTrrrrrrrrrrr)r:rrrrrrr)r6rrrrr`rrs r#_build_elicit_url_requestz'ServerSession._build_elicit_url_request6s$--(  ''FQU'V   &k)') G$>C>W>W&?j$j'  !: ;@Ou_-Qr&zl;TXTdTd  "    ! ##'   r") rrrrrrrSrrrc ~tj||||||||| | |  } | jddd}| 9d|vri|d<tj| jd|dt<| rd| d t | n |j }| |xj d z c_tjd |d | S)aBuild a sampling/createMessage request without sending it. Args: messages: The conversation messages to send max_tokens: Maximum number of tokens to generate system_prompt: Optional system prompt include_context: Optional context inclusion setting temperature: Optional sampling temperature stop_sequences: Optional stop sequences metadata: Optional metadata to pass through to the LLM provider model_preferences: Optional model selection preferences tools: Optional list of tools the LLM can use during sampling tool_choice: Optional control over tool usage behavior related_task_id: If provided, adds io.modelcontextprotocol/related-task metadata task: If provided, makes this a task-augmented request Returns: A JSONRPCRequest ready to be sent or queued ) rrrrrrrrrSrrTrrrrrrrrrzsampling/createMessager)r:rrrrrrr)r6rrrrrrrrrSrrrr`rrs r#_build_create_message_requestz+ServerSession._build_create_message_requestcsF11&*# (."  ''FQU'V   &k)') G$>C>W>W&?j$j'  !: ;@Ou_-Qr&zl;TXTdTd  "    ! ##+   r"cVK|jj|d{y7w)aSend a raw session message. This is primarily used by TaskResultHandler to deliver queued messages (elicitation/sampling requests) to the client during task execution. WARNING: This is a low-level experimental method that may change without notice. Prefer using higher-level methods like send_notification() or send_request() for normal operations. Args: message: The session message to send N) _write_streamsend)r6rs r# send_messagezServerSession.send_messages"  %%g... )')reqcVK|jj|d{y7wr2)rBr)r6rs r#_handle_incomingzServerSession._handle_incomings 2277<<r)s%N)) R(V3\MKD;$ )AU((%*<*<<=@X@XX[dd q 4          "q 4r"