@devries-cameron20 / composio Mirror · read-only / commits / f1898b67c
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, 08:30 UTC

fix(sdk): enforce hooks/session-config parity and precise hook_results errors

Review findings on #4958: - Python now rejects `hooks` combined with `experimental.session_config_id` on create() and update(), matching the TS zod refinement (update() co-PATCHed both fields; create() silently dropped session_config_id). - TS execute responses validate `hook_results` in a dedicated step so shape drift raises "returned malformed hook results" instead of the misleading "without a known result_type"; tests pin the error contract in both SDKs.

jkomyno committed Oct 20, 2026 at 19:19 UTC f1898b67c82e33c0c485b1d38f6738585a26acbc
5 files changed +124 -10
python/composio/core/models/tool_router.py
+10
@@ -1190,6 +1190,16 @@ class ToolRouter(Resource, t.Generic[TTool, TToolCollection]):
1190 if proxy_execute is not None:
1191 create_params["proxy_execute"] = _proxy_execute_payload(proxy_execute)
1192 if hooks is not None:
1193 + if (
1194 + experimental is not None
1195 + and t.cast(t.Dict[str, t.Any], experimental).get("session_config_id")
1196 + is not None
1197 + ):
1198 + raise InvalidParams(
1199 + "`hooks` cannot be combined with "
1200 + "`experimental={'session_config_id': ...}`; create the session "
1201 + "from the saved config and add hooks in a separate update() call"
1202 + )
1203 # The generated client has no typed parameter for ``hooks`` yet.
1204 create_params["extra_body"] = {"hooks": hooks}
1205
python/composio/core/models/tool_router_session.py
+12 -1
@@ -1298,7 +1298,8 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
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.
1301 + hook. ``hooks`` cannot be combined with
1302 + ``experimental={'session_config_id': ...}`` (``hooks=None`` counts).
1303
1304 By default the request carries no precondition: the last writer wins.
1305 Pass ``expected_config_version`` (for example this object's
@@ -1335,6 +1336,16 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
1336 "`instant` does not accept None; pass False to disable "
1337 "Instant usage, or omit it to keep the stored policy"
1338 )
1339 + if (
1340 + not isinstance(hooks, Omit)
1341 + and isinstance(experimental, dict)
1342 + and experimental.get("session_config_id") is not None
1343 + ):
1344 + raise exceptions.InvalidParams(
1345 + "`hooks` cannot be combined with `experimental={'session_config_id': ...}`; "
1346 + "a saved Session config sets the session's access policy, so apply "
1347 + "hooks in a separate update"
1348 + )
1349
1350 precondition: t.Union[int, "Omit"]
1351 if expected_config_version is None or expected_config_version is False:
python/tests/test_tool_router.py
+58
@@ -2875,6 +2875,37 @@ class TestSessionHooks:
2875 body = json.loads(requests[-1].content)
2876 assert body["hooks"] == expected
2877
2878 + @pytest.mark.parametrize(
2879 + "hooks",
2880 + [
2881 + pytest.param(_HOOKS, id="replace"),
2882 + pytest.param(None, id="remove"),
2883 + ],
2884 + )
2885 + def test_update_rejects_hooks_with_session_config_id(self, hooks):
2886 + client, requests = _transport_client(
2887 + auth=ProjectAuth("ak_test"), base_url="https://backend.composio.dev"
2888 + )
2889 + session = _created_session(client)
2890 + requests.clear()
2891 +
2892 + with pytest.raises(InvalidParams):
2893 + session.update(hooks=hooks, experimental={"session_config_id": "sc_1"})
2894 +
2895 + assert requests == []
2896 +
2897 + def test_create_rejects_hooks_with_session_config_id(
2898 + self, tool_router, mock_client
2899 + ):
2900 + with pytest.raises(InvalidParams):
2901 + tool_router.create(
2902 + user_id="user_123",
2903 + hooks=self._HOOKS,
2904 + experimental=t.cast(t.Any, {"session_config_id": "sc_1"}),
2905 + )
2906 +
2907 + mock_client.tool_router.session.create.assert_not_called()
2908 +
2909 @pytest.mark.parametrize(
2910 "run",
2911 [
@@ -3012,6 +3043,19 @@ class TestSessionHooks:
3043 with pytest.raises(ValidationError):
3044 _created_session(client).execute("GMAIL_SEND_EMAIL", arguments={})
3045
3046 + def test_malformed_hook_results_is_raised(self):
3047 + """A completed response whose hook results violate the schema raises a
3048 + malformed hook results error, not an unknown result_type."""
3049 + client, _ = _answering_client(
3050 + {
3051 + **_COMPLETED_JSON,
3052 + "hook_results": [{"id": "block_injection", "status": "nope"}],
3053 + }
3054 + )
3055 +
3056 + with pytest.raises(ValidationError, match="malformed hook results"):
3057 + _created_session(client).execute("GMAIL_SEND_EMAIL", arguments={})
3058 +
3059 @pytest.mark.parametrize(
3060 "run",
3061 [
@@ -3041,6 +3085,20 @@ class TestSessionHooks:
3085 ],
3086 }
3087
3088 + def test_proxy_execute_malformed_hook_results_is_raised(self):
3089 + client, _ = _answering_client(
3090 + {
3091 + "result_type": "completed",
3092 + "status": 200,
3093 + "data": {"id": 1},
3094 + "headers": {},
3095 + "hook_results": [{"id": "block_injection", "status": "nope"}],
3096 + }
3097 + )
3098 +
3099 + with pytest.raises(ValidationError, match="malformed hook results"):
3100 + _created_session(client).proxy_execute(**_PROXY_PARAMS)
3101 +
3102
3103 class _NoInput(BaseModel):
3104 pass
ts/packages/core/src/utils/transformers/toolRouterResponseTransform.ts
+16 -9
@@ -15,13 +15,12 @@ import {
15 } from '../../types/toolRouter.types';
16
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.
18 + * The `result_type` values of a call that ran. `input_required` and `blocked`
19 + * are handled before this is read. `hook_results` is validated in its own step
20 + * so a shape drift there doesn't read as an unknown `result_type`.
21 */
22 const ExecutedResponseSchema = z.object({
23 result_type: z.enum(['completed', 'failed']),
24 - hook_results: z.array(ToolRouterHookResultSchema).optional(),
24 });
25
26 /** A call a session hook blocked. The generated client does not type it yet. */
@@ -252,7 +251,7 @@ export function transformSearchResponse(raw: RawSearchResponse) {
251 * Transforms a raw session execute API response to camelCase.
252 *
253 * @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
254 + * @throws {ValidationError} If the response carries no `result_type`, one this SDK does not know, or malformed `hook_results`
255 */
256 export function transformExecuteResponse(
257 raw: SessionExecuteResponse,
@@ -280,18 +279,26 @@ export function transformExecuteResponse(
279 { cause: executed.error }
280 );
281 }
282 + const hookResults = CompletedHookResultsSchema.safeParse(raw);
283 + if (!hookResults.success) {
284 + throw new ValidationError(`Tool ${toolSlug} returned malformed hook results`, {
285 + cause: hookResults.error,
286 + });
287 + }
288 return {
289 data: raw.data,
290 error: raw.error,
291 logId: raw.log_id,
292 resultType: executed.data.result_type,
293 ...(raw.instant_charge !== undefined && { instantCharge: raw.instant_charge }),
289 - ...(executed.data.hook_results !== undefined && { hookResults: executed.data.hook_results }),
294 + ...(hookResults.data.hook_results !== undefined && {
295 + hookResults: hookResults.data.hook_results,
296 + }),
297 };
298 }
299
293 -/** Hook results on a proxied request that was sent. */
294 -const ProxyCompletedHookResultsSchema = z.object({
300 +/** Hook results on a call that ran: session execute, or a proxied request that was sent. */
301 +const CompletedHookResultsSchema = z.object({
302 hook_results: z.array(ToolRouterHookResultSchema).optional(),
303 });
304
@@ -314,7 +321,7 @@ export function transformProxyExecuteResponse(
321 ...(blocked.hook_results !== undefined && { hookResults: blocked.hook_results }),
322 };
323 }
317 - const hookResults = ProxyCompletedHookResultsSchema.safeParse(raw);
324 + const hookResults = CompletedHookResultsSchema.safeParse(raw);
325 if (!hookResults.success) {
326 throw new ValidationError(`${subject} returned malformed hook results`, {
327 cause: hookResults.error,
ts/packages/core/test/models/sessionHooksExecution.test.ts
+28
@@ -157,6 +157,20 @@ describe('session execute when a hook blocks the call', () => {
157 ValidationError
158 );
159 });
160 +
161 + it('raises malformed hook results on a completed call as malformed hook results', async () => {
162 + const { client } = createClient({
163 + result_type: 'completed',
164 + data: { id: 'msg_1' },
165 + error: null,
166 + log_id: 'log_1',
167 + hook_results: [{ id: 'no_external_email', status: 'nope' }],
168 + });
169 +
170 + await expect(createSession(client).execute('GMAIL_SEND_EMAIL', {})).rejects.toThrow(
171 + 'returned malformed hook results'
172 + );
173 + });
174 });
175
176 describe('session proxy execute when a hook blocks the request', () => {
@@ -196,4 +210,18 @@ describe('session proxy execute when a hook blocks the request', () => {
210 headers: { 'content-type': 'application/json' },
211 });
212 });
213 +
214 + it('raises malformed hook results on a completed response as malformed hook results', async () => {
215 + const { client } = createClient({
216 + result_type: 'completed',
217 + status: 200,
218 + data: { id: 'msg_1' },
219 + headers: {},
220 + hook_results: [{ id: 'no_external_email', status: 'nope' }],
221 + });
222 +
223 + await expect(createSession(client).proxyExecute(proxyParams)).rejects.toThrow(
224 + 'returned malformed hook results'
225 + );
226 + });
227 });