
    R-jk                        U d Z ddlZddlZddlmZmZ ddlZddlmZ ddlZ	ddl
mZ ddlmZ ddlmZ dd	lmZ ej"                  rdd
lmZ ddlmZ ddlmZ ddlmZ nIeZej8                  ed<   eZej8                  ed<   dZeed<   dZeed<   	 dd
lmZ ddlmZ ddlmZ ddlmZ dedej&                  fdZdedej&                  fdZ 	 d"de!e   de"de!ej&                     fdZ#dejH                  de"fdZ%dejH                  de"fdZ&de'e(e(f   ddfdZ)dejT                  dejT                  fdZ+ejX                  ded e(dejZ                  e   fd!       Z.y# e$ r dZdZdZdZY w xY w)#z!Utils for working with MCP tools.    N)PackageNotFoundErrorversion)Any)Request   )_common)types)_MULTI_REGIONAL_LOCATIONS)Tool)ClientSession)streamable_http_client)create_mcp_http_clientMcpClientSessionMcpToolr   r   toolreturnc                     t        j                  | j                  | j                  t         j                  j                  t        j                  di t        | j                              dg      S )z.Translates an MCP tool to a Google GenAI tool.)json_schema)namedescription
parametersfunction_declarations )	r	   r   r   r   Schemafrom_json_schema
JSONSchema_filter_to_supported_schemainputSchemar   s    e/Users/jameslopez/projects/TradingBot25/.venv/lib/python3.12/site-packages/google/genai/_mcp_utils.pymcp_to_gemini_toolr"   6   se    	))))55** /0@0@A 6  	

 
    c                 t    t        j                  | j                  | j                  | j                  dg      S )z9Translates an Agent Platform tool to a Google GenAI tool.)r   r   parameters_json_schemar   )r	   r   r   r   r   r    s    r!   agent_platform_to_gemini_toolr&   E   s8    	 ii!--(,(8(8
 r#   toolsis_agent_platformc                 ~    |r| D cg c]  }t        |       c}S | D cg c]  }t        |       c}S c c}w c c}w )z?Translates a list of MCP tools to a list of Google GenAI tools.)r&   r"   )r'   r(   r   s      r!   mcp_to_gemini_toolsr*   R   sF    
 <ABED)$/EBB/4	5ut
T
"u	55 C	5s   5:c                 d    t         y| D ]$  }t        |t              st        |t               s$ y y)zDChecks whether the list of tools contains any MCP tools or sessions.FT)r   
isinstancer   r'   r   s     r!   has_mcp_tool_usager.   \   s1    d$ Jt5E$F  
r#   c                 D    t         y| D ]  }t        |t               s y y)z;Checks whether the list of tools contains any MCP sessions.FT)r   r,   r-   s     r!   has_mcp_session_usager0   f   s(    d$()  
r#   headersc                     t         y	 t        d      }| j                  dd      }|d| z   j	                         | d<   y# t        $ r d}Y 9w xY w)z;Sets the MCP version label in the Google API client header.Nmcpz0.0.0zx-goog-api-client z
 mcp_used/)r   r   r   getlstrip)r1   version_labelexisting_headers      r!   set_mcp_usage_headerr9   p   sc    
ENM KK 3R8/*]O44
FH 

 
 Ms   A   AAschemac           	         t        t        j                  j                  j	                               }|j                  g d       d}d}d}i }| j                         D ]x  \  }}||v rt        |      ||<   ||v r|D cg c]  }t        |       c}||<   :||v r1|j                         D 	ci c]  \  }	}|	t        |       c}}	||<   o||v st|||<   z |S c c}w c c}}	w )zKFilters the schema to only include fields that are supported by JSONSchema.)additionalPropertiesanyOfoneOf$defsz$ref)itemsr<   additional_properties)r=   any_ofr>   one_of)
propertiesdefsr?   )setr	   r   model_fieldskeysupdater@   r   )
r:   supported_fieldsschema_field_nameslist_schema_field_namesdict_schema_field_namesfiltered_schema
field_namefield_valuevaluekeys
             r!   r   r   ~   s     #5#3#3#@#@#E#E#GH  
 C;$&/!'j+''$?$Loj!	.	.:E%:E
%e
,+%oj! 
.	. (--/%/jc5 *51
1/%oj! 
'	'$/oj! "0 
%%s   >C.C
api_clienttoolset_namec           	       K   t         t        d      d}t        | d      r,t        | j                  d      r| j                  j                  }|r|j                  d      r|dd }| d| }n1t        | dd	      }|d	k(  rd
| }n|t        v r	d| d| }nd| d| }| j                          d{   }t        | dd      }i }t        | d      rA| j                  r5| j                  j                  rt        | j                  j                        }d| |d<   |r||d<   t        |       t        j                  |d      }	 |4 d{    t        ||      4 d{   }	|	\  }
}}t        |
|      4 d{   }|j                          d{    	 | ddd      d{    ddd      d{    ddd      d{    y7 7 7 s7 Z7 D# t         $ r6 Y ddd      d{  7   ddd      d{  7   ddd      d{  7   yw xY w7 r# 1 d{  7  sw Y   xY w7 y# 1 d{  7  sw Y   xY w7 # 1 d{  7  sw Y   yxY w# t"        $ rX}g dt$        ddffdt'        |      j(                  dv st        |d      r |       t+        d| d       |Y d}~yd}~ww xY ww)zGInternal helper to manage the Agent Platform MCP lifecycle per request.Nz@The 'mcp' package is required to use Agent Platform MCP servers._http_optionsbase_url/z/mcp/locationglobalz&https://aiplatform.googleapis.com/mcp/zhttps://aiplatform.z.rep.googleapis.com/mcp/zhttps://z-aiplatform.googleapis.com/mcp/projectzBearer AuthorizationzX-Goog-User-Project)r1   timeout)urlhttp_clientexcr   c           	         t        | d      r| j                  D ]
  } |        y t        |       j                   dt	        |        }t        | d      r| j
                  t        | j
                  dt        | j
                  dd            }t        | j
                  dt	        | j
                              }t        |      rt	        | j
                        }|d| d| d	z  }j                  |       y )
N
exceptionsz: responsestatus_codestatusUnknowntextz (HTTP ))	hasattrrc   type__name__strrd   getattrcallableappend)ra   emsgrf   rh   _extract_errorserror_messagess        r!   rs   z4_connect_agent_platform_mcp.<locals>._extract_errors   s    	l	#A
!
   c##$Bs3xj13
#(@llcllHi8&
 vs3<</@A$d^s||$D
76("TF!,
,#c"r#   )ExceptionGroupBaseExceptionGrouprc   z2Failed to connect to Agent Platform MCP Server at z.
Underlying errors: )r   ImportErrorrj   rV   rW   endswithrn   r
   _async_access_tokenr1   dictr9   httpxAsyncClientr   
initializeGeneratorExitBaseExceptionr   rk   rl   
ValueError)rS   rT   rW   mcp_urlrZ   tokenr\   r1   r`   streamsread_streamwrite_stream_sessionegrs   rt   s                  @@r!   _connect_agent_platform_mcpr      s     #
H  (Z)gj6N6NPZ.[''00H#2h
%~.Gz:x8H88Gg	.	.%hZ/G~Vg8*$CL>Rg..0
0%J	40''Z)j.F.F:KcKcKkKk:++334G&ug.'/%,G!"w!!'4@++{'; '.$\1#K>>'""$
$
$M ?>	  {{! 1   ?
$   ?>>	   {{	 ?>>>	    {{{ 
 N#S #T #& BxDD
LI b>wi H  ./1 	I/s  B0K4G5BKI$ GI$ I#G$I'H8>G
?H8H!G
H!G!H8,H-H81I<H6=II$ II$ KI$ IH8H!	H	&H!'H82G53H88IHI	I$ HI$ KH	H!H8!H3'H*(H3/H86I8I
	>I?I
	II$ I!II!I$  K!I$ $	K-AK ;K KK)F)/__doc__
contextlibr{   importlib.metadatar   r   typingr   google.authgooglegoogle.auth.transport.requestsr   r4   r   r	   _api_clientr
   TYPE_CHECKING	mcp.typesr   r   r3   r   r   mcp.client.streamable_httpr   mcp.shared._httpx_utilsr   Type__annotations__rw   r"   r&   listboolr*   ToolListUnionr.   r0   rz   rm   r9   
StringDictr   asynccontextmanagerAsyncIteratorr   r   r#   r!   <module>r      s    (   <    2   2	'3?<"%FKK%'6;; $#$ $#$	")5A>W  
 
EJJ 
 $6=66 
%**6e11 d !4!4  $sCx. T """J R# RS RVMaMabeMf R  Rk 
 "G!!	"s   E E,+E,