o
    i[                  	   @   s&  U d dl Z d dlmZ d dlmZmZmZ d dlZd dl	m
Z
mZ d dlmZmZ d dlmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ d dlmZmZmZ d dlm Z  ej!dddZ"e #dZ$G dd deZ%G dd deZ&G dd deZ'G dd deZ(G dd deZ)deej*ej+f ej,B e-B ddfddZ.ded ef d!ej/dej0ej1B ej2B fd"d#Z3ded ef d!ej4dej5ej2B fd$d%Z6ded ef dej7ej2B fd&d'Z8d!ej9ddfd(d)Z:eej+ej2B Z;eej+ej2B  e<d*< G d+d  d eej=ej>ej+ej*ej,f Z?dS ),    N)	timedelta)AnyProtocoloverload)MemoryObjectReceiveStreamMemoryObjectSendStream)AnyUrlTypeAdapter)
deprecated)ExperimentalClientFeatures)ExperimentalTaskHandlers)RequestContext)SessionMessage)BaseSessionProgressFnTRequestResponder)SUPPORTED_PROTOCOL_VERSIONSZmcpz0.1.0)nameversionclientc                   @   s:   e Zd Zdedef dejdejejB ej	B fddZ
dS )SamplingFnTcontextClientSessionparamsreturnc                       d S N selfr   r   r   r   I/home/app/Keep/.python/lib/python3.10/site-packages/mcp/client/session.py__call__      zSamplingFnT.__call__N)__name__
__module____qualname__r   r   typesCreateMessageRequestParamsCreateMessageResultCreateMessageResultWithTools	ErrorDatar!   r   r   r   r    r      s    
r   c                   @   s4   e Zd Zdedef dejdejejB fddZ	dS )ElicitationFnTr   r   r   r   c                    r   r   r   r   r   r   r    r!       r"   zElicitationFnT.__call__N)
r#   r$   r%   r   r   r&   ElicitRequestParamsElicitResultr*   r!   r   r   r   r    r+      s    

r+   c                   @   s.   e Zd Zdedef dejejB fddZdS )ListRootsFnTr   r   r   c                    r   r   r   )r   r   r   r   r    r!   (      zListRootsFnT.__call__N)	r#   r$   r%   r   r   r&   ListRootsResultr*   r!   r   r   r   r    r.   '   s    

r.   c                   @   s    e Zd ZdejddfddZdS )
LoggingFnTr   r   Nc                    r   r   r   r   r   r   r   r    r!   .      zLoggingFnT.__call__)r#   r$   r%   r&    LoggingMessageNotificationParamsr!   r   r   r   r    r1   -   s    r1   c                   @   s4   e Zd Zdeejejf ejB eB ddfddZ	dS )MessageHandlerFnTmessager   Nc                    r   r   r   )r   r6   r   r   r    r!   5   r3   zMessageHandlerFnT.__call__)
r#   r$   r%   r   r&   ServerRequestClientResultServerNotification	Exceptionr!   r   r   r   r    r5   4   s    r5   r6   r   c                    s   t j I d H  d S r   )anyioZlowlevel
checkpoint)r6   r   r   r    _default_message_handler;   s   r=   r   r   r   c                       t jt jddS )NzSampling not supportedcoder6   r&   r*   ZINVALID_REQUESTr   r   r   r   r    _default_sampling_callbackA   
   rC   c                    r>   )NzElicitation not supportedr?   rA   rB   r   r   r    _default_elicitation_callbackK   rD   rE   c                    r>   )NzList roots not supportedr?   rA   )r   r   r   r    _default_list_roots_callbackU   s
   rF   c                    r   r   r   r   r   r   r    _default_logging_callback^   r3   rH   ClientResponsec                       s  e Zd Z							d`ddddeeeB  dee dedB dedB de	dB de
dB d	edB d
edB dejdB dejdB dedB ddf fddZdejfddZdejdB fddZedefddZdejfddZ		dadeeB dededB dedB ddf
ddZdejdejfd d!Z e!e"d"d#edB dej#fd$d%Z$e!d&ej%dB dej#fd'd%Z$e!dej#fd(d%Z$	dbdd)d#edB d&ej%dB dej#fd*d%Z$e!e"d+d#edB dej&fd,d-Z'e!d&ej%dB dej&fd.d-Z'e!dej&fd/d-Z'	dbdd)d#edB d&ej%dB dej&fd0d-Z'd1e(dej)fd2d3Z*d1e(dejfd4d5Z+d1e(dejfd6d7Z,			dcdd8d9ed:e-ee.f dB dedB d;e/dB d<e-ee.f dB dej0fd=d>Z1d9ed?ej0ddfd@dAZ2e!e"dBd#edB dej3fdCdDZ4e!d&ej%dB dej3fdEdDZ4e!dej3fdFdDZ4	dbdd)d#edB d&ej%dB dej3fdGdDZ4dbd9ed:e-eef dB dej5fdHdIZ6	dbdJej7ej8B dKe-eef dLe-eef dB dej9fdMdNZ:e!e"dOd#edB dej;fdPdQZ<e!d&ej%dB dej;fdRdQZ<e!dej;fdSdQZ<	dbdd)d#edB d&ej%dB dej;fdTdQZ<dddUdVZ=dWe>ej?ej@f ddfdXdYZAdZe>ej?ej@f ejBB eB ddfd[d\ZCd]ejBddfd^d_ZD  ZES )er   N)sampling_capabilitiesexperimental_task_handlersread_streamwrite_streamread_timeout_secondssampling_callbackelicitation_callbacklist_roots_callbacklogging_callbackmessage_handlerclient_inforJ   rK   r   c
                   s~   t  j||tjtj|d |	pt| _|pt| _|
| _	|pt
| _|p"t| _|p't| _|p,t| _i | _d | _d | _|p;t | _d S )N)rN   )super__init__r&   r7   r9   DEFAULT_CLIENT_INFO_client_inforC   _sampling_callback_sampling_capabilitiesrE   _elicitation_callbackrF   _list_roots_callbackrH   _logging_callbackr=   _message_handler_tool_output_schemas_server_capabilities_experimental_featuresr   _task_handlers)r   rL   rM   rN   rO   rP   rQ   rR   rS   rT   rJ   rK   	__class__r   r    rV   p   s$   





zClientSession.__init__c                    s   | j tur| jpt nd }| jturtjt t	 dnd }| j
tur,tjddnd }| ttjtjtjtj||d || j d| jddtjI d H }|jtvr_td|j |j| _| tt I d H  |S )N)formurlT)ZlistChanged)samplingelicitationexperimentalrootstasks)protocolVersioncapabilitiesZ
clientInforG   z.Unsupported protocol version from the server: )rY   rC   rZ   r&   SamplingCapabilityr[   rE   ZElicitationCapabilityZFormElicitationCapabilityZUrlElicitationCapabilityr\   rF   ZRootsCapabilitysend_requestClientRequestZInitializeRequestZInitializeRequestParamsZLATEST_PROTOCOL_VERSIONZClientCapabilitiesrb   Zbuild_capabilityrX   InitializeResultrl   r   RuntimeErrorrm   r`   send_notificationClientNotificationZInitializedNotification)r   rg   rh   rj   resultr   r   r    
initialize   sP   



	

zClientSession.initializec                 C   s   | j S )zReturn the server capabilities received during initialization.

        Returns None if the session has not been initialized yet.
        )r`   r   r   r   r    get_server_capabilities   s   z%ClientSession.get_server_capabilitiesc                 C   s   | j du r
t| | _ | j S )a2  Experimental APIs for tasks and other features.

        WARNING: These APIs are experimental and may change without notice.

        Example:
            status = await session.experimental.get_task(task_id)
            result = await session.experimental.get_task_result(task_id, CallToolResult)
        N)ra   r   rw   r   r   r    ri      s   


zClientSession.experimentalc                    s    |  tt tjI dH S )zSend a ping request.N)ro   r&   rp   PingRequestEmptyResultrw   r   r   r    	send_ping   s
   
zClientSession.send_pingprogress_tokenprogresstotalr6   c                    s2   |  ttjtj||||ddI dH  dS )zSend a progress notification.)ZprogressTokenr}   r~   r6   rG   N)rs   r&   rt   ZProgressNotificationZProgressNotificationParams)r   r|   r}   r~   r6   r   r   r    send_progress_notification   s   z(ClientSession.send_progress_notificationlevelc                    ,   |  ttjtj|ddtjI dH S )z Send a logging/setLevel request.)r   rG   N)ro   r&   rp   ZSetLevelRequestZSetLevelRequestParamsrz   )r   r   r   r   r    set_logging_level      

zClientSession.set_logging_levelz>Use list_resources(params=PaginatedRequestParams(...)) insteadcursorc                    r   r   r   r   r   r   r   r    list_resources  r/   zClientSession.list_resourcesr   c                   r   r   r   r2   r   r   r    r        c                    r   r   r   rw   r   r   r    r   
  r   rG   c                   d   |dur|durt d|dur|}n|durtj|d}nd}| ttj|dtjI dH S )zSend a resources/list request.

        Args:
            cursor: Simple cursor string for pagination (deprecated, use params instead)
            params: Full pagination parameters including cursor and any future fields
        N%Cannot specify both cursor and paramsr   rG   )
ValueErrorr&   PaginatedRequestParamsro   rp   ZListResourcesRequestListResourcesResultr   r   r   request_paramsr   r   r    r        
zGUse list_resource_templates(params=PaginatedRequestParams(...)) insteadc                    r   r   r   r   r   r   r    list_resource_templates(  r/   z%ClientSession.list_resource_templatesc                   r   r   r   r2   r   r   r    r   ,  r3   c                    r   r   r   rw   r   r   r    r   1  r   c                   r   )zSend a resources/templates/list request.

        Args:
            cursor: Simple cursor string for pagination (deprecated, use params instead)
            params: Full pagination parameters including cursor and any future fields
        Nr   r   rG   )r   r&   r   ro   rp   ZListResourceTemplatesRequestListResourceTemplatesResultr   r   r   r    r   4  r   uric                    r   )zSend a resources/read request.r   rG   N)ro   r&   rp   ZReadResourceRequestZReadResourceRequestParamsReadResourceResultr   r   r   r   r    read_resourceO  r   zClientSession.read_resourcec                    r   )z#Send a resources/subscribe request.r   rG   N)ro   r&   rp   ZSubscribeRequestZSubscribeRequestParamsrz   r   r   r   r    subscribe_resourceZ  r   z ClientSession.subscribe_resourcec                    r   )z%Send a resources/unsubscribe request.r   rG   N)ro   r&   rp   ZUnsubscribeRequestZUnsubscribeRequestParamsrz   r   r   r   r    unsubscribe_resourcee  r   z"ClientSession.unsubscribe_resource)metar   	argumentsprogress_callbackr   c             	      sp   d}|durt jjdi |}| jt t jt j|||ddt j||dI dH }|js6| 	||I dH  |S )zBSend a tools/call request with optional progress callback support.N)r   r   _metarG   )Zrequest_read_timeout_secondsr   r   )
r&   ZRequestParamsZMetaro   rp   ZCallToolRequestZCallToolRequestParamsCallToolResultZisError_validate_tool_result)r   r   r   rN   r   r   r   ru   r   r   r    	call_toolp  s"   zClientSession.call_toolru   c              
      s   || j vr|  I dH  d}|| j v r| j |}n	td| d |durtddlm}m}m} |j	du r?t
d| dz	||j	| W dS  |y^ } z
t
d| d| d}~w |ys } z
t
d	| d| d}~ww dS )
zKValidate the structured content of a tool result against its output schema.NzTool z= not listed by server, cannot validate any structured contentr   )SchemaErrorValidationErrorvalidatez; has an output schema but did not return structured contentz,Invalid structured content returned by tool z: zInvalid schema for tool )r_   
list_toolsgetloggerwarningZ
jsonschemar   r   r   ZstructuredContentrr   )r   r   ru   Zoutput_schemar   r   r   er   r   r    r     s.   



z#ClientSession._validate_tool_resultz<Use list_prompts(params=PaginatedRequestParams(...)) insteadc                    r   r   r   r   r   r   r    list_prompts  r/   zClientSession.list_promptsc                   r   r   r   r2   r   r   r    r     r   c                    r   r   r   rw   r   r   r    r     r   c                   r   )zSend a prompts/list request.

        Args:
            cursor: Simple cursor string for pagination (deprecated, use params instead)
            params: Full pagination parameters including cursor and any future fields
        Nr   r   rG   )r   r&   r   ro   rp   ZListPromptsRequestListPromptsResultr   r   r   r    r     r   c              	      s.   |  ttjtj||ddtjI dH S )zSend a prompts/get request.)r   r   rG   N)ro   r&   rp   ZGetPromptRequestZGetPromptRequestParamsGetPromptResult)r   r   r   r   r   r    
get_prompt  s   
zClientSession.get_promptrefargumentcontext_argumentsc                    sT   d}|durt j|d}| t t jt j|t jdi ||ddt jI dH S )z#Send a completion/complete request.N)r   )r   r   r   rG   r   )r&   ZCompletionContextro   rp   ZCompleteRequestZCompleteRequestParamsZCompletionArgumentCompleteResult)r   r   r   r   r   r   r   r    complete  s    	
zClientSession.completez:Use list_tools(params=PaginatedRequestParams(...)) insteadc                    r   r   r   r   r   r   r    r     r/   zClientSession.list_toolsc                   r   r   r   r2   r   r   r    r     r   c                    r   r   r   rw   r   r   r    r     r   c                   s   |dur|durt d|dur|}n|durtj|d}nd}| ttj|dtjI dH }|jD ]	}|j| j	|j
< q5|S )zSend a tools/list request.

        Args:
            cursor: Simple cursor string for pagination (deprecated, use params instead)
            params: Full pagination parameters including cursor and any future fields
        Nr   r   rG   )r   r&   r   ro   rp   ZListToolsRequestListToolsResultZtoolsZoutputSchemar_   r   )r   r   r   r   ru   Ztoolr   r   r    r     s   

c                    s    |  tt I dH  dS )z'Send a roots/list_changed notification.N)rs   r&   rt   ZRootsListChangedNotificationrw   r   r   r    send_roots_list_changed  s   z%ClientSession.send_roots_list_changed	responderc                    sb  t ttf |j|j| d d}| j|jr5| | j||I d H  W d    d S 1 s.w   Y  d S |jj	 t
jd r d  } |1 |jd urZ| j|||jI d H }n	| ||I d H }t|}||I d H  W d    d S 1 s{w   Y  d S   t
jd r d  } |1 |jd ur| j|||jI d H }n	| ||I d H }t|}||I d H  W d    d S 1 sw   Y  d S   t
jd r  | | |I d H }t|}||I d H  W d    d S 1 sw   Y  d S  t
jd r, | |t
jt
 dI d H W  d    S 1 s%w   Y  d S  	 	 d S )N)
request_idr   sessionZlifespan_contextrG   r   r   )root)r   r   r   r   Zrequest_metarb   Zhandles_requestrequesthandle_requestr   r&   ZCreateMessageRequesttaskZaugmented_samplingrY   rI   Zvalidate_pythonZrespondZElicitRequestZaugmented_elicitationr[   ZListRootsRequestr\   ry   r8   rz   )r   r   ctxr   responseZclient_responser   r   r    _received_request!  st   




  






"zClientSession._received_requestreqc                    s   |  |I dH  dS )z>Handle incoming messages by forwarding to the message handler.N)r^   )r   r   r   r   r    _handle_incomingT  s   zClientSession._handle_incomingnotificationc                    sZ   |j  tjd r d  } | |I dH  dS  tjd r( d  }dS  	 	 dS )z%Handle notifications from the server.rG   r   N)r   r&   ZLoggingMessageNotificationr]   ZElicitCompleteNotification)r   r   r   r   r   r    _received_notification[  s   z$ClientSession._received_notification)NNNNNNN)NNr   )NNN)r   N)Fr#   r$   r%   r   r   r:   r   r   r   r+   r.   r1   r5   r&   Implementationrn   r   rV   rq   rv   ZServerCapabilitiesrx   propertyr   ri   rz   r{   strintfloatr   ZLoggingLevelr   r   r
   r   r   r   r   r   r   r   r   r   r   dictr   r   r   r   r   r   r   r   r   ZResourceTemplateReferenceZPromptReferencer   r   r   r   r   r   r7   r8   r   r9   r   r   __classcell__r   r   rc   r    r   g   sP   
	
$3




&




"3
)@loggingdatetimer   typingr   r   r   Zanyio.lowlevelr;   Zanyio.streams.memoryr   r   Zpydanticr   r	   Ztyping_extensionsr
   Z	mcp.typesr&   Zmcp.client.experimentalr   Z%mcp.client.experimental.task_handlersr   Zmcp.shared.contextr   Zmcp.shared.messager   Zmcp.shared.sessionr   r   r   Zmcp.shared.versionr   r   rW   	getLoggerr   r   r+   r.   r1   r5   r7   r8   r9   r:   r=   r'   r(   r)   r*   rC   r,   r-   rE   r0   rF   r4   rH   rI   __annotations__rp   rt   r   r   r   r   r    <module>   sz   
 











	
$
