Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 167 lines 6.04 KB
Raw
1 """Guard the generated-client response shape the SDK reads by attribute.
2
3 Several SDK code paths walk a generated-client response two or more levels deep
4 -- ``item.meta.logo``, ``item.connected_account.auth_config.id``,
5 ``response.commands.claude``. That only works while the client constructs those
6 nested objects as models.
7
8 The rest of the suite mocks the client with ``MagicMock``, which answers every
9 attribute regardless of the real response shape, so a client release that stops
10 building nested models passes here and fails against the live backend instead.
11 These tests close that gap: they build responses through the *installed*
12 client's own response models, so a client whose nested fields decay to plain
13 mappings fails locally.
14 """
15
16 import typing as t
17 from unittest.mock import MagicMock
18
19 import httpx
20
21 import pytest
22 from composio_client.types.mcp.custom_create_response import CustomCreateResponse
23 from composio_client.types.tool_router.session_toolkits_response import (
24 SessionToolkitsResponse,
25 )
26 from pydantic import BaseModel
27
28 from composio.core.models.mcp import MCP
29 from composio.core.models.tool_router import ToolkitConnectionsDetails, ToolRouter
30
31 TOOLKITS_PAYLOAD: t.Dict[str, t.Any] = {
32 "current_page": 1,
33 "total_items": 2,
34 "total_pages": 1,
35 "next_cursor": "cursor_789",
36 "items": [
37 {
38 "slug": "gmail",
39 "name": "Gmail",
40 "enabled": True,
41 "is_no_auth": False,
42 "composio_managed_auth_schemes": ["OAUTH2"],
43 "meta": {"description": "Gmail toolkit", "logo": "https://logo/gmail.png"},
44 "connected_account": {
45 "id": "conn_123",
46 "status": "ACTIVE",
47 "created_at": "2026-01-01T00:00:00Z",
48 "user_id": "user_123",
49 "auth_config": {
50 "id": "auth_config_123",
51 "auth_scheme": "OAUTH2",
52 "is_composio_managed": True,
53 },
54 },
55 },
56 {
57 "slug": "github",
58 "name": "GitHub",
59 "enabled": True,
60 "is_no_auth": False,
61 "composio_managed_auth_schemes": [],
62 "meta": {"description": "GitHub toolkit", "logo": "https://logo/gh.png"},
63 },
64 ],
65 }
66
67 MCP_CREATE_PAYLOAD: t.Dict[str, t.Any] = {
68 "id": "mcp_123",
69 "name": "test-server",
70 "allowed_tools": ["GITHUB_CREATE_ISSUE"],
71 "auth_config_ids": ["ac_123"],
72 "mcp_url": "https://mcp.composio.dev/mcp_123",
73 "commands": {
74 "claude": "claude mcp add ...",
75 "cursor": "cursor://...",
76 "windsurf": "windsurf://...",
77 },
78 }
79
80
81 @pytest.mark.parametrize(
82 ("model", "payload", "path"),
83 [
84 (SessionToolkitsResponse, TOOLKITS_PAYLOAD, "items.0.meta"),
85 (SessionToolkitsResponse, TOOLKITS_PAYLOAD, "items.0.connected_account"),
86 (
87 SessionToolkitsResponse,
88 TOOLKITS_PAYLOAD,
89 "items.0.connected_account.auth_config",
90 ),
91 (CustomCreateResponse, MCP_CREATE_PAYLOAD, "commands"),
92 ],
93 )
94 def test_generated_client_builds_nested_response_models(
95 model: t.Type[BaseModel], payload: t.Dict[str, t.Any], path: str
96 ) -> None:
97 """A nested response field must arrive as a model, not a bare mapping."""
98 root: t.Any = model.model_validate(payload)
99 for part in path.split("."):
100 root = root[int(part)] if part.isdigit() else getattr(root, part)
101
102 assert isinstance(root, BaseModel), (
103 f"{model.__name__}.{path} is a {type(root).__name__}, not a model. The SDK "
104 f"reads this field by attribute, so a generated client that leaves nested "
105 f"objects as mappings breaks it at runtime."
106 )
107
108
109 def _client_with_session() -> MagicMock:
110 """A mocked client whose session.create is just real enough to build a session."""
111 client = MagicMock()
112 client.base_url = httpx.URL("https://backend.composio.dev")
113 client.default_headers = {}
114 session_response = MagicMock()
115 session_response.session_id = "session_123"
116 session_response.mcp.type = "http"
117 session_response.mcp.url = (
118 "https://backend.composio.dev/api/v3/tool_router/session/session_123"
119 )
120 session_response.config.preload.tools = []
121 session_response.experimental = None
122 client.tool_router.session.create.return_value = session_response
123 return client
124
125
126 def test_session_toolkits_reads_nested_connection_models() -> None:
127 """``Session.toolkits()`` walks meta and connected_account by attribute."""
128 client = _client_with_session()
129 client.tool_router.session.toolkits.return_value = (
130 SessionToolkitsResponse.model_validate(TOOLKITS_PAYLOAD)
131 )
132 session = ToolRouter(client=client, provider=MagicMock()).create(user_id="user_123")
133
134 result = session.toolkits()
135
136 assert isinstance(result, ToolkitConnectionsDetails)
137 gmail, github = result.items
138
139 assert gmail.slug == "gmail"
140 assert gmail.logo == "https://logo/gmail.png"
141 assert gmail.connection is not None
142 assert gmail.connection.is_active is True
143 assert gmail.connection.auth_config is not None
144 assert gmail.connection.auth_config.id == "auth_config_123"
145 assert gmail.connection.auth_config.mode == "OAUTH2"
146 assert gmail.connection.auth_config.is_composio_managed is True
147 assert gmail.connection.connected_account is not None
148 assert gmail.connection.connected_account.id == "conn_123"
149
150 assert github.slug == "github"
151 assert github.connection is not None
152 assert github.connection.is_active is False
153 assert github.connection.auth_config is None
154
155
156 def test_mcp_create_returns_attribute_addressable_commands() -> None:
157 """``mcp.create()`` hands callers a ``commands`` object, not a mapping."""
158 client = MagicMock()
159 client.mcp.custom.create.return_value = CustomCreateResponse.model_validate(
160 MCP_CREATE_PAYLOAD
161 )
162
163 response = MCP(client=client).create(name="test-server", toolkits=["github"])
164
165 assert response.commands.claude == "claude mcp add ..."
166 assert response.commands.cursor == "cursor://..."
167 assert response.commands.windsurf == "windsurf://..."