Skip to content

Commit e3be9af

Browse files
sararobcopybara-github
authored andcommitted
feat: Add Agent Platform MCP support to async generate_content
PiperOrigin-RevId: 925359496
1 parent bfa2a49 commit e3be9af

7 files changed

Lines changed: 414 additions & 109 deletions

File tree

‎google/genai/_adapters.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@ def __init__(
3030
self,
3131
session: "mcp.ClientSession", # type: ignore # noqa: F821
3232
list_tools_result: "mcp_types.ListToolsResult", # type: ignore
33+
is_agent_platform: bool = False,
3334
) -> None:
3435
self._mcp_session = session
3536
self._list_tools_result = list_tools_result
37+
self._is_agent_platform = is_agent_platform
3638

3739
async def call_tool(
3840
self, function_call: FunctionCall

‎google/genai/_extra_utils.py‎

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -120,18 +120,9 @@ def format_destination(
120120

121121
def find_afc_incompatible_tool_indexes(
122122
config: Optional[types.GenerateContentConfigOrDict] = None,
123+
is_agent_platform: bool = False,
123124
) -> list[int]:
124-
"""Checks if the config contains any AFC incompatible tools.
125-
126-
A `types.Tool` object that contains `function_declarations` is considered a
127-
non-AFC tool for this execution path.
128-
129-
Args:
130-
config: The GenerateContentConfig to check for incompatible tools.
131-
132-
Returns:
133-
A list of indexes of the incompatible tools in the config.
134-
"""
125+
"""Checks if the config contains any AFC incompatible tools."""
135126
if not config:
136127
return []
137128
config_model = _create_generate_content_config_model(config)
@@ -143,9 +134,11 @@ def find_afc_incompatible_tool_indexes(
143134
for index, tool in enumerate(config_model.tools):
144135
if not isinstance(tool, types.Tool):
145136
continue
146-
if tool.function_declarations:
137+
if getattr(tool, 'function_declarations', None):
147138
incompatible_tools_indexes.append(index)
148-
if tool.mcp_servers:
139+
140+
# Only mark it incompatible if it's MLDev, not Agent Platform.
141+
if getattr(tool, 'mcp_servers', None) and not is_agent_platform:
149142
incompatible_tools_indexes.append(index)
150143
return incompatible_tools_indexes
151144

@@ -383,12 +376,15 @@ async def get_function_response_parts_async(
383376
if not part.function_call:
384377
continue
385378
func_name = part.function_call.name
386-
if func_name is not None and part.function_call.args is not None:
379+
if func_name is not None:
387380
func = function_map[func_name]
388-
args = convert_number_values_for_dict_function_call_args(
381+
# Treat None as an empty dictionary for execution
382+
raw_args = (
389383
part.function_call.args
384+
if part.function_call.args is not None
385+
else {}
390386
)
391-
func_response: _common.StringDict
387+
args = convert_number_values_for_dict_function_call_args(raw_args)
392388
try:
393389
if isinstance(func, McpToGenAiToolAdapter):
394390
mcp_tool_response = await func.call_tool(
@@ -409,7 +405,7 @@ async def get_function_response_parts_async(
409405
)
410406
}
411407
except Exception as e: # pylint: disable=broad-except
412-
func_response = {'error': str(e)}
408+
func_response = {'error': str(e)} # type: ignore[dict-item]
413409
func_response_part = types.Part.from_function_response(
414410
name=func_name, response=func_response
415411
)
@@ -551,6 +547,7 @@ def parse_config_for_mcp_usage(
551547

552548
async def parse_config_for_mcp_sessions(
553549
config: Optional[types.GenerateContentConfigOrDict] = None,
550+
is_agent_platform: bool = False,
554551
) -> tuple[
555552
Optional[types.GenerateContentConfig],
556553
dict[str, McpToGenAiToolAdapter],
@@ -571,7 +568,7 @@ async def parse_config_for_mcp_sessions(
571568
for tool in parsed_config.tools:
572569
if McpClientSession is not None and isinstance(tool, McpClientSession):
573570
mcp_to_genai_tool_adapter = McpToGenAiToolAdapter(
574-
tool, await tool.list_tools()
571+
tool, await tool.list_tools(), is_agent_platform=is_agent_platform
575572
)
576573
# Extend the config with the MCP session tools converted to GenAI tools.
577574
parsed_config_copy.tools.extend(mcp_to_genai_tool_adapter.tools)
@@ -677,3 +674,19 @@ def prepare_resumable_upload(
677674
http_options.headers = {}
678675
http_options.headers['X-Goog-Upload-File-Name'] = os.path.basename(file)
679676
return http_options, size_bytes, mime_type
677+
678+
679+
def has_agent_platform_mcp_servers(
680+
config: Optional[types.GenerateContentConfigOrDict] = None,
681+
) -> bool:
682+
"""Checks whether the configuration contains any MCP server requests."""
683+
if not config:
684+
return False
685+
config_model = _create_generate_content_config_model(config)
686+
if not config_model.tools:
687+
return False
688+
689+
for tool in config_model.tools:
690+
if getattr(tool, 'mcp_servers', None):
691+
return True
692+
return False

‎google/genai/_live_converters.py‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1523,6 +1523,26 @@ def _LiveServerMessage_from_vertex(
15231523
return to_object
15241524

15251525

1526+
def _McpServer_to_vertex(
1527+
from_object: Union[dict[str, Any], object],
1528+
parent_object: Optional[dict[str, Any]] = None,
1529+
) -> dict[str, Any]:
1530+
to_object: dict[str, Any] = {}
1531+
if getv(from_object, ['name']) is not None:
1532+
raise ValueError(
1533+
'name parameter is only supported in Gemini Developer API mode, not in'
1534+
' Gemini Enterprise Agent Platform mode.'
1535+
)
1536+
1537+
if getv(from_object, ['streamable_http_transport']) is not None:
1538+
raise ValueError(
1539+
'streamable_http_transport parameter is only supported in Gemini'
1540+
' Developer API mode, not in Gemini Enterprise Agent Platform mode.'
1541+
)
1542+
1543+
return to_object
1544+
1545+
15261546
def _MultiSpeakerVoiceConfig_to_vertex(
15271547
from_object: Union[dict[str, Any], object],
15281548
parent_object: Optional[dict[str, Any]] = None,
@@ -1941,9 +1961,13 @@ def _Tool_to_vertex(
19411961
setv(to_object, ['urlContext'], getv(from_object, ['url_context']))
19421962

19431963
if getv(from_object, ['mcp_servers']) is not None:
1944-
raise ValueError(
1945-
'mcp_servers parameter is only supported in Gemini Developer API mode,'
1946-
' not in Gemini Enterprise Agent Platform mode.'
1964+
setv(
1965+
to_object,
1966+
['mcpServers'],
1967+
[
1968+
_McpServer_to_vertex(item, to_object)
1969+
for item in getv(from_object, ['mcp_servers'])
1970+
],
19471971
)
19481972

19491973
return to_object

‎google/genai/_mcp_utils.py‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -225,7 +225,15 @@ def _extract_errors(exc: Any) -> None:
225225
else:
226226
msg = f"{type(exc).__name__}: {str(exc)}"
227227
if hasattr(exc, "response") and exc.response is not None:
228-
msg += f" (HTTP {exc.response.status_code}: {exc.response.text})"
228+
status = getattr(
229+
exc.response,
230+
"status_code",
231+
getattr(exc.response, "status", "Unknown"),
232+
)
233+
text = getattr(exc.response, "text", str(exc.response))
234+
if callable(text):
235+
text = str(exc.response)
236+
msg += f" (HTTP {status}: {text})"
229237
error_messages.append(msg)
230238

231239
if type(eg).__name__ in ("ExceptionGroup", "BaseExceptionGroup") or hasattr(

‎google/genai/caches.py‎

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -665,6 +665,26 @@ def _ListCachedContentsResponse_from_vertex(
665665
return to_object
666666

667667

668+
def _McpServer_to_vertex(
669+
from_object: Union[dict[str, Any], object],
670+
parent_object: Optional[dict[str, Any]] = None,
671+
) -> dict[str, Any]:
672+
to_object: dict[str, Any] = {}
673+
if getv(from_object, ['name']) is not None:
674+
raise ValueError(
675+
'name parameter is only supported in Gemini Developer API mode, not in'
676+
' Gemini Enterprise Agent Platform mode.'
677+
)
678+
679+
if getv(from_object, ['streamable_http_transport']) is not None:
680+
raise ValueError(
681+
'streamable_http_transport parameter is only supported in Gemini'
682+
' Developer API mode, not in Gemini Enterprise Agent Platform mode.'
683+
)
684+
685+
return to_object
686+
687+
668688
def _Part_to_mldev(
669689
from_object: Union[dict[str, Any], object],
670690
parent_object: Optional[dict[str, Any]] = None,
@@ -1009,9 +1029,13 @@ def _Tool_to_vertex(
10091029
setv(to_object, ['urlContext'], getv(from_object, ['url_context']))
10101030

10111031
if getv(from_object, ['mcp_servers']) is not None:
1012-
raise ValueError(
1013-
'mcp_servers parameter is only supported in Gemini Developer API mode,'
1014-
' not in Gemini Enterprise Agent Platform mode.'
1032+
setv(
1033+
to_object,
1034+
['mcpServers'],
1035+
[
1036+
_McpServer_to_vertex(item, to_object)
1037+
for item in getv(from_object, ['mcp_servers'])
1038+
],
10151039
)
10161040

10171041
return to_object

0 commit comments

Comments
 (0)