@devries-cameron20 / composio Mirror · read-only / commits / d94a49ff4
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, 19:45 UTC

fix(py): centralize tool schema aliasing (#3652)

This PR: - supersedes https://github.com/ComposioHQ/composio/pull/3625, https://github.com/ComposioHQ/composio/pull/3629, and the Python SDK/provider-side fix proposed by https://github.com/ComposioHQ/composio/pull/3504 - adds `alias_tool_input_schema` / `restore_tool_arguments` for provider-visible schemas and backend argument restoration - keeps `substitute_reserved_python_keywords` / `reinstate_reserved_python_keywords` as compatibility wrappers - preserves the existing Python keyword alias style (`from` -> `from_rs`), aliases invalid Python parameter names like `$top`, avoids leading-underscore aliases so Pydantic-backed providers can build models, and caps aliases at 64 characters for Anthropic-style tool schema validators - dereferences internal `$ref` / `$defs` before aliasing so referenced object properties are exposed through the same safe provider-visible names - restores Gemini manual `handle_response` arguments with the per-tool alias map before execution - wraps Google ADK tools with aliased callable signatures and restores original backend argument names - wraps Anthropic and Claude Agent SDK tool schemas with the same shared alias map and restores original backend argument names before execution - fixes the package-local Claude Agent SDK provider tests so they run without `pytest-asyncio` and keep using the provider-visible schema conversion hook - adds dependency-light core tests for helper behavior, `$ref` aliasing, Pydantic model compatibility, Gemini manual response, Google ADK wrapping, Anthropic wrapping, and Claude Agent SDK wrapping Local validation: - `uv run --project python pytest python/tests/test_tool_schema_aliasing.py python/tests/test_schema_parser.py python/tests/test_json_schema.py python/tests/test_imports.py -q` -> 112 passed - `PYTHONPATH=python uv run --project python --with-editable ./python/providers/claude_agent_sdk pytest python/providers/claude_agent_sdk/tests/test_provider.py -q --timeout=20` -> 16 passed - `uv run --project python --with-editable ./python/providers/langchain pytest --ignore-glob='python/tests/test_type_inference*.py' python/tests/ -q` -> 742 passed, 31 skipped - `uv run --project python --with-editable ./python --with-editable ./python/providers/langchain python <LangChain $top wrap smoke>` -> wrapped args schema field `param_top` - `uv run --project python --with-editable ./python --with-editable ./python/providers/langgraph python <LangGraph $top wrap smoke>` -> wrapped args schema field `param_top` - `uv run --project python ruff check --config python/config/ruff.toml python/composio/utils/shared.py python/tests/test_tool_schema_aliasing.py` -> passed - `uv run --project python ruff format --check --config python/config/ruff.toml python/composio/utils/shared.py python/tests/test_tool_schema_aliasing.py` -> passed - `git diff --check` -> passed Note: #3500's hosted MCP emission-layer report is already closed; this PR covers the Python SDK/provider surface rather than changing hosted MCP schema emission.

Alberto Schiabel committed Jun 25, 2026 at 01:37 UTC d94a49ff434044becb3a69b88355baf81abb2dd8
8 files changed +618 -81
python/composio/utils/shared.py
+167 -45
@@ -3,6 +3,8 @@ Shared utils.
3 """
4
5 import copy
6 +import dataclasses
7 +import hashlib
8 import json
9 import keyword
10 import typing as t
@@ -12,7 +14,8 @@ from inspect import Parameter
14 from pydantic import BaseModel, Field, create_model
15 from pydantic.fields import FieldInfo
16
15 -from composio.exceptions import InvalidParams
17 +from composio.exceptions import InvalidParams, InvalidSchemaError
18 +from composio.utils.json_schema import dereference_json_schema
19 from composio.utils.logging import get as get_logger
20 from composio.utils.schema_converter import (
21 CONTAINER_TYPE,
@@ -36,6 +39,9 @@ __all__ = [
39 "get_signature_format_from_schema_params",
40 "get_pydantic_signature_format_from_schema_params",
41 "generate_request_id",
42 + "ToolSchemaAliases",
43 + "alias_tool_input_schema",
44 + "restore_tool_arguments",
45 "substitute_reserved_python_keywords",
46 "reinstate_reserved_python_keywords",
47 "normalize_tool_arguments",
@@ -44,6 +50,8 @@ __all__ = [
50 reserved_names = ["validate"]
51
52 _OBJ_MARKER = "-_object_-"
53 +_ARR_MARKER = "-_array_-"
54 +_MAX_PROVIDER_ALIAS_LENGTH = 64
55
56
57 def normalize_tool_arguments(arguments: t.Any) -> t.Dict[str, t.Any]:
@@ -97,73 +105,187 @@ def _make_safe_name(name: str) -> str:
105 return f"{name}_rs"
106
107
100 -def substitute_reserved_python_keywords(
101 - schema: t.Dict,
102 -) -> t.Tuple[dict, dict]:
103 - """Replace Python reserved keywords in a JSON schema's property names.
108 +def _make_python_identifier(name: str) -> str:
109 + if keyword.iskeyword(name):
110 + return _make_safe_name(name)
111 +
112 + safe = "".join(
113 + char if (char.isascii() and (char.isalnum() or char == "_")) else "_"
114 + for char in name
115 + )
116 + if not safe:
117 + safe = "param"
118 + if safe[0].isdigit() or safe[0] == "_":
119 + safe = f"param_{safe.lstrip('_') or 'value'}"
120 + if keyword.iskeyword(safe):
121 + safe = _make_safe_name(safe)
122 + if len(safe) > _MAX_PROVIDER_ALIAS_LENGTH:
123 + hash_suffix = hashlib.sha256(name.encode()).hexdigest()[:8]
124 + safe = (
125 + f"{safe[: _MAX_PROVIDER_ALIAS_LENGTH - len(hash_suffix) - 1]}_{hash_suffix}"
126 + )
127 + return safe
128 +
129
105 - Returns a ``(schema, keywords)`` tuple where *schema* has safe property
106 - names and *keywords* maps each safe name back to the original. Nested
107 - object schemas are processed recursively.
130 +@dataclasses.dataclass(frozen=True)
131 +class ToolSchemaAliases:
132 + """Provider-visible schema plus mapping back to backend argument names."""
133
109 - The schema is deep-copied before any mutation so the caller's original
110 - is never modified.
134 + schema: t.Dict[str, t.Any]
135 + aliases: t.Dict[str, t.Any]
136 +
137 + def restore_arguments(self, arguments: dict) -> dict:
138 + return restore_tool_arguments(arguments, self.aliases)
139 +
140 +
141 +def alias_tool_input_schema(schema: t.Dict) -> ToolSchemaAliases:
142 + """Alias tool input schema keys so they are valid Python parameter names.
143 +
144 + Returns a :class:`ToolSchemaAliases` object containing a deep-copied schema
145 + for provider/framework exposure and a reverse alias map for restoring model
146 + arguments before calling the backend executor.
147 +
148 + Python keywords keep the historical ``_rs`` suffix (``from`` becomes
149 + ``from_rs``). Other names that cannot be used as Python identifiers are
150 + converted to Pydantic-safe identifiers and long aliases are capped at 64
151 + characters so the same provider-facing schema is accepted by
152 + Anthropic-style tool schema validators. Internal JSON Schema references are
153 + inlined before aliasing so referenced object properties are exposed through
154 + the same safe names. If two properties would expose the same alias, an
155 + :class:`InvalidSchemaError` is raised instead of guessing.
156 """
112 - if "properties" not in schema:
113 - return schema, {}
157 + aliased_schema = t.cast(
158 + t.Dict[str, t.Any],
159 + dereference_json_schema(
160 + copy.deepcopy(schema),
161 + on_unresolved="sentinel",
162 + ),
163 + )
164 + schema_params, aliases = _alias_schema_properties(aliased_schema)
165 + return ToolSchemaAliases(schema=schema_params, aliases=aliases)
166
115 - schema = copy.deepcopy(schema)
167
117 - keywords: t.Dict[str, t.Any] = {}
118 - for p_name in list(schema["properties"]):
119 - if not keyword.iskeyword(p_name):
120 - continue
168 +def _alias_schema_properties(schema: t.Dict[str, t.Any]) -> t.Tuple[dict, dict]:
169 + properties = schema.get("properties")
170 + if not isinstance(properties, dict):
171 + return schema, {}
172
122 - _nested_kw: t.Dict[str, t.Any] = {}
123 - p_val = schema["properties"].pop(p_name)
124 - if p_val.get("type") == "object":
125 - p_val, _nested_kw = substitute_reserved_python_keywords(schema=p_val)
173 + aliases: t.Dict[str, t.Any] = {}
174 + aliased_properties: t.Dict[str, t.Any] = {}
175
127 - safe = _make_safe_name(p_name)
128 - schema["properties"][safe] = p_val
129 - keywords[safe] = p_name
130 - keywords[f"{safe}{_OBJ_MARKER}"] = _nested_kw
176 + for original_name, property_schema in properties.items():
177 + safe_name = _make_python_identifier(original_name)
178 + if safe_name in aliased_properties:
179 + raise InvalidSchemaError(
180 + "Tool input schema property names produce a duplicate Python "
181 + f"parameter alias {safe_name!r}"
182 + )
183 +
184 + nested_object_aliases: t.Dict[str, t.Any] = {}
185 + nested_array_aliases: t.Dict[str, t.Any] = {}
186 + if isinstance(property_schema, dict):
187 + property_schema, nested_object_aliases = _alias_nested_object_schema(
188 + property_schema
189 + )
190 + property_schema, nested_array_aliases = _alias_nested_array_schema(
191 + property_schema
192 + )
193
132 - # Also rename entries in the ``required`` list.
133 - if keywords and "required" in schema:
134 - reverse = {v: k for k, v in keywords.items() if not k.endswith(_OBJ_MARKER)}
194 + aliased_properties[safe_name] = property_schema
195 + if safe_name != original_name or nested_object_aliases or nested_array_aliases:
196 + aliases[safe_name] = original_name
197 + if nested_object_aliases:
198 + aliases[f"{safe_name}{_OBJ_MARKER}"] = nested_object_aliases
199 + if nested_array_aliases:
200 + aliases[f"{safe_name}{_ARR_MARKER}"] = nested_array_aliases
201 +
202 + schema["properties"] = aliased_properties
203 + if aliases and "required" in schema:
204 + reverse = {
205 + original: safe
206 + for safe, original in aliases.items()
207 + if not safe.endswith(_OBJ_MARKER) and not safe.endswith(_ARR_MARKER)
208 + }
209 schema["required"] = [reverse.get(r, r) for r in schema["required"]]
210
137 - return schema, keywords
211 + return schema, aliases
212
213
140 -def reinstate_reserved_python_keywords(
141 - request: dict,
142 - keywords: dict,
143 -) -> dict:
144 - """Reverse the substitution performed by :func:`substitute_reserved_python_keywords`.
214 +def _alias_nested_object_schema(
215 + property_schema: t.Dict[str, t.Any],
216 +) -> t.Tuple[dict, dict]:
217 + if not isinstance(property_schema.get("properties"), dict):
218 + return property_schema, {}
219 + return _alias_schema_properties(property_schema)
220
146 - Modifies *request* **in-place** and returns it.
147 - """
148 - for clean_key in sorted(list(keywords), reverse=True):
149 - subkeys = None
150 - if clean_key.endswith(_OBJ_MARKER):
151 - subkeys = keywords[clean_key]
152 - clean_key, _ = clean_key.split(_OBJ_MARKER, maxsplit=1)
221
222 +def _alias_nested_array_schema(
223 + property_schema: t.Dict[str, t.Any],
224 +) -> t.Tuple[dict, dict]:
225 + items_schema = property_schema.get("items")
226 + if not isinstance(items_schema, dict):
227 + return property_schema, {}
228 + aliased_items, aliases = _alias_schema_properties(items_schema)
229 + if aliases:
230 + property_schema["items"] = aliased_items
231 + return property_schema, aliases
232 +
233 +
234 +def restore_tool_arguments(request: dict, aliases: dict) -> dict:
235 + """Restore provider-visible argument aliases back to backend schema names.
236 +
237 + Modifies *request* in-place and returns it.
238 + """
239 + alias_keys = [
240 + key
241 + for key in aliases
242 + if not key.endswith(_OBJ_MARKER) and not key.endswith(_ARR_MARKER)
243 + ]
244 + for clean_key in sorted(alias_keys, reverse=True):
245 if clean_key not in request:
246 continue
247
248 original_value = request.pop(clean_key)
158 - if subkeys:
159 - original_value = reinstate_reserved_python_keywords(
249 + object_aliases = aliases.get(f"{clean_key}{_OBJ_MARKER}", {})
250 + array_aliases = aliases.get(f"{clean_key}{_ARR_MARKER}", {})
251 + if object_aliases and isinstance(original_value, dict):
252 + original_value = restore_tool_arguments(
253 request=original_value,
161 - keywords=subkeys,
254 + aliases=object_aliases,
255 )
163 - request[keywords[clean_key]] = original_value
256 + if array_aliases and isinstance(original_value, list):
257 + original_value = [
258 + restore_tool_arguments(item, array_aliases)
259 + if isinstance(item, dict)
260 + else item
261 + for item in original_value
262 + ]
263 + request[aliases.get(clean_key, clean_key)] = original_value
264 return request
265
266
267 +def substitute_reserved_python_keywords(
268 + schema: t.Dict,
269 +) -> t.Tuple[dict, dict]:
270 + """Replace unsafe JSON schema property names with Python parameter aliases.
271 +
272 + Backward-compatible wrapper around :func:`alias_tool_input_schema`.
273 + """
274 + aliased = alias_tool_input_schema(schema=schema)
275 + return aliased.schema, aliased.aliases
276 +
277 +
278 +def reinstate_reserved_python_keywords(
279 + request: dict,
280 + keywords: dict,
281 +) -> dict:
282 + """Reverse the substitution performed by :func:`substitute_reserved_python_keywords`.
283 +
284 + Modifies *request* **in-place** and returns it.
285 + """
286 + return restore_tool_arguments(request=request, aliases=keywords)
287 +
288 +
289 def _coerce_default_value(
290 default: t.Any,
291 json_schema: t.Dict[str, t.Any],
python/providers/anthropic/composio_anthropic/provider.py
+17 -3
@@ -7,7 +7,11 @@ 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
10 +from composio.utils.shared import (
11 + ToolSchemaAliases,
12 + alias_tool_input_schema,
13 + normalize_tool_arguments,
14 +)
15
16
17 class AnthropicProvider(
@@ -18,9 +22,15 @@ class AnthropicProvider(
22 Composio toolset for Anthropic Claude platform.
23 """
24
25 + def __init__(self, **kwargs: t.Any) -> None:
26 + super().__init__(**kwargs)
27 + self._aliases: dict[str, ToolSchemaAliases] = {}
28 +
29 def wrap_tool(self, tool: Tool) -> ToolParam:
30 + aliases = alias_tool_input_schema(tool.input_parameters or {})
31 + self._aliases[tool.slug] = aliases
32 return ToolParam(
23 - input_schema=tool.input_parameters,
33 + input_schema=aliases.schema,
34 name=tool.slug,
35 description=tool.description,
36 )
@@ -43,9 +53,13 @@ class AnthropicProvider(
53 :return: Object containing output data from the tool call.
54 """
55 # Models occasionally emit tool input as a JSON string rather than a dict (issue #2406).
56 + arguments = normalize_tool_arguments(tool_call.input)
57 + aliases = self._aliases.get(tool_call.name)
58 + if aliases is not None:
59 + arguments = aliases.restore_arguments(arguments)
60 return self.execute_tool(
61 slug=tool_call.name,
48 - arguments=normalize_tool_arguments(tool_call.input),
62 + arguments=arguments,
63 modifiers=modifiers,
64 user_id=user_id,
65 )
python/providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py
+9 -5
@@ -21,7 +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
24 +from composio.utils.shared import alias_tool_input_schema, normalize_tool_arguments
25
26
27 class ClaudeAgentSDKProvider(
@@ -91,22 +91,22 @@ class ClaudeAgentSDKProvider(
91 Returns:
92 A Claude Agent SDK MCP tool definition
93 """
94 - input_schema = tool.input_parameters or {}
94 + aliases = alias_tool_input_schema(tool.input_parameters or {})
95
96 @sdk_tool(
97 tool.slug,
98 tool.description or f"Execute {tool.slug}",
99 - input_schema,
99 + aliases.schema,
100 )
101 async def tool_handler(args: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
102 """Execute the Composio tool with the given arguments."""
103 try:
104 + arguments = aliases.restore_arguments(normalize_tool_arguments(args))
105 # Run the synchronous execute_tool in a thread
106 result = await asyncio.to_thread(
107 execute_tool,
108 tool.slug,
108 - # Models occasionally emit tool input as a JSON string (issue #2406).
109 - normalize_tool_arguments(args),
109 + arguments,
110 )
111 # Format the result for Claude Agent SDK
112 result_text = result if isinstance(result, str) else json.dumps(result)
@@ -136,6 +136,10 @@ class ClaudeAgentSDKProvider(
136
137 return tool_handler
138
139 + def _json_schema_to_simple_schema(self, schema: dict) -> dict:
140 + """Return the provider-visible schema for a Composio JSON schema."""
141 + return alias_tool_input_schema(schema or {}).schema
142 +
143 def wrap_tools(
144 self,
145 tools: t.Sequence[Tool],
python/providers/claude_agent_sdk/tests/test_provider.py
+7 -9
@@ -2,6 +2,7 @@
2 Tests for Claude Code Agents Provider
3 """
4
5 +import asyncio
6 import json
7 from unittest.mock import MagicMock, patch
8
@@ -234,8 +235,7 @@ class TestCreateMcpServer:
235 class TestToolHandlerExecution:
236 """Tests for tool handler execution."""
237
237 - @pytest.mark.asyncio
238 - async def test_tool_handler_success(self, provider, mock_tool):
238 + def test_tool_handler_success(self, provider, mock_tool):
239 """Test successful tool execution."""
240 mock_execute = MagicMock(return_value={"data": "success", "successful": True})
241
@@ -256,13 +256,12 @@ class TestToolHandlerExecution:
256 provider.wrap_tool(mock_tool, mock_execute)
257
258 # Execute the captured handler
259 - result = await captured_handler({"to": "test@example.com"})
259 + result = asyncio.run(captured_handler({"to": "test@example.com"}))
260
261 assert result["content"][0]["type"] == "text"
262 assert "success" in result["content"][0]["text"]
263
264 - @pytest.mark.asyncio
265 - async def test_tool_handler_error(self, provider, mock_tool):
264 + def test_tool_handler_error(self, provider, mock_tool):
265 """Test tool execution with error."""
266 mock_execute = MagicMock(side_effect=Exception("Test error"))
267
@@ -280,15 +279,14 @@ class TestToolHandlerExecution:
279 mock_sdk_tool.side_effect = capture_decorator
280 provider.wrap_tool(mock_tool, mock_execute)
281
283 - result = await captured_handler({"to": "test@example.com"})
282 + result = asyncio.run(captured_handler({"to": "test@example.com"}))
283
284 assert result["content"][0]["type"] == "text"
285 response = json.loads(result["content"][0]["text"])
286 assert response["successful"] is False
287 assert "Test error" in response["error"]
288
290 - @pytest.mark.asyncio
291 - async def test_tool_handler_string_result(self, provider, mock_tool):
289 + def test_tool_handler_string_result(self, provider, mock_tool):
290 """Test tool execution returning string result."""
291 mock_execute = MagicMock(return_value="Simple string result")
292
@@ -306,7 +304,7 @@ class TestToolHandlerExecution:
304 mock_sdk_tool.side_effect = capture_decorator
305 provider.wrap_tool(mock_tool, mock_execute)
306
309 - result = await captured_handler({})
307 + result = asyncio.run(captured_handler({}))
308
309 assert result["content"][0]["type"] == "text"
310 assert result["content"][0]["text"] == "Simple string result"
python/providers/gemini/composio_gemini/provider.py
+13 -15
@@ -13,10 +13,10 @@ from composio.client.types import Tool
13 from composio.core.provider import AgenticProvider
14 from composio.core.provider.agentic import AgenticProviderExecuteFn
15 from composio.utils.shared import (
16 + ToolSchemaAliases,
17 + alias_tool_input_schema,
18 get_pydantic_signature_format_from_schema_params,
19 normalize_tool_arguments,
18 - reinstate_reserved_python_keywords,
19 - substitute_reserved_python_keywords,
20 )
21
22 # google-genai is only needed for handle_response (backward compat)
@@ -82,7 +82,9 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
82
83 def __init__(self, **kwargs: t.Any):
84 super().__init__(**kwargs)
85 - self._executors: t.Dict[str, AgenticProviderExecuteFn] = {}
85 + self._executors: t.Dict[
86 + str, t.Tuple[AgenticProviderExecuteFn, ToolSchemaAliases]
87 + ] = {}
88
89 def wrap_tool(
90 self,
@@ -97,19 +99,13 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
99 1. Derive a ``FunctionDeclaration`` schema via ``from_callable()``
100 2. Store it in the AFC ``function_map`` for automatic execution
101 """
100 - self._executors[tool.slug] = execute_tool
101 -
102 - # Handle reserved Python keywords in parameter names
103 - schema_params, keywords = substitute_reserved_python_keywords(
104 - schema=tool.input_parameters
105 - )
102 + aliases = alias_tool_input_schema(schema=tool.input_parameters)
103 + self._executors[tool.slug] = (execute_tool, aliases)
104
105 def function(**kwargs: t.Any) -> t.Dict:
106 """Composio tool execution wrapper."""
107 kwargs = _to_serializable(kwargs)
110 - kwargs = reinstate_reserved_python_keywords(
111 - request=kwargs, keywords=keywords
112 - )
108 + kwargs = aliases.restore_arguments(kwargs)
109 # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
110 result = execute_tool(tool.slug, normalize_tool_arguments(kwargs))
111 return _process_execution_result(result)
@@ -130,7 +126,7 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
126 # The google-genai SDK requires parameterized array types — bare List
127 # generates {"type": "ARRAY"} without "items", which the API rejects.
128 sig_params = get_pydantic_signature_format_from_schema_params(
133 - schema_params=schema_params,
129 + schema_params=aliases.schema,
130 skip_default=True,
131 )
132 action_func.__signature__ = Signature(parameters=sig_params) # type: ignore
@@ -190,8 +186,10 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini
186 if fc.name not in self._executors:
187 continue
188
193 - result = self._executors[fc.name](
194 - slug=fc.name, arguments=normalize_tool_arguments(dict(fc.args))
189 + execute_tool, aliases = self._executors[fc.name]
190 + arguments = aliases.restore_arguments(dict(fc.args))
191 + result = execute_tool(
192 + slug=fc.name, arguments=normalize_tool_arguments(arguments)
193 )
194 processed = _process_execution_result(result)
195
python/providers/google_adk/composio_google_adk/provider.py
+5 -3
@@ -8,7 +8,7 @@ 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
11 +from composio.utils.shared import alias_tool_input_schema, normalize_tool_arguments
12
13
14 class GoogleAdkProvider(
@@ -36,9 +36,10 @@ class GoogleAdkProvider(
36 "required": [],
37 },
38 )
39 + aliases = alias_tool_input_schema(schema=input_parameters)
40 properties = t.cast(
41 t.Dict[str, t.Dict[str, t.Any]],
41 - input_parameters.get("properties", {}),
42 + aliases.schema.get("properties", {}),
43 )
44 docstring = tool.description or f"Execute {tool.slug}"
45 docstring += "\nArgs:"
@@ -50,6 +51,7 @@ class GoogleAdkProvider(
51 docstring += "\n A dictionary containing response from the action"
52
53 def _execute(**kwargs: t.Any) -> t.Dict:
54 + kwargs = aliases.restore_arguments(kwargs)
55 # Normalize defensively so a stringified payload is coerced to a dict (issue #2406).
56 return execute_tool(
57 slug=tool.slug, arguments=normalize_tool_arguments(kwargs)
@@ -62,7 +64,7 @@ class GoogleAdkProvider(
64 closure=_execute.__closure__,
65 )
66 parameters = function_signature_from_jsonschema(
65 - schema=input_parameters,
67 + schema=aliases.schema,
68 skip_default=self.skip_default,
69 )
70 setattr(function, "__signature__", Signature(parameters=parameters))
python/tests/test_gemini_provider.py
+2 -1
@@ -204,7 +204,8 @@ class TestWrapTool:
204 provider.wrap_tool(tool, execute_tool)
205
206 assert "GITHUB_STAR_REPO" in provider._executors
207 - assert provider._executors["GITHUB_STAR_REPO"] is execute_tool
207 + stored_execute_tool, _aliases = provider._executors["GITHUB_STAR_REPO"]
208 + assert stored_execute_tool is execute_tool
209
210 def test_callable_executes_correctly(self):
211 from composio_gemini import GeminiProvider
python/tests/test_tool_schema_aliasing.py new
+398
@@ -0,0 +1,398 @@
1 +"""Tests for provider-facing tool schema aliases."""
2 +
3 +import asyncio
4 +import copy
5 +import importlib.util
6 +import inspect
7 +import re
8 +import sys
9 +import types
10 +from pathlib import Path
11 +from types import SimpleNamespace
12 +from unittest.mock import Mock
13 +
14 +import pytest
15 +
16 +from composio.exceptions import InvalidSchemaError
17 +from composio.utils.shared import (
18 + alias_tool_input_schema,
19 + json_schema_to_model,
20 + substitute_reserved_python_keywords,
21 +)
22 +
23 +
24 +PYTHON_ROOT = Path(__file__).resolve().parents[1]
25 +ANTHROPIC_PROPERTY_RE = re.compile(r"^[a-zA-Z0-9_.-]{1,64}$")
26 +
27 +
28 +def _load_module(monkeypatch, module_name: str, path: Path):
29 + spec = importlib.util.spec_from_file_location(module_name, path)
30 + assert spec is not None
31 + assert spec.loader is not None
32 + module = importlib.util.module_from_spec(spec)
33 + monkeypatch.setitem(sys.modules, module_name, module)
34 + spec.loader.exec_module(module)
35 + return module
36 +
37 +
38 +def test_alias_tool_input_schema_restores_nested_aliases_without_mutating_schema():
39 + schema = {
40 + "type": "object",
41 + "properties": {
42 + "from": {"type": "string"},
43 + "payload": {
44 + "type": "object",
45 + "properties": {"class": {"type": "string"}},
46 + "required": ["class"],
47 + },
48 + "items": {
49 + "type": "array",
50 + "items": {
51 + "type": "object",
52 + "properties": {"for": {"type": "string"}},
53 + "required": ["for"],
54 + },
55 + },
56 + },
57 + "required": ["from", "payload"],
58 + }
59 + original = copy.deepcopy(schema)
60 +
61 + aliases = alias_tool_input_schema(schema)
62 +
63 + assert schema == original
64 + assert list(aliases.schema["properties"]) == ["from_rs", "payload", "items"]
65 + assert aliases.schema["required"] == ["from_rs", "payload"]
66 + assert aliases.schema["properties"]["payload"]["required"] == ["class_rs"]
67 + assert aliases.schema["properties"]["items"]["items"]["required"] == ["for_rs"]
68 +
69 + arguments = {
70 + "from_rs": "sender@example.com",
71 + "payload": {"class_rs": "primary"},
72 + "items": [{"for_rs": "recipient@example.com"}],
73 + }
74 + assert aliases.restore_arguments(arguments) == {
75 + "from": "sender@example.com",
76 + "payload": {"class": "primary"},
77 + "items": [{"for": "recipient@example.com"}],
78 + }
79 +
80 +
81 +def test_alias_tool_input_schema_rejects_duplicate_aliases():
82 + schema = {
83 + "type": "object",
84 + "properties": {
85 + "from": {"type": "string"},
86 + "from_rs": {"type": "string"},
87 + },
88 + }
89 +
90 + with pytest.raises(InvalidSchemaError, match="duplicate Python parameter alias"):
91 + alias_tool_input_schema(schema)
92 +
93 +
94 +def test_legacy_keyword_helpers_use_tool_schema_aliases():
95 + long_name = "x" * 80
96 + schema = {
97 + "title": "ODataParams",
98 + "type": "object",
99 + "properties": {
100 + "$top": {"type": "integer"},
101 + "@microsoft.graph.conflictBehavior": {"type": "string"},
102 + long_name: {"type": "string"},
103 + },
104 + "required": ["$top", long_name],
105 + }
106 +
107 + aliased_schema, aliases = substitute_reserved_python_keywords(schema)
108 +
109 + aliased_names = list(aliased_schema["properties"])
110 + assert aliased_names[0] == "param_top"
111 + assert aliased_names[1] == "param_microsoft_graph_conflictBehavior"
112 + assert len(aliased_names[2]) == 64
113 + assert all(ANTHROPIC_PROPERTY_RE.fullmatch(name) for name in aliased_names)
114 + assert aliased_schema["required"] == ["param_top", aliased_names[2]]
115 + assert aliases["param_top"] == "$top"
116 + assert aliases["param_microsoft_graph_conflictBehavior"] == (
117 + "@microsoft.graph.conflictBehavior"
118 + )
119 + assert aliases[aliased_names[2]] == long_name
120 + model = json_schema_to_model(aliased_schema)
121 + assert "param_top" in model.model_fields
122 +
123 +
124 +def test_alias_tool_input_schema_dereferences_refs_before_aliasing():
125 + schema = {
126 + "$ref": "#/$defs/SearchParams",
127 + "$defs": {
128 + "SearchParams": {
129 + "type": "object",
130 + "properties": {
131 + "filter": {"$ref": "#/$defs/ODataFilter"},
132 + },
133 + "required": ["filter"],
134 + },
135 + "ODataFilter": {
136 + "type": "object",
137 + "properties": {"$top": {"type": "integer"}},
138 + "required": ["$top"],
139 + },
140 + },
141 + }
142 +
143 + aliases = alias_tool_input_schema(schema)
144 +
145 + assert "$defs" not in aliases.schema
146 + assert aliases.schema["required"] == ["filter"]
147 + filter_schema = aliases.schema["properties"]["filter"]
148 + assert list(filter_schema["properties"]) == ["param_top"]
149 + assert filter_schema["required"] == ["param_top"]
150 + assert aliases.restore_arguments({"filter": {"param_top": 10}}) == {
151 + "filter": {"$top": 10}
152 + }
153 +
154 +
155 +def test_gemini_manual_response_restores_provider_visible_aliases(monkeypatch):
156 + google_module = types.ModuleType("google")
157 + genai_module = types.ModuleType("google.genai")
158 + genai_types_module = types.ModuleType("google.genai.types")
159 +
160 + class FunctionResponse:
161 + def __init__(self, name, response):
162 + self.name = name
163 + self.response = response
164 +
165 + class Part:
166 + def __init__(self, function_response):
167 + self.function_response = function_response
168 +
169 + genai_types_module.FunctionResponse = FunctionResponse
170 + genai_types_module.Part = Part
171 + genai_module.types = genai_types_module
172 + google_module.genai = genai_module
173 + monkeypatch.setitem(sys.modules, "google", google_module)
174 + monkeypatch.setitem(sys.modules, "google.genai", genai_module)
175 + monkeypatch.setitem(sys.modules, "google.genai.types", genai_types_module)
176 +
177 + provider_module = _load_module(
178 + monkeypatch,
179 + "test_composio_gemini_provider",
180 + PYTHON_ROOT / "providers/gemini/composio_gemini/provider.py",
181 + )
182 + provider = provider_module.GeminiProvider()
183 + execute_tool = Mock(return_value={"successful": True, "data": {"ok": True}})
184 + tool = SimpleNamespace(
185 + slug="TOOL_WITH_RESERVED",
186 + description="Tool with reserved parameters",
187 + input_parameters={
188 + "type": "object",
189 + "properties": {"for": {"type": "string"}},
190 + "required": ["for"],
191 + },
192 + )
193 + provider.wrap_tools([tool], execute_tool)
194 +
195 + response = SimpleNamespace(
196 + candidates=[
197 + SimpleNamespace(
198 + content=SimpleNamespace(
199 + parts=[
200 + SimpleNamespace(
201 + function_call=SimpleNamespace(
202 + name="TOOL_WITH_RESERVED",
203 + args={"for_rs": "recipient@example.com"},
204 + )
205 + )
206 + ]
207 + )
208 + )
209 + ]
210 + )
211 +
212 + function_responses, executed = provider.handle_response(response)
213 +
214 + assert executed is True
215 + assert function_responses[0].function_response.name == "TOOL_WITH_RESERVED"
216 + execute_tool.assert_called_once_with(
217 + slug="TOOL_WITH_RESERVED", arguments={"for": "recipient@example.com"}
218 + )
219 +
220 +
221 +def test_google_adk_wrap_tool_aliases_signature_and_restores_arguments(monkeypatch):
222 + google_module = types.ModuleType("google")
223 + adk_module = types.ModuleType("google.adk")
224 + tools_module = types.ModuleType("google.adk.tools")
225 +
226 + class FunctionTool:
227 + def __init__(self, func):
228 + self.func = func
229 +
230 + tools_module.FunctionTool = FunctionTool
231 + adk_module.tools = tools_module
232 + google_module.adk = adk_module
233 + monkeypatch.setitem(sys.modules, "google", google_module)
234 + monkeypatch.setitem(sys.modules, "google.adk", adk_module)
235 + monkeypatch.setitem(sys.modules, "google.adk.tools", tools_module)
236 +
237 + provider_module = _load_module(
238 + monkeypatch,
239 + "test_composio_google_adk_provider",
240 + PYTHON_ROOT / "providers/google_adk/composio_google_adk/provider.py",
241 + )
242 + provider = provider_module.GoogleAdkProvider()
243 + execute_tool = Mock(return_value={"successful": True, "data": {"ok": True}})
244 + tool = SimpleNamespace(
245 + slug="TOOL_WITH_RESERVED",
246 + description="Tool with reserved parameters",
247 + input_parameters={
248 + "type": "object",
249 + "properties": {
250 + "from": {"type": "string", "description": "Sender"},
251 + "limit": {"type": "integer", "description": "Limit"},
252 + },
253 + "required": ["from"],
254 + },
255 + )
256 +
257 + wrapped = provider.wrap_tool(tool, execute_tool)
258 +
259 + assert list(inspect.signature(wrapped.func).parameters) == ["from_rs", "limit"]
260 + assert "from_rs: Sender" in (wrapped.func.__doc__ or "")
261 + wrapped.func(from_rs="sender@example.com", limit=10)
262 + execute_tool.assert_called_once_with(
263 + slug="TOOL_WITH_RESERVED",
264 + arguments={"from": "sender@example.com", "limit": 10},
265 + )
266 +
267 +
268 +def test_anthropic_wrap_tool_aliases_schema_and_restores_arguments(monkeypatch):
269 + anthropic_module = types.ModuleType("anthropic")
270 + types_module = types.ModuleType("anthropic.types")
271 + beta_module = types.ModuleType("anthropic.types.beta")
272 + beta_tool_use_module = types.ModuleType("anthropic.types.beta.beta_tool_use_block")
273 + message_module = types.ModuleType("anthropic.types.message")
274 + tool_param_module = types.ModuleType("anthropic.types.tool_param")
275 + tool_use_module = types.ModuleType("anthropic.types.tool_use_block")
276 +
277 + class BetaToolUseBlock:
278 + pass
279 +
280 + class Message:
281 + def __init__(self, **kwargs):
282 + self.__dict__.update(kwargs)
283 +
284 + class ToolUseBlock:
285 + pass
286 +
287 + beta_tool_use_module.BetaToolUseBlock = BetaToolUseBlock
288 + message_module.Message = Message
289 + tool_param_module.ToolParam = dict
290 + tool_use_module.ToolUseBlock = ToolUseBlock
291 + monkeypatch.setitem(sys.modules, "anthropic", anthropic_module)
292 + monkeypatch.setitem(sys.modules, "anthropic.types", types_module)
293 + monkeypatch.setitem(sys.modules, "anthropic.types.beta", beta_module)
294 + monkeypatch.setitem(
295 + sys.modules,
296 + "anthropic.types.beta.beta_tool_use_block",
297 + beta_tool_use_module,
298 + )
299 + monkeypatch.setitem(sys.modules, "anthropic.types.message", message_module)
300 + monkeypatch.setitem(sys.modules, "anthropic.types.tool_param", tool_param_module)
301 + monkeypatch.setitem(sys.modules, "anthropic.types.tool_use_block", tool_use_module)
302 +
303 + provider_module = _load_module(
304 + monkeypatch,
305 + "test_composio_anthropic_provider",
306 + PYTHON_ROOT / "providers/anthropic/composio_anthropic/provider.py",
307 + )
308 + provider = provider_module.AnthropicProvider()
309 + provider.execute_tool = Mock(return_value={"successful": True})
310 + long_name = "x" * 80
311 + tool = SimpleNamespace(
312 + slug="TOOL_WITH_ODATA",
313 + description="Tool with OData parameters",
314 + input_parameters={
315 + "type": "object",
316 + "properties": {
317 + "$top": {"type": "integer"},
318 + "@microsoft.graph.conflictBehavior": {"type": "string"},
319 + long_name: {"type": "string"},
320 + },
321 + "required": ["$top", long_name],
322 + },
323 + )
324 +
325 + wrapped = provider.wrap_tool(tool)
326 +
327 + aliased_names = list(wrapped["input_schema"]["properties"])
328 + assert aliased_names[0] == "param_top"
329 + assert aliased_names[1] == "param_microsoft_graph_conflictBehavior"
330 + assert len(aliased_names[2]) == 64
331 + assert all(ANTHROPIC_PROPERTY_RE.fullmatch(name) for name in aliased_names)
332 +
333 + tool_call = SimpleNamespace(
334 + name="TOOL_WITH_ODATA",
335 + input={
336 + "param_top": 10,
337 + "param_microsoft_graph_conflictBehavior": "rename",
338 + aliased_names[2]: "value",
339 + },
340 + )
341 + provider.execute_tool_call(user_id="user", tool_call=tool_call)
342 +
343 + provider.execute_tool.assert_called_once_with(
344 + slug="TOOL_WITH_ODATA",
345 + arguments={
346 + "$top": 10,
347 + "@microsoft.graph.conflictBehavior": "rename",
348 + long_name: "value",
349 + },
350 + modifiers=None,
351 + user_id="user",
352 + )
353 +
354 +
355 +def test_claude_agent_sdk_wrap_tool_aliases_schema_and_restores_arguments(monkeypatch):
356 + claude_agent_sdk_module = types.ModuleType("claude_agent_sdk")
357 +
358 + def sdk_tool(name, description, input_schema):
359 + def decorator(fn):
360 + fn._tool_name = name
361 + fn._tool_description = description
362 + fn._input_schema = input_schema
363 + return fn
364 +
365 + return decorator
366 +
367 + claude_agent_sdk_module.McpSdkServerConfig = dict
368 + claude_agent_sdk_module.SdkMcpTool = object
369 + claude_agent_sdk_module.create_sdk_mcp_server = Mock()
370 + claude_agent_sdk_module.tool = sdk_tool
371 + monkeypatch.setitem(sys.modules, "claude_agent_sdk", claude_agent_sdk_module)
372 +
373 + provider_module = _load_module(
374 + monkeypatch,
375 + "test_composio_claude_agent_sdk_provider",
376 + PYTHON_ROOT
377 + / "providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py",
378 + )
379 + provider = provider_module.ClaudeAgentSDKProvider()
380 + execute_tool = Mock(return_value={"successful": True})
381 + tool = SimpleNamespace(
382 + slug="TOOL_WITH_ODATA",
383 + description="Tool with OData parameters",
384 + input_parameters={
385 + "type": "object",
386 + "properties": {"$top": {"type": "integer"}},
387 + "required": ["$top"],
388 + },
389 + )
390 +
391 + wrapped = provider.wrap_tool(tool, execute_tool)
392 +
393 + assert list(wrapped._input_schema["properties"]) == ["param_top"]
394 + assert wrapped._input_schema["required"] == ["param_top"]
395 + result = asyncio.run(wrapped({"param_top": 5}))
396 +
397 + assert result["content"][0]["type"] == "text"
398 + execute_tool.assert_called_once_with("TOOL_WITH_ODATA", {"$top": 5})