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 249 lines 7.87 KB
Raw
1 """Unit tests for the MCP model's request construction.
2
3 Regression coverage for the hackathon Area 5 (MCP lifecycle) findings:
4
5 - Tool-only updates must reach the API through ``allowed_tools`` — the update
6 endpoint never reads the create-time ``custom_tools`` alias, and tools must
7 not be gated behind ``toolkits``.
8 - ``manually_manage_connections`` must invert into
9 ``managed_auth_via_composio`` on update, matching create/generate.
10 - ``create`` uses the non-deprecated ``allowed_tools`` field.
11 """
12
13 import json
14 import subprocess
15 import sys
16 import typing as t
17 import warnings
18 from unittest.mock import Mock
19
20 import httpx
21 import pytest
22 from composio_client import ProjectAuth
23
24 from composio import ComposioDeprecationWarning
25 from composio.client import HttpClient
26 from composio.core.models import mcp as mcp_module
27 from composio.core.models.mcp import MCP
28
29
30 def _mock_update_response():
31 response = Mock()
32 response.id = "mcp_123"
33 response.name = "test-server"
34 response.allowed_tools = ["GITHUB_CREATE_ISSUE"]
35 response.auth_config_ids = ["ac_456"]
36 return response
37
38
39 @pytest.fixture
40 def mcp():
41 client = Mock()
42 client.mcp.update = Mock(return_value=_mock_update_response())
43 client.mcp.custom.create = Mock(return_value=_mock_update_response())
44 return MCP(client)
45
46
47 def test_update_sends_tool_only_updates_via_allowed_tools(mcp):
48 """A tool-only update (no toolkits) must send `allowed_tools`."""
49 mcp.update("mcp_123", allowed_tools=["GITHUB_CREATE_ISSUE"])
50
51 mcp._client.mcp.update.assert_called_once_with(
52 "mcp_123",
53 allowed_tools=["GITHUB_CREATE_ISSUE"],
54 )
55
56
57 def test_update_does_not_send_custom_tools_alias(mcp):
58 """`custom_tools` is not part of the update contract and is dropped
59 server-side; the SDK must never send it."""
60 mcp.update(
61 "mcp_123",
62 toolkits=["github"],
63 allowed_tools=["GITHUB_CREATE_ISSUE"],
64 )
65
66 call_kwargs = mcp._client.mcp.update.call_args.kwargs
67 assert "custom_tools" not in call_kwargs
68 assert call_kwargs["allowed_tools"] == ["GITHUB_CREATE_ISSUE"]
69 assert call_kwargs["toolkits"] == ["github"]
70 assert call_kwargs["auth_config_ids"] == []
71
72
73 def test_update_inverts_manually_manage_connections(mcp):
74 """`manually_manage_connections=True` must store
75 `managed_auth_via_composio=False`, consistent with create/generate."""
76 mcp.update("mcp_123", manually_manage_connections=True)
77 assert mcp._client.mcp.update.call_args.kwargs["managed_auth_via_composio"] is False
78
79 mcp.update("mcp_123", manually_manage_connections=False)
80 assert mcp._client.mcp.update.call_args.kwargs["managed_auth_via_composio"] is True
81
82
83 def test_update_omits_unset_fields(mcp):
84 """A sparse update must only send the fields the caller provided."""
85 mcp.update("mcp_123", name="renamed")
86
87 mcp._client.mcp.update.assert_called_once_with("mcp_123", name="renamed")
88
89
90 def test_update_extracts_toolkit_and_auth_config_from_combo_entry(mcp):
91 """A `{toolkit, auth_config_id}` entry contributes to both lists,
92 matching the documented behavior."""
93 mcp.update(
94 "mcp_123",
95 toolkits=[{"toolkit": "github", "auth_config_id": "ac_456"}],
96 )
97
98 call_kwargs = mcp._client.mcp.update.call_args.kwargs
99 assert call_kwargs["toolkits"] == ["github"]
100 assert call_kwargs["auth_config_ids"] == ["ac_456"]
101
102
103 def test_create_sends_allowed_tools_not_custom_tools(mcp):
104 """Create should use the non-deprecated `allowed_tools` field."""
105 mcp.create("test-server", toolkits=["github"], allowed_tools=["TOOL_A"])
106
107 call_kwargs = mcp._client.mcp.custom.create.call_args.kwargs
108 assert "custom_tools" not in call_kwargs
109 assert call_kwargs["allowed_tools"] == ["TOOL_A"]
110
111
112 def test_create_inverts_manually_manage_connections(mcp):
113 mcp.create("test-server", toolkits=["github"], manually_manage_connections=True)
114 assert (
115 mcp._client.mcp.custom.create.call_args.kwargs["managed_auth_via_composio"]
116 is False
117 )
118
119 mcp.create("test-server", toolkits=["github"], manually_manage_connections=False)
120 assert (
121 mcp._client.mcp.custom.create.call_args.kwargs["managed_auth_via_composio"]
122 is True
123 )
124
125
126 def _transport_mcp(requests: t.Optional[t.List[httpx.Request]] = None) -> MCP:
127 def handler(request: httpx.Request) -> httpx.Response:
128 if requests is not None:
129 requests.append(request)
130 if request.url.path.endswith("/generate"):
131 return httpx.Response(
132 200,
133 json={
134 "mcp_url": "https://mcp.test",
135 "connected_account_urls": [],
136 "user_ids_url": ["https://mcp.test/u"],
137 },
138 )
139 return httpx.Response(
140 200,
141 json={
142 "id": "mcp_123",
143 "name": "server",
144 "allowed_tools": [],
145 "auth_config_ids": [],
146 },
147 )
148
149 client = HttpClient(
150 provider="test",
151 auth=ProjectAuth("ak_test"),
152 base_url="https://backend.composio.dev",
153 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
154 )
155 return MCP(client)
156
157
158 @pytest.fixture
159 def fresh_managed_auth_notice(monkeypatch):
160 monkeypatch.setattr(mcp_module, "_managed_auth_deprecation_warned", False)
161
162
163 def _sdk_notices(caught):
164 return [
165 w
166 for w in caught
167 if w.category is ComposioDeprecationWarning
168 and "include_composio_helper_actions" in str(w.message)
169 ]
170
171
172 def test_generate_warns_once_per_process(fresh_managed_auth_notice):
173 """The SDK still sends `managed_auth_by_composio` (deprecated upstream) and
174 explains it once in SDK terms, even across call sites and instances."""
175 first, second = _transport_mcp(), _transport_mcp()
176
177 with warnings.catch_warnings(record=True) as caught:
178 warnings.simplefilter("always")
179 server = first.generate("user_123", "mcp_123")
180 first.generate("user_123", "mcp_123")
181 second.generate("user_123", "mcp_123")
182
183 assert server["url"] == "https://mcp.test/u"
184 notices = _sdk_notices(caught)
185 assert len(notices) == 1
186 assert notices[0].filename == __file__
187
188
189 def test_generate_without_managed_auth_omits_field_and_does_not_warn(
190 fresh_managed_auth_notice,
191 ):
192 requests: t.List[httpx.Request] = []
193 mcp = _transport_mcp(requests)
194
195 with warnings.catch_warnings(record=True) as caught:
196 warnings.simplefilter("always")
197 mcp.generate("user_123", "mcp_123", manually_manage_connections=True)
198
199 assert caught == []
200 body = json.loads(requests[-1].content)
201 assert "managed_auth_by_composio" not in body
202
203
204 _DEFAULT_FILTERS_SCRIPT = """
205 import warnings
206
207 import httpx
208 from composio_client import ProjectAuth
209
210 from composio.client import HttpClient
211 from composio.core.models.mcp import MCP
212
213
214 def handler(request):
215 if request.url.path.endswith("/generate"):
216 return httpx.Response(
217 200, json={"mcp_url": "u", "connected_account_urls": [], "user_ids_url": ["x"]}
218 )
219 return httpx.Response(
220 200, json={"id": "m", "name": "s", "allowed_tools": [], "auth_config_ids": []}
221 )
222
223
224 mcp = MCP(
225 HttpClient(
226 provider="test",
227 auth=ProjectAuth("ak_test"),
228 base_url="https://backend.composio.dev",
229 http_client=httpx.Client(transport=httpx.MockTransport(handler)),
230 )
231 )
232 for _ in range(3):
233 warnings.warn("unrelated notice", UserWarning)
234 mcp.generate("u", "m")
235 """
236
237
238 def test_generate_keeps_default_warning_deduplication():
239 """Under Python's default filters, repeated calls neither repeat the SDK
240 notice nor make an unrelated once-per-line warning show again."""
241 result = subprocess.run(
242 [sys.executable, "-c", _DEFAULT_FILTERS_SCRIPT],
243 capture_output=True,
244 text=True,
245 check=True,
246 )
247
248 assert result.stderr.count("include_composio_helper_actions") == 1
249 assert result.stderr.count("unrelated notice") == 1