@devries-cameron20 / composio Mirror · read-only / commits / 40546c36f
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 09:45 UTC

feat(core): require approval for session tools and answer input requests (PLEN-4462) (#4862)

## Summary Sessions can require the user's approval before a tool runs (experimental, Linear [PLEN-4462](https://linear.app/composio/issue/PLEN-4462/sdk-support-for-approval-mode)). The SDK already throws `ComposioToolInputRequiredError` when a call needs approval, but there is no way to set the approval rules or to send the user's answer back. This PR adds both, in TS and Python. ```ts const session = await composio.create('user_123', { tools: { gmail: { requireApproval: ['GMAIL_SEND_EMAIL'] } }, }); try { await session.execute('GMAIL_SEND_EMAIL', args); } catch (error) { if (!(error instanceof ComposioToolInputRequiredError)) throw error; // error.inputRequests: { elicit_3f9a…: { message, requestedSchema, … } } const [id] = Object.keys(error.inputRequests); await session.execute('GMAIL_SEND_EMAIL', args, { inputResponses: { [id]: { action: 'accept', content: { decision: 'approve' } } }, requestState: error.requestState, }); } ``` ## Changes - `create()` and `update()` accept `requireApproval` next to `enable`, `disable` and `tags` on `toolkits`, `tools` and `tags`, or on its own, and `experimental.noElicitationSupportFallback` (`'deny'` or `'allow'`). They map to the API's `require_approval` and `no_elicitation_support_fallback`, which the rc.13 client already types. Marked `@experimental`. - `execute()` takes `inputResponses` and `requestState` in its options. `executeMeta()` takes them as a new third argument. - The error message now says how to answer instead of "the SDK does not submit answers yet". - Python: the same, as `require_approval`, `experimental.no_elicitation_support_fallback`, and `input_responses` / `request_state` on `execute()` and `execute_meta()`. ## Type of change - [ ] Bug fix - [x] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? - TS: `pnpm --filter @composio/core typecheck` and `pnpm --filter @composio/core test` (72 files, 1825 passed). New tests check that the approval lists, the fallback and the answers reach the wire under their API names. - Python: `uv run --group dev pytest tests/test_tool_router.py` (204 passed), plus ruff and mypy on `composio/`. - Not tested against a live backend. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] 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 - [x] I added a changeset if this change affects published packages ## Additional context - `executeMeta()`'s request options move from the third argument to the fourth. It hasn't been released yet (its changeset is still pending), but it's your design, so flagging it. - `proxyExecute()` can't take answers: the API's proxy endpoint has no `input_responses` field. - Known limitation: a custom tool that calls an approval-gated tool through `ctx.execute()` doesn't pass the answers on. Repeating the custom tool call with `inputResponses` asks again and reruns the tool's own code. Left for a follow-up. - The docs page comes in a separate PR. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com> Co-authored-by: jkomyno <alberto@composio.dev>

mukund-composio committed Oct 15, 2026 at 18:42 UTC 40546c36f71625f5bb9e64a9528bad6cdbd380d6
15 files changed +630 -59
.changeset/session-tool-approvals.md new
+33
@@ -0,0 +1,33 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/slim': minor
4 +---
5 +
6 +Add experimental support for tool calls that need the user's approval.
7 +
8 +Sessions accept a `requireApproval` list next to the `toolkits`, `tools` and `tags` filters on `create()` and `update()`. A call to a matching tool doesn't run: `session.execute()` and `session.executeMeta()` throw `ComposioToolInputRequiredError` with the questions on `inputRequests`. To answer, repeat the same call with the user's answers in `inputResponses` and the error's `requestState`:
9 +
10 +```ts
11 +const session = await composio.create('user_123', {
12 + tools: { gmail: { requireApproval: ['GMAIL_SEND_EMAIL'] } },
13 +});
14 +
15 +try {
16 + await session.execute('GMAIL_SEND_EMAIL', args);
17 +} catch (error) {
18 + if (!(error instanceof ComposioToolInputRequiredError)) throw error;
19 + const inputResponses = await promptUser(error.inputRequests);
20 + await session.execute('GMAIL_SEND_EMAIL', args, {
21 + inputResponses,
22 + requestState: error.requestState,
23 + });
24 +}
25 +```
26 +
27 +`promptUser` is a placeholder for your application's consent UI. Display each request, wait for the user's response, and return the answers keyed by request ID. Forward `decline` and `cancel` responses unchanged.
28 +
29 +`experimental.noElicitationSupportFallback` (`'deny'` or `'allow'`) sets what happens to such a call when the session's MCP client can't ask the user.
30 +
31 +`session.executeMeta()` now takes these answers as its third argument, so its request options move to the fourth.
32 +
33 +The Python SDK gains the same `require_approval` lists, `experimental.no_elicitation_support_fallback`, and `input_responses` and `request_state` on `session.execute()` and `session.execute_meta()`.
python/composio/core/models/__init__.py
+2
@@ -23,6 +23,7 @@ from .tool_router_constants import SESSION_PRESET_DIRECT_TOOLS
23 from .tool_router_session import (
24 ToolRouterSession,
25 ToolRouterSessionExecuteResponse,
26 + ToolRouterInputResponse,
27 ToolRouterSessionMetaToolSlug,
28 )
29 from .tool_router_session_delete import ToolRouterSessionDeleteResponse
@@ -74,6 +75,7 @@ __all__ = [
75 "ToolRouterSession",
76 "ToolRouterSessionDeleteResponse",
77 "ToolRouterSessionExecuteResponse",
78 + "ToolRouterInputResponse",
79 "ToolRouterSessionMetaToolSlug",
80 "ToolRouterSessionFilesMount",
81 "ToolRouterSessionProxyExecuteResponse",
python/composio/core/models/tool_router.py
+80 -14
@@ -146,6 +146,10 @@ class ToolRouterToolkitsEnableConfig(te.TypedDict, total=False):
146 """
147
148 enable: t.List[str]
149 + require_approval: t.List[str]
150 + """Experimental. Toolkits whose tools need the user's approval before they
151 + run. A call that needs approval doesn't run: ``session.execute()`` raises
152 + ``ToolInputRequiredError`` with the question to show the user."""
153
154
155 class ToolRouterToolkitsDisableConfig(te.TypedDict, total=False):
@@ -156,6 +160,19 @@ class ToolRouterToolkitsDisableConfig(te.TypedDict, total=False):
160 """
161
162 disable: t.List[str]
163 + require_approval: t.List[str]
164 + """Experimental. Toolkits whose tools need the user's approval before they
165 + run. A call that needs approval doesn't run: ``session.execute()`` raises
166 + ``ToolInputRequiredError`` with the question to show the user."""
167 +
168 +
169 +class ToolRouterToolkitsRequireApprovalConfig(te.TypedDict):
170 + """Toolkit policy that only sets which toolkits need the user's approval."""
171 +
172 + require_approval: t.List[str]
173 + """Experimental. Toolkits whose tools need the user's approval before they
174 + run. A call that needs approval doesn't run: ``session.execute()`` raises
175 + ``ToolInputRequiredError`` with the question to show the user."""
176
177
178 class ToolRouterToolsEnableConfig(te.TypedDict, total=False):
@@ -166,6 +183,9 @@ class ToolRouterToolsEnableConfig(te.TypedDict, total=False):
183 """
184
185 enable: t.List[str]
186 + require_approval: t.List[str]
187 + """Experimental. Tools of this toolkit that need the user's approval
188 + before they run."""
189
190
191 class ToolRouterToolsDisableConfig(te.TypedDict, total=False):
@@ -176,6 +196,9 @@ class ToolRouterToolsDisableConfig(te.TypedDict, total=False):
196 """
197
198 disable: t.List[str]
199 + require_approval: t.List[str]
200 + """Experimental. Tools of this toolkit that need the user's approval
201 + before they run."""
202
203
204 class ToolRouterToolsTagsConfig(te.TypedDict, total=False):
@@ -188,6 +211,17 @@ class ToolRouterToolsTagsConfig(te.TypedDict, total=False):
211 """
212
213 tags: ToolRouterConfigTags
214 + require_approval: t.List[str]
215 + """Experimental. Tools of this toolkit that need the user's approval
216 + before they run."""
217 +
218 +
219 +class ToolRouterToolsRequireApprovalConfig(te.TypedDict):
220 + """Per-toolkit tool policy that only sets which tools need the user's approval."""
221 +
222 + require_approval: t.List[str]
223 + """Experimental. Tools of this toolkit that need the user's approval
224 + before they run."""
225
226
227 # Type alias for per-toolkit tool configuration
@@ -196,11 +230,14 @@ class ToolRouterToolsTagsConfig(te.TypedDict, total=False):
230 # - ToolRouterToolsEnableConfig: Dict with 'enable' key (whitelist)
231 # - ToolRouterToolsDisableConfig: Dict with 'disable' key (blacklist)
232 # - ToolRouterToolsTagsConfig: Dict with 'tags' key (filter by MCP tags)
233 +# - ToolRouterToolsRequireApprovalConfig: Dict with only 'require_approval'
234 +# Each dict can also carry an experimental 'require_approval' list.
235 ToolRouterToolsConfig = t.Union[
236 t.List[str],
237 ToolRouterToolsEnableConfig,
238 ToolRouterToolsDisableConfig,
239 ToolRouterToolsTagsConfig,
240 + ToolRouterToolsRequireApprovalConfig,
241 ]
242
243
@@ -214,6 +251,9 @@ class ToolRouterTagsEnableDisableConfig(te.TypedDict, total=False):
251
252 enable: t.Optional[t.List[ToolRouterTag]]
253 disable: t.Optional[t.List[ToolRouterTag]]
254 + require_approval: t.Optional[t.List[ToolRouterTag]]
255 + """Experimental. Tools with any of these tags need the user's approval
256 + before they run."""
257
258
259 # Type alias for tags configuration
@@ -432,6 +472,10 @@ class ToolRouterExperimentalConfig(te.TypedDict, total=False):
472 assistive_prompt: ToolRouterAssistivePromptConfig
473 custom_tools: t.List[CustomTool]
474 custom_toolkits: t.List[ExperimentalToolkit]
475 + no_elicitation_support_fallback: t.Literal["deny", "allow"]
476 + """What happens to a call that needs the user's approval when the
477 + session's MCP client can't ask the user: ``"deny"`` (the default) or
478 + ``"allow"``."""
479
480
481 @dataclass
@@ -696,24 +740,20 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
740 # Return value structure matches TagsUnionMember1: {"enable": [...]}
741 return {"enable": tags}
742 elif isinstance(tags, dict):
699 - # Object format with enable/disable
743 + # Object format with enable/disable and an approval list
744 # Only include keys that are present and not None
745 # Return value structure matches TagsUnionMember1
746 + result: session_create_params.TagsUnionMember1 = {}
747 enable_value = tags.get("enable")
748 + if enable_value is not None:
749 + result["enable"] = enable_value
750 disable_value = tags.get("disable")
704 -
705 - # Build result dict only with non-None values
706 - if enable_value is not None and disable_value is not None:
707 - return {
708 - "enable": enable_value,
709 - "disable": disable_value,
710 - }
711 - elif enable_value is not None:
712 - return {"enable": enable_value}
713 - elif disable_value is not None:
714 - return {"disable": disable_value}
715 - else:
716 - return None
751 + if disable_value is not None:
752 + result["disable"] = disable_value
753 + require_approval_value = tags.get("require_approval")
754 + if require_approval_value is not None:
755 + result["require_approval"] = require_approval_value
756 + return result or None
757
758 # Overloads: pass ``mcp=True`` to surface ``session.mcp`` in the returned
759 # type (ToolRouterSessionWithMcp). The MCP endpoint exists at runtime on
@@ -728,6 +768,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
768 t.List[str],
769 ToolRouterToolkitsEnableConfig,
770 ToolRouterToolkitsDisableConfig,
771 + ToolRouterToolkitsRequireApprovalConfig,
772 ]
773 ] = None,
774 tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None,
@@ -758,6 +799,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
799 t.List[str],
800 ToolRouterToolkitsEnableConfig,
801 ToolRouterToolkitsDisableConfig,
802 + ToolRouterToolkitsRequireApprovalConfig,
803 ]
804 ] = None,
805 tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None,
@@ -787,6 +829,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
829 t.List[str],
830 ToolRouterToolkitsEnableConfig,
831 ToolRouterToolkitsDisableConfig,
832 + ToolRouterToolkitsRequireApprovalConfig,
833 ]
834 ] = None,
835 tools: t.Optional[t.Dict[str, ToolRouterToolsConfig]] = None,
@@ -817,6 +860,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
860 Example: {'enable': ['github', 'slack']}
861 - ToolRouterToolkitsDisableConfig: Dict with 'disable' key.
862 Example: {'disable': ['linear']}
863 + Experimental: any dict can carry 'require_approval', the
864 + toolkits whose tools need the user's approval, or have
865 + only that key. Example: {'require_approval': ['gmail']}
866 :param tools: Optional per-toolkit tool configuration. Key is toolkit slug,
867 value is ToolRouterToolsConfig which can be:
868 - List[str]: List of tool slugs (shorthand for enable).
@@ -835,6 +881,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
881 'slack': {'disable': ['SLACK_DELETE_MESSAGE']},
882 'linear': {'tags': ['readOnlyHint']}
883 }
884 + Experimental: any dict can carry 'require_approval', the
885 + tools that need the user's approval, or have only that key.
886 + Example: {'gmail': {'require_approval': ['GMAIL_SEND_EMAIL']}}
887 :param tags: Optional global MCP tags to filter tools by.
888 Can be:
889 - List[str]: List of tag literals (shorthand for enable).
@@ -844,6 +893,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
893 Available tag values: 'readOnlyHint', 'createHint',
894 'updateHint', 'destructiveHint', 'idempotentHint',
895 'openWorldHint'.
896 + Experimental: the dict can also carry 'require_approval',
897 + tags whose tools need the user's approval.
898 + Example: {'require_approval': ['destructiveHint']}
899 Toolkit-level tags override this global setting.
900 :param manage_connections: Optional connection management configuration. Can be:
901 - bool: Simple boolean to enable/disable.
@@ -908,6 +960,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
960 - 'user_timezone' (str): IANA timezone identifier
961 (e.g., "America/New_York", "Europe/London").
962 - 'custom_tools' / 'custom_toolkits': SDK custom tools.
963 + - 'no_elicitation_support_fallback' ('deny' or 'allow'):
964 + what happens to a call that needs approval when the
965 + session's MCP client can't ask the user.
966 Set preload=True on a custom tool or toolkit to expose
967 it directly from session.tools(); otherwise custom tools
968 remain search-only.
@@ -1093,6 +1148,13 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1148 # config is ToolRouterToolsDisableConfig when "disable" is present
1149 disable_config = t.cast(ToolRouterToolsDisableConfig, config)
1150 transformed_config["disable"] = disable_config["disable"]
1151 + if "require_approval" in config:
1152 + approval_config = t.cast(
1153 + ToolRouterToolsRequireApprovalConfig, config
1154 + )
1155 + transformed_config["require_approval"] = approval_config[
1156 + "require_approval"
1157 + ]
1158 # Use type guard to narrow the type when "tags" is present
1159 if _is_tools_tags_config(config):
1160 # Type narrowed: config is now ToolRouterToolsTagsConfig
@@ -1203,6 +1265,10 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1265 "user_timezone": user_timezone,
1266 }
1267
1268 + fallback = experimental.get("no_elicitation_support_fallback")
1269 + if fallback is not None:
1270 + experimental_payload["no_elicitation_support_fallback"] = fallback
1271 +
1272 # Serialize custom tools and toolkits for the backend
1273 custom_tools = experimental.get("custom_tools")
1274 custom_toolkits = experimental.get("custom_toolkits")
python/composio/core/models/tool_router_session.py
+36
@@ -22,6 +22,7 @@ from composio_client.types.tool_list_response import (
22 )
23 from composio_client.types.tool_router import (
24 session_create_response,
25 + session_execute_params,
26 session_link_params,
27 session_patch_params,
28 session_search_response,
@@ -178,6 +179,14 @@ ToolRouterSessionExecuteResponse = SessionExecuteResponse
179 only when the Session sets ``instant.return_instant_charge`` and a charge is
180 available."""
181
182 +ToolRouterInputResponse = session_execute_params.CurrentInputResponsesValue
183 +"""Experimental. The user's answer to one question of a
184 +``ToolInputRequiredError``, in the shape of an MCP elicitation result:
185 +``action`` is ``"accept"`` with the form's fields in ``content``, ``"decline"``
186 +when they said no, or ``"cancel"`` when they dismissed it. For an approval,
187 +``content`` is ``{"decision": "approve"}``, ``{"decision": "always_approve"}``
188 +or ``{"decision": "deny"}``."""
189 +
190 ToolRouterSessionMetaToolSlug = t.Literal[
191 "COMPOSIO_SEARCH_TOOLS",
192 "COMPOSIO_MULTI_EXECUTE_TOOL",
@@ -237,6 +246,9 @@ class ToolRouterUpdateExperimentalConfig(te.TypedDict, total=False):
246 fast_mode: t.Optional[bool]
247 submit_feedback: t.Optional[t.Dict[str, bool]]
248 session_config_id: str
249 + no_elicitation_support_fallback: t.Literal["deny", "allow"]
250 + """What happens to a call that needs the user's approval when the
251 + session's MCP client can't ask the user: ``"deny"`` or ``"allow"``."""
252
253
254 class ToolRouterSession(t.Generic[TTool, TToolCollection]):
@@ -934,6 +946,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
946 *,
947 arguments: t.Optional[t.Dict[str, t.Any]] = None,
948 account: t.Optional[str] = None,
949 + input_responses: t.Optional[t.Dict[str, ToolRouterInputResponse]] = None,
950 + request_state: t.Optional[str] = None,
951 ) -> ToolRouterSessionExecuteResponse:
952 """
953 Execute a tool within the session.
@@ -946,6 +960,13 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
960 :param account: Account ID or alias for direct app tool execution in
961 multi-account sessions. Helper/meta tools either ignore this
962 top-level field or define their own account-selection fields.
963 + :param input_responses: Experimental. The user's answers to an earlier
964 + ``ToolInputRequiredError``, keyed by the IDs in its
965 + ``input_requests``. Repeat the same call (same tool and arguments)
966 + with them. An approved call runs; a denied or declined one returns
967 + ``result_type="failed"``.
968 + :param request_state: Experimental. The ``request_state`` of that
969 + error, sent back unchanged.
970
971 Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
972 ``error``, ``log_id``, ``result_type``, and ``instant_charge``
@@ -979,6 +1000,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1000 tool_slug=tool_slug,
1001 arguments=arguments if arguments is not None else omit,
1002 account=account if account is not None else omit,
1003 + input_responses=(
1004 + input_responses if input_responses is not None else omit
1005 + ),
1006 + request_state=request_state if request_state is not None else omit,
1007 experimental=inline_custom_tools_execute_experimental(
1008 self._inline_custom_tools_payload
1009 ),
@@ -991,6 +1016,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1016 slug: ToolRouterSessionMetaToolSlug,
1017 *,
1018 arguments: t.Optional[t.Dict[str, t.Any]] = None,
1019 + input_responses: t.Optional[t.Dict[str, ToolRouterInputResponse]] = None,
1020 + request_state: t.Optional[str] = None,
1021 ) -> ToolRouterSessionExecuteResponse:
1022 """
1023 Execute a Composio meta tool (``COMPOSIO_*``) within the session.
@@ -1002,6 +1029,11 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1029
1030 :param slug: The meta tool slug to execute.
1031 :param arguments: Optional meta tool arguments.
1032 + :param input_responses: Experimental. The user's answers to an earlier
1033 + ``ToolInputRequiredError``, keyed by the IDs in its
1034 + ``input_requests``. Repeat the same call with them, as in :meth:`execute`.
1035 + :param request_state: Experimental. The ``request_state`` of that
1036 + error, sent back unchanged.
1037 :returns: The tool execution result, in the same shape as
1038 :meth:`execute`.
1039 :raises ToolInputRequiredError: If the tool needs input from the user
@@ -1023,6 +1055,10 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1055 session_id=self.session_id,
1056 slug=slug,
1057 arguments=arguments if arguments is not None else omit,
1058 + input_responses=(
1059 + input_responses if input_responses is not None else omit
1060 + ),
1061 + request_state=request_state if request_state is not None else omit,
1062 experimental=inline_custom_tools_execute_meta_experimental(
1063 self._inline_custom_tools_payload
1064 ),
python/composio/exceptions.py
+6 -4
@@ -406,8 +406,9 @@ class ToolInputRequiredError(ComposioClientError):
406
407 ``input_requests`` holds the questions, keyed by the ID the answers must
408 reuse. ``request_state`` is the opaque state the API returned; when present
409 - it must be sent back unchanged together with the answers. The SDK does not
410 - submit answers yet, so nothing was executed and the call is not retried.
409 + it must be sent back unchanged together with the answers. Nothing was
410 + executed and the call is not retried: to answer, repeat the same call with
411 + ``input_responses`` and ``request_state``.
412
413 ``request_state`` is continuation state, so it is kept out of logs: read it
414 as an attribute. ``str()``, ``repr()``, ``args`` and a formatted traceback
@@ -425,8 +426,9 @@ class ToolInputRequiredError(ComposioClientError):
426 super().__init__(
427 f"{subject} requires user input before it can run "
428 f"({count} input request{'' if count == 1 else 's'}) and was not "
428 - "executed. The questions are on `input_requests` and the opaque "
429 - "`request_state` to send back with the answers is on `request_state`."
429 + "executed. The questions are on `input_requests`. Repeat the call "
430 + "with the answers in `input_responses` and this error's "
431 + "`request_state`."
432 )
433 self.input_requests = input_requests
434 self.request_state = request_state
python/tests/test_tool_router.py
+124
@@ -1449,6 +1449,8 @@ class TestToolRouter:
1449 tool_slug="GMAIL_FETCH_EMAILS",
1450 arguments={"max_results": 1},
1451 account="work",
1452 + input_responses=omit,
1453 + request_state=omit,
1454 experimental=omit,
1455 )
1456
@@ -2518,6 +2520,128 @@ def _created_session(client: HttpClient) -> ToolRouterSession:
2520 return ToolRouter(client=client, provider=MagicMock()).create(user_id="user_123")
2521
2522
2523 +_APPROVAL_ANSWERS: t.Dict[str, t.Any] = {
2524 + "approval_1": {"action": "accept", "content": {"decision": "approve"}},
2525 +}
2526 +
2527 +_COMPLETED_JSON: t.Dict[str, t.Any] = {
2528 + "result_type": "completed",
2529 + "data": {"id": "msg_1"},
2530 + "error": None,
2531 + "log_id": "log_1",
2532 +}
2533 +
2534 +
2535 +class TestAnsweringInputRequired:
2536 + """The answers to an ``input_required`` call travel on the repeated call
2537 + as ``input_responses``, with the ``request_state`` it returned."""
2538 +
2539 + @pytest.mark.parametrize(
2540 + "run",
2541 + [
2542 + pytest.param(
2543 + lambda session: session.execute(
2544 + "GMAIL_SEND_EMAIL",
2545 + arguments={"to": "test@test.com"},
2546 + input_responses=_APPROVAL_ANSWERS,
2547 + request_state="opaque-state-token",
2548 + ),
2549 + id="session.execute",
2550 + ),
2551 + pytest.param(
2552 + lambda session: session.execute_meta(
2553 + "COMPOSIO_MULTI_EXECUTE_TOOL",
2554 + arguments={"tools": []},
2555 + input_responses=_APPROVAL_ANSWERS,
2556 + request_state="opaque-state-token",
2557 + ),
2558 + id="session.execute_meta",
2559 + ),
2560 + ],
2561 + )
2562 + def test_sends_the_answers_and_the_request_state(self, run):
2563 + client, requests = _answering_client(_COMPLETED_JSON)
2564 +
2565 + run(_created_session(client))
2566 +
2567 + body = json.loads(requests[0].content)
2568 + assert body["input_responses"] == _APPROVAL_ANSWERS
2569 + assert body["request_state"] == "opaque-state-token"
2570 +
2571 + def test_sends_neither_field_without_answers(self):
2572 + client, requests = _answering_client(_COMPLETED_JSON)
2573 +
2574 + _created_session(client).execute("GMAIL_SEND_EMAIL")
2575 +
2576 + body = json.loads(requests[0].content)
2577 + assert "input_responses" not in body
2578 + assert "request_state" not in body
2579 +
2580 +
2581 +class TestApprovalRules:
2582 + """``require_approval`` lists and the no-elicitation fallback reach the
2583 + API next to the filters they belong to."""
2584 +
2585 + def test_create_sends_approval_lists_and_fallback(self):
2586 + client, requests = _transport_client(
2587 + api_key="ak_test", base_url="https://backend.composio.dev"
2588 + )
2589 +
2590 + ToolRouter(client=client, provider=MagicMock()).create(
2591 + user_id="user_123",
2592 + toolkits={"enable": ["gmail", "github"], "require_approval": ["github"]},
2593 + tools={
2594 + "gmail": {"require_approval": ["GMAIL_SEND_EMAIL"]},
2595 + "notion": {
2596 + "enable": ["NOTION_CREATE_PAGE"],
2597 + "require_approval": ["NOTION_CREATE_PAGE"],
2598 + },
2599 + "slack": {"tags": {"require_approval": ["destructiveHint"]}},
2600 + },
2601 + tags={
2602 + "disable": ["openWorldHint"],
2603 + "require_approval": ["destructiveHint"],
2604 + },
2605 + experimental={"no_elicitation_support_fallback": "allow"},
2606 + )
2607 +
2608 + body = json.loads(requests[0].content)
2609 + assert body["toolkits"] == {
2610 + "enable": ["gmail", "github"],
2611 + "require_approval": ["github"],
2612 + }
2613 + assert body["tools"] == {
2614 + "gmail": {"require_approval": ["GMAIL_SEND_EMAIL"]},
2615 + "notion": {
2616 + "enable": ["NOTION_CREATE_PAGE"],
2617 + "require_approval": ["NOTION_CREATE_PAGE"],
2618 + },
2619 + "slack": {"tags": {"require_approval": ["destructiveHint"]}},
2620 + }
2621 + assert body["tags"] == {
2622 + "disable": ["openWorldHint"],
2623 + "require_approval": ["destructiveHint"],
2624 + }
2625 + assert body["experimental"] == {"no_elicitation_support_fallback": "allow"}
2626 +
2627 + def test_update_sends_approval_lists_and_fallback(self):
2628 + client, requests = _transport_client(
2629 + api_key="ak_test", base_url="https://backend.composio.dev"
2630 + )
2631 + session = ToolRouter(client=client, provider=MagicMock()).create(
2632 + user_id="user_123"
2633 + )
2634 +
2635 + session.update(
2636 + toolkits={"require_approval": ["gmail"]},
2637 + experimental={"no_elicitation_support_fallback": "deny"},
2638 + )
2639 +
2640 + body = json.loads(requests[-1].content)
2641 + assert body["toolkits"] == {"require_approval": ["gmail"]}
2642 + assert body["experimental"] == {"no_elicitation_support_fallback": "deny"}
2643 +
2644 +
2645 class TestExecutionRequiresUserInput:
2646 """``result_type: "input_required"`` carries no data, log ID or HTTP status,
2647 so every execution path raises it instead of returning it as a result.
ts/packages/core/src/errors/ToolRouterErrors.ts
+5 -5
@@ -80,9 +80,9 @@ export class ComposioSessionConfigConflictError extends ComposioError {
80 *
81 * `inputRequests` holds the questions, keyed by the ID the answers must
82 * reuse. `requestState` is the opaque `request_state` the API returned; when
83 - * present it must be sent back unchanged together with the answers. The SDK
84 - * does not submit answers yet, so nothing was executed and the call is not
85 - * retried.
83 + * present it must be sent back unchanged together with the answers. Nothing
84 + * was executed and the call is not retried: to answer, repeat the same call
85 + * with `inputResponses` and `requestState` in its options.
86 */
87 export class ComposioToolInputRequiredError extends ComposioError {
88 /** Questions for the user, keyed by the ID the answers must reuse. */
@@ -104,12 +104,12 @@ export class ComposioToolInputRequiredError extends ComposioError {
104 const count = Object.keys(details.inputRequests).length;
105 super(
106 `${subject} requires user input before it can run (${count} input request${count === 1 ? '' : 's'}) and was not executed. ` +
107 - 'The questions are on `inputRequests` and the opaque `request_state` to send back with the answers is on `requestState`.',
107 + "The questions are on `inputRequests`. Repeat the call with the answers in `inputResponses` and this error's `requestState`.",
108 {
109 ...options,
110 code: ToolRouterErrorCodes.TOOL_INPUT_REQUIRED,
111 possibleFixes: options.possibleFixes ?? [
112 - 'Collect the answers described by `inputRequests`, then call the session execute endpoint again with `input_responses` and the unchanged `request_state`',
112 + 'Collect the answers described by `inputRequests`, then repeat the same call with `{ inputResponses, requestState }` in its options',
113 'Remove the tool, its toolkit or its tags from the `require_approval` lists of the session configuration if no approval is intended',
114 ],
115 }
ts/packages/core/src/lib/toolRouterParams.ts
+28 -16
@@ -29,14 +29,18 @@ type ParsedCreateSessionConfig = TypeOf<typeof ToolRouterCreateSessionConfigSche
29 /** Parsed update input; the public `ToolRouterUpdateSessionConfig` is a union over it. */
30 type ParsedUpdateSessionConfig = TypeOf<typeof ToolRouterUpdateSessionConfigSchema>;
31
32 +/** A toolkit's entry in the session `tools` map, as sent on create and update. */
33 +type SessionToolsEntry = NonNullable<SessionCreateParams['tools']>[string];
34 +
35 +/** `require_approval` when the caller set an approval list, nothing otherwise. */
36 +const requireApprovalParam = <T extends string>(
37 + requireApproval: T[] | undefined
38 +): { require_approval?: T[] } =>
39 + requireApproval !== undefined ? { require_approval: requireApproval } : {};
40 +
41 export const transformToolRouterToolsParams = (
42 params?: Record<string, ToolRouterToolsParam | ToolRouterConfigTools> | undefined
34 -):
35 - | Record<
36 - string,
37 - SessionCreateParams.Enable | SessionCreateParams.Disable | SessionCreateParams.Tags
38 - >
39 - | undefined => {
43 +): Record<string, SessionToolsEntry> | undefined => {
44 if (!params) {
45 return undefined;
46 }
@@ -53,14 +57,16 @@ export const transformToolRouterToolsParams = (
57 if (Array.isArray(data)) {
58 acc[key] = { enable: data };
59 } else if ('enable' in data) {
56 - acc[key] = { enable: data.enable };
60 + acc[key] = { enable: data.enable, ...requireApprovalParam(data.requireApproval) };
61 } else if ('disable' in data) {
58 - acc[key] = { disable: data.disable };
62 + acc[key] = { disable: data.disable, ...requireApprovalParam(data.requireApproval) };
63 } else if ('tags' in data) {
64 const tags = transformToolRouterTagsParams(data.tags);
65 if (tags) {
62 - acc[key] = { tags };
66 + acc[key] = { tags, ...requireApprovalParam(data.requireApproval) };
67 }
68 + } else {
69 + acc[key] = { require_approval: data.requireApproval };
70 }
71 } else {
72 throw new ValidationError(parsedResult.error.message);
@@ -70,10 +76,7 @@ export const transformToolRouterToolsParams = (
76 }
77 return acc;
78 },
73 - {} as Record<
74 - string,
75 - SessionCreateParams.Enable | SessionCreateParams.Disable | SessionCreateParams.Tags
76 - >
79 + {} as Record<string, SessionToolsEntry>
80 );
81 return result;
82 }
@@ -91,6 +94,7 @@ export const transformToolRouterTagsParams = (
94 return {
95 enable: params.enable,
96 disable: params.disable,
97 + ...requireApprovalParam(params.requireApproval),
98 };
99 }
100 };
@@ -276,6 +280,9 @@ const transformToolRouterUpdateExperimentalParams = (
280 if (config.sessionConfigId !== undefined) {
281 result.session_config_id = config.sessionConfigId;
282 }
283 + if (config.noElicitationSupportFallback !== undefined) {
284 + result.no_elicitation_support_fallback = config.noElicitationSupportFallback;
285 + }
286 return result;
287 };
288
@@ -332,7 +339,7 @@ export const transformToolRouterMultiAccountParams = (
339
340 export const transformToolRouterToolkitsParams = (
341 params?: ParsedCreateSessionConfig['toolkits']
335 -): SessionCreateParams.Enable | SessionCreateParams.Disable | undefined => {
342 +): NonNullable<SessionCreateParams['toolkits']> | undefined => {
343 if (!params) {
344 return undefined;
345 }
@@ -342,8 +349,13 @@ export const transformToolRouterToolkitsParams = (
349 return { enable: params };
350 }
351
345 - // Otherwise return as-is (already in enable/disable format)
346 - return params as SessionCreateParams.Enable | SessionCreateParams.Disable;
352 + if ('enable' in params) {
353 + return { enable: params.enable, ...requireApprovalParam(params.requireApproval) };
354 + }
355 + if ('disable' in params) {
356 + return { disable: params.disable, ...requireApprovalParam(params.requireApproval) };
357 + }
358 + return { require_approval: params.requireApproval };
359 };
360
361 /**
ts/packages/core/src/models/ToolRouter.ts
+5
@@ -240,6 +240,11 @@ export class ToolRouter<
240 experimentalPayload.session_config_id = routerConfig.experimental.sessionConfigId;
241 }
242
243 + if (routerConfig.experimental?.noElicitationSupportFallback !== undefined) {
244 + experimentalPayload.no_elicitation_support_fallback =
245 + routerConfig.experimental.noElicitationSupportFallback;
246 + }
247 +
248 if (routerConfig.experimental?.assistivePrompt?.userTimezone) {
249 experimentalPayload.assistive_prompt_config = {
250 user_timezone: routerConfig.experimental.assistivePrompt.userTimezone,
ts/packages/core/src/models/ToolRouterSession.ts
+17
@@ -21,6 +21,7 @@ import {
21 ToolRouterSessionExecuteResponseSchema,
22 ToolRouterSessionProxyExecuteResponse,
23 ToolRouterSessionExecuteOptions,
24 + ToolRouterSessionExecuteMetaOptions,
25 ToolRouterSessionMetaToolSlug,
26 ToolRouterSessionConfig,
27 ToolRouterSessionMetadata,
@@ -98,6 +99,16 @@ import { getSourceSessionConfig } from '../lib/toolRouterSourceSessionConfig';
99 import { deleteToolRouterSession } from '../lib/toolRouterSessionDelete';
100
101 const COMPOSIO_MULTI_EXECUTE_TOOL = 'COMPOSIO_MULTI_EXECUTE_TOOL';
102 +
103 +/** The request fields that carry the user's answers to an earlier `input_required` call. */
104 +function inputResponseParams(
105 + options: ToolRouterSessionExecuteMetaOptions | undefined
106 +): Pick<SessionExecuteParams, 'input_responses' | 'request_state'> {
107 + return {
108 + ...(options?.inputResponses !== undefined && { input_responses: options.inputResponses }),
109 + ...(options?.requestState !== undefined && { request_state: options.requestState }),
110 + };
111 +}
112 export const DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX =
113 '[Direct tool - call directly, no search needed beforehand.]';
114
@@ -684,6 +695,8 @@ export class ToolRouterSession<
695 * @param arguments_ - Optional tool arguments
696 * @param options - Optional execution options
697 * @param options.account - Account identifier for direct app tool execution. Accepted on every project: in multi-account sessions it picks the account; on single-account projects it must match one of the session's active connections for the toolkit. Helper/meta tools either ignore this top-level field or define their own account-selection fields.
698 + * @param options.inputResponses - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError`, keyed by the IDs in its `inputRequests`. Repeat the same call with them.
699 + * @param options.requestState - Experimental. The `requestState` of that error, sent back unchanged.
700 * @returns The tool execution result
701 * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
702 */
@@ -720,6 +733,7 @@ export class ToolRouterSession<
733 const executeParams: SessionExecuteParams = {
734 tool_slug: toolSlug,
735 arguments: arguments_ ?? {},
736 + ...inputResponseParams(options),
737 };
738 if (options?.account) {
739 executeParams.account = options.account;
@@ -754,6 +768,7 @@ export class ToolRouterSession<
768 *
769 * @param slug - The meta tool slug to execute
770 * @param arguments_ - Optional meta tool arguments
771 + * @param options - Experimental. The user's answers to an earlier `ComposioToolInputRequiredError` (`inputResponses`) and its `requestState`, as in `session.execute()`
772 * @returns The tool execution result, in the same shape as `session.execute()`
773 * @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
774 *
@@ -767,11 +782,13 @@ export class ToolRouterSession<
782 async executeMeta(
783 slug: ToolRouterSessionMetaToolSlug,
784 arguments_?: Record<string, unknown>,
785 + options?: ToolRouterSessionExecuteMetaOptions,
786 requestOptions?: ComposioRequestOptions
787 ): Promise<ToolRouterSessionExecuteResponse> {
788 const executeMetaParams: SessionExecuteMetaParams = {
789 slug,
790 arguments: arguments_ ?? {},
791 + ...inputResponseParams(options),
792 };
793 const experimental = inlineCustomToolsExperimental<SessionExecuteMetaParams.Experimental>(
794 this.inlineCustomToolsPayload
ts/packages/core/src/types/toolRouter.types.ts
+103 -17
@@ -9,6 +9,7 @@ import type {
9 SessionConfigHistoryResponse,
10 SessionCreateResponse,
11 SessionExecuteMetaParams,
12 + SessionExecuteParams,
13 } from '@composio/client/resources/tool-router/session/session.mjs';
14 import type {
15 CustomTool,
@@ -109,6 +110,39 @@ export const ToolRouterToolkitsEnabledConfigSchema = z
110 })
111 .strict();
112
113 +/**
114 + * Toolkits whose tools need the user's approval before they run. A call that
115 + * needs approval doesn't run: `session.execute()` throws
116 + * `ComposioToolInputRequiredError` with the question to show the user.
117 + * @experimental
118 + */
119 +const ToolRouterToolkitsRequireApprovalSchema = ToolRouterToolkitsParamSchema.describe(
120 + 'Experimental. Toolkits whose tools need the user approval before they run'
121 +);
122 +
123 +/** Session toolkit policy: a list to enable, an enable/disable object, or only an approval list. */
124 +const ToolRouterSessionToolkitsSchema = z.union([
125 + ToolRouterToolkitsParamSchema,
126 + ToolRouterToolkitsDisabledConfigSchema.extend({
127 + requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional(),
128 + }).strict(),
129 + ToolRouterToolkitsEnabledConfigSchema.extend({
130 + requireApproval: ToolRouterToolkitsRequireApprovalSchema.optional(),
131 + }).strict(),
132 + z.object({ requireApproval: ToolRouterToolkitsRequireApprovalSchema }).strict(),
133 +]);
134 +
135 +/**
136 + * What happens to a call that needs the user's approval when the session's MCP
137 + * client can't ask the user.
138 + * @experimental
139 + */
140 +const ToolRouterNoElicitationSupportFallbackSchema = z
141 + .enum(['deny', 'allow'])
142 + .describe(
143 + 'Experimental. What happens to a call that needs approval when the MCP client cannot ask the user'
144 + );
145 +
146 /** Experimental Instant usage policy for a Session. */
147 export const ToolRouterInstantSchema = z.union([
148 z.literal(false),
@@ -175,6 +209,13 @@ export const ToolRouterTagsEnableDisableSchema = z
209 disable: ToolRouterTagsParamSchema.optional().describe(
210 'The tags to disable in the tool router session'
211 ),
212 + /**
213 + * Tools with any of these tags need the user's approval before they run.
214 + * @experimental
215 + */
216 + requireApproval: ToolRouterTagsParamSchema.optional().describe(
217 + 'Experimental. Tools with any of these tags need the user approval before they run'
218 + ),
219 })
220 .strict();
221 export const ToolRouterConfigTagsSchema = z
@@ -209,6 +250,14 @@ export const ToolRouterToolsParamSchema = z
250 .describe('The tools to use in the tool router session');
251 export type ToolRouterToolsParam = z.infer<typeof ToolRouterToolsParamSchema>;
252
253 +/**
254 + * Tools of the toolkit that need the user's approval before they run.
255 + * @experimental
256 + */
257 +const ToolRouterToolsRequireApprovalSchema = ToolRouterToolsParamSchema.describe(
258 + 'Experimental. Tools of this toolkit that need the user approval before they run'
259 +);
260 +
261 export const ToolRouterConfigToolsSchema = z
262 .union([
263 ToolRouterToolsParamSchema,
@@ -217,6 +266,7 @@ export const ToolRouterConfigToolsSchema = z
266 enable: ToolRouterToolsParamSchema.describe(
267 'The tools to enable in the tool router session'
268 ),
269 + requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
270 })
271 .strict(),
272 z
@@ -224,6 +274,7 @@ export const ToolRouterConfigToolsSchema = z
274 disable: ToolRouterToolsParamSchema.describe(
275 'The tools to disable in the tool router session'
276 ),
277 + requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
278 })
279 .strict(),
280 z
@@ -231,13 +282,15 @@ export const ToolRouterConfigToolsSchema = z
282 tags: ToolRouterConfigTagsSchema.describe(
283 'The tags to filter the tools by, this will override the global tags'
284 ),
285 + requireApproval: ToolRouterToolsRequireApprovalSchema.optional(),
286 })
287 .strict(),
288 + z.object({ requireApproval: ToolRouterToolsRequireApprovalSchema }).strict(),
289 ])
290 .superRefine((val, ctx) => {
238 - // If it's an object (not an array), ensure only one property is present
291 + // If it's an object (not an array), allow at most one of enable, disable and tags
292 if (typeof val === 'object' && !Array.isArray(val)) {
240 - const keys = Object.keys(val);
293 + const keys = Object.keys(val).filter(key => key !== 'requireApproval');
294 if (keys.length > 1) {
295 ctx.addIssue({
296 code: z.ZodIssueCode.custom,
@@ -299,14 +352,9 @@ const ToolRouterCreateSessionConfigBaseSchema = z
352
353 tags: ToolRouterConfigTagsSchema.optional().describe('Global tags to filter the tools by'),
354
302 - toolkits: z
303 - .union([
304 - ToolRouterToolkitsParamSchema,
305 - ToolRouterToolkitsDisabledConfigSchema,
306 - ToolRouterToolkitsEnabledConfigSchema,
307 - ])
308 - .optional()
309 - .describe('The toolkits to use in the tool router session'),
355 + toolkits: ToolRouterSessionToolkitsSchema.optional().describe(
356 + 'The toolkits to use in the tool router session'
357 + ),
358
359 instant: ToolRouterInstantSchema.optional().describe(
360 'Experimental Instant usage policy. Omission permits eligible tools when the project allows Instant usage; false disables it for this Session.'
@@ -411,6 +459,13 @@ const ToolRouterCreateSessionConfigBaseSchema = z
459 .describe(
460 'ID of a saved Session config (`sc_…`) to apply when the session is created. Cannot be combined with toolkits, tools, tags, customTools or customToolkits.'
461 ),
462 + /**
463 + * What happens to a call that needs the user's approval when the
464 + * session's MCP client can't ask the user: `deny` (the default) or
465 + * `allow`.
466 + * @experimental
467 + */
468 + noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
469 })
470 .optional()
471 .describe('Experimental features configuration - not stable, may be modified or removed'),
@@ -773,17 +828,48 @@ export interface ToolRouterSessionExecuteOptions {
828 * COMPOSIO_MULTI_EXECUTE_TOOL.tools[].account.
829 */
830 account?: string;
831 + /**
832 + * The user's answers to the questions of a `ComposioToolInputRequiredError`,
833 + * keyed by the IDs in its `inputRequests`. Send them by repeating the same
834 + * call (same tool and arguments). An approved call runs; a denied or
835 + * declined one returns `resultType: 'failed'`.
836 + * @experimental
837 + */
838 + inputResponses?: Record<string, ToolRouterInputResponse>;
839 + /**
840 + * The `requestState` of the `ComposioToolInputRequiredError`, sent back
841 + * unchanged with `inputResponses`.
842 + * @experimental
843 + */
844 + requestState?: string;
845 }
846
847 +/**
848 + * The user's answer to one question, in the shape of an MCP elicitation
849 + * result: `accept` with the form's fields in `content`, `decline` when they
850 + * said no, or `cancel` when they dismissed it. For an approval, `content` is
851 + * `{ decision: 'approve' }`, `{ decision: 'always_approve' }` or
852 + * `{ decision: 'deny' }`.
853 + * @experimental
854 + */
855 +export type ToolRouterInputResponse = NonNullable<SessionExecuteParams['input_responses']>[string];
856 +
857 /**
858 * Slug of a Composio meta tool (`COMPOSIO_*`) that `session.executeMeta()` can
859 * run, for example `COMPOSIO_SEARCH_TOOLS`.
860 */
861 export type ToolRouterSessionMetaToolSlug = SessionExecuteMetaParams['slug'];
862
863 +/** Options for `session.executeMeta()`: the user's answers to an earlier `input_required` call. */
864 +export type ToolRouterSessionExecuteMetaOptions = Pick<
865 + ToolRouterSessionExecuteOptions,
866 + 'inputResponses' | 'requestState'
867 +>;
868 +
869 export type ToolRouterSessionExecuteMetaFn = (
870 slug: ToolRouterSessionMetaToolSlug,
871 arguments_?: Record<string, unknown>,
872 + options?: ToolRouterSessionExecuteMetaOptions,
873 requestOptions?: ComposioRequestOptions
874 ) => Promise<ToolRouterSessionExecuteResponse>;
875
@@ -925,6 +1011,12 @@ export const ToolRouterUpdateExperimentalSchema = z
1011 .describe(
1012 'Exposes the COMPOSIO_SUBMIT_FEEDBACK helper tool. `null` removes the stored block'
1013 ),
1014 + /**
1015 + * What happens to a call that needs the user's approval when the session's
1016 + * MCP client can't ask the user: `deny` or `allow`.
1017 + * @experimental
1018 + */
1019 + noElicitationSupportFallback: ToolRouterNoElicitationSupportFallbackSchema.optional(),
1020 sessionConfigId: z
1021 .string()
1022 .min(1)
@@ -947,13 +1039,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
1039 instant: ToolRouterInstantSchema.optional().describe(
1040 'Experimental Instant usage policy. False disables it. Any supplied object, even one that only sets returnInstantCharge, re-enables it. Omitted subfields keep their stored values.'
1041 ),
950 - toolkits: z
951 - .union([
952 - ToolRouterToolkitsParamSchema,
953 - ToolRouterToolkitsDisabledConfigSchema,
954 - ToolRouterToolkitsEnabledConfigSchema,
955 - ])
956 - .nullable()
1042 + toolkits: ToolRouterSessionToolkitsSchema.nullable()
1043 .optional()
1044 .describe(
1045 'Toolkit policy. An empty allowlist (`[]` or `{ enable: [] }`) is sent as-is and denies every app toolkit; `null` removes the stored policy and restores the unrestricted default'
ts/packages/core/test/lib/toolRouterParams.test.ts
+70 -1
@@ -2,9 +2,13 @@ import { describe, it, expect } from 'vitest';
2 import {
3 transformToolRouterTagsParams,
4 transformToolRouterMultiAccountParams,
5 + transformToolRouterToolsParams,
6 transformToolRouterUpdateParams,
7 } from '../../src/lib/toolRouterParams';
7 -import { ToolRouterConfigTags } from '../../src/types/toolRouter.types';
8 +import {
9 + ToolRouterConfigTags,
10 + ToolRouterConfigToolsSchema,
11 +} from '../../src/types/toolRouter.types';
12
13 describe('transformToolRouterMultiAccountParams', () => {
14 it('should return undefined when params is undefined', () => {
@@ -444,3 +448,68 @@ describe('transformToolRouterUpdateParams', () => {
448 expect(mc).toHaveProperty('callback_url', 'https://example.com');
449 });
450 });
451 +
452 +describe('approval lists', () => {
453 + it('maps requireApproval next to each toolkit, tool and tag filter', () => {
454 + expect(
455 + transformToolRouterUpdateParams({
456 + toolkits: { disable: ['slack'], requireApproval: ['github'] },
457 + tools: {
458 + gmail: { enable: ['GMAIL_SEND_EMAIL'], requireApproval: ['GMAIL_SEND_EMAIL'] },
459 + github: { disable: ['GITHUB_DELETE_A_REPOSITORY'], requireApproval: ['GITHUB_MERGE'] },
460 + notion: { tags: ['readOnlyHint'], requireApproval: ['NOTION_CREATE_PAGE'] },
461 + },
462 + tags: { disable: ['openWorldHint'], requireApproval: ['destructiveHint'] },
463 + })
464 + ).toEqual({
465 + toolkits: { disable: ['slack'], require_approval: ['github'] },
466 + tools: {
467 + gmail: { enable: ['GMAIL_SEND_EMAIL'], require_approval: ['GMAIL_SEND_EMAIL'] },
468 + github: { disable: ['GITHUB_DELETE_A_REPOSITORY'], require_approval: ['GITHUB_MERGE'] },
469 + notion: { tags: { enable: ['readOnlyHint'] }, require_approval: ['NOTION_CREATE_PAGE'] },
470 + },
471 + tags: { disable: ['openWorldHint'], require_approval: ['destructiveHint'] },
472 + });
473 + });
474 +
475 + it('maps a toolkit or tool entry that only has an approval list', () => {
476 + expect(
477 + transformToolRouterUpdateParams({
478 + toolkits: { requireApproval: ['gmail'] },
479 + tools: { gmail: { requireApproval: ['GMAIL_SEND_EMAIL'] } },
480 + })
481 + ).toEqual({
482 + toolkits: { require_approval: ['gmail'] },
483 + tools: { gmail: { require_approval: ['GMAIL_SEND_EMAIL'] } },
484 + });
485 + });
486 +
487 + it('leaves require_approval out when no list is given', () => {
488 + expect(transformToolRouterToolsParams({ gmail: { enable: ['GMAIL_SEND_EMAIL'] } })).toEqual({
489 + gmail: { enable: ['GMAIL_SEND_EMAIL'] },
490 + });
491 + expect(transformToolRouterTagsParams({ enable: ['readOnlyHint'] })).toEqual({
492 + enable: ['readOnlyHint'],
493 + disable: undefined,
494 + });
495 + });
496 +
497 + it('allows requireApproval next to one of enable, disable and tags, but not two of them', () => {
498 + expect(
499 + ToolRouterConfigToolsSchema.safeParse({ enable: ['A'], requireApproval: ['A'] }).success
500 + ).toBe(true);
501 + expect(
502 + ToolRouterConfigToolsSchema.safeParse({
503 + enable: ['A'],
504 + disable: ['B'],
505 + requireApproval: ['A'],
506 + }).success
507 + ).toBe(false);
508 + });
509 +
510 + it('maps noElicitationSupportFallback to its wire name', () => {
511 + expect(
512 + transformToolRouterUpdateParams({ experimental: { noElicitationSupportFallback: 'deny' } })
513 + ).toEqual({ experimental: { no_elicitation_support_fallback: 'deny' } });
514 + });
515 +});
ts/packages/core/test/models/inputRequiredExecution.test.ts
+69 -1
@@ -131,7 +131,7 @@ describe('execution that requires user input', () => {
131 assert(error instanceof ComposioToolInputRequiredError);
132 expect(error.code).toBe('TS-SDK::TOOL_INPUT_REQUIRED');
133 expect(error.message).toContain(`${subject} requires user input`);
134 - expect(error.message).toContain('request_state');
134 + expect(error.message).toContain('inputResponses');
135 // The opaque state and the proxied URL stay out of the message.
136 expect(error.message).not.toContain('opaque-state-token');
137 expect(error.message).not.toContain('secret');
@@ -231,6 +231,74 @@ describe('execution that requires user input', () => {
231 });
232 });
233
234 +// The answers to an `input_required` call travel on the repeated call as
235 +// `input_responses`, with the `request_state` it returned.
236 +const answers = {
237 + approval_1: { action: 'accept' as const, content: { decision: 'approve' } },
238 +};
239 +
240 +const answeringPaths: Array<{
241 + name: string;
242 + run: (session: ToolRouterSession) => Promise<unknown>;
243 +}> = [
244 + {
245 + name: 'session.execute',
246 + run: session =>
247 + session.execute(
248 + 'GMAIL_SEND_EMAIL',
249 + { to: 'test@test.com' },
250 + { inputResponses: answers, requestState: 'opaque-state-token' }
251 + ),
252 + },
253 + {
254 + name: 'session.executeMeta',
255 + run: session =>
256 + session.executeMeta(
257 + 'COMPOSIO_MULTI_EXECUTE_TOOL',
258 + { tools: [] },
259 + { inputResponses: answers, requestState: 'opaque-state-token' }
260 + ),
261 + },
262 +];
263 +
264 +const sentBody = (fetch: ReturnType<typeof createClient>['fetch']): Record<string, unknown> => {
265 + const init = fetch.mock.calls[0]?.[1];
266 + assert(typeof init?.body === 'string');
267 + return z.record(z.unknown()).parse(JSON.parse(init.body));
268 +};
269 +
270 +describe('answering a call that required user input', () => {
271 + it.each(answeringPaths)('$name sends the answers and the request state', async ({ run }) => {
272 + const { client, fetch } = createClient({
273 + result_type: 'completed',
274 + data: { id: 'msg_1' },
275 + error: null,
276 + log_id: 'log_1',
277 + });
278 +
279 + await run(createSession(client));
280 +
281 + expect(sentBody(fetch)).toMatchObject({
282 + input_responses: answers,
283 + request_state: 'opaque-state-token',
284 + });
285 + });
286 +
287 + it('session.execute sends neither field without answers', async () => {
288 + const { client, fetch } = createClient({
289 + result_type: 'completed',
290 + data: {},
291 + error: null,
292 + log_id: 'log_1',
293 + });
294 +
295 + await createSession(client).execute('GMAIL_SEND_EMAIL', {});
296 +
297 + expect(sentBody(fetch)).not.toHaveProperty('input_responses');
298 + expect(sentBody(fetch)).not.toHaveProperty('request_state');
299 + });
300 +});
301 +
302 // A local custom tool reaches the API through the `ctx.execute()` and
303 // `ctx.proxyExecute()` helpers. The wrapper that runs the tool turns whatever
304 // it throws into a failed result, which must not happen to an input request:
ts/packages/core/test/models/toolRouter.test.ts
+38
@@ -1853,6 +1853,44 @@ describe('ToolRouter', () => {
1853 });
1854 });
1855
1856 + describe('approval rules', () => {
1857 + const createPayload = () => mockClient.toolRouter.session.create.mock.calls[0][0];
1858 +
1859 + it('sends requireApproval lists as require_approval', async () => {
1860 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1861 +
1862 + await toolRouter.create(userId, {
1863 + toolkits: { enable: ['gmail', 'github'], requireApproval: ['github'] },
1864 + tools: {
1865 + gmail: { requireApproval: ['GMAIL_SEND_EMAIL'] },
1866 + slack: { tags: { requireApproval: ['destructiveHint'] } },
1867 + },
1868 + tags: { requireApproval: ['destructiveHint'] },
1869 + });
1870 +
1871 + expect(createPayload()).toMatchObject({
1872 + toolkits: { enable: ['gmail', 'github'], require_approval: ['github'] },
1873 + tools: {
1874 + gmail: { require_approval: ['GMAIL_SEND_EMAIL'] },
1875 + slack: { tags: { require_approval: ['destructiveHint'] } },
1876 + },
1877 + tags: { require_approval: ['destructiveHint'] },
1878 + });
1879 + });
1880 +
1881 + it('sends noElicitationSupportFallback as experimental.no_elicitation_support_fallback', async () => {
1882 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
1883 +
1884 + await toolRouter.create(userId, {
1885 + toolkits: { requireApproval: ['gmail'] },
1886 + experimental: { noElicitationSupportFallback: 'allow' },
1887 + });
1888 +
1889 + expect(createPayload().toolkits).toEqual({ require_approval: ['gmail'] });
1890 + expect(createPayload().experimental).toEqual({ no_elicitation_support_fallback: 'allow' });
1891 + });
1892 + });
1893 +
1894 describe('session configs', () => {
1895 const createPayload = () => mockClient.toolRouter.session.create.mock.calls[0][0];
1896
ts/packages/core/type-tests/session-execute-meta.test-d.ts
+14 -1
@@ -12,7 +12,20 @@ async function sessionExecuteMeta(): Promise<void> {
12 );
13 void result;
14 await session.executeMeta('COMPOSIO_MANAGE_CONNECTIONS');
15 - await session.executeMeta('COMPOSIO_SEARCH_TOOLS', {}, { signal: new AbortController().signal });
15 + await session.executeMeta(
16 + 'COMPOSIO_SEARCH_TOOLS',
17 + {},
18 + {},
19 + { signal: new AbortController().signal }
20 + );
21 + await session.executeMeta(
22 + 'COMPOSIO_MULTI_EXECUTE_TOOL',
23 + { tools: [] },
24 + {
25 + inputResponses: { elicit_1: { action: 'accept', content: { decision: 'approve' } } },
26 + requestState: 'state',
27 + }
28 + );
29
30 // @ts-expect-error only meta tool slugs are accepted
31 await session.executeMeta('GMAIL_SEND_EMAIL');