@devries-cameron20 / composio-1 / commits / b34133dc6
Fork 0

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

fix(py): expose premium charge on session execute responses (#4623)

## Summary This PR: - follows up on https://github.com/ComposioHQ/composio/pull/4599, which added the `premium_usage.return_premium_charge` opt-in to both SDKs but only surfaced the resulting `premium_charge` on TypeScript responses - types `session.execute()` results as `ToolRouterSessionExecuteResponse` (matching the TypeScript name, exported from `composio.core.models`), a subclass of the generated client's `SessionExecuteResponse` with `premium_charge: Optional[PremiumCharge]`, so it's no longer an untyped pydantic extra - adds `premium_charge` as a `NotRequired` key on `ToolExecutionResponse`, and has the provider-wrapped session execute function forward it; previously it rebuilt the result as `{data, error, successful}` and dropped the charge for every framework integration - keeps the remote charge when `COMPOSIO_MULTI_EXECUTE_TOOL` mixes local custom tools with remote tools, matching the TypeScript merge in `ToolRouterSession.ts` - exports the new `PremiumCharge` TypedDict (`amount`, `currency`, `charged_by`, per the OpenAPI execute response) from `composio.types` `composio-client` 2.0.0rc8 is still the latest release and doesn't declare `premium_charge`, so the typing lives in the SDK. `session.execute()` rebuilds the response with `model_construct` so a malformed charge can't raise after the tool has already run. Existing `isinstance` checks against the client's `SessionExecuteResponse` still pass. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? - `nox -s chk` (ruff + mypy): passes - `nox -s tst`: 2082 passed, 41 skipped - New regression tests cover `session.execute()` with and without a charge, the provider wrapper with and without a charge, and a mixed local/remote multi-execute ## Checklist - [ ] I have read the Code of Conduct and this PR adheres to it - [ ] I have read and understand every line of this diff, including any LLM-generated code - [x] Any third-party docs links or promotional content follow the [third-party links policy](https://github.com/ComposioHQ/composio/blob/next/CONTRIBUTING.md#third-party-links-in-docs) - [x] I ran linters/tests locally and they passed - [ ] I updated documentation as needed - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages ## Additional context No changeset: this only touches the Python SDK, which doesn't use Changesets. TypeScript still types `premiumCharge` as `unknown`. Narrowing it to the same shape would be a separate follow-up.

Alberto Schiabel committed Sep 24, 2026 at 15:48 UTC b34133dc65ad2707b5c9c5ad54ea5b4dc8abd11a
6 files changed +149 -13
python/composio/core/models/__init__.py
+2 -1
@@ -19,7 +19,7 @@ from .logs import Logs
19 from .mcp import MCP
20 from .tool_router import ToolRouter
21 from .tool_router_constants import SESSION_PRESET_DIRECT_TOOLS
22 -from .tool_router_session import ToolRouterSession
22 +from .tool_router_session import ToolRouterSession, ToolRouterSessionExecuteResponse
23 from .tool_router_session_delete import ToolRouterSessionDeleteResponse
24 from .tool_router_session_files import RemoteFile, ToolRouterSessionFilesMount
25 from .toolkits import Toolkits
@@ -67,6 +67,7 @@ __all__ = [
67 "ToolRouter",
68 "ToolRouterSession",
69 "ToolRouterSessionDeleteResponse",
70 + "ToolRouterSessionExecuteResponse",
71 "ToolRouterSessionFilesMount",
72 "ToolRouterSessionProxyExecuteResponse",
73 "Toolkits",
python/composio/core/models/tool_router_session.py
+26 -11
@@ -74,7 +74,11 @@ from composio.core.models.tool_router_session_delete import (
74 ToolRouterSessionDeleteResponse,
75 delete_tool_router_session,
76 )
77 -from composio.core.models.tools import ToolExecuteParams, ToolExecutionResponse
77 +from composio.core.models.tools import (
78 + PremiumCharge,
79 + ToolExecuteParams,
80 + ToolExecutionResponse,
81 +)
82 from composio.core.provider import TTool, TToolCollection
83 from composio.core.provider.base import BaseProvider
84
@@ -129,6 +133,14 @@ class ToolRouterPremiumUsageConfig(te.TypedDict, total=False):
133 return_premium_charge: bool
134
135
136 +class ToolRouterSessionExecuteResponse(SessionExecuteResponse):
137 + """Result of :meth:`ToolRouterSession.execute`."""
138 +
139 + premium_charge: t.Optional[PremiumCharge] = None
140 + """Present only when the Session sets
141 + ``premium_usage.return_premium_charge`` and a charge is available."""
142 +
143 +
144 class ToolRouterUpdateManageConnectionsConfig(te.TypedDict, total=False):
145 """``manage_connections`` shape accepted by :meth:`ToolRouterSession.update`.
146
@@ -690,11 +702,14 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
702 else f"{failed} out of {len(all_results)} tools failed"
703 )
704
693 - return {
705 + merged: t.Dict[str, t.Any] = {
706 "data": merged_data,
707 "error": error_message,
708 "successful": not has_any_error,
709 }
710 + if remote_result and remote_result.get("premium_charge") is not None:
711 + merged["premium_charge"] = remote_result["premium_charge"]
712 + return merged
713
714 def authorize(
715 self,
@@ -849,7 +864,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
864 *,
865 arguments: t.Optional[t.Dict[str, t.Any]] = None,
866 account: t.Optional[str] = None,
852 - ) -> SessionExecuteResponse:
867 + ) -> ToolRouterSessionExecuteResponse:
868 """
869 Execute a tool within the session.
870
@@ -862,18 +877,14 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
877 multi-account sessions. Helper/meta tools either ignore this
878 top-level field or define their own account-selection fields.
879
865 - Both paths return a ``SessionExecuteResponse`` with ``data``,
866 - ``error``, and ``log_id`` attributes.
880 + Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
881 + ``error``, ``log_id``, and ``premium_charge`` attributes.
882 """
868 - from composio_client.types.tool_router.session_execute_response import (
869 - SessionExecuteResponse,
870 - )
871 -
883 # Check if this is a local tool (by original or final slug)
884 entry = find_custom_tool(self._custom_tools_map, tool_slug)
885 if entry and self._session_context:
886 result = execute_custom_tool(entry, arguments or {}, self._session_context)
876 - return SessionExecuteResponse(
887 + return ToolRouterSessionExecuteResponse(
888 data=result["data"],
889 error=result["error"],
890 log_id="",
@@ -881,7 +892,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
892
893 assert_unambiguous_custom_tool_slug(self._custom_tools_map, tool_slug)
894
884 - return self._client.tool_router.session.execute(
895 + response = self._client.tool_router.session.execute(
896 session_id=self.session_id,
897 tool_slug=tool_slug,
898 arguments=arguments if arguments is not None else omit,
@@ -890,6 +901,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
901 self._inline_custom_tools_payload
902 ),
903 )
904 + # The client already validated data/error/log_id and kept the
905 + # undeclared premium_charge as an extra. Construct without
906 + # revalidating so a malformed charge can't fail an executed call.
907 + return ToolRouterSessionExecuteResponse.model_construct(**dict(response))
908
909 def custom_tools(
910 self, *, toolkit: t.Optional[str] = None
python/composio/core/models/tools.py
+16
@@ -114,10 +114,22 @@ def _serialize_arguments(arguments: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
114 return {k: _serialize_value(v) for k, v in arguments.items()}
115
116
117 +class PremiumCharge(te.TypedDict):
118 + """Premium usage charge reported for a Session tool execution."""
119 +
120 + amount: str
121 + """Exact non-negative USD decimal string, e.g. ``"0.01"``."""
122 + currency: str
123 + charged_by: str
124 +
125 +
126 class ToolExecutionResponse(te.TypedDict):
127 data: t.Dict
128 error: t.Optional[str]
129 successful: bool
130 + premium_charge: te.NotRequired[PremiumCharge]
131 + """Present only when the Session sets
132 + ``premium_usage.return_premium_charge`` and a charge is available."""
133
134
135 class Tools(Resource, t.Generic[TTool, TToolCollection]):
@@ -571,6 +583,9 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
583 "error": response.error if hasattr(response, "error") else None,
584 "successful": not (hasattr(response, "error") and response.error),
585 }
586 + premium_charge = getattr(response, "premium_charge", None)
587 + if isinstance(premium_charge, dict):
588 + result["premium_charge"] = t.cast(PremiumCharge, premium_charge)
589
590 # Apply after_execute modifiers
591 if modifiers is not None:
@@ -801,6 +816,7 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
816
817 __all__ = [
818 "Tools",
819 + "PremiumCharge",
820 "ToolExecuteParams",
821 "ToolExecutionResponse",
822 "Modifiers",
python/composio/types.py
+2
@@ -2,6 +2,7 @@ from composio.client.types import Tool
2 from composio.core.models.connected_accounts import auth_scheme
3 from composio.core.models.tools import (
4 Modifiers,
5 + PremiumCharge,
6 ToolExecuteParams,
7 ToolExecutionResponse,
8 )
@@ -19,6 +20,7 @@ __all__ = [
20 "Tool",
21 "TTool",
22 "TToolCollection",
23 + "PremiumCharge",
24 "ToolExecuteParams",
25 "ToolExecutionResponse",
26 "TriggerEvent",
python/tests/test_custom_tools.py
+68 -1
@@ -41,7 +41,10 @@ from composio.core.models.custom_tool_execution import (
41 )
42 from composio.core.models.experimental import ExperimentalAPI
43 from composio.core.models.session_context import SessionContextImpl
44 -from composio.core.models.tool_router_session import ToolRouterSession
44 +from composio.core.models.tool_router_session import (
45 + ToolRouterSession,
46 + ToolRouterSessionExecuteResponse,
47 +)
48 from composio.exceptions import ValidationError
49
50 # ────────────────────────────────────────────────────────────────
@@ -978,6 +981,42 @@ class TestToolRouterSessionCustomTools:
981 assert result.data == {"sent": True}
982 assert result.log_id == "log_123"
983
984 + def test_execute_remote_exposes_premium_charge(self, mock_session_deps):
985 + charge = {"amount": "0.01", "currency": "USD", "charged_by": "composio"}
986 + mock_session_deps[
987 + "client"
988 + ].tool_router.session.execute.return_value = (
989 + SessionExecuteResponse.model_validate(
990 + {
991 + "data": {"sent": True},
992 + "error": None,
993 + "log_id": "log_123",
994 + "premium_charge": charge,
995 + }
996 + )
997 + )
998 + s = _session(mock_session_deps)
999 +
1000 + result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
1001 +
1002 + assert isinstance(result, ToolRouterSessionExecuteResponse)
1003 + assert isinstance(result, SessionExecuteResponse)
1004 + assert result.premium_charge == charge
1005 + assert result.data == {"sent": True}
1006 + assert result.log_id == "log_123"
1007 +
1008 + def test_execute_remote_without_premium_charge(self, mock_session_deps):
1009 + mock_session_deps[
1010 + "client"
1011 + ].tool_router.session.execute.return_value = SessionExecuteResponse(
1012 + data={"sent": True}, error=None, log_id="log_123"
1013 + )
1014 + s = _session(mock_session_deps)
1015 +
1016 + result = s.execute("GMAIL_SEND_EMAIL", arguments={"to": "a@b.com"})
1017 +
1018 + assert result.premium_charge is None
1019 +
1020 def test_execute_remote_passes_inline_custom_tools(self, mock_session_deps):
1021 mock_response = SessionExecuteResponse(
1022 data={"sent": True}, error=None, log_id="log_123"
@@ -1302,6 +1341,34 @@ class TestMultiExecuteRouting:
1341 assert result["data"]["total_count"] == 2
1342 assert result["data"]["success_count"] == 2
1343 assert result["data"]["error_count"] == 0
1344 + assert "premium_charge" not in result
1345 +
1346 + def test_mixed_preserves_remote_premium_charge(self, grep_tool):
1347 + s = self._make_session(grep_tool)
1348 + tm = MagicMock()
1349 + charge = {"amount": "0.01", "currency": "USD", "charged_by": "composio"}
1350 + remote = {
1351 + "data": {
1352 + "results": [
1353 + {"tool_slug": "R", "response": {"successful": True, "data": {}}},
1354 + ],
1355 + },
1356 + "error": None,
1357 + "successful": True,
1358 + "premium_charge": charge,
1359 + }
1360 + tm._wrap_execute_tool_for_tool_router.return_value = lambda slug, args: remote
1361 + result = s._route_multi_execute(
1362 + {
1363 + "tools": [
1364 + {"tool_slug": "GREP", "arguments": {"pattern": "x"}},
1365 + {"tool_slug": "REMOTE", "arguments": {}},
1366 + ]
1367 + },
1368 + tm,
1369 + )
1370 +
1371 + assert result["premium_charge"] == charge
1372
1373 def test_failure_propagated(self):
1374 @exp.tool()
python/tests/test_tool_router.py
+35
@@ -2040,6 +2040,41 @@ class TestToolRouterExecution:
2040 assert result["data"] == {"result": "success"}
2041 assert result["error"] is None
2042 assert result["successful"] is True
2043 + assert "premium_charge" not in result
2044 +
2045 + def test_execute_endpoint_preserves_premium_charge(
2046 + self, tool_router, mock_client, mock_provider
2047 + ):
2048 + """Provider-wrapped session tools keep the reported premium charge."""
2049 + from composio_client.types.tool_router.session_execute_response import (
2050 + SessionExecuteResponse,
2051 + )
2052 +
2053 + from composio.core.models.tools import Tools as RealTools
2054 +
2055 + charge = {"amount": "0.01", "currency": "USD", "charged_by": "composio"}
2056 + mock_client.tool_router.session.execute.return_value = (
2057 + SessionExecuteResponse.model_validate(
2058 + {
2059 + "data": {"result": "success"},
2060 + "error": None,
2061 + "log_id": "log_123",
2062 + "premium_charge": charge,
2063 + }
2064 + )
2065 + )
2066 + real_tools = RealTools(
2067 + client=mock_client,
2068 + provider=mock_provider,
2069 + dangerously_allow_auto_upload_download_files=False,
2070 + )
2071 + execute_fn = real_tools._wrap_execute_tool_for_tool_router(
2072 + session_id="session_123"
2073 + )
2074 +
2075 + result = execute_fn("GMAIL_SEND_EMAIL", {"to": "test@example.com"})
2076 +
2077 + assert result["premium_charge"] == charge
2078
2079 def test_execute_endpoint_passes_inline_custom_tools(
2080 self, tool_router, mock_client, mock_provider