o
    *iA                      @   s:  d dl 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Zd dlZd dl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mZ d dlmZ e eZde de fddZ!de de dB fddZ"edddeddfde de#e ef dB de$de$dedej%dB dee gdf dB fddZ&dS )    N)Callable)asynccontextmanager)Any)parse_qsurljoinurlparse)
TaskStatus)MemoryObjectReceiveStreamMemoryObjectSendStream)aconnect_sse)SSEError)McpHttpClientFactorycreate_mcp_http_client)SessionMessageurlreturnc                 C   s   t | t| jS )N)r   r   path)r    r   K/home/ubuntu/veenaModal/venv/lib/python3.10/site-packages/mcp/client/sse.pyremove_request_params   s   r   endpoint_urlc                 C   s2   t t| j}|dd gd p|dd gd S )N	sessionIdr   
session_id)r   r   queryget)r   query_paramsr   r   r   !_extract_session_id_from_endpoint   s   $r      i,  headerstimeoutsse_read_timeouthttpx_client_factoryauthon_session_createdc                   s  t d\}t d\t  4 I dH }ztdt  |||tj||dd4 I dH z t d4 I dH Zj	
  td t jfdtt ffd	d
}	dtf fdd}
||	I dH }td|  ||
| z|fV  W |j  n|j  w W d  I dH  n1 I dH sw   Y  W d  I dH  n1 I dH sw   Y  W  I dH   I dH  n I dH   I dH  w W d  I dH  dS 1 I dH sw   Y  dS )a9  
    Client transport for SSE.

    `sse_read_timeout` determines how long (in seconds) the client will wait for a new
    event before disconnecting. All other HTTP operations are controlled by `timeout`.

    Args:
        url: The SSE endpoint URL.
        headers: Optional headers to include in requests.
        timeout: HTTP timeout for regular operations.
        sse_read_timeout: Timeout for SSE read operations.
        auth: Optional HTTPX authentication handler.
        on_session_created: Optional callback invoked with the session ID when received.
    r   NzConnecting to SSE endpoint: )read)r   r"   r   GETzSSE connection establishedtask_statusc                    s  zz   2 z3 d H W }td|j  |j dkr_ t|j}td|  t}t|}|j|jks?|j|jkrMd| }t	| t
|rYt|}|rY| | | qdkr|jsfqztj|j}td|  W n ty } ztd |I d H  W Y d }~qd }~ww t|}	|	I d H  q	 td|j  q6 W n1 ty }
 ztd	 |
d }
~
w ty } ztd
 |I d H  W Y d }~nd }~ww W  I d H  d S W  I d H  d S  I d H  w )NzReceived SSE event: endpointzReceived endpoint URL: z2Endpoint origin does not match connection origin: messagezReceived server message: zError parsing server messagezUnknown SSE event: zEncountered SSE exceptionzError in sse_reader)	aiter_sseloggerdebugeventr   datar   netlocschemeerror
ValueErrorr   startedtypesJSONRPCMessagemodel_validate_json	Exception	exceptionsendr   warningr   aclose)r&   sser   
url_parsedendpoint_parsed	error_msgr   r(   excsession_messagesse_exc)event_sourcer#   read_stream_writerr   r   r   
sse_readerM   sj   


,

3"zsse_client.<locals>.sse_readerr   c              	      s   zqzN4 I d H ; 2 z,3 d H W }t d|   j| |jjdddddI d H }|  t d|j  q6 W d   I d H  n1 I d H sJw   Y  W n ty^   t d Y nw W 	 I d H  d S W 	 I d H  d S 	 I d H  w )NzSending client message: Tjson)by_aliasmodeexclude_none)rE   z"Client message sent successfully: zError in post_writer)
r*   r+   postr(   
model_dumpraise_for_statusstatus_coder6   r7   r:   )r   r@   response)clientwrite_streamwrite_stream_readerr   r   post_writer   s2   ("zsse_client.<locals>.post_writerz(Starting post writer with endpoint URL: )anyiocreate_memory_object_streamcreate_task_groupr*   r+   r   httpxTimeoutr   rM   rK   TASK_STATUS_IGNOREDr   strstart
start_sooncancel_scopecancelr:   )r   r   r   r    r!   r"   r#   read_streamtgrD   rQ   r   r   )rN   rB   r#   rC   r   rO   rP   r   
sse_client   sJ   

9*(a.r_   )'loggingcollections.abcr   
contextlibr   typingr   urllib.parser   r   r   rR   rU   	anyio.abcr   anyio.streams.memoryr	   r
   	httpx_sser   httpx_sse._exceptionsr   	mcp.typesr3   mcp.shared._httpx_utilsr   r   mcp.shared.messager   	getLogger__name__r*   rX   r   r   dictfloatAuthr_   r   r   r   r   <module>   sN    
