@devries-cameron20 / composio Mirror · read-only / commits / cdabe06e5
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, 11:00 UTC

feat(providers): accept a Tool Router session in all provider helpers (#4675)

This PR: - closes https://github.com/ComposioHQ/composio/issues/4571 and https://github.com/ComposioHQ/composio/issues/4660 - adds a session overload to the TS Google and Cloudflare `executeToolCall` and to OpenAI Responses `handleResponse`, completing the rollout from https://github.com/ComposioHQ/composio/pull/4098 - adds `session=` to the Python Google `execute_tool_call` and `handle_response` - keeps user-ID calls on the original `executeTool` path: the Google/Cloudflare peer ranges admit `@composio/core` releases that predate `executeToolForTarget`, so only session calls need core ≥ 0.17.0 - makes the Cloudflare `options` argument optional (widening only; existing calls still type-check) - fixes the Google (TS and Python) and Cloudflare README quickstarts, which paired `session.tools()` with a user-ID helper, so session meta-tools failed - updates `google.mdx` and the LLM guardrail notes, and extends the docs session check to catch `handleResponse`/`handle_response` bound to a user ID - supersedes https://github.com/ComposioHQ/composio/pull/4572 and https://github.com/ComposioHQ/composio/pull/4661; thanks to their authors for the reports and the matching approach ## Testing - `vitest run` in google (19), cloudflare (17), openai (40), anthropic (49), typesafe (117) — all pass; new tests cover session routing, session error results, option rejection, and user-ID calls on a core without `executeToolForTarget` - `pytest tests/test_google_provider.py` (6 pass); ruff with `config/ruff.toml` and mypy clean on the changed files - docs: `bun test` on `session-execution`, `execute-version`, `api-version-markdown`, `llms-openapi` — all pass OpenAI Assistants helpers (`handleAssistantMessage`, `handle_assistant_tool_calls`) stay user-ID only: deprecated, and the Assistants API is sunset.

Alberto Schiabel committed Sep 28, 2026 at 17:45 UTC cdabe06e512b9c17d2f52a28e79382024173228f
15 files changed +510 -43
.changeset/session-aware-google-cloudflare-helpers.md new
+7
@@ -0,0 +1,7 @@
1 +---
2 +'@composio/google': minor
3 +'@composio/cloudflare': minor
4 +'@composio/openai': minor
5 +---
6 +
7 +Allow the Google and Cloudflare providers' `executeToolCall` and the OpenAI Responses provider's `handleResponse` to execute through a supplied Tool Router session, matching the other provider helpers. Session meta-tools now keep their session context through these helpers. Existing user-ID calls keep using direct execution unchanged, and the Cloudflare `options` argument is now optional. Passing a session requires `@composio/core` 0.17.0 or later. Custom provider subclasses overriding these methods may require updates because they now accept session targets.
docs/content/docs/providers/google.mdx
+11 -6
@@ -13,7 +13,7 @@ The Google provider formats Composio tools for [Gemini](https://ai.google.dev/)
13
14 <IntegrationContent value="gemini">
15
16 -In Python, the Gemini provider (`composio_gemini`) wraps Composio tools as typed callables, and the `google-genai` SDK's Automatic Function Calling executes tool calls inside the chat loop for you. In TypeScript, the Google provider transforms Composio tools into Gemini function declarations, and you run the loop: execute each call with `session.execute`, feed the result back, and repeat until the model replies with text.
16 +In Python, the Gemini provider (`composio_gemini`) wraps Composio tools as typed callables, and the `google-genai` SDK's Automatic Function Calling executes tool calls inside the chat loop for you. In TypeScript, the Google provider transforms Composio tools into Gemini function declarations, and you run the loop: execute each call with `composio.provider.executeToolCall(session, functionCall)`, feed the result back, and repeat until the model replies with text.
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
@@ -73,7 +73,9 @@ print(response.text)
73 ```
74 </Tab>
75 <Tab value="TypeScript">
76 +{/* TODO: remove the `@errors: 2345` twoslash marker below once docs/package.json resolves @composio/google >= 0.12.0 (session-aware executeToolCall). The pin needs a manual range bump — ^0.11.1 does not admit this minor release. */}
77 ```typescript
78 +// @errors: 2345
79 import { Composio } from '@composio/core';
80 import { GoogleProvider } from '@composio/google';
81 import { GoogleGenAI, type Part } from '@google/genai';
@@ -98,16 +100,19 @@ let response = await chat.sendMessage({
100 message: "Send an email to john@example.com with the subject 'Hello' and body 'Hello from Composio!'",
101 });
102
101 -// Agentic loop: run each tool call with session.execute() until the model responds with text
103 +// Agentic loop: execute each tool call through the session until the model responds with text
104 while (response.functionCalls && response.functionCalls.length > 0) {
105 const parts: Part[] = [];
106 for (const fc of response.functionCalls) {
105 - const result = await session.execute(fc.name || '', (fc.args || {}) as Record<string, unknown>);
107 + const result = await composio.provider.executeToolCall(session, {
108 + name: fc.name || '',
109 + args: (fc.args || {}) as Record<string, unknown>,
110 + });
111 parts.push({
112 functionResponse: {
113 id: fc.id,
114 name: fc.name,
110 - response: result.error ? { error: result.error } : result.data,
115 + response: JSON.parse(result),
116 },
117 });
118 }
@@ -121,8 +126,8 @@ console.log(response.text);
126 </Step>
127 </Steps>
128
124 -<Callout type="warn">
125 -In TypeScript, execute session tools with `session.execute(toolSlug, arguments)`, as shown above. The provider's `executeToolCall` helper executes tools through the direct path, which does not carry your session — session meta-tools (`COMPOSIO_SEARCH_TOOLS`, `COMPOSIO_MANAGE_CONNECTIONS`, …) are rejected there with `"can only be called inside a tool-router session"`. Use `executeToolCall` only with tools fetched via [`tools.get`](/docs/tools-direct/executing-tools), not with `session.tools()`. Unlike the [OpenAI](/docs/providers/openai) and [Anthropic](/docs/providers/anthropic) helpers, the Google provider's `executeToolCall` does not yet accept a session. (The Python Gemini tab is unaffected: Automatic Function Calling runs provider-wrapped callables, which carry the session.)
129 +<Callout type="info">
130 +Pass the session to `executeToolCall` when the model received tools from `session.tools()`. The helper preserves the provider's argument normalization and executes the call through that session, so session meta-tools such as `COMPOSIO_SEARCH_TOOLS` keep working. For tools fetched via [`tools.get`](/docs/tools-direct/executing-tools), pass the user ID instead. Passing a session requires `@composio/core` ≥ 0.17.0 with `@composio/google` ≥ 0.12.0; on earlier versions, execute session tools with [`session.execute()`](/docs/how-composio-works#executing-session-tools). The Python Gemini tab needs neither: Automatic Function Calling runs provider-wrapped callables, which carry the session.
131 </Callout>
132
133 </IntegrationContent>
docs/lib/llm-guardrails/session.ts
+1 -1
@@ -63,7 +63,7 @@ Use \`session.mcp.url\` and \`session.mcp.headers\` with any MCP-compatible clie
63 ## 2. Integration Notes
64
65 - \`composio.create(user_id)\` is the standard entry point for agent integrations. Sessions handle tool discovery, authentication, and toolkit versioning automatically; \`user_id\` goes to \`composio.create()\` — individual tool calls in session mode don't take one.
66 -- Execute session tool calls through the session, never through a user ID: either \`session.execute(tool_slug, arguments=...)\` / \`session.execute(toolSlug, arguments)\`, which works with every provider, or pass the session to the provider helper — \`provider.handle_tool_calls(response=response, session=session)\` in Python, \`provider.handleToolCalls(session, response)\` in TypeScript. Only the OpenAI and Anthropic helpers accept a session; with other providers, use \`session.execute()\`. Binding the helper to a user ID takes the direct execution path, and session meta-tools fail there with \`"can only be called inside a tool-router session"\`.
66 +- Execute session tool calls through the session, never through a user ID: either \`session.execute(tool_slug, arguments=...)\` / \`session.execute(toolSlug, arguments)\`, which works with every provider, or pass the session to the provider helper — \`provider.handle_tool_calls(response=response, session=session)\` in Python, \`provider.handleToolCalls(session, response)\` in TypeScript. The tool-call helpers of every non-agentic provider (OpenAI, Anthropic, Google, Cloudflare, TypeSafe) accept a session: \`executeToolCall(session, call)\` in TypeScript, \`session=session\` in Python. Agentic providers execute session tools on their own. Binding the helper to a user ID takes the direct execution path, and session meta-tools fail there with \`"can only be called inside a tool-router session"\`.
67 - Composio-managed auth is the default: the agent connects accounts at runtime through the session, so users don't need to pre-create auth configs or connected accounts for managed toolkits.
68 - Provider packages follow the framework, not the model vendor: for the OpenAI Agents SDK the package is \`composio_openai_agents\` / \`@composio/openai-agents\` (importing \`composio_openai\` / \`@composio/openai\` there is the most common mistake in generated code — that package is for the plain OpenAI Chat Completions API).
69 - **Direct execution** (\`composio.tools.get()\`, \`composio.tools.execute()\`, \`provider.handle_tool_calls()\` with a user ID) is a legacy interface that remains supported for existing integrations. Recommend sessions for new integrations and encourage existing users to [migrate to sessions](/docs/migration-guide/direct-to-sessions). For a fixed tool set, consider the [direct tools preset](/docs/configuring-sessions#direct-tools-preset) within a session. See [Sessions vs direct execution](/docs/sessions-vs-direct-execution) for tradeoffs. Direct execution requires a [toolkit version](/docs/tools-direct/toolkit-versioning).
docs/tests/static/session-execution.test.ts
+19 -1
@@ -45,7 +45,7 @@ const SESSION_TOKEN_RE =
45 // a string-literal first argument, or a whole identifier that names a user ID
46 // (`userId`, `user_id`, `uid`) — a session argument never does.
47 const DIRECT_HELPER_TOKEN_RE =
48 - /(?:handle_tool_calls|execute_tool_call)\s*\((?:[^()]*\([^()]*\))*[^()]*\buser_id\s*=|(?:handleToolCalls|executeToolCall)\s*\(\s*(?:["'`]|(?:user_?[iI]d|uid)\b)/;
48 + /(?:handle_tool_calls|handle_response|execute_tool_call)\s*\((?:[^()]*\([^()]*\))*[^()]*\buser_id\s*=|(?:handleToolCalls|handleResponse|executeToolCall)\s*\(\s*(?:["'`]|(?:user_?[iI]d|uid)\b)/;
49 const SAMPLE_BOUNDARY_RE = /^\s*(?:<\/?(?:Tab|Step)\b|#{1,6}\s)/;
50 const FENCE_OPEN_RE = /^\s*(`{3,}|~{3,})/;
51 const FENCE_CLOSE_RE = /^\s*(`{3,}|~{3,})\s*$/;
@@ -218,6 +218,24 @@ const results = await composio.provider.handleToolCalls(userId, response);
218 expect(hasDirectHelperBoundToSessionTools(source)).toBe(true);
219 });
220
221 + test("detects response helpers bound to a user ID", () => {
222 + const python = `
223 +\`\`\`python
224 +session = composio.create(user_id="user_123")
225 +tools = session.tools()
226 +results = composio.provider.handle_response(user_id="user_123", response=response)
227 +\`\`\``;
228 + const typescript = `
229 +\`\`\`typescript
230 +const session = await composio.create("user_123");
231 +const tools = await session.tools();
232 +const outputs = await composio.provider.handleResponse("user_123", response);
233 +\`\`\``;
234 +
235 + expect(hasDirectHelperBoundToSessionTools(python)).toBe(true);
236 + expect(hasDirectHelperBoundToSessionTools(typescript)).toBe(true);
237 + });
238 +
239 test("LLM guardrail blocks never bind provider helpers to a user ID", () => {
240 for (const guardrails of [SESSION_GUARDRAILS, DIRECT_EXECUTION_GUARDRAILS]) {
241 expect(hasDirectHelperBoundToSessionTools(guardrails)).toBe(false);
python/providers/google/README.md
+3 -3
@@ -12,7 +12,7 @@ Set `COMPOSIO_API_KEY` (create one at https://dashboard.composio.dev/settings) i
12
13 ## Quickstart
14
15 -`GoogleProvider` is non-agentic: the model returns function calls, and `composio.provider.handle_response` executes every function call in the response and returns the results.
15 +`GoogleProvider` is non-agentic: the model returns function calls, and `composio.provider.handle_response` executes every function call in the response through the session and returns the results.
16
17 ```python
18 import vertexai
@@ -40,11 +40,11 @@ response = chat.send_message(
40 )
41
42 # Execute the function calls the model requested
43 -results = composio.provider.handle_response(user_id="user_123", response=response)
43 +results = composio.provider.handle_response(session=session, response=response)
44 print(results)
45 ```
46
47 -To execute a single call instead of the whole response, use `composio.provider.execute_tool_call(user_id="user_123", function_call=part.function_call)`.
47 +To execute a single call instead of the whole response, use `composio.provider.execute_tool_call(session=session, function_call=part.function_call)`. For tools fetched with `composio.tools.get()`, pass `user_id=` instead of `session=`.
48
49 ## composio-google vs composio-gemini
50
python/providers/google/composio_google/provider.py
+64 -9
@@ -12,7 +12,7 @@ from vertexai.generative_models import (
12 Part,
13 )
14
15 -from composio.core.provider import NonAgenticProvider
15 +from composio.core.provider import NonAgenticProvider, ToolCallSession
16 from composio.types import Modifiers, Tool, ToolExecutionResponse
17 from composio.utils.json_schema import dereference_json_schema
18 from composio.utils.shared import normalize_tool_arguments
@@ -62,43 +62,93 @@ class GoogleProvider(
62 def wrap_tools(self, tools: t.Sequence[Tool]) -> list[FunctionDeclaration]:
63 return [self.wrap_tool(tool) for tool in tools]
64
65 + @t.overload
66 def execute_tool_call(
67 self,
68 user_id: str,
69 function_call: t.Any,
70 modifiers: t.Optional[Modifiers] = None,
71 + ) -> ToolExecutionResponse: ...
72 +
73 + @t.overload
74 + def execute_tool_call(
75 + self,
76 + *,
77 + session: ToolCallSession,
78 + function_call: t.Any,
79 + ) -> ToolExecutionResponse: ...
80 +
81 + def execute_tool_call(
82 + self,
83 + user_id: t.Optional[str] = None,
84 + function_call: t.Any = None,
85 + modifiers: t.Optional[Modifiers] = None,
86 + *,
87 + session: t.Optional[ToolCallSession] = None,
88 ) -> ToolExecutionResponse:
89 """
90 Execute a function call.
91
92 :param function_call: Function call metadata from Gemini model response.
75 - :param user_id: User ID to use for executing the function call.
93 + :param user_id: User ID for direct tool execution.
94 + :param session: Tool Router session that produced session tools.
95 + :param modifiers: Modifiers to use for direct execution.
96 :return: Object containing output data from the function call.
97 """
98 + if function_call is None:
99 + raise TypeError("function_call is required")
100 # Gemini returns args as a MapComposite; normalize after converting to a
101 # plain dict so a stringified payload is handled uniformly too (issue #2406).
80 - return self.execute_tool(
81 - slug=function_call.name,
82 - arguments=normalize_tool_arguments(
83 - _convert_map_composite(function_call.args)
102 + arguments = normalize_tool_arguments(_convert_map_composite(function_call.args))
103 + return self.execute_tool_for_target(
104 + target=self.resolve_tool_call_execution_target(
105 + user_id=user_id, session=session
106 ),
107 + slug=function_call.name,
108 + arguments=arguments,
109 modifiers=modifiers,
86 - user_id=user_id,
110 )
111
112 + @t.overload
113 def handle_response(
114 self,
115 user_id: str,
116 response: GenerationResponse,
117 modifiers: t.Optional[Modifiers] = None,
118 + ) -> t.List[ToolExecutionResponse]: ...
119 +
120 + @t.overload
121 + def handle_response(
122 + self,
123 + *,
124 + session: ToolCallSession,
125 + response: GenerationResponse,
126 + ) -> t.List[ToolExecutionResponse]: ...
127 +
128 + def handle_response(
129 + self,
130 + user_id: t.Optional[str] = None,
131 + response: t.Optional[GenerationResponse] = None,
132 + modifiers: t.Optional[Modifiers] = None,
133 + *,
134 + session: t.Optional[ToolCallSession] = None,
135 ) -> t.List[ToolExecutionResponse]:
136 """
137 Handle response from Google AI Python Gemini model.
138
139 :param response: Generation response from the Gemini model.
99 - :param user_id: User ID to use for executing the function call.
140 + :param user_id: User ID for direct tool execution.
141 + :param session: Tool Router session that produced session tools.
142 + :param modifiers: Modifiers to use for direct execution.
143 :return: A list of output objects from the function calls.
144 """
145 + if response is None:
146 + raise TypeError("response is required")
147 + self.resolve_tool_call_execution_target(user_id=user_id, session=session)
148 + if session is not None and modifiers is not None:
149 + raise ValueError(
150 + "Direct execution modifiers cannot be used with a Tool Router session"
151 + )
152 outputs = []
153 for candidate in response.candidates:
154 if isinstance(candidate.content, Content) and candidate.content.parts:
@@ -106,7 +156,12 @@ class GoogleProvider(
156 if isinstance(part, Part) and part.function_call:
157 outputs.append(
158 self.execute_tool_call(
109 - user_id=user_id,
159 + session=session,
160 + function_call=part.function_call,
161 + )
162 + if session is not None
163 + else self.execute_tool_call(
164 + user_id=t.cast(str, user_id),
165 function_call=part.function_call,
166 modifiers=modifiers,
167 )
python/tests/test_google_provider.py
+112
@@ -1,10 +1,17 @@
1 """Tests for the Vertex AI Google provider."""
2
3 +from types import SimpleNamespace
4 +from typing import Any
5 +from unittest.mock import Mock
6 +
7 import pytest
8
9 from composio.client.types import Tool
10
11 GoogleProvider = pytest.importorskip("composio_google").GoogleProvider
12 +GenerationResponse = pytest.importorskip(
13 + "vertexai.generative_models"
14 +).GenerationResponse
15
16
17 def test_wrap_tool_dereferences_internal_refs() -> None:
@@ -31,3 +38,108 @@ def test_wrap_tool_dereferences_internal_refs() -> None:
38
39 assert "ref" not in message_schema
40 assert message_schema["properties"]["subject"]["type"] == "STRING"
41 +
42 +
43 +def _function_call_response() -> Any:
44 + return GenerationResponse.from_dict(
45 + {
46 + "candidates": [
47 + {
48 + "content": {
49 + "role": "model",
50 + "parts": [
51 + {"text": "Searching"},
52 + {
53 + "function_call": {
54 + "name": "COMPOSIO_SEARCH_TOOLS",
55 + "args": {"query": "send an email"},
56 + }
57 + },
58 + ],
59 + }
60 + }
61 + ]
62 + }
63 + )
64 +
65 +
66 +def _session() -> Mock:
67 + session = Mock()
68 + session.execute.return_value = SimpleNamespace(
69 + data={"results": []}, error=None, log_id="log-session"
70 + )
71 + return session
72 +
73 +
74 +def test_handle_response_routes_function_calls_through_session() -> None:
75 + """Session tools execute through their Tool Router session, not tools.execute."""
76 + provider = GoogleProvider()
77 + provider.execute_tool = Mock()
78 + session = _session()
79 +
80 + results = provider.handle_response(
81 + response=_function_call_response(), session=session
82 + )
83 +
84 + session.execute.assert_called_once_with(
85 + tool_slug="COMPOSIO_SEARCH_TOOLS", arguments={"query": "send an email"}
86 + )
87 + provider.execute_tool.assert_not_called()
88 + assert results == [{"data": {"results": []}, "error": None, "successful": True}]
89 +
90 +
91 +def test_handle_response_keeps_direct_user_id_execution() -> None:
92 + """Existing positional user-ID calls keep the direct execution path."""
93 + provider = GoogleProvider()
94 + provider.execute_tool = Mock(
95 + return_value={"data": {}, "error": None, "successful": True}
96 + )
97 + modifiers = [Mock()]
98 +
99 + results = provider.handle_response("user_123", _function_call_response(), modifiers)
100 +
101 + provider.execute_tool.assert_called_once_with(
102 + slug="COMPOSIO_SEARCH_TOOLS",
103 + arguments={"query": "send an email"},
104 + modifiers=modifiers,
105 + user_id="user_123",
106 + )
107 + assert results == [{"data": {}, "error": None, "successful": True}]
108 +
109 +
110 +def test_execute_tool_call_routes_through_session() -> None:
111 + provider = GoogleProvider()
112 + provider.execute_tool = Mock()
113 + session = _session()
114 + function_call = SimpleNamespace(name="COMPOSIO_SEARCH_TOOLS", args={"query": "x"})
115 +
116 + result = provider.execute_tool_call(session=session, function_call=function_call)
117 +
118 + session.execute.assert_called_once_with(
119 + tool_slug="COMPOSIO_SEARCH_TOOLS", arguments={"query": "x"}
120 + )
121 + provider.execute_tool.assert_not_called()
122 + assert result == {"data": {"results": []}, "error": None, "successful": True}
123 +
124 +
125 +def test_handle_response_rejects_modifiers_with_session() -> None:
126 + provider = GoogleProvider()
127 + session = _session()
128 +
129 + with pytest.raises(ValueError, match="cannot be used with a Tool Router session"):
130 + provider.handle_response(
131 + response=_function_call_response(),
132 + session=session,
133 + modifiers=[Mock()],
134 + )
135 + session.execute.assert_not_called()
136 +
137 +
138 +def test_execute_tool_call_requires_exactly_one_target() -> None:
139 + provider = GoogleProvider()
140 + function_call = SimpleNamespace(name="COMPOSIO_SEARCH_TOOLS", args={})
141 +
142 + with pytest.raises(ValueError, match="exactly one of user_id or session"):
143 + provider.execute_tool_call(
144 + user_id="user_123", session=_session(), function_call=function_call
145 + )
ts/packages/providers/cloudflare/README.md
+2 -2
@@ -40,7 +40,7 @@ export default {
40
41 const results = [];
42 for (const toolCall of response.tool_calls ?? []) {
43 - results.push(await composio.provider.executeToolCall('user_123', toolCall, {}));
43 + results.push(await composio.provider.executeToolCall(session, toolCall));
44 }
45
46 return Response.json({ response, results });
@@ -48,7 +48,7 @@ export default {
48 };
49 ```
50
51 -`executeToolCall` takes the `{ name, arguments }` tool calls that Workers AI emits, runs the matching Composio tool for that user, and returns the result as a JSON string.
51 +`executeToolCall` takes the `{ name, arguments }` tool calls that Workers AI emits, runs the matching Composio tool through the session that produced the tools, and returns the result as a JSON string. For tools fetched with `tools.get()`, pass the user ID instead: `executeToolCall(userId, toolCall, options?, modifiers?)`.
52
53 ## Links
54
ts/packages/providers/cloudflare/src/index.ts
+38 -10
@@ -16,6 +16,8 @@ import {
16 BaseNonAgenticProvider,
17 ToolExecuteParams,
18 ExecuteToolFnOptions,
19 + ToolCallExecutionTarget,
20 + ToolCallSession,
21 McpUrlResponse,
22 McpServerGetResponse,
23 normalizeToolArguments,
@@ -186,10 +188,10 @@ export class CloudflareProvider extends BaseNonAgenticProvider<
188 * This method processes a function call from Cloudflare's AI API,
189 * executes the corresponding Composio tool, and returns the result.
190 *
189 - * @param userId - The user ID for authentication and tracking
191 + * @param executionTarget - A user ID for direct tools or the session that produced session tools
192 * @param tool - The tool call object with name and arguments
191 - * @param options - Optional execution options like connected account ID
192 - * @param modifiers - Optional execution modifiers for tool behavior
193 + * @param options - Optional execution options like connected account ID (user ID targets only)
194 + * @param modifiers - Optional execution modifiers for tool behavior (user ID targets only)
195 * @returns The result of the tool execution as a JSON string
196 *
197 * @example
@@ -224,21 +226,47 @@ export class CloudflareProvider extends BaseNonAgenticProvider<
226 * ],
227 * tools: cloudflareTools
228 * });
229 + *
230 + * // For tools from session.tools(), pass the session instead of a user ID
231 + * const sessionResult = await provider.executeToolCall(session, toolCall);
232 * ```
233 */
234 + async executeToolCall(
235 + session: ToolCallSession,
236 + tool: { name: string; arguments: unknown }
237 + ): Promise<string>;
238 async executeToolCall(
239 userId: string,
240 tool: { name: string; arguments: unknown },
232 - options: ExecuteToolFnOptions,
241 + options?: ExecuteToolFnOptions,
242 + modifiers?: ExecuteToolModifiers
243 + ): Promise<string>;
244 + async executeToolCall(
245 + executionTarget: ToolCallExecutionTarget,
246 + tool: { name: string; arguments: unknown },
247 + options?: ExecuteToolFnOptions,
248 modifiers?: ExecuteToolModifiers
249 ): Promise<string> {
250 + // Models occasionally emit tool arguments as a JSON string rather than an object (issue #2406).
251 + const toolArguments = normalizeToolArguments(tool.arguments, tool.name);
252 + if (typeof executionTarget !== 'string') {
253 + const result = await this.executeToolForTarget(
254 + executionTarget,
255 + tool.name,
256 + toolArguments,
257 + options,
258 + modifiers
259 + );
260 + return JSON.stringify(result);
261 + }
262 +
263 + // Keep direct execution on `executeTool`, which every supported @composio/core provides.
264 const payload: ToolExecuteParams = {
236 - // Models occasionally emit tool arguments as a JSON string rather than an object (issue #2406).
237 - arguments: normalizeToolArguments(tool.arguments, tool.name),
238 - connectedAccountId: options.connectedAccountId,
239 - customAuthParams: options.customAuthParams,
240 - customConnectionData: options.customConnectionData,
241 - userId: userId,
265 + arguments: toolArguments,
266 + connectedAccountId: options?.connectedAccountId,
267 + customAuthParams: options?.customAuthParams,
268 + customConnectionData: options?.customConnectionData,
269 + userId: executionTarget,
270 };
271
272 const result = await this.executeTool(tool.name, payload, modifiers);
ts/packages/providers/cloudflare/test/cloudflare.test.ts
+80
@@ -286,4 +286,84 @@ describe('CloudflareProvider', () => {
286 expect(wrapped.type).toBe('function');
287 });
288 });
289 +
290 + describe('executeToolCall with a Tool Router session', () => {
291 + it('keeps user ID calls working on @composio/core releases without session helpers', async () => {
292 + // The peer range admits cores that predate executeToolForTarget.
293 + Object.defineProperty(provider, 'executeToolForTarget', { value: undefined });
294 +
295 + await provider.executeToolCall('test-user', { name: 'test-tool', arguments: {} });
296 +
297 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
298 + 'test-tool',
299 + expect.objectContaining({ userId: 'test-user' }),
300 + undefined
301 + );
302 + });
303 +
304 + it('still executes a user ID call without options', async () => {
305 + await provider.executeToolCall('test-user', { name: 'test-tool', arguments: {} });
306 +
307 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
308 + 'test-tool',
309 + expect.objectContaining({ arguments: {}, userId: 'test-user' }),
310 + undefined
311 + );
312 + });
313 +
314 + it('executes through the session instead of the direct tools API', async () => {
315 + const session = {
316 + execute: vi.fn().mockResolvedValue({
317 + data: { result: 'session-success' },
318 + error: null,
319 + logId: 'log-session',
320 + }),
321 + };
322 +
323 + const result = await provider.executeToolCall(session, {
324 + name: 'COMPOSIO_SEARCH_TOOLS',
325 + arguments: JSON.stringify({ query: 'send an email' }),
326 + });
327 +
328 + expect(session.execute).toHaveBeenCalledWith('COMPOSIO_SEARCH_TOOLS', {
329 + query: 'send an email',
330 + });
331 + expect(mockExecuteToolFn).not.toHaveBeenCalled();
332 + expect(JSON.parse(result)).toEqual({
333 + data: { result: 'session-success' },
334 + error: null,
335 + logId: 'log-session',
336 + successful: true,
337 + });
338 + });
339 +
340 + it('reports a failed session execution in the result', async () => {
341 + const session = {
342 + execute: vi.fn().mockResolvedValue({ data: {}, error: 'Tool failed', logId: 'log-fail' }),
343 + };
344 +
345 + const result = await provider.executeToolCall(session, {
346 + name: 'COMPOSIO_SEARCH_TOOLS',
347 + arguments: {},
348 + });
349 +
350 + expect(JSON.parse(result)).toMatchObject({ error: 'Tool failed', successful: false });
351 + });
352 +
353 + it('rejects direct execution options with a session', async () => {
354 + const session = { execute: vi.fn() };
355 +
356 + await expect(
357 + provider.executeToolCall(
358 + // @ts-expect-error direct execution options are not accepted with a session
359 + session,
360 + { name: 'COMPOSIO_SEARCH_TOOLS', arguments: {} },
361 + { connectedAccountId: 'conn-123' }
362 + )
363 + ).rejects.toThrow(
364 + 'Direct execution options and modifiers cannot be used with a Tool Router session'
365 + );
366 + expect(session.execute).not.toHaveBeenCalled();
367 + });
368 + });
369 });
ts/packages/providers/google/README.md
+2 -2
@@ -44,7 +44,7 @@ let response = await chat.sendMessage({
44 while (response.functionCalls && response.functionCalls.length > 0) {
45 const parts: Part[] = [];
46 for (const fc of response.functionCalls) {
47 - const result = await composio.provider.executeToolCall('user_123', {
47 + const result = await composio.provider.executeToolCall(session, {
48 name: fc.name || '',
49 args: (fc.args || {}) as Record<string, unknown>,
50 });
@@ -64,7 +64,7 @@ console.log(response.text);
64
65 ## Tool execution
66
67 -Gemini function calling is non-agentic; the model returns function calls and you execute them. `GoogleProvider` exposes `executeToolCall(userId, functionCall, options?, modifiers?)`, which takes a `{ name, args }` pair and returns the tool result as a JSON string. The constructor takes no options.
67 +Gemini function calling is non-agentic; the model returns function calls and you execute them. `GoogleProvider` exposes `executeToolCall(session, functionCall)`, which takes a `{ name, args }` pair, executes it through the session that produced the tools, and returns the tool result as a JSON string. For tools fetched with `tools.get()`, call `executeToolCall(userId, functionCall, options?, modifiers?)` instead. The constructor takes no options.
68
69 ## Links
70
ts/packages/providers/google/src/index.ts
+31 -6
@@ -13,6 +13,8 @@ import {
13 ToolExecuteParams,
14 ExecuteToolModifiers,
15 ExecuteToolFnOptions,
16 + ToolCallExecutionTarget,
17 + ToolCallSession,
18 McpUrlResponse,
19 McpServerGetResponse,
20 normalizeToolArguments,
@@ -209,10 +211,10 @@ export class GoogleProvider extends BaseNonAgenticProvider<
211 * This method processes a function call from Google's GenAI API,
212 * executes the corresponding Composio tool, and returns the result.
213 *
212 - * @param userId - The user ID for authentication and tracking
214 + * @param executionTarget - A user ID for direct tools or the session that produced session tools
215 * @param tool - The Google GenAI function call to execute
214 - * @param options - Optional execution options like connected account ID
215 - * @param modifiers - Optional execution modifiers for tool behavior
216 + * @param options - Optional execution options like connected account ID (user ID targets only)
217 + * @param modifiers - Optional execution modifiers for tool behavior (user ID targets only)
218 * @returns The result of the tool execution as a JSON string
219 *
220 * @example
@@ -245,21 +247,44 @@ export class GoogleProvider extends BaseNonAgenticProvider<
247 * { role: 'model', parts: [{ functionResponse: { name: 'SEARCH_TOOL', response: result } }] }
248 * ]
249 * });
250 + *
251 + * // For tools from session.tools(), pass the session instead of a user ID
252 + * const sessionResult = await provider.executeToolCall(session, functionCall);
253 * ```
254 */
255 + async executeToolCall(session: ToolCallSession, tool: GoogleGenAIFunctionCall): Promise<string>;
256 async executeToolCall(
257 userId: string,
258 tool: GoogleGenAIFunctionCall,
259 options?: ExecuteToolFnOptions,
260 modifiers?: ExecuteToolModifiers
261 + ): Promise<string>;
262 + async executeToolCall(
263 + executionTarget: ToolCallExecutionTarget,
264 + tool: GoogleGenAIFunctionCall,
265 + options?: ExecuteToolFnOptions,
266 + modifiers?: ExecuteToolModifiers
267 ): Promise<string> {
268 + // Models occasionally emit tool args as a JSON string rather than an object (issue #2406).
269 + const toolArguments = normalizeToolArguments(tool.args, tool.name);
270 + if (typeof executionTarget !== 'string') {
271 + const result = await this.executeToolForTarget(
272 + executionTarget,
273 + tool.name,
274 + toolArguments,
275 + options,
276 + modifiers
277 + );
278 + return JSON.stringify(result);
279 + }
280 +
281 + // Keep direct execution on `executeTool`, which every supported @composio/core provides.
282 const payload: ToolExecuteParams = {
257 - // Models occasionally emit tool args as a JSON string rather than an object (issue #2406).
258 - arguments: normalizeToolArguments(tool.args, tool.name),
283 + arguments: toolArguments,
284 connectedAccountId: options?.connectedAccountId,
285 customAuthParams: options?.customAuthParams,
286 customConnectionData: options?.customConnectionData,
262 - userId: userId,
287 + userId: executionTarget,
288 };
289
290 const result = await this.executeTool(tool.name, payload, modifiers);
ts/packages/providers/google/test/google.test.ts
+70
@@ -248,4 +248,74 @@ describe('GoogleProvider', () => {
248 );
249 });
250 });
251 +
252 + describe('executeToolCall with a Tool Router session', () => {
253 + it('keeps user ID calls working on @composio/core releases without session helpers', async () => {
254 + // The peer range admits cores that predate executeToolForTarget.
255 + Object.defineProperty(provider, 'executeToolForTarget', { value: undefined });
256 +
257 + await provider.executeToolCall('test-user', { name: 'test-tool', args: {} });
258 +
259 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
260 + 'test-tool',
261 + expect.objectContaining({ userId: 'test-user' }),
262 + undefined
263 + );
264 + });
265 +
266 + it('executes through the session instead of the direct tools API', async () => {
267 + const session = {
268 + execute: vi.fn().mockResolvedValue({
269 + data: { result: 'session-success' },
270 + error: null,
271 + logId: 'log-session',
272 + }),
273 + };
274 +
275 + const result = await provider.executeToolCall(session, {
276 + name: 'COMPOSIO_SEARCH_TOOLS',
277 + args: { query: 'send an email' },
278 + });
279 +
280 + expect(session.execute).toHaveBeenCalledWith('COMPOSIO_SEARCH_TOOLS', {
281 + query: 'send an email',
282 + });
283 + expect(mockExecuteToolFn).not.toHaveBeenCalled();
284 + expect(JSON.parse(result)).toEqual({
285 + data: { result: 'session-success' },
286 + error: null,
287 + logId: 'log-session',
288 + successful: true,
289 + });
290 + });
291 +
292 + it('reports a failed session execution in the result', async () => {
293 + const session = {
294 + execute: vi.fn().mockResolvedValue({ data: {}, error: 'Tool failed', logId: 'log-fail' }),
295 + };
296 +
297 + const result = await provider.executeToolCall(session, {
298 + name: 'COMPOSIO_SEARCH_TOOLS',
299 + args: {},
300 + });
301 +
302 + expect(JSON.parse(result)).toMatchObject({ error: 'Tool failed', successful: false });
303 + });
304 +
305 + it('rejects direct execution options with a session', async () => {
306 + const session = { execute: vi.fn() };
307 +
308 + await expect(
309 + provider.executeToolCall(
310 + // @ts-expect-error direct execution options are not accepted with a session
311 + session,
312 + { name: 'COMPOSIO_SEARCH_TOOLS', args: {} },
313 + { connectedAccountId: 'conn-123' }
314 + )
315 + ).rejects.toThrow(
316 + 'Direct execution options and modifiers cannot be used with a Tool Router session'
317 + );
318 + expect(session.execute).not.toHaveBeenCalled();
319 + });
320 + });
321 });
ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+16 -3
@@ -396,7 +396,7 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
396 * This method processes tool calls from an OpenAI Responses request,
397 * executes each tool call, and returns the tool outputs for submission.
398 *
399 - * @param {string} userId - The user ID for authentication and tracking
399 + * @param {string | ToolCallSession} executionTarget - A user ID for direct tools or the session that produced session tools
400 * @param {OpenAI.Responses.Response} response - The Responses request object containing tool calls
401 * @param {ExecuteToolFnOptions} [options] - Optional execution options
402 * @param {ExecuteToolModifiers} [modifiers] - Optional execution modifiers
@@ -422,14 +422,27 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
422 * });
423 * ```
424 */
425 + async handleResponse(
426 + session: ToolCallSession,
427 + response: OpenAI.Responses.Response
428 + ): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]>;
429 async handleResponse(
430 userId: string,
431 response: OpenAI.Responses.Response,
432 options?: ExecuteToolFnOptions,
433 modifiers?: ExecuteToolModifiers
434 + ): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]>;
435 + async handleResponse(
436 + executionTarget: ToolCallExecutionTarget,
437 + response: OpenAI.Responses.Response,
438 + options?: ExecuteToolFnOptions,
439 + modifiers?: ExecuteToolModifiers
440 ): Promise<OpenAI.Responses.ResponseInputItem.FunctionCallOutput[]> {
441 const tool_calls = response.output?.filter(output => output.type === 'function_call') || [];
432 - const tool_outputs = await this.handleToolCalls(userId, tool_calls, options, modifiers);
433 - return tool_outputs;
442 + if (typeof executionTarget === 'string') {
443 + return this.handleToolCalls(executionTarget, tool_calls, options, modifiers);
444 + }
445 + this.assertToolCallExecutionOptions(executionTarget, options, modifiers);
446 + return this.handleToolCalls(executionTarget, tool_calls);
447 }
448 }
ts/packages/providers/openai/test/opeanai-responses.test.ts
+54
@@ -688,5 +688,59 @@ describe('OpenAIResponsesProvider', () => {
688 expect(handleToolCallsSpy).toHaveBeenCalledWith(userId, [], undefined, undefined);
689 expect(results).toEqual([]);
690 });
691 +
692 + it('executes the response tool calls through a Tool Router session', async () => {
693 + const session = {
694 + execute: vi.fn().mockResolvedValue({
695 + data: { result: 'session-success' },
696 + error: null,
697 + logId: 'log-session',
698 + }),
699 + };
700 + const response = {
701 + output: [
702 + { type: 'message', id: 'msg-1', content: [] },
703 + {
704 + id: 'fc-1',
705 + type: 'function_call',
706 + name: 'COMPOSIO_SEARCH_TOOLS',
707 + arguments: JSON.stringify({ query: 'send an email' }),
708 + call_id: 'call-1',
709 + },
710 + ],
711 + } as unknown as OpenAI.Responses.Response;
712 +
713 + const results = await provider.handleResponse(session, response);
714 +
715 + expect(session.execute).toHaveBeenCalledWith('COMPOSIO_SEARCH_TOOLS', {
716 + query: 'send an email',
717 + });
718 + expect(mockExecuteToolFn).not.toHaveBeenCalled();
719 + expect(results).toEqual([
720 + {
721 + call_id: 'call-1',
722 + type: 'function_call_output',
723 + output: JSON.stringify({
724 + data: { result: 'session-success' },
725 + error: null,
726 + logId: 'log-session',
727 + successful: true,
728 + }),
729 + status: 'completed',
730 + },
731 + ]);
732 + });
733 +
734 + it('rejects direct execution options with a session', async () => {
735 + const session = { execute: vi.fn() };
736 + const response = { output: [] } as unknown as OpenAI.Responses.Response;
737 +
738 + await expect(
739 + // @ts-expect-error direct execution options are not accepted with a session
740 + provider.handleResponse(session, response, { connectedAccountId: 'conn-123' })
741 + ).rejects.toThrow(
742 + 'Direct execution options and modifiers cannot be used with a Tool Router session'
743 + );
744 + });
745 });
746 });