3
import json
4
import logging
5
import os
6
+import traceback
7
import typing as t
8
from unittest.mock import MagicMock, patch
9
35
ToolRouterSession,
36
ToolRouterSessionWithMcp,
37
)
38
+from composio.core.models.session_context import SessionContextImpl
39
from composio.exceptions import (
40
InvalidParams,
41
MCPDestinationError,
42
SessionConfigConflictError,
43
+ ToolInputRequiredError,
44
ValidationError,
45
)
46
from tests.conftest import mock_http_client
187
policy = {"toolkits": {"enable": ["exa"]}, "return_instant_charge": True}
188
tool_router.create(user_id="user_123", instant=policy)
189
kwargs = mock_client.tool_router.session.create.call_args.kwargs
187
- assert kwargs["extra_body"]["instant"] == policy
190
+ assert kwargs["instant"] == policy
191
assert "premium_usage" not in kwargs
192
193
mock_client.tool_router.session.create.reset_mock()
199
200
tool_router.create(user_id="user_123", instant=False)
201
assert (
199
- mock_client.tool_router.session.create.call_args.kwargs["extra_body"][
200
- "instant"
201
- ]
202
- is False
202
+ mock_client.tool_router.session.create.call_args.kwargs["instant"] is False
203
)
204
205
def test_create_session_default_returns_base_session(self, tool_router):
2333
assert "instant" not in body
2334
else:
2335
assert body["instant"] == policy
2336
- assert session.config.instant == {"return_instant_charge": True}
2336
+ assert not isinstance(session.config.instant, bool)
2337
+ assert session.config.instant.return_instant_charge is True
2338
assert "premium_usage" not in session.config.model_dump()
2339
2340
if policy is None:
2348
assert "instant" not in body
2349
else:
2350
assert body["instant"] == policy
2350
- assert session.config.instant == {"return_instant_charge": True}
2351
+ assert not isinstance(session.config.instant, bool)
2352
+ assert session.config.instant.return_instant_charge is True
2353
assert "premium_usage" not in session.config.model_dump()
2354
2355
attached = router.use(session_id="session_123")
2354
- assert attached.config.instant == {"return_instant_charge": True}
2356
+ assert not isinstance(attached.config.instant, bool)
2357
+ assert attached.config.instant.return_instant_charge is True
2358
2359
def test_execute_selector_charge_and_search_coverage(self):
2360
requests: t.List[httpx.Request] = []
2387
)
2388
result = session.execute("EXA_SEARCH", arguments={}, account="instant_account")
2389
assert json.loads(requests[-1].content)["account"] == "instant_account"
2387
- assert result.instant_charge == charge
2390
+ assert result.instant_charge is not None
2391
+ assert result.instant_charge.amount == "0.012"
2392
+ assert result.instant_charge.model_dump() == charge
2393
assert "premium_charge" not in result.model_dump()
2394
status = session.search(query="search").toolkit_connection_statuses[0]
2395
assert status.instant_account is not None
2425
assert result.to_dict() == payload
2426
2427
2428
+_INPUT_REQUIRED_JSON: t.Dict[str, t.Any] = {
2429
+ "result_type": "input_required",
2430
+ "input_requests": {
2431
+ "approval_1": {
2432
+ "type": "elicitation",
2433
+ "mode": "form",
2434
+ "message": "Allow GMAIL_SEND_EMAIL to send this email?",
2435
+ "requested_schema": {
2436
+ "type": "object",
2437
+ "properties": {"approved": {"type": "boolean"}},
2438
+ "required": ["approved"],
2439
+ },
2440
+ }
2441
+ },
2442
+ "request_state": "opaque-state-token",
2443
+}
2444
+
2445
+_PROXY_PARAMS: t.Dict[str, t.Any] = {
2446
+ "toolkit": "github",
2447
+ "endpoint": "https://api.github.com/user/repos?token=secret",
2448
+ "method": "POST",
2449
+ "body": {"name": "repo"},
2450
+}
2451
+
2452
+
2453
+def _answering_client(
2454
+ body: t.Dict[str, t.Any],
2455
+) -> t.Tuple[HttpClient, t.List[httpx.Request]]:
2456
+ """A real client whose execute and proxy calls are answered with ``body``."""
2457
+ requests: t.List[httpx.Request] = []
2458
+
2459
+ def handler(request: httpx.Request) -> httpx.Response:
2460
+ if request.url.path.endswith(("/execute", "/proxy_execute")):
2461
+ requests.append(request)
2462
+ return httpx.Response(200, json=body)
2463
+ return httpx.Response(200, json=_session_json(MCP_SAME_ORIGIN_URL))
2464
+
2465
+ client = HttpClient(
2466
+ provider="test",
2467
+ api_key="ak_test",
2468
+ base_url="https://backend.composio.dev",
2469
+ http_client=httpx.Client(transport=httpx.MockTransport(handler)),
2470
+ )
2471
+ return client, requests
2472
+
2473
+
2474
+def _created_session(client: HttpClient) -> ToolRouterSession:
2475
+ return ToolRouter(client=client, provider=MagicMock()).create(user_id="user_123")
2476
+
2477
+
2478
+class TestExecutionRequiresUserInput:
2479
+ """``result_type: "input_required"`` carries no data, log ID or HTTP status,
2480
+ so every execution path raises it instead of returning it as a result.
2481
+
2482
+ The cases run a real client over a stub transport so they cover the wire
2483
+ shape the generated client hands to the SDK.
2484
+ """
2485
+
2486
+ @pytest.mark.parametrize(
2487
+ ("run", "subject"),
2488
+ [
2489
+ pytest.param(
2490
+ lambda client: _created_session(client).execute(
2491
+ "GMAIL_SEND_EMAIL", arguments={"to": "test@test.com"}
2492
+ ),
2493
+ "Tool GMAIL_SEND_EMAIL",
2494
+ id="session.execute",
2495
+ ),
2496
+ pytest.param(
2497
+ lambda client: _created_session(client).proxy_execute(**_PROXY_PARAMS),
2498
+ "POST proxy call for toolkit github",
2499
+ id="session.proxy_execute",
2500
+ ),
2501
+ pytest.param(
2502
+ lambda client: SessionContextImpl(
2503
+ client, "user_123", "session_123"
2504
+ ).execute("GMAIL_SEND_EMAIL", {"to": "test@test.com"}),
2505
+ "Tool GMAIL_SEND_EMAIL",
2506
+ id="custom tool context execute",
2507
+ ),
2508
+ pytest.param(
2509
+ lambda client: SessionContextImpl(
2510
+ client, "user_123", "session_123"
2511
+ ).proxy_execute(**_PROXY_PARAMS),
2512
+ "POST proxy call for toolkit github",
2513
+ id="custom tool context proxy_execute",
2514
+ ),
2515
+ pytest.param(
2516
+ lambda client: _session_tool_execute_fn(client)(
2517
+ "GMAIL_SEND_EMAIL", {"to": "test@test.com"}
2518
+ ),
2519
+ "Tool GMAIL_SEND_EMAIL",
2520
+ id="provider-wrapped session tool",
2521
+ ),
2522
+ ],
2523
+ )
2524
+ def test_raises_tool_input_required_error(self, run, subject):
2525
+ client, requests = _answering_client(_INPUT_REQUIRED_JSON)
2526
+
2527
+ with pytest.raises(ToolInputRequiredError) as raised:
2528
+ run(client)
2529
+
2530
+ error = raised.value
2531
+ assert f"{subject} requires user input" in error.message
2532
+ assert "request_state" in error.message
2533
+ # The opaque state and the proxied URL stay out of the message.
2534
+ assert "opaque-state-token" not in error.message
2535
+ assert "secret" not in error.message
2536
+ assert error.request_state == "opaque-state-token"
2537
+ assert error.input_requests == {
2538
+ "approval_1": {
2539
+ "type": "elicitation",
2540
+ "mode": "form",
2541
+ "message": "Allow GMAIL_SEND_EMAIL to send this email?",
2542
+ "requested_schema": {
2543
+ "type": "object",
2544
+ "properties": {"approved": {"type": "boolean"}},
2545
+ "required": ["approved"],
2546
+ },
2547
+ }
2548
+ }
2549
+ # The call is not repeated: answering needs the user.
2550
+ assert len(requests) == 1
2551
+
2552
+ def test_request_state_stays_out_of_str_repr_and_args(self):
2553
+ """``request_state`` is continuation state: readable as an attribute
2554
+ for the code that answers the request, absent from what an exception
2555
+ is routinely logged as."""
2556
+ client, _ = _answering_client(_INPUT_REQUIRED_JSON)
2557
+
2558
+ with pytest.raises(ToolInputRequiredError) as raised:
2559
+ _created_session(client).execute("GMAIL_SEND_EMAIL")
2560
+
2561
+ error = raised.value
2562
+ assert error.request_state == "opaque-state-token"
2563
+ assert "opaque-state-token" not in str(error)
2564
+ assert "opaque-state-token" not in repr(error)
2565
+ assert "opaque-state-token" not in repr(error.args)
2566
+ assert error.args == (error.message,)
2567
+ formatted = "".join(
2568
+ traceback.format_exception(type(error), error, error.__traceback__)
2569
+ )
2570
+ assert "ToolInputRequiredError" in formatted
2571
+ assert "opaque-state-token" not in formatted
2572
+
2573
+ def test_request_state_is_none_when_the_api_returns_none(self):
2574
+ body = {k: v for k, v in _INPUT_REQUIRED_JSON.items() if k != "request_state"}
2575
+ client, _ = _answering_client(body)
2576
+
2577
+ with pytest.raises(ToolInputRequiredError) as raised:
2578
+ _created_session(client).execute("GMAIL_SEND_EMAIL")
2579
+
2580
+ assert raised.value.request_state is None
2581
+
2582
+ @pytest.mark.parametrize(
2583
+ ("result_type", "error"),
2584
+ [("completed", None), ("failed", "Connection not found")],
2585
+ )
2586
+ def test_execute_still_returns_a_result(self, result_type, error):
2587
+ client, _ = _answering_client(
2588
+ {
2589
+ "result_type": result_type,
2590
+ "data": {"id": "msg_1"},
2591
+ "error": error,
2592
+ "log_id": "log_1",
2593
+ }
2594
+ )
2595
+
2596
+ result = _created_session(client).execute("GMAIL_SEND_EMAIL")
2597
+
2598
+ assert result.result_type == result_type
2599
+ assert result.data == {"id": "msg_1"}
2600
+ assert result.error == error
2601
+ assert result.log_id == "log_1"
2602
+
2603
+ def test_proxy_execute_still_returns_a_completed_result(self):
2604
+ client, _ = _answering_client(
2605
+ {
2606
+ "result_type": "completed",
2607
+ "status": 201,
2608
+ "data": {"id": 1},
2609
+ "headers": {"x-request-id": "req_1"},
2610
+ }
2611
+ )
2612
+
2613
+ result = _created_session(client).proxy_execute(**_PROXY_PARAMS)
2614
+
2615
+ assert result == {
2616
+ "status": 201,
2617
+ "data": {"id": 1},
2618
+ "headers": {"x-request-id": "req_1"},
2619
+ }
2620
+
2621
+
2622
+class _NoInput(BaseModel):
2623
+ pass
2624
+
2625
+
2626
+def _custom_tool_calling(call: t.Callable[[t.Any], t.Any]) -> t.Any:
2627
+ """A custom tools map with one local tool whose body runs ``call(ctx)``."""
2628
+ from composio.core.models.custom_tool import build_custom_tools_map
2629
+
2630
+ @experimental_api.tool()
2631
+ def send_welcome_email(input: _NoInput, ctx: t.Any) -> t.Dict[str, t.Any]:
2632
+ """Sends the welcome email through a session helper."""
2633
+ return {"sent": call(ctx)}
2634
+
2635
+ return build_custom_tools_map([send_welcome_email])
2636
+
2637
+
2638
+def _session_with_custom_tools(
2639
+ client: HttpClient, custom_tools_map: t.Any
2640
+) -> ToolRouterSession:
2641
+ return ToolRouterSession(
2642
+ client=client,
2643
+ provider=MagicMock(),
2644
+ dangerously_allow_auto_upload_download_files=False,
2645
+ session_id="session_123",
2646
+ mcp=MagicMock(),
2647
+ experimental=MagicMock(),
2648
+ custom_tools_map=custom_tools_map,
2649
+ user_id="user_123",
2650
+ )
2651
+
2652
+
2653
+def _raise_boom(ctx: t.Any) -> t.Any:
2654
+ raise RuntimeError("boom")
2655
+
2656
+
2657
+class TestCustomToolBodyRequiresUserInput:
2658
+ """A local custom tool reaches the API through ``ctx.execute()`` and
2659
+ ``ctx.proxy_execute()``. The wrapper that runs the tool turns whatever it
2660
+ raises into a failed result, which must not happen to an input request: the
2661
+ caller needs the questions and the request state, not a message.
2662
+ """
2663
+
2664
+ _BODIES = [
2665
+ pytest.param(
2666
+ lambda ctx: ctx.execute("GMAIL_SEND_EMAIL", {"to": "test@test.com"}),
2667
+ "Tool GMAIL_SEND_EMAIL",
2668
+ id="ctx.execute",
2669
+ ),
2670
+ pytest.param(
2671
+ lambda ctx: ctx.proxy_execute(**_PROXY_PARAMS),
2672
+ "POST proxy call for toolkit github",
2673
+ id="ctx.proxy_execute",
2674
+ ),
2675
+ ]
2676
+
2677
+ @pytest.mark.parametrize(("call", "subject"), _BODIES)
2678
+ def test_session_execute_of_a_custom_tool_raises(self, call, subject):
2679
+ client, requests = _answering_client(_INPUT_REQUIRED_JSON)
2680
+ session = _session_with_custom_tools(client, _custom_tool_calling(call))
2681
+
2682
+ with pytest.raises(ToolInputRequiredError) as raised:
2683
+ session.execute("SEND_WELCOME_EMAIL", arguments={})
2684
+
2685
+ error = raised.value
2686
+ assert f"{subject} requires user input" in error.message
2687
+ assert error.request_state == "opaque-state-token"
2688
+ assert list(error.input_requests) == ["approval_1"]
2689
+ assert len(requests) == 1
2690
+
2691
+ @pytest.mark.parametrize(("call", "subject"), _BODIES)
2692
+ def test_sibling_custom_tool_raises_through_ctx_execute(self, call, subject):
2693
+ client, _ = _answering_client(_INPUT_REQUIRED_JSON)
2694
+ context = SessionContextImpl(
2695
+ client, "user_123", "session_123", _custom_tool_calling(call)
2696
+ )
2697
+
2698
+ with pytest.raises(ToolInputRequiredError) as raised:
2699
+ context.execute("SEND_WELCOME_EMAIL", {})
2700
+
2701
+ assert raised.value.request_state == "opaque-state-token"
2702
+
2703
+ def test_any_other_error_is_still_a_failed_result(self):
2704
+ client, _ = _answering_client(_INPUT_REQUIRED_JSON)
2705
+ session = _session_with_custom_tools(client, _custom_tool_calling(_raise_boom))
2706
+
2707
+ result = session.execute("SEND_WELCOME_EMAIL", arguments={})
2708
+
2709
+ assert result.error == "boom"
2710
+ assert result.result_type == "failed"
2711
+
2712
+
2713
+_EXECUTED_ANSWERS = [
2714
+ pytest.param("failed", None, False, id="failed with a null error"),
2715
+ pytest.param("failed", "", False, id="failed with an empty error"),
2716
+ pytest.param("failed", "Boom", False, id="failed with a message"),
2717
+ pytest.param("completed", None, True, id="completed"),
2718
+ pytest.param(None, None, True, id="no result_type and no error"),
2719
+ pytest.param(None, "Boom", False, id="no result_type and an error"),
2720
+]
2721
+
2722
+
2723
+def _executed_json(
2724
+ result_type: t.Optional[str], error: t.Optional[str]
2725
+) -> t.Dict[str, t.Any]:
2726
+ body: t.Dict[str, t.Any] = {"data": {}, "error": error, "log_id": "log"}
2727
+ if result_type is not None:
2728
+ body["result_type"] = result_type
2729
+ return body
2730
+
2731
+
2732
+class TestSessionExecutionSuccess:
2733
+ """``result_type`` says whether a tool that ran succeeded. A failed
2734
+ execution can carry a ``None`` or empty ``error``, so success is read from
2735
+ ``result_type`` and only falls back to the error text when the API sent no
2736
+ ``result_type``.
2737
+ """
2738
+
2739
+ @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2740
+ def test_provider_wrapped_session_tool(self, result_type, error, successful):
2741
+ client, _ = _answering_client(_executed_json(result_type, error))
2742
+
2743
+ result = _session_tool_execute_fn(client)("GMAIL_SEND_EMAIL", {})
2744
+
2745
+ # The error is passed through as the API sent it.
2746
+ assert result == {"data": {}, "error": error, "successful": successful}
2747
+
2748
+ @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2749
+ def test_provider_tool_call_bound_to_a_session(
2750
+ self, result_type, error, successful
2751
+ ):
2752
+ from composio.core.provider._openai import OpenAIProvider
2753
+
2754
+ client, _ = _answering_client(_executed_json(result_type, error))
2755
+
2756
+ result = OpenAIProvider().execute_tool_for_target(
2757
+ target=_created_session(client), slug="GMAIL_SEND_EMAIL", arguments={}
2758
+ )
2759
+
2760
+ assert result == {"data": {}, "error": error, "successful": successful}
2761
+
2762
+ @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2763
+ def test_session_execute_exposes_result_type(self, result_type, error, successful):
2764
+ client, _ = _answering_client(_executed_json(result_type, error))
2765
+
2766
+ result = _created_session(client).execute("GMAIL_SEND_EMAIL")
2767
+
2768
+ assert result.result_type == result_type
2769
+ assert result.error == error
2770
+
2771
+ @pytest.mark.parametrize(("result_type", "error", "successful"), _EXECUTED_ANSWERS)
2772
+ def test_custom_tool_context_execute_exposes_result_type(
2773
+ self, result_type, error, successful
2774
+ ):
2775
+ client, _ = _answering_client(_executed_json(result_type, error))
2776
+
2777
+ result = SessionContextImpl(client, "user_123", "session_123").execute(
2778
+ "GMAIL_SEND_EMAIL", {}
2779
+ )
2780
+
2781
+ assert result.result_type == result_type
2782
+ assert result.error == error
2783
+
2784
+
2785
+def _session_tool_execute_fn(client: HttpClient) -> t.Callable[..., t.Any]:
2786
+ """The execute function providers wrap session tools with."""
2787
+ from composio.core.models.tools import Tools
2788
+
2789
+ tools = Tools(
2790
+ client=client,
2791
+ provider=MagicMock(),
2792
+ dangerously_allow_auto_upload_download_files=False,
2793
+ )
2794
+ # Keep the (read) tool-schema lookup off the transport.
2795
+ tools._tool_schemas["GMAIL_SEND_EMAIL"] = MagicMock()
2796
+ return tools._wrap_execute_tool_for_tool_router(session_id="session_123")
2797
+
2798
+
2799
def _transport_client(
2800
*,
2801
api_key: t.Optional[str],
3100
}
3101
)
3102
kwargs = mock_client.tool_router.session.patch.call_args.kwargs
2727
- assert kwargs["extra_body"]["instant"] == {
3103
+ assert kwargs["instant"] == {
3104
"toolkits": {"enable": ["exa"]},
3105
"return_instant_charge": True,
3106
}
3109
def test_instant_can_be_disabled(self, session, mock_client):
3110
session.update(instant=False)
3111
assert (
2736
- mock_client.tool_router.session.patch.call_args.kwargs["extra_body"][
2737
- "instant"
2738
- ]
2739
- is False
3112
+ mock_client.tool_router.session.patch.call_args.kwargs["instant"] is False
3113
)
3114
3115
def test_instant_rejects_none(self, session, mock_client):