@devries-cameron20 / composio-1 / commits / 6aea85fda
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 Pydantic field aliases in Python tool execution (#4907)

## Summary Python tool execution currently converts Pydantic models to dictionaries using their Python field names, even when the models declare aliases. For example, a field named `display_name` with the alias `displayName` is sent as `display_name`, which can disagree with the tool's schema. This preserves the declared aliases when serializing model arguments. Fixes #4904 ## Changes - Use `by_alias=True` in the core Pydantic argument serializer. Optional fields, defaults, and null values keep their existing behavior. - Add HTTP-level regression tests for direct models, lists, nested dictionaries, root models, and tuples, covering both ordinary aliases and explicit serialization aliases. - Add a nested-model regression that checks defaults and null values remain present and input models are not modified. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? Python 3.12.13, Pydantic 2.14.1, composio-client 2.0.0rc16. Before the production change, nine new regression cases failed on incorrect argument keys. Both tuple controls passed. With the change, all 50 tests in `tests/test_tool_execution.py` pass. Run from `python/` in the SDK test environment: ```sh python -m pytest tests/test_tool_execution.py tests/test_tool_router.py tests/test_tool_router_session_files.py tests/test_normalize_tool_arguments.py tests/test_tool_retrieval_errors.py tests/test_tools_proxy.py tests/test_custom_tools.py tests/test_imports.py tests/test_sdk.py --timeout=20 -q --tb=short python -m pytest tests/test_tool_schema_aliasing.py tests/test_provider_argument_serialization.py --timeout=20 -q --tb=short ruff check --config config/ruff.toml composio/core/models/tools.py tests/test_tool_execution.py ruff format --check composio/core/models/tools.py tests/test_tool_execution.py mypy --config-file config/mypy.ini composio/core/models/tools.py tests/test_tool_execution.py ``` - First pytest command: 435 passed, with an existing unknown `core` marker warning. - Second pytest command: 9 passed, 32 skipped because optional provider packages are not installed. - Ruff lint and formatting: passed for both changed files. - `git diff --check`: passed. - Mypy 2.3.1: reports one error in untouched `composio/utils/schema_converter.py:813` involving `TypeAdapter`/`TypeForm`. I verified the same error with the production change removed. The HTTP regressions use the real SDK client with `httpx.MockTransport` to inspect outgoing JSON. No live toolkit or credentials were used. The complete provider/nox test matrix has not been run locally. ## Screenshots (if applicable) Not applicable. ## Checklist - [ ] I have read the Code of Conduct and this PR adheres to it - [ ] I have read and understand every line of this diff, including any LLM-generated code - [ ] Any third-party docs links or promotional content follow the third-party links policy - [ ] I ran linters/tests locally and they passed - [ ] I updated documentation as needed - [ ] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages ## Additional context Python-only runtime fix; no TypeScript changeset is needed under the contribution guidelines. No public signatures or dependencies change.

Gaurav Chintakunta committed Oct 16, 2026 at 04:37 UTC 6aea85fda5756a28b49605c60a7e0785cc6157fd
2 files changed +94 -2
python/composio/core/models/tools.py
+1 -1
@@ -107,7 +107,7 @@ def _needs_serialization(obj: t.Any) -> bool:
107 def _serialize_value(obj: t.Any) -> t.Any:
108 """Recursively convert Pydantic models to JSON-safe primitives."""
109 if isinstance(obj, PydanticBaseModel):
110 - return obj.model_dump(mode="json")
110 + return obj.model_dump(mode="json", by_alias=True)
111 if isinstance(obj, dict):
112 return {k: _serialize_value(v) for k, v in obj.items()}
113 if isinstance(obj, list):
python/tests/test_tool_execution.py
+93 -1
@@ -1,15 +1,19 @@
1 """Test tool execution with toolkit versions and argument serialization."""
2
3 +import json
4 import typing as t
5 from unittest.mock import Mock, patch
6
7 +import httpx
8 import pytest
9 from composio_client import omit
8 -from pydantic import BaseModel, RootModel
10 +from pydantic import BaseModel, Field, RootModel
11
12 +from composio.client import HttpClient
13 from composio.client.types import Tool, tool_list_response
14 from composio.core.models.base import allow_tracking
15 from composio.core.models.tools import Tools, _needs_serialization, _serialize_arguments
16 +from composio.core.provider._openai import OpenAIProvider
17 from composio.exceptions import ToolVersionRequiredError
18 from tests.conftest import mock_http_client
19
@@ -1425,6 +1429,94 @@ class TestSerializeArguments:
1429 result = _serialize_arguments({"outer": {"inner": Inner(value=42)}})
1430 assert result == {"outer": {"inner": {"value": 42}}}
1431
1432 + @pytest.mark.parametrize("shape", ["direct", "list", "dict", "root", "tuple"])
1433 + @pytest.mark.parametrize("serialization_alias", [None, "label"])
1434 + def test_execute_preserves_model_aliases_on_the_wire(
1435 + self, shape, serialization_alias
1436 + ):
1437 + """Model arguments must use the same names as their JSON schema."""
1438 +
1439 + class Block(BaseModel):
1440 + display_name: str = Field(
1441 + alias="displayName", serialization_alias=serialization_alias
1442 + )
1443 +
1444 + block = Block(displayName="paragraph")
1445 + expected = {serialization_alias or "displayName": "paragraph"}
1446 + schema = Block.model_json_schema(mode="serialization")
1447 + if shape in ("list", "tuple", "root"):
1448 + value = [block]
1449 + expected = [expected]
1450 + schema = {"type": "array", "items": schema}
1451 + if shape == "tuple":
1452 + value = tuple(value)
1453 + elif shape == "root":
1454 + value = RootModel[list[Block]](value)
1455 + elif shape == "dict":
1456 + value = {"child": block}
1457 + expected = {"child": expected}
1458 + schema = {"type": "object", "properties": {"child": schema}}
1459 + else:
1460 + value = block
1461 +
1462 + tool = TestToolExecution().create_mock_tool("TEST_TOOL", "test")
1463 + tool.input_parameters = {
1464 + "type": "object",
1465 + "properties": {"payload": schema},
1466 + }
1467 + bodies = []
1468 +
1469 + def respond(request):
1470 + if request.method == "GET":
1471 + return httpx.Response(200, json=tool.model_dump(mode="json"))
1472 + bodies.append(json.loads(request.content))
1473 + return httpx.Response(
1474 + 200, json={"data": {}, "error": None, "successful": True}
1475 + )
1476 +
1477 + with httpx.Client(transport=httpx.MockTransport(respond)) as transport:
1478 + client = HttpClient(
1479 + provider="openai",
1480 + api_key="test-key",
1481 + base_url="https://composio.invalid",
1482 + http_client=transport,
1483 + _environment_variables={},
1484 + )
1485 + tools = Tools(client=client, provider=OpenAIProvider())
1486 + result = tools.execute(
1487 + "TEST_TOOL",
1488 + arguments={"payload": value},
1489 + version="v1.0.0",
1490 + )
1491 +
1492 + assert result["successful"] is True
1493 + assert len(bodies) == 1
1494 + assert bodies[0]["arguments"] == {"payload": expected}
1495 +
1496 + def test_model_aliases_preserve_defaults_and_nulls(self):
1497 + class Child(BaseModel):
1498 + display_name: str = Field(alias="displayName")
1499 + optional_value: str | None = Field(default=None, alias="optionalValue")
1500 + default_value: int = Field(default=42, alias="defaultValue")
1501 +
1502 + class Parent(BaseModel):
1503 + child_model: Child = Field(alias="childModel")
1504 +
1505 + child = Child(displayName="paragraph")
1506 + parent = Parent(childModel=child)
1507 +
1508 + assert _serialize_arguments({"payload": parent}) == {
1509 + "payload": {
1510 + "childModel": {
1511 + "displayName": "paragraph",
1512 + "optionalValue": None,
1513 + "defaultValue": 42,
1514 + }
1515 + }
1516 + }
1517 + assert parent.child_model is child
1518 + assert child.model_fields_set == {"display_name"}
1519 +
1520 def test_execute_tool_serializes_pydantic_arguments(self):
1521 """Regression test for PLEN-1514: Pydantic models in arguments must be
1522 serialized to plain dicts before being sent to the API."""