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 22, 09:30 UTC
fix(py): fix nested pydantic serialization
jkomyno committed
Feb 11, 2026 at 21:23 UTC
c04d6724abed724682f42044da797dffa676d869
2 files changed
+176
-2
python/composio/core/models/tools.py
+42
@@ -4,6 +4,7 @@ import functools
4
import typing as t
5
6
import typing_extensions as te
7
+from pydantic import BaseModel as PydanticBaseModel
8
from composio_client import omit
9
10
from composio.client import HttpClient
@@ -36,6 +37,40 @@ from ._modifiers import (
37
)
38
39
40
+def _needs_serialization(obj: t.Any) -> bool:
41
+ """Check if an object contains any Pydantic model instances."""
42
+ if isinstance(obj, PydanticBaseModel):
43
+ return True
44
+ if isinstance(obj, dict):
45
+ return any(_needs_serialization(v) for v in obj.values())
46
+ if isinstance(obj, list):
47
+ return any(_needs_serialization(item) for item in obj)
48
+ return False
49
+
50
+
51
+def _serialize_value(obj: t.Any) -> t.Any:
52
+ """Recursively convert Pydantic models to JSON-safe primitives."""
53
+ if isinstance(obj, PydanticBaseModel):
54
+ return obj.model_dump(mode="json")
55
+ if isinstance(obj, dict):
56
+ return {k: _serialize_value(v) for k, v in obj.items()}
57
+ if isinstance(obj, list):
58
+ return [_serialize_value(item) for item in obj]
59
+ return obj
60
+
61
+
62
+def _serialize_arguments(arguments: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
63
+ """Serialize any Pydantic model instances in tool arguments to JSON-safe dicts.
64
+
65
+ Prevents JSON serialization errors when arguments contain complex types
66
+ (e.g., RootModel from discriminated union schemas). Returns the original
67
+ dict unchanged when no Pydantic models are present.
68
+ """
69
+ if not _needs_serialization(arguments):
70
+ return arguments
71
+ return {k: _serialize_value(v) for k, v in arguments.items()}
72
+
73
+
74
class ToolExecutionResponse(te.TypedDict):
75
data: t.Dict
76
error: t.Optional[str]
@@ -410,6 +445,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
445
)
446
processed_arguments = modified_params.get("arguments", arguments)
447
448
+ # Serialize any Pydantic model instances before sending to the API
449
+ processed_arguments = _serialize_arguments(processed_arguments)
450
+
451
# Execute the tool via the session's execute_meta endpoint
452
# Note: execute_meta accepts regular tool slugs at runtime, not just meta tool slugs
453
# The type signature expects Literal meta tool slugs, but runtime accepts any str
@@ -481,6 +519,10 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
519
dangerously_skip_version_check: t.Optional[bool] = None,
520
) -> ToolExecutionResponse:
521
"""Execute a tool"""
522
+ # Serialize any Pydantic model instances in arguments to plain dicts
523
+ # before sending to the API (fixes PLEN-1514: RootModel not JSON serializable)
524
+ arguments = _serialize_arguments(arguments)
525
+
526
# Get the tool to determine its toolkit
527
tool = self.get_raw_composio_tool_by_slug(slug)
528
python/tests/test_tool_execution.py
+134
-2
@@ -1,12 +1,13 @@
1
-"""Test tool execution with toolkit versions."""
1
+"""Test tool execution with toolkit versions and argument serialization."""
2
3
from unittest.mock import Mock, patch
4
5
import pytest
6
+from pydantic import BaseModel, RootModel
7
8
from composio.client.types import Tool, tool_list_response
9
from composio.core.models.base import allow_tracking
9
-from composio.core.models.tools import Tools
10
+from composio.core.models.tools import Tools, _serialize_arguments, _needs_serialization
11
from composio.exceptions import ToolVersionRequiredError
12
13
@@ -984,3 +985,134 @@ class TestToolExecution:
985
mock_client.tools.execute.assert_called_once()
986
call_args = mock_client.tools.execute.call_args
987
assert call_args.kwargs["custom_connection_data"] == custom_connection
988
+
989
+
990
+class TestSerializeArguments:
991
+ """Test _serialize_arguments and _needs_serialization helpers."""
992
+
993
+ def test_plain_dict_returns_same_object(self):
994
+ """When no Pydantic models are present, return the original dict (no copy)."""
995
+ args = {"page_id": "abc-123", "title": "Hello"}
996
+ result = _serialize_arguments(args)
997
+ assert result is args
998
+
999
+ def test_needs_serialization_false_for_primitives(self):
1000
+ assert not _needs_serialization({"s": "hello", "i": 42, "b": True})
1001
+
1002
+ def test_needs_serialization_true_for_basemodel(self):
1003
+ class M(BaseModel):
1004
+ x: int
1005
+
1006
+ assert _needs_serialization({"m": M(x=1)})
1007
+
1008
+ def test_basemodel_serialized(self):
1009
+ class Block(BaseModel):
1010
+ type: str
1011
+ content: str
1012
+
1013
+ result = _serialize_arguments(
1014
+ {"block": Block(type="paragraph", content="Hello")}
1015
+ )
1016
+ assert result == {"block": {"type": "paragraph", "content": "Hello"}}
1017
+
1018
+ def test_rootmodel_list_serialized(self):
1019
+ class Block(BaseModel):
1020
+ type: str
1021
+
1022
+ class BlockList(RootModel[list[Block]]):
1023
+ pass
1024
+
1025
+ blocks = BlockList([Block(type="paragraph"), Block(type="heading_1")])
1026
+ result = _serialize_arguments({"children": blocks})
1027
+ assert result == {"children": [{"type": "paragraph"}, {"type": "heading_1"}]}
1028
+
1029
+ def test_list_of_models_serialized(self):
1030
+ class Block(BaseModel):
1031
+ type: str
1032
+
1033
+ result = _serialize_arguments(
1034
+ {"children": [Block(type="paragraph"), Block(type="heading_1")]}
1035
+ )
1036
+ assert result == {"children": [{"type": "paragraph"}, {"type": "heading_1"}]}
1037
+
1038
+ def test_nested_dict_with_models(self):
1039
+ class Inner(BaseModel):
1040
+ value: int
1041
+
1042
+ result = _serialize_arguments({"outer": {"inner": Inner(value=42)}})
1043
+ assert result == {"outer": {"inner": {"value": 42}}}
1044
+
1045
+ def test_execute_tool_serializes_pydantic_arguments(self):
1046
+ """Regression test for PLEN-1514: Pydantic models in arguments must be
1047
+ serialized to plain dicts before being sent to the API."""
1048
+ mock_client = Mock()
1049
+ mock_provider = Mock()
1050
+ mock_provider.name = "test_provider"
1051
+
1052
+ tools = Tools(
1053
+ client=mock_client,
1054
+ provider=mock_provider,
1055
+ toolkit_versions={"notion": "latest"},
1056
+ )
1057
+
1058
+ notion_tool = Tool(
1059
+ name="Test NOTION_REPLACE_PAGE_CONTENT",
1060
+ slug="NOTION_REPLACE_PAGE_CONTENT",
1061
+ description="Test tool",
1062
+ input_parameters={},
1063
+ output_parameters={},
1064
+ available_versions=["v1.0.0"],
1065
+ version="v1.0.0",
1066
+ scopes=[],
1067
+ status="active",
1068
+ toolkit=tool_list_response.ItemToolkit(
1069
+ name="Notion", slug="notion", logo=""
1070
+ ),
1071
+ deprecated=tool_list_response.ItemDeprecated(
1072
+ available_versions=["v1.0.0"],
1073
+ displayName="Test NOTION_REPLACE_PAGE_CONTENT",
1074
+ version="v1.0.0",
1075
+ toolkit=tool_list_response.ItemDeprecatedToolkit(logo=""),
1076
+ is_deprecated=False,
1077
+ ),
1078
+ is_deprecated=False,
1079
+ no_auth=False,
1080
+ tags=[],
1081
+ )
1082
+
1083
+ class Block(BaseModel):
1084
+ type: str
1085
+ content: str
1086
+
1087
+ with patch.object(
1088
+ tools, "get_raw_composio_tool_by_slug", return_value=notion_tool
1089
+ ):
1090
+ mock_response = Mock()
1091
+ mock_response.model_dump.return_value = {
1092
+ "data": {"result": "success"},
1093
+ "error": None,
1094
+ "successful": True,
1095
+ }
1096
+ mock_client.tools.execute.return_value = mock_response
1097
+
1098
+ tools._execute_tool(
1099
+ slug="NOTION_REPLACE_PAGE_CONTENT",
1100
+ arguments={
1101
+ "page_id": "abc-123",
1102
+ "children": [
1103
+ Block(type="paragraph", content="Hello from composio"),
1104
+ ],
1105
+ },
1106
+ dangerously_skip_version_check=True,
1107
+ )
1108
+
1109
+ call_args = mock_client.tools.execute.call_args
1110
+ sent_arguments = call_args.kwargs["arguments"]
1111
+ assert sent_arguments == {
1112
+ "page_id": "abc-123",
1113
+ "children": [
1114
+ {"type": "paragraph", "content": "Hello from composio"},
1115
+ ],
1116
+ }
1117
+ for child in sent_arguments["children"]:
1118
+ assert not isinstance(child, BaseModel)