o
    pkj!                     @   s  U d Z ddlZddlZzddlZW n ey   dZY nw ddlZddlmZ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 d	efd
dZe	jrhddlmZ ddlmZ ddlmZ ddlmZ ne
Ze	jed< e
Ze	jed< dZe
ed< dZe
ed< ded	ejfddZded	ejfddZ 	d,de!e ded	e!ej fddZ"dej#d	efddZ$dej#d	efd d!Z%d"e&e'e'f d	dfd#d$Z(d%ej)d	ej)fd&d'Z*ej+d(e
d)e'd	e	j,e
 fd*d+Z-dS )-z!Utils for working with MCP tools.    N)PackageNotFoundErrorversion)Any   )_common)types)_MULTI_REGIONAL_LOCATIONSreturnc                   C   s
   dt jv S )Nmcp)sysmodules r   r   U/home/djax/ivt_ai_plugin/venv/lib/python3.10/site-packages/google/genai/_mcp_utils.py_is_mcp_loaded"   s   
r   ToolClientSession)streamable_http_client)create_mcp_http_clientMcpClientSessionMcpToolr   r   toolc                 C   sX   t | dt | di }tj| j| jtjjtjdi tt | dt | di ddgdS )z.Translates an MCP tool to a Google GenAI tool.inputSchemainput_schema)json_schema)namedescription
parametersfunction_declarationsNr   )	getattrr   r   r   r   Schemafrom_json_schema
JSONSchema_filter_to_supported_schemar   r   r   r   r   mcp_to_gemini_tool0   s   r'   c              
   C   s>   t | dt | di }tj| j| jt | dt | di dgdS )z9Translates an Agent Platform tool to a Google GenAI tool.r   r   )r   r   parameters_json_schemar   )r!   r   r   r   r   r&   r   r   r   agent_platform_to_gemini_toolD   s   r)   Ftoolsis_agent_platformc                 C   s    |r	dd | D S dd | D S )z?Translates a list of MCP tools to a list of Google GenAI tools.c                 S      g | ]}t |qS r   )r)   .0r   r   r   r   
<listcomp>X       z'mcp_to_gemini_tools.<locals>.<listcomp>c                 S   r,   r   )r'   r-   r   r   r   r/   Y   r0   r   )r*   r+   r   r   r   mcp_to_gemini_toolsR   s   r1   c                 C   sz   t  sdS zddlm} ddlm} W n ty(   tddi }tddi }Y nw | D ]}t||s7t||r: dS q+dS )	zDChecks whether the list of tools contains any MCP tools or sessions.Fr   r   r   DummySessionr   	DummyToolT)r   r
   r   	mcp.typesr   ImportErrortype
isinstance)r*   _McpClientSession_McpToolr   r   r   r   has_mcp_tool_usage\   s   r:   c                 C   sX   t  sdS zddlm} W n ty   tddi }Y nw | D ]
}t||r) dS qdS )z;Checks whether the list of tools contains any MCP sessions.Fr   r   r2   r   T)r   r
   r   r5   r6   r7   )r*   r8   r   r   r   r   has_mcp_session_usagem   s   
r;   headersc                 C   sT   t  sdS ztd}W n ty   d}Y nw | dd}|d|   | d< dS )z;Sets the MCP version label in the Google API client header.Nr
   z0.0.0zx-goog-api-client z
 mcp_used/)r   r   r   getlstrip)r<   version_labelexisting_headerr   r   r   set_mcp_usage_header|   s   
rB   schemac                 C   s   t tjj }|g d d}d}d}i }|  D ]5\}}||v r*t|||< q||v r8dd |D ||< q||v rHdd | D ||< q||v rP|||< q|S )	zKFilters the schema to only include fields that are supported by JSONSchema.)additionalPropertiesanyOfoneOf$defsz$ref)itemsrD   additional_properties)rE   any_ofrF   one_of)
propertiesdefsrG   c                 S   r,   r   r%   )r.   valuer   r   r   r/      s    z/_filter_to_supported_schema.<locals>.<listcomp>c                 S   s   i | ]	\}}|t |qS r   rN   )r.   keyrO   r   r   r   
<dictcomp>   s    z/_filter_to_supported_schema.<locals>.<dictcomp>)setr   r$   model_fieldskeysupdaterH   r%   )rC   supported_fieldsschema_field_nameslist_schema_field_namesdict_schema_field_namesfiltered_schema
field_namefield_valuer   r   r   r%      s*   r%   
api_clienttoolset_namec                   s  t du r	tdd}t| drt| jdr| jj}|r/|dr'|dd }| d| }n%t| dd	}|d	kr?d
| }n|tv rLd| d| }nd| d| }|  I dH }t| dd}i }t| dru| jru| jj	rut
| jj	}d| |d< |r||d< t| tdurtj|dd}ntj|dd}z|4 I dH  t ||d4 I dH f}	|	d }
|	d }t|
|4 I dH >}| I dH  z|V  W n& ty   Y W d  I dH  W d  I dH  W d  I dH  W dS w W d  I dH  n1 I dH sw   Y  W d  I dH  n1 I dH sw   Y  W d  I dH  W dS 1 I dH s0w   Y  W dS  tyv } z2g dtddf fdd t|jdv s\t|drk | td| d |W Y d}~dS d}~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)r<   timeout)urlhttp_clientr   r   excr	   c                    s   t | dr| jD ]} | qd S t| j dt|  }t | drQ| jd urQt| jdt| jdd}t| jdt| j}t|rFt| j}|d| d| d	7 }| d S )
N
exceptionsz: responsestatus_codestatusUnknowntextz (HTTP ))	hasattrrk   r6   __name__strrl   r!   callableappend)rj   emsgrn   rp   _extract_errorserror_messagesr   r   rz      s    



z4_connect_agent_platform_mcp.<locals>._extract_errors)ExceptionGroupBaseExceptionGrouprk   z2Failed to connect to Agent Platform MCP Server at z.
Underlying errors: )r   r5   rr   r_   r`   endswithr!   r   _async_access_tokenr<   dictrB   httpx2AsyncClienthttpxr   
initializeGeneratorExitBaseExceptionr   r6   rs   
ValueError)r]   r^   r`   mcp_urlrc   tokenre   r<   ri   streamsread_streamwrite_streamsessionegr   ry   r   _connect_agent_platform_mcp   s   


,,4r   )F).__doc__
contextlibr   r   r5   r   importlib.metadatar   r   typingr   r=   r   r   _api_clientr   boolr   TYPE_CHECKINGr4   r   r   r
   r   r   mcp.client.streamable_httpr   mcp.shared._httpx_utilsr   Type__annotations__r'   r)   listr1   ToolListUnionr:   r;   r   rt   rB   
StringDictr%   asynccontextmanagerAsyncIteratorr   r   r   r   r   <module>   sZ   


$"