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, 08:30 UTC
feat(core): add session hooks to TS and Python sessions
Sessions accept `hooks` on create and update. A call a hook blocks comes back with `result_type: blocked`; provider integrations pass its message to the agent as a failed call. Session proxy execute now returns a completed or blocked result. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Mukund committed
Oct 19, 2026 at 13:32 UTC
c2bbfa8a331c98585e29b785ccb15d51fdf03667
22 files changed
+1120
-85
.changeset/session-hooks.md
new
+30
@@ -0,0 +1,30 @@
1
+---
2
+'@composio/core': minor
3
+'@composio/slim': minor
4
+---
5
+
6
+Add session hooks. A hook can block a tool call before it runs, or block its result before the agent sees it.
7
+
8
+`create()` and `update()` accept `hooks`. On `update()`, `hooks` replaces the whole list and `null` removes every hook. `hooks` cannot be combined with `experimental.sessionConfigId`.
9
+
10
+```ts
11
+const session = await composio.create('user_123', {
12
+ hooks: [
13
+ {
14
+ type: 'before_execute',
15
+ id: 'no_external_email',
16
+ name: 'No external email',
17
+ appliesTo: { toolkits: ['gmail'] },
18
+ handler: {
19
+ type: 'prompt',
20
+ prompt: 'Sending email to anyone outside example.org',
21
+ onMatch: 'block',
22
+ },
23
+ },
24
+ ],
25
+});
26
+```
27
+
28
+A blocked call comes back from `session.execute()` and `session.executeMeta()` with `resultType: 'blocked'`, empty `data`, the hook's message in `error`, and `blockReason`. Provider integrations hand it to the agent as a failed call with that message. Every result also carries `hookResults` when a hook applied.
29
+
30
+`session.proxyExecute()` and `ctx.proxyExecute()` now return `resultType: 'completed'` or `resultType: 'blocked'`. A blocked request has no HTTP response, so TypeScript code that reads `status` has to check `resultType` first.
python/composio/core/models/__init__.py
+5
-1
@@ -7,6 +7,8 @@ from .custom_tool_types import (
7
RegisteredCustomTool,
8
RegisteredCustomToolkit,
9
SessionContext,
10
+ ToolRouterSessionProxyExecuteBlocked,
11
+ ToolRouterSessionProxyExecuteCompleted,
12
ToolRouterSessionProxyExecuteResponse,
13
)
14
from .experimental import (
@@ -21,9 +23,9 @@ from .mcp import MCP
23
from .tool_router import ToolRouter
24
from .tool_router_constants import SESSION_PRESET_DIRECT_TOOLS
25
from .tool_router_session import (
26
+ ToolRouterInputResponse,
27
ToolRouterSession,
28
ToolRouterSessionExecuteResponse,
26
- ToolRouterInputResponse,
29
ToolRouterSessionMetaToolSlug,
30
)
31
from .tool_router_session_delete import ToolRouterSessionDeleteResponse
@@ -79,6 +81,8 @@ __all__ = [
81
"ToolRouterSessionMetaToolSlug",
82
"ToolRouterSessionFilesMount",
83
"ToolRouterSessionProxyExecuteResponse",
84
+ "ToolRouterSessionProxyExecuteCompleted",
85
+ "ToolRouterSessionProxyExecuteBlocked",
86
"Toolkits",
87
"Tools",
88
"Triggers",
python/composio/core/models/custom_tool_types.py
+61
-5
@@ -10,11 +10,10 @@ from dataclasses import dataclass, field
10
11
import typing_extensions as te
12
from composio_client.types.tool_router import session_create_params
13
-from pydantic import BaseModel
14
-
13
from composio_client.types.tool_router.session_execute_response import (
14
SessionExecuteResponse,
15
)
16
+from pydantic import BaseModel
17
18
from composio.utils.safe_path import SAFE_COMPONENT_REGEX
19
@@ -35,11 +34,45 @@ class ProxyExecuteBinaryData(te.TypedDict):
34
expires_at: t.Optional[str]
35
36
38
-class ToolRouterSessionProxyExecuteResponse(te.TypedDict):
39
- """SDK-facing shape returned by ``proxy_execute()``.
37
+class ToolRouterHookEvaluatedResult(te.TypedDict):
38
+ """A session hook that ran. ``outcome`` is what it decided."""
39
+
40
+ id: str
41
+ status: t.Literal["evaluated"]
42
+ outcome: t.Literal["continue", "block"]
43
+
44
+
45
+class ToolRouterHookUnavailableResult(te.TypedDict):
46
+ """A session hook that could not be evaluated. The call is blocked."""
47
+
48
+ id: str
49
+ status: t.Literal["unavailable"]
50
+ reason: t.Literal["timeout", "error"]
51
+
52
+
53
+ToolRouterHookResult = t.Union[
54
+ ToolRouterHookEvaluatedResult, ToolRouterHookUnavailableResult
55
+]
56
+"""What one session hook decided about a call."""
57
+
58
+
59
+class ToolRouterBlockReason(te.TypedDict):
60
+ """Why a session hook blocked a call.
61
+
62
+ ``request_blocked``: a ``before_execute`` hook blocked it and the tool did not
63
+ run. ``response_blocked``: the tool ran and an ``after_execute`` hook
64
+ blocked its result.
65
+ """
66
+
67
+ type: t.Literal["request_blocked", "response_blocked"]
68
+ hook_id: str
69
+
70
+
71
+class ToolRouterSessionProxyExecuteCompleted(te.TypedDict):
72
+ """A proxied request that was sent.
73
74
Field-for-field equivalent to the TypeScript SDK's
42
- ``ToolRouterSessionProxyExecuteResponse``, spelled in snake_case: the same
75
+ ``ToolRouterSessionProxyExecuteCompleted``, spelled in snake_case: the same
76
fields carry the same meaning in both SDKs, each in its own language's
77
convention. The generated client's model is deliberately not exposed --
78
it is regenerated from the upstream spec, so returning it directly would
@@ -50,10 +83,33 @@ class ToolRouterSessionProxyExecuteResponse(te.TypedDict):
83
renders ``200.0`` where TypeScript renders ``200``.
84
"""
85
86
+ result_type: t.Literal["completed"]
87
status: int
88
data: t.Any
89
headers: t.Optional[t.Dict[str, str]]
90
binary_data: te.NotRequired[ProxyExecuteBinaryData]
91
+ hook_results: te.NotRequired[t.List[ToolRouterHookResult]]
92
+
93
+
94
+class ToolRouterSessionProxyExecuteBlocked(te.TypedDict):
95
+ """A proxied request that a session hook blocked. It has no HTTP response.
96
+
97
+ ``message`` is meant for the agent; it names the hook when the hook has a
98
+ ``name``.
99
+ """
100
+
101
+ result_type: t.Literal["blocked"]
102
+ block_reason: ToolRouterBlockReason
103
+ message: str
104
+ hook_results: te.NotRequired[t.List[ToolRouterHookResult]]
105
+
106
+
107
+ToolRouterSessionProxyExecuteResponse = t.Union[
108
+ ToolRouterSessionProxyExecuteCompleted, ToolRouterSessionProxyExecuteBlocked
109
+]
110
+"""SDK-facing shape returned by ``proxy_execute()``. Check ``result_type``
111
+before reading ``status``: a request a session hook blocked has no HTTP
112
+response."""
113
114
115
SLUG_REGEX = SAFE_COMPONENT_REGEX
python/composio/core/models/session_context.py
+28
-4
@@ -9,10 +9,11 @@ from __future__ import annotations
9
import typing as t
10
11
from composio_client import omit
12
-from composio_client.types.tool_router.session_proxy_execute_params import Parameter
12
from composio_client.types.tool_router.session_execute_response import (
13
SessionExecuteResponse,
14
)
15
+from composio_client.types.tool_router.session_proxy_execute_params import Parameter
16
+
17
from composio.client import HttpClient
18
from composio.core.models.custom_tool_execution import (
19
assert_unambiguous_custom_tool_slug,
@@ -22,6 +23,8 @@ from composio.core.models.custom_tool_execution import (
23
from composio.core.models.custom_tool_types import (
24
CustomToolsMap,
25
InlineCustomToolsWirePayload,
26
+ ToolRouterSessionProxyExecuteBlocked,
27
+ ToolRouterSessionProxyExecuteCompleted,
28
ToolRouterSessionProxyExecuteResponse,
29
)
30
from composio.core.models.inline_custom_tools_payload import (
@@ -29,12 +32,13 @@ from composio.core.models.inline_custom_tools_payload import (
32
)
33
from composio.core.models.tools import (
34
_serialize_arguments,
35
+ parse_blocked_response,
36
+ parse_hook_results,
37
require_execute_result,
38
require_executed,
39
)
40
from composio.exceptions import ValidationError
41
37
-
42
_VALID_METHODS = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH"})
43
_VALID_PARAM_TYPES = frozenset({"header", "query"})
44
@@ -86,6 +90,7 @@ def proxy_execute_impl(
90
)
91
)
92
93
+ subject = f"{method} proxy call for toolkit {toolkit}"
94
# Disable retries: a proxied call is a non-idempotent write, and a silent
95
# retry after a read timeout can duplicate the side effect.
96
response = require_executed(
@@ -97,17 +102,36 @@ def proxy_execute_impl(
102
body=body if body is not None else omit,
103
parameters=api_params if api_params else omit,
104
),
100
- f"{method} proxy call for toolkit {toolkit}",
105
+ subject,
106
)
107
108
+ # A blocked request has no HTTP response, so it is read before ``status``.
109
+ blocked = parse_blocked_response(response, subject)
110
+ if blocked is not None:
111
+ blocked_result: ToolRouterSessionProxyExecuteBlocked = {
112
+ "result_type": "blocked",
113
+ "block_reason": {
114
+ "type": blocked.reason.type,
115
+ "hook_id": blocked.reason.hook_id,
116
+ },
117
+ "message": blocked.message,
118
+ }
119
+ if blocked.hook_results is not None:
120
+ blocked_result["hook_results"] = blocked.hook_results
121
+ return blocked_result
122
+
123
# ``status`` and ``size`` are ``float`` on the generated model and pydantic
124
# coerces, so they arrive as ``200.0``/``123.0``. Narrow them here: an HTTP
125
# status and a byte count are integers, and TypeScript reports them as such.
106
- result: ToolRouterSessionProxyExecuteResponse = {
126
+ result: ToolRouterSessionProxyExecuteCompleted = {
127
+ "result_type": "completed",
128
"status": int(response.status),
129
"data": response.data,
130
"headers": response.headers,
131
}
132
+ hook_results = parse_hook_results(response, subject)
133
+ if hook_results is not None:
134
+ result["hook_results"] = hook_results
135
binary_data = response.binary_data
136
if binary_data is not None:
137
result["binary_data"] = {
python/composio/core/models/tool_router.py
+13
@@ -47,6 +47,7 @@ from composio.core.models.tool_router_constants import (
47
SESSION_PRESET_DIRECT_TOOLS,
48
)
49
from composio.core.models.tool_router_session import (
50
+ ToolRouterHook,
51
ToolRouterInstantConfig,
52
ToolRouterProxyExecuteConfig,
53
ToolRouterSession,
@@ -778,6 +779,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
779
workbench: t.Optional[ToolRouterWorkbenchConfig] = None,
780
multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,
781
proxy_execute: t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]] = None,
782
+ hooks: t.Optional[t.List[ToolRouterHook]] = None,
783
preload: t.Optional[ToolRouterPreloadConfig] = None,
784
session_preset: t.Optional[SessionPreset] = None,
785
experimental: t.Optional[ToolRouterExperimentalConfig] = None,
@@ -809,6 +811,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
811
workbench: t.Optional[ToolRouterWorkbenchConfig] = None,
812
multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,
813
proxy_execute: t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]] = None,
814
+ hooks: t.Optional[t.List[ToolRouterHook]] = None,
815
preload: t.Optional[ToolRouterPreloadConfig] = None,
816
session_preset: t.Optional[SessionPreset] = None,
817
experimental: t.Optional[ToolRouterExperimentalConfig] = None,
@@ -839,6 +842,7 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
842
workbench: t.Optional[ToolRouterWorkbenchConfig] = None,
843
multi_account: t.Optional[ToolRouterMultiAccountConfig] = None,
844
proxy_execute: t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]] = None,
845
+ hooks: t.Optional[t.List[ToolRouterHook]] = None,
846
preload: t.Optional[ToolRouterPreloadConfig] = None,
847
session_preset: t.Optional[SessionPreset] = None,
848
experimental: t.Optional[ToolRouterExperimentalConfig] = None,
@@ -969,6 +973,12 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
973
the sandbox ``proxy_execute()`` helper, and the API rejects it
974
together with ``sandbox={"enable_proxy_execution": True}``.
975
Leaving it out keeps the meta tool off.
976
+ :param hooks: Optional hooks that run on this session's tool calls. A
977
+ ``before_execute`` hook can block a call before it runs;
978
+ an ``after_execute`` hook can block its result before the
979
+ agent sees it. A blocked call comes back with
980
+ ``result_type="blocked"``. Cannot be combined with
981
+ ``experimental={"session_config_id": ...}``.
982
:param instant: Experimental Instant usage policy. The project
983
must allow Instant usage. ``False`` disables it for this
984
Session; a policy can restrict eligible toolkits and tools.
@@ -1179,6 +1189,9 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1189
create_params["instant"] = instant
1190
if proxy_execute is not None:
1191
create_params["proxy_execute"] = _proxy_execute_payload(proxy_execute)
1192
+ if hooks is not None:
1193
+ # The generated client has no typed parameter for ``hooks`` yet.
1194
+ create_params["extra_body"] = {"hooks": hooks}
1195
1196
# Build connections config
1197
connections_config: t.Dict[str, t.Any] = {
python/composio/core/models/tool_router_session.py
+83
-12
@@ -53,9 +53,9 @@ from composio.core.models.custom_tool_types import (
53
CustomToolsMap,
54
CustomToolsMapEntry,
55
InlineCustomToolsWirePayload,
56
- ToolRouterSessionProxyExecuteResponse,
56
RegisteredCustomTool,
57
RegisteredCustomToolkit,
58
+ ToolRouterSessionProxyExecuteResponse,
59
)
60
from composio.core.models.experimental import ACL_ONLY_FOR_SHARED_ERROR_FRAGMENT
61
from composio.core.models.inline_custom_tools_payload import (
@@ -174,6 +174,68 @@ class ToolRouterProxyExecuteConfig(te.TypedDict):
174
enable: bool
175
176
177
+class ToolRouterHookToolkitsScope(te.TypedDict):
178
+ """Runs a hook only on calls to these toolkits, including their proxy calls."""
179
+
180
+ toolkits: t.List[str]
181
+
182
+
183
+ToolRouterHookAppliesTo = t.Union[t.Literal["all"], ToolRouterHookToolkitsScope]
184
+"""Which tool calls a hook runs on: ``"all"``, or only the listed toolkits."""
185
+
186
+
187
+class ToolRouterHookPromptHandler(te.TypedDict):
188
+ """Blocks a call or result when it matches ``prompt``.
189
+
190
+ ``prompt`` is a plain sentence describing what to block, for example
191
+ ``"Sending email to anyone outside example.org"``.
192
+ """
193
+
194
+ type: t.Literal["prompt"]
195
+ prompt: str
196
+ on_match: t.Literal["block"]
197
+
198
+
199
+class ToolRouterHookPromptInjectionHandler(te.TypedDict):
200
+ """A pre-defined handler that blocks results with text that tries to give
201
+ the agent instructions."""
202
+
203
+ type: t.Literal["prompt_injection"]
204
+ on_match: t.Literal["block"]
205
+
206
+
207
+class ToolRouterBeforeExecuteHook(te.TypedDict):
208
+ """A hook that can block a tool call before it runs.
209
+
210
+ ``id`` is unique within the session and shows up in results and logs.
211
+ ``name`` is optional; the agent sees it when this hook blocks a call.
212
+ """
213
+
214
+ type: t.Literal["before_execute"]
215
+ id: str
216
+ name: te.NotRequired[str]
217
+ applies_to: ToolRouterHookAppliesTo
218
+ handler: ToolRouterHookPromptHandler
219
+
220
+
221
+class ToolRouterAfterExecuteHook(te.TypedDict):
222
+ """A hook that can block a tool call's result before the agent sees it.
223
+
224
+ ``id`` is unique within the session and shows up in results and logs.
225
+ ``name`` is optional; the agent sees it when this hook blocks a call.
226
+ """
227
+
228
+ type: t.Literal["after_execute"]
229
+ id: str
230
+ name: te.NotRequired[str]
231
+ applies_to: ToolRouterHookAppliesTo
232
+ handler: t.Union[ToolRouterHookPromptHandler, ToolRouterHookPromptInjectionHandler]
233
+
234
+
235
+ToolRouterHook = t.Union[ToolRouterBeforeExecuteHook, ToolRouterAfterExecuteHook]
236
+"""A hook on a session's tool calls."""
237
+
238
+
239
ToolRouterSessionExecuteResponse = SessionExecuteResponse
240
"""Result of :meth:`ToolRouterSession.execute`. ``instant_charge`` is present
241
only when the Session sets ``instant.return_instant_charge`` and a charge is
@@ -970,9 +1032,12 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1032
1033
Both paths return a ``ToolRouterSessionExecuteResponse`` with ``data``,
1034
``error``, ``log_id``, ``result_type``, and ``instant_charge``
973
- attributes. ``result_type`` is ``"completed"`` or ``"failed"``; a failed
974
- execution can carry a ``None`` or empty ``error``, so read
975
- ``result_type`` to tell the two apart.
1035
+ attributes. ``result_type`` is ``"completed"``, ``"failed"`` or
1036
+ ``"blocked"``; a failed execution can carry a ``None`` or empty
1037
+ ``error``, so read ``result_type`` to tell them apart. A ``"blocked"``
1038
+ call (a session hook blocked it) has empty ``data``, the hook's message
1039
+ in ``error``, and ``block_reason`` (``type`` and ``hook_id``).
1040
+ ``hook_results`` lists every session hook that applied.
1041
1042
:raises ToolInputRequiredError: If the tool needs input from the user
1043
(for example an approval) before it can run. Nothing was executed.
@@ -1159,7 +1224,9 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1224
:param method: HTTP method
1225
:param body: Request body (for POST, PUT, PATCH)
1226
:param parameters: Query/header parameters
1162
- :returns: Proxied API response
1227
+ :returns: The proxied API response with ``result_type="completed"``,
1228
+ or ``result_type="blocked"`` with the hook's ``message`` when a
1229
+ session hook blocked the request (it then has no ``status``)
1230
:raises ToolInputRequiredError: If the call needs input from the user
1231
before it can run. Nothing was executed.
1232
"""
@@ -1201,6 +1268,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1268
proxy_execute: t.Union[
1269
t.Optional[t.Union[bool, ToolRouterProxyExecuteConfig]], "Omit"
1270
] = omit,
1271
+ hooks: t.Union[t.Optional[t.List[ToolRouterHook]], "Omit"] = omit,
1272
preload: t.Union[t.Optional[session_patch_params.Preload], "Omit"] = omit,
1273
search: t.Union[t.Optional[session_patch_params.Search], "Omit"] = omit,
1274
execute: t.Union[t.Optional[session_patch_params.Execute], "Omit"] = omit,
@@ -1229,6 +1297,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1297
exposes the ``COMPOSIO_PROXY_EXECUTE`` meta tool, ``False`` also turns
1298
off the sandbox ``proxy_execute()`` helper, and ``None`` removes the
1299
stored block.
1300
+ ``hooks`` replaces the whole list of hooks, and ``None`` removes every
1301
+ hook.
1302
1303
By default the request carries no precondition: the last writer wins.
1304
Pass ``expected_config_version`` (for example this object's
@@ -1279,13 +1349,14 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1349
1350
workbench_payload = sandbox if sandbox is not omit else workbench
1351
1282
- # The generated client has no typed parameter for the precondition, so
1283
- # it travels as an extra root body field.
1284
- extra_body: t.Optional[t.Dict[str, t.Any]] = (
1285
- None
1286
- if isinstance(precondition, Omit)
1287
- else {"expected_config_version": precondition}
1288
- )
1352
+ # The generated client has no typed parameter for the precondition or
1353
+ # for ``hooks``, so they travel as extra root body fields.
1354
+ extra_fields: t.Dict[str, t.Any] = {}
1355
+ if not isinstance(precondition, Omit):
1356
+ extra_fields["expected_config_version"] = precondition
1357
+ if not isinstance(hooks, Omit):
1358
+ extra_fields["hooks"] = hooks
1359
+ extra_body: t.Optional[t.Dict[str, t.Any]] = extra_fields or None
1360
1361
# The generated client does not type ``None`` for every policy block
1362
# although the API accepts it (it removes the stored override), nor the
python/composio/core/models/tools.py
+104
-5
@@ -19,6 +19,8 @@ from composio_client.types.tool_router.session_proxy_execute_response import (
19
SessionProxyExecuteInputRequiredResponse,
20
)
21
from pydantic import BaseModel as PydanticBaseModel
22
+from pydantic import TypeAdapter
23
+from pydantic import ValidationError as PydanticValidationError
24
25
from composio.client import HttpClient
26
from composio.client.types import (
@@ -30,7 +32,10 @@ from composio.client.types import (
32
)
33
from composio.core.models._files import FileHelper
34
from composio.core.models.base import Resource
33
-from composio.core.models.custom_tool_types import InlineCustomToolsWirePayload
35
+from composio.core.models.custom_tool_types import (
36
+ InlineCustomToolsWirePayload,
37
+ ToolRouterHookResult,
38
+)
39
from composio.core.models.inline_custom_tools_payload import (
40
inline_custom_tools_execute_experimental,
41
)
@@ -169,26 +174,120 @@ def require_executed(
174
)
175
176
177
+class _BlockReasonWire(PydanticBaseModel):
178
+ type: t.Literal["request_blocked", "response_blocked"]
179
+ hook_id: str
180
+
181
+
182
+class BlockedResponse(PydanticBaseModel):
183
+ """A call a session hook blocked, as the API returns it.
184
+
185
+ The generated client does not type it yet, so it is validated here.
186
+ ``log_id`` and ``instant_charge`` come only from session execute; session
187
+ proxy execute leaves them out.
188
+ """
189
+
190
+ result_type: t.Literal["blocked"]
191
+ reason: _BlockReasonWire
192
+ message: str
193
+ log_id: t.Optional[str] = None
194
+ instant_charge: t.Optional[t.Any] = None
195
+ hook_results: t.Optional[t.List[ToolRouterHookResult]] = None
196
+
197
+
198
+_HOOK_RESULTS_ADAPTER: TypeAdapter[t.List[ToolRouterHookResult]] = TypeAdapter(
199
+ t.List[ToolRouterHookResult]
200
+)
201
+
202
+
203
+def parse_blocked_response(
204
+ response: t.Any, subject: str
205
+) -> t.Optional[BlockedResponse]:
206
+ """Read a ``blocked`` response, or return ``None`` for any other ``result_type``.
207
+
208
+ :raises ValidationError: If a ``blocked`` response does not match its shape.
209
+ """
210
+ if getattr(response, "result_type", None) != "blocked":
211
+ return None
212
+ try:
213
+ return BlockedResponse.model_validate(dict(response))
214
+ except PydanticValidationError as exc:
215
+ raise ValidationError(
216
+ f"{subject} returned a malformed blocked response"
217
+ ) from exc
218
+
219
+
220
+def _response_field(response: t.Any, name: str) -> t.Any:
221
+ """A field of a generated client response model, declared or not.
222
+
223
+ The generated client keeps fields it does not type yet (``hook_results``)
224
+ as extras; once it types them they become declared fields.
225
+ """
226
+ if not isinstance(response, PydanticBaseModel):
227
+ return None
228
+ if name in type(response).model_fields:
229
+ return getattr(response, name, None)
230
+ return (response.model_extra or {}).get(name)
231
+
232
+
233
+def parse_hook_results(
234
+ response: t.Any, subject: str
235
+) -> t.Optional[t.List[ToolRouterHookResult]]:
236
+ """The ``hook_results`` of a call that ran, or ``None`` when no hook applied.
237
+
238
+ :raises ValidationError: If ``hook_results`` does not match its shape.
239
+ """
240
+ raw = _response_field(response, "hook_results")
241
+ if raw is None:
242
+ return None
243
+ try:
244
+ return _HOOK_RESULTS_ADAPTER.validate_python(raw)
245
+ except PydanticValidationError as exc:
246
+ raise ValidationError(f"{subject} returned malformed hook results") from exc
247
+
248
+
249
def require_execute_result(
250
response: t.Union[SessionExecuteResponse, SessionExecuteInputRequiredResponse],
251
slug: str,
252
) -> SessionExecuteResponse:
253
"""Narrow a session execute response to a tool that ran.
254
178
- Every session execute response carries a ``result_type``. One without it,
179
- or with a value this SDK does not know, is neither a success nor a failure,
180
- so it is raised instead of being read as one. The TypeScript SDK applies
181
- the same rule.
255
+ Every session execute response carries a ``result_type``. A ``blocked``
256
+ call (a session hook blocked it) is returned as a result with empty
257
+ ``data``, the hook's message in ``error``, and ``block_reason``. One
258
+ without a ``result_type``, or with a value this SDK does not know, is
259
+ neither a success nor a failure, so it is raised instead of being read as
260
+ one. The TypeScript SDK applies the same rule.
261
262
:raises ToolInputRequiredError: If the tool asked for user input instead of
263
running.
264
:raises ValidationError: If ``result_type`` is missing or unknown.
265
"""
266
executed = require_executed(response, f"Tool {slug}")
267
+ blocked = parse_blocked_response(executed, f"Tool {slug}")
268
+ if blocked is not None:
269
+ # The agent reads ``error``, so a blocked call reaches it as a failed
270
+ # call with the hook's message.
271
+ fields: t.Dict[str, t.Any] = {
272
+ "data": {},
273
+ "error": blocked.message,
274
+ "log_id": blocked.log_id or "",
275
+ "result_type": "blocked",
276
+ "block_reason": {
277
+ "type": blocked.reason.type,
278
+ "hook_id": blocked.reason.hook_id,
279
+ },
280
+ }
281
+ if blocked.hook_results is not None:
282
+ fields["hook_results"] = blocked.hook_results
283
+ if blocked.instant_charge is not None:
284
+ fields["instant_charge"] = blocked.instant_charge
285
+ return SessionExecuteResponse.model_construct(_fields_set=set(fields), **fields)
286
if getattr(executed, "result_type", None) not in ("completed", "failed"):
287
raise ValidationError(
288
f"Tool {slug} returned an execute response without a known result_type"
289
)
290
+ parse_hook_results(executed, f"Tool {slug}")
291
return executed
292
293
python/composio/types.py
+16
@@ -1,7 +1,16 @@
1
from composio.client.types import Tool
2
from composio.core.models.connected_accounts import auth_scheme
3
+from composio.core.models.custom_tool_types import (
4
+ ToolRouterBlockReason,
5
+ ToolRouterHookResult,
6
+ ToolRouterSessionProxyExecuteBlocked,
7
+ ToolRouterSessionProxyExecuteCompleted,
8
+)
9
from composio.core.models.experimental import UsageSummaryResponse
10
from composio.core.models.tool_router_session import (
11
+ ToolRouterAfterExecuteHook,
12
+ ToolRouterBeforeExecuteHook,
13
+ ToolRouterHook,
14
ToolRouterInstantConfig,
15
ToolRouterProxyExecuteConfig,
16
ToolRouterSessionConfig,
@@ -30,6 +39,13 @@ __all__ = [
39
"InstantCharge",
40
"ToolRouterInstantConfig",
41
"ToolRouterProxyExecuteConfig",
42
+ "ToolRouterHook",
43
+ "ToolRouterBeforeExecuteHook",
44
+ "ToolRouterAfterExecuteHook",
45
+ "ToolRouterHookResult",
46
+ "ToolRouterBlockReason",
47
+ "ToolRouterSessionProxyExecuteCompleted",
48
+ "ToolRouterSessionProxyExecuteBlocked",
49
"ToolRouterSessionConfig",
50
"ToolRouterSessionSearchResponse",
51
"ToolExecuteParams",
python/tests/test_custom_tools.py
+22
-3
@@ -842,7 +842,12 @@ class TestSessionContextImpl:
842
result = ctx.proxy_execute(
843
toolkit="gmail", endpoint="https://example.com", method="GET"
844
)
845
- assert result == {"status": 200, "data": {"ok": True}, "headers": {}}
845
+ assert result == {
846
+ "result_type": "completed",
847
+ "status": 200,
848
+ "data": {"ok": True},
849
+ "headers": {},
850
+ }
851
assert "binary_data" not in result
852
853
def test_proxy_execute_narrows_status_to_int(self):
@@ -861,8 +866,14 @@ class TestSessionContextImpl:
866
result = ctx.proxy_execute(
867
toolkit="gmail", endpoint="https://example.com", method="GET"
868
)
869
+ assert result["result_type"] == "completed"
870
assert isinstance(result["status"], int)
865
- assert result == {"status": 200, "data": None, "headers": None}
871
+ assert result == {
872
+ "result_type": "completed",
873
+ "status": 200,
874
+ "data": None,
875
+ "headers": None,
876
+ }
877
878
def test_proxy_execute_projects_binary_data(self):
879
mock_client = mock_http_client(MagicMock)
@@ -884,6 +895,7 @@ class TestSessionContextImpl:
895
toolkit="gmail", endpoint="https://example.com", method="GET"
896
)
897
assert result == {
898
+ "result_type": "completed",
899
"status": 200,
900
"data": {"ok": True},
901
"headers": {"content-type": "application/pdf"},
@@ -1079,7 +1091,13 @@ class TestToolRouterSessionCustomTools:
1091
result = s.proxy_execute(
1092
toolkit="gmail", endpoint="https://example.com", method="GET"
1093
)
1082
- assert result == {"status": 200, "data": {"ok": True}, "headers": {}}
1094
+ assert result == {
1095
+ "result_type": "completed",
1096
+ "status": 200,
1097
+ "data": {"ok": True},
1098
+ "headers": {},
1099
+ }
1100
+ assert result["result_type"] == "completed"
1101
assert isinstance(result["status"], int)
1102
assert "binary_data" not in result
1103
@@ -1102,6 +1120,7 @@ class TestToolRouterSessionCustomTools:
1120
toolkit="gmail", endpoint="https://example.com", method="GET"
1121
)
1122
assert result == {
1123
+ "result_type": "completed",
1124
"status": 200,
1125
"data": {"ok": True},
1126
"headers": {"content-type": "application/pdf"},
python/tests/test_tool_router.py
+156
-1
@@ -27,6 +27,7 @@ from pydantic import BaseModel, Field
27
28
from composio.client import HttpClient
29
from composio.core.models.experimental import ExperimentalAPI
30
+from composio.core.models.session_context import SessionContextImpl
31
from composio.core.models.tool_router import (
32
SESSION_PRESET_DIRECT_TOOLS,
33
ToolkitConnectionsDetails,
@@ -47,7 +48,6 @@ from composio.core.models.tool_router_session import (
48
ToolRouterSessionMetaToolSlug,
49
ToolRouterSessionWithMcp,
50
)
50
-from composio.core.models.session_context import SessionContextImpl
51
from composio.exceptions import (
52
InvalidParams,
53
MCPDestinationError,
@@ -2798,12 +2798,167 @@ class TestExecutionRequiresUserInput:
2798
result = _created_session(client).proxy_execute(**_PROXY_PARAMS)
2799
2800
assert result == {
2801
+ "result_type": "completed",
2802
"status": 201,
2803
"data": {"id": 1},
2804
"headers": {"x-request-id": "req_1"},
2805
}
2806
2807
2808
+_BLOCKED_CALL_JSON: t.Dict[str, t.Any] = {
2809
+ "result_type": "blocked",
2810
+ "reason": {"type": "request_blocked", "hook_id": "no_external_email"},
2811
+ "message": "Blocked by session policy: No external email",
2812
+ "log_id": "",
2813
+ "hook_results": [
2814
+ {"id": "no_external_email", "status": "evaluated", "outcome": "block"}
2815
+ ],
2816
+}
2817
+
2818
+
2819
+class TestSessionHooks:
2820
+ """A session hook can block a call before it runs, or block its result
2821
+ before the agent sees it. The API answers ``result_type: "blocked"``,
2822
+ which has no data and no HTTP response.
2823
+
2824
+ The cases run a real client over a stub transport so they cover the wire
2825
+ shape the generated client hands to the SDK.
2826
+ """
2827
+
2828
+ _HOOKS: t.List[t.Any] = [
2829
+ {
2830
+ "type": "before_execute",
2831
+ "id": "no_external_email",
2832
+ "name": "No external email",
2833
+ "applies_to": {"toolkits": ["gmail"]},
2834
+ "handler": {
2835
+ "type": "prompt",
2836
+ "prompt": "Sending email to anyone outside example.org",
2837
+ "on_match": "block",
2838
+ },
2839
+ },
2840
+ {
2841
+ "type": "after_execute",
2842
+ "id": "block_injection",
2843
+ "applies_to": "all",
2844
+ "handler": {"type": "prompt_injection", "on_match": "block"},
2845
+ },
2846
+ ]
2847
+
2848
+ def test_create_sends_hooks(self, tool_router, mock_client):
2849
+ tool_router.create(user_id="user_123", hooks=self._HOOKS)
2850
+
2851
+ kwargs = mock_client.tool_router.session.create.call_args.kwargs
2852
+ assert kwargs["extra_body"] == {"hooks": self._HOOKS}
2853
+
2854
+ def test_create_omits_hooks_by_default(self, tool_router, mock_client):
2855
+ tool_router.create(user_id="user_123")
2856
+
2857
+ kwargs = mock_client.tool_router.session.create.call_args.kwargs
2858
+ assert "extra_body" not in kwargs
2859
+
2860
+ @pytest.mark.parametrize(
2861
+ ("hooks", "expected"),
2862
+ [
2863
+ pytest.param(_HOOKS, _HOOKS, id="replace"),
2864
+ pytest.param(None, None, id="remove"),
2865
+ ],
2866
+ )
2867
+ def test_update_sends_hooks(self, hooks, expected):
2868
+ client, requests = _transport_client(
2869
+ auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev"
2870
+ )
2871
+ session = _created_session(client)
2872
+
2873
+ session.update(hooks=hooks)
2874
+
2875
+ body = json.loads(requests[-1].content)
2876
+ assert body["hooks"] == expected
2877
+
2878
+ @pytest.mark.parametrize(
2879
+ "run",
2880
+ [
2881
+ pytest.param(
2882
+ lambda client: _created_session(client).execute(
2883
+ "GMAIL_SEND_EMAIL", arguments={"to": "ceo@rival.com"}
2884
+ ),
2885
+ id="session.execute",
2886
+ ),
2887
+ pytest.param(
2888
+ lambda client: SessionContextImpl(
2889
+ client, "user_123", "session_123"
2890
+ ).execute("GMAIL_SEND_EMAIL", {"to": "ceo@rival.com"}),
2891
+ id="custom tool context execute",
2892
+ ),
2893
+ ],
2894
+ )
2895
+ def test_execute_returns_a_blocked_result(self, run):
2896
+ client, _ = _answering_client(_BLOCKED_CALL_JSON)
2897
+
2898
+ result = run(client)
2899
+
2900
+ assert result.result_type == "blocked"
2901
+ assert result.data == {}
2902
+ assert result.error == "Blocked by session policy: No external email"
2903
+ assert result.log_id == ""
2904
+ assert result.block_reason == {
2905
+ "type": "request_blocked",
2906
+ "hook_id": "no_external_email",
2907
+ }
2908
+ assert result.hook_results == [
2909
+ {"id": "no_external_email", "status": "evaluated", "outcome": "block"}
2910
+ ]
2911
+
2912
+ def test_blocked_call_reaches_the_agent_as_a_failed_call(self):
2913
+ """Every provider hands the agent ``data``, ``error`` and
2914
+ ``successful``, so this is what the agent sees in any framework."""
2915
+ client, _ = _answering_client(_BLOCKED_CALL_JSON)
2916
+
2917
+ result = _session_tool_execute_fn(client)(
2918
+ "GMAIL_SEND_EMAIL", {"to": "ceo@rival.com"}
2919
+ )
2920
+
2921
+ assert result["successful"] is False
2922
+ assert result["data"] == {}
2923
+ assert result["error"] == "Blocked by session policy: No external email"
2924
+
2925
+ def test_malformed_blocked_response_is_raised(self):
2926
+ malformed = {k: v for k, v in _BLOCKED_CALL_JSON.items() if k != "reason"}
2927
+ client, _ = _answering_client(malformed)
2928
+
2929
+ with pytest.raises(ValidationError):
2930
+ _created_session(client).execute("GMAIL_SEND_EMAIL", arguments={})
2931
+
2932
+ @pytest.mark.parametrize(
2933
+ "run",
2934
+ [
2935
+ pytest.param(
2936
+ lambda client: _created_session(client).proxy_execute(**_PROXY_PARAMS),
2937
+ id="session.proxy_execute",
2938
+ ),
2939
+ pytest.param(
2940
+ lambda client: SessionContextImpl(
2941
+ client, "user_123", "session_123"
2942
+ ).proxy_execute(**_PROXY_PARAMS),
2943
+ id="custom tool context proxy_execute",
2944
+ ),
2945
+ ],
2946
+ )
2947
+ def test_proxy_execute_returns_a_blocked_result(self, run):
2948
+ client, _ = _answering_client(
2949
+ {k: v for k, v in _BLOCKED_CALL_JSON.items() if k != "log_id"}
2950
+ )
2951
+
2952
+ assert run(client) == {
2953
+ "result_type": "blocked",
2954
+ "block_reason": {"type": "request_blocked", "hook_id": "no_external_email"},
2955
+ "message": "Blocked by session policy: No external email",
2956
+ "hook_results": [
2957
+ {"id": "no_external_email", "status": "evaluated", "outcome": "block"}
2958
+ ],
2959
+ }
2960
+
2961
+
2962
class _NoInput(BaseModel):
2963
pass
2964
ts/packages/core/src/lib/toolRouterParams.ts
+33
-3
@@ -19,6 +19,7 @@ import {
19
ToolRouterSandboxConfig,
20
ToolRouterInstant,
21
ToolRouterProxyExecute,
22
+ ToolRouterHook,
23
} from '../types/toolRouter.types';
24
import { ValidationError } from '../errors';
25
import { z } from 'zod';
@@ -189,11 +190,36 @@ export type SessionPatchExperimentalBody = WithNull<
190
'permissions' | 'link_url_overwrite' | 'fast_mode' | 'submit_feedback'
191
>;
192
193
+/** A hook as the API takes it, in snake_case. The generated client does not type `hooks` yet. */
194
+export type SessionHookBody = {
195
+ type: 'before_execute' | 'after_execute';
196
+ id: string;
197
+ name?: string;
198
+ applies_to: 'all' | { toolkits: string[] };
199
+ handler:
200
+ | { type: 'prompt'; prompt: string; on_match: 'block' }
201
+ | { type: 'prompt_injection'; on_match: 'block' };
202
+};
203
+
204
+/** Request body of `sessions.create()`: the generated `SessionCreateParams` plus `hooks`. */
205
+export type SessionCreateBody = SessionCreateParams & { hooks?: SessionHookBody[] };
206
+
207
+/** `hooks` as sent on create and update: `appliesTo` and `onMatch` become `applies_to` and `on_match`. */
208
+export const transformToolRouterHooksParams = (hooks: ToolRouterHook[]): SessionHookBody[] =>
209
+ hooks.map(({ appliesTo, handler, ...hook }) => ({
210
+ ...hook,
211
+ applies_to: appliesTo,
212
+ handler:
213
+ handler.type === 'prompt'
214
+ ? { type: 'prompt', prompt: handler.prompt, on_match: handler.onMatch }
215
+ : { type: 'prompt_injection', on_match: handler.onMatch },
216
+ }));
217
+
218
/**
219
* Request body of `session.update()`. Extends the generated `SessionPatchParams`
194
- * with the nullable policy blocks (`null` removes the stored override) and the
195
- * `expected_config_version` root precondition, none of which the generated
196
- * client types yet.
220
+ * with the nullable policy blocks (`null` removes the stored override), `hooks`
221
+ * and the `expected_config_version` root precondition, none of which the
222
+ * generated client types yet.
223
*/
224
export type SessionPatchBody = Omit<
225
WithNull<
@@ -205,6 +231,7 @@ export type SessionPatchBody = Omit<
231
manage_connections?: SessionPatchManageConnectionsBody | null;
232
multi_account?: SessionPatchMultiAccountBody | null;
233
experimental?: SessionPatchExperimentalBody | null;
234
+ hooks?: SessionHookBody[] | null;
235
expected_config_version?: number;
236
};
237
@@ -419,6 +446,9 @@ export const transformToolRouterUpdateParams = (
446
? null
447
: transformToolRouterProxyExecuteParams(config.proxyExecute);
448
}
449
+ if (config.hooks !== undefined) {
450
+ params.hooks = config.hooks === null ? null : transformToolRouterHooksParams(config.hooks);
451
+ }
452
if (config.preload !== undefined) {
453
params.preload = config.preload;
454
}
ts/packages/core/src/models/SessionContext.ts
+2
-17
@@ -24,8 +24,8 @@ import {
24
executeCustomTool,
25
} from './customToolExecution';
26
import {
27
- assertNotInputRequired,
27
transformExecuteResponse,
28
+ transformProxyExecuteResponse,
29
} from '../utils/transformers/toolRouterResponseTransform';
30
import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session/session.mjs';
31
import { inlineCustomToolsExperimental } from './inlineCustomToolsPayload';
@@ -144,24 +144,9 @@ export class SessionContextImpl implements SessionContext {
144
requestOptions?.signal
145
);
146
147
- assertNotInputRequired(
147
+ return transformProxyExecuteResponse(
148
response,
149
`${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
150
);
151
- return {
152
- status: response.status,
153
- data: response.data,
154
- headers: response.headers,
155
- ...(response.binary_data
156
- ? {
157
- binaryData: {
158
- contentType: response.binary_data.content_type,
159
- size: response.binary_data.size,
160
- url: response.binary_data.url,
161
- expiresAt: response.binary_data.expires_at,
162
- },
163
- }
164
- : {}),
165
- };
151
}
152
}
ts/packages/core/src/models/ToolRouter.ts
+6
-1
@@ -52,6 +52,8 @@ import {
52
transformToolRouterMultiAccountParams,
53
transformToolRouterInstantParams,
54
transformToolRouterProxyExecuteParams,
55
+ transformToolRouterHooksParams,
56
+ type SessionCreateBody,
57
resolveToolRouterSandboxConfig,
58
} from '../lib/toolRouterParams';
59
import { PRELOAD_TOOLS_ALL } from '../lib/toolRouterConstants';
@@ -275,7 +277,7 @@ export class ToolRouter<
277
])
278
);
279
278
- const payload: SessionCreateParams = {
280
+ const payload: SessionCreateBody = {
281
user_id: userId,
282
auth_configs: routerConfig.authConfigs,
283
connected_accounts: connectedAccountsPayload,
@@ -293,6 +295,9 @@ export class ToolRouter<
295
...(routerConfig.proxyExecute !== undefined && {
296
proxy_execute: transformToolRouterProxyExecuteParams(routerConfig.proxyExecute),
297
}),
298
+ ...(routerConfig.hooks !== undefined && {
299
+ hooks: transformToolRouterHooksParams(routerConfig.hooks),
300
+ }),
301
preload: routerConfig.preload,
302
...(isDirectToolsPreset && {
303
search: { enable: false },
ts/packages/core/src/models/ToolRouterSession.ts
+4
-19
@@ -39,9 +39,9 @@ import {
39
type ToolRouterSessionDeleteResponse,
40
} from '../types/toolRouter.types';
41
import {
42
- assertNotInputRequired,
42
transformSearchResponse,
43
transformExecuteResponse,
44
+ transformProxyExecuteResponse,
45
} from '../utils/transformers/toolRouterResponseTransform';
46
import { SessionMetaToolOptions } from '../types/modifiers.types';
47
import { ConnectionRequest } from '../types/connectionRequest.types';
@@ -697,7 +697,7 @@ export class ToolRouterSession<
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
700
+ * @returns The tool execution result. `resultType: 'blocked'` means a session hook blocked the call; `error` then holds the hook's message
701
* @throws {ComposioToolInputRequiredError} If the tool needs input from the user (for example an approval) before it can run
702
*/
703
async execute(
@@ -815,7 +815,7 @@ export class ToolRouterSession<
815
* The backend resolves the connected account from the toolkit within the session.
816
*
817
* @param params - Proxy request parameters (toolkit, endpoint, method, body, headers/query params)
818
- * @returns The proxied API response with status, data, headers
818
+ * @returns The proxied API response with status, data and headers (`resultType: 'completed'`), or `resultType: 'blocked'` with the hook's message when a session hook blocked the request
819
* @throws {ComposioToolInputRequiredError} If the call needs input from the user before it can run
820
*/
821
async proxyExecute(
@@ -838,25 +838,10 @@ export class ToolRouterSession<
838
requestOptions?.signal
839
);
840
841
- assertNotInputRequired(
841
+ return transformProxyExecuteResponse(
842
response,
843
`${validated.data.method} proxy call for toolkit ${validated.data.toolkit}`
844
);
845
- return {
846
- status: response.status,
847
- data: response.data,
848
- headers: response.headers,
849
- ...(response.binary_data
850
- ? {
851
- binaryData: {
852
- contentType: response.binary_data.content_type,
853
- size: response.binary_data.size,
854
- url: response.binary_data.url,
855
- expiresAt: response.binary_data.expires_at,
856
- },
857
- }
858
- : {}),
859
- };
845
}
846
847
/**
ts/packages/core/src/types/toolRouter.types.ts
+150
-10
@@ -329,6 +329,73 @@ export const ToolRouterProxyExecuteSchema = z.union([
329
]);
330
export type ToolRouterProxyExecute = z.infer<typeof ToolRouterProxyExecuteSchema>;
331
332
+/** Which tool calls a hook runs on: `'all'`, or only calls to the listed toolkits (including their proxy calls). */
333
+export const ToolRouterHookAppliesToSchema = z.union([
334
+ z.literal('all'),
335
+ z.object({ toolkits: z.array(z.string()).describe('Toolkit slugs') }).strict(),
336
+]);
337
+export type ToolRouterHookAppliesTo = z.infer<typeof ToolRouterHookAppliesToSchema>;
338
+
339
+/** Blocks a call or result when it matches `prompt`, a plain sentence describing what to block. */
340
+export const ToolRouterHookPromptHandlerSchema = z
341
+ .object({
342
+ type: z.literal('prompt'),
343
+ prompt: z
344
+ .string()
345
+ .describe(
346
+ 'What to block, written as a plain sentence. For example: "Sending email to anyone outside example.org".'
347
+ ),
348
+ onMatch: z.literal('block'),
349
+ })
350
+ .strict();
351
+export type ToolRouterHookPromptHandler = z.infer<typeof ToolRouterHookPromptHandlerSchema>;
352
+
353
+/** A pre-defined handler that blocks results with text that tries to give the agent instructions. */
354
+export const ToolRouterHookPromptInjectionHandlerSchema = z
355
+ .object({
356
+ type: z.literal('prompt_injection'),
357
+ onMatch: z.literal('block'),
358
+ })
359
+ .strict();
360
+export type ToolRouterHookPromptInjectionHandler = z.infer<
361
+ typeof ToolRouterHookPromptInjectionHandlerSchema
362
+>;
363
+
364
+const toolRouterHookIdentityFields = {
365
+ id: z.string().describe('Unique within the session. Shows up in results and logs.'),
366
+ name: z
367
+ .string()
368
+ .optional()
369
+ .describe('A readable name. The agent sees it when this hook blocks a call.'),
370
+ appliesTo: ToolRouterHookAppliesToSchema,
371
+};
372
+
373
+/**
374
+ * A hook on a session's tool calls. A `before_execute` hook can block a call
375
+ * before it runs; an `after_execute` hook can block its result before the
376
+ * agent sees it.
377
+ */
378
+export const ToolRouterHookSchema = z.discriminatedUnion('type', [
379
+ z
380
+ .object({
381
+ type: z.literal('before_execute'),
382
+ ...toolRouterHookIdentityFields,
383
+ handler: ToolRouterHookPromptHandlerSchema,
384
+ })
385
+ .strict(),
386
+ z
387
+ .object({
388
+ type: z.literal('after_execute'),
389
+ ...toolRouterHookIdentityFields,
390
+ handler: z.discriminatedUnion('type', [
391
+ ToolRouterHookPromptHandlerSchema,
392
+ ToolRouterHookPromptInjectionHandlerSchema,
393
+ ]),
394
+ })
395
+ .strict(),
396
+]);
397
+export type ToolRouterHook = z.infer<typeof ToolRouterHookSchema>;
398
+
399
const ToolRouterCreateSessionConfigBaseSchema = z
400
.object({
401
sessionPreset: z
@@ -414,6 +481,13 @@ const ToolRouterCreateSessionConfigBaseSchema = z
481
'Proxy execute configuration for this session; a boolean is shorthand for `{ enable }`. Rejected by the API when enable is false and sandbox.enableProxyExecution is true.'
482
),
483
484
+ hooks: z
485
+ .array(ToolRouterHookSchema)
486
+ .optional()
487
+ .describe(
488
+ "Hooks that run on this session's tool calls. A hook can block a call before it runs, or block its result before the agent sees it."
489
+ ),
490
+
491
preload: z
492
.object({
493
tools: z
@@ -480,6 +554,7 @@ const ToolRouterCreateSessionConfigBaseSchema = z
554
config.toolkits !== undefined && 'toolkits',
555
config.tools !== undefined && 'tools',
556
config.tags !== undefined && 'tags',
557
+ config.hooks !== undefined && 'hooks',
558
config.experimental.customTools !== undefined && 'experimental.customTools',
559
config.experimental.customToolkits !== undefined && 'experimental.customToolkits',
560
].filter((field): field is string => field !== false)
@@ -544,10 +619,11 @@ export const ToolRouterCreateSessionConfigSchema = z
619
* @param {boolean} [multiAccount.requireExplicitSelection] - When true, require explicit account selection when multiple accounts are connected
620
* @param {boolean | object} [proxyExecute] - Proxy execute configuration for this session. A boolean is shorthand for `{ enable }`.
621
* @param {boolean} proxyExecute.enable - `true` exposes the `COMPOSIO_PROXY_EXECUTE` meta tool. `false` also turns off the sandbox `proxy_execute()` helper.
622
+ * @param {ToolRouterHook[]} [hooks] - Hooks that run on this session's tool calls. A `before_execute` hook can block a call before it runs; an `after_execute` hook can block its result before the agent sees it. Cannot be combined with `experimental.sessionConfigId`.
623
* @param {object} [preload] - Tools to preload into session.tools() and the MCP tool list
624
* @param {string[] | 'all'} [preload.tools] - Tool slugs to preload, or "all" to preload every app tool allowed by the session filters. "all" requires a positive filter such as toolkits, tools, or tags; the backend validates and caps the final tool set.
625
* @param {object} [experimental] - Experimental features configuration. Not stable; may change or be removed.
550
- * @param {string} [experimental.sessionConfigId] - ID of a saved Session config (`sc_…`) to apply at creation; see `composio.sessionConfigs`. Cannot be combined with `toolkits`, `tools`, `tags`, `experimental.customTools` or `experimental.customToolkits`. Per-session fields such as `authConfigs`, `connectedAccounts`, `manageConnections`, `sandbox`, `multiAccount` and `preload` stay allowed.
626
+ * @param {string} [experimental.sessionConfigId] - ID of a saved Session config (`sc_…`) to apply at creation; see `composio.sessionConfigs`. Cannot be combined with `toolkits`, `tools`, `tags`, `hooks`, `experimental.customTools` or `experimental.customToolkits`. Per-session fields such as `authConfigs`, `connectedAccounts`, `manageConnections`, `sandbox`, `multiAccount` and `preload` stay allowed.
627
*/
628
export type ToolRouterCreateSessionConfig =
629
InlineAccessCreateSessionConfig | SavedConfigCreateSessionConfig;
@@ -565,11 +641,12 @@ type InlineAccessCreateSessionConfig = Omit<ParsedCreateSessionConfig, 'experime
641
/** Create input that takes its access policy from a saved Session config. */
642
type SavedConfigCreateSessionConfig = Omit<
643
ParsedCreateSessionConfig,
568
- 'toolkits' | 'tools' | 'tags' | 'experimental'
644
+ 'toolkits' | 'tools' | 'tags' | 'hooks' | 'experimental'
645
> & {
646
toolkits?: never;
647
tools?: never;
648
tags?: never;
649
+ hooks?: never;
650
experimental: Omit<
651
ParsedCreateSessionExperimental,
652
'sessionConfigId' | 'customTools' | 'customToolkits'
@@ -745,6 +822,34 @@ export const ToolRouterSessionSearchResponseSchema = z.object({
822
});
823
export type ToolRouterSessionSearchResponse = z.infer<typeof ToolRouterSessionSearchResponseSchema>;
824
825
+// --- Session hook results (camelCase) ---
826
+
827
+/** What one session hook decided about a call. */
828
+export const ToolRouterHookResultSchema = z.discriminatedUnion('status', [
829
+ z.object({
830
+ id: z.string().describe('The hook id'),
831
+ status: z.literal('evaluated'),
832
+ outcome: z.enum(['continue', 'block']).describe('What the hook decided'),
833
+ }),
834
+ z.object({
835
+ id: z.string().describe('The hook id'),
836
+ status: z.literal('unavailable'),
837
+ reason: z.enum(['timeout', 'error']).describe('Why the hook could not be evaluated'),
838
+ }),
839
+]);
840
+export type ToolRouterHookResult = z.infer<typeof ToolRouterHookResultSchema>;
841
+
842
+/**
843
+ * Why a session hook blocked a call. `request_blocked`: a `before_execute` hook
844
+ * blocked it and the tool did not run. `response_blocked`: the tool ran and an
845
+ * `after_execute` hook blocked its result.
846
+ */
847
+export const ToolRouterBlockReasonSchema = z.object({
848
+ type: z.enum(['request_blocked', 'response_blocked']),
849
+ hookId: z.string(),
850
+});
851
+export type ToolRouterBlockReason = z.infer<typeof ToolRouterBlockReasonSchema>;
852
+
853
// --- Session execute response schema (camelCase) ---
854
855
export const ToolRouterSessionExecuteResponseSchema = z.object({
@@ -752,13 +857,19 @@ export const ToolRouterSessionExecuteResponseSchema = z.object({
857
error: z.string().nullable(),
858
logId: z.string(),
859
/**
755
- * Whether the tool ran and succeeded (`completed`) or ran and failed
756
- * (`failed`). A failed execution can carry a `null` or empty `error`, so
757
- * read this rather than `error` to tell the two apart.
860
+ * Whether the tool ran and succeeded (`completed`), ran and failed
861
+ * (`failed`), or was blocked by a session hook (`blocked`). A failed
862
+ * execution can carry a `null` or empty `error`, so read this rather than
863
+ * `error` to tell them apart. A blocked call has empty `data` and the
864
+ * agent-facing message in `error`.
865
*/
759
- resultType: z.enum(['completed', 'failed']),
866
+ resultType: z.enum(['completed', 'failed', 'blocked']),
867
/** Actual Instant usage charge when the Session opts into returning it. */
868
instantCharge: z.unknown().optional(),
869
+ /** Set when `resultType` is `blocked`: which hook blocked the call, and at which stage. */
870
+ blockReason: ToolRouterBlockReasonSchema.optional(),
871
+ /** Every session hook that applied to this call. Absent when none applied. */
872
+ hookResults: z.array(ToolRouterHookResultSchema).optional(),
873
});
874
export type ToolRouterSessionExecuteResponse = z.infer<
875
typeof ToolRouterSessionExecuteResponseSchema
@@ -766,7 +877,9 @@ export type ToolRouterSessionExecuteResponse = z.infer<
877
878
// --- Session proxy execute response (matches ToolProxyResponse from client) ---
879
769
-export interface ToolRouterSessionProxyExecuteResponse {
880
+/** A proxied request that was sent. */
881
+export interface ToolRouterSessionProxyExecuteCompleted {
882
+ resultType: 'completed';
883
/** The HTTP status code returned from the proxied API */
884
status: number;
885
/** The response data from the proxied API */
@@ -780,8 +893,28 @@ export interface ToolRouterSessionProxyExecuteResponse {
893
url: string;
894
expiresAt?: string;
895
};
896
+ /** Every session hook that applied to this request. Absent when none applied. */
897
+ hookResults?: ToolRouterHookResult[];
898
+}
899
+
900
+/** A proxied request that a session hook blocked. */
901
+export interface ToolRouterSessionProxyExecuteBlocked {
902
+ resultType: 'blocked';
903
+ /** Which hook blocked the request, and at which stage. */
904
+ blockReason: ToolRouterBlockReason;
905
+ /** A message for the agent. It names the hook when the hook has a `name`. */
906
+ message: string;
907
+ /** Every session hook that applied to this request. */
908
+ hookResults?: ToolRouterHookResult[];
909
}
910
911
+/**
912
+ * Result of `session.proxyExecute()`. Check `resultType` before reading
913
+ * `status`: a request a session hook blocked has no HTTP response.
914
+ */
915
+export type ToolRouterSessionProxyExecuteResponse =
916
+ ToolRouterSessionProxyExecuteCompleted | ToolRouterSessionProxyExecuteBlocked;
917
+
918
/**
919
* Experimental features on a tool router session.
920
* Contains features that may be modified or removed in future versions.
@@ -1096,6 +1229,11 @@ export const ToolRouterUpdateSessionConfigSchema = z
1229
.describe(
1230
'Replaces the proxy execute block; a boolean is shorthand for `{ enable }` and `null` removes it'
1231
),
1232
+ hooks: z
1233
+ .array(ToolRouterHookSchema)
1234
+ .nullable()
1235
+ .optional()
1236
+ .describe('Replaces the whole list of hooks; `null` removes every hook'),
1237
preload: z
1238
.object({
1239
tools: z.union([z.array(z.string()), z.literal('all')]).optional(),
@@ -1136,6 +1274,7 @@ export const ToolRouterUpdateSessionConfigSchema = z
1274
config.toolkits !== undefined && 'toolkits',
1275
config.tools !== undefined && 'tools',
1276
config.tags !== undefined && 'tags',
1277
+ config.hooks !== undefined && 'hooks',
1278
].filter((field): field is string => field !== false)
1279
);
1280
}
@@ -1151,8 +1290,8 @@ export const ToolRouterUpdateSessionConfigSchema = z
1290
1291
/**
1292
* Options for `session.update()`. `experimental.sessionConfigId` applies a
1154
- * saved Session config and cannot be combined with `toolkits`, `tools` or
1155
- * `tags` (including `null`).
1293
+ * saved Session config and cannot be combined with `toolkits`, `tools`,
1294
+ * `tags` or `hooks` (including `null`).
1295
*/
1296
export type ToolRouterUpdateSessionConfig =
1297
InlineAccessUpdateSessionConfig | SavedConfigUpdateSessionConfig;
@@ -1169,11 +1308,12 @@ type InlineAccessUpdateSessionConfig = Omit<ParsedUpdateSessionConfig, 'experime
1308
/** Update input that applies a saved Session config. */
1309
type SavedConfigUpdateSessionConfig = Omit<
1310
ParsedUpdateSessionConfig,
1172
- 'toolkits' | 'tools' | 'tags' | 'experimental'
1311
+ 'toolkits' | 'tools' | 'tags' | 'hooks' | 'experimental'
1312
> & {
1313
toolkits?: never;
1314
tools?: never;
1315
tags?: never;
1316
+ hooks?: never;
1317
experimental: Omit<ParsedUpdateSessionExperimental, 'sessionConfigId'> & {
1318
sessionConfigId: string;
1319
};
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts
+115
-4
@@ -8,10 +8,54 @@ import type {
8
import z from 'zod/v3';
9
import { ComposioToolInputRequiredError } from '../../errors/ToolRouterErrors';
10
import { ValidationError } from '../../errors/ValidationErrors';
11
-import type { ToolRouterSessionExecuteResponse } from '../../types/toolRouter.types';
11
+import {
12
+ ToolRouterHookResultSchema,
13
+ type ToolRouterSessionExecuteResponse,
14
+ type ToolRouterSessionProxyExecuteResponse,
15
+} from '../../types/toolRouter.types';
16
13
-/** The `result_type` values of a call that ran. `input_required` is raised before this is read. */
14
-const ExecutedResponseSchema = z.object({ result_type: z.enum(['completed', 'failed']) });
17
+/**
18
+ * The `result_type` values of a call that ran, with the results of the
19
+ * session hooks that applied. `input_required` and `blocked` are handled
20
+ * before this is read.
21
+ */
22
+const ExecutedResponseSchema = z.object({
23
+ result_type: z.enum(['completed', 'failed']),
24
+ hook_results: z.array(ToolRouterHookResultSchema).optional(),
25
+});
26
+
27
+/** A call a session hook blocked. The generated client does not type it yet. */
28
+const BlockedResponseSchema = z.object({
29
+ result_type: z.literal('blocked'),
30
+ reason: z.object({
31
+ type: z.enum(['request_blocked', 'response_blocked']),
32
+ hook_id: z.string(),
33
+ }),
34
+ message: z.string(),
35
+ // Only session execute carries these; session proxy execute leaves them out.
36
+ log_id: z.string().optional(),
37
+ instant_charge: z.unknown().optional(),
38
+ hook_results: z.array(ToolRouterHookResultSchema).optional(),
39
+});
40
+type BlockedResponse = z.infer<typeof BlockedResponseSchema>;
41
+
42
+const IsBlockedSchema = z.object({ result_type: z.literal('blocked') });
43
+
44
+/**
45
+ * Reads a `blocked` response, or returns `undefined` for any other
46
+ * `result_type`. A `blocked` response that does not match its schema is
47
+ * raised rather than read as a result.
48
+ */
49
+function parseBlockedResponse(raw: unknown, subject: string): BlockedResponse | undefined {
50
+ if (!IsBlockedSchema.safeParse(raw).success) return undefined;
51
+ const blocked = BlockedResponseSchema.safeParse(raw);
52
+ if (!blocked.success) {
53
+ throw new ValidationError(`${subject} returned a malformed blocked response`, {
54
+ cause: blocked.error,
55
+ });
56
+ }
57
+ return blocked.data;
58
+}
59
60
/**
61
* Whether a session tool execution succeeded. `resultType` decides: a `failed`
@@ -210,8 +254,25 @@ export function transformSearchResponse(raw: RawSearchResponse) {
254
* @throws {ComposioToolInputRequiredError} If the tool asked for user input instead of running
255
* @throws {ValidationError} If the response carries no `result_type`, or one this SDK does not know
256
*/
213
-export function transformExecuteResponse(raw: SessionExecuteResponse, toolSlug: string) {
257
+export function transformExecuteResponse(
258
+ raw: SessionExecuteResponse,
259
+ toolSlug: string
260
+): ToolRouterSessionExecuteResponse {
261
assertNotInputRequired(raw, `Tool ${toolSlug}`);
262
+ const blocked = parseBlockedResponse(raw, `Tool ${toolSlug}`);
263
+ if (blocked) {
264
+ // The agent reads `error`, so a blocked call reaches it as a failed call
265
+ // with the hook's message.
266
+ return {
267
+ data: {},
268
+ error: blocked.message,
269
+ logId: blocked.log_id ?? '',
270
+ resultType: 'blocked',
271
+ blockReason: { type: blocked.reason.type, hookId: blocked.reason.hook_id },
272
+ ...(blocked.hook_results !== undefined && { hookResults: blocked.hook_results }),
273
+ ...(blocked.instant_charge !== undefined && { instantCharge: blocked.instant_charge }),
274
+ };
275
+ }
276
const executed = ExecutedResponseSchema.safeParse(raw);
277
if (!executed.success) {
278
throw new ValidationError(
@@ -225,5 +286,55 @@ export function transformExecuteResponse(raw: SessionExecuteResponse, toolSlug:
286
logId: raw.log_id,
287
resultType: executed.data.result_type,
288
...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
289
+ ...(executed.data.hook_results !== undefined && { hookResults: executed.data.hook_results }),
290
+ };
291
+}
292
+
293
+/** Hook results on a proxied request that was sent. */
294
+const ProxyCompletedHookResultsSchema = z.object({
295
+ hook_results: z.array(ToolRouterHookResultSchema).optional(),
296
+});
297
+
298
+/**
299
+ * Projects a session proxy execute response onto the SDK's shape: a request a
300
+ * session hook blocked comes back as `resultType: 'blocked'` with no HTTP
301
+ * response.
302
+ */
303
+export function transformProxyExecuteResponse(
304
+ raw: SessionProxyExecuteResponse,
305
+ subject: string
306
+): ToolRouterSessionProxyExecuteResponse {
307
+ assertNotInputRequired(raw, subject);
308
+ const blocked = parseBlockedResponse(raw, subject);
309
+ if (blocked) {
310
+ return {
311
+ resultType: 'blocked',
312
+ blockReason: { type: blocked.reason.type, hookId: blocked.reason.hook_id },
313
+ message: blocked.message,
314
+ ...(blocked.hook_results !== undefined && { hookResults: blocked.hook_results }),
315
+ };
316
+ }
317
+ const hookResults = ProxyCompletedHookResultsSchema.safeParse(raw);
318
+ if (!hookResults.success) {
319
+ throw new ValidationError(`${subject} returned malformed hook results`, {
320
+ cause: hookResults.error,
321
+ });
322
+ }
323
+ return {
324
+ resultType: 'completed',
325
+ status: raw.status,
326
+ data: raw.data,
327
+ headers: raw.headers,
328
+ ...(raw.binary_data && {
329
+ binaryData: {
330
+ contentType: raw.binary_data.content_type,
331
+ size: raw.binary_data.size,
332
+ url: raw.binary_data.url,
333
+ expiresAt: raw.binary_data.expires_at,
334
+ },
335
+ }),
336
+ ...(hookResults.data.hook_results !== undefined && {
337
+ hookResults: hookResults.data.hook_results,
338
+ }),
339
};
340
}
ts/packages/core/test/lib/toolRouterParams.test.ts
+47
@@ -226,6 +226,53 @@ describe('transformToolRouterUpdateParams', () => {
226
});
227
});
228
229
+ it('maps hooks to snake_case, and null removes every hook', () => {
230
+ expect(
231
+ transformToolRouterUpdateParams({
232
+ hooks: [
233
+ {
234
+ type: 'before_execute',
235
+ id: 'no_external_email',
236
+ name: 'No external email',
237
+ appliesTo: { toolkits: ['gmail'] },
238
+ handler: {
239
+ type: 'prompt',
240
+ prompt: 'Sending email to anyone outside example.org',
241
+ onMatch: 'block',
242
+ },
243
+ },
244
+ {
245
+ type: 'after_execute',
246
+ id: 'block_injection',
247
+ appliesTo: 'all',
248
+ handler: { type: 'prompt_injection', onMatch: 'block' },
249
+ },
250
+ ],
251
+ })
252
+ ).toEqual({
253
+ hooks: [
254
+ {
255
+ type: 'before_execute',
256
+ id: 'no_external_email',
257
+ name: 'No external email',
258
+ applies_to: { toolkits: ['gmail'] },
259
+ handler: {
260
+ type: 'prompt',
261
+ prompt: 'Sending email to anyone outside example.org',
262
+ on_match: 'block',
263
+ },
264
+ },
265
+ {
266
+ type: 'after_execute',
267
+ id: 'block_injection',
268
+ applies_to: 'all',
269
+ handler: { type: 'prompt_injection', on_match: 'block' },
270
+ },
271
+ ],
272
+ });
273
+ expect(transformToolRouterUpdateParams({ hooks: null })).toEqual({ hooks: null });
274
+ });
275
+
276
it('keeps an empty toolkit allowlist in the request', () => {
277
expect(transformToolRouterUpdateParams({ toolkits: [] })).toEqual({
278
toolkits: { enable: [] },
ts/packages/core/test/models/customTool.test.ts
+1
@@ -896,6 +896,7 @@ describe('SessionContextImpl', () => {
896
{ maxRetries: 0 }
897
);
898
expect(result).toEqual({
899
+ resultType: 'completed',
900
status: 200,
901
data: { proxy_result: true },
902
});
ts/packages/core/test/models/customToolRouting.test.ts
+1
@@ -410,6 +410,7 @@ describe('ToolRouterSession execution routing', () => {
410
{ maxRetries: 0 }
411
);
412
expect(result).toEqual({
413
+ resultType: 'completed',
414
status: 200,
415
data: { ok: true },
416
headers: { 'x-test': '1' },
ts/packages/core/test/models/inputRequiredExecution.test.ts
+1
@@ -224,6 +224,7 @@ describe('execution that requires user input', () => {
224
});
225
226
await expect(createSession(client).proxyExecute(proxyParams)).resolves.toEqual({
227
+ resultType: 'completed',
228
status: 201,
229
data: { id: 1 },
230
headers: { 'x-request-id': 'req_1' },
ts/packages/core/test/models/sessionHooksExecution.test.ts
new
+192
@@ -0,0 +1,192 @@
1
+import { describe, it, expect, vi } from 'vitest';
2
+import ComposioClient, { Auth, createFetchTransport } from '@composio/client';
3
+import { Tools } from '../../src/models/Tools';
4
+import { ToolRouterSession } from '../../src/models/ToolRouterSession';
5
+import { SessionContextImpl } from '../../src/models/SessionContext';
6
+import { ValidationError } from '../../src/errors';
7
+import { MockProvider } from '../utils/mocks/provider.mock';
8
+
9
+vi.mock('../../src/telemetry/Telemetry', () => ({
10
+ telemetry: { instrument: vi.fn() },
11
+}));
12
+
13
+// A session hook can block a call before it runs, or block its result before
14
+// the agent sees it. The API answers with `result_type: "blocked"`, which has
15
+// no data and no HTTP response. These tests run a real client against a
16
+// stubbed `fetch` so they cover the wire shape the SDK reads.
17
+
18
+const SESSION_ID = 'sess_123';
19
+
20
+const blockedCall = {
21
+ result_type: 'blocked',
22
+ reason: { type: 'request_blocked', hook_id: 'no_external_email' },
23
+ message: 'Blocked by session policy: No external email',
24
+ log_id: '',
25
+ hook_results: [{ id: 'no_external_email', status: 'evaluated', outcome: 'block' }],
26
+};
27
+
28
+const blockedResponse = {
29
+ result_type: 'blocked',
30
+ reason: { type: 'response_blocked', hook_id: 'no_outside_data' },
31
+ message: 'Blocked by session policy',
32
+ log_id: 'log_456',
33
+ instant_charge: { amount: '0.01', currency: 'USD', charged_by: 'composio' },
34
+ hook_results: [{ id: 'no_outside_data', status: 'unavailable', reason: 'timeout' }],
35
+};
36
+
37
+const { log_id: _logId, ...blockedProxy } = blockedCall;
38
+
39
+const createClient = (body: unknown) => {
40
+ const fetch = vi.fn<typeof globalThis.fetch>(
41
+ async () =>
42
+ new Response(JSON.stringify(body), {
43
+ status: 200,
44
+ headers: { 'content-type': 'application/json' },
45
+ })
46
+ );
47
+ const client = new ComposioClient({
48
+ auth: Auth.project('test-api-key'),
49
+ baseURL: 'https://backend.invalid',
50
+ transport: createFetchTransport({ fetch }),
51
+ });
52
+ return { client, fetch };
53
+};
54
+
55
+const createSession = (client: ComposioClient) =>
56
+ new ToolRouterSession(client, { apiKey: 'key', provider: new MockProvider() }, SESSION_ID, {
57
+ type: 'http' as const,
58
+ url: `https://backend.invalid/api/v3/tool_router/session/${SESSION_ID}`,
59
+ });
60
+
61
+const proxyParams = {
62
+ toolkit: 'gmail',
63
+ endpoint: '/gmail/v1/users/me/messages/send',
64
+ method: 'POST' as const,
65
+ body: { raw: 'VG86IGNlb0ByaXZhbC5jb20' },
66
+};
67
+
68
+describe('session execute when a hook blocks the call', () => {
69
+ it.each([
70
+ {
71
+ name: 'session.execute',
72
+ run: (client: ComposioClient) =>
73
+ createSession(client).execute('GMAIL_SEND_EMAIL', { to: 'ceo@rival.com' }),
74
+ },
75
+ {
76
+ name: 'custom tool context execute',
77
+ run: (client: ComposioClient) =>
78
+ new SessionContextImpl(client, 'test-user', SESSION_ID).execute('GMAIL_SEND_EMAIL', {
79
+ to: 'ceo@rival.com',
80
+ }),
81
+ },
82
+ ])('$name returns resultType blocked with the message in error', async ({ run }) => {
83
+ const { client } = createClient(blockedCall);
84
+
85
+ await expect(run(client)).resolves.toEqual({
86
+ data: {},
87
+ error: 'Blocked by session policy: No external email',
88
+ logId: '',
89
+ resultType: 'blocked',
90
+ blockReason: { type: 'request_blocked', hookId: 'no_external_email' },
91
+ hookResults: [{ id: 'no_external_email', status: 'evaluated', outcome: 'block' }],
92
+ });
93
+ });
94
+
95
+ it('keeps the log id and the charge when the tool ran and its result was blocked', async () => {
96
+ const { client } = createClient(blockedResponse);
97
+
98
+ await expect(createSession(client).execute('GMAIL_FETCH_EMAILS', {})).resolves.toEqual({
99
+ data: {},
100
+ error: 'Blocked by session policy',
101
+ logId: 'log_456',
102
+ resultType: 'blocked',
103
+ blockReason: { type: 'response_blocked', hookId: 'no_outside_data' },
104
+ hookResults: [{ id: 'no_outside_data', status: 'unavailable', reason: 'timeout' }],
105
+ instantCharge: { amount: '0.01', currency: 'USD', charged_by: 'composio' },
106
+ });
107
+ });
108
+
109
+ // Every provider hands the agent `{ data, error, successful }`, so this is
110
+ // what the agent sees in any framework.
111
+ it('reaches the agent as a failed call with the hook message', async () => {
112
+ const { client } = createClient(blockedCall);
113
+
114
+ const result = await new Tools(client, { provider: new MockProvider() }).executeSessionTool(
115
+ 'GMAIL_SEND_EMAIL',
116
+ { sessionId: SESSION_ID, arguments: { to: 'ceo@rival.com' } }
117
+ );
118
+
119
+ expect(result).toEqual({
120
+ data: {},
121
+ error: 'Blocked by session policy: No external email',
122
+ successful: false,
123
+ logId: '',
124
+ });
125
+ });
126
+
127
+ it('returns the hook results of a call that ran', async () => {
128
+ const { client } = createClient({
129
+ result_type: 'completed',
130
+ data: { id: 'msg_1' },
131
+ error: null,
132
+ log_id: 'log_1',
133
+ hook_results: [{ id: 'no_external_email', status: 'evaluated', outcome: 'continue' }],
134
+ });
135
+
136
+ await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).resolves.toEqual({
137
+ data: { id: 'msg_1' },
138
+ error: null,
139
+ logId: 'log_1',
140
+ resultType: 'completed',
141
+ hookResults: [{ id: 'no_external_email', status: 'evaluated', outcome: 'continue' }],
142
+ });
143
+ });
144
+
145
+ it('raises a blocked response that is missing its reason', async () => {
146
+ const { reason: _reason, ...malformed } = blockedCall;
147
+ const { client } = createClient(malformed);
148
+
149
+ await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).rejects.toThrow(
150
+ ValidationError
151
+ );
152
+ });
153
+});
154
+
155
+describe('session proxy execute when a hook blocks the request', () => {
156
+ it.each([
157
+ {
158
+ name: 'session.proxyExecute',
159
+ run: (client: ComposioClient) => createSession(client).proxyExecute(proxyParams),
160
+ },
161
+ {
162
+ name: 'custom tool context proxyExecute',
163
+ run: (client: ComposioClient) =>
164
+ new SessionContextImpl(client, 'test-user', SESSION_ID).proxyExecute(proxyParams),
165
+ },
166
+ ])('$name returns resultType blocked with no HTTP response', async ({ run }) => {
167
+ const { client } = createClient(blockedProxy);
168
+
169
+ await expect(run(client)).resolves.toEqual({
170
+ resultType: 'blocked',
171
+ blockReason: { type: 'request_blocked', hookId: 'no_external_email' },
172
+ message: 'Blocked by session policy: No external email',
173
+ hookResults: [{ id: 'no_external_email', status: 'evaluated', outcome: 'block' }],
174
+ });
175
+ });
176
+
177
+ it('marks a request that was sent as completed', async () => {
178
+ const { client } = createClient({
179
+ result_type: 'completed',
180
+ status: 200,
181
+ data: { id: 'msg_1' },
182
+ headers: { 'content-type': 'application/json' },
183
+ });
184
+
185
+ await expect(createSession(client).proxyExecute(proxyParams)).resolves.toEqual({
186
+ resultType: 'completed',
187
+ status: 200,
188
+ data: { id: 'msg_1' },
189
+ headers: { 'content-type': 'application/json' },
190
+ });
191
+ });
192
+});
ts/packages/core/test/models/toolRouter.test.ts
+50
@@ -239,6 +239,56 @@ describe('ToolRouter', () => {
239
expect(bodies[4]).not.toHaveProperty('proxy_execute');
240
});
241
242
+ it('sends hooks in snake_case, and omits them otherwise', async () => {
243
+ mockClient.toolRouter.session.create.mockResolvedValue(mockSessionCreateResponse);
244
+
245
+ await toolRouter.create(userId, {
246
+ hooks: [
247
+ {
248
+ type: 'after_execute',
249
+ id: 'block_injection',
250
+ appliesTo: 'all',
251
+ handler: { type: 'prompt_injection', onMatch: 'block' },
252
+ },
253
+ ],
254
+ });
255
+ await toolRouter.create(userId);
256
+
257
+ const bodies = mockClient.toolRouter.session.create.mock.calls.map(call => call[0]);
258
+ expect(bodies[0]).toMatchObject({
259
+ hooks: [
260
+ {
261
+ type: 'after_execute',
262
+ id: 'block_injection',
263
+ applies_to: 'all',
264
+ handler: { type: 'prompt_injection', on_match: 'block' },
265
+ },
266
+ ],
267
+ });
268
+ expect(bodies[1]).not.toHaveProperty('hooks');
269
+ });
270
+
271
+ it('rejects hooks together with a saved session config', async () => {
272
+ await expect(
273
+ toolRouter.create(
274
+ userId,
275
+ // @ts-expect-error hooks cannot be combined with sessionConfigId
276
+ {
277
+ hooks: [
278
+ {
279
+ type: 'after_execute',
280
+ id: 'block_injection',
281
+ appliesTo: 'all',
282
+ handler: { type: 'prompt_injection', onMatch: 'block' },
283
+ },
284
+ ],
285
+ experimental: { sessionConfigId: 'sc_1' },
286
+ }
287
+ )
288
+ ).rejects.toThrow();
289
+ expect(mockClient.toolRouter.session.create).not.toHaveBeenCalled();
290
+ });
291
+
292
it('rejects a proxyExecute block without enable', async () => {
293
await expect(
294
// @ts-expect-error enable is required