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): fix nested pydantic serialization
jkomynoc04d6724abed
diff --git a/python/composio/core/models/tools.py b/python/composio/core/models/tools.pyindex f79fa98ec..8129dc051 100644--- a/python/composio/core/models/tools.py+++ b/python/composio/core/models/tools.py@@ -4,6 +4,7 @@ import functoolsimport typing as timport typing_extensions as te+from pydantic import BaseModel as PydanticBaseModelfrom composio_client import omitfrom composio.client import HttpClient@@ -36,6 +37,40 @@ from ._modifiers import ()+def _needs_serialization(obj: t.Any) -> bool:+ """Check if an object contains any Pydantic model instances."""+ if isinstance(obj, PydanticBaseModel):+ return True+ if isinstance(obj, dict):+ return any(_needs_serialization(v) for v in obj.values())+ if isinstance(obj, list):+ return any(_needs_serialization(item) for item in obj)+ return False+++def _serialize_value(obj: t.Any) -> t.Any:+ """Recursively convert Pydantic models to JSON-safe primitives."""+ if isinstance(obj, PydanticBaseModel):+ return obj.model_dump(mode="json")+ if isinstance(obj, dict):+ return {k: _serialize_value(v) for k, v in obj.items()}+ if isinstance(obj, list):+ return [_serialize_value(item) for item in obj]+ return obj+++def _serialize_arguments(arguments: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:+ """Serialize any Pydantic model instances in tool arguments to JSON-safe dicts.++ Prevents JSON serialization errors when arguments contain complex types+ (e.g., RootModel from discriminated union schemas). Returns the original+ dict unchanged when no Pydantic models are present.+ """+ if not _needs_serialization(arguments):+ return arguments+ return {k: _serialize_value(v) for k, v in arguments.items()}++class ToolExecutionResponse(te.TypedDict):data: t.Dicterror: t.Optional[str]@@ -410,6 +445,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):)processed_arguments = modified_params.get("arguments", arguments)+ # Serialize any Pydantic model instances before sending to the API+ processed_arguments = _serialize_arguments(processed_arguments)+# Execute the tool via the session's execute_meta endpoint# Note: execute_meta accepts regular tool slugs at runtime, not just meta tool slugs# The type signature expects Literal meta tool slugs, but runtime accepts any str@@ -481,6 +519,10 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):dangerously_skip_version_check: t.Optional[bool] = None,) -> ToolExecutionResponse:"""Execute a tool"""+ # Serialize any Pydantic model instances in arguments to plain dicts+ # before sending to the API (fixes PLEN-1514: RootModel not JSON serializable)+ arguments = _serialize_arguments(arguments)+# Get the tool to determine its toolkittool = self.get_raw_composio_tool_by_slug(slug)diff --git a/python/tests/test_tool_execution.py b/python/tests/test_tool_execution.pyindex 5a401ca06..5ad603dd8 100644--- a/python/tests/test_tool_execution.py+++ b/python/tests/test_tool_execution.py@@ -1,12 +1,13 @@-"""Test tool execution with toolkit versions."""+"""Test tool execution with toolkit versions and argument serialization."""from unittest.mock import Mock, patchimport pytest+from pydantic import BaseModel, RootModelfrom composio.client.types import Tool, tool_list_responsefrom composio.core.models.base import allow_tracking-from composio.core.models.tools import Tools+from composio.core.models.tools import Tools, _serialize_arguments, _needs_serializationfrom composio.exceptions import ToolVersionRequiredError@@ -984,3 +985,134 @@ class TestToolExecution:mock_client.tools.execute.assert_called_once()call_args = mock_client.tools.execute.call_argsassert call_args.kwargs["custom_connection_data"] == custom_connection+++class TestSerializeArguments:+ """Test _serialize_arguments and _needs_serialization helpers."""++ def test_plain_dict_returns_same_object(self):+ """When no Pydantic models are present, return the original dict (no copy)."""+ args = {"page_id": "abc-123", "title": "Hello"}+ result = _serialize_arguments(args)+ assert result is args++ def test_needs_serialization_false_for_primitives(self):+ assert not _needs_serialization({"s": "hello", "i": 42, "b": True})++ def test_needs_serialization_true_for_basemodel(self):+ class M(BaseModel):+ x: int++ assert _needs_serialization({"m": M(x=1)})++ def test_basemodel_serialized(self):+ class Block(BaseModel):+ type: str+ content: str++ result = _serialize_arguments(+ {"block": Block(type="paragraph", content="Hello")}+ )+ assert result == {"block": {"type": "paragraph", "content": "Hello"}}++ def test_rootmodel_list_serialized(self):+ class Block(BaseModel):+ type: str++ class BlockList(RootModel[list[Block]]):+ pass++ blocks = BlockList([Block(type="paragraph"), Block(type="heading_1")])+ result = _serialize_arguments({"children": blocks})+ assert result == {"children": [{"type": "paragraph"}, {"type": "heading_1"}]}++ def test_list_of_models_serialized(self):+ class Block(BaseModel):+ type: str++ result = _serialize_arguments(+ {"children": [Block(type="paragraph"), Block(type="heading_1")]}+ )+ assert result == {"children": [{"type": "paragraph"}, {"type": "heading_1"}]}++ def test_nested_dict_with_models(self):+ class Inner(BaseModel):+ value: int++ result = _serialize_arguments({"outer": {"inner": Inner(value=42)}})+ assert result == {"outer": {"inner": {"value": 42}}}++ def test_execute_tool_serializes_pydantic_arguments(self):+ """Regression test for PLEN-1514: Pydantic models in arguments must be+ serialized to plain dicts before being sent to the API."""+ mock_client = Mock()+ mock_provider = Mock()+ mock_provider.name = "test_provider"++ tools = Tools(+ client=mock_client,+ provider=mock_provider,+ toolkit_versions={"notion": "latest"},+ )++ notion_tool = Tool(+ name="Test NOTION_REPLACE_PAGE_CONTENT",+ slug="NOTION_REPLACE_PAGE_CONTENT",+ description="Test tool",+ input_parameters={},+ output_parameters={},+ available_versions=["v1.0.0"],+ version="v1.0.0",+ scopes=[],+ status="active",+ toolkit=tool_list_response.ItemToolkit(+ name="Notion", slug="notion", logo=""+ ),+ deprecated=tool_list_response.ItemDeprecated(+ available_versions=["v1.0.0"],+ displayName="Test NOTION_REPLACE_PAGE_CONTENT",+ version="v1.0.0",+ toolkit=tool_list_response.ItemDeprecatedToolkit(logo=""),+ is_deprecated=False,+ ),+ is_deprecated=False,+ no_auth=False,+ tags=[],+ )++ class Block(BaseModel):+ type: str+ content: str++ with patch.object(+ tools, "get_raw_composio_tool_by_slug", return_value=notion_tool+ ):+ mock_response = Mock()+ mock_response.model_dump.return_value = {+ "data": {"result": "success"},+ "error": None,+ "successful": True,+ }+ mock_client.tools.execute.return_value = mock_response++ tools._execute_tool(+ slug="NOTION_REPLACE_PAGE_CONTENT",+ arguments={+ "page_id": "abc-123",+ "children": [+ Block(type="paragraph", content="Hello from composio"),+ ],+ },+ dangerously_skip_version_check=True,+ )++ call_args = mock_client.tools.execute.call_args+ sent_arguments = call_args.kwargs["arguments"]+ assert sent_arguments == {+ "page_id": "abc-123",+ "children": [+ {"type": "paragraph", "content": "Hello from composio"},+ ],+ }+ for child in sent_arguments["children"]:+ assert not isinstance(child, BaseModel)