@devries-cameron20 / composio-1 / commits / 2f6a8a5ec
Fork 0

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

fix(python): own the proxy_execute response shape (#4180)

> ### ⚠️ Breaking change > > `proxy_execute()` now returns a dict instead of the generated `SessionProxyExecuteResponse` model. Every caller since `py@0.11.4` that reads the result with attribute access breaks at runtime with `AttributeError`. > > ```python > # before > response.status > > # after > response["status"] > ``` > > `data`, `headers`, and `binary_data` follow the same rule. No version bump or changelog entry ships in this PR. That omission is deliberate, so the release call stays explicit. Details below. ## Summary Builds on @AseemPrasad's #4163, which spotted a real problem. Python's `proxy_execute()` returns the generated client's `SessionProxyExecuteResponse` directly, while TypeScript's `proxyExecute()` projects onto a curated shape. Returning the generated model leaks a regenerated artifact into a public SDK return type. This PR keeps that fix and resolves the review findings on top. #4163's commit is preserved with its original authorship. The commits on top carry the correction and the review fixes. ## What changed relative to #4163 | | #4163 | Here | |---|---|---| | Key casing | `binaryData`, `contentType`, `expiresAt` | `binary_data`, `content_type`, `expires_at` | | `status` type | declared `int`, returned `200.0` | declared `int`, returns `200` | | Test doubles | `SimpleNamespace` | real `SessionProxyExecuteResponse` / `BinaryData` | | `mypy` | fails `nox -s chk` | clean | | Docs | 3 snippets left broken | fixed | **Casing.** Python public APIs use snake_case and TypeScript public APIs use camelCase. The fields and their meanings match across SDKs, and the spelling follows each language. `session.delete()` already works this way (`session_id` in Python, `sessionId` in TypeScript), and so does `RemoteFile` (`expires_at` / `expiresAt`). **`status` and `size` are narrowed to `int`.** The generated model types both as `float` and pydantic coerces, so a response read straight off it renders `200.0` where TypeScript renders `200`. #4163 declared `int` but still returned `200.0`. That mismatch also failed `nox -s chk`: ``` composio/core/models/session_context.py:56: error: Incompatible types (expression has type "float", TypedDict item "status" has type "int") [typeddict-item] ``` **Tests use the real generated models again.** `SimpleNamespace` accepts any attribute name and any type, so it silently tolerates a client regeneration that renames or retypes a field. It was also what hid the `float` coercion, since `assert result == {"status": 200}` passes against `200.0`. The suite now asserts the narrowed types directly. This matters ahead of the `composio-client` 2.x migration, which types every response field as `Any` and removes type checking on this projection entirely. The tests become the only remaining check. **Simplification.** The projection folds into `proxy_execute_impl`, so both entry points are a single call rather than an impl-then-normalize pair. `response.binary_data` is read directly instead of through `getattr(..., None)`. The defensive default could never fire on a typed response, but it made mypy infer `Any` and stop checking the projection. **Docs.** Three Python snippets that read the result as attributes are fixed, and the response-shape table gets a per-language column. The follow-up commit also marks `headers` and `data` as nullable in that table, replaces the "returns the upstream response verbatim" claim with what the projection actually does, and documents that `expires_at` can be absent in TypeScript and `None` in Python. ## Breaking change The method has shipped since `py@0.11.4`. Both directions of the old access pattern were already inconsistent in the repo. `python/examples/custom_tools_agent_test.py:95` does `res["status"]`, which raises `TypeError` on `next` today and is fixed by this PR. The doc snippets did attribute access and are updated here. No changelog entry and no version bump are included. That is deliberate, so the release call stays explicit rather than implied by the merge. ## How Has This Been Tested? ```bash cd python mypy --config-file config/mypy.ini composio/ tests/ # clean ruff check --config config/ruff.toml composio/ tests/ # clean pytest tests/ # 1336 passed, 33 skipped ``` `ruff format` was run with the repo's pinned toolchain. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [x] Breaking change ## Checklist - [x] I ran linters/tests locally and they passed - [x] I updated documentation as needed - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages. Not applicable: `AGENTS.md` reserves changesets for published TypeScript packages https://claude.ai/code/session_01GsD8zvAhrjFwk144oWkD9K --------- Co-authored-by: AseemPrasad <aseemprasad0520@gmail.com> Co-authored-by: Kshitij Jhunjhunwala <113939507+KJ-11@users.noreply.github.com>

Alberto Schiabel committed Aug 23, 2026 at 00:30 UTC 2f6a8a5ec96eeb940c1dad9494260ab106f5f58f
8 files changed +229 -33
docs/content/docs/extending-sessions/custom-tools-and-toolkits.mdx
+1 -1
@@ -273,7 +273,7 @@ def send_promo_email(input: PromoEmailInput, ctx):
273 method="POST",
274 body={"raw": raw},
275 )
276 - return {"status": res.status, "to": input.to}
276 + return {"status": res["status"], "to": input.to}
277 ```
278 </Tab>
279 </Tabs>
docs/content/docs/extending-sessions/proxy-execute.mdx
+42 -9
@@ -38,8 +38,8 @@ response = session.proxy_execute(
38 ],
39 )
40
41 -print(response.status)
42 -print(response.data)
41 +print(response["status"])
42 +print(response["data"])
43 ```
44 </Tab>
45 <Tab value="TypeScript">
@@ -81,14 +81,47 @@ Proxy execute rejects cross-domain requests. The `endpoint` must resolve to the
81
82 ## Response shape
83
84 -The call returns the upstream response verbatim:
84 +The call forwards the upstream response's status, headers, and parsed body.
85 +Both SDKs expose the same fields; each spells them the way its language does, so
86 +TypeScript reads them as properties and Python as dictionary keys.
87
86 -| Field | Type | Description |
87 -|---|---|---|
88 -| `status` | `number` | HTTP status code from the upstream API. |
89 -| `data` | `unknown` | Parsed JSON body the API returned. |
90 -| `headers` | `Record<string, string>` | Response headers. |
91 -| `binaryData` | `object` | Present only when the upstream returns a file (`url`, `contentType`, `size`, `expiresAt`). |
88 +| TypeScript | Python | Type | Description |
89 +|---|---|---|---|
90 +| `status` | `status` | `number` / `int` | HTTP status code from the upstream API. |
91 +| `data` | `data` | `unknown` / `Any` | Parsed JSON body the API returned. Optional in TypeScript; in Python the key is always present but may be `None`. |
92 +| `headers` | `headers` | `Record<string, string>` / `dict[str, str] \| None` | Response headers. Optional in TypeScript; in Python the key is always present but may be `None`. |
93 +| `binaryData` | `binary_data` | `object` / `dict` | Present only when the upstream returns a file. |
94 +
95 +When the upstream returns a file, the binary entry carries `url`, `contentType`,
96 +`size`, and `expiresAt` in TypeScript, and `url`, `content_type`, `size`, and
97 +`expires_at` in Python. `expires_at` may be absent in TypeScript and `None` in
98 +Python when the upstream gives no expiry. The key is absent entirely when the
99 +response is not a file, so check for it before reading:
100 +
101 +<Tabs groupId="language" items={['Python', 'TypeScript']} persist>
102 +<Tab value="Python">
103 +```python
104 +if "binary_data" in response:
105 + print(response["binary_data"]["url"])
106 +```
107 +</Tab>
108 +<Tab value="TypeScript">
109 +```typescript
110 +import { Composio } from '@composio/core';
111 +const composio = new Composio({ apiKey: 'your_api_key' });
112 +const session = await composio.create('user_123', { toolkits: ['github'] });
113 +const response = await session.proxyExecute({
114 + toolkit: 'github',
115 + endpoint: '/repos/composiohq/composio/issues/1',
116 + method: 'GET',
117 +});
118 +// ---cut---
119 +if (response.binaryData) {
120 + console.log(response.binaryData.url);
121 +}
122 +```
123 +</Tab>
124 +</Tabs>
125
126 <Callout type="warn">
127 Don't set the `Authorization` header yourself through `parameters`. Composio injects the correct one from the connected account's auth scheme, and setting it manually overrides that credential and usually produces a `401`.
docs/content/docs/migration-guide/new-sdk.mdx
+1 -1
@@ -582,7 +582,7 @@ def get_issue_info(input: GetIssueInfoInput, ctx) -> dict:
582 endpoint=f"/repos/composiohq/composio/issues/{input.issue_number}",
583 method="GET",
584 )
585 - return {"data": result.data}
585 + return {"data": result["data"]}
586
587 session = composio.create(
588 user_id="default",
python/composio/core/models/__init__.py
+4
@@ -3,9 +3,11 @@ from .connected_accounts import ConnectedAccounts
3 from .custom_tool import ExperimentalToolkit
4 from .custom_tool_types import (
5 CustomTool,
6 + ProxyExecuteBinaryData,
7 RegisteredCustomTool,
8 RegisteredCustomToolkit,
9 SessionContext,
10 + ToolRouterSessionProxyExecuteResponse,
11 )
12 from .experimental import ExperimentalAPI
13 from .mcp import MCP
@@ -38,6 +40,7 @@ __all__ = [
40 "ExperimentalAPI",
41 "ExperimentalToolkit",
42 "MCP",
43 + "ProxyExecuteBinaryData",
44 "RegisteredCustomTool",
45 "RegisteredCustomToolkit",
46 "RemoteFile",
@@ -48,6 +51,7 @@ __all__ = [
51 "ToolRouterSession",
52 "ToolRouterSessionDeleteResponse",
53 "ToolRouterSessionFilesMount",
54 + "ToolRouterSessionProxyExecuteResponse",
55 "Toolkits",
56 "Tools",
57 "Triggers",
python/composio/core/models/custom_tool_types.py
+33 -5
@@ -15,9 +15,6 @@ from pydantic import BaseModel
15 from composio_client.types.tool_router.session_execute_response import (
16 SessionExecuteResponse,
17 )
18 -from composio_client.types.tool_router.session_proxy_execute_response import (
19 - SessionProxyExecuteResponse,
20 -)
18
19 from composio.utils.safe_path import SAFE_COMPONENT_REGEX
20
@@ -28,6 +25,37 @@ from composio.utils.safe_path import SAFE_COMPONENT_REGEX
25 LOCAL_TOOL_PREFIX = "LOCAL_"
26 MAX_SLUG_LENGTH = 60
27
28 +
29 +class ProxyExecuteBinaryData(te.TypedDict):
30 + """Binary payload metadata, present when the proxied API returned a file."""
31 +
32 + content_type: str
33 + size: int
34 + url: str
35 + expires_at: t.Optional[str]
36 +
37 +
38 +class ToolRouterSessionProxyExecuteResponse(te.TypedDict):
39 + """SDK-facing shape returned by ``proxy_execute()``.
40 +
41 + Field-for-field equivalent to the TypeScript SDK's
42 + ``ToolRouterSessionProxyExecuteResponse``, spelled in snake_case: the same
43 + fields carry the same meaning in both SDKs, each in its own language's
44 + convention. The generated client's model is deliberately not exposed --
45 + it is regenerated from the upstream spec, so returning it directly would
46 + let a regeneration reshape a public SDK return type.
47 +
48 + ``status`` and ``size`` are narrowed to ``int``. The generated model types
49 + both as ``float`` and pydantic coerces, so a response read straight off it
50 + renders ``200.0`` where TypeScript renders ``200``.
51 + """
52 +
53 + status: int
54 + data: t.Any
55 + headers: t.Optional[t.Dict[str, str]]
56 + binary_data: te.NotRequired[ProxyExecuteBinaryData]
57 +
58 +
59 SLUG_REGEX = SAFE_COMPONENT_REGEX
60 """Alias of the canonical pattern in :mod:`composio.utils.safe_path`.
61
@@ -87,10 +115,10 @@ class SessionContext(te.Protocol):
115 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
116 body: t.Any = None,
117 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
90 - ) -> SessionProxyExecuteResponse:
118 + ) -> ToolRouterSessionProxyExecuteResponse:
119 """Proxy API calls through Composio's auth layer.
120
93 - Returns the same response model as ``session.proxy_execute()``.
121 + Returns the same response shape as ``session.proxy_execute()``.
122 """
123 ...
124
python/composio/core/models/session_context.py
+28 -8
@@ -13,9 +13,6 @@ from composio_client.types.tool_router.session_proxy_execute_params import Param
13 from composio_client.types.tool_router.session_execute_response import (
14 SessionExecuteResponse,
15 )
16 -from composio_client.types.tool_router.session_proxy_execute_response import (
17 - SessionProxyExecuteResponse,
18 -)
16 from composio.client import HttpClient
17 from composio.core.models.custom_tool_execution import (
18 execute_custom_tool,
@@ -24,6 +21,7 @@ from composio.core.models.custom_tool_execution import (
21 from composio.core.models.custom_tool_types import (
22 CustomToolsMap,
23 InlineCustomToolsWirePayload,
24 + ToolRouterSessionProxyExecuteResponse,
25 )
26 from composio.core.models.inline_custom_tools_payload import (
27 inline_custom_tools_execute_experimental,
@@ -45,8 +43,12 @@ def proxy_execute_impl(
43 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
44 body: t.Any = None,
45 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
48 -) -> SessionProxyExecuteResponse:
49 - """Shared proxy execute implementation used by SessionContextImpl and ToolRouterSession."""
46 +) -> ToolRouterSessionProxyExecuteResponse:
47 + """Shared proxy execute implementation used by SessionContextImpl and ToolRouterSession.
48 +
49 + Projects the generated client's response model onto the SDK's own shape so
50 + the public return type does not move when the client is regenerated.
51 + """
52 # Client-side validation (matches TS SessionProxyExecuteParamsSchema)
53 if not toolkit:
54 raise ValidationError("proxy_execute: toolkit is required")
@@ -79,7 +81,7 @@ def proxy_execute_impl(
81 )
82 )
83
82 - return client.tool_router.session.proxy_execute(
84 + response = client.tool_router.session.proxy_execute(
85 session_id=session_id,
86 toolkit_slug=toolkit,
87 endpoint=endpoint,
@@ -88,6 +90,24 @@ def proxy_execute_impl(
90 parameters=api_params if api_params else omit,
91 )
92
93 + # ``status`` and ``size`` are ``float`` on the generated model and pydantic
94 + # coerces, so they arrive as ``200.0``/``123.0``. Narrow them here: an HTTP
95 + # status and a byte count are integers, and TypeScript reports them as such.
96 + result: ToolRouterSessionProxyExecuteResponse = {
97 + "status": int(response.status),
98 + "data": response.data,
99 + "headers": response.headers,
100 + }
101 + binary_data = response.binary_data
102 + if binary_data is not None:
103 + result["binary_data"] = {
104 + "content_type": binary_data.content_type,
105 + "size": int(binary_data.size),
106 + "url": binary_data.url,
107 + "expires_at": binary_data.expires_at,
108 + }
109 + return result
110 +
111
112 class SessionContextImpl:
113 """Concrete implementation of SessionContext.
@@ -159,10 +179,10 @@ class SessionContextImpl:
179 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
180 body: t.Any = None,
181 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
162 - ) -> SessionProxyExecuteResponse:
182 + ) -> ToolRouterSessionProxyExecuteResponse:
183 """Proxy API calls through Composio's auth layer.
184
165 - Returns the same response model as ``session.proxy_execute()``.
185 + Returns the same response shape as ``session.proxy_execute()``.
186 """
187 return proxy_execute_impl(
188 self._client,
python/composio/core/models/tool_router_session.py
+6 -5
@@ -23,9 +23,6 @@ from composio_client.types.tool_router import session_link_params, session_patch
23 from composio_client.types.tool_router.session_execute_response import (
24 SessionExecuteResponse,
25 )
26 -from composio_client.types.tool_router.session_proxy_execute_response import (
27 - SessionProxyExecuteResponse,
28 -)
26 from composio_client.types.tool_router.session_search_response import (
27 SessionSearchResponse,
28 )
@@ -44,6 +41,7 @@ from composio.core.models.custom_tool_types import (
41 CustomToolsMap,
42 CustomToolsMapEntry,
43 InlineCustomToolsWirePayload,
44 + ToolRouterSessionProxyExecuteResponse,
45 RegisteredCustomTool,
46 RegisteredCustomToolkit,
47 )
@@ -52,7 +50,10 @@ from composio.core.models.inline_custom_tools_payload import (
50 inline_custom_tools_execute_experimental,
51 inline_custom_tools_search_experimental,
52 )
55 -from composio.core.models.session_context import SessionContextImpl, proxy_execute_impl
53 +from composio.core.models.session_context import (
54 + SessionContextImpl,
55 + proxy_execute_impl,
56 +)
57 from composio.core.models.tool_router_session_delete import (
58 ToolRouterSessionDeleteResponse,
59 delete_tool_router_session,
@@ -812,7 +813,7 @@ class ToolRouterSession(t.Generic[TTool, TToolCollection]):
813 method: t.Literal["GET", "POST", "PUT", "DELETE", "PATCH"],
814 body: t.Any = None,
815 parameters: t.Optional[t.List[t.Dict[str, t.Any]]] = None,
815 - ) -> SessionProxyExecuteResponse:
816 + ) -> ToolRouterSessionProxyExecuteResponse:
817 """Proxy an API call through Composio's auth layer.
818
819 :param toolkit: Composio toolkit slug (e.g. 'gmail', 'github')
python/tests/test_custom_tools.py
+114 -4
@@ -21,6 +21,7 @@ from composio_client.types.tool_router.session_execute_response import (
21 SessionExecuteResponse,
22 )
23 from composio_client.types.tool_router.session_proxy_execute_response import (
24 + BinaryData,
25 SessionProxyExecuteResponse,
26 )
27 from pydantic import BaseModel, Field
@@ -612,8 +613,85 @@ class TestSessionContextImpl:
613 result = ctx.proxy_execute(
614 toolkit="gmail", endpoint="https://example.com", method="GET"
615 )
615 - assert isinstance(result, SessionProxyExecuteResponse)
616 - assert result.status == 200
616 + assert result == {"status": 200, "data": {"ok": True}, "headers": {}}
617 + assert "binary_data" not in result
618 +
619 + def test_proxy_execute_narrows_status_to_int(self):
620 + """The generated model types ``status`` as ``float`` and pydantic coerces.
621 +
622 + Equality alone cannot catch the leak, because ``200 == 200.0``. Only the
623 + type assertion distinguishes ``200`` from the ``200.0`` a raw read returns.
624 + """
625 + mock_client = MagicMock()
626 + mock_client.tool_router.session.proxy_execute.return_value = (
627 + SessionProxyExecuteResponse(
628 + status=200, data=None, headers=None, binary_data=None
629 + )
630 + )
631 + ctx = SessionContextImpl(client=mock_client, user_id="u", session_id="s")
632 + result = ctx.proxy_execute(
633 + toolkit="gmail", endpoint="https://example.com", method="GET"
634 + )
635 + assert isinstance(result["status"], int)
636 + assert result == {"status": 200, "data": None, "headers": None}
637 +
638 + def test_proxy_execute_projects_binary_data(self):
639 + mock_client = MagicMock()
640 + mock_client.tool_router.session.proxy_execute.return_value = (
641 + SessionProxyExecuteResponse(
642 + status=200,
643 + data={"ok": True},
644 + headers={"content-type": "application/pdf"},
645 + binary_data=BinaryData(
646 + content_type="application/pdf",
647 + size=123,
648 + url="https://example.com/file.pdf",
649 + expires_at="2026-08-18T00:00:00Z",
650 + ),
651 + )
652 + )
653 + ctx = SessionContextImpl(client=mock_client, user_id="u", session_id="s")
654 + result = ctx.proxy_execute(
655 + toolkit="gmail", endpoint="https://example.com", method="GET"
656 + )
657 + assert result == {
658 + "status": 200,
659 + "data": {"ok": True},
660 + "headers": {"content-type": "application/pdf"},
661 + "binary_data": {
662 + "content_type": "application/pdf",
663 + "size": 123,
664 + "url": "https://example.com/file.pdf",
665 + "expires_at": "2026-08-18T00:00:00Z",
666 + },
667 + }
668 + assert isinstance(result["binary_data"]["size"], int)
669 +
670 + def test_proxy_execute_binary_data_without_expiry(self):
671 + """``expires_at`` is optional on the generated model; the key stays present."""
672 + mock_client = MagicMock()
673 + mock_client.tool_router.session.proxy_execute.return_value = (
674 + SessionProxyExecuteResponse(
675 + status=200,
676 + data=None,
677 + headers=None,
678 + binary_data=BinaryData(
679 + content_type="image/png",
680 + size=7,
681 + url="https://example.com/file.png",
682 + ),
683 + )
684 + )
685 + ctx = SessionContextImpl(client=mock_client, user_id="u", session_id="s")
686 + result = ctx.proxy_execute(
687 + toolkit="gmail", endpoint="https://example.com", method="GET"
688 + )
689 + assert result["binary_data"] == {
690 + "content_type": "image/png",
691 + "size": 7,
692 + "url": "https://example.com/file.png",
693 + "expires_at": None,
694 + }
695
696
697 # ────────────────────────────────────────────────────────────────
@@ -711,8 +789,40 @@ class TestToolRouterSessionCustomTools:
789 result = s.proxy_execute(
790 toolkit="gmail", endpoint="https://example.com", method="GET"
791 )
714 - assert isinstance(result, SessionProxyExecuteResponse)
715 - assert result.status == 200
792 + assert result == {"status": 200, "data": {"ok": True}, "headers": {}}
793 + assert isinstance(result["status"], int)
794 + assert "binary_data" not in result
795 +
796 + def test_proxy_execute_projects_binary_data(self, mock_session_deps):
797 + mock_session_deps[
798 + "client"
799 + ].tool_router.session.proxy_execute.return_value = SessionProxyExecuteResponse(
800 + status=200,
801 + data={"ok": True},
802 + headers={"content-type": "application/pdf"},
803 + binary_data=BinaryData(
804 + content_type="application/pdf",
805 + size=123,
806 + url="https://example.com/file.pdf",
807 + expires_at="2026-08-18T00:00:00Z",
808 + ),
809 + )
810 + s = _session(mock_session_deps)
811 + result = s.proxy_execute(
812 + toolkit="gmail", endpoint="https://example.com", method="GET"
813 + )
814 + assert result == {
815 + "status": 200,
816 + "data": {"ok": True},
817 + "headers": {"content-type": "application/pdf"},
818 + "binary_data": {
819 + "content_type": "application/pdf",
820 + "size": 123,
821 + "url": "https://example.com/file.pdf",
822 + "expires_at": "2026-08-18T00:00:00Z",
823 + },
824 + }
825 + assert isinstance(result["binary_data"]["size"], int)
826
827 def test_custom_tools_list(self, mock_session_deps):
828 s = _session(mock_session_deps)