
    Cj             	         S SK Jr  S SKrS SKrS SKrS SKrS SKJrJrJ	r	  S SK
JrJrJr  S SKJr  S SKJr  S SKJrJrJrJrJrJr  S SKrS SKr\R6                  S:  a  S S	KJr  S S
KJr  S SKJ r J!r!  S SK"J#r#J$r$J%r&J'r'  S SK(J)r)  S SK*J+r+  S SK,J-r-J.r.J/r/  S SK0J1r1  S SK2J3r3  S SK4J5r5J6r6J7r7J8r8J9r9J:r:J;r;  S SK<J=r=J>r>  SSK?J@r@  SSKAJArA  SSKBJCrC  SSKDJErE  SSKFJGrG  SSKHJIrIJJrJJKrKJLrLJMrM   " S S\>SS9rN " S  S!\>SS9rO\S"   rP\Q\R\P4   rS\(       a  \	\C\   S#\&/\G\T   4   rUO\	S$\4   rU\(       a  \P\O-  \S-  \U-  \T-  S-  rVO\\P\O\S\U\TS4   rV\" S%5      rW   SE       SFS& jjrX " S' S(\.5      rY\SS)S*S+\XS\.S,.                 SGS- jj5       rZ " S. S/\[5      r\ " S0 S1\[5      r] " S2 S35      r^\^" 5       r_\(       a  SS4K`Jara  \b\ \3\[-     \!\3   4   \b\ \3\[-     \!\3   \-S-  4   -  rc " S5 S6\R                  5      re " S7 S8\e\R                  5      rf " S9 S:\>5      rg " S; S<\f5      rh " S= S>\>5      ri " S? S@\f5      rj " SA SB\>5      rk " SC SD\f5      rlg)H    )annotationsN)AsyncGenerator	AwaitableCallable)AbstractAsyncContextManagerAsyncExitStackasynccontextmanager)	timedelta)Path)TYPE_CHECKINGAnyLiteralTypeVarUnioncast)      )BaseExceptionGroup)ClosedResourceError)MemoryObjectReceiveStreamMemoryObjectSendStream)ClientSessionStdioServerParametersToolstdio_client)MessageHandlerFnT)
sse_client)GetSessionIdCallbackStreamableHTTPTransportstreamablehttp_client)McpError)SessionMessage)CallToolResultGetPromptResultInitializeResultListPromptsResultListResourcesResultListResourceTemplatesResultReadResourceResult)NotRequired	TypedDict   )	UserError)logger)RunContextWrapper)ToolErrorFunction)MaybeAwaitable   )HttpClientFactoryMCPToolMetaResolver
ToolFilterToolFilterContextToolFilterStaticc                       \ rS rSr% S\S'   Srg)RequireApprovalToolList7   z	list[str]
tool_names N__name__
__module____qualname____firstlineno____annotations____static_attributes__r<       c/home/rurouni/.local/share/pipx/venvs/strix-agent/lib/python3.13/site-packages/agents/mcp/server.pyr9   r9   7   s    rD   r9   F)totalc                  *    \ rS rSr% S\S'   S\S'   Srg)RequireApprovalObject;   r9   alwaysneverr<   Nr=   r<   rD   rE   rH   rH   ;   s    ##""rD   rH   rJ   rK   	AgentBase.Tc                `    SS0nUb  XS'   U b  XS'   Ub  X#S'   [         R                  " S0 UD6$ )Nfollow_redirectsTtimeoutheadersauthr<   )httpxAsyncClient)rR   rQ   rS   kwargss       rE   &_create_default_streamable_http_clientrW   a   sK    
 1$7F#y#yv&v&&rD   c                  ,   ^  \ rS rSrSU 4S jjrSrU =r$ )7_InitializedNotificationTolerantStreamableHTTPTransportp   c                ,  >#    UR                   R                  nU R                  U5      (       d  [        TU ]  U5      I S h  vN   g  [        TU ]  U5      I S h  vN   g  N N! [
        R                   a    [        R                  " SSS9   g f = f7f)Nz.Ignoring initialized notification HTTP failureT)exc_info)	session_messagemessage_is_initialized_notificationsuper_handle_post_requestrT   	HTTPErrorr.   warning)selfctxr^   	__class__s      rE   ra   L_InitializedNotificationTolerantStreamableHTTPTransport._handle_post_requestq   s     %%--0099'.s333	'.s333	 4 4 	NN@ 	sG   ?BA!B	A% A#A%  B#A% %)BBBBr<   )re   r   returnNone)r>   r?   r@   rA   ra   rC   __classcell__rf   s   @rE   rY   rY   p   s     rD   rY      ,  T)rR   rQ   sse_read_timeoutterminate_on_closehttpx_client_factoryrS   transport_factoryc              R  ^^^^#    [        U[        5      (       a  UR                  5       OUn[        U[        5      (       a  UR                  5       OUn	U" U[        R                  " XS9US9mU" U 5      m[
        R                  [        [        -     " S5      u  mn
[
        R                  [           " S5      u  pT IS h  vN   [
        R                  " 5        IS h  vN m [        R                  " SU  35        SUUUU4S jjnTR                  TR                  TUTUUT5         U
UTR                  47v   TR                  (       a   U(       a  TR!                  T5      I S h  vN   TR"                  R%                  5          TR'                  5       I S h  vN   UR'                  5       I S h  vN   S S S 5      IS h  vN   S S S 5      IS h  vN   g  GN N Nu! TR                  (       a!  U(       a  TR!                  T5      I S h  vN    TR"                  R%                  5         f = f N N! TR'                  5       I S h  vN    UR'                  5       I S h  vN    f = f N! , IS h  vN  (       d  f       N= f N! , IS h  vN  (       d  f       g = f7f)N)read)rR   rQ   rS   r   z'Connecting to StreamableHTTP endpoint: c                 @   > TR                  TR                  T T5        g N)
start_soonhandle_get_stream)clientread_stream_writertg	transports   rE   start_get_stream?_streamablehttp_client_with_transport.<locals>.start_get_stream   s    MM)"="=vGYZrD   )rh   ri   )
isinstancer
   total_secondsrT   Timeoutanyiocreate_memory_object_streamr"   	Exceptioncreate_task_groupr.   debugrv   post_writerget_session_id
session_idterminate_sessioncancel_scopecancelaclose)urlrR   rQ   rn   ro   rp   rS   rq   timeout_secondssse_read_timeout_secondsread_streamwrite_streamwrite_stream_readerr|   rx   ry   rz   r{   s                 @@@@rE   %_streamablehttp_client_with_transportr      s"     2<GY1O1Og++-U\O &	22 	&&(  "oMF
 "#&I&+&G&GYbHb&c	'# ).(I(I.(YZ[(\%Lv**,,,FseLM[ [ ))'& $	-#$!00  !++0B'99&AAAOO**,(//111"))+++; -, vv,2 B !++0B'99&AAAOO**,1+ )//111"))+++; -,,, vvvs  B=J'GJ'J!G"J%I1'AH8-G#?,H8+G!,H8I1H4I16H67I1;JI/JJ'JJ'J!H8#-H1H H11H84I16I18I,II,%I(&I,,I1/J1J	7I:8J	JJ'J$JJ$ J'c                      \ rS rSrSrSrg)#_SharedSessionRequestNeedsIsolation   zNRaised when a shared-session request should be retried on an isolated session.r<   Nr>   r?   r@   rA   __doc__rC   r<   rD   rE   r   r      s    XrD   r   c                      \ rS rSrSrSrg)_IsolatedSessionRetryFailed   zIRaised when an isolated-session retry fails after consuming retry budget.r<   Nr   r<   rD   rE   r   r      s    SrD   r   c                      \ rS rSrSrg)
_UnsetType   r<   N)r>   r?   r@   rA   rC   r<   rD   rE   r   r      s    rD   r   )rM   c                     \ rS rSrSrSS\S4       SS jjr\R                  S 5       r	\
\R                  SS j5       5       r\R                  S 5       r\R                    S     SS	 jj5       r\R                   S       SS
 jj5       r\
SS j5       r\R                    SS j5       r\R                   S     SS jj5       rSSS jjr S   SS jjrS S jr\    S!S j5       r      S"S jr    S#S jrSrg)$	MCPServer   z.Base class for Model Context Protocol servers.FNc                P    Xl         U R                  US9U l        X0l        X@l        g)a  
Args:
    use_structured_content: Whether to use `tool_result.structured_content` when calling an
        MCP tool.Defaults to False for backwards compatibility - most MCP servers still
        include the structured content in the `tool_result.content`, and using it by
        default will cause duplicate content. You can set this to True if you know the
        server will not duplicate the structured content in the `tool_result.content`.
    require_approval: Approval policy for tools on this server. Accepts "always"/"never",
        a dict of tool names to those values, a boolean, an object with always/never
        tool lists (mirroring TS requireApproval), or a sync/async callable that receives
        `(run_context, agent, tool)` and returns whether the tool call needs approval.
        Normalized into a needs_approval policy.
    failure_error_function: Optional function used to convert MCP tool failures into
        a model-visible error message. If explicitly set to None, tool errors will be
        raised instead of converted. If left unset, the agent-level configuration (or
        SDK default) will be used.
    tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for
        tool calls. It is invoked by the Agents SDK before calling `call_tool`.
)require_approvalN)use_structured_content_normalize_needs_approval_needs_approval_policy_failure_error_functiontool_meta_resolver)rd   r   r   failure_error_functionr   s        rE   __init__MCPServer.__init__   s4    4 '=#&*&D&D- 'E '
# (>$"4rD   c                   #    g7f)zConnect to the server. For example, this might mean spawning a subprocess or
opening a network connection. The server is expected to remain connected until
`cleanup()` is called.
Nr<   rd   s    rE   connectMCPServer.connect  s
      	   c                    g)A readable name for the server.Nr<   r   s    rE   nameMCPServer.name  s     	rD   c                   #    g7f)zgCleanup the server. For example, this might mean closing a subprocess or
closing a network connection.
Nr<   r   s    rE   cleanupMCPServer.cleanup  
     
 	r   c                   #    g7f)'List the tools available on the server.Nr<   )rd   run_contextagents      rE   
list_toolsMCPServer.list_tools  s
      	r   c                   #    g7f)Invoke a tool on the server.Nr<   )rd   	tool_name	argumentsmetas       rE   	call_toolMCPServer.call_tool!  s
      	r   c                    g)zReturn the most recently fetched tools list, if available.

Implementations may return `None` when tools have not been fetched yet or caching is
disabled.
Nr<   r   s    rE   cached_toolsMCPServer.cached_tools+  s     rD   c                   #    g7f))List the prompts available on the server.Nr<   r   s    rE   list_promptsMCPServer.list_prompts5  r   r   c                   #    g7f)&Get a specific prompt from the server.Nr<   )rd   r   r   s      rE   
get_promptMCPServer.get_prompt<  r   r   c                <   #    [        SU R                   S35      e7f)a@  List the resources available on the server.

Args:
    cursor: An opaque pagination cursor returned in a previous
        :class:`~mcp.types.ListResourcesResult` as ``nextCursor``.  Pass it
        here to fetch the next page of results.  ``None`` fetches the first
        page.

Returns a :class:`~mcp.types.ListResourcesResult`.  When the result contains
a ``nextCursor`` field, call this method again with that cursor to retrieve
the next page.  Subclasses that do not support resources may leave this
unimplemented; it will raise :exc:`NotImplementedError` at call time.
MCP server 'zV' does not support list_resources. Override this method in your server implementation.NotImplementedErrorr   rd   cursors     rE   list_resourcesMCPServer.list_resourcesC  s+      "499+ &B B
 	
   c                <   #    [        SU R                   S35      e7f)aa  List the resource templates available on the server.

Args:
    cursor: An opaque pagination cursor returned in a previous
        :class:`~mcp.types.ListResourceTemplatesResult` as ``nextCursor``.
        Pass it here to fetch the next page of results.  ``None`` fetches
        the first page.

Returns a :class:`~mcp.types.ListResourceTemplatesResult`.  When the result
contains a ``nextCursor`` field, call this method again with that cursor to
retrieve the next page.  Subclasses that do not support resource templates
may leave this unimplemented; it will raise :exc:`NotImplementedError` at
call time.
r   z_' does not support list_resource_templates. Override this method in your server implementation.r   r   s     rE   list_resource_templates!MCPServer.list_resource_templatesV  s+     " "499+ &B B
 	
r   c                <   #    [        SU R                   S35      e7f)ab  Read the contents of a specific resource by URI.

Args:
    uri: The URI of the resource to read. See :class:`~pydantic.networks.AnyUrl`
        for the supported URI formats.

Returns a :class:`~mcp.types.ReadResourceResult`.  Subclasses that do not
support resources may leave this unimplemented; it will raise
:exc:`NotImplementedError` at call time.
r   zU' does not support read_resource. Override this method in your server implementation.r   )rd   uris     rE   read_resourceMCPServer.read_resourcel  s+      "499+ &B B
 	
r   c                &   U c  gS	S jnS
S jn[        U [        5      (       a  U" U 5      (       a  U R                  S0 5      nU R                  S0 5      n[        U[        5      (       a  UR                  S/ 5      O/ n[        U[        5      (       a  UR                  S/ 5      O/ n0 nU H  nSU[        U5      '   M     U H  nSU[        U5      '   M     U$ [        U [        5      (       at  0 n	U R	                  5        H\  u  p[        U
[
        5      (       a  X[        U5      '   M)  [        U
[        5      (       d  M@  U
S;   d  MH  U" U
5      U	[        U5      '   M^     U	$ [        U 5      (       a  U $ [        U [
        5      (       a  U $ U" U 5      $ )z:Normalize approval inputs to booleans or a name->bool map.Fc                    U S:H  $ )NrJ   r<   )values    rE   _to_bool5MCPServer._normalize_needs_approval.<locals>._to_bool  s    H$$rD   c                    [        U [        5      (       d  gS H:  nX;  a  M
  U R                  U5      n[        U[        5      (       d  M2  SU;   d  M:    g   g)NFrL   r;   T)r~   dictget)r   keyentrys      rE   _is_tool_list_schemaAMCPServer._normalize_needs_approval.<locals>._is_tool_list_schema  sN    eT***#		#eT**|u/D + rD   rJ   rK   r;   TrL   )r   strrh   bool)r   objectrh   r   )r~   r   r   r   itemsr   callable)r   r   r   always_entrynever_entryalways_namesnever_namestool_list_mappingr   tool_mappingr   s              rE   r   #MCPServer._normalize_needs_approval|  s    #	%		 &--2FGW2X2X:J:N:NxY[:\L9I9M9MgWY9ZK6@t6T6T  r2Z\  @J+W[?\?\+//,;bdK13$/3!#d), %#/4!#d), $$$&--,.L/557eT**.3T+s++9L0L.6uoLT+	  8
  $%%##&--##())rD   c                   ^^^ U R                   m[        T5      (       a  Tc  g        SUUU4S jjnU$ [        T[        5      (       a%  [	        TR                  TR                  S5      5      $ [	        T5      $ )a4  Return a FunctionTool.needs_approval value for a given MCP tool.

Legacy callers may omit ``agent`` when using ``MCPUtil.to_function_tool()`` directly.
When approval is configured with a callable policy and no agent is available, this method
returns ``True`` to preserve the historical fail-closed behavior.
Tc                   >#    T" U TT5      n[         R                  " U5      (       a
  UI S h  vN n[        U5      $  N7fru   )inspectisawaitabler   )r   _args_call_idresultr   policytools       rE   _needs_approval?MCPServer._get_needs_approval_for_tool.<locals>._needs_approval  s=       UD9&&v..#)\FF|# *s   +A >A F)r   RunContextWrapper[Any]r   zdict[str, Any]r   r   rh   r   )r   r   r~   r   r   r   r   )rd   r  r   r  r   s    `` @rE   _get_needs_approval_for_tool&MCPServer._get_needs_approval_for_tool  s     ,,F}$3$<J$VY$$ $ #"fd##

499e455F|rD   c                f    U R                   [        L a  U$ [        [        S-  U R                   5      $ )z9Return the effective error handler for MCP tool failures.N)r   _UNSETr   r0   )rd   agent_failure_error_functions     rE   _get_failure_error_function%MCPServer._get_failure_error_function  s1     ''61//%,d.J.JKKrD   )r   r   r   r   )r   r   r   RequireApprovalSettingr   %ToolErrorFunction | None | _UnsetTyper   MCPToolMetaResolver | Nonerh   r   NNr   RunContextWrapper[Any] | Noner   AgentBase | Nonerh   list[MCPTool]ru   r   r   r   dict[str, Any] | Noner   r  rh   r#   rh   zlist[MCPTool] | Nonerh   r&   r   r   r   r  rh   r$   r   
str | Nonerh   r'   r   r  rh   r(   r   r   rh   r)   )r   r  rh   zebool | dict[str, bool] | Callable[[RunContextWrapper[Any], AgentBase, MCPTool], MaybeAwaitable[bool]])r  MCPToolr   r  rh   zObool | Callable[[RunContextWrapper[Any], dict[str, Any], str], Awaitable[bool]])r	  ToolErrorFunction | Nonerh   r  )r>   r?   r@   rA   r   r  r   abcabstractmethodr   propertyr   r   r   r   r   r   r   r   r   r   staticmethodr   r  r
  rC   r<   rD   rE   r   r      s   8 (-37HN9=5 $5 15 !F	5
 75B 	     	  	 6:"&2   
	  	
 '+	 ) $	
 
    		  	<@$9	 
( $(
 
	$
,
  8*08*	W	8* 8*t   
Y	BL,DL	!LrD   r   c                    ^  \ rS rSrSr\SS j5       rSSSSSS\S4                   S U 4S jjjrS!S	 jr	  S"       S#S
 jjr
      S$S jr        S%S jr\R                    S&S j5       rS rS rS rS'S jrS(S jrS!S jrS r  S"     S)S jjr S*       S+S jjr      S,S jr  S-S jr S*     S.S jjrS*S/S jjr S*   S0S jjrS1S jrS rSr U =r!$ )2_MCPServerWithClientSessioni  zUBase class for MCP servers that use a `ClientSession` to communicate with the server.c                    U R                   $ ru   )_tools_listr   s    rE   r   (_MCPServerWithClientSession.cached_tools  s    rD   NFr         ?c                H  > [         TU ]  UUU	U
S9  SU l        [        5       U l        [
        R                  " 5       U l        [
        R                  " 5       U l        Xl	        SU l
        X l        XPl        X`l        Xpl        SU l        SU l        X0l        SU l        SU l        g)a+  
Args:
    cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
    cached and only fetched from the server once. If `False`, the tools list will be
    fetched from the server on each call to `list_tools()`. The cache can be invalidated
    by calling `invalidate_tools_cache()`. You should set this to `True` if you know the
    server will not change its tools list, because it can drastically improve latency
    (by avoiding a round-trip to the server every time).

    client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.
    tool_filter: The tool filter to use for filtering tools.
    use_structured_content: Whether to use `tool_result.structured_content` when calling an
        MCP tool. Defaults to False for backwards compatibility - most MCP servers still
        include the structured content in the `tool_result.content`, and using it by
        default will cause duplicate content. You can set this to True if you know the
        server will not duplicate the structured content in the `tool_result.content`.
    max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.
        Defaults to no retries.
    retry_backoff_seconds_base: The base delay, in seconds, used for exponential
        backoff between retries.
    message_handler: Optional handler invoked for session messages as delivered by the
        ClientSession.
    require_approval: Approval policy for tools on this server. Accepts "always"/"never",
        a dict of tool names to those values, a boolean, or an object with always/never
        tool lists.
    failure_error_function: Optional function used to convert MCP tool failures into
        a model-visible error message. If explicitly set to None, tool errors will be
        raised instead of converted. If left unset, the agent-level configuration (or
        SDK default) will be used.
    tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for
        tool calls. It is invoked by the Agents SDK before calling `call_tool`.
)r   r   r   r   NTF)r`   r   sessionr   
exit_stackasyncioLock_cleanup_lock_request_lockcache_tools_listserver_initialize_resultclient_session_timeout_secondsmax_retry_attemptsretry_backoff_seconds_basemessage_handler_cache_dirtyr'  tool_filter_serialize_session_requests_get_session_id)rd   r1  r3  r8  r   r4  r5  r6  r   r   r   rf   s              rE   r   $_MCPServerWithClientSession.__init__  s    Z 	#9-#91	 	 	
 .2*8*:+2<<>+2<<> 0AE%.L+"4*D'. !15&+0(<@rD   c                   #    U R                   (       d  U" 5       I S h  vN $ U R                   IS h  vN   U" 5       I S h  vN sS S S 5      IS h  vN   $  N9 N& N N! , IS h  vN  (       d  f       g = f7fru   )r9  r0  )rd   funcs     rE   _maybe_serialize_request4_MCPServerWithClientSession._maybe_serialize_request/  sO     //<%%%< &%%  % &%%%sf   A:AA:AA:A AA A:AA:A:A A: A7&A)'A73A:c                   #    U R                   c  U$ [        U R                   [        5      (       a  U R                  XR                   5      $ Ub  Uc  [	        S5      eU R                  XU5      I Sh  vN $  N7f)z+Apply the tool filter to the list of tools.Nz=run_context and agent are required for dynamic tool filtering)r8  r~   r   _apply_static_tool_filterr-   _apply_dynamic_tool_filter)rd   toolsr   r   s       rE   _apply_tool_filter._MCPServerWithClientSession._apply_tool_filter5  su      #L d&&--11%9I9IJJ "em _``88USSSSs   A0A92A73A9c                    UnSU;   a(  US   nU Vs/ s H  oUR                   U;   d  M  UPM     nnSU;   a(  US   nU Vs/ s H  oUR                   U;  d  M  UPM     nnU$ s  snf s  snf )z=Apply static tool filtering based on allowlist and blocklist.allowed_tool_namesblocked_tool_namesr   )rd   rC  static_filterfiltered_toolsallowed_namestblocked_namess          rE   rA  5_MCPServerWithClientSession._apply_static_tool_filterI  s       =0)*>?M)7SA66];RaNS  =0)*>?M)7WA66;VaNW T
 Xs   A!A! A&A&c           
       #    [        U R                  5      (       d  [        S5      eU R                  n[        UUU R                  S9n/ nU HN  n U" XW5      n[
        R                  " U5      (       a  UI Sh  vN n	OUn	U	(       a  UR                  U5        MN  MP     U$  N'! [         a>  n
[        R                  " SUR                   SU R                   SU
 35         Sn
A
M  Sn
A
ff = f7f)z>Apply dynamic tool filtering using a callable filter function.z2Tool filter must be callable for dynamic filtering)r   r   server_nameNz$Error applying tool filter to tool 'z' on server '': )r   r8  
ValueErrorr6   r   r   r   appendr   r.   error)rd   rC  r   r   tool_filter_funcfilter_contextrK  r  r   should_includees              rE   rB  6_MCPServerWithClientSession._apply_dynamic_tool_filter[  s      (())QRR++ +#		
 D).?&&v..+1\N%+N!"))$/ " &  &2  :499+]SWS\S\R]]`ab`cd sB   AC.(B#9B!:B#C.!B##
C+-3C& C.&C++C.c                    g)"Create the streams for the server.Nr<   r   s    rE   create_streams*_MCPServerWithClientSession.create_streams  s    
 	rD   c                B   #    U R                  5       I S h  vN   U $  N7fru   )r   r   s    rE   
__aenter__&_MCPServerWithClientSession.__aenter__  s     lln 	s   c                @   #    U R                  5       I S h  vN   g  N7fru   )r   )rd   exc_type	exc_value	tracebacks       rE   	__aexit__%_MCPServerWithClientSession.__aexit__  s     llns   c                    SU l         g)zInvalidate the tools cache.TN)r7  r   s    rE   invalidate_tools_cache2_MCPServerWithClientSession.invalidate_tools_cache  s
     rD   c                d   [        U[        R                  [        R                  -  [        R                  -  5      (       a  U$ [        U[
        5      (       aX  UR                   HH  n[        U[        R                  [        R                  -  [        R                  -  5      (       d  MF  Us  $    g)z4Extract HTTP error from exception or ExceptionGroup.N)r~   rT   HTTPStatusErrorConnectErrorTimeoutExceptionr   
exceptions)rd   rY  excs      rE   "_extract_http_error_from_exception>_MCPServerWithClientSession._extract_http_error_from_exception  s    a..1C1CCeF\F\\]]H a+,,||..1C1CCeF\F\\  J	 $ rD   c                t   SU R                    S3n[        U[        R                  5      (       a5  USUR                  R
                   SUR                  R                   S3-  nOI[        U[        R                  5      (       a  US-  nO$[        U[        R                  5      (       a  US-  n[        U5      Ue)z+Raise appropriate UserError for HTTP error.!Failed to connect to MCP server 'rR  HTTP error  ()Could not reach the server.Connection timeout.)
r   r~   rT   rl  responsestatus_codereason_phraserm  rn  r-   )rd   
http_errorerror_messages      rE    _raise_user_error_for_http_error<_MCPServerWithClientSession._raise_user_error_for_http_error  s    ;DII;cJj%"7"788{:+>+>+J+J*K2jNaNaNoNoMppqrrM
E$6$677::M
E$:$:;;22M&J6rD   c                
  #    Sn  U" 5       I S h  vN $  N! [          a\    US-  nU R                  S:w  a  X R                  :  a  e U R                  SUS-
  -  -  n[        R                  " U5      I S h  vN     Of = fM}  7f)Nr   r2   r,   )r   r4  r5  r-  sleep)rd   r=  attemptsbackoffs       rE   _run_with_retries-_MCPServerWithClientSession._run_with_retries  s     -!V|#| -A**b0X@W@W5W99Q8a<=PQmmG,,,- s>   B
  B AA>5A86A>;B=A>>Bc           
        #    Sn U R                   R                  U R                  5       5      I Sh  vN nUtp4nU(       a  [        US   5      (       a  US   OSU l        U R                   R                  [        UUU R                  (       a  [        U R                  S9OSU R                  S95      I Sh  vN nUR                  5       I Sh  vN nXpl
        X`l        Sn U(       d   U R-                  5       I Sh  vN   gg N NO N9! [         a  nU R                  U5      n	U	(       a  U R                  U	5        [        U[         R"                  5      (       a  e [        U[$        R&                  [$        R(                  -  [$        R*                  -  5      (       a  U R                  U5        e SnAff = f N! [.         a    e [         a  n
[        U
[0        5      (       a:  S[3        U
5      ;   a+  [4        R6                  " SU R8                   S	U
 35         Sn
A
g[4        R:                  " S
U R8                   S	U
 35         Sn
A
gSn
A
ff = f! U(       d   U R-                  5       I Sh  vN    f ! [.         a    e [         a  n
[        U
[0        5      (       a:  S[3        U
5      ;   a+  [4        R6                  " SU R8                   S	U
 35         Sn
A
f [4        R:                  " S
U R8                   S	U
 35         Sn
A
f Sn
A
ff = ff = f7f)zConnect to the server.FNr   secondsr6  Tcancel scopez:Ignoring cancel scope error during cleanup of MCP server 'rR  z$Error during cleanup of MCP server ')r,  enter_async_contextr]  r   r:  r   r3  r
   r6  
initializer2  r+  r   rq  r  r~   r-  CancelledErrorrT   rl  rm  rn  r   r-   RuntimeErrorr   r.   r   r   rc   )rd   connection_succeededr{   rs   writerestr+  server_resultrY  r}  cleanup_errors              rE   r   #_MCPServerWithClientSession.connect  s    $@	"ooAA$BUBUBWXXI "+D$.2xQ7H7H47dD  OO??:: d&I&IJ$($8$8	 	G #*"4"4"66M,9)"L#' ( (,,.(( (S Y	 7  	@@CJ55jA !W3344 !U22U5G5GG%J`J``aa55a8 !	* )     "->>>UX%V D   $		{#m_>  B499+SQ^P_`  (,,.((     "->>>UX%V D   $		{#m_>  B499+SQ^P_`  (s   L,D DBD 7D8D D	D #L+F; >F9?F; LD D 	D 
F6BF11F66I 9F; ;IA
I	L&I	L	ILLI4-I0.I43L4LA
LL&L=LLLLc                  ^ ^#    T R                   (       d  [        S5      eT R                   mTc   e T R                  (       a/  T R                  (       d  T R                  (       a  T R                  nOBT R                  U U4S j5      I Sh  vN nUR                  T l        ST l        T R                  nUnT R                  b  T R                  XQU5      I Sh  vN nU$  NS N! [        R                   a7  nUR                  R                  n[        ST R                   SU 35      UeSnAf[        R                   a  n[        ST R                   S35      UeSnAff = f7f)r   =Server not initialized. Make sure you call `connect()` first.Nc                 .   > T R                  U4S j5      $ )Nc                 $   > T R                  5       $ ru   )r   r+  s   rE   <lambda>J_MCPServerWithClientSession.list_tools.<locals>.<lambda>.<locals>.<lambda>  s    'BTBTBVrD   r>  rd   r+  s   rE   r  8_MCPServerWithClientSession.list_tools.<locals>.<lambda>  s    D99:VWrD   Fz&Failed to list tools from MCP server '': HTTP error 5': Connection lost. The server may have disconnected.)r+  r-   r1  r7  r'  r  rC  r8  rD  rT   rl  rz  r{  r   rm  )	rd   r   r   rC  r   rK  rY  r{  r+  s	   `       @rE   r   &_MCPServerWithClientSession.list_tools  sQ     ||[\\,,"""	$$T->->4CSCS((  $55W   $*<< $)!(( #N+'+'>'>~\a'b!b!! "c$$ 	**00K8>R]Q^_ !! 	8 D4 5 	sZ   .E#AC$ C AC$ C"C$ E# C$ "C$ $E 82D**E EE  E#c           	     *  ^ ^^^^#    T R                   (       d  [        S5      eT R                   mTc   e T R                  TTS9  Tc   T R                  UU UU4S j5      I Sh  vN $ T R                  UUU UU4S j5      I Sh  vN $  N% N! [        R
                   a:  nUR                  R                  n[        ST ST R                   SU 35      UeSnAf[        R                   a"  n[        ST ST R                   S	35      UeSnAff = f7f)
r   r  Nr   r   c                 2   > TR                  U UU4S j5      $ )Nc                 (   > TR                  TT 5      $ ru   r   )r   r+  r   s   rE   r  I_MCPServerWithClientSession.call_tool.<locals>.<lambda>.<locals>.<lambda>>  s     1 1)Y GrD   r  )r   rd   r+  r   s   rE   r  7_MCPServerWithClientSession.call_tool.<locals>.<lambda>=  s    D99GrD   c                 4   > TR                  U UUU4S j5      $ )Nc                 &   > TR                  TT TS9$ N)r   r  )r   r   r+  r   s   rE   r  r  C  s    G--i-NrD   r  r   r   rd   r+  r   s   rE   r  r  B  s    55NrD   Failed to call tool '' on MCP server 'r  r  )
r+  r-   _validate_required_parametersr  rT   rl  rz  r{  r   rm  )rd   r   r   r   rY  r{  r+  s   ````  @rE   r   %_MCPServerWithClientSession.call_tool-  s2     ||[\\,,"""	..i.X|!33  
 //   

 $$ 	**00K'	{2CDII; O)],  !! 	'	{2CDII; O4 5 	sd   .D.B $B
%B (D)B BB 	D
B B D"5CD.DDDc                  ^ U R                   c  g[        U4S jU R                    5       S5      nUb  [        UR                  [        5      (       d  gUR                  R                  S5      n[        U[        5      (       a  U(       d  gUc  0 nO4[        U[        5      (       a  UnO[        ST SU R                   S35      eU Vs/ s H  n[        U[        5      (       d  M  UPM     nnU Vs/ s H  ofU;  d  M
  UPM     nnU(       a8  SR                  [        U5      5      n	[        ST SU R                   SU	 35      egs  snf s  snf )	zQValidate required tool parameters from cached MCP tool schemas before invocation.Nc              3  J   >#    U  H  oR                   T:X  d  M  Uv   M     g 7fru   rI  ).0itemr   s     rE   	<genexpr>L_MCPServerWithClientSession._validate_required_parameters.<locals>.<genexpr>Y  s     Q&6d))y:PTT&6s   #	#requiredr  r  z': arguments must be an object.z, z ': missing required parameters: )r'  nextr~   inputSchemar   r   listr-   r   r   joinsorted)
rd   r   r   r  raw_requiredarguments_to_validater   required_namesmissingmissing_texts
    `        rE   r  9_MCPServerWithClientSession._validate_required_parametersR  sC    #Qd&6&6QSWX<z$*:*:DAA''++J7,--\46!	4(($-!'	{2CDII; O/ / 
 ,8Q<4:dC;P$<Q$2XNDBW6W4NX99VG_5L'	{2CDII; O00<~?   RXs   	E&E2	E?Ec                   ^#    U R                   (       d  [        S5      eU R                   mTc   eU R                  U4S j5      I Sh  vN $  N7f)r   r  Nc                 $   > T R                  5       $ ru   )r   r  s   rE   r  :_MCPServerWithClientSession.list_prompts.<locals>.<lambda>|  s    7;O;O;QrD   r+  r-   r>  r  s    @rE   r   (_MCPServerWithClientSession.list_promptst  sH      ||[\\,,"""223QRRRRs   AA	A
Ac                   ^^^#    U R                   (       d  [        S5      eU R                   mTc   eU R                  UUU4S j5      I Sh  vN $  N7f)r   r  Nc                 (   > TR                  TT 5      $ ru   )r   )r   r   r+  s   rE   r  8_MCPServerWithClientSession.get_prompt.<locals>.<lambda>  s    7;M;MdT];^rD   r  )rd   r   r   r+  s    ``@rE   r   &_MCPServerWithClientSession.get_prompt~  sH      ||[\\,,"""223^____s   AAAAc                   ^^#    U R                   (       d  [        S5      eU R                   mTc   eU R                  UU4S j5      I Sh  vN $  N7f)z+List the resources available on the server.r  Nc                 &   > TR                  T 5      $ ru   )r   r   r+  s   rE   r  <_MCPServerWithClientSession.list_resources.<locals>.<lambda>  s    7;Q;QRX;YrD   r  rd   r   r+  s    `@rE   r   *_MCPServerWithClientSession.list_resources  sF     ||[\\,,"""223YZZZZ   AAAAc                   ^^#    U R                   (       d  [        S5      eU R                   mTc   eU R                  UU4S j5      I Sh  vN $  N7f)z4List the resource templates available on the server.r  Nc                 &   > TR                  T 5      $ ru   )r   r  s   rE   r  E_MCPServerWithClientSession.list_resource_templates.<locals>.<lambda>  s    7;Z;Z[a;brD   r  r  s    `@rE   r   3_MCPServerWithClientSession.list_resource_templates  sH      ||[\\,,"""223bccccr  c                   ^^^#    U R                   (       d  [        S5      eU R                   mTc   eSSKJm  U R	                  UUU4S j5      I Sh  vN $  N7f)zRead the contents of a specific resource by URI.

Args:
    uri: The URI of the resource to read. See :class:`~pydantic.networks.AnyUrl`
        for the supported URI formats.
r  Nr   )AnyUrlc                 2   > TR                  T " T5      5      $ ru   )r   )r  r+  r   s   rE   r  ;_MCPServerWithClientSession.read_resource.<locals>.<lambda>  s    7;P;PQWX[Q\;]rD   )r+  r-   pydanticr  r>  )rd   r   r  r+  s    `@@rE   r   )_MCPServerWithClientSession.read_resource  sK      ||[\\,,"""#223]^^^^s   AAAAc                  #    U R                    ISh  vN   U R                  SL n U R                  R                  5       I Sh  vN   SU l        SU l        SSS5      ISh  vN   g NT N%! [        R
                   a,  n[        R                  " SU R                   SU 35        e SnAf[         Ga  nSnSnSnSU R                   S3nUR                   Hl  n[        U[        R                  5      (       a  UnM&  [        U[        R                  5      (       a  UnMI  [        U[        R                  5      (       d  Mj  UnMn     U(       as  U(       a@  USUR                   R"                   SUR                   R$                   S3-  n['        U5      Ue[        R(                  " SU R                   SU 35         SnAGNxU(       aD  U(       a  US	-  n['        U5      Ue[        R(                  " S
U R                   SU 35         SnAGNU(       aD  U(       a  US-  n['        U5      Ue[        R(                  " SU R                   SU 35         SnAGN[+        S UR                   5       5      n	U	(       a  [        R                  " SU 35         SnAGNP[        R,                  " SU 35         SnAGNoSnAf[.         ag  n[        U[0        5      (       a.  S[3        U5      ;   a  [        R                  " SU 35         SnAGN[        R,                  " SU 35         SnAGNSnAff = f! SU l        SU l        f = f GN! , ISh  vN  (       d  f       g= f7f)zCleanup the server.Nz"Cleanup cancelled for MCP server 'rR  rt  ru  rv  rw  z)HTTP error during cleanup of MCP server 'rx  z/Connection error during cleanup of MCP server 'ry  z,Timeout error during cleanup of MCP server 'c              3  l   #    U  H*  n[        U[        5      =(       a    S [        U5      ;   v   M,     g7f)r  N)r~   r  r   )r  rp  s     rE   r  6_MCPServerWithClientSession.cleanup.<locals>.<genexpr>  s0      1#0C #35T.CPSH:TT#0s   24z,Ignoring cancel scope error during cleanup: zError cleaning up server: r  )r/  r+  r,  r   r-  r  r.   r   r   r   ro  r~   rT   rl  rm  rn  rz  r{  r|  r-   rc   anyrU  r   r  r   r:  )
rd   is_failed_connection_cleanuprY  egr}  connect_errortimeout_errorr~  rp  has_cancel_scope_errors
             rE   r   #_MCPServerWithClientSession.cleanup  s    %%% ,0<<4+?(C,oo,,...B  $'+$S &%% /)) A$))CPQsST% 4H "
 $ $"CDII;c R==C!#u'<'<==%(
#C););<<(+#C)?)?@@(+ ) 3%;z7J7J7V7V6WWYZdZmZmZ{Z{Y||})~~'6JF G		{RUV`Uab  #3%)FF'6MIMdii[X[\i[jk  #3%)>>'6MIJ499+UXYfXgh 
 .1 1#%==1 .* .'STVSW%XYY'A"%FGG C a..>SV3KLL#OPQs!STTLL#=aS!ABBC  $'+$S &%%%s   MA(MMA,A*A,	MM"M#M*A,,L, 'B''L,5BJ8A:J8;L/AJ8L/AJ8L/<J8L/J82L/8L,=L'L/L'!L/'L,,L//L??MMMMMM)r7  r/  r:  r0  r9  r'  r1  r3  r,  r4  r6  r5  r2  r+  r8  r  )r1  r   r3  float | Noner8  r5   r   r   r4  intr5  floatr6  MessageHandlerFnT | Noner   r  r   r  r   r  )r=  zCallable[[], Awaitable[T]]rh   rN   r  )rC  r  r   r  r   r  rh   r  )rC  r  rJ  r7   rh   r  )rC  r  r   r  r   rM   rh   r  rh   z/AbstractAsyncContextManager[MCPStreamTransport])rY  BaseExceptionrh   zException | None)r}  r   rh   ri   r  ru   r  )r   r   r   r  rh   ri   r  r  r  r  r  )"r>   r?   r@   rA   r   r"  r   r  r   r>  rD  rA  rB  r   r!  r]  r`  rf  ri  rq  r  r  r   r   r   r  r   r   r   r   r   r   rC   rj   rk   s   @rE   r%  r%    si   _    #'',"#,/4837HN9=EAEA )5EA  	EA
 !%EA  EA %*EA 2EA 1EA !FEA 7EA EAN  6:"&	TT 3T  	T
 
T("3C	$(( ,( 	(
 
(T 		8 !7
-CN 6:"&&2&  & 
	&X '+	## )# $	#
 
#J  )> 	 DS	S =A``$9`	`[ $(d d	$d_K, K,rD   r%  c                  `    \ rS rSr% SrS\S'    S\S'    S\S'    S	\S
'    S\S'    S\S'   Srg)MCPServerStdioParamsi  zcMirrors `mcp.client.stdio.StdioServerParameters`, but lets you pass params without another
import.
r   commandzNotRequired[list[str]]argsNotRequired[dict[str, str]]envzNotRequired[str | Path]cwdzNotRequired[str]encodingz3NotRequired[Literal['strict', 'ignore', 'replace']]encoding_error_handlerr<   Nr>   r?   r@   rA   r   rB   rC   r<   rD   rE   r  r    sD     LU
  * 
%$<	  AdOOrD   r  c                     ^  \ rS rSrSrSSSSSSSSS\S4                       SU 4S jjjr  SS	 jr\SS
 j5       r	Sr
U =r$ )MCPServerStdioi  zMCP server implementation that uses the stdio transport. See the [spec]
(https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#stdio) for
details.
FN   r   r)  c                H  > [         TU ]  UUUUUUU	U
UUS9
  [        US   UR                  S/ 5      UR                  S5      UR                  S5      UR                  SS5      UR                  SS	5      S
9U l        U=(       d    SU R                  R
                   3U l        g)a
  Create a new MCP server based on the stdio transport.

Args:
    params: The params that configure the server. This includes the command to run to
        start the server, the args to pass to the command, the environment variables to
        set for the server, the working directory to use when spawning the process, and
        the text encoding used when sending/receiving messages to the server.
    cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
        cached and only fetched from the server once. If `False`, the tools list will be
        fetched from the server on each call to `list_tools()`. The cache can be
        invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
        if you know the server will not change its tools list, because it can drastically
        improve latency (by avoiding a round-trip to the server every time).
    name: A readable name for the server. If not provided, we'll create one from the
        command.
    client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.
    tool_filter: The tool filter to use for filtering tools.
    use_structured_content: Whether to use `tool_result.structured_content` when calling an
        MCP tool. Defaults to False for backwards compatibility - most MCP servers still
        include the structured content in the `tool_result.content`, and using it by
        default will cause duplicate content. You can set this to True if you know the
        server will not duplicate the structured content in the `tool_result.content`.
    max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.
        Defaults to no retries.
    retry_backoff_seconds_base: The base delay, in seconds, for exponential
        backoff between retries.
    message_handler: Optional handler invoked for session messages as delivered by the
        ClientSession.
    require_approval: Approval policy for tools on this server. Accepts "always"/"never",
        a dict of tool names to those values, or an object with always/never tool lists.
    failure_error_function: Optional function used to convert MCP tool failures into
        a model-visible error message. If explicitly set to None, tool errors will be
        raised instead of converted. If left unset, the agent-level configuration (or
        SDK default) will be used.
    tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for
        tool calls. It is invoked by the Agents SDK before calling `call_tool`.

r1  r3  r8  r   r4  r5  r6  r   r   r   r  r  r  r  r  zutf-8r  strict)r  r  r  r  r  r  zstdio: N)r`   r   r   r   paramsr  _namerd   r  r1  r   r3  r8  r   r4  r5  r6  r   r   r   rf   s                rE   r   MCPServerStdio.__init__  s    h 	-+I##91'A+-#91 	 	
 ,9%FB'

5!

5!ZZ
G4#)::.F#Q
 <wt{{':':&;<
rD   c                ,    [        U R                  5      $ )r\  )r   r  r   s    rE   r]  MCPServerStdio.create_streamsf  s     DKK((rD   c                    U R                   $ r   r   r   s    rE   r   MCPServerStdio.namel       zzrD   r   r  )r  r  r1  r   r   r  r3  r  r8  r5   r   r   r4  r  r5  r  r6  r  r   r  r   r  r   r  r  r  r>   r?   r@   rA   r   r  r   r]  r"  r   rC   rj   rk   s   @rE   r  r    s     "'78"&',"#,/4837HN9=J=$J= J= 	J=
 )5J=  J= !%J=  J= %*J= 2J= 1J= !FJ= 7J= J=X)	8)  rD   r  c                  `    \ rS rSr% SrS\S'    S\S'    S\S'    S\S	'    S
\S'    S\S'   Srg)MCPServerSseParamsir  z1Mirrors the params in`mcp.client.sse.sse_client`.r   r   r  rR   zNotRequired[float]rQ   rn   NotRequired[httpx.Auth | None]rS   NotRequired[HttpClientFactory]rp   r<   Nr  r<   rD   rE   r  r  r  s@    ;	H ((,B((P
((
 98rD   r  c                     ^  \ rS rSrSrSSSSSSSSS\S4                       SU 4S jjjr  SS	 jr\SS
 j5       r	Sr
U =r$ )MCPServerSsei  zMCP server implementation that uses the HTTP with SSE transport. See the [spec]
(https://spec.modelcontextprotocol.io/specification/2024-11-05/basic/transports/#http-with-sse)
for details.
FNr  r   r)  c                ~   > [         TU ]  UUUUUUU	U
UUS9
  Xl        U=(       d    SU R                  S    3U l        g)a	  Create a new MCP server based on the HTTP with SSE transport.

Args:
    params: The params that configure the server. This includes the URL of the server,
        the headers to send to the server, the timeout for the HTTP request, and the
        timeout for the SSE connection.

    cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
        cached and only fetched from the server once. If `False`, the tools list will be
        fetched from the server on each call to `list_tools()`. The cache can be
        invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
        if you know the server will not change its tools list, because it can drastically
        improve latency (by avoiding a round-trip to the server every time).

    name: A readable name for the server. If not provided, we'll create one from the
        URL.

    client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.
    tool_filter: The tool filter to use for filtering tools.
    use_structured_content: Whether to use `tool_result.structured_content` when calling an
        MCP tool. Defaults to False for backwards compatibility - most MCP servers still
        include the structured content in the `tool_result.content`, and using it by
        default will cause duplicate content. You can set this to True if you know the
        server will not duplicate the structured content in the `tool_result.content`.
    max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.
        Defaults to no retries.
    retry_backoff_seconds_base: The base delay, in seconds, for exponential
        backoff between retries.
    message_handler: Optional handler invoked for session messages as delivered by the
        ClientSession.
    require_approval: Approval policy for tools on this server. Accepts "always"/"never",
        a dict of tool names to those values, or an object with always/never tool lists.
    failure_error_function: Optional function used to convert MCP tool failures into
        a model-visible error message. If explicitly set to None, tool errors will be
        raised instead of converted. If left unset, the agent-level configuration (or
        SDK default) will be used.
    tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for
        tool calls. It is invoked by the Agents SDK before calling `call_tool`.
r  zsse: r   N)r`   r   r  r   r  s                rE   r   MCPServerSse.__init__  sZ    l 	-+I##91'A+-#91 	 	
 9uT[[%7$89
rD   c                d   U R                   S   U R                   R                  SS5      U R                   R                  SS5      U R                   R                  SS5      S.nS	U R                   ;   a  U R                   S	   US	'   S
U R                   ;   a  U R                   S
   US
'   [        S0 UD6$ )r\  r   rR   NrQ   r  rn   rm   )r   rR   rQ   rn   rS   rp   r<   )r  r   r   )rd   rV   s     rE   r]  MCPServerSse.create_streams  s    
 ;;u%{{y$7{{y!4 $0BF K	"
 T[[ ![[0F6N!T[[0-1[[9O-PF)*#F##rD   c                    U R                   $ r  r  r   s    rE   r   MCPServerSse.name  r	  rD   r
  )r  r  r1  r   r   r  r3  r  r8  r5   r   r   r4  r  r5  r  r6  r  r   r  r   r  r   r  r  r  r  rk   s   @rE   r  r    s     "'78"&',"#,/4837HN9=D:"D: D: 	D:
 )5D:  D: !%D:  D: %*D: 2D: 1D: !FD: 7D: D:L$	8$   rD   r  c                  x    \ rS rSr% SrS\S'    S\S'    S\S'    S\S	'    S
\S'    S\S'    S\S'    S
\S'   Srg)MCPServerStreamableHttpParamsi  zHMirrors the params in`mcp.client.streamable_http.streamablehttp_client`.r   r   r  rR   zNotRequired[timedelta | float]rQ   rn   zNotRequired[bool]ro   r  rp   r  rS   'ignore_initialized_notification_failurer<   Nr  r<   rD   rE   r  r    sR    R	H ((,++B44P))88P
(( .?>rD   r  c                  L  ^  \ rS rSrSrSSSSSSSSS\S4                       SU 4S jjjr  SS	 jr\S
 5       r	 S         SS jjr
SS jr S         SS jjr S         SS jjr S       SS jjr\SS j5       r\SS j5       rSrU =r$ )MCPServerStreamableHttpi  zMCP server implementation that uses the Streamable HTTP transport. See the [spec]
(https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http)
for details.
FNr  r   r)  c                   > [         TU ]  UUUUUUU	U
UUS9
  Xl        U=(       d    SU R                  S    3U l        SU l        g)a
  Create a new MCP server based on the Streamable HTTP transport.

Args:
    params: The params that configure the server. This includes the URL of the server,
        the headers to send to the server, the timeout for the HTTP request, the
        timeout for the Streamable HTTP connection, whether we need to
        terminate on close, and an optional custom HTTP client factory.

    cache_tools_list: Whether to cache the tools list. If `True`, the tools list will be
        cached and only fetched from the server once. If `False`, the tools list will be
        fetched from the server on each call to `list_tools()`. The cache can be
        invalidated by calling `invalidate_tools_cache()`. You should set this to `True`
        if you know the server will not change its tools list, because it can drastically
        improve latency (by avoiding a round-trip to the server every time).

    name: A readable name for the server. If not provided, we'll create one from the
        URL.

    client_session_timeout_seconds: the read timeout passed to the MCP ClientSession.
    tool_filter: The tool filter to use for filtering tools.
    use_structured_content: Whether to use `tool_result.structured_content` when calling an
        MCP tool. Defaults to False for backwards compatibility - most MCP servers still
        include the structured content in the `tool_result.content`, and using it by
        default will cause duplicate content. You can set this to True if you know the
        server will not duplicate the structured content in the `tool_result.content`.
    max_retry_attempts: Number of times to retry failed list_tools/call_tool calls.
        Defaults to no retries.
    retry_backoff_seconds_base: The base delay, in seconds, for exponential
        backoff between retries.
    message_handler: Optional handler invoked for session messages as delivered by the
        ClientSession.
    require_approval: Approval policy for tools on this server. Accepts "always"/"never",
        a dict of tool names to those values, or an object with always/never tool lists.
    failure_error_function: Optional function used to convert MCP tool failures into
        a model-visible error message. If explicitly set to None, tool errors will be
        raised instead of converted. If left unset, the agent-level configuration (or
        SDK default) will be used.
    tool_meta_resolver: Optional callable that produces MCP request metadata (`_meta`) for
        tool calls. It is invoked by the Agents SDK before calling `call_tool`.
r  zstreamable_http: r   TN)r`   r   r  r   r9  r  s                rE   r    MCPServerStreamableHttp.__init__  sc    n 	-+I##91'A+-#91 	 	
 E0U1C0DE
+/(rD   c                R   U R                   S   U R                   R                  SS5      U R                   R                  SS5      U R                   R                  SS5      U R                   R                  SS	5      S
.nU R                   R                  S5      nU R                   R                  SS5      (       a;  [        S0 UDU=(       d    [        U R                   R                  S5      [        S.D6$ Ub  X!S'   SU R                   ;   a  U R                   S   US'   [        S0 UD6$ )r\  r   rR   NrQ   r  rn   rm   ro   T)r   rR   rQ   rn   ro   rp   r  FrS   )rp   rS   rq   r<   )r  r   r   rW   rY   r    )rd   rV   rp   s      rE   r]  &MCPServerStreamableHttp.create_streamsb  s    
 ;;u%{{y$7{{y!4 $0BF K"&++//2F"M"
  ${{/EF;;??DeLL8 %9%c=c[[__V,"Y	   +-A)*T[[ ![[0F6N$.v..rD   c                 #    [        5        IS h  vN nUR                  U R                  5       5      I S h  vN nUtp4nUR                  [        UUU R                  (       a  [        U R                  S9OS U R                  S95      I S h  vN nUR                  5       I S h  vN   U7v   S S S 5      IS h  vN   g  N N N6 N  N! , IS h  vN  (       d  f       g = f7f)Nr  r  )r   r  r]  r   r3  r
   r6  r  )rd   r,  r{   rs   r  _r+  s          rE   _isolated_client_session0MCPServerStreamableHttp._isolated_client_session{  s     !##z(<<T=P=P=RSSI'OD!&:::: d&I&IJ$($8$8	 	G $$&&&M $##S	 ' $###sy   C$C C$#C
CAC
CC
%C&	C
/C$:C;C$C
C
C
C$
C!CC!C$c                z   #    Uc  UR                  X#5      I S h  vN $ UR                  X#US9I S h  vN $  N N7fr  r  )rd   r+  r   r   r   s        rE   _call_tool_with_session/MCPServerStreamableHttp._call_tool_with_session  sB      < **9@@@&&y$&GGG AGs   ;7;9;;c                4  ^  [        U[        R                  [        -  [        R
                  -  [        R                  -  5      (       a  g[        U[        R                  5      (       a  UR                  R                  S:  $ [        U[        5      (       a1  UR                  R                  [        R                  R                  :H  $ [        U[        5      (       a;  [!        UR"                  5      =(       a    [%        U 4S jUR"                   5       5      $ g)NTi  c              3  F   >#    U  H  nTR                  U5      v   M     g 7fru   )!_should_retry_in_isolated_session)r  innerrd   s     rE   r  LMCPServerStreamableHttp._should_retry_in_isolated_session.<locals>.<genexpr>  s"      0KY%66u==>s   !F)r~   r-  r  r   rT   rm  rn  rl  rz  r{  r!   rU  codecodesREQUEST_TIMEOUTr   r   ro  all)rd   rp  s   ` rE   r*  9MCPServerStreamableHttp._should_retry_in_isolated_session  s    ""!"  ! $$%
 
 c50011<<++s22c8$$99>>U[[%@%@@@c-..' C 0KN>>0 -  rD   c                  ^ ^^^^#    T R                   mTc   e T R                  UUU UU4S j5      I S h  vN $  N! [         a*  nU(       a  T R                  U5      (       a  [        Uee S nAff = f7f)Nc                 ,   > TR                  TTT T5      $ ru   )r&  r  s   rE   r  HMCPServerStreamableHttp._call_tool_with_shared_session.<locals>.<lambda>  s    44WiTXYrD   )r+  r>  r  r*  r   )rd   r   r   r   allow_isolated_retryrp  r+  s   ````  @rE   _call_tool_with_shared_session6MCPServerStreamableHttp._call_tool_with_shared_session  st      ,,"""	66YY     	#(N(Ns(S(S9sB	s1   A4= ;= A4= 
A1%A,,A11A4c          	       #    [         R                  " U R                  UUUUS95      n [         R                  " U5      I S h  vN S4$  N! [         Ga#    [        5       n UR                  U R                  5       5      I S h  vN  nOc! [         R                   a    UR                  5       I S h  vN    e [         a)  nUR                  5       I S h  vN    [        5       UeS nAff = f  U R                  XqX#5      I S h  vN  n	U	S4UR                  5       I S h  vN    s $ ! [         R                   a    e [         a  n[        5       UeS nAff = f! UR                  5       I S h  vN    f = f[         R                   aC    UR                  5       (       d  UR                  5          UI S h  vN    e ! [         a     e f = ff = f7f)Nr5  FT)r-  create_taskr6  shieldr   r   r  r#  r  r   r  r   r&  doner   )
rd   r   r   r   r5  request_taskr,  r+  rp  r   s
             rE   _call_tool_with_isolated_retry6MCPServerStreamableHttp._call_tool_with_isolated_retry  s     **//%9	 0 
	 55u<<52 	*')J= * > >t?\?\?^ ___))  '')))  = '')))13<=	*A#'#?#?T]#dddF!4< !''))) -- $ A57S@A !'')))%% 	$$&&##%"""  ! 	s   'GA A
A 	G
A G""BBB
G'C+2B53C+C&CC&&C++G0D*DD*G!D$"G(G*EEEEE6/E2
0E66;G2F>7F:8F>=G>
GG
GGGc           	       #    U R                   (       d  [        S5      e U R                  XS9  SnSn U(       d  U R                  S:w  a  US-  nU R                  S:H  =(       d    X@R                  :  n U R	                  UUUUS9I S h  vN u  pxU(       a  U R                  S:w  a  US-  nU$  N$! [
         a~  n	US-  nU R                  S:w  a+  X@R                  :  a  U	R                  b  U	R                  U	eU	eU R                  SUS-
  -  -  n
[        R                  " U
5      I S h  vN     S n	A	OdS n	A	f[         aT    U R                  S:w  a  X@R                  :  a  e U R                  SU-  -  n
[        R                  " U
5      I S h  vN     Of = fS	nGMi  ! [        R                   a:  nUR                  R                  n[        S
U SU R                   SU 35      UeS nAf[        R                    a"  n[        S
U SU R                   S35      UeS nAf["         a  nU R%                  U5      n['        U[        R                  5      (       a5  UR                  R                  n[        S
U SU R                   SU 35      Ue['        U[        R                   5      (       a  [        S
U SU R                   S35      Ue['        U[        R(                  5      (       a  [        S
U SU R                   S35      Uee S nAff = f7f)Nr  r  r   Tr  r2   r9  r,   Fr  r  r  r  z': Connection timeout.)r+  r-   r  r4  r>  r   	__cause__r5  r-  r  r   rT   rl  rz  r{  r   rm  r   rq  r~   rn  )rd   r   r   r   retries_usedfirst_attemptr5  r   used_isolated_retryrp  r  rY  r{  r}  s                 rE   r   !MCPServerStreamableHttp.call_tool  s<     ||[\\?	...XL M$)@)@B)F A%L++r1[\D[D[5[ %18<8[8[!!-A	 9\ 9 3/F +t/F/F"/L$)!M3 3 1 A%L.."4I`I`9`==4"%--S8!	"==|VWGWAXYG!--000  1.."4I`I`9`"==LQG!--000	1
 !&; < $$ 	**00K'	{2CDII; O)],  !! 	'	{2CDII; O4 5  " 	@@CJ*e&;&;<<(11==+I;6G		{ S""-0 "" *e&8&899+I;6G		{ SI I "" *e&<&<==+I;6G		{ S* * "" %	s   LAF 5B1 
B/#B1 .L/B1 1
F;A.D4)D,*D4/F 4AFFFF FF L
15G&&L
=HL
'CLL

Lc                    U R                   $ r  r  r   s    rE   r   MCPServerStreamableHttp.name7  r	  rD   c                >    U R                   c  gU R                  5       $ )a  The MCP session ID assigned by the server, or None if not yet connected
or if the server did not issue a session ID.

The session ID is stable for the lifetime of this server instance's connection.
You can persist it and pass it back via the Mcp-Session-Id request header
(params["headers"]) on a new MCPServerStreamableHttp instance to resume
the same server-side session across process restarts or stateless workers.

Example::

    async with MCPServerStreamableHttp(params={"url": url}) as server:
        session_id = server.session_id

    # In a new worker / process:
    async with MCPServerStreamableHttp(
        params={"url": url, "headers": {"Mcp-Session-Id": session_id}}
    ) as server:
        # Resumes the same server-side session.
        ...
N)r:  r   s    rE   r   "MCPServerStreamableHttp.session_id<  s"    , '##%%rD   )r   r9  r  )r  r  r1  r   r   r  r3  r  r8  r5   r   r   r4  r  r5  r  r6  r  r   r  r   r  r   r  r  ru   )
r+  r   r   r   r   r  r   r  rh   r#   )rp  r  rh   r   )
r   r   r   r  r   r  r5  r   rh   r#   )
r   r   r   r  r   r  r5  r   rh   ztuple[CallToolResult, bool]r  r  )rh   r  )r>   r?   r@   rA   r   r  r   r]  r	   r#  r&  r*  r6  r>  r   r"  r   r   rC   rj   rk   s   @rE   r  r    s    "'78"&',"#,/4837HN9=F0-F0 F0 	F0
 )5F0  F0 !%F0  F0 %*F0 2F0 1F0 !FF0 7F0 F0P/	8/2  , '+	H	H 	H )		H
 $	H 
	H. '+	 ) $	 # 
. '+	-- )- $	- #- 
%-f '+	HH )H $	H
 
HT   & &rD   r  )NNN)rR   dict[str, str] | NonerQ   zhttpx.Timeout | NonerS   httpx.Auth | Nonerh   zhttpx.AsyncClient)r   r   rR   rJ  rQ   float | timedeltarn   rL  ro   r   rp   r3   rS   rK  rq   z(Callable[[str], StreamableHTTPTransport]rh   z(AsyncGenerator[MCPStreamTransport, None])m
__future__r   r   r-  r   syscollections.abcr   r   r   
contextlibr   r   r	   datetimer
   pathlibr   typingr   r   r   r   r   r   r   rT   version_infoexceptiongroupr   r   anyio.streams.memoryr   r   mcpr   r   r   r  r   mcp.client.sessionr   mcp.client.sser   mcp.client.streamable_httpr   r   r    mcp.shared.exceptionsr!   mcp.shared.messager"   	mcp.typesr#   r$   r%   r&   r'   r(   r)   typing_extensionsr*   r+   ro  r-   r.   r   r/   r  r0   util._typesr1   utilr3   r4   r5   r6   r7   r9   rH   RequireApprovalPolicyr   r   RequireApprovalMappingr   LocalMCPApprovalCallabler  rN   rW   rY   r   r   r   r   r   r  r   rM   tupleMCPStreamTransportABCr   r%  r  r  r  r  r  r  r<   rD   rE   <module>rg     sE   " 
   
 ? ? W W   D D  g1 % R S S 0 % 
 + -   5 "  + $ ( iu #IU #
   12 c#889 '	3	g6t	 
  (S1
	 
 	! #	# 		
 	  # 	 CL &*$("'"'!' ' 	'>U "  &*!#*0#.T"BY;,	;, #;, 	;,
 (;, ;, ,;, ;, @;, .;, ;,|Y) YT) T	 	 
! 
!.9"<=~.	0 !.9"<=~.t#	%	 L LDS,)SWW S,l9 :[0 [| 6_. _D"I "J@&9 @&rD   