xjOdZddlZddlmZmZmZddlZddlmZ ddl m Z ddl m Z mZddlmZddlmZmZdd lmZmZmZdd lmZmZmZdd lmZdd lmZd gZ ejBe"Z#e#Z$edeZ%Gdd Z&y)aX`ServerSession`: server-to-client requests and notifications. A per-request proxy built by the kernel for each inbound request. Exposes the request-scoped outbound channel and the connection's standalone channel. Handlers reach it as `ctx.session` and use the typed helpers (`elicit_form`, `send_log_message`, ...) to call back to the client. N)AnyTypeVaroverload)methods)MODERN_PROTOCOL_VERSIONS)AnyUrl BaseModel) deprecated) Connectionallowed_log_levels)validate_sampling_tools!validate_tool_use_result_messageswants_sampling_tools) CallOptionsDispatchContext ProgressFnT)MCPDeprecationWarning)ServerMessageMetadata ServerSessionResultT)boundc` eZdZdZdddeededejdzddfdZ e dejdzfd Z e dejdzfd Ze defd Ze defd Z dFd ej&deededzdedzdedzdef dZ dGdej4dej6dzddfdZdej4deddfdZdejdefdZede  dHdejBdededzdej6dzddf dZ"d ee#zddfd!Z$e%ed"e dddddddddd# d$e&ejNd%e(d&edzd'ejRdzd(edzd)e&edzde*eefdzd*ejVdzd+dd,ddej6dzdejXfd-Z-e%ed"e ddddddddd.d$e&ejNd%e(d&edzd'ejRdzd(edzd)e&edzde*eefdzd*ejVdzd+e&ej\d,ej^dzdej6dzdej`fd/Z-e%ed"e ddddddddd0d$e&ejNd%e(d&edzd'ejRdzd(edzd)e&edzde*eefdzd*ejVdzd+e&ej\dzd,ej^dej6dzdej`fd1Z-ed"e dddddddddd# d$e&ejNd%e(d&edzd'ejRdzd(edzd)e&edzde*eefdzd*ejVdzd+e&ej\dzd,ej^dzdej6dzdejXej`zfd2Z-ed3e dejbfd4Z2 dGd5ed6ejfdej6dzdejhfd7Z5 dGd5ed6ejfdej6dzdejhfd8Z6 dGd5ed9ed:edej6dzdejhf d;Z7dejpfd<Z9dHd=ed>edzd5edzddfd?Z: dFd@ee(zd=ed>edzd5edzdedzddf dAZ;dIdBZ dGd:edej6dzddfdEZ?y)Jru0Per-request proxy for server-to-client requests and notifications. Built once per inbound request by the kernel's `_make_context`. Holds two `Outbound` channels: the request-scoped one (the per-request `DispatchContext`, which on streamable HTTP routes onto the originating POST's response stream) and the connection's standalone channel (`connection.outbound`). `related_request_id` on the public methods is the selector — present means request-scoped, absent means standalone — and never crosses the `Outbound` Protocol. N) request_metarequest_outbound connectionrreturnc||_||_|jtv|_t |j||_yN)_request_outbound _connectionprotocol_versionr_log_is_request_scopedr _allowed_log_levels)selfrrrs f/mnt/ssd/data/Dropbox/adrian/sandbox/mcp-query/venv/lib/python3.12/site-packages/mcp/server/session.py__init__zServerSession.__init__/s@"2% '1&A&AE]&]##5j6Q6QS_#` c.|jjS)zRThe client's `initialize` request params; `None` when no client info was supplied.)r client_paramsr$s r%r)zServerSession.client_params@s---r'c.|jjS)a*The capabilities the client declared; `None` when none were declared. Prefer this over `client_params.capabilities`: on 2026-07-28+ the request envelope declares capabilities while client info stays optional, so capabilities can be present without `client_params`. )r client_capabilitiesr*s r%r,z!ServerSession.client_capabilitiesEs333r'c.|jjS)zPWhether this request's channel can currently deliver a server-initiated request.)rcan_send_requestr*s r%r.zServerSession.can_send_requestOs%%666r'c.|jjS)zThe protocol version this connection speaks. Populated at `Connection` construction and overwritten once the handshake commits on the loop path; never `None`. )r r!r*s r%r!zServerSession.protocol_versionTs000r'request result_typerequest_read_timeout_secondsmetadataprogress_callbackcK| |jnd}| |jn|jj}|j ddd}i} ||| d<||| d<|j |d|j d| xsdd{} tj|j|j| |j| d S7C#t$rY wxYww) axSend a typed server-to-client request and validate the result. Raises: MCPError: The peer responded with an error. NoBackChannelError: The connection has no back-channel for server-initiated requests (raised by the held `Outbound`). pydantic.ValidationError: The peer's result does not match `result_type`. NTjsonby_aliasmode exclude_nonetimeout on_progressmethodparamsF)by_name) related_request_idrr outbound model_dumpsend_raw_requestget_methodsvalidate_client_resultr=r!KeyErrormodel_validate) r$r0r1r2r3r4relatedchanneldataoptsresults r% send_requestzServerSession.send_request]s 2:1E(--4,3,?$((TEUEUE^E^!!4f4!P ' 3:DO  ("3D //X@RTXT`\`aa   + +GNND)rr rArBnotifyrD)r$rOrRrJrKs r%rSzServerSession._notifysZ,:$((@P@P@Y@Y&&6PT&UnnT(^TXXh-?@@@sA A*"A(#A* capabilityc8|jj|S)z3Check if the client supports a specific capability.)r check_capability)r$rWs r%check_client_capabilityz%ServerSession.check_client_capabilitys00<rQ)r#_loggerdebugrStypesLoggingMessageNotification LoggingMessageNotificationParamsr")r$r\rKr]r@s r%send_log_messagezServerSession.send_log_messages$ 00 0 MMkmr s ll  , ,==!  66X:LTX:X  sA6B8A>9Buric K|jtjtjt |d{y7w)z%Send a resource updated notification.)rfr_N)rTrbResourceUpdatedNotification!ResourceUpdatedNotificationParamsstr)r$rfs r%send_resource_updatedz#ServerSession.send_resource_updateds>$$  - ->>3s8L    sAAA AzBThe sampling capability is deprecated as of 2026-07-28 (SEP-2577).) system_promptinclude_context temperaturestop_sequencesr3model_preferencestools tool_choicer@messages max_tokensrlrmrnrorprqrrc  Kyw)z?Overload: Without tools or tool_choice, returns single content.N r$rsrtrlrmrnror3rprqrrr@s r%create_messagezServerSession.create_message $ )rlrmrnror3rprrr@c  Kyw)z4Overload: With tools, returns array-capable content.Nrvrws r%rxzServerSession.create_messageryrz)rlrmrnror3rprqr@c  Kyw)z:Overload: With tool_choice, returns array-capable content.Nrvrws r%rxzServerSession.create_messageryrzc Kt|j| | t|tjtj ||||||||| |  } t | } t| | r*|j| tj| d{S|j| tj| d{S7.7w)afSend 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. NoBackChannelError: The connection has no back-channel for server-initiated requests. ) rsrlrmrnrtror3rprqrrr_r@)r0r1r3N) r r,rrbCreateMessageRequestCreateMessageRequestParamsrrrNCreateMessageResultWithToolsCreateMessageResult)r$rsrtrlrmrnror3rprqrrr@r0 metadata_objs r%rxzServerSession.create_messagesX  8 8%M)(3,,33!+ /'%-!"3'   -@RS { 3**!>>%+  &&11!'     s$BCC)C?CCCz?The roots capability is deprecated as of 2026-07-28 (SEP-2577).cK|jtjtjd{S7w)zSend a roots/list request. Raises: NoBackChannelError: The connection has no back-channel for server-initiated requests. N)rNrbListRootsRequestListRootsResultr*s r% list_rootszServerSession.list_roots<s:&&  " " $  ! !    6?=?messagerequested_schemacDK|j|||d{S7w)aSend a form mode elicitation/create request. Args: message: The message to present to the user. requested_schema: 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_formr$rrr@s r%elicitzServerSession.elicitIs%(%%g/?ASTTTTs   cK|jtjtj||tjt |d{S7w)aSend a form mode elicitation/create request. Args: message: The message to present to the user. requested_schema: 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. Raises: NoBackChannelError: The connection has no back-channel for server-initiated requests. )rrr_r~r3N)rNrb ElicitRequestElicitRequestFormParams ElicitResultrrs r%rzServerSession.elicit_form_s`(&&   44#%5    *>PQ'    sAA"A A"urlelicitation_idc K|jtjtj|||tjt |d{S7w)aSend 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. Raises: NoBackChannelError: The connection has no back-channel for server-initiated requests. )rrrr_r~rN)rNrbrElicitRequestURLParamsrr)r$rrrr@s r% elicit_urlzServerSession.elicit_url~sc2&&   33##1    *>PQ'    sAA#A!A#cK|jtjtjd{S7w)zSend a ping request.N)rNrb PingRequest EmptyResultr*s r% send_pingzServerSession.send_pings8&&           rprogresstotalcZK|jj|||d{y7w)afReport progress for the inbound request this session is scoped to. A no-op when the caller did not request progress. Dispatcher-agnostic: on JSON-RPC the held `DispatchContext` emits ``notifications/progress`` against the caller's token; on the in-process direct dispatcher it invokes the caller's callback directly. N)rr)r$rrrs r%report_progresszServerSession.report_progresss&$$--hwGGGs !+)+progress_tokenc K|jtjtj|||||d{y7w)zSend a progress notification.)rrrrr_N)rTrbProgressNotificationProgressNotificationParams)r$rrrrr@s r%send_progress_notificationz(ServerSession.send_progress_notificationsM$$  & &77#1%#     sAA A A cfK|jtjd{y7w)z*Send a resource list changed notification.N)rTrbResourceListChangedNotificationr*s r%send_resource_list_changedz(ServerSession.send_resource_list_changeds#$$U%J%J%LMMM '1/1cfK|jtjd{y7w)z&Send a tool list changed notification.N)rTrbToolListChangedNotificationr*s r%send_tool_list_changedz$ServerSession.send_tool_list_changeds#$$U%F%F%HIIIrcfK|jtjd{y7w)z(Send a prompt list changed notification.N)rTrbPromptListChangedNotificationr*s r%send_prompt_list_changedz&ServerSession.send_prompt_list_changeds#$$U%H%H%JKKKrcK|jtjtj||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 notification )rr_N)rTrbElicitCompleteNotification ElicitCompleteNotificationParams)r$rr@s r%send_elicit_completez"ServerSession.send_elicit_completesA$$  , ,==^\      s>AAA)NNNr)NN)rN)@__name__ __module__ __qualname____doc__rrr rbRequestParamsMetar&propertyInitializeRequestParamsr)ClientCapabilitiesr,boolr.rjr! ServerRequesttyperfloatrrrNServerNotification RequestIdrTrSrZr r LoggingLevelrerrkrlistSamplingMessageintIncludeContextdictModelPreferencesrrxTool ToolChoicerrrElicitRequestedSchemarrrrrrrrrrrrrvr'r%rr#s}  8< a)#.aa --4 a  a".u< sV|  T_tu %)7;$(+/*.;? 59 u,,-   Tz  --4  T\ S D( sCx.4' !11D8   "OOd2   " " v $T_tu %)7;$(+/*.;?/359 u,,-   Tz  --4  T\ S D( sCx.4' !11D8 EJJ %%, "OOd2   + + v $T_tu %)7;$(+/*.;?)-59 u,,-   Tz  --4  T\ S D( sCx.4' !11D8 EJJ$& %% "OOd2   + + v $T_tu %)7;$(+/*.;?)-/359H u,,-H  H Tz H --4 H T\H S D(H sCx.4'H !11D8H EJJ$&H %%,H "OOd2H   " "U%G%G GH vH TQ\qr  %"7"7  s  6: UU 55U"OOd2 U    U46:    55 "OOd2      H6: # # #  # "OOd2 #    # J !2!2 HeHEDLHZ]`dZdHptH#")-  c   t|  t   $J    *NJL6:  "OOd2    r')'rloggingtypingrrr mcp_typesrbrrEmcp_types.versionrpydanticrr typing_extensionsr mcp.server.connectionr r mcp.server.validationr rrmcp.shared.dispatcherrrrmcp.shared.exceptionsrmcp.shared.messager__all__ getLoggerrr]r`rrrvr'r%rsr)))6&(@rrKK74     8 $  )9 -F F r'