diff --git a/google/genai/_extra_utils.py b/google/genai/_extra_utils.py index 3ee695c59..5bbfb617f 100644 --- a/google/genai/_extra_utils.py +++ b/google/genai/_extra_utils.py @@ -602,6 +602,23 @@ def should_append_afc_history( return not config_model.automatic_function_calling.ignore_call_history +def deep_copy_config_except_tools( + config: types.GenerateContentConfig, +) -> types.GenerateContentConfig: + """Deep-copies a config, but keeps its `tools` list instead of deep-copying it. + + `model_copy` deep-copies before it applies `update`, so a live MCP + `ClientSession` in `tools` can't be deep-copied. Clear `tools` with a + shallow copy first, deep-copy the rest, then give the copy its own list. + """ + copied_config = config.model_copy(update={'tools': None}).model_copy( + deep=True + ) + if config.tools is not None: + copied_config.tools = list(config.tools) + return copied_config + + def parse_config_for_mcp_usage( config: Optional[types.GenerateContentConfigOrDict] = None, ) -> Optional[types.GenerateContentConfig]: diff --git a/google/genai/chats.py b/google/genai/chats.py index 5dd6c3503..6f0234339 100644 --- a/google/genai/chats.py +++ b/google/genai/chats.py @@ -707,7 +707,7 @@ async def send_message( elif isinstance(method_config, dict): parsed_config = types.GenerateContentConfig(**method_config) else: - parsed_config = method_config.model_copy(deep=True) + parsed_config = _extra_utils.deep_copy_config_except_tools(method_config) if incompatible_tools_indexes: _extra_utils.log_afc_incompatible_tools_warning( diff --git a/google/genai/models.py b/google/genai/models.py index 6ab68807b..3826ab19d 100644 --- a/google/genai/models.py +++ b/google/genai/models.py @@ -8360,7 +8360,7 @@ async def generate_content( elif isinstance(config, dict): parsed_config = types.GenerateContentConfig(**config) else: - parsed_config = config.model_copy(deep=True) + parsed_config = _extra_utils.deep_copy_config_except_tools(config) # Use AsyncExitStack to keep MCP connections alive across the entire AFC loop async with contextlib.AsyncExitStack() as stack: @@ -8604,7 +8604,7 @@ async def generate_content_stream( elif isinstance(config, dict): parsed_config = types.GenerateContentConfig(**config) else: - parsed_config = config.model_copy(deep=True) + parsed_config = _extra_utils.deep_copy_config_except_tools(config) incompatible_tools_indexes = ( _extra_utils.find_afc_incompatible_tool_indexes( diff --git a/google/genai/tests/models/test_generate_content_mcp.py b/google/genai/tests/models/test_generate_content_mcp.py index 87f959e34..6c6b12513 100644 --- a/google/genai/tests/models/test_generate_content_mcp.py +++ b/google/genai/tests/models/test_generate_content_mcp.py @@ -13,8 +13,10 @@ # limitations under the License. # +import asyncio import sys from typing import Any +from unittest import mock import pytest from ... import _transformers as t from ... import errors @@ -343,3 +345,104 @@ async def list_tools(self): with pytest.raises(errors.UnsupportedFunctionError): for chunk in response: pass + + +class _LiveMcpClientSession(McpClientSession): + """Holds an asyncio.Future, like a connected session, so deepcopy fails.""" + + def __init__(self): + self._read_stream = None + self._write_stream = None + self._pending_response = asyncio.get_running_loop().create_future() + + async def list_tools(self): + return mcp_types.ListToolsResult( + tools=[ + mcp_types.Tool( + name='get_weather', + description='Get the weather in a city.', + inputSchema={ + 'type': 'object', + 'properties': {'location': {'type': 'string'}}, + }, + ) + ] + ) + + +def _live_session_config(session): + return types.GenerateContentConfig( + temperature=0, + tools=[session], + http_options=types.HttpOptions(headers={'x-custom-header': 'value'}), + ) + + +def _assert_session_converted_and_config_unchanged( + mock_generate, config, session +): + """Checks the request got the session's tools and the config is intact.""" + mock_generate.assert_called_once() + sent_tools = mock_generate.call_args.kwargs['config'].tools + assert len(sent_tools) == 1 + assert [ + declaration.name for declaration in sent_tools[0].function_declarations + ] == ['get_weather'] + assert len(config.tools) == 1 + assert config.tools[0] is session + assert config.http_options.headers == {'x-custom-header': 'value'} + + +@pytest.mark.asyncio +async def test_mcp_session_in_config_object_async(client): + """A live session in a GenerateContentConfig is converted, not deep-copied. + + The caller's config keeps its tools and headers. + """ + session = _LiveMcpClientSession() + config = _live_session_config(session) + + # Patch the client's own class, which is private.models.AsyncModels in + # private SDK runs. + with mock.patch.object( + type(client.aio.models), + '_generate_content', + return_value=types.GenerateContentResponse(), + ) as mock_generate: + await client.aio.models.generate_content( + model='gemini-2.5-flash', + contents='What is the weather in Boston?', + config=config, + ) + + _assert_session_converted_and_config_unchanged(mock_generate, config, session) + + +@pytest.mark.asyncio +async def test_mcp_session_in_config_object_stream_async(client): + """The streaming variant also converts a live session without deep-copying. + + The caller's config keeps its tools and headers. + """ + session = _LiveMcpClientSession() + config = _live_session_config(session) + + async def mock_stream(): + yield types.GenerateContentResponse() + + with mock.patch.object( + type(client.aio.models), + '_generate_content_stream', + side_effect=[mock_stream()], + ) as mock_generate_stream: + response = await client.aio.models.generate_content_stream( + model='gemini-2.5-flash', + contents='What is the weather in Boston?', + config=config, + ) + async for _ in response: + pass + + _assert_session_converted_and_config_unchanged( + mock_generate_stream, config, session + )