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_VERSIONS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   O/home/ubuntu/veenaModal/venv/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!   r2   -   s    r2   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    r7   r   r   r!   r"   5   r4   zMessageHandlerFnT.__call__)
r$   r%   r&   r   r'   ServerRequestClientResultServerNotification	Exceptionr"   r   r   r   r!   r6   4   s    r6   r7   r   c                    s   t j I d H  d S r   )anyiolowlevel
checkpoint)r7   r   r   r!   _default_message_handler;   s   r?   r   r   r   c                       t jt jddS )NzSampling not supportedcoder7   r'   r+   INVALID_REQUESTr   r   r   r   r!   _default_sampling_callbackA   
   rF   c                    r@   )NzElicitation not supportedrA   rC   rE   r   r   r!   _default_elicitation_callbackK   rG   rH   c                    r@   )NzList roots not supportedrA   rC   )r   r   r   r!   _default_list_roots_callbackU   s
   rI   c                    r   r   r   r   r   r   r!   _default_logging_callback^   r4   rK   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_inforM   rN   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)rQ   )super__init__r'   r8   r:   DEFAULT_CLIENT_INFO_client_inforF   _sampling_callback_sampling_capabilitiesrH   _elicitation_callbackrI   _list_roots_callbackrK   _logging_callbackr?   _message_handler_tool_output_schemas_server_capabilities_experimental_featuresr   _task_handlers)r    rO   rP   rQ   rR   rS   rT   rU   rV   rW   rM   rN   	__class__r   r!   rY   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)listChanged)samplingelicitationexperimentalrootstasks)protocolVersioncapabilities
clientInforJ   z.Unsupported protocol version from the server: )r\   rF   r]   r'   SamplingCapabilityr^   rH   ElicitationCapabilityFormElicitationCapabilityUrlElicitationCapabilityr_   rI   RootsCapabilitysend_requestClientRequestInitializeRequestInitializeRequestParamsLATEST_PROTOCOL_VERSIONClientCapabilitiesre   build_capabilityr[   InitializeResultrp   r   RuntimeErrorrq   rc   send_notificationClientNotificationInitializedNotification)r    rk   rl   rn   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.
        )rc   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)rd   r   r   r   r   r!   rm      s   


zClientSession.experimentalc                    s    |  tt tjI dH S )zSend a ping request.N)rx   r'   ry   PingRequestEmptyResultr   r   r   r!   	send_ping   s
   
zClientSession.send_pingprogress_tokenprogresstotalr7   c                    s2   |  ttjtj||||ddI dH  dS )zSend a progress notification.)progressTokenr   r   r7   rJ   N)r   r'   r   ProgressNotificationProgressNotificationParams)r    r   r   r   r7   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   rJ   N)rx   r'   ry   SetLevelRequestSetLevelRequestParamsr   )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  r0   zClientSession.list_resourcesr   c                   r   r   r   r3   r   r   r!   r        c                    r   r   r   r   r   r   r!   r   
  r   rJ   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   rJ   )
ValueErrorr'   PaginatedRequestParamsrx   ry   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(  r0   z%ClientSession.list_resource_templatesc                   r   r   r   r3   r   r   r!   r   ,  r4   c                    r   r   r   r   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   rJ   )r   r'   r   rx   ry   ListResourceTemplatesRequestListResourceTemplatesResultr   r   r   r!   r   4  r   uric                    r   )zSend a resources/read request.r   rJ   N)rx   r'   ry   ReadResourceRequestReadResourceRequestParamsReadResourceResultr    r   r   r   r!   read_resourceO  r   zClientSession.read_resourcec                    r   )z#Send a resources/subscribe request.r   rJ   N)rx   r'   ry   SubscribeRequestSubscribeRequestParamsr   r   r   r   r!   subscribe_resourceZ  r   z ClientSession.subscribe_resourcec                    r   )z%Send a resources/unsubscribe request.r   rJ   N)rx   r'   ry   UnsubscribeRequestUnsubscribeRequestParamsr   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   _metarJ   )request_read_timeout_secondsr   r   )
r'   RequestParamsMetarx   ry   CallToolRequestCallToolRequestParamsCallToolResultisError_validate_tool_result)r    r   r   rQ   r   r   r   r   r   r   r!   	call_toolp  s"   zClientSession.call_toolr   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 )rb   
list_toolsgetloggerwarning
jsonschemar   r   r   structuredContentr   )r    r   r   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  r0   zClientSession.list_promptsc                   r   r   r   r3   r   r   r!   r     r   c                    r   r   r   r   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   rJ   )r   r'   r   rx   ry   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   rJ   N)rx   r'   ry   GetPromptRequest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   rJ   r   )r'   CompletionContextrx   ry   CompleteRequestCompleteRequestParams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     r0   zClientSession.list_toolsc                   r   r   r   r3   r   r   r!   r     r   c                    r   r   r   r   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   rJ   )r   r'   r   rx   ry   ListToolsRequestListToolsResulttoolsoutputSchemarb   r   )r    r   r   r   r   toolr   r   r!   r     s   

c                    s    |  tt I dH  dS )z'Send a roots/list_changed notification.N)r   r'   r   RootsListChangedNotificationr   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   sessionlifespan_contextrJ   r   r   )root)r   r   r   r   request_metare   handles_requestrequesthandle_requestr   r'   CreateMessageRequesttaskaugmented_samplingr\   rL   validate_pythonrespondElicitRequestaugmented_elicitationr^   ListRootsRequestr_   r   r9   r   )r    r   ctxr   response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)ra   )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.rJ   r   N)r   r'   LoggingMessageNotificationr`   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/   r2   r6   r'   Implementationrs   r   rY   r   r   ServerCapabilitiesr   propertyr   rm   r   r   strintfloatr   LoggingLevelr   r   r
   r   r   r   r   r   r   r   r   r   r   dictr   r   r   r   r   r   r   r   r   ResourceTemplateReferencePromptReferencer   r   r   r   r   r   r8   r9   r   r:   r   r   __classcell__r   r   rf   r!   r   g   sP   
	
$3




&




"3
)@loggingdatetimer   typingr   r   r   anyio.lowlevelr<   anyio.streams.memoryr   r   pydanticr   r	   typing_extensionsr
   	mcp.typesr'   mcp.client.experimentalr   %mcp.client.experimental.task_handlersr   mcp.shared.contextr   mcp.shared.messager   mcp.shared.sessionr   r   r   mcp.shared.versionr   r   rZ   	getLoggerr   r   r,   r/   r2   r6   r8   r9   r:   r;   r?   r(   r)   r*   r+   rF   r-   r.   rH   r1   rI   r5   rK   rL   __annotations__ry   r   r   r   r   r   r!   <module>   sz   
 









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