+
    wiJ*                        R t ^ RIt^ RIHt ^ RIHt ^ RIHt ^ RIH	t	H
t
 ^ RIt^ RIHtHt ^ RIHt ^ RIHt ^ R	IHt ^ R
IHt ^ RIHtHtHt ^ RIHt ^ RIHtHt ^ RI H!t!H"t" ]PF                  ! ]$4      t% ! R R4      t&R# )a  
SSE Server Transport Module

This module implements a Server-Sent Events (SSE) transport layer for MCP servers.

Example usage:
```
    # Create an SSE transport at an endpoint
    sse = SseServerTransport("/messages/")

    # Create Starlette routes for SSE and message handling
    routes = [
        Route("/sse", endpoint=handle_sse, methods=["GET"]),
        Mount("/messages/", app=sse.handle_post_message),
    ]

    # Define handler functions
    async def handle_sse(request):
        async with sse.connect_sse(
            request.scope, request.receive, request._send
        ) as streams:
            await app.run(
                streams[0], streams[1], app.create_initialization_options()
            )
        # Return empty response to avoid NoneType error
        return Response()

    # Create and run Starlette app
    starlette_app = Starlette(routes=routes)
    uvicorn.run(starlette_app, host="127.0.0.1", port=port)
```

Note: The handle_sse function must return a Response to avoid a "TypeError: 'NoneType'
object is not callable" error when client disconnects. The example above returns
an empty Response() after the SSE connection ends to fix this.

See SseServerTransport class documentation for more details.
N)asynccontextmanager)Any)quote)UUIDuuid4)MemoryObjectReceiveStreamMemoryObjectSendStream)ValidationError)EventSourceResponse)Request)Response)ReceiveScopeSend)TransportSecurityMiddlewareTransportSecuritySettings)ServerMessageMetadataSessionMessagec                      a a ] tR t^@t oRtR
V3R lV 3R lllt]V3R lR l4       tV3R lR ltV3R lt	R	t
VtV ;t# )SseServerTransporta  
SSE server transport for MCP. This class provides _two_ ASGI applications,
suitable to be used with a framework like Starlette and a server like Hypercorn:

    1. connect_sse() is an ASGI application which receives incoming GET requests,
       and sets up a new SSE stream to send server messages to the client.
    2. handle_post_message() is an ASGI application which receives incoming POST
       requests, which should contain client messages that link to a
       previously-established SSE session.
c                8   < V ^8  d   QhRS[ RS[R,          RR/# )   endpointsecurity_settingsNreturn)strr   )format__classdict__s   "B/home/ubuntu/.local/lib/python3.14/site-packages/mcp/server/sse.py__annotate__SseServerTransport.__annotate__P   s/     'R 'R 'R9RUY9Y 'Rei 'R    c                D  < \         SV `  4        RV9   g&   VP                  R4      '       g   RV9   g   RV9   d   \        RV R24      hVP                  R4      '       g
   RV,           pWn        / V n        \        V4      V n        \        P                  RV 24       R	# )
a?  
Creates a new SSE server transport, which will direct the client to POST
messages to the relative path given.

Args:
    endpoint: A relative path where messages should be posted
            (e.g., "/messages/").
    security_settings: Optional security settings for DNS rebinding protection.

Note:
    We use relative paths instead of full URLs for several reasons:
    1. Security: Prevents cross-origin requests by ensuring clients only connect
       to the same origin they established the SSE connection with
    2. Flexibility: The server can be mounted at any path without needing to
       know its full URL
    3. Portability: The same endpoint configuration works across different
       environments (development, staging, production)

Raises:
    ValueError: If the endpoint is a full URL instead of a relative path
z://z//?#zGiven endpoint: z] is not a relative path (e.g., '/messages/'), expecting a relative path (e.g., '/messages/')./z.SseServerTransport initialized with endpoint: N)
super__init__
startswith
ValueError	_endpoint_read_stream_writersr   	_securityloggerdebug)selfr   r   	__class__s   &&&r   r'   SseServerTransport.__init__P   s    . 	 H 3 3D 9 9SH_PSW_P_"8* -B B  ""3''X~H!$&!45FGEhZPQr!   c                ,   < V ^8  d   QhRS[ RS[RS[/# r   scopereceivesendr   r   r   )r   r   s   "r   r   r    z   s'     M. M.u M.w M.d M.r!   c               ~  aaaaaaa"   VR ,          R8w  d!   \         P                  R4       \        R4      h\        W4      pV P                  P                  VRR7      G Rj  xL
 pV'       d   V! WV4      G Rj  xL
  \        R4      h\         P                  R4       \        P                  ! ^ 4      w  op\        P                  ! ^ 4      w  po\        4       oSV P                  S&   \         P                  R	S 24       VP                  R
R4      pVP                  R4      V P                  ,           p	\        V	4       RSP                   2o\        P                  \         \"        \$        3,          ,          ! ^ 4      w  ooVVV3R lo\        P&                  ! 4       ;_uu_4       GRj  xL
 p
R VVVVV3R llp\         P                  R4       V
P)                  WW#4       \         P                  R4       Wg35x  RRR4      GRj  xL
  R#  EL EL Lk L  + GRj  xL 
 '       g   i     R# ; i5i)typehttpz%connect_sse received non-HTTP requestz)connect_sse can only handle HTTP requestsFis_postNzRequest validation failedzSetting up SSE connectionzCreated new session with ID: 	root_path r%   z?session_id=c                  z  <"   \         P                  R 4       S;_uu_4       GRj  xL
  S;_uu_4       GRj  xL
  SP                  RRRS/4      G Rj  xL
  \         P                  RS 24       S  Rj  xL
  p \         P                  RV  24       SP                  RRRV P                  P	                  RRR	7      /4      G Rj  xL
  K\   L L L~ L] LD`RRR4      GRj  xL 
  M  + GRj  xL 
 '       g   i     M; iRRR4      GRj  xL 
  R#   + GRj  xL 
 '       g   i     R# ; i5i)
zStarting SSE writerNeventr   datazSent endpoint event: zSending message via SSE: messageT)by_aliasexclude_none)r-   r.   r6   rB   model_dump_json)session_messageclient_post_uri_datasse_stream_writerwrite_stream_readers    r   
sse_writer2SseServerTransport.connect_sse.<locals>.sse_writer   s     LL./(((*=*=*=',,gz6K_-`aaa45I4JKL-@  /LL#<_<M!NO+00#Y"O$;$;$K$KUYhl$K$m   )*=a .A	 +>*=*=*=*=*=((((((s   $D;CD;DCDC/	CC/	6C
:C;C
>AC/	CC/	D;DC/	C
C/	C/	D(C+)D/D5C86
DDDD;DD;D8	$D'%
D8	0D8	2	D;c                <    V ^8  d   QhR\         R\        R\        /# r3   r7   )r   s   "r   r   4SseServerTransport.connect_sse.<locals>.__annotate__   s&     K Ke Kg KT Kr!   c                   <"   \        SSR7      ! WV4      G Rj  xL
  SP                  4       G Rj  xL
  SP                  4       G Rj  xL
  \        P                  ! RS 24       R#  LO L9 L#5i)z
The EventSourceResponse returning signals a client close / disconnect.
In this case we close our side of the streams to signal the client that
the connection has been closed.
)contentdata_sender_callableNzClient session disconnected )r
   acloseloggingr.   )r4   r5   r6   read_stream_writer
session_idsse_stream_readerrJ   rI   s   &&&r   response_wrapper8SseServerTransport.connect_sse.<locals>.response_wrapper   so      *2CZdeD   )//111)00222 <ZLIJ 22s1   A1A+A1A-A1A/ A1-A1/A1zStarting SSE response taskzYielding read and write streams)r-   errorr)   r   r,   validate_requestr.   anyiocreate_memory_object_streamr   r+   getrstripr*   r   hexdictr   r   create_task_group
start_soon)r/   r4   r5   r6   requesterror_responseread_streamwrite_streamr=   full_message_path_for_clienttgrV   rG   rS   rT   rU   rH   rJ   rI   s   &&&&        @@@@@@@r   connect_sseSseServerTransport.connect_ssey   s    =F"LL@AHII %)#~~>>wPU>VV 66689901 +0*K*KA*N'K,1,M,Ma,P))W
0B!!*-4ZLAB IIk2.	 (1'7'7'<t~~'M$ #((D"E!FlS]SaSaRbc/4/P/PQUVY[^V^Q_/`ab/c,,	 **,,,K K LL56MM*7ALL:;--' -,,g W6b -,,,sz   AH=#H$H=0H=<H=D3H=0H1H=4AH H=HH=H=H=H= H:	&H)'
H:	2H:	4	H=c                0   < V ^8  d   QhRS[ RS[RS[RR/# )r   r4   r5   r6   r   Nr7   )r   r   s   "r   r   r       s*     0+ 0+u 0+w 0+d 0+W[ 0+r!   c                  "   \         P                  R 4       \        W4      pV P                  P	                  VRR7      G Rj  xL
 pV'       d   V! WV4      G Rj  xL
 # VP
                  P                  R4      pVf4   \         P                  R4       \        RRR7      pV! WV4      G Rj  xL
 #  \        VR	7      p\         P                  R
V 24       T P                  P                  T4      p	T	'       g7   \         P                  RT 24       \        RRR7      pT! YT4      G Rj  xL
 # TP                  4       G Rj  xL
 p
\         P                  RT
 24        \        P                  P                  T
4      p\         P                  RT 24       \'        TR7      p\)        YR7      p\         P                  RT 24       \        R^R7      pT! YT4      G Rj  xL
  T	P%                  T4      G Rj  xL
  R#  EL EL ELZ  \         d;    \         P                  RT 24       \        RRR7      pT! YT4      G Rj  xL 
 u # i ; i EL' EL  \          dZ   p\         P#                  R4       \        RRR7      pT! YT4      G Rj  xL 
  T	P%                  T4      G Rj  xL 
   Rp?R# Rp?ii ; i L L5i)zHandling POST messageTr;   NrT   z#Received request without session_idzsession_id is requiredi  )status_code)r^   zParsed session ID: zReceived invalid session ID: zInvalid session IDzCould not find session for ID: zCould not find sessioni  zReceived JSON: zValidated client message: zFailed to parse messagezCould not parse message)request_context)metadataz#Sending session message to writer: Accepted)r-   r.   r   r,   rY   query_paramsr\   warningr   r   r)   r+   bodytypesJSONRPCMessagemodel_validate_jsonr	   	exceptionr6   r   r   )r/   r4   r5   r6   rb   rc   session_id_paramresponserT   writerrr   rB   errrn   rF   s   &&&&           r   handle_post_message&SseServerTransport.handle_post_message   sg    ,-%)  $~~>>wPT>UU'==="//33LA#NN@A 8cJH!%$777	8"23JLL.zl;< **..z:NN<ZLIJ 8cJH!%$777\\^#tf-.	**>>tDGLL5gY?@ )A(D:?:KLMJC8ut,,,kk/***W V= 8
  	8NN:;K:LMN 4#FH!%$7777	8 8#  	67 9sKH54000++c"""	 	-*s   AKHKKHAK.H/K4$H "K;1K,I-KIK"7I A	K"K #K;K<KKK<II
IKIKKJ=$.J8JJ8,J/-J82K8J==KKc                t   < V ^8  d   Qh/ S[ ;R&   S[S[S[S[S[,          ,          3,          ;R&   S[;R&   # )r   r*   r+   r,   )r   r_   r   r   r   	Exceptionr   )r   r   s   "r   r   r    @   s@      N  t%;NY<V%WWXX  +* r!   )r*   r+   r,   )N)__name__
__module____qualname____firstlineno____doc__r'   r   rh   r{   __annotate_func____static_attributes____classdictcell____classcell__)r0   r   s   @@r   r   r   @   s@     	'R 'RR M. M.^0+ 0+S  r!   r   )'r   rR   
contextlibr   typingr   urllib.parser   uuidr   r   rZ   anyio.streams.memoryr   r   pydanticr	   sse_starletter
   starlette.requestsr   starlette.responsesr   starlette.typesr   r   r   	mcp.typesrs   mcp.server.transport_securityr   r   mcp.shared.messager   r   	getLoggerr   r-   r    r!   r   <module>r      s^   %N  *     R $ - & ( 0 0  E			8	$y+ y+r!   