Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
fix(py): centralize tool schema aliasing (#3652)
Alberto Schiabeld94a49ff4340
diff --git a/python/composio/utils/shared.py b/python/composio/utils/shared.pyindex 6509905ac..438aa40d1 100644--- a/python/composio/utils/shared.py+++ b/python/composio/utils/shared.py@@ -3,6 +3,8 @@ Shared utils."""import copy+import dataclasses+import hashlibimport jsonimport keywordimport typing as t@@ -12,7 +14,8 @@ from inspect import Parameterfrom pydantic import BaseModel, Field, create_modelfrom pydantic.fields import FieldInfo-from composio.exceptions import InvalidParams+from composio.exceptions import InvalidParams, InvalidSchemaError+from composio.utils.json_schema import dereference_json_schemafrom composio.utils.logging import get as get_loggerfrom composio.utils.schema_converter import (CONTAINER_TYPE,@@ -36,6 +39,9 @@ __all__ = ["get_signature_format_from_schema_params","get_pydantic_signature_format_from_schema_params","generate_request_id",+ "ToolSchemaAliases",+ "alias_tool_input_schema",+ "restore_tool_arguments","substitute_reserved_python_keywords","reinstate_reserved_python_keywords","normalize_tool_arguments",@@ -44,6 +50,8 @@ __all__ = [reserved_names = ["validate"]_OBJ_MARKER = "-_object_-"+_ARR_MARKER = "-_array_-"+_MAX_PROVIDER_ALIAS_LENGTH = 64def normalize_tool_arguments(arguments: t.Any) -> t.Dict[str, t.Any]:@@ -97,73 +105,187 @@ def _make_safe_name(name: str) -> str:return f"{name}_rs"-def substitute_reserved_python_keywords(- schema: t.Dict,-) -> t.Tuple[dict, dict]:- """Replace Python reserved keywords in a JSON schema's property names.+def _make_python_identifier(name: str) -> str:+ if keyword.iskeyword(name):+ return _make_safe_name(name)++ safe = "".join(+ char if (char.isascii() and (char.isalnum() or char == "_")) else "_"+ for char in name+ )+ if not safe:+ safe = "param"+ if safe[0].isdigit() or safe[0] == "_":+ safe = f"param_{safe.lstrip('_') or 'value'}"+ if keyword.iskeyword(safe):+ safe = _make_safe_name(safe)+ if len(safe) > _MAX_PROVIDER_ALIAS_LENGTH:+ hash_suffix = hashlib.sha256(name.encode()).hexdigest()[:8]+ safe = (+ f"{safe[: _MAX_PROVIDER_ALIAS_LENGTH - len(hash_suffix) - 1]}_{hash_suffix}"+ )+ return safe+- Returns a ``(schema, keywords)`` tuple where *schema* has safe property- names and *keywords* maps each safe name back to the original. Nested- object schemas are processed recursively.[email protected](frozen=True)+class ToolSchemaAliases:+ """Provider-visible schema plus mapping back to backend argument names."""- The schema is deep-copied before any mutation so the caller's original- is never modified.+ schema: t.Dict[str, t.Any]+ aliases: t.Dict[str, t.Any]++ def restore_arguments(self, arguments: dict) -> dict:+ return restore_tool_arguments(arguments, self.aliases)+++def alias_tool_input_schema(schema: t.Dict) -> ToolSchemaAliases:+ """Alias tool input schema keys so they are valid Python parameter names.++ Returns a :class:`ToolSchemaAliases` object containing a deep-copied schema+ for provider/framework exposure and a reverse alias map for restoring model+ arguments before calling the backend executor.++ Python keywords keep the historical ``_rs`` suffix (``from`` becomes+ ``from_rs``). Other names that cannot be used as Python identifiers are+ converted to Pydantic-safe identifiers and long aliases are capped at 64+ characters so the same provider-facing schema is accepted by+ Anthropic-style tool schema validators. Internal JSON Schema references are+ inlined before aliasing so referenced object properties are exposed through+ the same safe names. If two properties would expose the same alias, an+ :class:`InvalidSchemaError` is raised instead of guessing."""- if "properties" not in schema:- return schema, {}+ aliased_schema = t.cast(+ t.Dict[str, t.Any],+ dereference_json_schema(+ copy.deepcopy(schema),+ on_unresolved="sentinel",+ ),+ )+ schema_params, aliases = _alias_schema_properties(aliased_schema)+ return ToolSchemaAliases(schema=schema_params, aliases=aliases)- schema = copy.deepcopy(schema)- keywords: t.Dict[str, t.Any] = {}- for p_name in list(schema["properties"]):- if not keyword.iskeyword(p_name):- continue+def _alias_schema_properties(schema: t.Dict[str, t.Any]) -> t.Tuple[dict, dict]:+ properties = schema.get("properties")+ if not isinstance(properties, dict):+ return schema, {}- _nested_kw: t.Dict[str, t.Any] = {}- p_val = schema["properties"].pop(p_name)- if p_val.get("type") == "object":- p_val, _nested_kw = substitute_reserved_python_keywords(schema=p_val)+ aliases: t.Dict[str, t.Any] = {}+ aliased_properties: t.Dict[str, t.Any] = {}- safe = _make_safe_name(p_name)- schema["properties"][safe] = p_val- keywords[safe] = p_name- keywords[f"{safe}{_OBJ_MARKER}"] = _nested_kw+ for original_name, property_schema in properties.items():+ safe_name = _make_python_identifier(original_name)+ if safe_name in aliased_properties:+ raise InvalidSchemaError(+ "Tool input schema property names produce a duplicate Python "+ f"parameter alias {safe_name!r}"+ )++ nested_object_aliases: t.Dict[str, t.Any] = {}+ nested_array_aliases: t.Dict[str, t.Any] = {}+ if isinstance(property_schema, dict):+ property_schema, nested_object_aliases = _alias_nested_object_schema(+ property_schema+ )+ property_schema, nested_array_aliases = _alias_nested_array_schema(+ property_schema+ )- # Also rename entries in the ``required`` list.- if keywords and "required" in schema:- reverse = {v: k for k, v in keywords.items() if not k.endswith(_OBJ_MARKER)}+ aliased_properties[safe_name] = property_schema+ if safe_name != original_name or nested_object_aliases or nested_array_aliases:+ aliases[safe_name] = original_name+ if nested_object_aliases:+ aliases[f"{safe_name}{_OBJ_MARKER}"] = nested_object_aliases+ if nested_array_aliases:+ aliases[f"{safe_name}{_ARR_MARKER}"] = nested_array_aliases++ schema["properties"] = aliased_properties+ if aliases and "required" in schema:+ reverse = {+ original: safe+ for safe, original in aliases.items()+ if not safe.endswith(_OBJ_MARKER) and not safe.endswith(_ARR_MARKER)+ }schema["required"] = [reverse.get(r, r) for r in schema["required"]]- return schema, keywords+ return schema, aliases-def reinstate_reserved_python_keywords(- request: dict,- keywords: dict,-) -> dict:- """Reverse the substitution performed by :func:`substitute_reserved_python_keywords`.+def _alias_nested_object_schema(+ property_schema: t.Dict[str, t.Any],+) -> t.Tuple[dict, dict]:+ if not isinstance(property_schema.get("properties"), dict):+ return property_schema, {}+ return _alias_schema_properties(property_schema)- Modifies *request* **in-place** and returns it.- """- for clean_key in sorted(list(keywords), reverse=True):- subkeys = None- if clean_key.endswith(_OBJ_MARKER):- subkeys = keywords[clean_key]- clean_key, _ = clean_key.split(_OBJ_MARKER, maxsplit=1)+def _alias_nested_array_schema(+ property_schema: t.Dict[str, t.Any],+) -> t.Tuple[dict, dict]:+ items_schema = property_schema.get("items")+ if not isinstance(items_schema, dict):+ return property_schema, {}+ aliased_items, aliases = _alias_schema_properties(items_schema)+ if aliases:+ property_schema["items"] = aliased_items+ return property_schema, aliases+++def restore_tool_arguments(request: dict, aliases: dict) -> dict:+ """Restore provider-visible argument aliases back to backend schema names.++ Modifies *request* in-place and returns it.+ """+ alias_keys = [+ key+ for key in aliases+ if not key.endswith(_OBJ_MARKER) and not key.endswith(_ARR_MARKER)+ ]+ for clean_key in sorted(alias_keys, reverse=True):if clean_key not in request:continueoriginal_value = request.pop(clean_key)- if subkeys:- original_value = reinstate_reserved_python_keywords(+ object_aliases = aliases.get(f"{clean_key}{_OBJ_MARKER}", {})+ array_aliases = aliases.get(f"{clean_key}{_ARR_MARKER}", {})+ if object_aliases and isinstance(original_value, dict):+ original_value = restore_tool_arguments(request=original_value,- keywords=subkeys,+ aliases=object_aliases,)- request[keywords[clean_key]] = original_value+ if array_aliases and isinstance(original_value, list):+ original_value = [+ restore_tool_arguments(item, array_aliases)+ if isinstance(item, dict)+ else item+ for item in original_value+ ]+ request[aliases.get(clean_key, clean_key)] = original_valuereturn request+def substitute_reserved_python_keywords(+ schema: t.Dict,+) -> t.Tuple[dict, dict]:+ """Replace unsafe JSON schema property names with Python parameter aliases.++ Backward-compatible wrapper around :func:`alias_tool_input_schema`.+ """+ aliased = alias_tool_input_schema(schema=schema)+ return aliased.schema, aliased.aliases+++def reinstate_reserved_python_keywords(+ request: dict,+ keywords: dict,+) -> dict:+ """Reverse the substitution performed by :func:`substitute_reserved_python_keywords`.++ Modifies *request* **in-place** and returns it.+ """+ return restore_tool_arguments(request=request, aliases=keywords)++def _coerce_default_value(default: t.Any,json_schema: t.Dict[str, t.Any],diff --git a/python/providers/anthropic/composio_anthropic/provider.py b/python/providers/anthropic/composio_anthropic/provider.pyindex 5115fe948..f0234f227 100644--- a/python/providers/anthropic/composio_anthropic/provider.py+++ b/python/providers/anthropic/composio_anthropic/provider.py@@ -7,7 +7,11 @@ from anthropic.types.tool_use_block import ToolUseBlockfrom composio.core.provider import NonAgenticProviderfrom composio.types import Modifiers, Tool, ToolExecutionResponse-from composio.utils.shared import normalize_tool_arguments+from composio.utils.shared import (+ ToolSchemaAliases,+ alias_tool_input_schema,+ normalize_tool_arguments,+)class AnthropicProvider(@@ -18,9 +22,15 @@ class AnthropicProvider(Composio toolset for Anthropic Claude platform."""+ def __init__(self, **kwargs: t.Any) -> None:+ super().__init__(**kwargs)+ self._aliases: dict[str, ToolSchemaAliases] = {}+def wrap_tool(self, tool: Tool) -> ToolParam:+ aliases = alias_tool_input_schema(tool.input_parameters or {})+ self._aliases[tool.slug] = aliasesreturn ToolParam(- input_schema=tool.input_parameters,+ input_schema=aliases.schema,name=tool.slug,description=tool.description,)@@ -43,9 +53,13 @@ class AnthropicProvider(:return: Object containing output data from the tool call."""# Models occasionally emit tool input as a JSON string rather than a dict (issue #2406).+ arguments = normalize_tool_arguments(tool_call.input)+ aliases = self._aliases.get(tool_call.name)+ if aliases is not None:+ arguments = aliases.restore_arguments(arguments)return self.execute_tool(slug=tool_call.name,- arguments=normalize_tool_arguments(tool_call.input),+ arguments=arguments,modifiers=modifiers,user_id=user_id,)diff --git a/python/providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py b/python/providers/claude_agent_sdk/composio_claude_agent_sdk/provider.pyindex ae923e21e..100d651b8 100644--- a/python/providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py+++ b/python/providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py@@ -21,7 +21,7 @@ from claude_agent_sdk import (from composio.core.provider import AgenticProviderfrom composio.core.provider.agentic import AgenticProviderExecuteFnfrom composio.types import Tool-from composio.utils.shared import normalize_tool_arguments+from composio.utils.shared import alias_tool_input_schema, normalize_tool_argumentsclass ClaudeAgentSDKProvider(@@ -91,22 +91,22 @@ class ClaudeAgentSDKProvider(Returns:A Claude Agent SDK MCP tool definition"""- input_schema = tool.input_parameters or {}+ aliases = alias_tool_input_schema(tool.input_parameters or {})@sdk_tool(tool.slug,tool.description or f"Execute {tool.slug}",- input_schema,+ aliases.schema,)async def tool_handler(args: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:"""Execute the Composio tool with the given arguments."""try:+ arguments = aliases.restore_arguments(normalize_tool_arguments(args))# Run the synchronous execute_tool in a threadresult = await asyncio.to_thread(execute_tool,tool.slug,- # Models occasionally emit tool input as a JSON string (issue #2406).- normalize_tool_arguments(args),+ arguments,)# Format the result for Claude Agent SDKresult_text = result if isinstance(result, str) else json.dumps(result)@@ -136,6 +136,10 @@ class ClaudeAgentSDKProvider(return tool_handler+ def _json_schema_to_simple_schema(self, schema: dict) -> dict:+ """Return the provider-visible schema for a Composio JSON schema."""+ return alias_tool_input_schema(schema or {}).schema+def wrap_tools(self,tools: t.Sequence[Tool],diff --git a/python/providers/claude_agent_sdk/tests/test_provider.py b/python/providers/claude_agent_sdk/tests/test_provider.pyindex 07eb8697d..c885d417d 100644--- a/python/providers/claude_agent_sdk/tests/test_provider.py+++ b/python/providers/claude_agent_sdk/tests/test_provider.py@@ -2,6 +2,7 @@Tests for Claude Code Agents Provider"""+import asyncioimport jsonfrom unittest.mock import MagicMock, patch@@ -234,8 +235,7 @@ class TestCreateMcpServer:class TestToolHandlerExecution:"""Tests for tool handler execution."""- @pytest.mark.asyncio- async def test_tool_handler_success(self, provider, mock_tool):+ def test_tool_handler_success(self, provider, mock_tool):"""Test successful tool execution."""mock_execute = MagicMock(return_value={"data": "success", "successful": True})@@ -256,13 +256,12 @@ class TestToolHandlerExecution:provider.wrap_tool(mock_tool, mock_execute)# Execute the captured handler- result = await captured_handler({"to": "[email protected]"})+ result = asyncio.run(captured_handler({"to": "[email protected]"}))assert result["content"][0]["type"] == "text"assert "success" in result["content"][0]["text"]- @pytest.mark.asyncio- async def test_tool_handler_error(self, provider, mock_tool):+ def test_tool_handler_error(self, provider, mock_tool):"""Test tool execution with error."""mock_execute = MagicMock(side_effect=Exception("Test error"))@@ -280,15 +279,14 @@ class TestToolHandlerExecution:mock_sdk_tool.side_effect = capture_decoratorprovider.wrap_tool(mock_tool, mock_execute)- result = await captured_handler({"to": "[email protected]"})+ result = asyncio.run(captured_handler({"to": "[email protected]"}))assert result["content"][0]["type"] == "text"response = json.loads(result["content"][0]["text"])assert response["successful"] is Falseassert "Test error" in response["error"]- @pytest.mark.asyncio- async def test_tool_handler_string_result(self, provider, mock_tool):+ def test_tool_handler_string_result(self, provider, mock_tool):"""Test tool execution returning string result."""mock_execute = MagicMock(return_value="Simple string result")@@ -306,7 +304,7 @@ class TestToolHandlerExecution:mock_sdk_tool.side_effect = capture_decoratorprovider.wrap_tool(mock_tool, mock_execute)- result = await captured_handler({})+ result = asyncio.run(captured_handler({}))assert result["content"][0]["type"] == "text"assert result["content"][0]["text"] == "Simple string result"diff --git a/python/providers/gemini/composio_gemini/provider.py b/python/providers/gemini/composio_gemini/provider.pyindex c7e3dc2ea..0a33e10d5 100644--- a/python/providers/gemini/composio_gemini/provider.py+++ b/python/providers/gemini/composio_gemini/provider.py@@ -13,10 +13,10 @@ from composio.client.types import Toolfrom composio.core.provider import AgenticProviderfrom composio.core.provider.agentic import AgenticProviderExecuteFnfrom composio.utils.shared import (+ ToolSchemaAliases,+ alias_tool_input_schema,get_pydantic_signature_format_from_schema_params,normalize_tool_arguments,- reinstate_reserved_python_keywords,- substitute_reserved_python_keywords,)# google-genai is only needed for handle_response (backward compat)@@ -82,7 +82,9 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="geminidef __init__(self, **kwargs: t.Any):super().__init__(**kwargs)- self._executors: t.Dict[str, AgenticProviderExecuteFn] = {}+ self._executors: t.Dict[+ str, t.Tuple[AgenticProviderExecuteFn, ToolSchemaAliases]+ ] = {}def wrap_tool(self,@@ -97,19 +99,13 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini1. Derive a ``FunctionDeclaration`` schema via ``from_callable()``2. Store it in the AFC ``function_map`` for automatic execution"""- self._executors[tool.slug] = execute_tool-- # Handle reserved Python keywords in parameter names- schema_params, keywords = substitute_reserved_python_keywords(- schema=tool.input_parameters- )+ aliases = alias_tool_input_schema(schema=tool.input_parameters)+ self._executors[tool.slug] = (execute_tool, aliases)def function(**kwargs: t.Any) -> t.Dict:"""Composio tool execution wrapper."""kwargs = _to_serializable(kwargs)- kwargs = reinstate_reserved_python_keywords(- request=kwargs, keywords=keywords- )+ kwargs = aliases.restore_arguments(kwargs)# Normalize defensively so a stringified payload is coerced to a dict (issue #2406).result = execute_tool(tool.slug, normalize_tool_arguments(kwargs))return _process_execution_result(result)@@ -130,7 +126,7 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="gemini# The google-genai SDK requires parameterized array types — bare List# generates {"type": "ARRAY"} without "items", which the API rejects.sig_params = get_pydantic_signature_format_from_schema_params(- schema_params=schema_params,+ schema_params=aliases.schema,skip_default=True,)action_func.__signature__ = Signature(parameters=sig_params) # type: ignore@@ -190,8 +186,10 @@ class GeminiProvider(AgenticProvider[t.Callable, list[t.Callable]], name="geminiif fc.name not in self._executors:continue- result = self._executors[fc.name](- slug=fc.name, arguments=normalize_tool_arguments(dict(fc.args))+ execute_tool, aliases = self._executors[fc.name]+ arguments = aliases.restore_arguments(dict(fc.args))+ result = execute_tool(+ slug=fc.name, arguments=normalize_tool_arguments(arguments))processed = _process_execution_result(result)diff --git a/python/providers/google_adk/composio_google_adk/provider.py b/python/providers/google_adk/composio_google_adk/provider.pyindex ce84c0526..30b5dd4cc 100644--- a/python/providers/google_adk/composio_google_adk/provider.py+++ b/python/providers/google_adk/composio_google_adk/provider.py@@ -8,7 +8,7 @@ from composio.client.types import Toolfrom composio.core.provider import AgenticProviderfrom composio.core.provider.agentic import AgenticProviderExecuteFnfrom composio.utils.openapi import function_signature_from_jsonschema-from composio.utils.shared import normalize_tool_arguments+from composio.utils.shared import alias_tool_input_schema, normalize_tool_argumentsclass GoogleAdkProvider(@@ -36,9 +36,10 @@ class GoogleAdkProvider("required": [],},)+ aliases = alias_tool_input_schema(schema=input_parameters)properties = t.cast(t.Dict[str, t.Dict[str, t.Any]],- input_parameters.get("properties", {}),+ aliases.schema.get("properties", {}),)docstring = tool.description or f"Execute {tool.slug}"docstring += "\nArgs:"@@ -50,6 +51,7 @@ class GoogleAdkProvider(docstring += "\n A dictionary containing response from the action"def _execute(**kwargs: t.Any) -> t.Dict:+ kwargs = aliases.restore_arguments(kwargs)# Normalize defensively so a stringified payload is coerced to a dict (issue #2406).return execute_tool(slug=tool.slug, arguments=normalize_tool_arguments(kwargs)@@ -62,7 +64,7 @@ class GoogleAdkProvider(closure=_execute.__closure__,)parameters = function_signature_from_jsonschema(- schema=input_parameters,+ schema=aliases.schema,skip_default=self.skip_default,)setattr(function, "__signature__", Signature(parameters=parameters))diff --git a/python/tests/test_gemini_provider.py b/python/tests/test_gemini_provider.pyindex a20d66eb8..ba9761889 100644--- a/python/tests/test_gemini_provider.py+++ b/python/tests/test_gemini_provider.py@@ -204,7 +204,8 @@ class TestWrapTool:provider.wrap_tool(tool, execute_tool)assert "GITHUB_STAR_REPO" in provider._executors- assert provider._executors["GITHUB_STAR_REPO"] is execute_tool+ stored_execute_tool, _aliases = provider._executors["GITHUB_STAR_REPO"]+ assert stored_execute_tool is execute_tooldef test_callable_executes_correctly(self):from composio_gemini import GeminiProviderdiff --git a/python/tests/test_tool_schema_aliasing.py b/python/tests/test_tool_schema_aliasing.pynew file mode 100644index 000000000..c3186032c--- /dev/null+++ b/python/tests/test_tool_schema_aliasing.py@@ -0,0 +1,398 @@+"""Tests for provider-facing tool schema aliases."""++import asyncio+import copy+import importlib.util+import inspect+import re+import sys+import types+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import Mock++import pytest++from composio.exceptions import InvalidSchemaError+from composio.utils.shared import (+ alias_tool_input_schema,+ json_schema_to_model,+ substitute_reserved_python_keywords,+)+++PYTHON_ROOT = Path(__file__).resolve().parents[1]+ANTHROPIC_PROPERTY_RE = re.compile(r"^[a-zA-Z0-9_.-]{1,64}$")+++def _load_module(monkeypatch, module_name: str, path: Path):+ spec = importlib.util.spec_from_file_location(module_name, path)+ assert spec is not None+ assert spec.loader is not None+ module = importlib.util.module_from_spec(spec)+ monkeypatch.setitem(sys.modules, module_name, module)+ spec.loader.exec_module(module)+ return module+++def test_alias_tool_input_schema_restores_nested_aliases_without_mutating_schema():+ schema = {+ "type": "object",+ "properties": {+ "from": {"type": "string"},+ "payload": {+ "type": "object",+ "properties": {"class": {"type": "string"}},+ "required": ["class"],+ },+ "items": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {"for": {"type": "string"}},+ "required": ["for"],+ },+ },+ },+ "required": ["from", "payload"],+ }+ original = copy.deepcopy(schema)++ aliases = alias_tool_input_schema(schema)++ assert schema == original+ assert list(aliases.schema["properties"]) == ["from_rs", "payload", "items"]+ assert aliases.schema["required"] == ["from_rs", "payload"]+ assert aliases.schema["properties"]["payload"]["required"] == ["class_rs"]+ assert aliases.schema["properties"]["items"]["items"]["required"] == ["for_rs"]++ arguments = {+ "from_rs": "[email protected]",+ "payload": {"class_rs": "primary"},+ "items": [{"for_rs": "[email protected]"}],+ }+ assert aliases.restore_arguments(arguments) == {+ "from": "[email protected]",+ "payload": {"class": "primary"},+ "items": [{"for": "[email protected]"}],+ }+++def test_alias_tool_input_schema_rejects_duplicate_aliases():+ schema = {+ "type": "object",+ "properties": {+ "from": {"type": "string"},+ "from_rs": {"type": "string"},+ },+ }++ with pytest.raises(InvalidSchemaError, match="duplicate Python parameter alias"):+ alias_tool_input_schema(schema)+++def test_legacy_keyword_helpers_use_tool_schema_aliases():+ long_name = "x" * 80+ schema = {+ "title": "ODataParams",+ "type": "object",+ "properties": {+ "$top": {"type": "integer"},+ "@microsoft.graph.conflictBehavior": {"type": "string"},+ long_name: {"type": "string"},+ },+ "required": ["$top", long_name],+ }++ aliased_schema, aliases = substitute_reserved_python_keywords(schema)++ aliased_names = list(aliased_schema["properties"])+ assert aliased_names[0] == "param_top"+ assert aliased_names[1] == "param_microsoft_graph_conflictBehavior"+ assert len(aliased_names[2]) == 64+ assert all(ANTHROPIC_PROPERTY_RE.fullmatch(name) for name in aliased_names)+ assert aliased_schema["required"] == ["param_top", aliased_names[2]]+ assert aliases["param_top"] == "$top"+ assert aliases["param_microsoft_graph_conflictBehavior"] == (+ "@microsoft.graph.conflictBehavior"+ )+ assert aliases[aliased_names[2]] == long_name+ model = json_schema_to_model(aliased_schema)+ assert "param_top" in model.model_fields+++def test_alias_tool_input_schema_dereferences_refs_before_aliasing():+ schema = {+ "$ref": "#/$defs/SearchParams",+ "$defs": {+ "SearchParams": {+ "type": "object",+ "properties": {+ "filter": {"$ref": "#/$defs/ODataFilter"},+ },+ "required": ["filter"],+ },+ "ODataFilter": {+ "type": "object",+ "properties": {"$top": {"type": "integer"}},+ "required": ["$top"],+ },+ },+ }++ aliases = alias_tool_input_schema(schema)++ assert "$defs" not in aliases.schema+ assert aliases.schema["required"] == ["filter"]+ filter_schema = aliases.schema["properties"]["filter"]+ assert list(filter_schema["properties"]) == ["param_top"]+ assert filter_schema["required"] == ["param_top"]+ assert aliases.restore_arguments({"filter": {"param_top": 10}}) == {+ "filter": {"$top": 10}+ }+++def test_gemini_manual_response_restores_provider_visible_aliases(monkeypatch):+ google_module = types.ModuleType("google")+ genai_module = types.ModuleType("google.genai")+ genai_types_module = types.ModuleType("google.genai.types")++ class FunctionResponse:+ def __init__(self, name, response):+ self.name = name+ self.response = response++ class Part:+ def __init__(self, function_response):+ self.function_response = function_response++ genai_types_module.FunctionResponse = FunctionResponse+ genai_types_module.Part = Part+ genai_module.types = genai_types_module+ google_module.genai = genai_module+ monkeypatch.setitem(sys.modules, "google", google_module)+ monkeypatch.setitem(sys.modules, "google.genai", genai_module)+ monkeypatch.setitem(sys.modules, "google.genai.types", genai_types_module)++ provider_module = _load_module(+ monkeypatch,+ "test_composio_gemini_provider",+ PYTHON_ROOT / "providers/gemini/composio_gemini/provider.py",+ )+ provider = provider_module.GeminiProvider()+ execute_tool = Mock(return_value={"successful": True, "data": {"ok": True}})+ tool = SimpleNamespace(+ slug="TOOL_WITH_RESERVED",+ description="Tool with reserved parameters",+ input_parameters={+ "type": "object",+ "properties": {"for": {"type": "string"}},+ "required": ["for"],+ },+ )+ provider.wrap_tools([tool], execute_tool)++ response = SimpleNamespace(+ candidates=[+ SimpleNamespace(+ content=SimpleNamespace(+ parts=[+ SimpleNamespace(+ function_call=SimpleNamespace(+ name="TOOL_WITH_RESERVED",+ args={"for_rs": "[email protected]"},+ )+ )+ ]+ )+ )+ ]+ )++ function_responses, executed = provider.handle_response(response)++ assert executed is True+ assert function_responses[0].function_response.name == "TOOL_WITH_RESERVED"+ execute_tool.assert_called_once_with(+ slug="TOOL_WITH_RESERVED", arguments={"for": "[email protected]"}+ )+++def test_google_adk_wrap_tool_aliases_signature_and_restores_arguments(monkeypatch):+ google_module = types.ModuleType("google")+ adk_module = types.ModuleType("google.adk")+ tools_module = types.ModuleType("google.adk.tools")++ class FunctionTool:+ def __init__(self, func):+ self.func = func++ tools_module.FunctionTool = FunctionTool+ adk_module.tools = tools_module+ google_module.adk = adk_module+ monkeypatch.setitem(sys.modules, "google", google_module)+ monkeypatch.setitem(sys.modules, "google.adk", adk_module)+ monkeypatch.setitem(sys.modules, "google.adk.tools", tools_module)++ provider_module = _load_module(+ monkeypatch,+ "test_composio_google_adk_provider",+ PYTHON_ROOT / "providers/google_adk/composio_google_adk/provider.py",+ )+ provider = provider_module.GoogleAdkProvider()+ execute_tool = Mock(return_value={"successful": True, "data": {"ok": True}})+ tool = SimpleNamespace(+ slug="TOOL_WITH_RESERVED",+ description="Tool with reserved parameters",+ input_parameters={+ "type": "object",+ "properties": {+ "from": {"type": "string", "description": "Sender"},+ "limit": {"type": "integer", "description": "Limit"},+ },+ "required": ["from"],+ },+ )++ wrapped = provider.wrap_tool(tool, execute_tool)++ assert list(inspect.signature(wrapped.func).parameters) == ["from_rs", "limit"]+ assert "from_rs: Sender" in (wrapped.func.__doc__ or "")+ wrapped.func(from_rs="[email protected]", limit=10)+ execute_tool.assert_called_once_with(+ slug="TOOL_WITH_RESERVED",+ arguments={"from": "[email protected]", "limit": 10},+ )+++def test_anthropic_wrap_tool_aliases_schema_and_restores_arguments(monkeypatch):+ anthropic_module = types.ModuleType("anthropic")+ types_module = types.ModuleType("anthropic.types")+ beta_module = types.ModuleType("anthropic.types.beta")+ beta_tool_use_module = types.ModuleType("anthropic.types.beta.beta_tool_use_block")+ message_module = types.ModuleType("anthropic.types.message")+ tool_param_module = types.ModuleType("anthropic.types.tool_param")+ tool_use_module = types.ModuleType("anthropic.types.tool_use_block")++ class BetaToolUseBlock:+ pass++ class Message:+ def __init__(self, **kwargs):+ self.__dict__.update(kwargs)++ class ToolUseBlock:+ pass++ beta_tool_use_module.BetaToolUseBlock = BetaToolUseBlock+ message_module.Message = Message+ tool_param_module.ToolParam = dict+ tool_use_module.ToolUseBlock = ToolUseBlock+ monkeypatch.setitem(sys.modules, "anthropic", anthropic_module)+ monkeypatch.setitem(sys.modules, "anthropic.types", types_module)+ monkeypatch.setitem(sys.modules, "anthropic.types.beta", beta_module)+ monkeypatch.setitem(+ sys.modules,+ "anthropic.types.beta.beta_tool_use_block",+ beta_tool_use_module,+ )+ monkeypatch.setitem(sys.modules, "anthropic.types.message", message_module)+ monkeypatch.setitem(sys.modules, "anthropic.types.tool_param", tool_param_module)+ monkeypatch.setitem(sys.modules, "anthropic.types.tool_use_block", tool_use_module)++ provider_module = _load_module(+ monkeypatch,+ "test_composio_anthropic_provider",+ PYTHON_ROOT / "providers/anthropic/composio_anthropic/provider.py",+ )+ provider = provider_module.AnthropicProvider()+ provider.execute_tool = Mock(return_value={"successful": True})+ long_name = "x" * 80+ tool = SimpleNamespace(+ slug="TOOL_WITH_ODATA",+ description="Tool with OData parameters",+ input_parameters={+ "type": "object",+ "properties": {+ "$top": {"type": "integer"},+ "@microsoft.graph.conflictBehavior": {"type": "string"},+ long_name: {"type": "string"},+ },+ "required": ["$top", long_name],+ },+ )++ wrapped = provider.wrap_tool(tool)++ aliased_names = list(wrapped["input_schema"]["properties"])+ assert aliased_names[0] == "param_top"+ assert aliased_names[1] == "param_microsoft_graph_conflictBehavior"+ assert len(aliased_names[2]) == 64+ assert all(ANTHROPIC_PROPERTY_RE.fullmatch(name) for name in aliased_names)++ tool_call = SimpleNamespace(+ name="TOOL_WITH_ODATA",+ input={+ "param_top": 10,+ "param_microsoft_graph_conflictBehavior": "rename",+ aliased_names[2]: "value",+ },+ )+ provider.execute_tool_call(user_id="user", tool_call=tool_call)++ provider.execute_tool.assert_called_once_with(+ slug="TOOL_WITH_ODATA",+ arguments={+ "$top": 10,+ "@microsoft.graph.conflictBehavior": "rename",+ long_name: "value",+ },+ modifiers=None,+ user_id="user",+ )+++def test_claude_agent_sdk_wrap_tool_aliases_schema_and_restores_arguments(monkeypatch):+ claude_agent_sdk_module = types.ModuleType("claude_agent_sdk")++ def sdk_tool(name, description, input_schema):+ def decorator(fn):+ fn._tool_name = name+ fn._tool_description = description+ fn._input_schema = input_schema+ return fn++ return decorator++ claude_agent_sdk_module.McpSdkServerConfig = dict+ claude_agent_sdk_module.SdkMcpTool = object+ claude_agent_sdk_module.create_sdk_mcp_server = Mock()+ claude_agent_sdk_module.tool = sdk_tool+ monkeypatch.setitem(sys.modules, "claude_agent_sdk", claude_agent_sdk_module)++ provider_module = _load_module(+ monkeypatch,+ "test_composio_claude_agent_sdk_provider",+ PYTHON_ROOT+ / "providers/claude_agent_sdk/composio_claude_agent_sdk/provider.py",+ )+ provider = provider_module.ClaudeAgentSDKProvider()+ execute_tool = Mock(return_value={"successful": True})+ tool = SimpleNamespace(+ slug="TOOL_WITH_ODATA",+ description="Tool with OData parameters",+ input_parameters={+ "type": "object",+ "properties": {"$top": {"type": "integer"}},+ "required": ["$top"],+ },+ )++ wrapped = provider.wrap_tool(tool, execute_tool)++ assert list(wrapped._input_schema["properties"]) == ["param_top"]+ assert wrapped._input_schema["required"] == ["param_top"]+ result = asyncio.run(wrapped({"param_top": 5}))++ assert result["content"][0]["type"] == "text"+ execute_tool.assert_called_once_with("TOOL_WITH_ODATA", {"$top": 5})