@devries-cameron20 / composio Mirror · read-only / commits / d2ac3cf17
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 07:15 UTC

fix(gemini): run `handle_response` calls for the user the caller passes (#5120)

This PR: - Closes #5112 - adds keyword-only `user_id=` and `session=` to `GeminiProvider.handle_response(response, ...)`, matching the names of `GoogleProvider.handle_response`; each call runs through the executor that `tools.get(user_id=...)` or `session.tools()` installed for that target, so get-time modifiers and the session's local custom-tool routing for `COMPOSIO_MULTI_EXECUTE_TOOL` apply as they do for AFC - allows a bare `handle_response(response)` only while the provider has wrapped tools for a single user or session; after that it raises `ValueError` and executes nothing - picks every executor and its schema under a lock before running any call, so a concurrent fetch cannot switch the user partway through a response - adds `bind_execution_target` / `get_execution_target` to `composio.core.provider`: `Tools._wrap_execute_tool` and `ToolRouterSession.tools()` record their user ID or session on the execute function they pass to agentic providers - updates the `composio-gemini` README, the Google provider docs page, and adds a changelog entry ## Context The issue lists three options. This takes option 2 (the `GoogleProvider` shape) and also accepts `session=`. `response` stays the first positional argument so existing `handle_response(response)` calls keep working in single-user processes. Behavior notes for reviewers: - Each wrapped tool's executor and argument schema are kept together per user ID or session for the provider's lifetime (one small dict per distinct user or session), so a call is validated with the schema, including schema modifiers, of the same fetch whose executor runs it. - `handle_response(user_id=...)` for a user the provider never wrapped tools for raises `ValueError` rather than guessing. - `composio-gemini` now imports `get_execution_target` from core, so it needs a `composio` release that includes this PR (both ship together). - Same gap elsewhere, not fixed here: `GoogleProvider.handle_response(session=...)` and the other non-agentic session helpers go through `BaseProvider.execute_tool_for_target` → `session.execute`, which sends a `COMPOSIO_MULTI_EXECUTE_TOOL` batch to the backend without running local custom tools in process. TypeScript: there is no TS Gemini provider. `@composio/google`'s `executeToolCall` already takes `userId` or a session explicitly. ## Verification Run from `python/` in a venv with `composio`, `composio-gemini` and `composio-google` installed editable (like CI); `composio.__file__` points at this checkout. - Issue repro script: before the fix the call ran as `bob`; now the bare call raises `ValueError` and `user_id="alice"` runs as `alice`. - `TestHandleResponseUser` in `tests/test_gemini_provider.py` (through the real `Composio.tools.get()`, API mocked): explicit user, same-slug and disjoint-slug ambiguity, single user without a user, unknown user, fetch for another user during execution, a schema modifier on another user's fetch of the same tool not affecting the caller's validation, and `session=` using the session's own executor rather than `session.execute`. `tests/test_tool_router.py` checks `session.tools()` records the session on its routing executor. - `pytest tests`: 2501 passed, 136 skipped. - `ruff --config config/ruff.toml check` on `composio/ providers/ tests/` and `format --check` on the touched files: clean. - `mypy --config-file config/mypy.ini composio/ providers/gemini tests/test_gemini_provider.py tests/test_tool_router.py`: no errors in touched files; one existing error in `composio/utils/schema_converter.py:813`, which this PR does not touch.

Alberto Schiabel committed Oct 28, 2026 at 10:37 UTC d2ac3cf17322f16f8cfd58bc15efd2994e17a60c
10 files changed +413 -38
docs/content/changelog/10-27-26-gemini-handle-response-user.mdx new
+33
@@ -0,0 +1,33 @@
1 +---
2 +title: 'Gemini Manual Function Calling Runs as the Right User'
3 +description: 'The Python Gemini provider no longer executes a manually handled function call as whichever user fetched the tools last'
4 +date: '2026-10-27'
5 +---
6 +
7 +With Automatic Function Calling turned off, `GeminiProvider.handle_response(response)` in `composio-gemini` executed each function call with the executor stored by the latest `tools.get()` or `session.tools()` for that tool. When one `Composio` instance served several users, a call from Alice's conversation could run with Bob's `user_id` and connected account, and Bob's result went back into Alice's chat. The callables used by Automatic Function Calling were not affected.
8 +
9 +### Bug Fixes
10 +
11 +- **Gemini** (`composio-gemini`): `handle_response` accepts `user_id=` or `session=`, with the same names as `GoogleProvider.handle_response` in `composio-google`. Each call runs exactly as the tool fetched for that user or Tool Router session would: validated against the schema from that fetch (including its schema modifiers), with the modifiers given to `tools.get()`, and through the session's routing, so local custom tools in a `COMPOSIO_MULTI_EXECUTE_TOOL` batch run in process.
12 +- Without a user or session, `handle_response` keeps working for a process that has fetched tools for a single user or session. Once the provider has wrapped tools for more than one, it raises a `ValueError` instead of picking one, and executes nothing.
13 +
14 +**Before:**
15 +
16 +```python
17 +alice_tools = composio.tools.get(user_id="alice", tools=["GMAIL_FETCH_EMAILS"])
18 +bob_tools = composio.tools.get(user_id="bob", tools=["GMAIL_FETCH_EMAILS"])
19 +
20 +# response comes from Alice's conversation
21 +composio.provider.handle_response(response)
22 +# The tool executed as bob
23 +```
24 +
25 +**After:**
26 +
27 +```python
28 +composio.provider.handle_response(response, user_id="alice")
29 +# The tool executes as alice
30 +
31 +composio.provider.handle_response(response)
32 +# ValueError: tools were wrapped for more than one user or session
33 +```
docs/content/docs/providers/google.mdx
+1 -1
@@ -17,7 +17,7 @@ In Python, the Gemini provider (`composio_gemini`) wraps Composio tools as typed
17
18 Object arguments that declare no properties preserve arbitrary nested keys in both providers. The TypeScript provider also adds `type: "object"` to schema nodes that declare `properties` without a type, which is the shape Gemini expects for object schemas.
19
20 -If you use the Python `composio_google` provider with a manual Gemini loop, pass the Session to `composio.provider.execute_tool_call(session=session, function_call=function_call)` or `composio.provider.handle_response(session=session, response=response)`. Both helpers execute through that Session. Calls with `user_id` use direct execution for tools fetched with `tools.get()`. The `composio_gemini` callables in the example below already carry the Session.
20 +If you use the Python `composio_google` provider with a manual Gemini loop, pass the Session to `composio.provider.execute_tool_call(session=session, function_call=function_call)` or `composio.provider.handle_response(session=session, response=response)`. Both helpers execute through that Session. Calls with `user_id` use direct execution for tools fetched with `tools.get()`. The `composio_gemini` callables in the example below already carry the Session. If you turn off Automatic Function Calling in `composio_gemini`, pass the Session the same way: `composio.provider.handle_response(response, session=session)`.
21
22 <Steps>
23 <Step>
python/composio/core/models/tool_router_session.py
+6 -2
@@ -439,7 +439,11 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
439 in-process, remote tools are sent to the backend.
440 """
441 from composio.core.models.tools import Tools as ToolsModel
442 - from composio.core.provider import AgenticProvider, NonAgenticProvider
442 + from composio.core.provider import (
443 + AgenticProvider,
444 + NonAgenticProvider,
445 + bind_execution_target,
446 + )
447
448 if self._provider is None:
449 raise ValueError(
@@ -490,7 +494,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
494 TToolCollection,
495 t.cast(AgenticProvider[TTool, TToolCollection], self._provider).wrap_tools(
496 tools=router_tools,
493 - execute_tool=execute_fn,
497 + execute_tool=bind_execution_target(execute_fn, self),
498 ),
499 )
500
python/composio/core/models/tools.py
+9 -2
@@ -41,7 +41,11 @@ from composio.core.models.inline_custom_tools_payload import (
41 inline_custom_tools_execute_experimental,
42 )
43 from composio.core.provider import TTool, TToolCollection
44 -from composio.core.provider.agentic import AgenticProvider, AgenticProviderExecuteFn
44 +from composio.core.provider.agentic import (
45 + AgenticProvider,
46 + AgenticProviderExecuteFn,
47 + bind_execution_target,
48 +)
49 from composio.core.provider.base import BaseProvider, ExecuteToolFn
50 from composio.core.provider.none_agentic import NonAgenticProvider
51 from composio.core.types import ToolkitVersionParam
@@ -670,7 +674,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
674 user_id: t.Optional[str] = None,
675 ) -> AgenticProviderExecuteFn:
676 """Wrap the execute tool function"""
673 - return t.cast(
677 + execute_tool = t.cast(
678 AgenticProviderExecuteFn,
679 functools.partial(
680 self.execute,
@@ -681,6 +685,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
685 dangerously_skip_version_check=True,
686 ),
687 )
688 + if user_id is None:
689 + return execute_tool
690 + return bind_execution_target(execute_tool, user_id)
691
692 def _wrap_execute_tool_for_tool_router(
693 self,
python/composio/core/provider/__init__.py
+8 -1
@@ -1,6 +1,11 @@
1 from __future__ import annotations
2
3 -from .agentic import AgenticProvider, AgenticProviderExecuteFn
3 +from .agentic import (
4 + AgenticProvider,
5 + AgenticProviderExecuteFn,
6 + bind_execution_target,
7 + get_execution_target,
8 +)
9 from .base import TTool, TToolCollection, ToolCallExecutionTarget, ToolCallSession
10 from .none_agentic import NonAgenticProvider
11
@@ -12,4 +17,6 @@ __all__ = [
17 "AgenticProvider",
18 "NonAgenticProvider",
19 "AgenticProviderExecuteFn",
20 + "bind_execution_target",
21 + "get_execution_target",
22 ]
python/composio/core/provider/agentic.py
+32 -1
@@ -3,7 +3,12 @@ from __future__ import annotations
3 import typing as t
4
5 from composio.client.types import Tool
6 -from composio.core.provider.base import BaseProvider, TTool, TToolCollection
6 +from composio.core.provider.base import (
7 + BaseProvider,
8 + ToolCallExecutionTarget,
9 + TTool,
10 + TToolCollection,
11 +)
12
13
14 class AgenticProviderExecuteFn(t.Protocol):
@@ -22,6 +27,32 @@ class AgenticProviderExecuteFn(t.Protocol):
27 ...
28
29
30 +_EXECUTION_TARGET_ATTR = "__composio_execution_target__"
31 +
32 +TExecuteFn = t.TypeVar("TExecuteFn", bound=t.Callable[..., t.Any])
33 +
34 +
35 +def bind_execution_target(
36 + execute_tool: TExecuteFn,
37 + target: ToolCallExecutionTarget,
38 +) -> TExecuteFn:
39 + """Record the user ID or Tool Router session ``execute_tool`` runs as.
40 +
41 + A provider that executes calls outside the wrapped tools, such as Gemini's
42 + ``handle_response``, reads it back with :func:`get_execution_target` to
43 + pick the executor that belongs to a caller's ``user_id`` or ``session``.
44 + """
45 + setattr(execute_tool, _EXECUTION_TARGET_ATTR, target)
46 + return execute_tool
47 +
48 +
49 +def get_execution_target(
50 + execute_tool: t.Callable[..., t.Any],
51 +) -> t.Optional[ToolCallExecutionTarget]:
52 + """Return the target recorded by :func:`bind_execution_target`, if any."""
53 + return getattr(execute_tool, _EXECUTION_TARGET_ATTR, None)
54 +
55 +
56 class AgenticProvider(BaseProvider[TTool, TToolCollection]):
57 """
58 Base class for all agentic providers. This class is not meant to be used
python/providers/gemini/README.md
+9 -1
@@ -36,7 +36,15 @@ response = chat.send_message(
36 print(response.text)
37 ```
38
39 -If you disable Automatic Function Calling and handle function calls yourself, `composio.provider.handle_response(response)` executes the function calls in a Gemini response and returns `Part` objects ready to send back.
39 +If you disable Automatic Function Calling and handle function calls yourself, `composio.provider.handle_response(response, session=session)` executes the function calls in a Gemini response the way that session's tools would, and returns `Part` objects ready to send back. For tools fetched with `composio.tools.get(user_id=...)`, pass `user_id=` instead:
40 +
41 +```python
42 +function_responses, executed = composio.provider.handle_response(
43 + response, user_id="user_123"
44 +)
45 +```
46 +
47 +A Gemini response does not record which user it belongs to, so pass the user or session whenever one `Composio` instance serves more than one. Without one, `handle_response` raises a `ValueError` once the provider has wrapped tools for more than one user or session.
48
49 ## composio-gemini vs composio-google
50
python/providers/gemini/composio_gemini/provider.py
+115 -19
@@ -5,6 +5,7 @@ Calling (AFC). The SDK can introspect the callable's signature to derive
5 FunctionDeclaration schemas and auto-execute tool calls in the chat loop.
6 """
7
8 +import threading
9 import types as pytypes
10 import typing as t
11 from inspect import Parameter, Signature
@@ -12,7 +13,12 @@ from inspect import Parameter, Signature
13 from pydantic import BaseModel
14
15 from composio.client.types import Tool
15 -from composio.core.provider import AgenticProvider
16 +from composio.core.provider import (
17 + AgenticProvider,
18 + ToolCallExecutionTarget,
19 + ToolCallSession,
20 + get_execution_target,
21 +)
22 from composio.core.provider.agentic import AgenticProviderExecuteFn
23 from composio.utils.shared import (
24 ToolSchemaAliases,
@@ -107,6 +113,30 @@ def _afc_annotation(annotation: t.Any, schema: t.Any = None) -> t.Any:
113 return annotation
114
115
116 +def _execution_context(execute_tool: AgenticProviderExecuteFn) -> object:
117 + """Identify who a wrapped tool executes as.
118 +
119 + ``tools.get(user_id=...)`` and ``session.tools()`` record their user ID or
120 + session on the execute function, so two fetches for the same user share a
121 + context. Any other execute function is its own context.
122 + """
123 + target = get_execution_target(execute_tool)
124 + return execute_tool if target is None else target
125 +
126 +
127 +class _WrappedTool(t.NamedTuple):
128 + """How one fetch wrapped a tool: the argument schema it built and the
129 + execute function of the user or session it was fetched for.
130 +
131 + They are stored together because schema modifiers can differ per fetch, so
132 + a call must be validated with the schema of the fetch whose executor runs it.
133 + """
134 +
135 + execute_tool: AgenticProviderExecuteFn
136 + aliases: ToolSchemaAliases
137 + args_schema: t.Type[BaseModel]
138 +
139 +
140 def _process_execution_result(result: t.Any) -> t.Dict:
141 """Process a tool execution result into a dict suitable for Gemini function responses."""
142 if not isinstance(result, dict):
@@ -138,10 +168,13 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
168
169 def __init__(self, **kwargs: t.Any):
170 super().__init__(**kwargs)
141 - self._executors: t.Dict[
142 - str,
143 - t.Tuple[AgenticProviderExecuteFn, ToolSchemaAliases, t.Type[BaseModel]],
144 - ] = {}
171 + # Guards the registries below: tools can be fetched on one thread while
172 + # ``handle_response`` reads them on another.
173 + self._lock = threading.Lock()
174 + # Wrapped tool per slug, for each user ID or session the tools were
175 + # fetched for, so ``handle_response`` runs a call as the caller's user,
176 + # with the caller's schema, rather than whoever fetched the tool last.
177 + self._wrapped_tools: t.Dict[object, t.Dict[str, _WrappedTool]] = {}
178
179 def wrap_tool(
180 self,
@@ -161,7 +194,11 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
194 # validation model needs them: without a default every optional field
195 # would be required.
196 args_schema = json_schema_to_model(aliases.schema, skip_default=False)
164 - self._executors[tool.slug] = (execute_tool, aliases, args_schema)
197 + context = _execution_context(execute_tool)
198 + with self._lock:
199 + self._wrapped_tools.setdefault(context, {})[tool.slug] = _WrappedTool(
200 + execute_tool, aliases, args_schema
201 + )
202
203 def function(**kwargs: t.Any) -> t.Dict:
204 """Composio tool execution wrapper."""
@@ -222,7 +259,13 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
259
260 # --- Backward compatibility: manual function calling ---
261
225 - def handle_response(self, response: t.Any) -> tuple[list, bool]:
262 + def handle_response(
263 + self,
264 + response: t.Any,
265 + *,
266 + user_id: t.Optional[str] = None,
267 + session: t.Optional[ToolCallSession] = None,
268 + ) -> tuple[list, bool]:
269 """Manually handle function calls in a Gemini response.
270
271 Provided for backward compatibility with code that uses manual function
@@ -230,11 +273,26 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
273 ``wrap_tools()`` to ``GenerateContentConfig(tools=...)`` and AFC will
274 handle execution automatically.
275
276 + A Gemini response does not say which user it belongs to. Pass the
277 + ``user_id`` given to ``tools.get()``, or the Tool Router ``session``
278 + whose ``tools()`` produced the tools, and each call runs exactly as
279 + the matching wrapped tool would, with the same modifiers and session
280 + routing. Without either, the provider must have wrapped tools for a
281 + single user or session only; otherwise this raises ``ValueError``.
282 +
283 Returns:
284 tuple: ``(function_responses, executed)`` where *function_responses*
285 are ``genai_types.Part`` objects ready to send back, and *executed*
286 is ``True`` if any functions were executed.
287 """
288 + target = (
289 + None
290 + if user_id is None and session is None
291 + else self.resolve_tool_call_execution_target(
292 + user_id=user_id, session=session
293 + )
294 + )
295 +
296 if not HAS_GENAI:
297 return [], False
298
@@ -245,19 +303,32 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
303 if not (hasattr(candidate, "content") and candidate.content.parts):
304 return [], False
305
248 - function_responses: list = []
249 - executed = False
250 -
251 - for part in candidate.content.parts:
252 - if not (hasattr(part, "function_call") and part.function_call):
253 - continue
306 + function_calls = [
307 + part.function_call
308 + for part in candidate.content.parts
309 + if hasattr(part, "function_call") and part.function_call
310 + ]
311
255 - fc = part.function_call
256 - if fc.name not in self._executors:
257 - continue
312 + # Pick every wrapped tool before running any call, so a concurrent
313 + # fetch cannot change who a later call in this response runs as, or
314 + # which schema checks it.
315 + with self._lock:
316 + if not any(
317 + fc.name in wrapped
318 + for fc in function_calls
319 + for wrapped in self._wrapped_tools.values()
320 + ):
321 + return [], False
322 + wrapped_tools = self._wrapped_tools_for(target)
323 + calls = [
324 + (fc, *wrapped_tools[fc.name])
325 + for fc in function_calls
326 + if fc.name in wrapped_tools
327 + ]
328
329 + function_responses: list = []
330 + for fc, execute_tool, aliases, args_schema in calls:
331 # Same validate -> serialize -> alias sequence as the AFC callable.
260 - execute_tool, aliases, args_schema = self._executors[fc.name]
332 arguments = validate_and_serialize_tool_arguments(
333 args_schema,
334 normalize_tool_arguments(_to_serializable(dict(fc.args))),
@@ -273,6 +344,31 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
344 )
345 )
346 )
276 - executed = True
347
278 - return function_responses, executed
348 + return function_responses, bool(function_responses)
349 +
350 + def _wrapped_tools_for(
351 + self,
352 + target: t.Optional[ToolCallExecutionTarget],
353 + ) -> t.Dict[str, _WrappedTool]:
354 + """Return the tools wrapped for *target*. Call with the lock held."""
355 + if target is None:
356 + if len(self._wrapped_tools) > 1:
357 + raise ValueError(
358 + "This provider has wrapped tools for more than one user or "
359 + "session, so the user to execute the response as is "
360 + "ambiguous. Pass the user the response belongs to: "
361 + "handle_response(response, user_id=...) or "
362 + "handle_response(response, session=...)."
363 + )
364 + return next(iter(self._wrapped_tools.values()), {})
365 +
366 + wrapped_tools = self._wrapped_tools.get(target)
367 + if wrapped_tools is None:
368 + source = (
369 + "composio.tools.get() for this user_id"
370 + if isinstance(target, str)
371 + else "this session's tools()"
372 + )
373 + raise ValueError(f"This provider has not wrapped any tools from {source}.")
374 + return wrapped_tools
python/tests/test_gemini_provider.py
+196 -11
@@ -6,11 +6,12 @@ Verifies:
6 - wrap_tools returns list of callables
7 - Callables are AFC-compatible (work with google-genai's function map)
8 - handle_response dispatches function calls via stored executors (backward compat)
9 + and runs each call for the user or session the caller passes
10 - _process_execution_result helper
11 """
12
13 import inspect
13 -from unittest.mock import MagicMock, Mock
14 +from unittest.mock import MagicMock, Mock, PropertyMock, patch
15
16 import pytest
17
@@ -112,11 +113,11 @@ class TestGeminiProviderInitialization:
113 assert provider.name == "gemini"
114 assert isinstance(provider, AgenticProvider)
115
115 - def test_has_empty_executors_on_init(self):
116 + def test_has_no_wrapped_tools_on_init(self):
117 from composio_gemini import GeminiProvider
118
119 provider = GeminiProvider()
119 - assert provider._executors == {}
120 + assert provider._wrapped_tools == {}
121
122
123 # ---------------------------------------------------------------------------
@@ -225,11 +226,9 @@ class TestWrapTool:
226 execute_tool = create_mock_execute_tool()
227 provider.wrap_tool(tool, execute_tool)
228
228 - assert "GITHUB_STAR_REPO" in provider._executors
229 - stored_execute_tool, _aliases, _args_schema = provider._executors[
230 - "GITHUB_STAR_REPO"
231 - ]
232 - assert stored_execute_tool is execute_tool
229 + assert list(provider._wrapped_tools) == [execute_tool]
230 + wrapped = provider._wrapped_tools[execute_tool]["GITHUB_STAR_REPO"]
231 + assert wrapped.execute_tool is execute_tool
232
233 def test_callable_executes_correctly(self):
234 from composio_gemini import GeminiProvider
@@ -522,10 +521,13 @@ class TestWrapTools:
521 create_mock_tool("GITHUB_STAR_REPO", "github"),
522 create_mock_tool("GMAIL_SEND_EMAIL", "gmail"),
523 ]
525 - provider.wrap_tools(tools, create_mock_execute_tool())
524 + execute_tool = create_mock_execute_tool()
525 + provider.wrap_tools(tools, execute_tool)
526
527 - assert "GITHUB_STAR_REPO" in provider._executors
528 - assert "GMAIL_SEND_EMAIL" in provider._executors
527 + assert set(provider._wrapped_tools[execute_tool]) == {
528 + "GITHUB_STAR_REPO",
529 + "GMAIL_SEND_EMAIL",
530 + }
531
532 def test_empty_list(self):
533 from composio_gemini import GeminiProvider
@@ -923,6 +925,189 @@ class TestHandleResponse:
925 assert function_responses == []
926
927
928 +@requires_genai
929 +class TestHandleResponseUser:
930 + """A function call runs for the user its tools were fetched for (#5112).
931 +
932 + These go through ``Composio.tools.get()`` so the execute function each
933 + fetch binds is the one the SDK really builds.
934 + """
935 +
936 + GMAIL = "GMAIL_FETCH_EMAILS"
937 + NOTION = "NOTION_CREATE_PAGE"
938 + SCHEMA = {
939 + "type": "object",
940 + "properties": {"query": {"type": "string"}},
941 + "required": ["query"],
942 + }
943 +
944 + def _tool(self, slug: str) -> Tool:
945 + return create_mock_tool(
946 + slug, slug.split("_")[0].lower(), input_parameters=self.SCHEMA
947 + )
948 +
949 + @pytest.fixture
950 + def composio(self):
951 + from composio import Composio
952 + from composio_gemini import GeminiProvider
953 +
954 + composio = Composio(
955 + provider=GeminiProvider(), api_key="test-key", allow_tracking=False
956 + )
957 + tools = {slug: self._tool(slug) for slug in (self.GMAIL, self.NOTION)}
958 +
959 + def execute(*, tool_slug, arguments, user_id, **_kwargs):
960 + return MagicMock(
961 + **{
962 + "model_dump.return_value": {
963 + "data": {"user_id": user_id},
964 + "error": None,
965 + "successful": True,
966 + }
967 + }
968 + )
969 +
970 + with (
971 + patch.object(
972 + composio.tools,
973 + "get_raw_composio_tools",
974 + side_effect=lambda **kwargs: [tools[s] for s in kwargs["tools"]],
975 + ),
976 + patch.object(
977 + type(composio.tools._client),
978 + "without_retries",
979 + new_callable=PropertyMock,
980 + ) as without_retries,
981 + ):
982 + without_retries.return_value.tools.execute.side_effect = execute
983 + yield composio
984 +
985 + @staticmethod
986 + def _response(*slugs: str):
987 + return genai_types.GenerateContentResponse(
988 + candidates=[
989 + genai_types.Candidate(
990 + content=genai_types.Content(
991 + role="model",
992 + parts=[
993 + genai_types.Part(
994 + function_call=genai_types.FunctionCall(
995 + name=slug, args={"query": "is:unread"}
996 + )
997 + )
998 + for slug in slugs
999 + ],
1000 + )
1001 + )
1002 + ]
1003 + )
1004 +
1005 + def _executed_for(self, composio, *slugs: str, **kwargs) -> list[str]:
1006 + parts, executed = composio.provider.handle_response(
1007 + self._response(*slugs), **kwargs
1008 + )
1009 + assert executed is True
1010 + return [part.function_response.response["user_id"] for part in parts]
1011 +
1012 + def test_explicit_user_wins_over_last_fetch(self, composio):
1013 + composio.tools.get(user_id="alice", tools=[self.GMAIL])
1014 + composio.tools.get(user_id="bob", tools=[self.GMAIL])
1015 +
1016 + assert self._executed_for(composio, self.GMAIL, user_id="alice") == ["alice"]
1017 + assert self._executed_for(composio, self.GMAIL, user_id="bob") == ["bob"]
1018 +
1019 + @pytest.mark.parametrize(
1020 + "bob_slug",
1021 + [GMAIL, NOTION],
1022 + ids=["same-slug", "disjoint-slugs"],
1023 + )
1024 + def test_rejects_call_without_user_once_two_users_fetched(self, composio, bob_slug):
1025 + composio.tools.get(user_id="alice", tools=[self.GMAIL])
1026 + composio.tools.get(user_id="bob", tools=[bob_slug])
1027 + execute = composio.tools._client.without_retries.tools.execute
1028 +
1029 + with pytest.raises(ValueError, match="user_id="):
1030 + composio.provider.handle_response(self._response(self.GMAIL))
1031 + execute.assert_not_called()
1032 +
1033 + def test_single_user_without_user_still_works(self, composio):
1034 + composio.tools.get(user_id="alice", tools=[self.GMAIL])
1035 + composio.tools.get(user_id="alice", tools=[self.NOTION])
1036 +
1037 + assert self._executed_for(composio, self.GMAIL, self.NOTION) == [
1038 + "alice",
1039 + "alice",
1040 + ]
1041 +
1042 + def test_rejects_user_with_no_fetched_tools(self, composio):
1043 + composio.tools.get(user_id="alice", tools=[self.GMAIL])
1044 +
1045 + with pytest.raises(ValueError, match="user_id"):
1046 + composio.provider.handle_response(
1047 + self._response(self.GMAIL), user_id="carol"
1048 + )
1049 +
1050 + def test_fetch_during_execution_does_not_switch_user(self, composio):
1051 + """Executors are picked before any call runs (review of #5120)."""
1052 + composio.tools.get(user_id="alice", tools=[self.GMAIL, self.NOTION])
1053 + execute = composio.tools._client.without_retries.tools.execute
1054 + alice_execute = execute.side_effect
1055 +
1056 + def fetch_for_bob_then_execute(**kwargs):
1057 + execute.side_effect = alice_execute
1058 + composio.tools.get(user_id="bob", tools=[self.NOTION])
1059 + return alice_execute(**kwargs)
1060 +
1061 + execute.side_effect = fetch_for_bob_then_execute
1062 +
1063 + # Without a user: Bob's fetch mid-response would make a later lookup
1064 + # ambiguous, but the response was resolved before it.
1065 + assert self._executed_for(composio, self.GMAIL, self.NOTION) == [
1066 + "alice",
1067 + "alice",
1068 + ]
1069 + with pytest.raises(ValueError, match="user_id="):
1070 + composio.provider.handle_response(self._response(self.GMAIL))
1071 +
1072 + def test_call_is_validated_with_its_own_users_schema(self, composio):
1073 + """Each user's schema modifiers check that user's calls (review of #5120)."""
1074 + from composio import schema_modifier
1075 +
1076 + @schema_modifier(tools=[self.GMAIL])
1077 + def starred_only(tool: str, toolkit: str, schema: Tool) -> Tool:
1078 + schema.input_parameters = {
1079 + **self.SCHEMA,
1080 + "properties": {"query": {"type": "string", "enum": ["is:starred"]}},
1081 + }
1082 + return schema
1083 +
1084 + composio.tools.get(user_id="alice", tools=[self.GMAIL])
1085 + composio.tools.get(user_id="bob", tools=[self.GMAIL], modifiers=[starred_only])
1086 +
1087 + assert self._executed_for(composio, self.GMAIL, user_id="alice") == ["alice"]
1088 + with pytest.raises(ValueError, match="is:starred"):
1089 + composio.provider.handle_response(self._response(self.GMAIL), user_id="bob")
1090 +
1091 + def test_session_runs_through_its_own_executor(self, composio):
1092 + """``session=`` keeps the routing ``session.tools()`` installed, which
1093 + runs local custom tools in a batch in process."""
1094 + from composio.core.provider import bind_execution_target
1095 +
1096 + composio.tools.get(user_id="alice", tools=[self.GMAIL])
1097 + session = Mock()
1098 + routing_execute = bind_execution_target(
1099 + Mock(return_value={"data": {"user_id": "session"}, "successful": True}),
1100 + session,
1101 + )
1102 + composio.provider.wrap_tools([self._tool(self.GMAIL)], routing_execute)
1103 +
1104 + assert self._executed_for(composio, self.GMAIL, session=session) == ["session"]
1105 + routing_execute.assert_called_once_with(
1106 + slug=self.GMAIL, arguments={"query": "is:unread"}
1107 + )
1108 + session.execute.assert_not_called()
1109 +
1110 +
1111 # ---------------------------------------------------------------------------
1112 # _process_execution_result
1113 # ---------------------------------------------------------------------------
python/tests/test_tool_router.py
+4
@@ -32,6 +32,7 @@ from pydantic import BaseModel, Field
32 from composio.client import HttpClient
33 from composio.core.models.experimental import ExperimentalAPI
34 from composio.core.models.session_context import SessionContextImpl
35 +from composio.core.provider import get_execution_target
36 from composio.core.models.tool_router import (
37 SESSION_PRESET_DIRECT_TOOLS,
38 ToolkitConnectionsDetails,
@@ -1758,6 +1759,9 @@ class TestToolRouter:
1759 assert result == "mocked-custom-tools"
1760
1761 execute_tool = mock_provider.wrap_tools.call_args.kwargs["execute_tool"]
1762 + # Gemini's manual handle_response(session=...) finds this routing
1763 + # executor by the session recorded on it.
1764 + assert get_execution_target(execute_tool) is session
1765 local_result = execute_tool(slug="SERVER_GREP", arguments={"pattern": "needle"})
1766 assert local_result == {
1767 "data": {"matches": ["needle"]},