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 21, 03:37 UTC
| 1 | """Test ToolRouter functionality.""" |
| 2 | |
| 3 | import json |
| 4 | import logging |
| 5 | import os |
| 6 | import traceback |
| 7 | import typing as t |
| 8 | import warnings |
| 9 | from unittest.mock import MagicMock, patch |
| 10 | |
| 11 | import httpx |
| 12 | import pytest |
| 13 | from composio_client import ( |
| 14 | Auth, |
| 15 | AutoAuth, |
| 16 | ConflictError, |
| 17 | NoAuth, |
| 18 | ProjectAuth, |
| 19 | Scope, |
| 20 | UserAuth, |
| 21 | omit, |
| 22 | ) |
| 23 | from composio_client import ComposioError as ClientComposioError |
| 24 | from composio_client.types.tool_router.session_execute_response import ( |
| 25 | SessionExecuteResponse, |
| 26 | ) |
| 27 | from composio_client.types.tool_router.session_search_response import ( |
| 28 | SessionSearchResponse, |
| 29 | ) |
| 30 | from pydantic import BaseModel, Field |
| 31 | |
| 32 | from composio.client import HttpClient |
| 33 | from composio.core.models.experimental import ExperimentalAPI |
| 34 | from composio.core.models.session_context import SessionContextImpl |
| 35 | from composio.core.models.tool_router import ( |
| 36 | SESSION_PRESET_DIRECT_TOOLS, |
| 37 | ToolkitConnectionsDetails, |
| 38 | ToolkitConnectionState, |
| 39 | ToolRouter, |
| 40 | ToolRouterExperimentalConfig, |
| 41 | ToolRouterManageConnectionsConfig, |
| 42 | ToolRouterMCPServerConfig, |
| 43 | ToolRouterMCPServerType, |
| 44 | ToolRouterSessionExperimental, |
| 45 | ToolRouterToolkitsDisableConfig, |
| 46 | ToolRouterToolkitsEnableConfig, |
| 47 | ) |
| 48 | from composio.core.models.tool_router_session import ( |
| 49 | DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX, |
| 50 | ToolRouterSession, |
| 51 | ToolRouterSessionExecuteResponse, |
| 52 | ToolRouterSessionMetaToolSlug, |
| 53 | ToolRouterSessionWithMcp, |
| 54 | ) |
| 55 | from composio.core.provider import get_execution_target |
| 56 | from composio.exceptions import ( |
| 57 | ComposioDeprecationWarning, |
| 58 | InvalidParams, |
| 59 | MCPDestinationError, |
| 60 | SessionConfigConflictError, |
| 61 | ToolInputRequiredError, |
| 62 | ValidationError, |
| 63 | ) |
| 64 | from tests.conftest import mock_http_client |
| 65 | |
| 66 | experimental_api = ExperimentalAPI() |
| 67 | |
| 68 | |
| 69 | class GrepInput(BaseModel): |
| 70 | pattern: str = Field(description="Pattern to search for") |
| 71 | |
| 72 | |
| 73 | @pytest.fixture |
| 74 | def mock_client(): |
| 75 | """Create a mock HTTP client.""" |
| 76 | client = mock_http_client(MagicMock) |
| 77 | client.sdk_auth = ProjectAuth("test-api-key") |
| 78 | client.scope = None |
| 79 | client.base_url = httpx.URL("https://backend.composio.dev") |
| 80 | client.default_headers = {} |
| 81 | |
| 82 | # Mock session responses |
| 83 | mock_session_response = MagicMock() |
| 84 | mock_session_response.session_id = "session_123" |
| 85 | mock_session_response.config_version = 7 |
| 86 | mock_session_response.mcp = MagicMock() |
| 87 | mock_session_response.mcp.type = "http" |
| 88 | mock_session_response.mcp.url = ( |
| 89 | "https://backend.composio.dev/api/v3/tool_router/session/session_123" |
| 90 | ) |
| 91 | mock_session_response.tool_router_tools = [ |
| 92 | "GMAIL_FETCH_EMAILS", |
| 93 | "SLACK_SEND_MESSAGE", |
| 94 | "GITHUB_CREATE_ISSUE", |
| 95 | ] |
| 96 | mock_session_response.config = MagicMock() |
| 97 | mock_session_response.config.user_id = "user_123" |
| 98 | mock_session_response.config.preload = MagicMock() |
| 99 | mock_session_response.config.preload.tools = [] |
| 100 | mock_session_response.experimental = None # Default to None |
| 101 | |
| 102 | client.tool_router.session.create.return_value = mock_session_response |
| 103 | client.tool_router.session.retrieve.return_value = mock_session_response |
| 104 | client.tool_router.session.attach.return_value = mock_session_response |
| 105 | client.tool_router.session.search.return_value = ( |
| 106 | SessionSearchResponse.model_validate(_search_json()) |
| 107 | ) |
| 108 | |
| 109 | # Mock link response |
| 110 | mock_link_response = MagicMock() |
| 111 | mock_link_response.connected_account_id = "conn_456" |
| 112 | mock_link_response.redirect_url = "https://composio.dev/auth/redirect" |
| 113 | client.tool_router.session.link.return_value = mock_link_response |
| 114 | |
| 115 | # Mock toolkits response |
| 116 | mock_toolkit_item_active = MagicMock() |
| 117 | mock_toolkit_item_active.slug = "gmail" |
| 118 | mock_toolkit_item_active.name = "Gmail" |
| 119 | mock_toolkit_item_active.meta.logo = "https://example.com/gmail-logo.png" |
| 120 | mock_toolkit_item_active.is_no_auth = False |
| 121 | mock_toolkit_item_active.connected_account = MagicMock() |
| 122 | mock_toolkit_item_active.connected_account.id = "conn_123" |
| 123 | mock_toolkit_item_active.connected_account.status = "ACTIVE" |
| 124 | mock_toolkit_item_active.connected_account.auth_config = MagicMock() |
| 125 | mock_toolkit_item_active.connected_account.auth_config.id = "auth_config_123" |
| 126 | mock_toolkit_item_active.connected_account.auth_config.auth_scheme = "OAUTH2" |
| 127 | mock_toolkit_item_active.connected_account.auth_config.is_composio_managed = True |
| 128 | |
| 129 | mock_toolkit_item_inactive = MagicMock() |
| 130 | mock_toolkit_item_inactive.slug = "github" |
| 131 | mock_toolkit_item_inactive.name = "GitHub" |
| 132 | mock_toolkit_item_inactive.meta.logo = "https://example.com/github-logo.png" |
| 133 | mock_toolkit_item_inactive.is_no_auth = False |
| 134 | mock_toolkit_item_inactive.connected_account = None |
| 135 | |
| 136 | mock_toolkits_response = MagicMock() |
| 137 | mock_toolkits_response.items = [ |
| 138 | mock_toolkit_item_active, |
| 139 | mock_toolkit_item_inactive, |
| 140 | ] |
| 141 | mock_toolkits_response.next_cursor = "cursor_789" |
| 142 | mock_toolkits_response.total_pages = 2 |
| 143 | client.tool_router.session.toolkits.return_value = mock_toolkits_response |
| 144 | |
| 145 | return client |
| 146 | |
| 147 | |
| 148 | @pytest.fixture |
| 149 | def mock_provider(): |
| 150 | """Create a mock provider.""" |
| 151 | provider = MagicMock() |
| 152 | return provider |
| 153 | |
| 154 | |
| 155 | @pytest.fixture |
| 156 | def tool_router(mock_client, mock_provider): |
| 157 | """Create a ToolRouter instance with mocked client.""" |
| 158 | return ToolRouter(client=mock_client, provider=mock_provider) |
| 159 | |
| 160 | |
| 161 | class TestToolRouter: |
| 162 | """Test cases for ToolRouter class.""" |
| 163 | |
| 164 | def test_constructor(self, tool_router, mock_client, mock_provider): |
| 165 | """Test that ToolRouter initializes correctly.""" |
| 166 | assert tool_router._client == mock_client |
| 167 | assert tool_router._provider == mock_provider |
| 168 | |
| 169 | def test_session_list_config_history(self, tool_router, mock_client): |
| 170 | """``session.list_config_history`` passes the session id and pagination.""" |
| 171 | session = tool_router.create(user_id="user_123") |
| 172 | mock_client.tool_router.session.config_history.return_value = "history" |
| 173 | |
| 174 | assert session.list_config_history() == "history" |
| 175 | mock_client.tool_router.session.config_history.assert_called_once_with( |
| 176 | session_id="session_123" |
| 177 | ) |
| 178 | |
| 179 | mock_client.tool_router.session.config_history.reset_mock() |
| 180 | session.list_config_history(limit=10, cursor="c1") |
| 181 | mock_client.tool_router.session.config_history.assert_called_once_with( |
| 182 | session_id="session_123", limit=10, cursor="c1" |
| 183 | ) |
| 184 | |
| 185 | def test_create_basic_session(self, tool_router, mock_client): |
| 186 | """Test creating a basic session with minimal configuration.""" |
| 187 | session = tool_router.create(user_id="user_123") |
| 188 | |
| 189 | # Verify session properties |
| 190 | assert session.session_id == "session_123" |
| 191 | assert session.mcp.type == ToolRouterMCPServerType.HTTP |
| 192 | assert ( |
| 193 | session.mcp.url |
| 194 | == "https://backend.composio.dev/api/v3/tool_router/session/session_123" |
| 195 | ) |
| 196 | assert session.mcp.headers == {"x-api-key": "test-api-key"} |
| 197 | assert callable(session.tools) |
| 198 | assert callable(session.authorize) |
| 199 | assert callable(session.toolkits) |
| 200 | |
| 201 | # Verify API was called |
| 202 | mock_client.tool_router.session.create.assert_called_once() |
| 203 | |
| 204 | @pytest.mark.parametrize( |
| 205 | ("proxy_execute", "expected"), |
| 206 | [ |
| 207 | ({"enable": True}, {"enable": True}), |
| 208 | ({"enable": False}, {"enable": False}), |
| 209 | (True, {"enable": True}), |
| 210 | (False, {"enable": False}), |
| 211 | ], |
| 212 | ) |
| 213 | def test_create_sends_proxy_execute_block( |
| 214 | self, tool_router, mock_client, proxy_execute, expected |
| 215 | ): |
| 216 | tool_router.create(user_id="user_123", proxy_execute=proxy_execute) |
| 217 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 218 | assert kwargs["proxy_execute"] == expected |
| 219 | |
| 220 | def test_create_omits_proxy_execute_by_default(self, tool_router, mock_client): |
| 221 | tool_router.create(user_id="user_123") |
| 222 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 223 | assert "proxy_execute" not in kwargs |
| 224 | |
| 225 | def test_create_with_instant_policy(self, tool_router, mock_client): |
| 226 | policy = {"toolkits": {"enable": ["exa"]}, "return_instant_charge": True} |
| 227 | tool_router.create(user_id="user_123", instant=policy) |
| 228 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 229 | assert kwargs["instant"] == policy |
| 230 | |
| 231 | mock_client.tool_router.session.create.reset_mock() |
| 232 | tool_router.create(user_id="user_123") |
| 233 | assert "instant" not in mock_client.tool_router.session.create.call_args.kwargs |
| 234 | assert ( |
| 235 | "extra_body" not in mock_client.tool_router.session.create.call_args.kwargs |
| 236 | ) |
| 237 | |
| 238 | tool_router.create(user_id="user_123", instant=False) |
| 239 | assert ( |
| 240 | mock_client.tool_router.session.create.call_args.kwargs["instant"] is False |
| 241 | ) |
| 242 | |
| 243 | def test_create_session_default_returns_base_session(self, tool_router): |
| 244 | """Default create() (mcp omitted) returns the base ToolRouterSession. |
| 245 | |
| 246 | MCP is opt-in: the type must NOT be the mcp-surfacing subclass. |
| 247 | """ |
| 248 | session = tool_router.create(user_id="user_123") |
| 249 | |
| 250 | assert type(session) is ToolRouterSession |
| 251 | assert not isinstance(session, ToolRouterSessionWithMcp) |
| 252 | |
| 253 | def test_create_session_with_mcp_true_returns_with_mcp(self, tool_router): |
| 254 | """create(..., mcp=True) returns ToolRouterSessionWithMcp with mcp surfaced.""" |
| 255 | session = tool_router.create(user_id="user_123", mcp=True) |
| 256 | |
| 257 | assert isinstance(session, ToolRouterSessionWithMcp) |
| 258 | # The MCP endpoint is populated on the runtime object either way. |
| 259 | assert session.mcp.type == ToolRouterMCPServerType.HTTP |
| 260 | assert ( |
| 261 | session.mcp.url |
| 262 | == "https://backend.composio.dev/api/v3/tool_router/session/session_123" |
| 263 | ) |
| 264 | |
| 265 | def test_use_session_default_returns_base_session(self, tool_router): |
| 266 | """Default use() (mcp omitted) returns the base ToolRouterSession.""" |
| 267 | session = tool_router.use("session_123") |
| 268 | |
| 269 | assert type(session) is ToolRouterSession |
| 270 | assert not isinstance(session, ToolRouterSessionWithMcp) |
| 271 | |
| 272 | def test_use_session_with_mcp_true_returns_with_mcp(self, tool_router): |
| 273 | """use(..., mcp=True) returns ToolRouterSessionWithMcp.""" |
| 274 | session = tool_router.use("session_123", mcp=True) |
| 275 | |
| 276 | assert isinstance(session, ToolRouterSessionWithMcp) |
| 277 | assert ( |
| 278 | session.mcp.url |
| 279 | == "https://backend.composio.dev/api/v3/tool_router/session/session_123" |
| 280 | ) |
| 281 | |
| 282 | def test_delete_session_by_id(self, tool_router, mock_client): |
| 283 | """delete() removes a session by ID.""" |
| 284 | mock_client.tool_router.session.delete.return_value = MagicMock( |
| 285 | session_id="session_123", deleted=True |
| 286 | ) |
| 287 | |
| 288 | result = tool_router.delete("session_123") |
| 289 | |
| 290 | mock_client.tool_router.session.delete.assert_called_once_with("session_123") |
| 291 | assert result == { |
| 292 | "session_id": "session_123", |
| 293 | "deleted": True, |
| 294 | } |
| 295 | |
| 296 | def test_delete_session_by_id_rejects_unconfirmed_response( |
| 297 | self, tool_router, mock_client |
| 298 | ): |
| 299 | """delete() raises when the response does not confirm the deletion.""" |
| 300 | mock_client.tool_router.session.delete.return_value = MagicMock( |
| 301 | session_id="session_123", deleted=False |
| 302 | ) |
| 303 | |
| 304 | with pytest.raises(ValidationError): |
| 305 | tool_router.delete("session_123") |
| 306 | |
| 307 | def test_delete_session_by_id_calls_http_endpoint(self): |
| 308 | """delete() sends one DELETE with the session ID URL-encoded.""" |
| 309 | requests: t.List[httpx.Request] = [] |
| 310 | |
| 311 | def handler(request: httpx.Request) -> httpx.Response: |
| 312 | requests.append(request) |
| 313 | return httpx.Response( |
| 314 | 200, |
| 315 | json={ |
| 316 | "session_id": "session/with spaces", |
| 317 | "deleted": True, |
| 318 | }, |
| 319 | ) |
| 320 | |
| 321 | client = HttpClient( |
| 322 | provider="test", |
| 323 | auth=ProjectAuth("sk-test"), |
| 324 | base_url="https://backend.invalid", |
| 325 | http_client=httpx.Client(transport=httpx.MockTransport(handler)), |
| 326 | ) |
| 327 | tool_router = ToolRouter(client=client, provider=MagicMock()) |
| 328 | |
| 329 | result = tool_router.delete("session/with spaces") |
| 330 | |
| 331 | assert result == { |
| 332 | "session_id": "session/with spaces", |
| 333 | "deleted": True, |
| 334 | } |
| 335 | assert len(requests) == 1 |
| 336 | assert requests[0].method == "DELETE" |
| 337 | assert ( |
| 338 | str(requests[0].url) |
| 339 | == "https://backend.invalid/api/v3.1/tool_router/session/session%2Fwith%20spaces" |
| 340 | ) |
| 341 | |
| 342 | def test_create_session_with_toolkits_list(self, tool_router, mock_client): |
| 343 | """Test creating a session with toolkits as a list.""" |
| 344 | session = tool_router.create(user_id="user_123", toolkits=["github", "slack"]) |
| 345 | |
| 346 | assert session.session_id == "session_123" |
| 347 | |
| 348 | # Verify the API was called with correct parameters |
| 349 | call_args = mock_client.tool_router.session.create.call_args |
| 350 | assert call_args is not None |
| 351 | kwargs = call_args.kwargs |
| 352 | assert "toolkits" in kwargs |
| 353 | assert kwargs["toolkits"] == {"enable": ["github", "slack"]} |
| 354 | |
| 355 | def test_create_session_with_disable_toolkits(self, tool_router, mock_client): |
| 356 | """Test creating a session with disable toolkits.""" |
| 357 | session = tool_router.create( |
| 358 | user_id="user_123", toolkits={"disable": ["linear", "notion"]} |
| 359 | ) |
| 360 | |
| 361 | assert session.session_id == "session_123" |
| 362 | |
| 363 | # Verify the API was called with correct parameters |
| 364 | call_args = mock_client.tool_router.session.create.call_args |
| 365 | kwargs = call_args.kwargs |
| 366 | assert kwargs["toolkits"] == {"disable": ["linear", "notion"]} |
| 367 | |
| 368 | def test_create_session_with_tools_config(self, tool_router, mock_client): |
| 369 | """Test creating a session with per-toolkit tool configuration.""" |
| 370 | session = tool_router.create( |
| 371 | user_id="user_123", |
| 372 | tools={ |
| 373 | "gmail": ["GMAIL_SEND_EMAIL", "GMAIL_SEARCH"], |
| 374 | "github": {"enable": ["GITHUB_CREATE_ISSUE"]}, |
| 375 | }, |
| 376 | ) |
| 377 | |
| 378 | assert session.session_id == "session_123" |
| 379 | |
| 380 | # Verify the API was called with tools config |
| 381 | call_args = mock_client.tool_router.session.create.call_args |
| 382 | kwargs = call_args.kwargs |
| 383 | assert "tools" in kwargs |
| 384 | assert "gmail" in kwargs["tools"] |
| 385 | assert kwargs["tools"]["gmail"] == { |
| 386 | "enable": ["GMAIL_SEND_EMAIL", "GMAIL_SEARCH"] |
| 387 | } |
| 388 | assert kwargs["tools"]["github"] == {"enable": ["GITHUB_CREATE_ISSUE"]} |
| 389 | |
| 390 | def test_create_session_with_global_tags(self, tool_router, mock_client): |
| 391 | """Test creating a session with global tag filtering (array format).""" |
| 392 | session = tool_router.create( |
| 393 | user_id="user_123", tags=["readOnlyHint", "idempotentHint"] |
| 394 | ) |
| 395 | |
| 396 | assert session.session_id == "session_123" |
| 397 | |
| 398 | # Verify the API was called with tags transformed to enable format |
| 399 | call_args = mock_client.tool_router.session.create.call_args |
| 400 | kwargs = call_args.kwargs |
| 401 | assert "tags" in kwargs |
| 402 | assert kwargs["tags"] == {"enable": ["readOnlyHint", "idempotentHint"]} |
| 403 | |
| 404 | def test_create_session_with_global_tags_object_enable( |
| 405 | self, tool_router, mock_client |
| 406 | ): |
| 407 | """Test creating a session with global tags using object format with enable.""" |
| 408 | session = tool_router.create( |
| 409 | user_id="user_123", tags={"enable": ["readOnlyHint", "idempotentHint"]} |
| 410 | ) |
| 411 | |
| 412 | assert session.session_id == "session_123" |
| 413 | |
| 414 | call_args = mock_client.tool_router.session.create.call_args |
| 415 | kwargs = call_args.kwargs |
| 416 | assert "tags" in kwargs |
| 417 | assert kwargs["tags"] == {"enable": ["readOnlyHint", "idempotentHint"]} |
| 418 | |
| 419 | def test_create_session_with_global_tags_object_disable( |
| 420 | self, tool_router, mock_client |
| 421 | ): |
| 422 | """Test creating a session with global tags using object format with disable.""" |
| 423 | session = tool_router.create( |
| 424 | user_id="user_123", tags={"disable": ["destructiveHint"]} |
| 425 | ) |
| 426 | |
| 427 | assert session.session_id == "session_123" |
| 428 | |
| 429 | call_args = mock_client.tool_router.session.create.call_args |
| 430 | kwargs = call_args.kwargs |
| 431 | assert "tags" in kwargs |
| 432 | assert kwargs["tags"] == {"disable": ["destructiveHint"]} |
| 433 | |
| 434 | def test_create_session_with_global_tags_object_both( |
| 435 | self, tool_router, mock_client |
| 436 | ): |
| 437 | """Test creating a session with global tags using object format with both enable and disable.""" |
| 438 | session = tool_router.create( |
| 439 | user_id="user_123", |
| 440 | tags={ |
| 441 | "enable": ["readOnlyHint", "idempotentHint"], |
| 442 | "disable": ["destructiveHint"], |
| 443 | }, |
| 444 | ) |
| 445 | |
| 446 | assert session.session_id == "session_123" |
| 447 | |
| 448 | call_args = mock_client.tool_router.session.create.call_args |
| 449 | kwargs = call_args.kwargs |
| 450 | assert "tags" in kwargs |
| 451 | assert kwargs["tags"] == { |
| 452 | "enable": ["readOnlyHint", "idempotentHint"], |
| 453 | "disable": ["destructiveHint"], |
| 454 | } |
| 455 | |
| 456 | def test_create_session_with_toolkit_specific_tags(self, tool_router, mock_client): |
| 457 | """Test creating a session with per-toolkit tag filtering (array format).""" |
| 458 | session = tool_router.create( |
| 459 | user_id="user_123", |
| 460 | tools={ |
| 461 | "gmail": {"tags": ["readOnlyHint"]}, |
| 462 | "github": {"tags": ["readOnlyHint", "idempotentHint"]}, |
| 463 | }, |
| 464 | ) |
| 465 | |
| 466 | assert session.session_id == "session_123" |
| 467 | |
| 468 | call_args = mock_client.tool_router.session.create.call_args |
| 469 | kwargs = call_args.kwargs |
| 470 | assert "tools" in kwargs |
| 471 | assert kwargs["tools"]["gmail"] == {"tags": {"enable": ["readOnlyHint"]}} |
| 472 | assert kwargs["tools"]["github"] == { |
| 473 | "tags": {"enable": ["readOnlyHint", "idempotentHint"]} |
| 474 | } |
| 475 | |
| 476 | def test_create_session_with_toolkit_specific_tags_object_enable( |
| 477 | self, tool_router, mock_client |
| 478 | ): |
| 479 | """Test creating a session with per-toolkit tags using object format with enable.""" |
| 480 | session = tool_router.create( |
| 481 | user_id="user_123", |
| 482 | tools={ |
| 483 | "gmail": {"tags": {"enable": ["readOnlyHint", "idempotentHint"]}}, |
| 484 | }, |
| 485 | ) |
| 486 | |
| 487 | assert session.session_id == "session_123" |
| 488 | |
| 489 | call_args = mock_client.tool_router.session.create.call_args |
| 490 | kwargs = call_args.kwargs |
| 491 | assert "tools" in kwargs |
| 492 | assert kwargs["tools"]["gmail"] == { |
| 493 | "tags": {"enable": ["readOnlyHint", "idempotentHint"]} |
| 494 | } |
| 495 | |
| 496 | def test_create_session_with_toolkit_specific_tags_object_disable( |
| 497 | self, tool_router, mock_client |
| 498 | ): |
| 499 | """Test creating a session with per-toolkit tags using object format with disable.""" |
| 500 | session = tool_router.create( |
| 501 | user_id="user_123", |
| 502 | tools={ |
| 503 | "gmail": {"tags": {"disable": ["destructiveHint"]}}, |
| 504 | }, |
| 505 | ) |
| 506 | |
| 507 | assert session.session_id == "session_123" |
| 508 | |
| 509 | call_args = mock_client.tool_router.session.create.call_args |
| 510 | kwargs = call_args.kwargs |
| 511 | assert "tools" in kwargs |
| 512 | assert kwargs["tools"]["gmail"] == {"tags": {"disable": ["destructiveHint"]}} |
| 513 | |
| 514 | def test_create_session_with_toolkit_specific_tags_object_both( |
| 515 | self, tool_router, mock_client |
| 516 | ): |
| 517 | """Test creating a session with per-toolkit tags using object format with both enable and disable.""" |
| 518 | session = tool_router.create( |
| 519 | user_id="user_123", |
| 520 | tools={ |
| 521 | "gmail": { |
| 522 | "tags": { |
| 523 | "enable": ["readOnlyHint", "idempotentHint"], |
| 524 | "disable": ["destructiveHint"], |
| 525 | } |
| 526 | }, |
| 527 | }, |
| 528 | ) |
| 529 | |
| 530 | assert session.session_id == "session_123" |
| 531 | |
| 532 | call_args = mock_client.tool_router.session.create.call_args |
| 533 | kwargs = call_args.kwargs |
| 534 | assert "tools" in kwargs |
| 535 | assert kwargs["tools"]["gmail"] == { |
| 536 | "tags": { |
| 537 | "enable": ["readOnlyHint", "idempotentHint"], |
| 538 | "disable": ["destructiveHint"], |
| 539 | } |
| 540 | } |
| 541 | |
| 542 | def test_create_session_with_open_world_hint_tag(self, tool_router, mock_client): |
| 543 | """Test creating a session with openWorldHint tag.""" |
| 544 | session = tool_router.create( |
| 545 | user_id="user_123", |
| 546 | tags=["openWorldHint", "readOnlyHint"], |
| 547 | ) |
| 548 | |
| 549 | assert session.session_id == "session_123" |
| 550 | |
| 551 | call_args = mock_client.tool_router.session.create.call_args |
| 552 | kwargs = call_args.kwargs |
| 553 | assert "tags" in kwargs |
| 554 | assert kwargs["tags"] == {"enable": ["openWorldHint", "readOnlyHint"]} |
| 555 | |
| 556 | def test_create_session_with_mixed_tools_config(self, tool_router, mock_client): |
| 557 | """Test creating a session with mixed tool configuration (enable, disable, tags).""" |
| 558 | session = tool_router.create( |
| 559 | user_id="user_123", |
| 560 | tools={ |
| 561 | "gmail": ["GMAIL_SEND_EMAIL"], # List shorthand |
| 562 | "slack": {"disable": ["SLACK_DELETE_MESSAGE"]}, |
| 563 | "github": {"tags": ["readOnlyHint"]}, |
| 564 | }, |
| 565 | ) |
| 566 | |
| 567 | assert session.session_id == "session_123" |
| 568 | |
| 569 | call_args = mock_client.tool_router.session.create.call_args |
| 570 | kwargs = call_args.kwargs |
| 571 | assert kwargs["tools"]["gmail"] == {"enable": ["GMAIL_SEND_EMAIL"]} |
| 572 | assert kwargs["tools"]["slack"] == {"disable": ["SLACK_DELETE_MESSAGE"]} |
| 573 | assert kwargs["tools"]["github"] == {"tags": {"enable": ["readOnlyHint"]}} |
| 574 | |
| 575 | def test_create_session_with_global_and_toolkit_tags( |
| 576 | self, tool_router, mock_client |
| 577 | ): |
| 578 | """Test creating a session with both global tags and toolkit-specific tags.""" |
| 579 | session = tool_router.create( |
| 580 | user_id="user_123", |
| 581 | tags=["readOnlyHint"], # Global tags |
| 582 | tools={ |
| 583 | "gmail": { |
| 584 | "tags": { |
| 585 | "enable": ["idempotentHint"], |
| 586 | "disable": ["destructiveHint"], |
| 587 | } |
| 588 | }, |
| 589 | }, |
| 590 | ) |
| 591 | |
| 592 | assert session.session_id == "session_123" |
| 593 | |
| 594 | call_args = mock_client.tool_router.session.create.call_args |
| 595 | kwargs = call_args.kwargs |
| 596 | assert kwargs["tags"] == {"enable": ["readOnlyHint"]} |
| 597 | assert kwargs["tools"]["gmail"] == { |
| 598 | "tags": {"enable": ["idempotentHint"], "disable": ["destructiveHint"]} |
| 599 | } |
| 600 | |
| 601 | def test_create_session_with_empty_tags_array(self, tool_router, mock_client): |
| 602 | """Test creating a session with empty tags array.""" |
| 603 | session = tool_router.create( |
| 604 | user_id="user_123", |
| 605 | tags=[], |
| 606 | ) |
| 607 | |
| 608 | assert session.session_id == "session_123" |
| 609 | |
| 610 | call_args = mock_client.tool_router.session.create.call_args |
| 611 | kwargs = call_args.kwargs |
| 612 | assert kwargs["tags"] == {"enable": []} |
| 613 | |
| 614 | def test_create_session_with_all_tag_types(self, tool_router, mock_client): |
| 615 | """Test creating a session with all available tag types.""" |
| 616 | session = tool_router.create( |
| 617 | user_id="user_123", |
| 618 | tags=[ |
| 619 | "readOnlyHint", |
| 620 | "destructiveHint", |
| 621 | "idempotentHint", |
| 622 | "openWorldHint", |
| 623 | ], |
| 624 | ) |
| 625 | |
| 626 | assert session.session_id == "session_123" |
| 627 | |
| 628 | call_args = mock_client.tool_router.session.create.call_args |
| 629 | kwargs = call_args.kwargs |
| 630 | assert kwargs["tags"] == { |
| 631 | "enable": [ |
| 632 | "readOnlyHint", |
| 633 | "destructiveHint", |
| 634 | "idempotentHint", |
| 635 | "openWorldHint", |
| 636 | ] |
| 637 | } |
| 638 | |
| 639 | def test_create_session_with_manage_connections_boolean( |
| 640 | self, tool_router, mock_client |
| 641 | ): |
| 642 | """Test creating a session with manage_connections as boolean.""" |
| 643 | session = tool_router.create(user_id="user_123", manage_connections=True) |
| 644 | |
| 645 | assert session.session_id == "session_123" |
| 646 | |
| 647 | call_args = mock_client.tool_router.session.create.call_args |
| 648 | kwargs = call_args.kwargs |
| 649 | assert kwargs["manage_connections"]["enable"] is True |
| 650 | |
| 651 | def test_create_session_with_manage_connections_config( |
| 652 | self, tool_router, mock_client |
| 653 | ): |
| 654 | """Test creating a session with manage_connections as config object.""" |
| 655 | session = tool_router.create( |
| 656 | user_id="user_123", |
| 657 | manage_connections={ |
| 658 | "enable": True, |
| 659 | "callback_url": "https://example.com/callback", |
| 660 | }, |
| 661 | ) |
| 662 | |
| 663 | assert session.session_id == "session_123" |
| 664 | |
| 665 | call_args = mock_client.tool_router.session.create.call_args |
| 666 | kwargs = call_args.kwargs |
| 667 | assert kwargs["manage_connections"]["enable"] is True |
| 668 | assert ( |
| 669 | kwargs["manage_connections"]["callback_url"] |
| 670 | == "https://example.com/callback" |
| 671 | ) |
| 672 | |
| 673 | def test_create_session_with_wait_for_connections(self, tool_router, mock_client): |
| 674 | """Test creating a session with wait_for_connections in manage_connections config.""" |
| 675 | session = tool_router.create( |
| 676 | user_id="user_123", |
| 677 | manage_connections={ |
| 678 | "enable": True, |
| 679 | "callback_url": "https://example.com/callback", |
| 680 | "wait_for_connections": True, |
| 681 | }, |
| 682 | ) |
| 683 | |
| 684 | assert session.session_id == "session_123" |
| 685 | |
| 686 | call_args = mock_client.tool_router.session.create.call_args |
| 687 | kwargs = call_args.kwargs |
| 688 | assert kwargs["manage_connections"]["enable"] is True |
| 689 | assert ( |
| 690 | kwargs["manage_connections"]["callback_url"] |
| 691 | == "https://example.com/callback" |
| 692 | ) |
| 693 | assert kwargs["manage_connections"]["enable_wait_for_connections"] is True |
| 694 | |
| 695 | def test_create_session_with_auth_configs(self, tool_router, mock_client): |
| 696 | """Test creating a session with auth configs.""" |
| 697 | session = tool_router.create( |
| 698 | user_id="user_123", auth_configs={"github": "ac_xxx", "slack": "ac_yyy"} |
| 699 | ) |
| 700 | |
| 701 | assert session.session_id == "session_123" |
| 702 | |
| 703 | call_args = mock_client.tool_router.session.create.call_args |
| 704 | kwargs = call_args.kwargs |
| 705 | assert kwargs["auth_configs"] == {"github": "ac_xxx", "slack": "ac_yyy"} |
| 706 | |
| 707 | def test_create_session_with_connected_accounts(self, tool_router, mock_client): |
| 708 | """Test creating a session with connected accounts.""" |
| 709 | session = tool_router.create( |
| 710 | user_id="user_123", |
| 711 | connected_accounts={"github": "ca_xxx", "slack": "ca_yyy"}, |
| 712 | ) |
| 713 | |
| 714 | assert session.session_id == "session_123" |
| 715 | |
| 716 | call_args = mock_client.tool_router.session.create.call_args |
| 717 | kwargs = call_args.kwargs |
| 718 | assert kwargs["connected_accounts"] == { |
| 719 | "github": ["ca_xxx"], |
| 720 | "slack": ["ca_yyy"], |
| 721 | } |
| 722 | |
| 723 | def test_create_session_with_sandbox_config(self, tool_router, mock_client): |
| 724 | """Test creating a session with preferred sandbox configuration.""" |
| 725 | session = tool_router.create( |
| 726 | user_id="user_123", |
| 727 | sandbox={ |
| 728 | "enable_proxy_execution": False, |
| 729 | "auto_offload_threshold": 300, |
| 730 | "sandbox_size": "large", |
| 731 | }, |
| 732 | ) |
| 733 | |
| 734 | assert session.session_id == "session_123" |
| 735 | |
| 736 | call_args = mock_client.tool_router.session.create.call_args |
| 737 | kwargs = call_args.kwargs |
| 738 | assert "workbench" in kwargs |
| 739 | assert kwargs["workbench"] == { |
| 740 | "enable": True, |
| 741 | "enable_proxy_execution": False, |
| 742 | "auto_offload_threshold": 300, |
| 743 | "sandbox_size": "large", |
| 744 | } |
| 745 | |
| 746 | def test_create_session_rejects_sandbox_and_workbench( |
| 747 | self, tool_router, mock_client |
| 748 | ): |
| 749 | """Test creating a session rejects both sandbox and workbench.""" |
| 750 | with pytest.raises(InvalidParams): |
| 751 | tool_router.create( |
| 752 | user_id="user_123", |
| 753 | sandbox={"enable": True}, |
| 754 | workbench={"enable": True}, |
| 755 | ) |
| 756 | |
| 757 | mock_client.tool_router.session.create.assert_not_called() |
| 758 | |
| 759 | def test_create_session_with_workbench_config(self, tool_router, mock_client): |
| 760 | """Test creating a session with backwards-compatible workbench configuration.""" |
| 761 | session = tool_router.create( |
| 762 | user_id="user_123", |
| 763 | workbench={"enable_proxy_execution": False, "auto_offload_threshold": 300}, |
| 764 | ) |
| 765 | |
| 766 | assert session.session_id == "session_123" |
| 767 | |
| 768 | call_args = mock_client.tool_router.session.create.call_args |
| 769 | kwargs = call_args.kwargs |
| 770 | assert "workbench" in kwargs |
| 771 | assert kwargs["workbench"]["enable"] is True |
| 772 | assert kwargs["workbench"]["enable_proxy_execution"] is False |
| 773 | assert kwargs["workbench"]["auto_offload_threshold"] == 300 |
| 774 | |
| 775 | def test_create_session_with_workbench_disabled(self, tool_router, mock_client): |
| 776 | """Test creating a session with workbench entirely disabled.""" |
| 777 | session = tool_router.create( |
| 778 | user_id="user_123", |
| 779 | workbench={"enable": False}, |
| 780 | ) |
| 781 | |
| 782 | assert session.session_id == "session_123" |
| 783 | |
| 784 | call_args = mock_client.tool_router.session.create.call_args |
| 785 | kwargs = call_args.kwargs |
| 786 | assert "workbench" in kwargs |
| 787 | assert kwargs["workbench"]["enable"] is False |
| 788 | |
| 789 | def test_create_session_with_workbench_enabled_and_configured( |
| 790 | self, tool_router, mock_client |
| 791 | ): |
| 792 | """Test creating a session with workbench explicitly enabled and configured.""" |
| 793 | session = tool_router.create( |
| 794 | user_id="user_123", |
| 795 | workbench={ |
| 796 | "enable": True, |
| 797 | "enable_proxy_execution": False, |
| 798 | "auto_offload_threshold": 20000, |
| 799 | }, |
| 800 | ) |
| 801 | |
| 802 | assert session.session_id == "session_123" |
| 803 | |
| 804 | call_args = mock_client.tool_router.session.create.call_args |
| 805 | kwargs = call_args.kwargs |
| 806 | assert "workbench" in kwargs |
| 807 | assert kwargs["workbench"]["enable"] is True |
| 808 | assert kwargs["workbench"]["enable_proxy_execution"] is False |
| 809 | assert kwargs["workbench"]["auto_offload_threshold"] == 20000 |
| 810 | |
| 811 | def test_create_session_with_workbench_sandbox_size(self, tool_router, mock_client): |
| 812 | """sandbox_size is forwarded on the wire when set, omitted otherwise.""" |
| 813 | tool_router.create( |
| 814 | user_id="user_123", |
| 815 | workbench={"sandbox_size": "large"}, |
| 816 | ) |
| 817 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 818 | assert kwargs["workbench"]["sandbox_size"] == "large" |
| 819 | |
| 820 | tool_router.create( |
| 821 | user_id="user_123", |
| 822 | workbench={"enable_proxy_execution": True}, |
| 823 | ) |
| 824 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 825 | assert "sandbox_size" not in kwargs["workbench"] |
| 826 | |
| 827 | def test_create_session_with_multi_account(self, tool_router, mock_client): |
| 828 | """multi_account is forwarded on the wire when set, omitted otherwise.""" |
| 829 | # Forwarded as-is when provided (TypedDict already uses snake_case keys). |
| 830 | tool_router.create( |
| 831 | user_id="user_123", |
| 832 | multi_account={ |
| 833 | "enable": True, |
| 834 | "max_accounts_per_toolkit": 3, |
| 835 | "require_explicit_selection": True, |
| 836 | }, |
| 837 | ) |
| 838 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 839 | assert kwargs["multi_account"] == { |
| 840 | "enable": True, |
| 841 | "max_accounts_per_toolkit": 3, |
| 842 | "require_explicit_selection": True, |
| 843 | } |
| 844 | |
| 845 | # Omitted entirely when not provided. |
| 846 | tool_router.create(user_id="user_123") |
| 847 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 848 | assert "multi_account" not in kwargs |
| 849 | |
| 850 | def test_create_session_with_preload(self, tool_router, mock_client): |
| 851 | """preload is forwarded and exposed on the session.""" |
| 852 | mock_client.tool_router.session.create.return_value.config.preload.tools = [ |
| 853 | "GMAIL_FETCH_EMAILS" |
| 854 | ] |
| 855 | |
| 856 | session = tool_router.create( |
| 857 | user_id="user_123", |
| 858 | preload={"tools": ["GMAIL_FETCH_EMAILS"]}, |
| 859 | ) |
| 860 | |
| 861 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 862 | assert kwargs["preload"] == {"tools": ["GMAIL_FETCH_EMAILS"]} |
| 863 | assert session.preload.tools == ["GMAIL_FETCH_EMAILS"] |
| 864 | |
| 865 | def test_create_session_with_preload_all(self, tool_router, mock_client): |
| 866 | """preload tools='all' is forwarded and exposed on the session.""" |
| 867 | mock_client.tool_router.session.create.return_value.config.preload.tools = "all" |
| 868 | |
| 869 | session = tool_router.create( |
| 870 | user_id="user_123", |
| 871 | preload={"tools": "all"}, |
| 872 | ) |
| 873 | |
| 874 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 875 | assert kwargs["preload"] == {"tools": "all"} |
| 876 | assert session.preload.tools == "all" |
| 877 | |
| 878 | def test_create_session_rejects_custom_slug_in_top_level_preload( |
| 879 | self, tool_router, mock_client |
| 880 | ): |
| 881 | @experimental_api.tool( |
| 882 | slug="GREP", |
| 883 | name="Grep", |
| 884 | description="Search local text", |
| 885 | ) |
| 886 | def grep(input: GrepInput, ctx): |
| 887 | return {"matches": []} |
| 888 | |
| 889 | with pytest.raises( |
| 890 | ValidationError, |
| 891 | match="Set preload=True on the SDK custom tool", |
| 892 | ): |
| 893 | tool_router.create( |
| 894 | user_id="user_123", |
| 895 | preload={"tools": ["GREP"]}, |
| 896 | experimental={"local_tools": [grep]}, |
| 897 | ) |
| 898 | |
| 899 | mock_client.tool_router.session.create.assert_not_called() |
| 900 | |
| 901 | def test_create_session_rejects_bare_string_preload_tools( |
| 902 | self, tool_router, mock_client |
| 903 | ): |
| 904 | with pytest.raises( |
| 905 | ValidationError, |
| 906 | match='preload.tools must be a list of Composio tool slugs or "all"', |
| 907 | ): |
| 908 | tool_router.create( |
| 909 | user_id="user_123", |
| 910 | preload={"tools": "GMAIL_FETCH_EMAILS"}, |
| 911 | ) |
| 912 | |
| 913 | mock_client.tool_router.session.create.assert_not_called() |
| 914 | |
| 915 | def test_create_session_with_direct_tools_preset(self, tool_router, mock_client): |
| 916 | """direct_tools applies SDK-side defaults for direct tool exposure.""" |
| 917 | mock_client.tool_router.session.create.return_value.config.preload.tools = "all" |
| 918 | |
| 919 | session = tool_router.create( |
| 920 | user_id="user_123", |
| 921 | session_preset=SESSION_PRESET_DIRECT_TOOLS, |
| 922 | toolkits=["github"], |
| 923 | ) |
| 924 | |
| 925 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 926 | assert kwargs["toolkits"] == {"enable": ["github"]} |
| 927 | assert kwargs["manage_connections"] == {"enable": False} |
| 928 | assert kwargs["workbench"] == {"enable": False} |
| 929 | assert kwargs["preload"] == {"tools": "all"} |
| 930 | assert kwargs["search"] == {"enable": False} |
| 931 | assert kwargs["execute"] == {"enable_multi_execute": False} |
| 932 | assert session.preload.tools == "all" |
| 933 | |
| 934 | def test_create_session_with_direct_tools_preset_overrides( |
| 935 | self, tool_router, mock_client |
| 936 | ): |
| 937 | """Explicit user fields override direct_tools defaults.""" |
| 938 | mock_client.tool_router.session.create.return_value.config.preload.tools = [ |
| 939 | "GITHUB_CREATE_ISSUE" |
| 940 | ] |
| 941 | |
| 942 | session = tool_router.create( |
| 943 | user_id="user_123", |
| 944 | session_preset=SESSION_PRESET_DIRECT_TOOLS, |
| 945 | toolkits=["github"], |
| 946 | manage_connections=True, |
| 947 | workbench={"enable": True}, |
| 948 | preload={"tools": ["GITHUB_CREATE_ISSUE"]}, |
| 949 | ) |
| 950 | |
| 951 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 952 | assert kwargs["manage_connections"] == {"enable": True} |
| 953 | assert kwargs["workbench"] == {"enable": True} |
| 954 | assert kwargs["preload"] == {"tools": ["GITHUB_CREATE_ISSUE"]} |
| 955 | assert kwargs["search"] == {"enable": False} |
| 956 | assert kwargs["execute"] == {"enable_multi_execute": False} |
| 957 | assert session.preload.tools == ["GITHUB_CREATE_ISSUE"] |
| 958 | |
| 959 | def test_direct_tools_does_not_default_custom_preload_when_preload_overridden( |
| 960 | self, tool_router, mock_client |
| 961 | ): |
| 962 | """Explicit preload config also overrides the custom-tool preload default.""" |
| 963 | |
| 964 | @experimental_api.tool( |
| 965 | slug="GREP", |
| 966 | name="Grep", |
| 967 | description="Search local text", |
| 968 | ) |
| 969 | def grep(input: GrepInput, ctx): |
| 970 | return {"matches": []} |
| 971 | |
| 972 | mock_response = mock_client.tool_router.session.create.return_value |
| 973 | mock_response.config.preload.tools = ["GITHUB_CREATE_ISSUE"] |
| 974 | mock_response.experimental = MagicMock() |
| 975 | mock_response.experimental.assistive_prompt = None |
| 976 | mock_response.experimental.custom_toolkits = [] |
| 977 | mock_custom_tool = MagicMock() |
| 978 | mock_custom_tool.slug = "SERVER_GREP" |
| 979 | mock_custom_tool.original_slug = "GREP" |
| 980 | mock_custom_tool.extends_toolkit = None |
| 981 | mock_response.experimental.custom_tools = [mock_custom_tool] |
| 982 | |
| 983 | tool_router.create( |
| 984 | user_id="user_123", |
| 985 | session_preset=SESSION_PRESET_DIRECT_TOOLS, |
| 986 | toolkits=["github"], |
| 987 | preload={"tools": ["GITHUB_CREATE_ISSUE"]}, |
| 988 | experimental={"local_tools": [grep]}, |
| 989 | ) |
| 990 | |
| 991 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 992 | assert kwargs["preload"] == {"tools": ["GITHUB_CREATE_ISSUE"]} |
| 993 | assert "preload" not in kwargs["experimental"]["custom_tools"][0] |
| 994 | |
| 995 | def test_create_session_complex_config(self, tool_router, mock_client): |
| 996 | """Test creating a session with complex configuration.""" |
| 997 | session = tool_router.create( |
| 998 | user_id="user_123", |
| 999 | toolkits=["github", "slack"], |
| 1000 | tools={ |
| 1001 | "gmail": ["GMAIL_SEND_EMAIL"], |
| 1002 | }, |
| 1003 | tags=["readOnlyHint", "idempotentHint"], |
| 1004 | manage_connections={ |
| 1005 | "enable": True, |
| 1006 | "callback_url": "https://example.com/callback", |
| 1007 | }, |
| 1008 | auth_configs={"github": "ac_xxx"}, |
| 1009 | connected_accounts={"slack": "ca_yyy"}, |
| 1010 | workbench={"enable_proxy_execution": True, "auto_offload_threshold": 600}, |
| 1011 | multi_account={"enable": True, "max_accounts_per_toolkit": 5}, |
| 1012 | ) |
| 1013 | |
| 1014 | assert session.session_id == "session_123" |
| 1015 | assert session.mcp.type == ToolRouterMCPServerType.HTTP |
| 1016 | |
| 1017 | # Verify all parameters were passed correctly |
| 1018 | call_args = mock_client.tool_router.session.create.call_args |
| 1019 | kwargs = call_args.kwargs |
| 1020 | assert kwargs["user_id"] == "user_123" |
| 1021 | assert "toolkits" in kwargs |
| 1022 | assert "tools" in kwargs |
| 1023 | assert "tags" in kwargs |
| 1024 | assert "manage_connections" in kwargs |
| 1025 | assert "auth_configs" in kwargs |
| 1026 | assert "connected_accounts" in kwargs |
| 1027 | assert "workbench" in kwargs |
| 1028 | assert kwargs["multi_account"] == { |
| 1029 | "enable": True, |
| 1030 | "max_accounts_per_toolkit": 5, |
| 1031 | "require_explicit_selection": True, |
| 1032 | } |
| 1033 | |
| 1034 | def test_create_session_with_experimental_config(self, tool_router, mock_client): |
| 1035 | """Test creating a session with experimental configuration.""" |
| 1036 | session = tool_router.create( |
| 1037 | user_id="user_123", |
| 1038 | experimental={ |
| 1039 | "assistive_prompt": { |
| 1040 | "user_timezone": "America/New_York", |
| 1041 | } |
| 1042 | }, |
| 1043 | ) |
| 1044 | |
| 1045 | assert session.session_id == "session_123" |
| 1046 | |
| 1047 | # Verify the API was called with experimental config transformed correctly |
| 1048 | call_args = mock_client.tool_router.session.create.call_args |
| 1049 | kwargs = call_args.kwargs |
| 1050 | assert "experimental" in kwargs |
| 1051 | assert kwargs["experimental"] == { |
| 1052 | "assistive_prompt_config": { |
| 1053 | "user_timezone": "America/New_York", |
| 1054 | } |
| 1055 | } |
| 1056 | |
| 1057 | def test_create_session_with_experimental_empty_config( |
| 1058 | self, tool_router, mock_client |
| 1059 | ): |
| 1060 | """Test creating a session with empty experimental configuration.""" |
| 1061 | session = tool_router.create( |
| 1062 | user_id="user_123", |
| 1063 | experimental={}, |
| 1064 | ) |
| 1065 | |
| 1066 | assert session.session_id == "session_123" |
| 1067 | |
| 1068 | # Verify experimental is not included when empty |
| 1069 | call_args = mock_client.tool_router.session.create.call_args |
| 1070 | kwargs = call_args.kwargs |
| 1071 | assert "experimental" not in kwargs |
| 1072 | |
| 1073 | def test_create_session_with_experimental_no_timezone( |
| 1074 | self, tool_router, mock_client |
| 1075 | ): |
| 1076 | """Test creating a session with experimental config but no timezone.""" |
| 1077 | session = tool_router.create( |
| 1078 | user_id="user_123", |
| 1079 | experimental={ |
| 1080 | "assistive_prompt": {}, |
| 1081 | }, |
| 1082 | ) |
| 1083 | |
| 1084 | assert session.session_id == "session_123" |
| 1085 | |
| 1086 | # Verify experimental is not included when timezone is not set |
| 1087 | call_args = mock_client.tool_router.session.create.call_args |
| 1088 | kwargs = call_args.kwargs |
| 1089 | assert "experimental" not in kwargs |
| 1090 | |
| 1091 | def test_create_session_with_experimental_empty_string_timezone( |
| 1092 | self, tool_router, mock_client |
| 1093 | ): |
| 1094 | """Test creating a session with empty string timezone is excluded. |
| 1095 | |
| 1096 | This ensures consistency with TypeScript SDK which uses truthy check. |
| 1097 | """ |
| 1098 | session = tool_router.create( |
| 1099 | user_id="user_123", |
| 1100 | experimental={ |
| 1101 | "assistive_prompt": { |
| 1102 | "user_timezone": "", # Empty string should be excluded |
| 1103 | }, |
| 1104 | }, |
| 1105 | ) |
| 1106 | |
| 1107 | assert session.session_id == "session_123" |
| 1108 | |
| 1109 | # Verify experimental is not included when timezone is empty string |
| 1110 | call_args = mock_client.tool_router.session.create.call_args |
| 1111 | kwargs = call_args.kwargs |
| 1112 | assert "experimental" not in kwargs |
| 1113 | |
| 1114 | def test_create_session_experimental_response_transformation( |
| 1115 | self, tool_router, mock_client |
| 1116 | ): |
| 1117 | """Test that experimental response is transformed correctly.""" |
| 1118 | # Setup mock response with experimental |
| 1119 | mock_response_with_experimental = MagicMock() |
| 1120 | mock_response_with_experimental.session_id = "session_exp" |
| 1121 | mock_response_with_experimental.mcp = MagicMock() |
| 1122 | mock_response_with_experimental.mcp.type = "http" |
| 1123 | mock_response_with_experimental.mcp.url = ( |
| 1124 | "https://backend.composio.dev/api/v3/tool_router/session/session_exp" |
| 1125 | ) |
| 1126 | mock_response_with_experimental.tool_router_tools = ["TOOL_1"] |
| 1127 | mock_response_with_experimental.experimental = MagicMock() |
| 1128 | mock_response_with_experimental.experimental.assistive_prompt = ( |
| 1129 | "You are a helpful assistant working in the America/New_York timezone." |
| 1130 | ) |
| 1131 | |
| 1132 | mock_client.tool_router.session.create.return_value = ( |
| 1133 | mock_response_with_experimental |
| 1134 | ) |
| 1135 | |
| 1136 | session = tool_router.create( |
| 1137 | user_id="user_123", |
| 1138 | experimental={ |
| 1139 | "assistive_prompt": { |
| 1140 | "user_timezone": "America/New_York", |
| 1141 | } |
| 1142 | }, |
| 1143 | ) |
| 1144 | |
| 1145 | # Verify experimental response is transformed correctly |
| 1146 | assert session.experimental is not None |
| 1147 | assert isinstance(session.experimental, ToolRouterSessionExperimental) |
| 1148 | assert ( |
| 1149 | session.experimental.assistive_prompt |
| 1150 | == "You are a helpful assistant working in the America/New_York timezone." |
| 1151 | ) |
| 1152 | assert session.experimental.files is not None |
| 1153 | |
| 1154 | def test_create_session_without_experimental_response( |
| 1155 | self, tool_router, mock_client |
| 1156 | ): |
| 1157 | """Test that session without experimental response has experimental with files only.""" |
| 1158 | session = tool_router.create(user_id="user_123") |
| 1159 | |
| 1160 | # Verify experimental is present with files, assistive_prompt is None |
| 1161 | assert session.experimental is not None |
| 1162 | assert session.experimental.assistive_prompt is None |
| 1163 | assert session.experimental.files is not None |
| 1164 | |
| 1165 | def test_create_session_raises_error_without_provider(self, mock_client): |
| 1166 | """Test that creating a session without provider raises an error when calling tools().""" |
| 1167 | tool_router = ToolRouter(client=mock_client, provider=None) |
| 1168 | |
| 1169 | # The error is raised during create() because it calls _create_tools_fn |
| 1170 | with pytest.raises(ValueError, match="Provider is required for tool router"): |
| 1171 | tool_router.create(user_id="user_123") |
| 1172 | |
| 1173 | def test_use_session_raises_error_without_provider(self, mock_client): |
| 1174 | """Test that use() raises when provider is None.""" |
| 1175 | tool_router = ToolRouter(client=mock_client, provider=None) |
| 1176 | |
| 1177 | with pytest.raises(ValueError, match="Provider is required for tool router"): |
| 1178 | tool_router.use(session_id="session_123") |
| 1179 | |
| 1180 | def test_use_session(self, tool_router, mock_client): |
| 1181 | """Test retrieving an existing session.""" |
| 1182 | mock_client.tool_router.session.retrieve.return_value.config.preload.tools = [ |
| 1183 | "GMAIL_FETCH_EMAILS" |
| 1184 | ] |
| 1185 | |
| 1186 | session = tool_router.use(session_id="session_123") |
| 1187 | |
| 1188 | # Verify session properties |
| 1189 | assert session.session_id == "session_123" |
| 1190 | assert session.mcp.type == ToolRouterMCPServerType.HTTP |
| 1191 | assert ( |
| 1192 | session.mcp.url |
| 1193 | == "https://backend.composio.dev/api/v3/tool_router/session/session_123" |
| 1194 | ) |
| 1195 | assert session.mcp.headers == {"x-api-key": "test-api-key"} |
| 1196 | assert session.experimental.files is not None |
| 1197 | assert hasattr(session.experimental.files, "list") |
| 1198 | assert hasattr(session.experimental.files, "upload") |
| 1199 | assert hasattr(session.experimental.files, "download") |
| 1200 | assert hasattr(session.experimental.files, "delete") |
| 1201 | assert callable(session.search) |
| 1202 | assert callable(session.execute) |
| 1203 | assert callable(session.tools) |
| 1204 | assert callable(session.authorize) |
| 1205 | assert callable(session.toolkits) |
| 1206 | assert callable(session.delete) |
| 1207 | assert session.preload.tools == ["GMAIL_FETCH_EMAILS"] |
| 1208 | assert ( |
| 1209 | session.config |
| 1210 | is mock_client.tool_router.session.retrieve.return_value.config |
| 1211 | ) |
| 1212 | |
| 1213 | mock_client.tool_router.session.retrieve.assert_called_once_with("session_123") |
| 1214 | mock_client.tool_router.session.attach.assert_not_called() |
| 1215 | mock_client.post.assert_not_called() |
| 1216 | |
| 1217 | def test_create_session_exposes_config(self, tool_router, mock_client): |
| 1218 | """create() exposes the server-side session config on the session.""" |
| 1219 | create_config = mock_client.tool_router.session.create.return_value.config |
| 1220 | create_config.toolkits = {"enabled": ["gmail"]} |
| 1221 | |
| 1222 | session = tool_router.create(user_id="user_123", toolkits=["gmail"]) |
| 1223 | |
| 1224 | assert session.config is create_config |
| 1225 | assert session.config.toolkits == {"enabled": ["gmail"]} |
| 1226 | |
| 1227 | def test_update_session_returns_config(self, tool_router, mock_client): |
| 1228 | """update() returns the patched config and refreshes it on the session.""" |
| 1229 | patched = MagicMock() |
| 1230 | patched.toolkits = {"enabled": ["gmail"]} |
| 1231 | patched.preload = MagicMock() |
| 1232 | patched.preload.tools = ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"] |
| 1233 | mock_client.tool_router.session.patch.return_value.config = patched |
| 1234 | |
| 1235 | session = tool_router.use(session_id="session_123") |
| 1236 | before = session.config |
| 1237 | |
| 1238 | config = session.update(toolkits={"enable": ["gmail"]}) |
| 1239 | |
| 1240 | mock_client.tool_router.session.patch.assert_called_once() |
| 1241 | assert config is patched |
| 1242 | assert session.config is patched |
| 1243 | assert session.config is not before |
| 1244 | assert session.preload.tools == ["GMAIL_FETCH_EMAILS", "GMAIL_SEND_EMAIL"] |
| 1245 | |
| 1246 | def test_session_delete(self, tool_router, mock_client): |
| 1247 | """Session delete removes the current session.""" |
| 1248 | mock_client.tool_router.session.delete.return_value = MagicMock( |
| 1249 | session_id="session_123", deleted=True |
| 1250 | ) |
| 1251 | session = tool_router.use(session_id="session_123") |
| 1252 | |
| 1253 | result = session.delete() |
| 1254 | |
| 1255 | mock_client.tool_router.session.delete.assert_called_once_with("session_123") |
| 1256 | assert result == { |
| 1257 | "session_id": "session_123", |
| 1258 | "deleted": True, |
| 1259 | } |
| 1260 | |
| 1261 | def test_use_session_with_custom_tools(self, tool_router, mock_client): |
| 1262 | """Test attaching custom tools when reusing a session.""" |
| 1263 | |
| 1264 | @experimental_api.tool( |
| 1265 | slug="GREP", |
| 1266 | name="Grep", |
| 1267 | description="Search local text", |
| 1268 | ) |
| 1269 | def grep(input: GrepInput, ctx): |
| 1270 | return {"matches": []} |
| 1271 | |
| 1272 | mock_response = mock_client.tool_router.session.attach.return_value |
| 1273 | mock_response.experimental = MagicMock() |
| 1274 | mock_response.experimental.assistive_prompt = None |
| 1275 | mock_response.experimental.custom_toolkits = [] |
| 1276 | mock_custom_tool = MagicMock() |
| 1277 | mock_custom_tool.slug = "SERVER_GREP" |
| 1278 | mock_custom_tool.original_slug = "GREP" |
| 1279 | mock_custom_tool.extends_toolkit = None |
| 1280 | mock_response.experimental.custom_tools = [mock_custom_tool] |
| 1281 | |
| 1282 | session = tool_router.use(session_id="session_123", local_tools=[grep]) |
| 1283 | |
| 1284 | mock_client.tool_router.session.attach.assert_called_once() |
| 1285 | kwargs = mock_client.tool_router.session.attach.call_args.kwargs |
| 1286 | assert kwargs["experimental"]["custom_tools"][0]["slug"] == "GREP" |
| 1287 | assert "custom_toolkits" not in kwargs["experimental"] |
| 1288 | mock_client.tool_router.session.retrieve.assert_not_called() |
| 1289 | mock_client.post.assert_not_called() |
| 1290 | assert session.local_tools()[0].slug == "SERVER_GREP" |
| 1291 | assert session.local_tools()[0].name == "Grep" |
| 1292 | |
| 1293 | @patch("composio.core.models.tools.Tools") |
| 1294 | def test_use_session_attaches_preloaded_custom_tools( |
| 1295 | self, |
| 1296 | mock_tools_class, |
| 1297 | tool_router, |
| 1298 | mock_client, |
| 1299 | mock_provider, |
| 1300 | ): |
| 1301 | """use() attaches customs and exposes SDK-preloaded schemas locally.""" |
| 1302 | |
| 1303 | @experimental_api.tool( |
| 1304 | slug="GREP", |
| 1305 | name="Grep", |
| 1306 | description="Search local text", |
| 1307 | preload=True, |
| 1308 | ) |
| 1309 | def grep(input: GrepInput, ctx): |
| 1310 | return {"matches": [input.pattern]} |
| 1311 | |
| 1312 | attach_response = mock_client.tool_router.session.attach.return_value |
| 1313 | attach_response.tool_router_tools = ["COMPOSIO_SEARCH_TOOLS"] |
| 1314 | attach_response.config.preload.tools = [] |
| 1315 | attach_response.experimental = MagicMock() |
| 1316 | attach_response.experimental.assistive_prompt = None |
| 1317 | attach_response.experimental.custom_toolkits = [] |
| 1318 | mock_custom_tool = MagicMock() |
| 1319 | mock_custom_tool.slug = "LOCAL_GREP" |
| 1320 | mock_custom_tool.original_slug = "GREP" |
| 1321 | mock_custom_tool.extends_toolkit = None |
| 1322 | attach_response.experimental.custom_tools = [mock_custom_tool] |
| 1323 | |
| 1324 | mock_tools_instance = MagicMock() |
| 1325 | mock_tool = MagicMock() |
| 1326 | mock_tool.slug = "COMPOSIO_SEARCH_TOOLS" |
| 1327 | mock_tool.toolkit.slug = "composio" |
| 1328 | mock_tool.input_parameters = {} |
| 1329 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 1330 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 1331 | mock_tools_class.return_value = mock_tools_instance |
| 1332 | mock_provider.wrap_tools.return_value = "mocked-custom-tools" |
| 1333 | |
| 1334 | session = tool_router.use(session_id="session_123", local_tools=[grep]) |
| 1335 | session.tools() |
| 1336 | |
| 1337 | mock_client.tool_router.session.attach.assert_called_once() |
| 1338 | attach_kwargs = mock_client.tool_router.session.attach.call_args.kwargs |
| 1339 | assert attach_kwargs["experimental"]["custom_tools"][0]["slug"] == "GREP" |
| 1340 | assert attach_kwargs["experimental"]["custom_tools"][0]["preload"] is True |
| 1341 | mock_client.post.assert_not_called() |
| 1342 | mock_client.tool_router.session.retrieve.assert_not_called() |
| 1343 | |
| 1344 | wrapped_tools = mock_provider.wrap_tools.call_args.kwargs["tools"] |
| 1345 | assert [tool.slug for tool in wrapped_tools] == [ |
| 1346 | "COMPOSIO_SEARCH_TOOLS", |
| 1347 | "LOCAL_GREP", |
| 1348 | ] |
| 1349 | |
| 1350 | @patch("composio.core.models.tools.Tools") |
| 1351 | def test_use_session_applies_preload_all_to_custom_tools( |
| 1352 | self, |
| 1353 | mock_tools_class, |
| 1354 | tool_router, |
| 1355 | mock_client, |
| 1356 | mock_provider, |
| 1357 | ): |
| 1358 | """preload.tools='all' on an existing session selects attached customs.""" |
| 1359 | |
| 1360 | @experimental_api.tool( |
| 1361 | slug="GREP", |
| 1362 | name="Grep", |
| 1363 | description="Search local text", |
| 1364 | ) |
| 1365 | def grep(input: GrepInput, ctx): |
| 1366 | return {"matches": [input.pattern]} |
| 1367 | |
| 1368 | attach_response = mock_client.tool_router.session.attach.return_value |
| 1369 | attach_response.tool_router_tools = ["COMPOSIO_SEARCH_TOOLS"] |
| 1370 | attach_response.config.preload.tools = "all" |
| 1371 | attach_response.experimental = MagicMock() |
| 1372 | attach_response.experimental.assistive_prompt = None |
| 1373 | attach_response.experimental.custom_toolkits = [] |
| 1374 | mock_custom_tool = MagicMock() |
| 1375 | mock_custom_tool.slug = "LOCAL_GREP" |
| 1376 | mock_custom_tool.original_slug = "GREP" |
| 1377 | mock_custom_tool.extends_toolkit = None |
| 1378 | attach_response.experimental.custom_tools = [mock_custom_tool] |
| 1379 | |
| 1380 | mock_tools_instance = MagicMock() |
| 1381 | mock_tool = MagicMock() |
| 1382 | mock_tool.slug = "COMPOSIO_SEARCH_TOOLS" |
| 1383 | mock_tool.toolkit.slug = "composio" |
| 1384 | mock_tool.input_parameters = {} |
| 1385 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 1386 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 1387 | mock_tools_class.return_value = mock_tools_instance |
| 1388 | mock_provider.wrap_tools.return_value = "mocked-custom-tools" |
| 1389 | |
| 1390 | session = tool_router.use(session_id="session_123", local_tools=[grep]) |
| 1391 | session.tools() |
| 1392 | session.search(query="search local text") |
| 1393 | |
| 1394 | wrapped_tools = mock_provider.wrap_tools.call_args.kwargs["tools"] |
| 1395 | assert [tool.slug for tool in wrapped_tools] == [ |
| 1396 | "COMPOSIO_SEARCH_TOOLS", |
| 1397 | "LOCAL_GREP", |
| 1398 | ] |
| 1399 | mock_client.tool_router.session.search.assert_called_once() |
| 1400 | search_kwargs = mock_client.tool_router.session.search.call_args.kwargs |
| 1401 | assert search_kwargs["experimental"]["custom_tools"][0]["slug"] == "GREP" |
| 1402 | assert search_kwargs["experimental"]["custom_tools"][0]["preload"] is True |
| 1403 | |
| 1404 | def test_use_session_with_different_user(self, tool_router, mock_client): |
| 1405 | """Test that use() extracts user_id from session config.""" |
| 1406 | mock_attach_response = MagicMock() |
| 1407 | mock_attach_response.session_id = "session_456" |
| 1408 | mock_attach_response.mcp = MagicMock() |
| 1409 | mock_attach_response.mcp.type = "http" |
| 1410 | mock_attach_response.mcp.url = ( |
| 1411 | "https://backend.composio.dev/api/v3/tool_router/session/session_456" |
| 1412 | ) |
| 1413 | mock_attach_response.tool_router_tools = ["TOOL_1"] |
| 1414 | mock_attach_response.config = MagicMock() |
| 1415 | mock_attach_response.config.user_id = "custom_user_789" |
| 1416 | mock_attach_response.config.preload = MagicMock() |
| 1417 | mock_attach_response.config.preload.tools = [] |
| 1418 | mock_attach_response.experimental = None |
| 1419 | |
| 1420 | mock_client.tool_router.session.retrieve.return_value = mock_attach_response |
| 1421 | |
| 1422 | session = tool_router.use(session_id="session_456") |
| 1423 | |
| 1424 | assert session.session_id == "session_456" |
| 1425 | assert session.mcp.type == ToolRouterMCPServerType.HTTP |
| 1426 | |
| 1427 | def test_use_session_throws_error_on_failure(self, tool_router, mock_client): |
| 1428 | """Test that use() throws error if retrieve fails.""" |
| 1429 | mock_client.tool_router.session.retrieve.side_effect = Exception( |
| 1430 | "Session not found" |
| 1431 | ) |
| 1432 | |
| 1433 | with pytest.raises(Exception, match="Session not found"): |
| 1434 | tool_router.use(session_id="invalid_session") |
| 1435 | |
| 1436 | def test_session_execute_with_account(self, tool_router, mock_client): |
| 1437 | """session.execute forwards account for direct app tool execution.""" |
| 1438 | mock_execute_response = MagicMock() |
| 1439 | mock_execute_response.data = {"ok": True} |
| 1440 | mock_execute_response.error = None |
| 1441 | mock_execute_response.result_type = "completed" |
| 1442 | mock_execute_response.log_id = "log_123" |
| 1443 | mock_client.tool_router.session.execute.return_value = mock_execute_response |
| 1444 | |
| 1445 | session = tool_router.create(user_id="user_123") |
| 1446 | session.execute( |
| 1447 | "GMAIL_FETCH_EMAILS", |
| 1448 | arguments={"max_results": 1}, |
| 1449 | account="work", |
| 1450 | ) |
| 1451 | |
| 1452 | mock_client.tool_router.session.execute.assert_called_once_with( |
| 1453 | session_id="session_123", |
| 1454 | tool_slug="GMAIL_FETCH_EMAILS", |
| 1455 | arguments={"max_results": 1}, |
| 1456 | account="work", |
| 1457 | input_responses=omit, |
| 1458 | request_state=omit, |
| 1459 | experimental=omit, |
| 1460 | ) |
| 1461 | |
| 1462 | def test_authorize_function(self, tool_router, mock_client): |
| 1463 | """Test the authorize function returned by session.""" |
| 1464 | session = tool_router.create(user_id="user_123") |
| 1465 | |
| 1466 | session.authorize("github") |
| 1467 | |
| 1468 | # Verify link was called |
| 1469 | mock_client.tool_router.session.link.assert_called_once() |
| 1470 | call_args = mock_client.tool_router.session.link.call_args |
| 1471 | assert call_args.kwargs["session_id"] == "session_123" |
| 1472 | assert call_args.kwargs["toolkit"] == "github" |
| 1473 | |
| 1474 | def test_authorize_function_with_callback_url(self, tool_router, mock_client): |
| 1475 | """Test the authorize function with callback URL.""" |
| 1476 | session = tool_router.create(user_id="user_123") |
| 1477 | |
| 1478 | session.authorize("github", callback_url="https://myapp.com/callback") |
| 1479 | |
| 1480 | # Verify link was called with callback_url |
| 1481 | call_args = mock_client.tool_router.session.link.call_args |
| 1482 | assert call_args.kwargs.get("callback_url") == "https://myapp.com/callback" |
| 1483 | |
| 1484 | def test_authorize_forwards_experimental_block(self, tool_router, mock_client): |
| 1485 | """authorize() should pass the experimental options through verbatim.""" |
| 1486 | session = tool_router.create(user_id="user_123") |
| 1487 | |
| 1488 | session.authorize( |
| 1489 | "github", |
| 1490 | experimental={ |
| 1491 | "account_type": "SHARED", |
| 1492 | "acl_config_for_shared": { |
| 1493 | "allow_all_users": True, |
| 1494 | "not_allowed_user_ids": ["user_bob"], |
| 1495 | }, |
| 1496 | }, |
| 1497 | ) |
| 1498 | |
| 1499 | call_kwargs = mock_client.tool_router.session.link.call_args.kwargs |
| 1500 | assert call_kwargs["experimental"] == { |
| 1501 | "account_type": "SHARED", |
| 1502 | "acl_config_for_shared": { |
| 1503 | "allow_all_users": True, |
| 1504 | "not_allowed_user_ids": ["user_bob"], |
| 1505 | }, |
| 1506 | } |
| 1507 | |
| 1508 | def test_toolkits_function(self, tool_router, mock_client): |
| 1509 | """Test the toolkits function returned by session.""" |
| 1510 | session = tool_router.create(user_id="user_123") |
| 1511 | |
| 1512 | toolkits_result = session.toolkits() |
| 1513 | |
| 1514 | # Verify toolkits was called |
| 1515 | mock_client.tool_router.session.toolkits.assert_called_once_with( |
| 1516 | session_id="session_123" |
| 1517 | ) |
| 1518 | |
| 1519 | # Verify result structure |
| 1520 | assert isinstance(toolkits_result, ToolkitConnectionsDetails) |
| 1521 | assert len(toolkits_result.items) == 2 |
| 1522 | assert toolkits_result.next_cursor == "cursor_789" |
| 1523 | assert toolkits_result.total_pages == 2 |
| 1524 | |
| 1525 | def test_toolkits_function_with_pagination(self, tool_router, mock_client): |
| 1526 | """Test the toolkits function with pagination options.""" |
| 1527 | session = tool_router.create(user_id="user_123") |
| 1528 | |
| 1529 | session.toolkits(next_cursor="cursor_abc", limit=10) |
| 1530 | |
| 1531 | # Verify toolkits was called with pagination params |
| 1532 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1533 | assert call_args.kwargs.get("cursor") == "cursor_abc" |
| 1534 | assert call_args.kwargs.get("limit") == 10 |
| 1535 | |
| 1536 | def test_toolkits_transform_active_connection(self, tool_router, mock_client): |
| 1537 | """Test that toolkits function correctly transforms active connections.""" |
| 1538 | session = tool_router.create(user_id="user_123") |
| 1539 | |
| 1540 | toolkits_result = session.toolkits() |
| 1541 | |
| 1542 | gmail_toolkit = toolkits_result.items[0] |
| 1543 | assert gmail_toolkit.slug == "gmail" |
| 1544 | assert gmail_toolkit.name == "Gmail" |
| 1545 | assert gmail_toolkit.logo == "https://example.com/gmail-logo.png" |
| 1546 | assert gmail_toolkit.is_no_auth is False |
| 1547 | assert gmail_toolkit.connection.is_active is True |
| 1548 | assert gmail_toolkit.connection.auth_config is not None |
| 1549 | assert gmail_toolkit.connection.auth_config.id == "auth_config_123" |
| 1550 | assert gmail_toolkit.connection.auth_config.mode == "OAUTH2" |
| 1551 | assert gmail_toolkit.connection.auth_config.is_composio_managed is True |
| 1552 | assert gmail_toolkit.connection.connected_account is not None |
| 1553 | assert gmail_toolkit.connection.connected_account.id == "conn_123" |
| 1554 | assert gmail_toolkit.connection.connected_account.status == "ACTIVE" |
| 1555 | |
| 1556 | def test_toolkits_transform_no_connection(self, tool_router, mock_client): |
| 1557 | """Test that toolkits function correctly transforms toolkits with no connection.""" |
| 1558 | session = tool_router.create(user_id="user_123") |
| 1559 | |
| 1560 | toolkits_result = session.toolkits() |
| 1561 | |
| 1562 | github_toolkit = toolkits_result.items[1] |
| 1563 | assert github_toolkit.slug == "github" |
| 1564 | assert github_toolkit.name == "GitHub" |
| 1565 | assert github_toolkit.connection.is_active is False |
| 1566 | assert github_toolkit.connection.auth_config is None |
| 1567 | assert github_toolkit.connection.connected_account is None |
| 1568 | |
| 1569 | def test_toolkits_function_with_search(self, tool_router, mock_client): |
| 1570 | """Test the toolkits function with search parameter.""" |
| 1571 | session = tool_router.create(user_id="user_123") |
| 1572 | |
| 1573 | session.toolkits(search="gmail") |
| 1574 | |
| 1575 | # Verify toolkits was called with search param |
| 1576 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1577 | assert call_args.kwargs.get("search") == "gmail" |
| 1578 | assert call_args.kwargs["session_id"] == "session_123" |
| 1579 | |
| 1580 | def test_toolkits_function_with_search_and_toolkits_filter( |
| 1581 | self, tool_router, mock_client |
| 1582 | ): |
| 1583 | """Test the toolkits function with search and toolkits filter together.""" |
| 1584 | session = tool_router.create(user_id="user_123") |
| 1585 | |
| 1586 | session.toolkits(search="github", toolkits=["github", "slack"]) |
| 1587 | |
| 1588 | # Verify toolkits was called with both search and toolkits params |
| 1589 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1590 | assert call_args.kwargs.get("search") == "github" |
| 1591 | assert call_args.kwargs.get("toolkits") == ["github", "slack"] |
| 1592 | assert call_args.kwargs["session_id"] == "session_123" |
| 1593 | |
| 1594 | def test_toolkits_function_with_search_and_is_connected( |
| 1595 | self, tool_router, mock_client |
| 1596 | ): |
| 1597 | """Test the toolkits function with search and is_connected filter.""" |
| 1598 | session = tool_router.create(user_id="user_123") |
| 1599 | |
| 1600 | session.toolkits(search="mail", is_connected=True) |
| 1601 | |
| 1602 | # Verify toolkits was called with search and is_connected params |
| 1603 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1604 | assert call_args.kwargs.get("search") == "mail" |
| 1605 | assert call_args.kwargs.get("is_connected") is True |
| 1606 | assert call_args.kwargs["session_id"] == "session_123" |
| 1607 | |
| 1608 | def test_toolkits_function_with_search_and_pagination( |
| 1609 | self, tool_router, mock_client |
| 1610 | ): |
| 1611 | """Test the toolkits function with search and pagination parameters.""" |
| 1612 | session = tool_router.create(user_id="user_123") |
| 1613 | |
| 1614 | session.toolkits(search="slack", next_cursor="cursor_xyz", limit=5) |
| 1615 | |
| 1616 | # Verify toolkits was called with search and pagination params |
| 1617 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1618 | assert call_args.kwargs.get("search") == "slack" |
| 1619 | assert call_args.kwargs.get("cursor") == "cursor_xyz" |
| 1620 | assert call_args.kwargs.get("limit") == 5 |
| 1621 | assert call_args.kwargs["session_id"] == "session_123" |
| 1622 | |
| 1623 | def test_toolkits_function_with_search_all_params(self, tool_router, mock_client): |
| 1624 | """Test the toolkits function with search and all other parameters.""" |
| 1625 | session = tool_router.create(user_id="user_123") |
| 1626 | |
| 1627 | session.toolkits( |
| 1628 | search="gmail", |
| 1629 | toolkits=["gmail", "github"], |
| 1630 | next_cursor="cursor_123", |
| 1631 | limit=20, |
| 1632 | is_connected=False, |
| 1633 | ) |
| 1634 | |
| 1635 | # Verify toolkits was called with all params including search |
| 1636 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1637 | assert call_args.kwargs.get("search") == "gmail" |
| 1638 | assert call_args.kwargs.get("toolkits") == ["gmail", "github"] |
| 1639 | assert call_args.kwargs.get("cursor") == "cursor_123" |
| 1640 | assert call_args.kwargs.get("limit") == 20 |
| 1641 | assert call_args.kwargs.get("is_connected") is False |
| 1642 | assert call_args.kwargs["session_id"] == "session_123" |
| 1643 | |
| 1644 | def test_toolkits_function_with_empty_search(self, tool_router, mock_client): |
| 1645 | """Test the toolkits function with empty search string.""" |
| 1646 | session = tool_router.create(user_id="user_123") |
| 1647 | |
| 1648 | session.toolkits(search="") |
| 1649 | |
| 1650 | # Verify toolkits was called with empty search string |
| 1651 | call_args = mock_client.tool_router.session.toolkits.call_args |
| 1652 | assert call_args.kwargs.get("search") == "" |
| 1653 | assert call_args.kwargs["session_id"] == "session_123" |
| 1654 | |
| 1655 | @patch("composio.core.models.tools.Tools") |
| 1656 | def test_tools_function( |
| 1657 | self, mock_tools_class, tool_router, mock_client, mock_provider |
| 1658 | ): |
| 1659 | """Test the tools function returned by session.""" |
| 1660 | # Setup mock Tools instance |
| 1661 | mock_tools_instance = MagicMock() |
| 1662 | mock_tool = MagicMock() |
| 1663 | mock_tool.slug = "GMAIL_FETCH_EMAILS" |
| 1664 | mock_tool.toolkit.slug = "gmail" |
| 1665 | mock_tool.input_parameters = {} |
| 1666 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 1667 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 1668 | mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {} |
| 1669 | mock_tools_class.return_value = mock_tools_instance |
| 1670 | |
| 1671 | # Setup provider mock |
| 1672 | mock_provider.wrap_tools.return_value = "mocked-wrapped-tools" |
| 1673 | |
| 1674 | session = tool_router.create(user_id="user_123") |
| 1675 | result = session.tools() |
| 1676 | |
| 1677 | # Verify Tools was instantiated (resolved flag; default ToolRouter is off) |
| 1678 | mock_tools_class.assert_called_once_with( |
| 1679 | client=mock_client, |
| 1680 | provider=mock_provider, |
| 1681 | dangerously_allow_auto_upload_download_files=False, |
| 1682 | sensitive_file_upload_protection=True, |
| 1683 | file_upload_path_deny_segments=None, |
| 1684 | file_upload_dirs=None, |
| 1685 | ) |
| 1686 | |
| 1687 | # Verify get_raw_tool_router_meta_tools was called |
| 1688 | mock_tools_instance.get_raw_tool_router_meta_tools.assert_called_once() |
| 1689 | |
| 1690 | # Verify provider's wrap_tools was called |
| 1691 | mock_provider.wrap_tools.assert_called_once() |
| 1692 | wrapped_tools = mock_provider.wrap_tools.call_args.kwargs["tools"] |
| 1693 | assert [tool.slug for tool in wrapped_tools] == ["GMAIL_FETCH_EMAILS"] |
| 1694 | assert result == "mocked-wrapped-tools" |
| 1695 | |
| 1696 | @patch("composio.core.models.tools.Tools") |
| 1697 | def test_tools_function_includes_preloaded_custom_tools( |
| 1698 | self, |
| 1699 | mock_tools_class, |
| 1700 | tool_router, |
| 1701 | mock_client, |
| 1702 | mock_provider, |
| 1703 | ): |
| 1704 | """Custom tools with SDK preload enabled are exposed locally.""" |
| 1705 | |
| 1706 | @experimental_api.tool( |
| 1707 | slug="GREP", |
| 1708 | name="Grep", |
| 1709 | description="Search local text", |
| 1710 | preload=True, |
| 1711 | ) |
| 1712 | def grep(input: GrepInput, ctx): |
| 1713 | return {"matches": [input.pattern]} |
| 1714 | |
| 1715 | mock_response = mock_client.tool_router.session.create.return_value |
| 1716 | mock_response.tool_router_tools = ["COMPOSIO_SEARCH_TOOLS"] |
| 1717 | mock_response.experimental = MagicMock() |
| 1718 | mock_response.experimental.assistive_prompt = None |
| 1719 | mock_response.experimental.custom_toolkits = [] |
| 1720 | mock_custom_tool = MagicMock() |
| 1721 | mock_custom_tool.slug = "SERVER_GREP" |
| 1722 | mock_custom_tool.original_slug = "GREP" |
| 1723 | mock_custom_tool.extends_toolkit = None |
| 1724 | mock_response.experimental.custom_tools = [mock_custom_tool] |
| 1725 | |
| 1726 | mock_tools_instance = MagicMock() |
| 1727 | mock_tool = MagicMock() |
| 1728 | mock_tool.slug = "COMPOSIO_SEARCH_TOOLS" |
| 1729 | mock_tool.toolkit.slug = "composio" |
| 1730 | mock_tool.input_parameters = {} |
| 1731 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 1732 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 1733 | mock_tools_class.return_value = mock_tools_instance |
| 1734 | mock_provider.wrap_tools.return_value = "mocked-custom-tools" |
| 1735 | |
| 1736 | session = tool_router.create( |
| 1737 | user_id="user_123", |
| 1738 | experimental={"local_tools": [grep]}, |
| 1739 | ) |
| 1740 | result = session.tools() |
| 1741 | |
| 1742 | wrapped_tools = mock_provider.wrap_tools.call_args.kwargs["tools"] |
| 1743 | assert [tool.slug for tool in wrapped_tools] == [ |
| 1744 | "COMPOSIO_SEARCH_TOOLS", |
| 1745 | "SERVER_GREP", |
| 1746 | ] |
| 1747 | assert DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX in wrapped_tools[1].description |
| 1748 | assert wrapped_tools[1].toolkit.slug == "custom" |
| 1749 | assert result == "mocked-custom-tools" |
| 1750 | |
| 1751 | execute_tool = mock_provider.wrap_tools.call_args.kwargs["execute_tool"] |
| 1752 | # Gemini's manual handle_response(session=...) finds this routing |
| 1753 | # executor by the session recorded on it. |
| 1754 | assert get_execution_target(execute_tool) is session |
| 1755 | local_result = execute_tool(slug="SERVER_GREP", arguments={"pattern": "needle"}) |
| 1756 | assert local_result == { |
| 1757 | "data": {"matches": ["needle"]}, |
| 1758 | "error": None, |
| 1759 | "successful": True, |
| 1760 | } |
| 1761 | mock_client.tool_router.session.execute.assert_not_called() |
| 1762 | |
| 1763 | @patch("composio.core.models.tools.Tools") |
| 1764 | def test_tools_function_with_modifiers( |
| 1765 | self, |
| 1766 | mock_tools_class, |
| 1767 | tool_router, |
| 1768 | mock_client, |
| 1769 | mock_provider, |
| 1770 | ): |
| 1771 | """Test the tools function with modifiers.""" |
| 1772 | mock_tools_instance = MagicMock() |
| 1773 | mock_tool = MagicMock() |
| 1774 | mock_tool.slug = "GMAIL_FETCH_EMAILS" |
| 1775 | mock_tool.toolkit.slug = "gmail" |
| 1776 | mock_tool.input_parameters = {} |
| 1777 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 1778 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 1779 | mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {} |
| 1780 | mock_tools_class.return_value = mock_tools_instance |
| 1781 | |
| 1782 | # Setup provider mock |
| 1783 | mock_provider.wrap_tools.return_value = "mocked-wrapped-tools" |
| 1784 | |
| 1785 | session = tool_router.create(user_id="user_123") |
| 1786 | |
| 1787 | # Create a proper modifier structure |
| 1788 | from composio.core.models._modifiers import Modifier |
| 1789 | |
| 1790 | modifier = Modifier(modifier=None, type_="schema", tools=[], toolkits=[]) |
| 1791 | modifiers = [modifier] |
| 1792 | result = session.tools(modifiers=modifiers) |
| 1793 | |
| 1794 | # Verify provider's wrap_tools was called |
| 1795 | mock_provider.wrap_tools.assert_called_once() |
| 1796 | # Verify get_raw_tool_router_meta_tools was called with modifiers |
| 1797 | call_args = mock_tools_instance.get_raw_tool_router_meta_tools.call_args |
| 1798 | assert call_args.kwargs.get("modifiers") == modifiers |
| 1799 | assert result == "mocked-wrapped-tools" |
| 1800 | |
| 1801 | def test_session_mcp_type_http(self, tool_router, mock_client): |
| 1802 | """Test that MCP type is correctly set to HTTP enum.""" |
| 1803 | session = tool_router.create(user_id="user_123") |
| 1804 | |
| 1805 | assert session.mcp.type == ToolRouterMCPServerType.HTTP |
| 1806 | assert session.mcp.type.value == "http" |
| 1807 | |
| 1808 | def test_session_mcp_sse_type(self, tool_router, mock_client): |
| 1809 | """Test that SSE MCP type is handled correctly.""" |
| 1810 | mock_sse_response = MagicMock() |
| 1811 | mock_sse_response.session_id = "session_sse" |
| 1812 | mock_sse_response.mcp = MagicMock() |
| 1813 | mock_sse_response.mcp.type = "sse" |
| 1814 | mock_sse_response.mcp.url = ( |
| 1815 | "https://backend.composio.dev/api/v3/tool_router/session/sse/session_sse" |
| 1816 | ) |
| 1817 | mock_sse_response.tool_router_tools = ["TOOL_1"] |
| 1818 | |
| 1819 | mock_client.tool_router.session.create.return_value = mock_sse_response |
| 1820 | |
| 1821 | session = tool_router.create(user_id="user_123") |
| 1822 | |
| 1823 | assert session.mcp.type == ToolRouterMCPServerType.SSE |
| 1824 | assert session.mcp.type.value == "sse" |
| 1825 | assert ( |
| 1826 | session.mcp.url |
| 1827 | == "https://backend.composio.dev/api/v3/tool_router/session/sse/session_sse" |
| 1828 | ) |
| 1829 | |
| 1830 | def test_multiple_sessions_independently(self, tool_router, mock_client): |
| 1831 | """Test that multiple sessions can be created independently.""" |
| 1832 | mock_session_1 = MagicMock() |
| 1833 | mock_session_1.session_id = "session_1" |
| 1834 | mock_session_1.mcp = MagicMock() |
| 1835 | mock_session_1.mcp.type = "http" |
| 1836 | mock_session_1.mcp.url = ( |
| 1837 | "https://backend.composio.dev/api/v3/tool_router/session/session_1" |
| 1838 | ) |
| 1839 | mock_session_1.tool_router_tools = ["TOOL_1"] |
| 1840 | |
| 1841 | mock_session_2 = MagicMock() |
| 1842 | mock_session_2.session_id = "session_2" |
| 1843 | mock_session_2.mcp = MagicMock() |
| 1844 | mock_session_2.mcp.type = "http" |
| 1845 | mock_session_2.mcp.url = ( |
| 1846 | "https://backend.composio.dev/api/v3/tool_router/session/session_2" |
| 1847 | ) |
| 1848 | mock_session_2.tool_router_tools = ["TOOL_2"] |
| 1849 | |
| 1850 | mock_client.tool_router.session.create.side_effect = [ |
| 1851 | mock_session_1, |
| 1852 | mock_session_2, |
| 1853 | ] |
| 1854 | |
| 1855 | session1 = tool_router.create(user_id="user_1") |
| 1856 | session2 = tool_router.create(user_id="user_2") |
| 1857 | |
| 1858 | assert session1.session_id == "session_1" |
| 1859 | assert session2.session_id == "session_2" |
| 1860 | assert mock_client.tool_router.session.create.call_count == 2 |
| 1861 | |
| 1862 | def test_use_vs_create_independence(self, tool_router, mock_client): |
| 1863 | """Test that use() and create() are independent.""" |
| 1864 | # Setup different responses for create and attach |
| 1865 | mock_create_response = MagicMock() |
| 1866 | mock_create_response.session_id = "created_session" |
| 1867 | mock_create_response.mcp = MagicMock() |
| 1868 | mock_create_response.mcp.type = "http" |
| 1869 | mock_create_response.mcp.url = ( |
| 1870 | "https://backend.composio.dev/api/v3/tool_router/session/created" |
| 1871 | ) |
| 1872 | mock_create_response.tool_router_tools = ["TOOL_1"] |
| 1873 | |
| 1874 | mock_attach_response = MagicMock() |
| 1875 | mock_attach_response.session_id = "retrieved_session" |
| 1876 | mock_attach_response.mcp = MagicMock() |
| 1877 | mock_attach_response.mcp.type = "http" |
| 1878 | mock_attach_response.mcp.url = ( |
| 1879 | "https://backend.composio.dev/api/v3/tool_router/session/retrieved" |
| 1880 | ) |
| 1881 | mock_attach_response.tool_router_tools = ["TOOL_2"] |
| 1882 | mock_attach_response.config = MagicMock() |
| 1883 | mock_attach_response.config.user_id = "user_456" |
| 1884 | mock_attach_response.config.preload = MagicMock() |
| 1885 | mock_attach_response.config.preload.tools = [] |
| 1886 | mock_attach_response.experimental = None |
| 1887 | |
| 1888 | mock_client.tool_router.session.create.return_value = mock_create_response |
| 1889 | mock_client.tool_router.session.retrieve.return_value = mock_attach_response |
| 1890 | |
| 1891 | # Create a new session |
| 1892 | created_session = tool_router.create(user_id="user_123") |
| 1893 | assert created_session.session_id == "created_session" |
| 1894 | |
| 1895 | # Use an existing session |
| 1896 | retrieved_session = tool_router.use(session_id="retrieved_session") |
| 1897 | assert retrieved_session.session_id == "retrieved_session" |
| 1898 | |
| 1899 | # Verify both methods were called |
| 1900 | mock_client.tool_router.session.create.assert_called_once() |
| 1901 | mock_client.tool_router.session.retrieve.assert_called_once_with( |
| 1902 | "retrieved_session" |
| 1903 | ) |
| 1904 | mock_client.post.assert_not_called() |
| 1905 | |
| 1906 | |
| 1907 | def _local_grep_tool(): |
| 1908 | @experimental_api.tool(slug="GREP", name="Grep", description="Search local text") |
| 1909 | def grep(input: GrepInput, ctx): |
| 1910 | return {"matches": []} |
| 1911 | |
| 1912 | return grep |
| 1913 | |
| 1914 | |
| 1915 | def _local_role_toolkit(): |
| 1916 | toolkit = experimental_api.Toolkit( |
| 1917 | slug="ROLES", name="Roles", description="Manage roles" |
| 1918 | ) |
| 1919 | |
| 1920 | @toolkit.tool(slug="SET_ROLE") |
| 1921 | def set_role(input: GrepInput, ctx): |
| 1922 | """Set a role.""" |
| 1923 | return {"ok": True} |
| 1924 | |
| 1925 | return toolkit |
| 1926 | |
| 1927 | |
| 1928 | def _mock_local_tools_response(response): |
| 1929 | response.experimental = MagicMock() |
| 1930 | response.experimental.assistive_prompt = None |
| 1931 | server_tool = MagicMock() |
| 1932 | server_tool.slug = "LOCAL_GREP" |
| 1933 | server_tool.original_slug = "GREP" |
| 1934 | server_tool.extends_toolkit = None |
| 1935 | response.experimental.custom_tools = [server_tool] |
| 1936 | server_toolkit = MagicMock() |
| 1937 | server_toolkit.slug = "ROLES" |
| 1938 | server_toolkit.tools = [ |
| 1939 | MagicMock(slug="LOCAL_ROLES_SET_ROLE", original_slug="SET_ROLE") |
| 1940 | ] |
| 1941 | response.experimental.custom_toolkits = [server_toolkit] |
| 1942 | |
| 1943 | |
| 1944 | class TestLocalToolsOptions: |
| 1945 | """`local_tools`/`local_toolkits` and their deprecated `custom_*` aliases.""" |
| 1946 | |
| 1947 | def test_create_with_local_tools_sends_custom_wire_fields( |
| 1948 | self, tool_router, mock_client |
| 1949 | ): |
| 1950 | _mock_local_tools_response(mock_client.tool_router.session.create.return_value) |
| 1951 | tool = _local_grep_tool() |
| 1952 | toolkit = _local_role_toolkit() |
| 1953 | |
| 1954 | with warnings.catch_warnings(): |
| 1955 | warnings.simplefilter("error") |
| 1956 | session = tool_router.create( |
| 1957 | user_id="user_123", |
| 1958 | experimental={ |
| 1959 | "local_tools": [tool], |
| 1960 | "local_toolkits": [toolkit], |
| 1961 | }, |
| 1962 | ) |
| 1963 | |
| 1964 | experimental = mock_client.tool_router.session.create.call_args.kwargs[ |
| 1965 | "experimental" |
| 1966 | ] |
| 1967 | assert set(experimental) == {"custom_tools", "custom_toolkits"} |
| 1968 | assert experimental["custom_tools"][0]["slug"] == "GREP" |
| 1969 | assert experimental["custom_toolkits"][0]["slug"] == "ROLES" |
| 1970 | assert [tool.slug for tool in session.local_tools()] == [ |
| 1971 | "LOCAL_GREP", |
| 1972 | "LOCAL_ROLES_SET_ROLE", |
| 1973 | ] |
| 1974 | assert [tk.slug for tk in session.local_toolkits()] == ["ROLES"] |
| 1975 | |
| 1976 | def test_create_with_deprecated_custom_names_warns(self, tool_router, mock_client): |
| 1977 | _mock_local_tools_response(mock_client.tool_router.session.create.return_value) |
| 1978 | tool = _local_grep_tool() |
| 1979 | toolkit = _local_role_toolkit() |
| 1980 | |
| 1981 | with pytest.warns(ComposioDeprecationWarning) as record: |
| 1982 | session = tool_router.create( |
| 1983 | user_id="user_123", |
| 1984 | experimental={ |
| 1985 | "custom_tools": [tool], |
| 1986 | "custom_toolkits": [toolkit], |
| 1987 | }, |
| 1988 | ) |
| 1989 | |
| 1990 | assert [str(w.message) for w in record] == [ |
| 1991 | "`custom_tools` is deprecated; use `local_tools`", |
| 1992 | "`custom_toolkits` is deprecated; use `local_toolkits`", |
| 1993 | ] |
| 1994 | assert record[0].filename == __file__ |
| 1995 | experimental = mock_client.tool_router.session.create.call_args.kwargs[ |
| 1996 | "experimental" |
| 1997 | ] |
| 1998 | assert experimental["custom_tools"][0]["slug"] == "GREP" |
| 1999 | assert experimental["custom_toolkits"][0]["slug"] == "ROLES" |
| 2000 | assert session.local_tools()[0].slug == "LOCAL_GREP" |
| 2001 | |
| 2002 | @pytest.mark.parametrize( |
| 2003 | ("new_name", "old_name", "value"), |
| 2004 | [ |
| 2005 | ("local_tools", "custom_tools", _local_grep_tool), |
| 2006 | ("local_toolkits", "custom_toolkits", _local_role_toolkit), |
| 2007 | ], |
| 2008 | ) |
| 2009 | def test_create_rejects_new_and_deprecated_names_together( |
| 2010 | self, tool_router, mock_client, new_name, old_name, value |
| 2011 | ): |
| 2012 | with pytest.raises( |
| 2013 | InvalidParams, |
| 2014 | match=f"^Pass either `{new_name}` or `{old_name}`, not both", |
| 2015 | ): |
| 2016 | tool_router.create( |
| 2017 | user_id="user_123", |
| 2018 | experimental=t.cast( |
| 2019 | ToolRouterExperimentalConfig, |
| 2020 | {new_name: [value()], old_name: [value()]}, |
| 2021 | ), |
| 2022 | ) |
| 2023 | |
| 2024 | mock_client.tool_router.session.create.assert_not_called() |
| 2025 | |
| 2026 | def test_use_with_local_tools_sends_custom_wire_fields( |
| 2027 | self, tool_router, mock_client |
| 2028 | ): |
| 2029 | _mock_local_tools_response(mock_client.tool_router.session.attach.return_value) |
| 2030 | tool = _local_grep_tool() |
| 2031 | toolkit = _local_role_toolkit() |
| 2032 | |
| 2033 | with warnings.catch_warnings(): |
| 2034 | warnings.simplefilter("error") |
| 2035 | session = tool_router.use( |
| 2036 | "session_123", |
| 2037 | local_tools=[tool], |
| 2038 | local_toolkits=[toolkit], |
| 2039 | ) |
| 2040 | |
| 2041 | experimental = mock_client.tool_router.session.attach.call_args.kwargs[ |
| 2042 | "experimental" |
| 2043 | ] |
| 2044 | assert set(experimental) == {"custom_tools", "custom_toolkits"} |
| 2045 | assert [tool.slug for tool in session.local_tools()] == [ |
| 2046 | "LOCAL_GREP", |
| 2047 | "LOCAL_ROLES_SET_ROLE", |
| 2048 | ] |
| 2049 | |
| 2050 | def test_use_with_deprecated_custom_names_warns(self, tool_router, mock_client): |
| 2051 | _mock_local_tools_response(mock_client.tool_router.session.attach.return_value) |
| 2052 | tool = _local_grep_tool() |
| 2053 | toolkit = _local_role_toolkit() |
| 2054 | |
| 2055 | with pytest.warns(ComposioDeprecationWarning) as record: |
| 2056 | session = tool_router.use( |
| 2057 | "session_123", |
| 2058 | custom_tools=[tool], |
| 2059 | custom_toolkits=[toolkit], |
| 2060 | ) |
| 2061 | |
| 2062 | assert [str(w.message) for w in record] == [ |
| 2063 | "`custom_tools` is deprecated; use `local_tools`", |
| 2064 | "`custom_toolkits` is deprecated; use `local_toolkits`", |
| 2065 | ] |
| 2066 | assert record[0].filename == __file__ |
| 2067 | experimental = mock_client.tool_router.session.attach.call_args.kwargs[ |
| 2068 | "experimental" |
| 2069 | ] |
| 2070 | assert experimental["custom_tools"][0]["slug"] == "GREP" |
| 2071 | assert session.local_toolkits()[0].slug == "ROLES" |
| 2072 | |
| 2073 | @pytest.mark.parametrize( |
| 2074 | ("new_name", "old_name", "value"), |
| 2075 | [ |
| 2076 | ("local_tools", "custom_tools", _local_grep_tool), |
| 2077 | ("local_toolkits", "custom_toolkits", _local_role_toolkit), |
| 2078 | ], |
| 2079 | ) |
| 2080 | def test_use_rejects_new_and_deprecated_names_together( |
| 2081 | self, tool_router, mock_client, new_name, old_name, value |
| 2082 | ): |
| 2083 | with pytest.raises( |
| 2084 | InvalidParams, |
| 2085 | match=f"^Pass either `{new_name}` or `{old_name}`, not both", |
| 2086 | ): |
| 2087 | tool_router.use("session_123", **{new_name: [value()], old_name: [value()]}) |
| 2088 | |
| 2089 | mock_client.tool_router.session.attach.assert_not_called() |
| 2090 | mock_client.tool_router.session.retrieve.assert_not_called() |
| 2091 | |
| 2092 | |
| 2093 | class TestToolRouterTypes: |
| 2094 | """Test type definitions for ToolRouter.""" |
| 2095 | |
| 2096 | def test_toolkit_enable_config_type(self): |
| 2097 | """Test ToolRouterToolkitsEnableConfig type.""" |
| 2098 | config: ToolRouterToolkitsEnableConfig = {"enable": ["github", "slack"]} |
| 2099 | assert "enable" in config |
| 2100 | assert config["enable"] == ["github", "slack"] |
| 2101 | |
| 2102 | def test_toolkit_disable_config_type(self): |
| 2103 | """Test ToolRouterToolkitsDisableConfig type.""" |
| 2104 | config: ToolRouterToolkitsDisableConfig = {"disable": ["linear"]} |
| 2105 | assert "disable" in config |
| 2106 | |
| 2107 | def test_manage_connections_config_type(self): |
| 2108 | """Test ToolRouterManageConnectionsConfig type.""" |
| 2109 | config: ToolRouterManageConnectionsConfig = { |
| 2110 | "enable": True, |
| 2111 | "callback_url": "https://example.com/callback", |
| 2112 | } |
| 2113 | assert config["enable"] is True |
| 2114 | assert config["callback_url"] == "https://example.com/callback" |
| 2115 | |
| 2116 | def test_experimental_config_type(self): |
| 2117 | """Test ToolRouterExperimentalConfig type.""" |
| 2118 | config: ToolRouterExperimentalConfig = { |
| 2119 | "assistive_prompt": { |
| 2120 | "user_timezone": "America/New_York", |
| 2121 | } |
| 2122 | } |
| 2123 | assert "assistive_prompt" in config |
| 2124 | assert config["assistive_prompt"]["user_timezone"] == "America/New_York" |
| 2125 | |
| 2126 | def test_session_experimental_dataclass(self): |
| 2127 | """Test ToolRouterSessionExperimental dataclass.""" |
| 2128 | mock_files = MagicMock() |
| 2129 | experimental = ToolRouterSessionExperimental( |
| 2130 | files=mock_files, |
| 2131 | assistive_prompt="You are a helpful assistant.", |
| 2132 | ) |
| 2133 | assert experimental.assistive_prompt == "You are a helpful assistant." |
| 2134 | assert experimental.files is mock_files |
| 2135 | |
| 2136 | # Test with None assistive_prompt |
| 2137 | mock_files_none = MagicMock() |
| 2138 | experimental_none = ToolRouterSessionExperimental( |
| 2139 | files=mock_files_none, |
| 2140 | assistive_prompt=None, |
| 2141 | ) |
| 2142 | assert experimental_none.assistive_prompt is None |
| 2143 | assert experimental_none.files is mock_files_none |
| 2144 | |
| 2145 | def test_mcp_server_config(self): |
| 2146 | """Test ToolRouterMCPServerConfig dataclass.""" |
| 2147 | mcp = ToolRouterMCPServerConfig( |
| 2148 | type=ToolRouterMCPServerType.HTTP, url="https://mcp.example.com" |
| 2149 | ) |
| 2150 | assert mcp.type == ToolRouterMCPServerType.HTTP |
| 2151 | assert mcp.type.value == "http" |
| 2152 | assert mcp.url == "https://mcp.example.com" |
| 2153 | assert mcp.headers is None # Headers are optional |
| 2154 | |
| 2155 | def test_mcp_server_config_with_headers(self): |
| 2156 | """Test ToolRouterMCPServerConfig dataclass with headers.""" |
| 2157 | mcp = ToolRouterMCPServerConfig( |
| 2158 | type=ToolRouterMCPServerType.HTTP, |
| 2159 | url="https://mcp.example.com", |
| 2160 | headers={"x-api-key": "test-api-key"}, |
| 2161 | ) |
| 2162 | assert mcp.type == ToolRouterMCPServerType.HTTP |
| 2163 | assert mcp.url == "https://mcp.example.com" |
| 2164 | assert mcp.headers == {"x-api-key": "test-api-key"} |
| 2165 | |
| 2166 | def test_toolkit_connection_state(self): |
| 2167 | """Test ToolkitConnectionState dataclass.""" |
| 2168 | from composio.core.models.tool_router import ( |
| 2169 | ToolkitConnectedAccount, |
| 2170 | ToolkitConnection, |
| 2171 | ToolkitConnectionAuthConfig, |
| 2172 | ) |
| 2173 | |
| 2174 | connection = ToolkitConnection( |
| 2175 | is_active=True, |
| 2176 | auth_config=ToolkitConnectionAuthConfig( |
| 2177 | id="ac_123", mode="OAUTH2", is_composio_managed=True |
| 2178 | ), |
| 2179 | connected_account=ToolkitConnectedAccount(id="ca_123", status="ACTIVE"), |
| 2180 | ) |
| 2181 | |
| 2182 | state = ToolkitConnectionState( |
| 2183 | slug="github", |
| 2184 | name="GitHub", |
| 2185 | is_no_auth=False, |
| 2186 | connection=connection, |
| 2187 | logo="https://example.com/logo.png", |
| 2188 | ) |
| 2189 | |
| 2190 | assert state.slug == "github" |
| 2191 | assert state.name == "GitHub" |
| 2192 | assert state.connection.is_active is True |
| 2193 | assert state.connection.auth_config is not None |
| 2194 | assert state.connection.auth_config.id == "ac_123" |
| 2195 | |
| 2196 | |
| 2197 | class TestToolRouterExecution: |
| 2198 | """Tests for tool router execution functionality.""" |
| 2199 | |
| 2200 | @patch("composio.core.models.tools.Tools") |
| 2201 | def test_wrap_execute_tool_for_tool_router_called( |
| 2202 | self, mock_tools_class, tool_router, mock_client, mock_provider |
| 2203 | ): |
| 2204 | """Test that _wrap_execute_tool_for_tool_router is called when creating tools.""" |
| 2205 | # Setup |
| 2206 | mock_tools_instance = MagicMock() |
| 2207 | mock_tool = MagicMock() |
| 2208 | mock_tool.slug = "GMAIL_SEND_EMAIL" |
| 2209 | mock_tool.toolkit.slug = "gmail" |
| 2210 | mock_tool.input_parameters = {} |
| 2211 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 2212 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 2213 | mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {} |
| 2214 | mock_tools_instance._wrap_execute_tool_for_tool_router = MagicMock( |
| 2215 | return_value=lambda slug, args: { |
| 2216 | "data": {}, |
| 2217 | "error": None, |
| 2218 | "successful": True, |
| 2219 | } |
| 2220 | ) |
| 2221 | mock_tools_class.return_value = mock_tools_instance |
| 2222 | |
| 2223 | # Setup provider mock |
| 2224 | mock_provider.wrap_tools.return_value = ["wrapped_tool"] |
| 2225 | |
| 2226 | # Create session and get tools |
| 2227 | session = tool_router.create(user_id="user_123") |
| 2228 | session.tools() |
| 2229 | |
| 2230 | # Verify _wrap_execute_tool_for_tool_router was called with correct session_id |
| 2231 | mock_tools_instance._wrap_execute_tool_for_tool_router.assert_called_once() |
| 2232 | call_args = mock_tools_instance._wrap_execute_tool_for_tool_router.call_args |
| 2233 | assert call_args.kwargs["session_id"] == "session_123" |
| 2234 | |
| 2235 | def test_execute_endpoint_called_with_auto_offload_opt_in( |
| 2236 | self, tool_router, mock_client, mock_provider |
| 2237 | ): |
| 2238 | """Test that session execute is called for agentic tool execution.""" |
| 2239 | mock_client.tool_router.session.execute.return_value = ( |
| 2240 | SessionExecuteResponse.model_validate( |
| 2241 | { |
| 2242 | "result_type": "completed", |
| 2243 | "data": {"result": "success"}, |
| 2244 | "error": None, |
| 2245 | "log_id": "log_123", |
| 2246 | } |
| 2247 | ) |
| 2248 | ) |
| 2249 | |
| 2250 | # Create a real Tools instance to test the execute function |
| 2251 | from composio.core.models.tools import Tools as RealTools |
| 2252 | |
| 2253 | real_tools = RealTools( |
| 2254 | client=mock_client, |
| 2255 | provider=mock_provider, |
| 2256 | dangerously_allow_auto_upload_download_files=False, |
| 2257 | ) |
| 2258 | execute_fn = real_tools._wrap_execute_tool_for_tool_router( |
| 2259 | session_id="session_123" |
| 2260 | ) |
| 2261 | |
| 2262 | # Execute the tool |
| 2263 | result = execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"}) |
| 2264 | |
| 2265 | # Verify execute was called with direct offload opt-in for agentic calls |
| 2266 | mock_client.tool_router.session.execute.assert_called_once_with( |
| 2267 | session_id="session_123", |
| 2268 | tool_slug="GMAIL_SEND_EMAIL", |
| 2269 | arguments={"to": "test@example.com"}, |
| 2270 | enable_auto_workbench_offload=True, |
| 2271 | experimental=omit, |
| 2272 | ) |
| 2273 | |
| 2274 | # Verify result format |
| 2275 | assert result["data"] == {"result": "success"} |
| 2276 | assert result["error"] is None |
| 2277 | assert result["successful"] is True |
| 2278 | assert "instant_charge" not in result |
| 2279 | |
| 2280 | def test_execute_endpoint_preserves_instant_charge( |
| 2281 | self, tool_router, mock_client, mock_provider |
| 2282 | ): |
| 2283 | """Provider-wrapped session tools keep the reported Instant charge.""" |
| 2284 | from composio_client.types.tool_router.session_execute_response import ( |
| 2285 | SessionExecuteResponse, |
| 2286 | ) |
| 2287 | |
| 2288 | from composio.core.models.tools import Tools as RealTools |
| 2289 | |
| 2290 | charge = {"amount": "0.01", "currency": "USD", "charged_by": "composio"} |
| 2291 | mock_client.tool_router.session.execute.return_value = ( |
| 2292 | SessionExecuteResponse.model_validate( |
| 2293 | { |
| 2294 | "result_type": "completed", |
| 2295 | "data": {"result": "success"}, |
| 2296 | "error": None, |
| 2297 | "log_id": "log_123", |
| 2298 | "instant_charge": charge, |
| 2299 | } |
| 2300 | ) |
| 2301 | ) |
| 2302 | real_tools = RealTools( |
| 2303 | client=mock_client, |
| 2304 | provider=mock_provider, |
| 2305 | dangerously_allow_auto_upload_download_files=False, |
| 2306 | ) |
| 2307 | execute_fn = real_tools._wrap_execute_tool_for_tool_router( |
| 2308 | session_id="session_123" |
| 2309 | ) |
| 2310 | |
| 2311 | result = execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"}) |
| 2312 | |
| 2313 | assert result["instant_charge"] == charge |
| 2314 | |
| 2315 | def test_execute_endpoint_passes_inline_custom_tools( |
| 2316 | self, tool_router, mock_client, mock_provider |
| 2317 | ): |
| 2318 | """Provider-wrapped session tools pass inline custom definitions.""" |
| 2319 | mock_client.tool_router.session.execute.return_value = SessionExecuteResponse( |
| 2320 | data={"result": "success"}, |
| 2321 | error=None, |
| 2322 | result_type="completed", |
| 2323 | log_id="log-inline", |
| 2324 | ) |
| 2325 | |
| 2326 | from composio.core.models.tools import Tools as RealTools |
| 2327 | |
| 2328 | inline_payload = { |
| 2329 | "custom_tools": [ |
| 2330 | { |
| 2331 | "slug": "GREP", |
| 2332 | "name": "Grep", |
| 2333 | "description": "Search local text", |
| 2334 | "input_schema": {"type": "object", "properties": {}}, |
| 2335 | } |
| 2336 | ] |
| 2337 | } |
| 2338 | real_tools = RealTools( |
| 2339 | client=mock_client, |
| 2340 | provider=mock_provider, |
| 2341 | dangerously_allow_auto_upload_download_files=False, |
| 2342 | ) |
| 2343 | execute_fn = real_tools._wrap_execute_tool_for_tool_router( |
| 2344 | session_id="session_123", |
| 2345 | inline_custom_tools_payload=inline_payload, |
| 2346 | ) |
| 2347 | |
| 2348 | execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"}) |
| 2349 | |
| 2350 | mock_client.tool_router.session.execute.assert_called_once_with( |
| 2351 | session_id="session_123", |
| 2352 | tool_slug="GMAIL_SEND_EMAIL", |
| 2353 | arguments={"to": "test@example.com"}, |
| 2354 | enable_auto_workbench_offload=True, |
| 2355 | experimental=inline_payload, |
| 2356 | ) |
| 2357 | |
| 2358 | def test_modifiers_applied_in_tool_router_execution( |
| 2359 | self, tool_router, mock_client, mock_provider |
| 2360 | ): |
| 2361 | """Test that modifiers are applied before and after tool execution.""" |
| 2362 | mock_client.tool_router.session.execute.return_value = SessionExecuteResponse( |
| 2363 | data={"result": "success"}, |
| 2364 | error=None, |
| 2365 | result_type="completed", |
| 2366 | log_id="log-modified", |
| 2367 | ) |
| 2368 | |
| 2369 | # Create modifier functions |
| 2370 | def before_modifier(tool, toolkit, params): |
| 2371 | """Modifier to change arguments before execution.""" |
| 2372 | params["arguments"] = {"to": "modified@example.com"} |
| 2373 | return params |
| 2374 | |
| 2375 | def after_modifier(tool, toolkit, response): |
| 2376 | """Modifier to change response after execution.""" |
| 2377 | response["data"] = {"modified": True} |
| 2378 | return response |
| 2379 | |
| 2380 | # Create a real execute function with modifiers |
| 2381 | from composio.core.models._modifiers import Modifier |
| 2382 | from composio.core.models.tools import Tools as RealTools |
| 2383 | |
| 2384 | real_tools = RealTools( |
| 2385 | client=mock_client, |
| 2386 | provider=mock_provider, |
| 2387 | dangerously_allow_auto_upload_download_files=False, |
| 2388 | ) |
| 2389 | |
| 2390 | modifiers = [ |
| 2391 | Modifier( |
| 2392 | modifier=before_modifier, type_="before_execute", tools=[], toolkits=[] |
| 2393 | ), |
| 2394 | Modifier( |
| 2395 | modifier=after_modifier, type_="after_execute", tools=[], toolkits=[] |
| 2396 | ), |
| 2397 | ] |
| 2398 | |
| 2399 | execute_fn = real_tools._wrap_execute_tool_for_tool_router( |
| 2400 | session_id="session_123", modifiers=modifiers |
| 2401 | ) |
| 2402 | |
| 2403 | # Execute the tool |
| 2404 | result = execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"}) |
| 2405 | |
| 2406 | # Verify execute was called with modified arguments |
| 2407 | mock_client.tool_router.session.execute.assert_called_once() |
| 2408 | call_args = mock_client.tool_router.session.execute.call_args |
| 2409 | assert call_args.kwargs["arguments"] == {"to": "modified@example.com"} |
| 2410 | assert call_args.kwargs["enable_auto_workbench_offload"] is True |
| 2411 | |
| 2412 | # Verify result was modified by after_execute |
| 2413 | assert result["data"] == {"modified": True} |
| 2414 | |
| 2415 | def test_execute_tool_error_handling(self, tool_router, mock_client, mock_provider): |
| 2416 | """Test that tool execution errors are handled correctly.""" |
| 2417 | mock_client.tool_router.session.execute.return_value = ( |
| 2418 | SessionExecuteResponse.model_validate( |
| 2419 | { |
| 2420 | "result_type": "failed", |
| 2421 | "data": {}, |
| 2422 | "error": "Authentication failed", |
| 2423 | "log_id": "log_123", |
| 2424 | } |
| 2425 | ) |
| 2426 | ) |
| 2427 | |
| 2428 | # Create a real execute function |
| 2429 | from composio.core.models.tools import Tools as RealTools |
| 2430 | |
| 2431 | real_tools = RealTools( |
| 2432 | client=mock_client, |
| 2433 | provider=mock_provider, |
| 2434 | dangerously_allow_auto_upload_download_files=False, |
| 2435 | ) |
| 2436 | execute_fn = real_tools._wrap_execute_tool_for_tool_router( |
| 2437 | session_id="session_123" |
| 2438 | ) |
| 2439 | |
| 2440 | # Execute the tool |
| 2441 | result = execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"}) |
| 2442 | |
| 2443 | # Verify error is returned correctly |
| 2444 | assert result["error"] == "Authentication failed" |
| 2445 | assert result["successful"] is False |
| 2446 | assert result["data"] == {} |
| 2447 | |
| 2448 | |
| 2449 | class TestToolRouterIntegration: |
| 2450 | """Integration tests for ToolRouter.""" |
| 2451 | |
| 2452 | @patch("composio.core.models.tools.Tools") |
| 2453 | def test_full_session_workflow( |
| 2454 | self, mock_tools_class, tool_router, mock_client, mock_provider |
| 2455 | ): |
| 2456 | """Test a complete session workflow.""" |
| 2457 | # Setup |
| 2458 | mock_tools_instance = MagicMock() |
| 2459 | mock_tool = MagicMock() |
| 2460 | mock_tool.slug = "TOOL1" |
| 2461 | mock_tool.toolkit.slug = "github" |
| 2462 | mock_tool.input_parameters = {} |
| 2463 | mock_tools_instance.get_raw_tool_router_meta_tools.return_value = [mock_tool] |
| 2464 | mock_tools_instance._file_helper.enhance_schema_descriptions.return_value = {} |
| 2465 | mock_tools_instance._file_helper.process_file_uploadable_schema.return_value = {} |
| 2466 | mock_tools_class.return_value = mock_tools_instance |
| 2467 | |
| 2468 | # Setup provider mock |
| 2469 | mock_provider.wrap_tools.return_value = ["tool1", "tool2"] |
| 2470 | |
| 2471 | # Create session |
| 2472 | session = tool_router.create( |
| 2473 | user_id="user_123", toolkits=["github", "slack"], manage_connections=True |
| 2474 | ) |
| 2475 | |
| 2476 | assert session.session_id == "session_123" |
| 2477 | |
| 2478 | # Use authorize |
| 2479 | session.authorize("github") |
| 2480 | assert mock_client.tool_router.session.link.called |
| 2481 | |
| 2482 | # Use toolkits |
| 2483 | toolkits = session.toolkits() |
| 2484 | assert len(toolkits.items) == 2 |
| 2485 | |
| 2486 | # Use tools |
| 2487 | tools = session.tools() |
| 2488 | assert tools == ["tool1", "tool2"] |
| 2489 | |
| 2490 | def test_create_and_use_same_session(self, tool_router, mock_client): |
| 2491 | """Test creating a session and then attaching it.""" |
| 2492 | # Create session |
| 2493 | created_session = tool_router.create(user_id="user_123") |
| 2494 | created_session_id = created_session.session_id |
| 2495 | |
| 2496 | # Setup retrieve to return the same session |
| 2497 | mock_client.tool_router.session.retrieve.return_value = ( |
| 2498 | mock_client.tool_router.session.create.return_value |
| 2499 | ) |
| 2500 | |
| 2501 | # Use the session |
| 2502 | retrieved_session = tool_router.use(session_id=created_session_id) |
| 2503 | |
| 2504 | assert created_session.session_id == retrieved_session.session_id |
| 2505 | assert created_session.mcp.url == retrieved_session.mcp.url |
| 2506 | |
| 2507 | |
| 2508 | MCP_SAME_ORIGIN_URL = ( |
| 2509 | "https://backend.composio.dev/api/v3/tool_router/session/session_123/mcp" |
| 2510 | ) |
| 2511 | |
| 2512 | |
| 2513 | def _session_json(mcp_url: str) -> t.Dict[str, t.Any]: |
| 2514 | return { |
| 2515 | "session_id": "session_123", |
| 2516 | "mcp": {"type": "http", "url": mcp_url}, |
| 2517 | "config": { |
| 2518 | "user_id": "user_123", |
| 2519 | "instant": { |
| 2520 | "return_instant_charge": True, |
| 2521 | "return_prices_in_search": True, |
| 2522 | }, |
| 2523 | "execute": {}, |
| 2524 | "search": {}, |
| 2525 | "preload": {"tools": []}, |
| 2526 | }, |
| 2527 | "config_version": 3, |
| 2528 | "warnings": [], |
| 2529 | } |
| 2530 | |
| 2531 | |
| 2532 | def _search_json() -> t.Dict[str, t.Any]: |
| 2533 | return { |
| 2534 | "success": True, |
| 2535 | "error": None, |
| 2536 | "results": [], |
| 2537 | "tool_schemas": {}, |
| 2538 | "toolkit_connection_statuses": [ |
| 2539 | { |
| 2540 | "toolkit": "exa", |
| 2541 | "description": "Search", |
| 2542 | "has_active_connection": True, |
| 2543 | "status_message": "Instant account available", |
| 2544 | "instant_account": { |
| 2545 | "allowed_tool_slugs": ["EXA_SEARCH"], |
| 2546 | "prices": {"EXA_SEARCH": {"description": "$0.01 per call"}}, |
| 2547 | }, |
| 2548 | } |
| 2549 | ], |
| 2550 | "next_steps_guidance": [], |
| 2551 | "session": {"id": "session_123", "generate_id": False, "instructions": ""}, |
| 2552 | "time_info": { |
| 2553 | "current_time_utc": "2026-09-29T12:00:00Z", |
| 2554 | "current_time_utc_epoch_seconds": 1790683200, |
| 2555 | "message": "UTC", |
| 2556 | }, |
| 2557 | } |
| 2558 | |
| 2559 | |
| 2560 | class TestInstantContractTransport: |
| 2561 | """Exercise new wire fields through the pinned generated client.""" |
| 2562 | |
| 2563 | @pytest.mark.parametrize( |
| 2564 | "policy", |
| 2565 | [ |
| 2566 | False, |
| 2567 | {}, |
| 2568 | {"return_instant_charge": True}, |
| 2569 | {"return_prices_in_search": True}, |
| 2570 | None, |
| 2571 | ], |
| 2572 | ) |
| 2573 | def test_create_and_patch_send_new_policy(self, policy): |
| 2574 | client, requests = _transport_client( |
| 2575 | auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev" |
| 2576 | ) |
| 2577 | router = ToolRouter(client=client, provider=MagicMock()) |
| 2578 | session = router.create(user_id="user_123", instant=policy) |
| 2579 | body = json.loads(requests[0].content) |
| 2580 | if policy is None: |
| 2581 | assert "instant" not in body |
| 2582 | else: |
| 2583 | assert body["instant"] == policy |
| 2584 | assert not isinstance(session.config.instant, bool) |
| 2585 | assert session.config.instant.return_instant_charge is True |
| 2586 | assert session.config.instant.return_prices_in_search is True |
| 2587 | |
| 2588 | if policy is None: |
| 2589 | session.update(expected_config_version=3) |
| 2590 | else: |
| 2591 | session.update(instant=policy, expected_config_version=3) |
| 2592 | body = json.loads(requests[-1].content) |
| 2593 | assert body["expected_config_version"] == 3 |
| 2594 | if policy is None: |
| 2595 | assert "instant" not in body |
| 2596 | else: |
| 2597 | assert body["instant"] == policy |
| 2598 | assert not isinstance(session.config.instant, bool) |
| 2599 | assert session.config.instant.return_instant_charge is True |
| 2600 | assert session.config.instant.return_prices_in_search is True |
| 2601 | |
| 2602 | attached = router.use(session_id="session_123") |
| 2603 | assert not isinstance(attached.config.instant, bool) |
| 2604 | assert attached.config.instant.return_instant_charge is True |
| 2605 | |
| 2606 | def test_execute_selector_charge_and_search_coverage(self): |
| 2607 | requests: t.List[httpx.Request] = [] |
| 2608 | charge = {"amount": "0.012", "currency": "USD", "charged_by": "composio"} |
| 2609 | |
| 2610 | def handler(request): |
| 2611 | requests.append(request) |
| 2612 | if request.url.path.endswith("/execute"): |
| 2613 | return httpx.Response( |
| 2614 | 200, |
| 2615 | json={ |
| 2616 | "result_type": "completed", |
| 2617 | "data": {}, |
| 2618 | "error": None, |
| 2619 | "log_id": "log_123", |
| 2620 | "instant_charge": charge, |
| 2621 | }, |
| 2622 | ) |
| 2623 | if request.url.path.endswith("/search"): |
| 2624 | return httpx.Response(200, json=_search_json()) |
| 2625 | return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL)) |
| 2626 | |
| 2627 | client = HttpClient( |
| 2628 | provider="test", |
| 2629 | auth=ProjectAuth("ak_test"), |
| 2630 | base_url="https://backend.composio.dev", |
| 2631 | http_client=httpx.Client(transport=httpx.MockTransport(handler)), |
| 2632 | ) |
| 2633 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 2634 | user_id="user_123" |
| 2635 | ) |
| 2636 | result = session.execute("EXA_SEARCH", arguments={}, account="instant_account") |
| 2637 | assert json.loads(requests[-1].content)["account"] == "instant_account" |
| 2638 | assert result.instant_charge is not None |
| 2639 | assert result.instant_charge.amount == "0.012" |
| 2640 | assert result.instant_charge.model_dump() == charge |
| 2641 | status = session.search(query="search").toolkit_connection_statuses[0] |
| 2642 | assert status.instant_account is not None |
| 2643 | assert status.instant_account.allowed_tool_slugs == ["EXA_SEARCH"] |
| 2644 | assert status.instant_account.prices is not None |
| 2645 | assert status.instant_account.prices["EXA_SEARCH"].description == ( |
| 2646 | "$0.01 per call" |
| 2647 | ) |
| 2648 | assert "hosted_account" not in status.model_dump() |
| 2649 | |
| 2650 | def test_search_keeps_lenient_generated_response(self): |
| 2651 | payload = _search_json() |
| 2652 | payload["toolkit_connection_statuses"][0]["account_type"] = "INSTANT" |
| 2653 | del payload["time_info"] |
| 2654 | |
| 2655 | def handler(request): |
| 2656 | if request.url.path.endswith("/search"): |
| 2657 | return httpx.Response(200, json=payload) |
| 2658 | return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL)) |
| 2659 | |
| 2660 | client = HttpClient( |
| 2661 | provider="test", |
| 2662 | auth=ProjectAuth("ak_test"), |
| 2663 | base_url="https://backend.composio.dev", |
| 2664 | http_client=httpx.Client(transport=httpx.MockTransport(handler)), |
| 2665 | ) |
| 2666 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 2667 | user_id="user_123" |
| 2668 | ) |
| 2669 | result = session.search(query="search") |
| 2670 | |
| 2671 | assert isinstance(result, SessionSearchResponse) |
| 2672 | status = result.toolkit_connection_statuses[0] |
| 2673 | assert status.account_type == "INSTANT" |
| 2674 | assert status.instant_account is not None |
| 2675 | assert status.instant_account.allowed_tool_slugs == ["EXA_SEARCH"] |
| 2676 | assert result.to_dict() == payload |
| 2677 | |
| 2678 | |
| 2679 | _INPUT_REQUIRED_JSON: t.Dict[str, t.Any] = { |
| 2680 | "result_type": "input_required", |
| 2681 | "input_requests": { |
| 2682 | "approval_1": { |
| 2683 | "type": "elicitation", |
| 2684 | "mode": "form", |
| 2685 | "message": "Allow GMAIL_SEND_EMAIL to send this email?", |
| 2686 | "requested_schema": { |
| 2687 | "type": "object", |
| 2688 | "properties": {"approved": {"type": "boolean"}}, |
| 2689 | "required": ["approved"], |
| 2690 | }, |
| 2691 | } |
| 2692 | }, |
| 2693 | "request_state": "opaque-state-token", |
| 2694 | } |
| 2695 | |
| 2696 | _PROXY_PARAMS: t.Dict[str, t.Any] = { |
| 2697 | "toolkit": "github", |
| 2698 | "endpoint": "https://api.github.com/user/repos?token=secret", |
| 2699 | "method": "POST", |
| 2700 | "body": {"name": "repo"}, |
| 2701 | } |
| 2702 | |
| 2703 | |
| 2704 | def _answering_client( |
| 2705 | body: t.Dict[str, t.Any], |
| 2706 | ) -> t.Tuple[HttpClient, t.List[httpx.Request]]: |
| 2707 | """A real client whose execute and proxy calls are answered with ``body``.""" |
| 2708 | requests: t.List[httpx.Request] = [] |
| 2709 | |
| 2710 | def handler(request: httpx.Request) -> httpx.Response: |
| 2711 | if request.url.path.endswith(("/execute", "/execute_meta", "/proxy_execute")): |
| 2712 | requests.append(request) |
| 2713 | return httpx.Response(200, json=body) |
| 2714 | return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL)) |
| 2715 | |
| 2716 | client = HttpClient( |
| 2717 | provider="test", |
| 2718 | auth=ProjectAuth("ak_test"), |
| 2719 | base_url="https://backend.composio.dev", |
| 2720 | http_client=httpx.Client(transport=httpx.MockTransport(handler)), |
| 2721 | ) |
| 2722 | return client, requests |
| 2723 | |
| 2724 | |
| 2725 | def _created_session(client: HttpClient) -> ToolRouterSession: |
| 2726 | return ToolRouter(client=client, provider=MagicMock()).create(user_id="user_123") |
| 2727 | |
| 2728 | |
| 2729 | _APPROVAL_ANSWERS: t.Dict[str, t.Any] = { |
| 2730 | "approval_1": {"action": "accept", "content": {"decision": "approve"}}, |
| 2731 | } |
| 2732 | |
| 2733 | _COMPLETED_JSON: t.Dict[str, t.Any] = { |
| 2734 | "result_type": "completed", |
| 2735 | "data": {"id": "msg_1"}, |
| 2736 | "error": None, |
| 2737 | "log_id": "log_1", |
| 2738 | } |
| 2739 | |
| 2740 | |
| 2741 | class TestAnsweringInputRequired: |
| 2742 | """The answers to an ``input_required`` call travel on the repeated call |
| 2743 | as ``input_responses``, with the ``request_state`` it returned.""" |
| 2744 | |
| 2745 | @pytest.mark.parametrize( |
| 2746 | "run", |
| 2747 | [ |
| 2748 | pytest.param( |
| 2749 | lambda session: session.execute( |
| 2750 | "GMAIL_SEND_EMAIL", |
| 2751 | arguments={"to": "test@test.com"}, |
| 2752 | input_responses=_APPROVAL_ANSWERS, |
| 2753 | request_state="opaque-state-token", |
| 2754 | ), |
| 2755 | id="session.execute", |
| 2756 | ), |
| 2757 | pytest.param( |
| 2758 | lambda session: session.execute_meta( |
| 2759 | "COMPOSIO_MULTI_EXECUTE_TOOL", |
| 2760 | arguments={"tools": []}, |
| 2761 | input_responses=_APPROVAL_ANSWERS, |
| 2762 | request_state="opaque-state-token", |
| 2763 | ), |
| 2764 | id="session.execute_meta", |
| 2765 | ), |
| 2766 | ], |
| 2767 | ) |
| 2768 | def test_sends_the_answers_and_the_request_state(self, run): |
| 2769 | client, requests = _answering_client(_COMPLETED_JSON) |
| 2770 | |
| 2771 | run(_created_session(client)) |
| 2772 | |
| 2773 | body = json.loads(requests[0].content) |
| 2774 | assert body["input_responses"] == _APPROVAL_ANSWERS |
| 2775 | assert body["request_state"] == "opaque-state-token" |
| 2776 | |
| 2777 | def test_sends_neither_field_without_answers(self): |
| 2778 | client, requests = _answering_client(_COMPLETED_JSON) |
| 2779 | |
| 2780 | _created_session(client).execute("GMAIL_SEND_EMAIL") |
| 2781 | |
| 2782 | body = json.loads(requests[0].content) |
| 2783 | assert "input_responses" not in body |
| 2784 | assert "request_state" not in body |
| 2785 | |
| 2786 | |
| 2787 | class TestApprovalRules: |
| 2788 | """``require_approval`` lists and the no-elicitation fallback reach the |
| 2789 | API next to the filters they belong to.""" |
| 2790 | |
| 2791 | def test_create_sends_approval_lists_and_fallback(self): |
| 2792 | client, requests = _transport_client( |
| 2793 | auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev" |
| 2794 | ) |
| 2795 | |
| 2796 | ToolRouter(client=client, provider=MagicMock()).create( |
| 2797 | user_id="user_123", |
| 2798 | toolkits={"enable": ["gmail", "github"], "require_approval": ["github"]}, |
| 2799 | tools={ |
| 2800 | "gmail": {"require_approval": ["GMAIL_SEND_EMAIL"]}, |
| 2801 | "notion": { |
| 2802 | "enable": ["NOTION_CREATE_PAGE"], |
| 2803 | "require_approval": ["NOTION_CREATE_PAGE"], |
| 2804 | }, |
| 2805 | "slack": {"tags": {"require_approval": ["destructiveHint"]}}, |
| 2806 | }, |
| 2807 | tags={ |
| 2808 | "disable": ["openWorldHint"], |
| 2809 | "require_approval": ["destructiveHint"], |
| 2810 | }, |
| 2811 | experimental={"no_elicitation_support_fallback": "allow"}, |
| 2812 | ) |
| 2813 | |
| 2814 | body = json.loads(requests[0].content) |
| 2815 | assert body["toolkits"] == { |
| 2816 | "enable": ["gmail", "github"], |
| 2817 | "require_approval": ["github"], |
| 2818 | } |
| 2819 | assert body["tools"] == { |
| 2820 | "gmail": {"require_approval": ["GMAIL_SEND_EMAIL"]}, |
| 2821 | "notion": { |
| 2822 | "enable": ["NOTION_CREATE_PAGE"], |
| 2823 | "require_approval": ["NOTION_CREATE_PAGE"], |
| 2824 | }, |
| 2825 | "slack": {"tags": {"require_approval": ["destructiveHint"]}}, |
| 2826 | } |
| 2827 | assert body["tags"] == { |
| 2828 | "disable": ["openWorldHint"], |
| 2829 | "require_approval": ["destructiveHint"], |
| 2830 | } |
| 2831 | assert body["experimental"] == {"no_elicitation_support_fallback": "allow"} |
| 2832 | |
| 2833 | def test_update_sends_approval_lists_and_fallback(self): |
| 2834 | client, requests = _transport_client( |
| 2835 | auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev" |
| 2836 | ) |
| 2837 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 2838 | user_id="user_123" |
| 2839 | ) |
| 2840 | |
| 2841 | session.update( |
| 2842 | toolkits={"require_approval": ["gmail"]}, |
| 2843 | experimental={"no_elicitation_support_fallback": "deny"}, |
| 2844 | ) |
| 2845 | |
| 2846 | body = json.loads(requests[-1].content) |
| 2847 | assert body["toolkits"] == {"require_approval": ["gmail"]} |
| 2848 | assert body["experimental"] == {"no_elicitation_support_fallback": "deny"} |
| 2849 | |
| 2850 | |
| 2851 | class TestExecutionRequiresUserInput: |
| 2852 | """``result_type: "input_required"`` carries no data, log ID or HTTP status, |
| 2853 | so every execution path raises it instead of returning it as a result. |
| 2854 | |
| 2855 | The cases run a real client over a stub transport so they cover the wire |
| 2856 | shape the generated client hands to the SDK. |
| 2857 | """ |
| 2858 | |
| 2859 | @pytest.mark.parametrize( |
| 2860 | ("run", "subject"), |
| 2861 | [ |
| 2862 | pytest.param( |
| 2863 | lambda client: _created_session(client).execute( |
| 2864 | "GMAIL_SEND_EMAIL", arguments={"to": "test@test.com"} |
| 2865 | ), |
| 2866 | "Tool GMAIL_SEND_EMAIL", |
| 2867 | id="session.execute", |
| 2868 | ), |
| 2869 | pytest.param( |
| 2870 | lambda client: _created_session(client).execute_meta( |
| 2871 | "COMPOSIO_MULTI_EXECUTE_TOOL", |
| 2872 | arguments={"tools": [{"tool_slug": "GMAIL_SEND_EMAIL"}]}, |
| 2873 | ), |
| 2874 | "Tool COMPOSIO_MULTI_EXECUTE_TOOL", |
| 2875 | id="session.execute_meta", |
| 2876 | ), |
| 2877 | pytest.param( |
| 2878 | lambda client: _created_session(client).proxy_execute(**_PROXY_PARAMS), |
| 2879 | "POST proxy call for toolkit github", |
| 2880 | id="session.proxy_execute", |
| 2881 | ), |
| 2882 | pytest.param( |
| 2883 | lambda client: SessionContextImpl( |
| 2884 | client, "user_123", "session_123" |
| 2885 | ).execute("GMAIL_SEND_EMAIL", {"to": "test@test.com"}), |
| 2886 | "Tool GMAIL_SEND_EMAIL", |
| 2887 | id="custom tool context execute", |
| 2888 | ), |
| 2889 | pytest.param( |
| 2890 | lambda client: SessionContextImpl( |
| 2891 | client, "user_123", "session_123" |
| 2892 | ).proxy_execute(**_PROXY_PARAMS), |
| 2893 | "POST proxy call for toolkit github", |
| 2894 | id="custom tool context proxy_execute", |
| 2895 | ), |
| 2896 | pytest.param( |
| 2897 | lambda client: _session_tool_execute_fn(client)( |
| 2898 | "GMAIL_SEND_EMAIL", {"to": "test@test.com"} |
| 2899 | ), |
| 2900 | "Tool GMAIL_SEND_EMAIL", |
| 2901 | id="provider-wrapped session tool", |
| 2902 | ), |
| 2903 | ], |
| 2904 | ) |
| 2905 | def test_raises_tool_input_required_error(self, run, subject): |
| 2906 | client, requests = _answering_client(_INPUT_REQUIRED_JSON) |
| 2907 | |
| 2908 | with pytest.raises(ToolInputRequiredError) as raised: |
| 2909 | run(client) |
| 2910 | |
| 2911 | error = raised.value |
| 2912 | assert f"{subject} requires user input" in error.message |
| 2913 | assert "request_state" in error.message |
| 2914 | # The opaque state and the proxied URL stay out of the message. |
| 2915 | assert "opaque-state-token" not in error.message |
| 2916 | assert "secret" not in error.message |
| 2917 | assert error.request_state == "opaque-state-token" |
| 2918 | assert error.input_requests == { |
| 2919 | "approval_1": { |
| 2920 | "type": "elicitation", |
| 2921 | "mode": "form", |
| 2922 | "message": "Allow GMAIL_SEND_EMAIL to send this email?", |
| 2923 | "requested_schema": { |
| 2924 | "type": "object", |
| 2925 | "properties": {"approved": {"type": "boolean"}}, |
| 2926 | "required": ["approved"], |
| 2927 | }, |
| 2928 | } |
| 2929 | } |
| 2930 | # The call is not repeated: answering needs the user. |
| 2931 | assert len(requests) == 1 |
| 2932 | |
| 2933 | def test_request_state_stays_out_of_str_repr_and_args(self): |
| 2934 | """``request_state`` is continuation state: readable as an attribute |
| 2935 | for the code that answers the request, absent from what an exception |
| 2936 | is routinely logged as.""" |
| 2937 | client, _ = _answering_client(_INPUT_REQUIRED_JSON) |
| 2938 | |
| 2939 | with pytest.raises(ToolInputRequiredError) as raised: |
| 2940 | _created_session(client).execute("GMAIL_SEND_EMAIL") |
| 2941 | |
| 2942 | error = raised.value |
| 2943 | assert error.request_state == "opaque-state-token" |
| 2944 | assert "opaque-state-token" not in str(error) |
| 2945 | assert "opaque-state-token" not in repr(error) |
| 2946 | assert "opaque-state-token" not in repr(error.args) |
| 2947 | assert error.args == (error.message,) |
| 2948 | formatted = "".join( |
| 2949 | traceback.format_exception(type(error), error, error.__traceback__) |
| 2950 | ) |
| 2951 | assert "ToolInputRequiredError" in formatted |
| 2952 | assert "opaque-state-token" not in formatted |
| 2953 | |
| 2954 | def test_request_state_is_none_when_the_api_returns_none(self): |
| 2955 | body = {k: v for k, v in _INPUT_REQUIRED_JSON.items() if k != "request_state"} |
| 2956 | client, _ = _answering_client(body) |
| 2957 | |
| 2958 | with pytest.raises(ToolInputRequiredError) as raised: |
| 2959 | _created_session(client).execute("GMAIL_SEND_EMAIL") |
| 2960 | |
| 2961 | assert raised.value.request_state is None |
| 2962 | |
| 2963 | @pytest.mark.parametrize( |
| 2964 | ("result_type", "error"), |
| 2965 | [("completed", None), ("failed", "Connection not found")], |
| 2966 | ) |
| 2967 | def test_execute_still_returns_a_result(self, result_type, error): |
| 2968 | client, _ = _answering_client( |
| 2969 | { |
| 2970 | "result_type": result_type, |
| 2971 | "data": {"id": "msg_1"}, |
| 2972 | "error": error, |
| 2973 | "log_id": "log_1", |
| 2974 | } |
| 2975 | ) |
| 2976 | |
| 2977 | result = _created_session(client).execute("GMAIL_SEND_EMAIL") |
| 2978 | |
| 2979 | assert result.result_type == result_type |
| 2980 | assert result.data == {"id": "msg_1"} |
| 2981 | assert result.error == error |
| 2982 | assert result.log_id == "log_1" |
| 2983 | |
| 2984 | def test_proxy_execute_still_returns_a_completed_result(self): |
| 2985 | client, _ = _answering_client( |
| 2986 | { |
| 2987 | "result_type": "completed", |
| 2988 | "status": 201, |
| 2989 | "data": {"id": 1}, |
| 2990 | "headers": {"x-request-id": "req_1"}, |
| 2991 | } |
| 2992 | ) |
| 2993 | |
| 2994 | result = _created_session(client).proxy_execute(**_PROXY_PARAMS) |
| 2995 | |
| 2996 | assert result == { |
| 2997 | "result_type": "completed", |
| 2998 | "status": 201, |
| 2999 | "data": {"id": 1}, |
| 3000 | "headers": {"x-request-id": "req_1"}, |
| 3001 | } |
| 3002 | |
| 3003 | |
| 3004 | _BLOCKED_CALL_JSON: t.Dict[str, t.Any] = { |
| 3005 | "result_type": "blocked", |
| 3006 | "reason": {"type": "request_blocked", "hook_id": "no_external_email"}, |
| 3007 | "message": "Blocked by session policy: No external email", |
| 3008 | "log_id": "", |
| 3009 | "hook_results": [ |
| 3010 | {"id": "no_external_email", "status": "evaluated", "outcome": "block"} |
| 3011 | ], |
| 3012 | } |
| 3013 | |
| 3014 | |
| 3015 | class TestSessionHooks: |
| 3016 | """A session hook can block a call before it runs, or block its result |
| 3017 | before the agent sees it. The API answers ``result_type: "blocked"``, |
| 3018 | which has no data and no HTTP response. |
| 3019 | |
| 3020 | The cases run a real client over a stub transport so they cover the wire |
| 3021 | shape the generated client hands to the SDK. |
| 3022 | """ |
| 3023 | |
| 3024 | _HOOKS: t.List[t.Any] = [ |
| 3025 | { |
| 3026 | "type": "before_execute", |
| 3027 | "id": "no_external_email", |
| 3028 | "name": "No external email", |
| 3029 | "applies_to": {"toolkits": ["gmail"]}, |
| 3030 | "handler": { |
| 3031 | "type": "condition_check", |
| 3032 | "condition": "Sending email to anyone outside example.org", |
| 3033 | "action": "block", |
| 3034 | }, |
| 3035 | }, |
| 3036 | { |
| 3037 | "type": "after_execute", |
| 3038 | "id": "block_injection", |
| 3039 | "applies_to": "all", |
| 3040 | "handler": {"type": "prompt_injection_check", "action": "block"}, |
| 3041 | }, |
| 3042 | ] |
| 3043 | |
| 3044 | def test_create_sends_hooks(self, tool_router, mock_client): |
| 3045 | tool_router.create(user_id="user_123", hooks=self._HOOKS) |
| 3046 | |
| 3047 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 3048 | assert kwargs["hooks"] == self._HOOKS |
| 3049 | |
| 3050 | def test_create_omits_hooks_by_default(self, tool_router, mock_client): |
| 3051 | tool_router.create(user_id="user_123") |
| 3052 | |
| 3053 | kwargs = mock_client.tool_router.session.create.call_args.kwargs |
| 3054 | assert "hooks" not in kwargs |
| 3055 | |
| 3056 | @pytest.mark.parametrize( |
| 3057 | ("hooks", "expected"), |
| 3058 | [ |
| 3059 | pytest.param(_HOOKS, _HOOKS, id="replace"), |
| 3060 | pytest.param(None, None, id="remove"), |
| 3061 | ], |
| 3062 | ) |
| 3063 | def test_update_sends_hooks(self, hooks, expected): |
| 3064 | client, requests = _transport_client( |
| 3065 | auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev" |
| 3066 | ) |
| 3067 | session = _created_session(client) |
| 3068 | |
| 3069 | session.update(hooks=hooks) |
| 3070 | |
| 3071 | body = json.loads(requests[-1].content) |
| 3072 | assert body["hooks"] == expected |
| 3073 | |
| 3074 | @pytest.mark.parametrize( |
| 3075 | "hooks", |
| 3076 | [ |
| 3077 | pytest.param(_HOOKS, id="replace"), |
| 3078 | pytest.param(None, id="remove"), |
| 3079 | ], |
| 3080 | ) |
| 3081 | def test_update_rejects_hooks_with_session_config_id(self, hooks): |
| 3082 | client, requests = _transport_client( |
| 3083 | auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev" |
| 3084 | ) |
| 3085 | session = _created_session(client) |
| 3086 | requests.clear() |
| 3087 | |
| 3088 | with pytest.raises(InvalidParams): |
| 3089 | session.update(hooks=hooks, experimental={"session_config_id": "sc_1"}) |
| 3090 | |
| 3091 | assert requests == [] |
| 3092 | |
| 3093 | def test_create_rejects_hooks_with_session_config_id( |
| 3094 | self, tool_router, mock_client |
| 3095 | ): |
| 3096 | with pytest.raises(InvalidParams): |
| 3097 | tool_router.create( |
| 3098 | user_id="user_123", |
| 3099 | hooks=self._HOOKS, |
| 3100 | experimental=t.cast(t.Any, {"session_config_id": "sc_1"}), |
| 3101 | ) |
| 3102 | |
| 3103 | mock_client.tool_router.session.create.assert_not_called() |
| 3104 | |
| 3105 | @pytest.mark.parametrize( |
| 3106 | "run", |
| 3107 | [ |
| 3108 | pytest.param( |
| 3109 | lambda client: _created_session(client).execute( |
| 3110 | "GMAIL_SEND_EMAIL", arguments={"to": "ceo@rival.com"} |
| 3111 | ), |
| 3112 | id="session.execute", |
| 3113 | ), |
| 3114 | pytest.param( |
| 3115 | lambda client: SessionContextImpl( |
| 3116 | client, "user_123", "session_123" |
| 3117 | ).execute("GMAIL_SEND_EMAIL", {"to": "ceo@rival.com"}), |
| 3118 | id="custom tool context execute", |
| 3119 | ), |
| 3120 | ], |
| 3121 | ) |
| 3122 | def test_execute_returns_a_blocked_result(self, run): |
| 3123 | client, _ = _answering_client(_BLOCKED_CALL_JSON) |
| 3124 | |
| 3125 | result = run(client) |
| 3126 | |
| 3127 | assert result.result_type == "blocked" |
| 3128 | assert result.data == {} |
| 3129 | assert result.error == "Blocked by session policy: No external email" |
| 3130 | assert result.log_id == "" |
| 3131 | assert result.block_reason == { |
| 3132 | "type": "request_blocked", |
| 3133 | "hook_id": "no_external_email", |
| 3134 | } |
| 3135 | assert result.hook_results == [ |
| 3136 | {"id": "no_external_email", "status": "evaluated", "outcome": "block"} |
| 3137 | ] |
| 3138 | assert ( |
| 3139 | ToolRouterSessionExecuteResponse.model_validate(result.model_dump()) |
| 3140 | == result |
| 3141 | ) |
| 3142 | |
| 3143 | @pytest.mark.parametrize( |
| 3144 | "body", |
| 3145 | [ |
| 3146 | pytest.param(_BLOCKED_CALL_JSON, id="blocked"), |
| 3147 | pytest.param( |
| 3148 | { |
| 3149 | "data": {"sent": True}, |
| 3150 | "error": None, |
| 3151 | "log_id": "log_1", |
| 3152 | "result_type": "completed", |
| 3153 | "hook_results": [ |
| 3154 | {"id": "block_injection", "status": "unavailable"} |
| 3155 | ], |
| 3156 | }, |
| 3157 | id="completed", |
| 3158 | ), |
| 3159 | ], |
| 3160 | ) |
| 3161 | def test_a_result_dumps_its_hook_results_as_the_dicts_it_holds(self, body): |
| 3162 | """The client types ``hook_results`` as models and the SDK's result |
| 3163 | holds them as its own dicts, so dumping it must not warn.""" |
| 3164 | client, _ = _answering_client(body) |
| 3165 | result = _created_session(client).execute( |
| 3166 | "GMAIL_SEND_EMAIL", arguments={"to": "ceo@rival.com"} |
| 3167 | ) |
| 3168 | |
| 3169 | with warnings.catch_warnings(): |
| 3170 | warnings.simplefilter("error") |
| 3171 | dumped = result.model_dump() |
| 3172 | |
| 3173 | assert dumped["hook_results"] == body["hook_results"] |
| 3174 | |
| 3175 | def test_blocked_call_reaches_the_agent_as_a_failed_call(self): |
| 3176 | """Every provider hands the agent ``data``, ``error`` and |
| 3177 | ``successful``, so this is what the agent sees in any framework.""" |
| 3178 | client, _ = _answering_client(_BLOCKED_CALL_JSON) |
| 3179 | |
| 3180 | result = _session_tool_execute_fn(client)( |
| 3181 | "GMAIL_SEND_EMAIL", {"to": "ceo@rival.com"} |
| 3182 | ) |
| 3183 | |
| 3184 | assert result["successful"] is False |
| 3185 | assert result["data"] == {} |
| 3186 | assert result["error"] == "Blocked by session policy: No external email" |
| 3187 | |
| 3188 | def test_blocked_response_keeps_its_charge_for_the_agent(self): |
| 3189 | """The tool ran before an ``after_execute`` hook blocked its result, so |
| 3190 | the provider result still reports the charge.""" |
| 3191 | client, _ = _answering_client( |
| 3192 | { |
| 3193 | **_BLOCKED_CALL_JSON, |
| 3194 | "reason": {"type": "response_blocked", "hook_id": "no_outside_data"}, |
| 3195 | "log_id": "log_456", |
| 3196 | "instant_charge": { |
| 3197 | "amount": "0.01", |
| 3198 | "currency": "USD", |
| 3199 | "charged_by": "composio", |
| 3200 | }, |
| 3201 | } |
| 3202 | ) |
| 3203 | |
| 3204 | result = _session_tool_execute_fn(client)("GMAIL_SEND_EMAIL", {}) |
| 3205 | |
| 3206 | assert result["successful"] is False |
| 3207 | assert result["instant_charge"] == { |
| 3208 | "amount": "0.01", |
| 3209 | "currency": "USD", |
| 3210 | "charged_by": "composio", |
| 3211 | } |
| 3212 | |
| 3213 | def test_unavailable_hook_does_not_block(self): |
| 3214 | """A hook that could not be evaluated is reported, and the call still |
| 3215 | returns its normal result.""" |
| 3216 | client, _ = _answering_client( |
| 3217 | { |
| 3218 | **_COMPLETED_JSON, |
| 3219 | "hook_results": [{"id": "block_injection", "status": "unavailable"}], |
| 3220 | } |
| 3221 | ) |
| 3222 | |
| 3223 | result = _created_session(client).execute("GMAIL_SEND_EMAIL", arguments={}) |
| 3224 | |
| 3225 | assert result.result_type == "completed" |
| 3226 | assert result.data == {"id": "msg_1"} |
| 3227 | assert result.hook_results == [ |
| 3228 | {"id": "block_injection", "status": "unavailable"} |
| 3229 | ] |
| 3230 | |
| 3231 | @pytest.mark.parametrize( |
| 3232 | "run", |
| 3233 | [ |
| 3234 | pytest.param( |
| 3235 | lambda client: _created_session(client).proxy_execute(**_PROXY_PARAMS), |
| 3236 | id="session.proxy_execute", |
| 3237 | ), |
| 3238 | pytest.param( |
| 3239 | lambda client: SessionContextImpl( |
| 3240 | client, "user_123", "session_123" |
| 3241 | ).proxy_execute(**_PROXY_PARAMS), |
| 3242 | id="custom tool context proxy_execute", |
| 3243 | ), |
| 3244 | ], |
| 3245 | ) |
| 3246 | def test_proxy_execute_returns_a_blocked_result(self, run): |
| 3247 | client, _ = _answering_client( |
| 3248 | {k: v for k, v in _BLOCKED_CALL_JSON.items() if k != "log_id"} |
| 3249 | ) |
| 3250 | |
| 3251 | assert run(client) == { |
| 3252 | "result_type": "blocked", |
| 3253 | "block_reason": {"type": "request_blocked", "hook_id": "no_external_email"}, |
| 3254 | "message": "Blocked by session policy: No external email", |
| 3255 | "hook_results": [ |
| 3256 | {"id": "no_external_email", "status": "evaluated", "outcome": "block"} |
| 3257 | ], |
| 3258 | } |
| 3259 | |
| 3260 | def test_proxy_execute_returns_the_hook_results_of_a_sent_request(self): |
| 3261 | client, _ = _answering_client( |
| 3262 | { |
| 3263 | "result_type": "completed", |
| 3264 | "status": 200, |
| 3265 | "data": {"id": 1}, |
| 3266 | "headers": {}, |
| 3267 | "hook_results": [ |
| 3268 | { |
| 3269 | "id": "no_external_email", |
| 3270 | "status": "evaluated", |
| 3271 | "outcome": "continue", |
| 3272 | }, |
| 3273 | {"id": "block_injection", "status": "unavailable"}, |
| 3274 | ], |
| 3275 | } |
| 3276 | ) |
| 3277 | |
| 3278 | result = _created_session(client).proxy_execute(**_PROXY_PARAMS) |
| 3279 | |
| 3280 | assert result["result_type"] == "completed" |
| 3281 | assert result.get("hook_results") == [ |
| 3282 | {"id": "no_external_email", "status": "evaluated", "outcome": "continue"}, |
| 3283 | {"id": "block_injection", "status": "unavailable"}, |
| 3284 | ] |
| 3285 | |
| 3286 | |
| 3287 | class _NoInput(BaseModel): |
| 3288 | pass |
| 3289 | |
| 3290 | |
| 3291 | def _custom_tool_calling(call: t.Callable[[t.Any], t.Any]) -> t.Any: |
| 3292 | """A custom tools map with one local tool whose body runs ``call(ctx)``.""" |
| 3293 | from composio.core.models.custom_tool import build_custom_tools_map |
| 3294 | |
| 3295 | @experimental_api.tool() |
| 3296 | def send_welcome_email(input: _NoInput, ctx: t.Any) -> t.Dict[str, t.Any]: |
| 3297 | """Sends the welcome email through a session helper.""" |
| 3298 | return {"sent": call(ctx)} |
| 3299 | |
| 3300 | return build_custom_tools_map([send_welcome_email]) |
| 3301 | |
| 3302 | |
| 3303 | def _session_with_custom_tools( |
| 3304 | client: HttpClient, custom_tools_map: t.Any |
| 3305 | ) -> ToolRouterSession: |
| 3306 | return ToolRouterSession( |
| 3307 | client=client, |
| 3308 | provider=MagicMock(), |
| 3309 | dangerously_allow_auto_upload_download_files=False, |
| 3310 | session_id="session_123", |
| 3311 | mcp=MagicMock(), |
| 3312 | experimental=MagicMock(), |
| 3313 | custom_tools_map=custom_tools_map, |
| 3314 | user_id="user_123", |
| 3315 | ) |
| 3316 | |
| 3317 | |
| 3318 | def _raise_boom(ctx: t.Any) -> t.Any: |
| 3319 | raise RuntimeError("boom") |
| 3320 | |
| 3321 | |
| 3322 | class TestCustomToolBodyRequiresUserInput: |
| 3323 | """A local custom tool reaches the API through ``ctx.execute()`` and |
| 3324 | ``ctx.proxy_execute()``. The wrapper that runs the tool turns whatever it |
| 3325 | raises into a failed result, which must not happen to an input request: the |
| 3326 | caller needs the questions and the request state, not a message. |
| 3327 | """ |
| 3328 | |
| 3329 | _BODIES = [ |
| 3330 | pytest.param( |
| 3331 | lambda ctx: ctx.execute("GMAIL_SEND_EMAIL", {"to": "test@test.com"}), |
| 3332 | "Tool GMAIL_SEND_EMAIL", |
| 3333 | id="ctx.execute", |
| 3334 | ), |
| 3335 | pytest.param( |
| 3336 | lambda ctx: ctx.proxy_execute(**_PROXY_PARAMS), |
| 3337 | "POST proxy call for toolkit github", |
| 3338 | id="ctx.proxy_execute", |
| 3339 | ), |
| 3340 | ] |
| 3341 | |
| 3342 | @pytest.mark.parametrize(("call", "subject"), _BODIES) |
| 3343 | def test_session_execute_of_a_custom_tool_raises(self, call, subject): |
| 3344 | client, requests = _answering_client(_INPUT_REQUIRED_JSON) |
| 3345 | session = _session_with_custom_tools(client, _custom_tool_calling(call)) |
| 3346 | |
| 3347 | with pytest.raises(ToolInputRequiredError) as raised: |
| 3348 | session.execute("SEND_WELCOME_EMAIL", arguments={}) |
| 3349 | |
| 3350 | error = raised.value |
| 3351 | assert f"{subject} requires user input" in error.message |
| 3352 | assert error.request_state == "opaque-state-token" |
| 3353 | assert list(error.input_requests) == ["approval_1"] |
| 3354 | assert len(requests) == 1 |
| 3355 | |
| 3356 | @pytest.mark.parametrize(("call", "subject"), _BODIES) |
| 3357 | def test_sibling_custom_tool_raises_through_ctx_execute(self, call, subject): |
| 3358 | client, _ = _answering_client(_INPUT_REQUIRED_JSON) |
| 3359 | context = SessionContextImpl( |
| 3360 | client, "user_123", "session_123", _custom_tool_calling(call) |
| 3361 | ) |
| 3362 | |
| 3363 | with pytest.raises(ToolInputRequiredError) as raised: |
| 3364 | context.execute("SEND_WELCOME_EMAIL", {}) |
| 3365 | |
| 3366 | assert raised.value.request_state == "opaque-state-token" |
| 3367 | |
| 3368 | def test_any_other_error_is_still_a_failed_result(self): |
| 3369 | client, _ = _answering_client(_INPUT_REQUIRED_JSON) |
| 3370 | session = _session_with_custom_tools(client, _custom_tool_calling(_raise_boom)) |
| 3371 | |
| 3372 | result = session.execute("SEND_WELCOME_EMAIL", arguments={}) |
| 3373 | |
| 3374 | assert result.error == "boom" |
| 3375 | assert result.result_type == "failed" |
| 3376 | |
| 3377 | |
| 3378 | class TestMixedMultiExecuteRequiresUserInput: |
| 3379 | """A ``COMPOSIO_MULTI_EXECUTE_TOOL`` batch that mixes local and remote |
| 3380 | tools turns a raised backend error into per-tool failures. An input request |
| 3381 | is not one: the caller needs the questions and the request state. |
| 3382 | """ |
| 3383 | |
| 3384 | def test_remote_half_input_required_raises(self): |
| 3385 | from composio.core.models.tools import Tools |
| 3386 | |
| 3387 | client, requests = _answering_client(_INPUT_REQUIRED_JSON) |
| 3388 | local_calls: t.List[bool] = [] |
| 3389 | session = _session_with_custom_tools( |
| 3390 | client, _custom_tool_calling(lambda ctx: local_calls.append(True)) |
| 3391 | ) |
| 3392 | tools = Tools( |
| 3393 | client=client, |
| 3394 | provider=MagicMock(), |
| 3395 | dangerously_allow_auto_upload_download_files=False, |
| 3396 | ) |
| 3397 | # Keep the (read) tool-schema lookup off the transport. |
| 3398 | tools._tool_schemas["COMPOSIO_MULTI_EXECUTE_TOOL"] = MagicMock() |
| 3399 | |
| 3400 | with pytest.raises(ToolInputRequiredError) as raised: |
| 3401 | session._route_multi_execute( |
| 3402 | { |
| 3403 | "tools": [ |
| 3404 | {"tool_slug": "SEND_WELCOME_EMAIL", "arguments": {}}, |
| 3405 | {"tool_slug": "GMAIL_SEND_EMAIL", "arguments": {}}, |
| 3406 | ] |
| 3407 | }, |
| 3408 | tools, |
| 3409 | ) |
| 3410 | |
| 3411 | error = raised.value |
| 3412 | assert "Tool COMPOSIO_MULTI_EXECUTE_TOOL requires user input" in error.message |
| 3413 | assert list(error.input_requests) == ["approval_1"] |
| 3414 | assert error.request_state == "opaque-state-token" |
| 3415 | # Only the remote half reached the API, once. |
| 3416 | assert len(requests) == 1 |
| 3417 | assert [ |
| 3418 | tool["tool_slug"] |
| 3419 | for tool in json.loads(requests[0].content)["arguments"]["tools"] |
| 3420 | ] == ["GMAIL_SEND_EMAIL"] |
| 3421 | # The local tool had already run; its result is discarded by the raise. |
| 3422 | assert local_calls == [True] |
| 3423 | |
| 3424 | |
| 3425 | _EXECUTED_ANSWERS = [ |
| 3426 | pytest.param("failed", None, False, id="failed with a null error"), |
| 3427 | pytest.param("failed", "", False, id="failed with an empty error"), |
| 3428 | pytest.param("failed", "Boom", False, id="failed with a message"), |
| 3429 | pytest.param("completed", None, True, id="completed"), |
| 3430 | ] |
| 3431 | |
| 3432 | |
| 3433 | def _executed_json(result_type: str, error: t.Optional[str]) -> t.Dict[str, t.Any]: |
| 3434 | return {"result_type": result_type, "data": {}, "error": error, "log_id": "log"} |
| 3435 | |
| 3436 | |
| 3437 | class TestSessionExecutionSuccess: |
| 3438 | """``result_type`` says whether a tool that ran succeeded. A failed |
| 3439 | execution can carry a ``None`` or empty ``error``, so success is read from |
| 3440 | ``result_type`` alone. |
| 3441 | """ |
| 3442 | |
| 3443 | @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS) |
| 3444 | def test_provider_wrapped_session_tool(self, result_type, error, successful): |
| 3445 | client, _ = _answering_client(_executed_json(result_type, error)) |
| 3446 | |
| 3447 | result = _session_tool_execute_fn(client)("GMAIL_SEND_EMAIL", {}) |
| 3448 | |
| 3449 | # The error is passed through as the API sent it. |
| 3450 | assert result == { |
| 3451 | "data": {}, |
| 3452 | "error": error, |
| 3453 | "successful": successful, |
| 3454 | "log_id": "log", |
| 3455 | "result_type": result_type, |
| 3456 | } |
| 3457 | |
| 3458 | @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS) |
| 3459 | def test_provider_tool_call_bound_to_a_session( |
| 3460 | self, result_type, error, successful |
| 3461 | ): |
| 3462 | from composio.core.provider._openai import OpenAIProvider |
| 3463 | |
| 3464 | client, _ = _answering_client(_executed_json(result_type, error)) |
| 3465 | |
| 3466 | result = OpenAIProvider().execute_tool_for_target( |
| 3467 | target=_created_session(client), slug="GMAIL_SEND_EMAIL", arguments={} |
| 3468 | ) |
| 3469 | |
| 3470 | assert result == { |
| 3471 | "data": {}, |
| 3472 | "error": error, |
| 3473 | "successful": successful, |
| 3474 | "log_id": "log", |
| 3475 | "result_type": result_type, |
| 3476 | } |
| 3477 | |
| 3478 | @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS) |
| 3479 | def test_session_execute_exposes_result_type(self, result_type, error, successful): |
| 3480 | client, _ = _answering_client(_executed_json(result_type, error)) |
| 3481 | |
| 3482 | result = _created_session(client).execute("GMAIL_SEND_EMAIL") |
| 3483 | |
| 3484 | assert result.result_type == result_type |
| 3485 | assert result.error == error |
| 3486 | |
| 3487 | @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS) |
| 3488 | def test_custom_tool_context_execute_exposes_result_type( |
| 3489 | self, result_type, error, successful |
| 3490 | ): |
| 3491 | client, _ = _answering_client(_executed_json(result_type, error)) |
| 3492 | |
| 3493 | result = SessionContextImpl(client, "user_123", "session_123").execute( |
| 3494 | "GMAIL_SEND_EMAIL", {} |
| 3495 | ) |
| 3496 | |
| 3497 | assert result.result_type == result_type |
| 3498 | assert result.error == error |
| 3499 | |
| 3500 | |
| 3501 | _INVALID_ANSWERS = [ |
| 3502 | pytest.param({"data": {}, "error": None, "log_id": "log"}, id="no result_type"), |
| 3503 | pytest.param( |
| 3504 | {"result_type": "deferred", "data": {}, "error": None, "log_id": "log"}, |
| 3505 | id="an unknown result_type", |
| 3506 | ), |
| 3507 | ] |
| 3508 | |
| 3509 | |
| 3510 | @pytest.mark.parametrize("body", _INVALID_ANSWERS) |
| 3511 | class TestSessionExecuteAnswerWithoutAKnownResultType: |
| 3512 | """Every session execute answer carries a ``result_type``. One without it, |
| 3513 | or with a value this SDK does not know, is not a result: reading it as a |
| 3514 | success or as a failure would be a guess, so each path raises instead. |
| 3515 | """ |
| 3516 | |
| 3517 | _MESSAGE = ( |
| 3518 | "Tool GMAIL_SEND_EMAIL returned an execute response without a known result_type" |
| 3519 | ) |
| 3520 | |
| 3521 | def test_provider_wrapped_session_tool_raises(self, body): |
| 3522 | client, requests = _answering_client(body) |
| 3523 | |
| 3524 | with pytest.raises(ValidationError, match=self._MESSAGE): |
| 3525 | _session_tool_execute_fn(client)("GMAIL_SEND_EMAIL", {}) |
| 3526 | |
| 3527 | assert len(requests) == 1 |
| 3528 | |
| 3529 | def test_provider_tool_call_bound_to_a_session_raises(self, body): |
| 3530 | from composio.core.provider._openai import OpenAIProvider |
| 3531 | |
| 3532 | client, _ = _answering_client(body) |
| 3533 | |
| 3534 | with pytest.raises(ValidationError, match=self._MESSAGE): |
| 3535 | OpenAIProvider().execute_tool_for_target( |
| 3536 | target=_created_session(client), slug="GMAIL_SEND_EMAIL", arguments={} |
| 3537 | ) |
| 3538 | |
| 3539 | def test_session_execute_raises(self, body): |
| 3540 | client, _ = _answering_client(body) |
| 3541 | |
| 3542 | with pytest.raises(ValidationError, match=self._MESSAGE): |
| 3543 | _created_session(client).execute("GMAIL_SEND_EMAIL") |
| 3544 | |
| 3545 | def test_custom_tool_context_execute_raises(self, body): |
| 3546 | client, _ = _answering_client(body) |
| 3547 | |
| 3548 | with pytest.raises(ValidationError, match=self._MESSAGE): |
| 3549 | SessionContextImpl(client, "user_123", "session_123").execute( |
| 3550 | "GMAIL_SEND_EMAIL", {} |
| 3551 | ) |
| 3552 | |
| 3553 | |
| 3554 | def _session_tool_execute_fn(client: HttpClient) -> t.Callable[..., t.Any]: |
| 3555 | """The execute function providers wrap session tools with.""" |
| 3556 | from composio.core.models.tools import Tools |
| 3557 | |
| 3558 | tools = Tools( |
| 3559 | client=client, |
| 3560 | provider=MagicMock(), |
| 3561 | dangerously_allow_auto_upload_download_files=False, |
| 3562 | ) |
| 3563 | # Keep the (read) tool-schema lookup off the transport. |
| 3564 | tools._tool_schemas["GMAIL_SEND_EMAIL"] = MagicMock() |
| 3565 | return tools._wrap_execute_tool_for_tool_router(session_id="session_123") |
| 3566 | |
| 3567 | |
| 3568 | def _transport_client( |
| 3569 | *, |
| 3570 | auth: Auth, |
| 3571 | base_url: str, |
| 3572 | scope: t.Optional[Scope] = None, |
| 3573 | default_headers: t.Optional[t.Dict[str, str]] = None, |
| 3574 | mcp_url: str = MCP_SAME_ORIGIN_URL, |
| 3575 | ) -> t.Tuple[HttpClient, t.List[httpx.Request]]: |
| 3576 | requests: t.List[httpx.Request] = [] |
| 3577 | |
| 3578 | def handler(request: httpx.Request) -> httpx.Response: |
| 3579 | requests.append(request) |
| 3580 | return httpx.Response(200, json=_session_json(mcp_url)) |
| 3581 | |
| 3582 | client = HttpClient( |
| 3583 | provider="test", |
| 3584 | auth=auth, |
| 3585 | scope=scope, |
| 3586 | base_url=base_url, |
| 3587 | default_headers=default_headers, |
| 3588 | http_client=httpx.Client(transport=httpx.MockTransport(handler)), |
| 3589 | ) |
| 3590 | return client, requests |
| 3591 | |
| 3592 | |
| 3593 | class TestMcpAuthContext: |
| 3594 | """The exported MCP headers match the effective session auth context.""" |
| 3595 | |
| 3596 | def test_project_key_session_exports_only_the_project_key(self): |
| 3597 | with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}): |
| 3598 | client, requests = _transport_client( |
| 3599 | auth=ProjectAuth("ak_project_key"), |
| 3600 | base_url="https://backend.composio.dev", |
| 3601 | default_headers={"x-request-id": "req-1"}, |
| 3602 | ) |
| 3603 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 3604 | user_id="user_123", mcp=True |
| 3605 | ) |
| 3606 | |
| 3607 | assert requests[0].headers["x-api-key"] == "ak_project_key" |
| 3608 | assert session.mcp.headers == {"x-api-key": "ak_project_key"} |
| 3609 | |
| 3610 | def test_user_key_option_session_exports_only_the_user_key(self): |
| 3611 | with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}): |
| 3612 | client, requests = _transport_client( |
| 3613 | auth=UserAuth("uak_user_key"), |
| 3614 | base_url="https://backend.composio.dev", |
| 3615 | default_headers={"x-request-id": "r"}, |
| 3616 | ) |
| 3617 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 3618 | user_id="user_123", mcp=True |
| 3619 | ) |
| 3620 | |
| 3621 | assert "x-api-key" not in requests[0].headers |
| 3622 | assert requests[0].headers["x-user-api-key"] == "uak_user_key" |
| 3623 | assert session.mcp.headers == {"x-user-api-key": "uak_user_key"} |
| 3624 | |
| 3625 | def test_user_key_header_session_exports_only_the_user_key(self): |
| 3626 | """Under ``NoAuth`` a caller-placed user key header is the credential.""" |
| 3627 | with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_foreign_env_key"}): |
| 3628 | client, requests = _transport_client( |
| 3629 | auth=NoAuth(), |
| 3630 | base_url="https://backend.composio.dev", |
| 3631 | default_headers={"x-user-api-key": "uak_user_key", "x-request-id": "r"}, |
| 3632 | ) |
| 3633 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 3634 | user_id="user_123", mcp=True |
| 3635 | ) |
| 3636 | |
| 3637 | assert "x-api-key" not in requests[0].headers |
| 3638 | assert requests[0].headers["x-user-api-key"] == "uak_user_key" |
| 3639 | assert session.mcp.headers == {"x-user-api-key": "uak_user_key"} |
| 3640 | |
| 3641 | def test_scope_headers_are_exported_with_the_user_key(self): |
| 3642 | client, requests = _transport_client( |
| 3643 | auth=UserAuth("uak_user_key"), |
| 3644 | scope=Scope(organization_id="org_nano_abc", project_id="proj_nano_xyz"), |
| 3645 | base_url="https://backend.composio.dev", |
| 3646 | default_headers={"x-request-id": "r"}, |
| 3647 | ) |
| 3648 | session = ToolRouter(client=client, provider=MagicMock()).use( |
| 3649 | "session_123", mcp=True |
| 3650 | ) |
| 3651 | |
| 3652 | assert requests[0].headers["x-org-id"] == "org_nano_abc" |
| 3653 | assert requests[0].headers["x-project-id"] == "proj_nano_xyz" |
| 3654 | assert session.mcp.headers == { |
| 3655 | "x-user-api-key": "uak_user_key", |
| 3656 | "x-org-id": "org_nano_abc", |
| 3657 | "x-project-id": "proj_nano_xyz", |
| 3658 | } |
| 3659 | |
| 3660 | def test_retrieve_preserves_the_user_key_after_environment_changes(self): |
| 3661 | with patch.dict(os.environ, {}, clear=True): |
| 3662 | client, requests = _transport_client( |
| 3663 | auth=NoAuth(), |
| 3664 | base_url="https://backend.composio.dev", |
| 3665 | default_headers={"X-User-Api-Key": "uak_user_key"}, |
| 3666 | ) |
| 3667 | with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_later_env_key"}): |
| 3668 | session = ToolRouter(client=client, provider=MagicMock()).use( |
| 3669 | "session_123", mcp=True |
| 3670 | ) |
| 3671 | |
| 3672 | assert "x-api-key" not in requests[0].headers |
| 3673 | assert session.mcp.headers == {"x-user-api-key": "uak_user_key"} |
| 3674 | |
| 3675 | def test_no_credential_exports_no_headers_without_reading_the_environment( |
| 3676 | self, tool_router, mock_client |
| 3677 | ): |
| 3678 | mock_client.sdk_auth = NoAuth() |
| 3679 | with patch.dict(os.environ, {"COMPOSIO_API_KEY": "ak_ambient"}): |
| 3680 | session = tool_router.create(user_id="user_123", mcp=True) |
| 3681 | |
| 3682 | assert session.mcp.headers == {} |
| 3683 | |
| 3684 | def test_cross_origin_mcp_url_raises_without_leaking_the_key( |
| 3685 | self, tool_router, mock_client |
| 3686 | ): |
| 3687 | response = mock_client.tool_router.session.create.return_value |
| 3688 | response.mcp.url = "https://mcp.example.com/session_123" |
| 3689 | |
| 3690 | with pytest.raises(MCPDestinationError) as excinfo: |
| 3691 | tool_router.create(user_id="user_123", mcp=True) |
| 3692 | |
| 3693 | message = str(excinfo.value) |
| 3694 | assert message == ( |
| 3695 | "The session MCP endpoint origin https://mcp.example.com does not match the API origin https://backend.composio.dev; the session credential was not attached" |
| 3696 | ) |
| 3697 | assert "test-api-key" not in message |
| 3698 | assert excinfo.value.mcp_origin == "https://mcp.example.com" |
| 3699 | assert excinfo.value.api_origin == "https://backend.composio.dev" |
| 3700 | |
| 3701 | def test_cross_origin_mcp_url_raises_on_use_when_mcp_is_requested( |
| 3702 | self, tool_router, mock_client |
| 3703 | ): |
| 3704 | response = mock_client.tool_router.session.retrieve.return_value |
| 3705 | response.mcp.url = "https://mcp.example.com/session_123" |
| 3706 | |
| 3707 | with pytest.raises(MCPDestinationError) as excinfo: |
| 3708 | tool_router.use("session_123", mcp=True) |
| 3709 | |
| 3710 | message = str(excinfo.value) |
| 3711 | assert message == ( |
| 3712 | "The session MCP endpoint origin https://mcp.example.com does not match the API origin https://backend.composio.dev; the session credential was not attached" |
| 3713 | ) |
| 3714 | assert "test-api-key" not in message |
| 3715 | |
| 3716 | def test_cross_origin_mcp_url_without_mcp_flag_exports_no_headers_and_warns( |
| 3717 | self, tool_router, mock_client, caplog |
| 3718 | ): |
| 3719 | for response in ( |
| 3720 | mock_client.tool_router.session.create.return_value, |
| 3721 | mock_client.tool_router.session.retrieve.return_value, |
| 3722 | ): |
| 3723 | response.mcp.url = "https://mcp.example.com/session_123" |
| 3724 | |
| 3725 | with caplog.at_level(logging.WARNING): |
| 3726 | created = tool_router.create(user_id="user_123") |
| 3727 | used = tool_router.use("session_123") |
| 3728 | |
| 3729 | assert created.mcp.url == "https://mcp.example.com/session_123" |
| 3730 | assert created.mcp.headers == {} |
| 3731 | assert used.mcp.headers == {} |
| 3732 | warnings = [r for r in caplog.records if r.levelno == logging.WARNING] |
| 3733 | assert len(warnings) == 2 |
| 3734 | message = warnings[0].getMessage() |
| 3735 | assert message == ( |
| 3736 | "The session MCP endpoint origin https://mcp.example.com does not match the API origin https://backend.composio.dev; the session credential was not attached" |
| 3737 | ". session.mcp.headers was left empty; pass mcp=True to make this an error" |
| 3738 | ) |
| 3739 | assert "test-api-key" not in caplog.text |
| 3740 | |
| 3741 | def test_opaque_origin_mcp_url_is_rejected_before_comparison( |
| 3742 | self, tool_router, mock_client, caplog |
| 3743 | ): |
| 3744 | response = mock_client.tool_router.session.create.return_value |
| 3745 | response.mcp.url = "data:text/plain,session_123" |
| 3746 | |
| 3747 | with pytest.raises(MCPDestinationError) as excinfo: |
| 3748 | tool_router.create(user_id="user_123", mcp=True) |
| 3749 | assert str(excinfo.value) == "The MCP URL has an opaque origin" |
| 3750 | assert excinfo.value.mcp_origin == "" |
| 3751 | |
| 3752 | with caplog.at_level(logging.WARNING): |
| 3753 | session = tool_router.create(user_id="user_123") |
| 3754 | assert session.mcp.headers == {} |
| 3755 | assert "The MCP URL has an opaque origin" in caplog.text |
| 3756 | assert "test-api-key" not in caplog.text |
| 3757 | |
| 3758 | def test_user_key_default_header_beside_a_project_key_is_refused(self): |
| 3759 | """A second credential next to ``auth`` cannot be configured at all, so |
| 3760 | the request and the MCP export can never disagree about it.""" |
| 3761 | with pytest.raises(ClientComposioError, match="`x-user-api-key`"): |
| 3762 | _transport_client( |
| 3763 | auth=ProjectAuth("ak_project_key"), |
| 3764 | base_url="https://backend.composio.dev", |
| 3765 | default_headers={"x-user-api-key": "uak_header_key"}, |
| 3766 | ) |
| 3767 | |
| 3768 | def test_project_key_beside_a_user_key_exports_the_project_key(self): |
| 3769 | client, requests = _transport_client( |
| 3770 | auth=AutoAuth(project="ak_project_key", user="uak_user_key"), |
| 3771 | base_url="https://backend.composio.dev", |
| 3772 | ) |
| 3773 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 3774 | user_id="user_123", mcp=True |
| 3775 | ) |
| 3776 | |
| 3777 | assert requests[0].headers["x-api-key"] == "ak_project_key" |
| 3778 | assert "x-user-api-key" not in requests[0].headers |
| 3779 | assert session.mcp.headers == {"x-api-key": "ak_project_key"} |
| 3780 | |
| 3781 | def test_scope_without_an_organization_exports_only_the_project_id(self): |
| 3782 | client, requests = _transport_client( |
| 3783 | auth=UserAuth("uak_user_key"), |
| 3784 | scope=Scope(project_id="proj_nano_xyz"), |
| 3785 | base_url="https://backend.composio.dev", |
| 3786 | ) |
| 3787 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 3788 | user_id="user_123", mcp=True |
| 3789 | ) |
| 3790 | |
| 3791 | assert "x-org-id" not in requests[0].headers |
| 3792 | assert requests[0].headers["x-project-id"] == "proj_nano_xyz" |
| 3793 | assert session.mcp.headers == { |
| 3794 | "x-user-api-key": "uak_user_key", |
| 3795 | "x-project-id": "proj_nano_xyz", |
| 3796 | } |
| 3797 | |
| 3798 | def test_invalid_port_in_mcp_url_raises_the_typed_error(self): |
| 3799 | client, _ = _transport_client( |
| 3800 | auth=ProjectAuth("ak_project_key"), |
| 3801 | base_url="https://backend.composio.dev", |
| 3802 | mcp_url="https://backend.composio.dev:bad/mcp", |
| 3803 | ) |
| 3804 | with pytest.raises(MCPDestinationError) as excinfo: |
| 3805 | ToolRouter(client=client, provider=MagicMock()).create( |
| 3806 | user_id="user_123", mcp=True |
| 3807 | ) |
| 3808 | |
| 3809 | assert str(excinfo.value) == "The MCP URL is not a valid absolute URL" |
| 3810 | |
| 3811 | def test_malformed_mcp_url_is_not_echoed_in_the_error(self): |
| 3812 | client, _ = _transport_client( |
| 3813 | auth=ProjectAuth("ak_project_key"), |
| 3814 | base_url="https://backend.composio.dev", |
| 3815 | mcp_url="not-a-url?token=secret_value", |
| 3816 | ) |
| 3817 | with pytest.raises(MCPDestinationError) as excinfo: |
| 3818 | ToolRouter(client=client, provider=MagicMock()).create( |
| 3819 | user_id="user_123", mcp=True |
| 3820 | ) |
| 3821 | |
| 3822 | assert str(excinfo.value) == "The MCP URL is not a valid absolute URL" |
| 3823 | assert "secret_value" not in str(excinfo.value) |
| 3824 | |
| 3825 | def test_same_origin_mcp_url_does_not_warn(self, tool_router, caplog): |
| 3826 | with caplog.at_level(logging.WARNING): |
| 3827 | session = tool_router.create(user_id="user_123") |
| 3828 | |
| 3829 | assert session.mcp.headers == {"x-api-key": "test-api-key"} |
| 3830 | assert not [r for r in caplog.records if r.levelno == logging.WARNING] |
| 3831 | |
| 3832 | def test_same_origin_plain_http_base_url_exports_credentials(self): |
| 3833 | client, requests = _transport_client( |
| 3834 | auth=ProjectAuth("ak_project_key"), |
| 3835 | base_url="http://localhost:3000", |
| 3836 | mcp_url="http://localhost:3000/api/v3/tool_router/session/session_123/mcp", |
| 3837 | ) |
| 3838 | session = ToolRouter(client=client, provider=MagicMock()).create( |
| 3839 | user_id="user_123", mcp=True |
| 3840 | ) |
| 3841 | |
| 3842 | assert requests[0].headers["x-api-key"] == "ak_project_key" |
| 3843 | assert session.mcp.headers == {"x-api-key": "ak_project_key"} |
| 3844 | |
| 3845 | def test_same_origin_https_mcp_url_behaves_as_before(self, tool_router): |
| 3846 | session = tool_router.create(user_id="user_123", mcp=True) |
| 3847 | |
| 3848 | assert session.mcp.url == ( |
| 3849 | "https://backend.composio.dev/api/v3/tool_router/session/session_123" |
| 3850 | ) |
| 3851 | assert session.mcp.headers == {"x-api-key": "test-api-key"} |
| 3852 | |
| 3853 | |
| 3854 | class TestSessionUpdateContract: |
| 3855 | """update() nullable fields, empty allowlists, and version preconditions.""" |
| 3856 | |
| 3857 | @pytest.fixture |
| 3858 | def session(self, tool_router, mock_client): |
| 3859 | patched = MagicMock() |
| 3860 | patched.preload = MagicMock() |
| 3861 | patched.preload.tools = ["SLACK_SEND_MESSAGE"] |
| 3862 | mock_client.tool_router.session.patch.return_value.config = patched |
| 3863 | mock_client.tool_router.session.patch.return_value.config_version = 8 |
| 3864 | return tool_router.use(session_id="session_123") |
| 3865 | |
| 3866 | @staticmethod |
| 3867 | def _conflict() -> ConflictError: |
| 3868 | response = httpx.Response( |
| 3869 | 409, |
| 3870 | request=httpx.Request("PATCH", "https://backend.composio.dev/patch"), |
| 3871 | json={"error": "version conflict"}, |
| 3872 | ) |
| 3873 | return ConflictError( |
| 3874 | "Conflict", response=response, body={"error": "version conflict"} |
| 3875 | ) |
| 3876 | |
| 3877 | def test_session_tracks_config_version(self, session): |
| 3878 | assert session.config_version == 7 |
| 3879 | |
| 3880 | @pytest.mark.parametrize( |
| 3881 | ("proxy_execute", "expected"), |
| 3882 | [ |
| 3883 | ({"enable": True}, {"enable": True}), |
| 3884 | ({"enable": False}, {"enable": False}), |
| 3885 | (True, {"enable": True}), |
| 3886 | (False, {"enable": False}), |
| 3887 | (None, None), |
| 3888 | ], |
| 3889 | ) |
| 3890 | def test_proxy_execute_is_sent_as_block( |
| 3891 | self, session, mock_client, proxy_execute, expected |
| 3892 | ): |
| 3893 | session.update(proxy_execute=proxy_execute) |
| 3894 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3895 | assert kwargs["proxy_execute"] == expected |
| 3896 | |
| 3897 | def test_proxy_execute_is_omitted_by_default(self, session, mock_client): |
| 3898 | session.update(toolkits={"enable": ["gmail"]}) |
| 3899 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3900 | assert kwargs["proxy_execute"] is omit |
| 3901 | |
| 3902 | def test_instant_policy_is_sent(self, session, mock_client): |
| 3903 | session.update( |
| 3904 | instant={ |
| 3905 | "toolkits": {"enable": ["exa"]}, |
| 3906 | "return_instant_charge": True, |
| 3907 | } |
| 3908 | ) |
| 3909 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3910 | assert kwargs["instant"] == { |
| 3911 | "toolkits": {"enable": ["exa"]}, |
| 3912 | "return_instant_charge": True, |
| 3913 | } |
| 3914 | |
| 3915 | def test_instant_can_be_disabled(self, session, mock_client): |
| 3916 | session.update(instant=False) |
| 3917 | assert ( |
| 3918 | mock_client.tool_router.session.patch.call_args.kwargs["instant"] is False |
| 3919 | ) |
| 3920 | |
| 3921 | def test_instant_rejects_none(self, session, mock_client): |
| 3922 | with pytest.raises(InvalidParams, match="instant"): |
| 3923 | session.update(instant=None) # type: ignore[arg-type] |
| 3924 | mock_client.tool_router.session.patch.assert_not_called() |
| 3925 | |
| 3926 | def test_update_sends_no_precondition_by_default_without_retries( |
| 3927 | self, session, mock_client |
| 3928 | ): |
| 3929 | session.update(toolkits={"enable": ["gmail"]}) |
| 3930 | |
| 3931 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3932 | assert kwargs["extra_body"] is None |
| 3933 | assert kwargs["request_options"] == {"max_retries": 0} |
| 3934 | assert session.config_version == 8 |
| 3935 | assert session.preload.tools == ["SLACK_SEND_MESSAGE"] |
| 3936 | |
| 3937 | def test_update_opt_out_sends_no_precondition(self, session, mock_client): |
| 3938 | session.update(toolkits={"enable": ["gmail"]}, expected_config_version=False) |
| 3939 | |
| 3940 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3941 | assert kwargs["extra_body"] is None |
| 3942 | |
| 3943 | def test_update_sends_an_explicit_expected_version(self, session, mock_client): |
| 3944 | session.update(toolkits={"enable": ["gmail"]}, expected_config_version=9) |
| 3945 | |
| 3946 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3947 | assert kwargs["extra_body"] == {"expected_config_version": 9} |
| 3948 | |
| 3949 | def test_update_rejects_non_positive_expected_version(self, session, mock_client): |
| 3950 | with pytest.raises(InvalidParams): |
| 3951 | session.update(toolkits={"enable": ["gmail"]}, expected_config_version=0) |
| 3952 | mock_client.tool_router.session.patch.assert_not_called() |
| 3953 | |
| 3954 | def test_update_passes_null_callback_url_through(self, session, mock_client): |
| 3955 | session.update(manage_connections={"callback_url": None}) |
| 3956 | |
| 3957 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3958 | assert kwargs["manage_connections"] == {"callback_url": None} |
| 3959 | |
| 3960 | def test_update_preserves_empty_toolkit_allowlist(self, session, mock_client): |
| 3961 | session.update(toolkits={"enable": []}) |
| 3962 | |
| 3963 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3964 | assert kwargs["toolkits"] == {"enable": []} |
| 3965 | |
| 3966 | def test_update_sends_none_for_cleared_blocks(self, session, mock_client): |
| 3967 | session.update( |
| 3968 | toolkits=None, |
| 3969 | tools=None, |
| 3970 | tags=None, |
| 3971 | auth_configs=None, |
| 3972 | connected_accounts=None, |
| 3973 | preload=None, |
| 3974 | multi_account=None, |
| 3975 | search=None, |
| 3976 | execute=None, |
| 3977 | experimental=None, |
| 3978 | ) |
| 3979 | |
| 3980 | kwargs = mock_client.tool_router.session.patch.call_args.kwargs |
| 3981 | for name in ( |
| 3982 | "toolkits", |
| 3983 | "tools", |
| 3984 | "tags", |
| 3985 | "auth_configs", |
| 3986 | "connected_accounts", |
| 3987 | "preload", |
| 3988 | "multi_account", |
| 3989 | "search", |
| 3990 | "execute", |
| 3991 | "experimental", |
| 3992 | ): |
| 3993 | assert kwargs[name] is None, name |
| 3994 | assert kwargs["manage_connections"] is omit |
| 3995 | assert kwargs["workbench"] is omit |
| 3996 | |
| 3997 | def test_update_conflict_is_typed_and_keeps_local_state(self, session, mock_client): |
| 3998 | preload_before = session.preload |
| 3999 | mock_client.tool_router.session.patch.side_effect = self._conflict() |
| 4000 | |
| 4001 | with pytest.raises(SessionConfigConflictError) as excinfo: |
| 4002 | session.update( |
| 4003 | toolkits={"enable": ["gmail"]}, |
| 4004 | expected_config_version=session.config_version, |
| 4005 | ) |
| 4006 | |
| 4007 | assert "re-fetch" in str(excinfo.value).lower() |
| 4008 | assert "retry" in str(excinfo.value).lower() |
| 4009 | assert excinfo.value.status_code == 409 |
| 4010 | assert excinfo.value.session_id == "session_123" |
| 4011 | assert excinfo.value.expected_config_version == 7 |
| 4012 | assert session.preload is preload_before |
| 4013 | assert session.config_version == 7 |
| 4014 | |
| 4015 | @pytest.mark.parametrize("opt_out", [{}, {"expected_config_version": False}]) |
| 4016 | def test_update_conflict_without_precondition_reports_in_flight_change( |
| 4017 | self, session, mock_client, opt_out |
| 4018 | ): |
| 4019 | config_before = session.config |
| 4020 | mock_client.tool_router.session.patch.side_effect = self._conflict() |
| 4021 | |
| 4022 | with pytest.raises(SessionConfigConflictError) as excinfo: |
| 4023 | session.update(toolkits={"enable": ["gmail"]}, **opt_out) |
| 4024 | |
| 4025 | message = str(excinfo.value) |
| 4026 | assert "changed while this update was in flight" in message |
| 4027 | assert "no longer at version" not in message |
| 4028 | assert excinfo.value.expected_config_version is None |
| 4029 | assert session.config is config_before |
| 4030 | assert session.config_version == 7 |
| 4031 | |
| 4032 | def test_two_handles_at_the_same_version(self, tool_router, mock_client): |
| 4033 | mock_client.tool_router.session.patch.return_value.config_version = 8 |
| 4034 | first = tool_router.use(session_id="session_123") |
| 4035 | second = tool_router.use(session_id="session_123") |
| 4036 | assert first.config_version == second.config_version == 7 |
| 4037 | |
| 4038 | first.update( |
| 4039 | toolkits={"enable": ["gmail"]}, |
| 4040 | expected_config_version=first.config_version, |
| 4041 | ) |
| 4042 | assert mock_client.tool_router.session.patch.call_args.kwargs["extra_body"] == { |
| 4043 | "expected_config_version": 7 |
| 4044 | } |
| 4045 | assert first.config_version == 8 |
| 4046 | |
| 4047 | mock_client.tool_router.session.patch.side_effect = self._conflict() |
| 4048 | with pytest.raises(SessionConfigConflictError): |
| 4049 | second.update( |
| 4050 | toolkits={"enable": ["slack"]}, |
| 4051 | expected_config_version=second.config_version, |
| 4052 | ) |
| 4053 | assert second.config_version == 7 |
| 4054 | |
| 4055 | mock_client.tool_router.session.patch.side_effect = None |
| 4056 | mock_client.tool_router.session.retrieve.return_value.config_version = 8 |
| 4057 | mock_client.tool_router.session.patch.return_value.config_version = 9 |
| 4058 | reread = tool_router.use(session_id="session_123") |
| 4059 | assert reread.config_version == 8 |
| 4060 | reread.update( |
| 4061 | toolkits={"enable": ["slack"]}, |
| 4062 | expected_config_version=reread.config_version, |
| 4063 | ) |
| 4064 | assert mock_client.tool_router.session.patch.call_args.kwargs["extra_body"] == { |
| 4065 | "expected_config_version": 8 |
| 4066 | } |
| 4067 | assert reread.config_version == 9 |
| 4068 | |
| 4069 | |
| 4070 | class TestSessionExecuteMeta: |
| 4071 | """``session.execute_meta`` runs a Composio meta tool through the meta |
| 4072 | endpoint and answers in the same shape as ``session.execute``. |
| 4073 | """ |
| 4074 | |
| 4075 | def test_sends_the_slug_and_arguments_to_the_meta_endpoint(self): |
| 4076 | client, requests = _answering_client(_executed_json("completed", None)) |
| 4077 | |
| 4078 | _created_session(client).execute_meta( |
| 4079 | "COMPOSIO_SEARCH_TOOLS", |
| 4080 | arguments={"queries": [{"use_case": "send an email"}]}, |
| 4081 | ) |
| 4082 | |
| 4083 | assert len(requests) == 1 |
| 4084 | assert requests[0].url.path == ( |
| 4085 | "/api/v3.1/tool_router/session/session_123/execute_meta" |
| 4086 | ) |
| 4087 | assert json.loads(requests[0].content) == { |
| 4088 | "slug": "COMPOSIO_SEARCH_TOOLS", |
| 4089 | "arguments": {"queries": [{"use_case": "send an email"}]}, |
| 4090 | } |
| 4091 | |
| 4092 | def test_omits_arguments_when_not_passed(self): |
| 4093 | client, requests = _answering_client(_executed_json("completed", None)) |
| 4094 | |
| 4095 | _created_session(client).execute_meta("COMPOSIO_MANAGE_CONNECTIONS") |
| 4096 | |
| 4097 | assert json.loads(requests[0].content) == { |
| 4098 | "slug": "COMPOSIO_MANAGE_CONNECTIONS" |
| 4099 | } |
| 4100 | |
| 4101 | @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS) |
| 4102 | def test_returns_the_session_execute_response(self, result_type, error, successful): |
| 4103 | client, _ = _answering_client( |
| 4104 | { |
| 4105 | **_executed_json(result_type, error), |
| 4106 | "data": {"results": []}, |
| 4107 | "instant_charge": { |
| 4108 | "amount": "0.01", |
| 4109 | "currency": "USD", |
| 4110 | "charged_by": "composio", |
| 4111 | }, |
| 4112 | } |
| 4113 | ) |
| 4114 | |
| 4115 | result = _created_session(client).execute_meta("COMPOSIO_SEARCH_TOOLS") |
| 4116 | |
| 4117 | assert isinstance(result, ToolRouterSessionExecuteResponse) |
| 4118 | assert result.result_type == result_type |
| 4119 | assert result.error == error |
| 4120 | assert result.data == {"results": []} |
| 4121 | assert result.log_id == "log" |
| 4122 | assert result.instant_charge is not None |
| 4123 | assert result.instant_charge.amount == "0.01" |
| 4124 | |
| 4125 | @pytest.mark.parametrize("body", _INVALID_ANSWERS) |
| 4126 | def test_raises_without_a_known_result_type(self, body): |
| 4127 | client, requests = _answering_client(body) |
| 4128 | |
| 4129 | with pytest.raises( |
| 4130 | ValidationError, |
| 4131 | match="Tool COMPOSIO_SEARCH_TOOLS returned an execute response " |
| 4132 | "without a known result_type", |
| 4133 | ): |
| 4134 | _created_session(client).execute_meta("COMPOSIO_SEARCH_TOOLS") |
| 4135 | |
| 4136 | assert len(requests) == 1 |
| 4137 | |
| 4138 | def test_slugs_match_the_generated_client(self): |
| 4139 | from composio_client.resources.tool_router.session import SessionResource |
| 4140 | |
| 4141 | slug_hint = t.get_type_hints(SessionResource.execute_meta)["slug"] |
| 4142 | client_slugs = { |
| 4143 | slug |
| 4144 | for member in t.get_args(slug_hint) |
| 4145 | for slug in t.get_args(member) |
| 4146 | if isinstance(slug, str) |
| 4147 | } |
| 4148 | |
| 4149 | assert client_slugs |
| 4150 | assert set(t.get_args(ToolRouterSessionMetaToolSlug)) == client_slugs |