@devries-cameron20 / composio-1 / commits / ce4b21336
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.

fix(providers): normalize string tool-call arguments across all providers (TS + Python) (#3514)

## Summary Models — and some MCP transports — occasionally emit tool-call arguments as a **JSON string instead of an object/dict**. The most visible trigger is `COMPOSIO_MULTI_EXECUTE_TOOL` on the Vercel AI SDK, where streaming fails with: > `messages.3.content.1.tool_use.input: Input should be a valid dictionary` Until now only a handful of providers guarded against this, each with its own slightly different inline check, leaving most providers vulnerable and behaviour inconsistent across the SDK. This PR centralizes the coercion into **one helper per language** and routes **every** provider through it, in both the TypeScript and Python SDKs. Closes https://github.com/ComposioHQ/composio/issues/2406 ## What changed **TypeScript** — new `normalizeToolArguments` in `@composio/core` (exported), used by every provider: `vercel`, `cloudflare`, `openai-agents`, `openai` (ChatCompletions + Responses), `anthropic`, `google`, `langchain`, `llamaindex`, `claude-agent-sdk`, `mastra`. **Python** — new `normalize_tool_arguments` in `composio.utils.shared`, used by every provider: `openai`, `openai-responses`, `anthropic`, `google`, `langchain`, `langgraph`, `crewai`, `autogen`, `llamaindex`, `gemini`, `google-adk`, `openai-agents`, `claude-agent-sdk`. Shared semantics (identical in both languages): | Input | Result | | --- | --- | | object / dict | returned unchanged | | JSON string | parsed to object | | empty / whitespace string | `{}` | | `null` / `undefined` / `None` | `{}` | | array, primitive, unparseable string, JSON that isn't an object | **typed error** (`ComposioInvalidToolArgumentsError` / `InvalidParams`) with the original parse error as cause | The typed error replaces the previous grab-bag of behaviours: a raw `SyntaxError`/`JSONDecodeError`, or — worse — silently forwarding a malformed string downstream. ## Why this supersedes the open PRs This consolidates and extends three open PRs that each addressed a slice of the problem inconsistently. Their authors are credited as co-authors on the relevant commits: - **#3489** (LlamaIndex + Claude Agent SDK, TS) — @srijanarya - **#3438** (Anthropic, Google, LangChain, TS) — @aptsalt - **#3437** (Google ADK empty schemas + name fix, Python) — @pragnyanramtha — its empty-`input_parameters` / missing-description handling and the `gemini` → `google_adk` provider-name fix are folded in here. Compared to the three combined, this PR additionally: covers **every** provider in **both** SDKs (not a subset of one), defines a single source of truth instead of per-provider snippets, normalizes empty/`null` payloads to `{}`, and raises an actionable typed error instead of leaking `SyntaxError` or forwarding a bad string. ## Tests - Exhaustive unit tests for both helpers (object passthrough, JSON-string parse, empty/null → `{}`, malformed/non-object → typed error). - Per-provider regression tests across the touched TypeScript providers (string path, malformed-string path, empty-payload path). - Full `@composio/core` + touched-provider TS suites pass; `typecheck` and `lint` clean. Python `ruff` clean and new test green. ## Changeset Patch bump for all affected TypeScript packages (`@composio/core` + the providers). Python follows its own versioning, so no changeset there. --------- Co-authored-by: srijanarya <74669415+srijanarya@users.noreply.github.com> Co-authored-by: Deepak Singh Kandari <deepaksinghkandari07@gmail.com> Co-authored-by: Pragnyan Ramtha <pragnyanramtha@gmail.com>

Alberto Schiabel committed Jun 16, 2026 at 12:49 UTC ce4b213361659caa959d88ce07aed2143eb575de
40 files changed +587 -39
.changeset/normalize-tool-arguments-2406.md new
+28
@@ -0,0 +1,28 @@
1 +---
2 +'@composio/core': patch
3 +'@composio/vercel': patch
4 +'@composio/openai-agents': patch
5 +'@composio/cloudflare': patch
6 +'@composio/anthropic': patch
7 +'@composio/google': patch
8 +'@composio/langchain': patch
9 +'@composio/llamaindex': patch
10 +'@composio/claude-agent-sdk': patch
11 +'@composio/mastra': patch
12 +'@composio/openai': patch
13 +---
14 +
15 +fix(providers): normalize string tool-call arguments across all providers
16 +
17 +Models occasionally emit tool-call arguments as a JSON string instead of an
18 +object (most visibly with `COMPOSIO_MULTI_EXECUTE_TOOL` on the Vercel AI SDK),
19 +which broke downstream validation with errors like
20 +`tool_use.input: Input should be a valid dictionary`.
21 +
22 +`@composio/core` now exposes a single `normalizeToolArguments` helper, and every
23 +provider routes model-supplied arguments through it. Object payloads pass
24 +through unchanged, JSON strings are parsed, empty/`null` payloads become `{}`,
25 +and anything that cannot resolve to an object throws a typed
26 +`ComposioInvalidToolArgumentsError` instead of a raw `SyntaxError` or a silently
27 +forwarded malformed string. This replaces the inconsistent per-provider guards
28 +that previously existed only in vercel, cloudflare and openai-agents.
python/composio/core/provider/_openai.py
+4 -1
@@ -21,6 +21,7 @@ from openai.types.shared_params.function_parameters import FunctionParameters
21
22 from composio.core.provider import NonAgenticProvider
23 from composio.types import Modifiers, Tool, ToolExecutionResponse
24 +from composio.utils.shared import normalize_tool_arguments
25
26 OpenAITool: t.TypeAlias = ChatCompletionToolParam
27 OpenAIToolCollection: t.TypeAlias = t.List[OpenAITool]
@@ -57,9 +58,11 @@ class OpenAIProvider(
58 :param user_id: User ID to use for executing the function call.
59 :return: Object containing output data from the tool call.
60 """
61 + # OpenAI always serializes tool arguments as a JSON string; normalize
62 + # tolerates empty / object-shaped payloads too (issue #2406).
63 return self.execute_tool(
64 slug=tool_call.function.name,
62 - arguments=json.loads(tool_call.function.arguments),
65 + arguments=normalize_tool_arguments(tool_call.function.arguments),
66 modifiers=modifiers,
67 user_id=user_id,
68 )
python/composio/core/provider/_openai_responses.py
+4 -2
@@ -4,7 +4,6 @@ OpenAI Responses API provider implementation.
4
5 from __future__ import annotations
6
7 -import json
7 import typing as t
8
9 from openai.types.responses.response import Response
@@ -12,6 +11,7 @@ from openai.types.responses.response_output_item import ResponseFunctionToolCall
11
12 from composio.core.provider import NonAgenticProvider
13 from composio.types import Modifiers, Tool, ToolExecutionResponse
14 +from composio.utils.shared import normalize_tool_arguments
15
16 # Responses API uses a flattened tool structure
17 ResponsesTool = t.Dict[str, t.Any]
@@ -49,8 +49,10 @@ class OpenAIResponsesProvider(
49 :param modifiers: Optional modifiers for tool execution.
50 :return: Object containing output data from the tool call.
51 """
52 + # OpenAI always serializes tool arguments as a JSON string; normalize
53 + # tolerates empty / object-shaped payloads too (issue #2406).
54 slug = tool_call.name
53 - arguments = json.loads(tool_call.arguments)
55 + arguments = normalize_tool_arguments(tool_call.arguments)
56
57 return self.execute_tool(
58 slug=slug,
python/composio/utils/shared.py
+49
@@ -3,6 +3,7 @@ Shared utils.
3 """
4
5 import copy
6 +import json
7 import keyword
8 import typing as t
9 import uuid
@@ -11,6 +12,7 @@ from inspect import Parameter
12 from pydantic import BaseModel, Field, create_model
13 from pydantic.fields import FieldInfo
14
15 +from composio.exceptions import InvalidParams
16 from composio.utils.logging import get as get_logger
17 from composio.utils.schema_converter import (
18 CONTAINER_TYPE,
@@ -36,6 +38,7 @@ __all__ = [
38 "generate_request_id",
39 "substitute_reserved_python_keywords",
40 "reinstate_reserved_python_keywords",
41 + "normalize_tool_arguments",
42 ]
43
44 reserved_names = ["validate"]
@@ -43,6 +46,52 @@ reserved_names = ["validate"]
46 _OBJ_MARKER = "-_object_-"
47
48
49 +def normalize_tool_arguments(arguments: t.Any) -> t.Dict[str, t.Any]:
50 + """Coerce model-supplied tool arguments into a dict.
51 +
52 + Models (and some MCP transports) occasionally emit tool-call arguments as a
53 + JSON string instead of a dict, which breaks execution with errors such as
54 + ``tool_use.input: Input should be a valid dictionary``. This is the single
55 + coercion every provider routes through so behaviour is identical everywhere.
56 +
57 + See https://github.com/ComposioHQ/composio/issues/2406.
58 +
59 + - ``None`` becomes ``{}`` (some models send no arguments for no-arg tools).
60 + - A dict is returned unchanged.
61 + - A string is JSON-parsed; an empty / whitespace-only string becomes ``{}``.
62 + - Anything that does not resolve to a dict (lists, primitives, unparseable
63 + strings, JSON that parses to a non-object) raises :class:`InvalidParams`.
64 +
65 + :param arguments: Raw arguments as received from the model / framework.
66 + :return: The normalized arguments as a dict.
67 + :raises InvalidParams: If the arguments cannot be resolved to a dict.
68 + """
69 + if arguments is None:
70 + return {}
71 +
72 + if isinstance(arguments, str):
73 + stripped = arguments.strip()
74 + if not stripped:
75 + return {}
76 + try:
77 + parsed = json.loads(stripped)
78 + except json.JSONDecodeError as e:
79 + raise InvalidParams(
80 + f"Tool arguments were provided as a string that is not valid JSON: {e}"
81 + ) from e
82 + return _as_dict(parsed)
83 +
84 + return _as_dict(arguments)
85 +
86 +
87 +def _as_dict(value: t.Any) -> t.Dict[str, t.Any]:
88 + if isinstance(value, dict):
89 + return value
90 + raise InvalidParams(
91 + f"Tool arguments must resolve to an object, received {type(value).__name__}"
92 + )
93 +
94 +
95 def _make_safe_name(name: str) -> str:
96 """Append ``_rs`` to a Python keyword so it can be used as a parameter name."""
97 return f"{name}_rs"
python/providers/anthropic/composio_anthropic/provider.py
+3 -1
@@ -7,6 +7,7 @@ from anthropic.types.tool_use_block import ToolUseBlock
7
8 from composio.core.provider import NonAgenticProvider
9 from composio.types import Modifiers, Tool, ToolExecutionResponse
10 +from composio.utils.shared import normalize_tool_arguments
11
12
13 class AnthropicProvider(
@@ -41,9 +42,10 @@ class AnthropicProvider(
42 :param modifiers: Modifiers to use for executing function calls.
43 :return: Object containing output data from the tool call.
44 """
45 + # Models occasionally emit tool input as a JSON string rather than a dict (issue #2406).
46 return self.execute_tool(
47 slug=tool_call.name,
46 - arguments=t.cast(t.Dict, tool_call.input),
48 + arguments=normalize_tool_arguments(tool_call.input),
49 modifiers=modifiers,
50 user_id=user_id,
51 )
python/providers/autogen/composio_autogen/provider.py
+5 -1
@@ -12,6 +12,7 @@ from composio.core.provider import AgenticProvider
12 from composio.core.provider.agentic import AgenticProviderExecuteFn
13 from composio.utils.shared import (
14 get_signature_format_from_schema_params,
15 + normalize_tool_arguments,
16 reinstate_reserved_python_keywords,
17 substitute_reserved_python_keywords,
18 )
@@ -78,7 +79,10 @@ class AutogenProvider(
79 kwargs = reinstate_reserved_python_keywords(
80 request=kwargs, keywords=keywords
81 )
81 - return execute_tool(slug=tool.slug, arguments=kwargs)
82 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
83 + return execute_tool(
84 + slug=tool.slug, arguments=normalize_tool_arguments(kwargs)
85 + )
86
87 # Create function with proper signature
88 function = types.FunctionType(
python/providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py
+3 -1
@@ -21,6 +21,7 @@ from claude_agent_sdk import (
21 from composio.core.provider import AgenticProvider
22 from composio.core.provider.agentic import AgenticProviderExecuteFn
23 from composio.types import Tool
24 +from composio.utils.shared import normalize_tool_arguments
25
26
27 class ClaudeAgentSDKProvider(
@@ -104,7 +105,8 @@ class ClaudeAgentSDKProvider(
105 result = await asyncio.to_thread(
106 execute_tool,
107 tool.slug,
107 - args,
108 + # Models occasionally emit tool input as a JSON string (issue #2406).
109 + normalize_tool_arguments(args),
110 )
111 # Format the result for Claude Agent SDK
112 result_text = result if isinstance(result, str) else json.dumps(result)
python/providers/crewai/composio_crewai/providers.py
+5 -2
@@ -6,7 +6,7 @@ from crewai.tools import BaseTool
6 from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
7 from composio.types import Tool
8 from composio.utils.pydantic import parse_pydantic_error
9 -from composio.utils.shared import json_schema_to_model
9 +from composio.utils.shared import json_schema_to_model, normalize_tool_arguments
10
11
12 class CrewAIProvider(AgenticProvider[BaseTool, list[BaseTool]], name="crewai"):
@@ -24,7 +24,10 @@ class CrewAIProvider(AgenticProvider[BaseTool, list[BaseTool]], name="crewai"):
24 class Wrapper(BaseTool):
25 def _run(self, **kwargs):
26 try:
27 - return execute_tool(slug=tool.slug, arguments=kwargs)
27 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
28 + return execute_tool(
29 + slug=tool.slug, arguments=normalize_tool_arguments(kwargs)
30 + )
31 except pydantic.ValidationError as e:
32 return {
33 "successful": False,
python/providers/gemini/composio_gemini/provider.py
+6 -2
@@ -14,6 +14,7 @@ from composio.core.provider import AgenticProvider
14 from composio.core.provider.agentic import AgenticProviderExecuteFn
15 from composio.utils.shared import (
16 get_pydantic_signature_format_from_schema_params,
17 + normalize_tool_arguments,
18 reinstate_reserved_python_keywords,
19 substitute_reserved_python_keywords,
20 )
@@ -109,7 +110,8 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
110 kwargs = reinstate_reserved_python_keywords(
111 request=kwargs, keywords=keywords
112 )
112 - result = execute_tool(tool.slug, kwargs)
113 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
114 + result = execute_tool(tool.slug, normalize_tool_arguments(kwargs))
115 return _process_execution_result(result)
116
117 # Create a real function object (passes inspect.isfunction)
@@ -188,7 +190,9 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
190 if fc.name not in self._executors:
191 continue
192
191 - result = self._executors[fc.name](slug=fc.name, arguments=dict(fc.args))
193 + result = self._executors[fc.name](
194 + slug=fc.name, arguments=normalize_tool_arguments(dict(fc.args))
195 + )
196 processed = _process_execution_result(result)
197
198 function_responses.append(
python/providers/google/composio_google/provider.py
+5 -5
@@ -14,6 +14,7 @@ from vertexai.generative_models import (
14
15 from composio.core.provider import NonAgenticProvider
16 from composio.types import Modifiers, Tool, ToolExecutionResponse
17 +from composio.utils.shared import normalize_tool_arguments
18
19
20 def _convert_map_composite(obj):
@@ -69,13 +70,12 @@ class GoogleProvider(
70 :param user_id: User ID to use for executing the function call.
71 :return: Object containing output data from the function call.
72 """
73 + # Gemini returns args as a MapComposite; normalize after converting to a
74 + # plain dict so a stringified payload is handled uniformly too (issue #2406).
75 return self.execute_tool(
76 slug=function_call.name,
74 - arguments=t.cast(
75 - dict,
76 - _convert_map_composite(
77 - function_call.args,
78 - ),
77 + arguments=normalize_tool_arguments(
78 + _convert_map_composite(function_call.args)
79 ),
80 modifiers=modifiers,
81 user_id=user_id,
python/providers/google_adk/composio_google_adk/provider.py
+22 -5
@@ -8,10 +8,11 @@ from composio.client.types import Tool
8 from composio.core.provider import AgenticProvider
9 from composio.core.provider.agentic import AgenticProviderExecuteFn
10 from composio.utils.openapi import function_signature_from_jsonschema
11 +from composio.utils.shared import normalize_tool_arguments
12
13
14 class GoogleAdkProvider(
14 - AgenticProvider[FunctionTool, list[FunctionTool]], name="gemini"
15 + AgenticProvider[FunctionTool, list[FunctionTool]], name="google_adk"
16 ):
17 """
18 Composio toolset for Google ADK framework.
@@ -26,9 +27,22 @@ class GoogleAdkProvider(
27 ) -> FunctionTool:
28 """Wraps composio tool as Google Genai SDK compatible function calling object."""
29
29 - docstring = tool.description
30 + input_parameters = t.cast(
31 + t.Dict[str, t.Any],
32 + tool.input_parameters
33 + or {
34 + "type": "object",
35 + "properties": {},
36 + "required": [],
37 + },
38 + )
39 + properties = t.cast(
40 + t.Dict[str, t.Dict[str, t.Any]],
41 + input_parameters.get("properties", {}),
42 + )
43 + docstring = tool.description or f"Execute {tool.slug}"
44 docstring += "\nArgs:"
31 - for _param, _schema in tool.input_parameters["properties"].items(): # type: ignore
45 + for _param, _schema in properties.items():
46 docstring += "\n "
47 docstring += _param + ": " + _schema.get("description", _param.title())
48
@@ -36,7 +50,10 @@ class GoogleAdkProvider(
50 docstring += "\n A dictionary containing response from the action"
51
52 def _execute(**kwargs: t.Any) -> t.Dict:
39 - return execute_tool(slug=tool.slug, arguments=kwargs)
53 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
54 + return execute_tool(
55 + slug=tool.slug, arguments=normalize_tool_arguments(kwargs)
56 + )
57
58 function = types.FunctionType(
59 code=_execute.__code__,
@@ -45,7 +62,7 @@ class GoogleAdkProvider(
62 closure=_execute.__closure__,
63 )
64 parameters = function_signature_from_jsonschema(
48 - schema=tool.input_parameters,
65 + schema=input_parameters,
66 skip_default=self.skip_default,
67 )
68 setattr(function, "__signature__", Signature(parameters=parameters))
python/providers/langchain/composio_langchain/provider.py
+3 -1
@@ -13,6 +13,7 @@ from composio.utils.pydantic import parse_pydantic_error
13 from composio.utils.shared import (
14 get_signature_format_from_schema_params,
15 json_schema_to_model,
16 + normalize_tool_arguments,
17 reinstate_reserved_python_keywords,
18 substitute_reserved_python_keywords,
19 )
@@ -51,7 +52,8 @@ class LangchainProvider(
52 request=kwargs,
53 keywords=keywords,
54 )
54 - return execute_tool(tool.slug, kwargs)
55 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
56 + return execute_tool(tool.slug, normalize_tool_arguments(kwargs))
57
58 action_func = types.FunctionType(
59 function.__code__,
python/providers/langgraph/composio_langgraph/provider.py
+3 -1
@@ -13,6 +13,7 @@ from composio.utils.pydantic import parse_pydantic_error
13 from composio.utils.shared import (
14 get_signature_format_from_schema_params,
15 json_schema_to_model,
16 + normalize_tool_arguments,
17 reinstate_reserved_python_keywords,
18 substitute_reserved_python_keywords,
19 )
@@ -47,7 +48,8 @@ class LanggraphProvider(
48 kwargs = reinstate_reserved_python_keywords(
49 request=kwargs, keywords=keywords
50 )
50 - return execute_tool(tool, kwargs)
51 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
52 + return execute_tool(tool, normalize_tool_arguments(kwargs))
53
54 action_func = types.FunctionType(
55 function.__code__,
python/providers/llamaindex/composio_llamaindex/provider.py
+5 -1
@@ -10,6 +10,7 @@ from composio.core.provider import AgenticProvider, AgenticProviderExecuteFn
10 from composio.types import Tool
11 from composio.utils.shared import (
12 get_signature_format_from_schema_params,
13 + normalize_tool_arguments,
14 reinstate_reserved_python_keywords,
15 substitute_reserved_python_keywords,
16 )
@@ -40,7 +41,10 @@ class LlamaIndexProvider(
41 kwargs = reinstate_reserved_python_keywords(
42 request=kwargs, keywords=keywords
43 )
43 - return execute_tool(slug=tool.slug, arguments=kwargs)
44 + # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
45 + return execute_tool(
46 + slug=tool.slug, arguments=normalize_tool_arguments(kwargs)
47 + )
48
49 action_func = types.FunctionType(
50 function.__code__,
python/providers/openai_agents/composio_openai_agents/provider.py
+3 -1
@@ -9,6 +9,7 @@ from composio.core.provider import AgenticProvider
9 from composio.core.provider.agentic import AgenticProviderExecuteFn
10 from composio.types import Tool
11 from composio.utils.pydantic import parse_pydantic_error
12 +from composio.utils.shared import normalize_tool_arguments
13
14
15 # Recursively remove 'examples' keys from the schema properties
@@ -86,7 +87,8 @@ class OpenAIAgentsProvider(
87 await asyncio.to_thread( # Running a thread since `execute_tool` is not async
88 execute_tool,
89 slug=tool.slug,
89 - arguments=json.loads(payload) if payload else {},
90 + # Models occasionally emit arguments as a JSON string (issue #2406).
91 + arguments=normalize_tool_arguments(payload),
92 )
93 )
94 )
python/tests/test_normalize_tool_arguments.py new
+44
@@ -0,0 +1,44 @@
1 +"""Tests for normalize_tool_arguments (issue #2406)."""
2 +
3 +import pytest
4 +
5 +from composio.exceptions import InvalidParams
6 +from composio.utils.shared import normalize_tool_arguments
7 +
8 +pytestmark = pytest.mark.core
9 +
10 +
11 +class TestNormalizeToolArguments:
12 + def test_dict_is_returned_unchanged(self):
13 + payload = {"to": "a@b.com", "subject": "hi"}
14 + assert normalize_tool_arguments(payload) is payload
15 +
16 + def test_json_string_is_parsed(self):
17 + payload = {"to": "a@b.com", "subject": "hi", "body": "Hello"}
18 + assert (
19 + normalize_tool_arguments(
20 + '{"to": "a@b.com", "subject": "hi", "body": "Hello"}'
21 + )
22 + == payload
23 + )
24 +
25 + def test_none_becomes_empty_dict(self):
26 + assert normalize_tool_arguments(None) == {}
27 +
28 + @pytest.mark.parametrize("value", ["", " ", "\n\t "])
29 + def test_empty_string_becomes_empty_dict(self, value):
30 + assert normalize_tool_arguments(value) == {}
31 +
32 + def test_malformed_json_string_raises(self):
33 + with pytest.raises(InvalidParams, match="not valid JSON"):
34 + normalize_tool_arguments('{"to": "a@b.com"')
35 +
36 + @pytest.mark.parametrize("value", ["[1, 2, 3]", "42", '"hello"'])
37 + def test_non_object_json_raises(self, value):
38 + with pytest.raises(InvalidParams, match="must resolve to an object"):
39 + normalize_tool_arguments(value)
40 +
41 + @pytest.mark.parametrize("value", [[1, 2, 3], 42, True])
42 + def test_non_dict_value_raises(self, value):
43 + with pytest.raises(InvalidParams, match="must resolve to an object"):
44 + normalize_tool_arguments(value)
ts/packages/core/src/errors/ToolErrors.ts
+18
@@ -7,6 +7,7 @@ export const ToolErrorCodes = {
7 TOOL_NOT_FOUND: 'TOOL_NOT_FOUND',
8 INVALID_MODIFIER: 'INVALID_MODIFIER',
9 TOOL_EXECUTION_ERROR: 'TOOL_EXECUTION_ERROR',
10 + INVALID_TOOL_ARGUMENTS: 'INVALID_TOOL_ARGUMENTS',
11 INVALID_EXECUTE_FUNCTION: 'INVALID_EXECUTE_FUNCTION',
12 GLOBAL_EXECUTE_TOOL_FN_NOT_SET: 'GLOBAL_EXECUTE_TOOL_FN_NOT_SET',
13 TOOL_VERSION_REQUIRED: 'TOOL_VERSION_REQUIRED',
@@ -76,6 +77,23 @@ export class ComposioToolExecutionError extends ComposioError {
77 }
78 }
79
80 +export class ComposioInvalidToolArgumentsError extends ComposioError {
81 + constructor(
82 + message: string = 'Invalid tool arguments',
83 + options: Omit<ComposioErrorOptions, 'code'> = {}
84 + ) {
85 + super(message, {
86 + ...options,
87 + code: ToolErrorCodes.INVALID_TOOL_ARGUMENTS,
88 + possibleFixes: options.possibleFixes || [
89 + 'Tool arguments must be a JSON object (or a string that parses to one)',
90 + 'If a model emitted the arguments as a string, ensure it is valid JSON',
91 + ],
92 + });
93 + this.name = 'ComposioInvalidToolArgumentsError';
94 + }
95 +}
96 +
97 export class ComposioInvalidExecuteFunctionError extends ComposioError {
98 constructor(
99 message: string = 'Invalid execute function',
ts/packages/core/src/index.ts
+1
@@ -15,6 +15,7 @@ export type {
15 UnresolvedRefStrategy,
16 } from './utils/jsonSchema';
17 export { getExtensionFromMimeType } from './utils/mime';
18 +export { normalizeToolArguments } from './utils/toolArguments';
19 export { AuthScheme } from './models/AuthScheme';
20 export { MCP } from './models/MCP';
21 export { RemoteFile } from './models/RemoteFile';
ts/packages/core/src/provider/OpenAIProvider.ts
+4 -1
@@ -15,6 +15,7 @@ import logger from '../utils/logger';
15 import { ExecuteToolModifiers } from '../types/modifiers.types';
16 import { ExecuteToolFnOptions } from '../types/provider.types';
17 import { McpUrlResponse, McpServerGetResponse } from '../types/mcp.types';
18 +import { normalizeToolArguments } from '../utils/toolArguments';
19
20 export type OpenAiTool = OpenAI.ChatCompletionTool;
21 export type OpenAiToolCollection = Array<OpenAiTool>;
@@ -184,7 +185,9 @@ export class OpenAIProvider extends BaseNonAgenticProvider<
185 modifiers?: ExecuteToolModifiers
186 ): Promise<string> {
187 const payload: ToolExecuteParams = {
187 - arguments: JSON.parse(tool.function.arguments),
188 + // OpenAI always serializes tool arguments as a JSON string; normalize tolerates
189 + // empty / object-shaped payloads too (issue #2406).
190 + arguments: normalizeToolArguments(tool.function.arguments, tool.function.name),
191 connectedAccountId: options?.connectedAccountId,
192 customAuthParams: options?.customAuthParams,
193 customConnectionData: options?.customConnectionData,
ts/packages/core/src/utils/toolArguments.ts new
+73
@@ -0,0 +1,73 @@
1 +/**
2 + * Tool-argument normalization.
3 + *
4 + * Models (and MCP transports) occasionally emit tool-call arguments as a JSON
5 + * *string* instead of an object. `COMPOSIO_MULTI_EXECUTE_TOOL` and Vercel AI
6 + * SDK streaming are common triggers. Forwarding that raw string to execution
7 + * surfaces opaque downstream errors such as
8 + * `tool_use.input: Input should be a valid dictionary`.
9 + *
10 + * `normalizeToolArguments` is the single coercion every provider routes through
11 + * so the behaviour is identical everywhere instead of being re-implemented
12 + * (inconsistently) per provider.
13 + *
14 + * @see https://github.com/ComposioHQ/composio/issues/2406
15 + */
16 +import { ComposioInvalidToolArgumentsError } from '../errors/ToolErrors';
17 +
18 +/**
19 + * Coerce model-supplied tool arguments into a plain object.
20 + *
21 + * Rules:
22 + * - `null` / `undefined` → `{}` (some models send no arguments for no-arg tools).
23 + * - A plain object is returned unchanged.
24 + * - A string is JSON-parsed; an empty / whitespace-only string becomes `{}`.
25 + * - Anything that does not resolve to a plain object (arrays, primitives,
26 + * unparseable strings, JSON that parses to a non-object) throws a typed
27 + * {@link ComposioInvalidToolArgumentsError} so callers get an actionable
28 + * message instead of a raw `SyntaxError` or a silent malformed payload.
29 + *
30 + * @param input - Raw arguments as received from the model / framework.
31 + * @param toolSlug - Optional tool slug, used to enrich the error message.
32 + * @returns The normalized arguments as a `Record<string, unknown>`.
33 + */
34 +export function normalizeToolArguments(input: unknown, toolSlug?: string): Record<string, unknown> {
35 + if (input === null || input === undefined) {
36 + return {};
37 + }
38 +
39 + if (typeof input === 'string') {
40 + const trimmed = input.trim();
41 + if (trimmed === '') {
42 + return {};
43 + }
44 +
45 + let parsed: unknown;
46 + try {
47 + parsed = JSON.parse(trimmed);
48 + } catch (cause) {
49 + throw new ComposioInvalidToolArgumentsError(
50 + `${describeTool(toolSlug)} received arguments as a string that is not valid JSON`,
51 + { cause: cause instanceof Error ? cause : undefined }
52 + );
53 + }
54 + return assertPlainObject(parsed, toolSlug);
55 + }
56 +
57 + return assertPlainObject(input, toolSlug);
58 +}
59 +
60 +function assertPlainObject(value: unknown, toolSlug?: string): Record<string, unknown> {
61 + if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
62 + return value as Record<string, unknown>;
63 + }
64 +
65 + const actual = Array.isArray(value) ? 'array' : typeof value;
66 + throw new ComposioInvalidToolArgumentsError(
67 + `${describeTool(toolSlug)} expected arguments to be an object, received ${actual}`
68 + );
69 +}
70 +
71 +function describeTool(toolSlug?: string): string {
72 + return toolSlug ? `Tool '${toolSlug}'` : 'Tool';
73 +}
ts/packages/core/test/provider/openai-provider.test.ts
+16
@@ -108,6 +108,22 @@ describe('OpenAIProvider', () => {
108 expect(result).toBe(JSON.stringify({ result: 'success' }));
109 });
110
111 + it('should coerce empty-string arguments to an empty object (issue #2406)', async () => {
112 + const toolCall = {
113 + id: 'call-123',
114 + type: 'function',
115 + function: { name: 'test-tool', arguments: '' },
116 + } as OpenAI.ChatCompletionMessageFunctionToolCall;
117 +
118 + await provider.executeToolCall('test-user', toolCall);
119 +
120 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
121 + 'test-tool',
122 + expect.objectContaining({ arguments: {} }),
123 + undefined
124 + );
125 + });
126 +
127 it('should pass options to executeTool', async () => {
128 const userId = 'test-user';
129 const toolCall = {
ts/packages/core/test/utils/toolArguments.test.ts new
+66
@@ -0,0 +1,66 @@
1 +import { describe, it, expect } from 'vitest';
2 +import { normalizeToolArguments } from '../../src/utils/toolArguments';
3 +import { ComposioInvalidToolArgumentsError } from '../../src/errors/ToolErrors';
4 +
5 +describe('normalizeToolArguments (issue #2406)', () => {
6 + it('returns a plain object unchanged', () => {
7 + const input = { to: 'a@b.com', subject: 'hi' };
8 + expect(normalizeToolArguments(input)).toBe(input);
9 + });
10 +
11 + it('parses a stringified JSON object into an object', () => {
12 + const params = { to: 'a@b.com', subject: 'hi', body: 'Hello' };
13 + expect(normalizeToolArguments(JSON.stringify(params))).toEqual(params);
14 + });
15 +
16 + it.each([null, undefined])('coerces %s to an empty object', value => {
17 + expect(normalizeToolArguments(value)).toEqual({});
18 + });
19 +
20 + it.each(['', ' ', '\n\t '])(
21 + 'coerces an empty/whitespace string %j to an empty object',
22 + value => {
23 + expect(normalizeToolArguments(value)).toEqual({});
24 + }
25 + );
26 +
27 + it('throws a typed error when the string is not valid JSON', () => {
28 + expect(() => normalizeToolArguments('{"to": "a@b.com"', 'GMAIL_SEND')).toThrow(
29 + ComposioInvalidToolArgumentsError
30 + );
31 + try {
32 + normalizeToolArguments('not json at all', 'GMAIL_SEND');
33 + } catch (error) {
34 + expect(error).toBeInstanceOf(ComposioInvalidToolArgumentsError);
35 + expect((error as Error).message).toContain("Tool 'GMAIL_SEND'");
36 + // The original SyntaxError is preserved as the cause for debugging.
37 + expect((error as { cause?: unknown }).cause).toBeInstanceOf(SyntaxError);
38 + }
39 + });
40 +
41 + it.each([
42 + ['a JSON array string', '[1, 2, 3]'],
43 + ['a JSON number string', '42'],
44 + ['a JSON string literal', '"hello"'],
45 + ])('throws when the parsed JSON %s is not an object', (_label, value) => {
46 + expect(() => normalizeToolArguments(value)).toThrow(ComposioInvalidToolArgumentsError);
47 + });
48 +
49 + it.each([
50 + ['an array', [1, 2, 3]],
51 + ['a number', 42],
52 + ['a boolean', true],
53 + ])('throws when given %s directly', (_label, value) => {
54 + expect(() => normalizeToolArguments(value)).toThrow(ComposioInvalidToolArgumentsError);
55 + });
56 +
57 + it('mentions the tool slug in the error message when provided', () => {
58 + expect(() => normalizeToolArguments(42, 'SLACK_SEND_MESSAGE')).toThrow(
59 + /Tool 'SLACK_SEND_MESSAGE'/
60 + );
61 + });
62 +
63 + it('falls back to a generic label when no slug is provided', () => {
64 + expect(() => normalizeToolArguments(42)).toThrow(/^.*\bTool expected arguments/);
65 + });
66 +});
ts/packages/providers/anthropic/src/index.ts
+3 -1
@@ -15,6 +15,7 @@ import {
15 ToolExecuteParams,
16 logger,
17 McpUrlResponse,
18 + normalizeToolArguments,
19 } from '@composio/core';
20 import Anthropic from '@anthropic-ai/sdk';
21 import { AnthropicTool, InputSchema } from './types';
@@ -211,7 +212,8 @@ export class AnthropicProvider extends BaseNonAgenticProvider<
212 modifiers?: ExecuteToolModifiers
213 ): Promise<string> {
214 const payload: ToolExecuteParams = {
214 - arguments: toolUse.input,
215 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
216 + arguments: normalizeToolArguments(toolUse.input, toolUse.name),
217 connectedAccountId: options?.connectedAccountId,
218 customAuthParams: options?.customAuthParams,
219 customConnectionData: options?.customConnectionData,
ts/packages/providers/anthropic/test/anthropic.test.ts
+31
@@ -172,6 +172,37 @@ describe('AnthropicProvider', () => {
172 expect(result).toBe(JSON.stringify({ result: 'success' }));
173 });
174
175 + it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
176 + const params = { input: 'test-value' };
177 + const toolUse: AnthropicToolUseBlock = {
178 + type: 'tool_use',
179 + id: 'tu_123',
180 + name: 'test-tool',
181 + input: JSON.stringify(params) as unknown as Record<string, unknown>,
182 + };
183 +
184 + await provider.executeToolCall('test-user', toolUse);
185 +
186 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
187 + 'test-tool',
188 + expect.objectContaining({ arguments: params }),
189 + undefined
190 + );
191 + });
192 +
193 + it('should throw a typed error for a malformed-JSON string input (issue #2406)', async () => {
194 + const toolUse: AnthropicToolUseBlock = {
195 + type: 'tool_use',
196 + id: 'tu_123',
197 + name: 'test-tool',
198 + input: '{"input":' as unknown as Record<string, unknown>,
199 + };
200 +
201 + await expect(provider.executeToolCall('test-user', toolUse)).rejects.toThrow(
202 + /not valid JSON/
203 + );
204 + });
205 +
206 it('should pass options to executeTool', async () => {
207 const userId = 'test-user';
208 const toolUse: AnthropicToolUseBlock = {
ts/packages/providers/claude-agent-sdk/src/index.ts
+6 -1
@@ -15,6 +15,7 @@ import {
15 McpUrlResponse,
16 McpServerGetResponse,
17 jsonSchemaToZodSchema,
18 + normalizeToolArguments,
19 } from '@composio/core';
20 import {
21 tool as sdkTool,
@@ -114,7 +115,11 @@ export class ClaudeAgentSDKProvider extends BaseAgenticProvider<
115 inputZodShape,
116 async args => {
117 try {
117 - const result = await executeTool(composioTool.slug, args);
118 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
119 + const result = await executeTool(
120 + composioTool.slug,
121 + normalizeToolArguments(args, composioTool.slug)
122 + );
123 return {
124 content: [
125 {
ts/packages/providers/claude-agent-sdk/test/claude-agent-sdk.test.ts
+23
@@ -173,6 +173,29 @@ describe('ClaudeAgentSDKProvider', () => {
173 });
174 });
175
176 + it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
177 + provider.wrapTool(mockTool, mockExecuteToolFn);
178 + const handler = (tool as any).mock.calls[0][3];
179 +
180 + const params = { to: 'test@example.com', subject: 'Test', body: 'Hello' };
181 + await handler(JSON.stringify(params));
182 +
183 + expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
184 + });
185 +
186 + it('should surface a typed error for a malformed-JSON string input (issue #2406)', async () => {
187 + provider.wrapTool(mockTool, mockExecuteToolFn);
188 + const handler = (tool as any).mock.calls[0][3];
189 +
190 + const result = await handler('{"to":');
191 +
192 + expect(mockExecuteToolFn).not.toHaveBeenCalled();
193 + expect(JSON.parse(result.content[0].text)).toMatchObject({
194 + successful: false,
195 + error: expect.stringContaining('not valid JSON'),
196 + });
197 + });
198 +
199 it('should handle string results from tool execution', async () => {
200 mockExecuteToolFn.mockResolvedValueOnce('Simple string result');
201 provider.wrapTool(mockTool, mockExecuteToolFn);
ts/packages/providers/cloudflare/src/index.ts
+3 -1
@@ -18,6 +18,7 @@ import {
18 ExecuteToolFnOptions,
19 McpUrlResponse,
20 McpServerGetResponse,
21 + normalizeToolArguments,
22 } from '@composio/core';
23
24 type AiToolCollection = Record<string, AiTextGenerationToolInput>;
@@ -230,7 +231,8 @@ export class CloudflareProvider extends BaseNonAgenticProvider<
231 modifiers?: ExecuteToolModifiers
232 ): Promise<string> {
233 const payload: ToolExecuteParams = {
233 - arguments: typeof tool.arguments === 'string' ? JSON.parse(tool.arguments) : tool.arguments,
234 + // Models occasionally emit tool arguments as a JSON string rather than an object (issue #2406).
235 + arguments: normalizeToolArguments(tool.arguments, tool.name),
236 connectedAccountId: options.connectedAccountId,
237 customAuthParams: options.customAuthParams,
238 customConnectionData: options.customConnectionData,
ts/packages/providers/google/src/index.ts
+3 -1
@@ -15,6 +15,7 @@ import {
15 ExecuteToolFnOptions,
16 McpUrlResponse,
17 McpServerGetResponse,
18 + normalizeToolArguments,
19 } from '@composio/core';
20 import { FunctionDeclaration, Schema } from '@google/genai';
21
@@ -242,7 +243,8 @@ export class GoogleProvider extends BaseNonAgenticProvider<
243 modifiers?: ExecuteToolModifiers
244 ): Promise<string> {
245 const payload: ToolExecuteParams = {
245 - arguments: tool.args,
246 + // Models occasionally emit tool args as a JSON string rather than an object (issue #2406).
247 + arguments: normalizeToolArguments(tool.args, tool.name),
248 connectedAccountId: options?.connectedAccountId,
249 customAuthParams: options?.customAuthParams,
250 customConnectionData: options?.customConnectionData,
ts/packages/providers/google/test/google.test.ts
+21
@@ -157,6 +157,27 @@ describe('GoogleProvider', () => {
157 );
158 });
159
160 + it('should normalize a stringified-JSON args into an object before executing (issue #2406)', async () => {
161 + const args = { input: 'test-value' };
162 + const toolCall = { name: 'test-tool', args: JSON.stringify(args) as unknown as object };
163 +
164 + await provider.executeToolCall('test-user', toolCall);
165 +
166 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
167 + 'test-tool',
168 + expect.objectContaining({ arguments: args }),
169 + undefined
170 + );
171 + });
172 +
173 + it('should throw a typed error for malformed-JSON args (issue #2406)', async () => {
174 + const toolCall = { name: 'test-tool', args: 'not json' as unknown as object };
175 +
176 + await expect(provider.executeToolCall('test-user', toolCall)).rejects.toThrow(
177 + /not valid JSON/
178 + );
179 + });
180 +
181 it('should pass options to executeTool', async () => {
182 const userId = 'test-user';
183 const toolCall = {
ts/packages/providers/langchain/src/index.ts
+3 -1
@@ -16,6 +16,7 @@ import {
16 ExecuteToolFn,
17 McpUrlResponse,
18 McpServerGetResponse,
19 + normalizeToolArguments,
20 } from '@composio/core';
21 import { DynamicStructuredTool } from '@langchain/core/tools';
22
@@ -128,7 +129,8 @@ export class LangchainProvider extends BaseAgenticProvider<
129 throw new Error('App name is not defined');
130 }
131 const func = async (...args: unknown[]): Promise<unknown> => {
131 - const result = await executeTool(toolName, args[0] as Record<string, unknown>);
132 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
133 + const result = await executeTool(toolName, normalizeToolArguments(args[0], toolName));
134 return JSON.stringify(result);
135 };
136 if (!tool.inputParameters) {
ts/packages/providers/langchain/test/langchain.test.ts
+20
@@ -154,5 +154,25 @@ describe('LangchainProvider', () => {
154 expect(typeof result).toBe('string');
155 expect(() => JSON.parse(result as string)).not.toThrow();
156 });
157 +
158 + it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
159 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
160 +
161 + const result = await wrappedTool.func(
162 + JSON.stringify({ query: 'test query' }) as unknown as Record<string, unknown>
163 + );
164 +
165 + // The mock echoes back the params it received; confirm it saw a parsed object.
166 + expect(executeToolFn).toHaveBeenCalledWith(sampleTool.slug, { query: 'test query' });
167 + expect(JSON.parse(result as string).data.params).toEqual({ query: 'test query' });
168 + });
169 +
170 + it('should throw a typed error for a malformed-JSON string input (issue #2406)', async () => {
171 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
172 +
173 + await expect(
174 + wrappedTool.func('{"query":' as unknown as Record<string, unknown>)
175 + ).rejects.toThrow(/not valid JSON/);
176 + });
177 });
178 });
ts/packages/providers/llamaindex/src/index.ts
+3 -1
@@ -13,6 +13,7 @@ import {
13 McpServerGetResponse,
14 McpUrlResponse,
15 jsonSchemaToZodSchema,
16 + normalizeToolArguments,
17 } from '@composio/core';
18 import { tool as createLlamaindexTool, JSONValue } from 'llamaindex';
19
@@ -39,7 +40,8 @@ export class LlamaindexProvider extends BaseAgenticProvider<
40 description: tool.description ?? tool.name ?? '',
41 parameters: inputParametersSchema,
42 execute: async input => {
42 - const result = await executeTool(tool.slug, input as Record<string, unknown>);
43 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
44 + const result = await executeTool(tool.slug, normalizeToolArguments(input, tool.slug));
45 return JSON.stringify(result);
46 },
47 });
ts/packages/providers/llamaindex/test/llamaindex.test.ts
+19
@@ -209,6 +209,25 @@ describe('LlamaindexProvider', () => {
209
210 await expect(wrappedTool.call({ query: 'test' })).rejects.toThrow('Tool execution failed');
211 });
212 +
213 + it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
214 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
215 +
216 + const result = await wrappedTool.call(
217 + JSON.stringify({ query: 'test query' }) as unknown as Record<string, unknown>
218 + );
219 +
220 + expect(executeToolFn).toHaveBeenCalledWith(sampleTool.slug, { query: 'test query' });
221 + expect(JSON.parse(result as string).data.params).toEqual({ query: 'test query' });
222 + });
223 +
224 + it('should throw a typed error for a malformed-JSON string input (issue #2406)', async () => {
225 + const wrappedTool = provider.wrapTool(sampleTool, executeToolFn);
226 +
227 + await expect(
228 + wrappedTool.call('{"query":' as unknown as Record<string, unknown>)
229 + ).rejects.toThrow(/not valid JSON/);
230 + });
231 });
232
233 describe('MCP Server Response Transformation', () => {
ts/packages/providers/mastra/src/index.ts
+3 -1
@@ -16,6 +16,7 @@ import {
16 removeNonRequiredProperties,
17 telemetry,
18 type UnresolvedRefReason,
19 + normalizeToolArguments,
20 } from '@composio/core';
21 import { applyCompatLayer } from '@mastra/schema-compat';
22 import { createTool } from '@mastra/core/tools';
@@ -141,7 +142,8 @@ export class MastraProvider extends BaseAgenticProvider<
142 // @ts-ignore
143 outputSchema,
144 execute: async (inputData, _context) => {
144 - const result = await executeTool(tool.slug, inputData as Record<string, unknown>);
145 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
146 + const result = await executeTool(tool.slug, normalizeToolArguments(inputData, tool.slug));
147 return result;
148 },
149 });
ts/packages/providers/mastra/test/mastra.test.ts
+21 -2
@@ -120,6 +120,24 @@ describe('MastraProvider', () => {
120 expect(wrapped._isMockedMastraTool).toBe(true);
121 });
122
123 + it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
124 + const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
125 + const params = { input: 'test-value' };
126 +
127 + await wrapped.execute(params, {});
128 + expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
129 +
130 + vi.clearAllMocks();
131 + await wrapped.execute(JSON.stringify(params), {});
132 + expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
133 + });
134 +
135 + it('should throw a typed error for a malformed-JSON string input (issue #2406)', async () => {
136 + const wrapped = provider.wrapTool(mockTool, mockExecuteToolFn) as unknown as MockedMastraTool;
137 +
138 + await expect(wrapped.execute('{"input":', {})).rejects.toThrow(/not valid JSON/);
139 + });
140 +
141 it('should handle tools without input parameters', () => {
142 const toolWithoutInputParams: Tool = {
143 ...mockTool,
@@ -255,10 +273,11 @@ describe('MastraProvider', () => {
273 // Extract the execute function from the call to createTool()
274 const executeFunction = (createTool as any).mock.calls[0][0].execute;
275
258 - // Test the execute function without any parameters
276 + // Test the execute function without any parameters: a missing payload is
277 + // normalized to an empty object rather than forwarded as undefined (issue #2406).
278 const result = await executeFunction(undefined);
279
261 - expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, undefined);
280 + expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, {});
281 expect(result).toEqual({
282 data: { result: 'success' },
283 error: null,
ts/packages/providers/openai-agents/src/index.ts
+6 -2
@@ -16,6 +16,7 @@ import {
16 ExecuteToolFn,
17 McpUrlResponse,
18 McpServerGetResponse,
19 + normalizeToolArguments,
20 } from '@composio/core';
21 import type { Tool as OpenAIAgentTool } from '@openai/agents';
22 import { tool as createOpenAIAgentTool } from '@openai/agents';
@@ -132,8 +133,11 @@ export class OpenAIAgentsProvider extends BaseAgenticProvider<
133 },
134 strict: false,
135 execute: async params => {
135 - const input = typeof params === 'string' ? JSON.parse(params) : params;
136 - return await executeTool(composioTool.slug, input);
136 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
137 + return await executeTool(
138 + composioTool.slug,
139 + normalizeToolArguments(params, composioTool.slug)
140 + );
141 },
142 });
143 }
ts/packages/providers/openai-agents/test/openai-agents.test.ts
+24
@@ -112,6 +112,30 @@ describe('OpenAIAgentsProvider', () => {
112
113 expect(wrapped._isMockedOpenAIAgentTool).toBe(true);
114 });
115 +
116 + it('should normalize a stringified-JSON input to an object before executing (issue #2406)', async () => {
117 + const wrapped = provider.wrapTool(
118 + mockTool,
119 + mockExecuteToolFn
120 + ) as unknown as MockedOpenAIAgentTool;
121 + const params = { input: 'test-value' };
122 +
123 + await wrapped.execute(params);
124 + expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
125 +
126 + vi.clearAllMocks();
127 + await wrapped.execute(JSON.stringify(params));
128 + expect(mockExecuteToolFn).toHaveBeenCalledWith(mockTool.slug, params);
129 + });
130 +
131 + it('should throw a typed error for a malformed-JSON string input (issue #2406)', async () => {
132 + const wrapped = provider.wrapTool(
133 + mockTool,
134 + mockExecuteToolFn
135 + ) as unknown as MockedOpenAIAgentTool;
136 +
137 + await expect(wrapped.execute('{"input":')).rejects.toThrow(/not valid JSON/);
138 + });
139 });
140
141 describe('wrapTools', () => {
ts/packages/providers/openai/src/OpenAIResponsesProvider.ts
+4 -1
@@ -18,6 +18,7 @@ import {
18 ExecuteToolFnOptions,
19 removeNonRequiredProperties,
20 McpUrlResponse,
21 + normalizeToolArguments,
22 } from '@composio/core';
23
24 export type OpenAiTool = OpenAI.Responses.FunctionTool;
@@ -221,7 +222,9 @@ export class OpenAIResponsesProvider extends BaseNonAgenticProvider<
222 modifiers?: ExecuteToolModifiers
223 ): Promise<string> {
224 const payload: ToolExecuteParams = {
224 - arguments: JSON.parse(tool.arguments),
225 + // OpenAI always serializes tool arguments as a JSON string; normalize tolerates
226 + // empty / object-shaped payloads too (issue #2406).
227 + arguments: normalizeToolArguments(tool.arguments, tool.name),
228 connectedAccountId: options?.connectedAccountId,
229 customAuthParams: options?.customAuthParams,
230 customConnectionData: options?.customConnectionData,
ts/packages/providers/openai/test/opeanai-responses.test.ts
+18
@@ -181,6 +181,24 @@ describe('OpenAIResponsesProvider', () => {
181 );
182 });
183
184 + it('should coerce empty-string arguments to an empty object (issue #2406)', async () => {
185 + const toolCall = {
186 + id: 'call-123',
187 + type: 'function',
188 + name: 'test-tool',
189 + arguments: '',
190 + call_id: 'call-123',
191 + } as unknown as OpenAI.Responses.ResponseFunctionToolCall;
192 +
193 + await provider.executeToolCall('test-user', toolCall);
194 +
195 + expect(mockExecuteToolFn).toHaveBeenCalledWith(
196 + 'test-tool',
197 + expect.objectContaining({ arguments: {} }),
198 + undefined
199 + );
200 + });
201 +
202 it('should pass options to executeTool', async () => {
203 const userId = 'test-user';
204 const toolCall = {
ts/packages/providers/vercel/src/index.ts
+6 -2
@@ -18,6 +18,7 @@ import {
18 McpServerGetResponse,
19 removeNonRequiredProperties,
20 jsonSchemaToZodSchema,
21 + normalizeToolArguments,
22 } from '@composio/core';
23 import type { ToolSet as VercelToolSet, Tool as VercelTool } from 'ai';
24 import { tool } from 'ai';
@@ -126,8 +127,11 @@ export class VercelProvider extends BaseAgenticProvider<
127 inputSchema: inputParametersSchema,
128
129 execute: async params => {
129 - const input = typeof params === 'string' ? JSON.parse(params) : params;
130 - return await executeTool(composioTool.slug, input);
130 + // Models occasionally emit tool input as a JSON string rather than an object (issue #2406).
131 + return await executeTool(
132 + composioTool.slug,
133 + normalizeToolArguments(params, composioTool.slug)
134 + );
135 },
136 });
137 }