@devries-cameron20 / composio-1 / commits / a1873e90a
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(core): make HTTP status errors catchable as ComposioError (#4543)

## Summary In the Python SDK, HTTP failures from the generated client escape `except ComposioError`: `composio_client` has its own exception root, unrelated to `composio.exceptions.ComposioError`. An invalid API key, a 429 or a 500 therefore bypasses a handler written against the SDK's base error, while the TypeScript SDK covers the equivalent case (#4459). Opened this so there's something concrete to look at alongside the issue. Happy to rework it or close it if you'd prefer a different approach. Fixes #4537 ## Changes - `HttpClient` overrides `_make_status_error`, the single place the generated client builds status errors, and returns each error as a subclass of **both** the generated class and `ComposioError` (one cached subclass per generated class). - New `python/tests/test_client_errors.py` covering every mapped status plus an unmapped one, class reuse, and the SDK's existing `ToolNotFoundError` mapping. I went with this rather than wrapping errors at call sites, which is what I suggested on the issue, because it keeps every existing handler working: - `except ComposioError` now catches HTTP failures. - `except composio_client.AuthenticationError` / `APIStatusError` still work, with `status_code`, `response` and `body` unchanged. - The SDK's own mappings are untouched: `get_raw_composio_tool_by_slug` still raises `ToolNotFoundError` on 400/404 and re-raises other client errors unchanged, per its docstring and `test_tool_retrieval_errors.py`. The same holds for `TriggerTypeNotFound`. - No call sites change, so every endpoint is covered, including ones added later. On relying on a private method: `_make_status_error` is the hook the generated base client declares (`raise NotImplementedError()`) and calls for every status error, and `HttpClient` already overrides `_prepare_request` from the same base. `composio-client` is pinned exactly, and the new tests run through a real `HttpClient`, so a generator change that altered the hook would fail CI at the version bump rather than silently regress. Left alone: - **Transport-level errors.** `APIConnectionError` and `APITimeoutError` are raised by the base client without going through `_make_status_error`, so an HTTP timeout still escapes `except ComposioError`. (The issue said timeouts were already covered; that was true only for the SDK's own `ComposioSDKTimeoutError` from `wait_for_connection`, not for HTTP timeouts.) Happy to follow up if you want those covered too. - **The existing `composio.client.ComposioAPIError` alias** still points at the generated `APIError`, unchanged. The name I floated on the issue would have collided with it, and this approach doesn't need a new public class. ## Type of change - [x] Bug fix - [ ] New feature - [ ] Refactor/Chore - [ ] Documentation - [ ] Breaking change ## How Has This Been Tested? `python/tests/test_client_errors.py` runs a real `HttpClient` against an `httpx.MockTransport`. Each status (400, 401, 403, 404, 409, 422, 429, 500, and an unmapped 418) raises an error that is both a `ComposioError` and the expected generated class, with `status_code` preserved. Without the fix, 12 of the 13 new tests fail. From `python/`, Python 3.12, `composio-client==1.43.0`: ``` $ pytest tests/ -q 2072 passed, 1 skipped $ ruff check --config config/ruff.toml composio tests All checks passed! $ ruff format --config config/ruff.toml --check composio/client/__init__.py tests/test_client_errors.py 2 files already formatted $ mypy --config-file config/mypy.ini composio Success: no issues found in 58 source files ``` Live check against production with an invalid key: ```python from composio import Composio from composio.exceptions import ComposioError try: Composio(api_key="ak_invalid").create(user_id="u") except ComposioError as e: print(type(e), e.status_code) ``` On `next` this raises `composio_client.AuthenticationError`, which escapes the handler. On this branch the handler catches it, and it is still an `AuthenticationError` with status 401. ## Checklist - [x] I have read the Code of Conduct and this PR adheres to it - [x] I ran linters/tests locally and they passed - [ ] I updated documentation as needed (no docs change; the public API is unchanged) - [x] I added tests or explain why not applicable - [ ] I added a changeset if this change affects published packages (Python-only change; CONTRIBUTING asks for changesets on published TypeScript packages) ## Additional context Found while integrating the Python SDK into [Inferra](https://github.com/deepgori/inferra), where a GitHub-issue filer caught `ComposioError` and missed the invalid-key path. --------- Co-authored-by: jkomyno <alberto@composio.dev> Co-authored-by: Alberto Schiabel <jkomyno@users.noreply.github.com>

Deep Gori committed Sep 21, 2026 at 13:46 UTC a1873e90a7897c2972c9e42558ca2becc1f32796
2 files changed +255 -1
python/composio/client/__init__.py
+76 -1
@@ -14,18 +14,79 @@ from composio_client import (
14 DEFAULT_MAX_RETRIES,
15 NOT_GIVEN,
16 APIError,
17 + APIStatusError,
18 NotGiven,
19 _base_client,
20 )
21 from composio_client import Composio as BaseComposio
21 -from httpx import URL, Client, Request, Timeout
22 +from httpx import URL, Client, Request, Response, Timeout
23
24 +from composio.exceptions import ComposioError
25 from composio.utils.logging import WithLogger
26
27 ComposioAPIError = APIError
28 APIEnvironment = te.Literal["production", "staging", "local"]
29
30
31 +_SDK_ERROR_CLASSES: t.Dict[t.Type[APIStatusError], t.Type[APIStatusError]] = {}
32 +
33 +
34 +def _with_sdk_error_base(
35 + error_class: t.Type[APIStatusError],
36 +) -> t.Type[APIStatusError]:
37 + """
38 + Return a subclass of a generated-client status error that also derives
39 + from the SDK's ``ComposioError``.
40 +
41 + The generated client has its own exception root, unrelated to
42 + ``composio.exceptions.ComposioError``, so HTTP failures such as an invalid
43 + API key used to escape ``except ComposioError``. Keeping the generated
44 + class as the first base preserves its constructor, ``status_code`` and
45 + ``isinstance`` checks, so existing ``except APIStatusError`` handlers keep
46 + working unchanged.
47 + """
48 + cached = _SDK_ERROR_CLASSES.get(error_class)
49 + if cached is not None:
50 + return cached
51 + sdk_class = t.cast(
52 + t.Type[APIStatusError],
53 + type(
54 + error_class.__name__,
55 + (error_class, ComposioError),
56 + {
57 + "__module__": error_class.__module__,
58 + "__reduce__": _reduce_sdk_error,
59 + },
60 + ),
61 + )
62 + # setdefault keeps the first class if two threads race to build one.
63 + return _SDK_ERROR_CLASSES.setdefault(error_class, sdk_class)
64 +
65 +
66 +def _reduce_sdk_error(self: APIStatusError) -> t.Tuple[t.Any, ...]:
67 + """
68 + Pickle support for the classes built by ``_with_sdk_error_base``.
69 +
70 + They are not module attributes, so pickle cannot find them by name. Record
71 + the generated class instead and rebuild the SDK subclass on load.
72 + """
73 + error_class = type(self).__mro__[1]
74 + return (
75 + _rebuild_sdk_error,
76 + (error_class, self.message, self.response, self.body),
77 + self.__dict__,
78 + )
79 +
80 +
81 +def _rebuild_sdk_error(
82 + error_class: t.Type[APIStatusError],
83 + message: str,
84 + response: Response,
85 + body: object,
86 +) -> APIStatusError:
87 + return _with_sdk_error_base(error_class)(message, response=response, body=body)
88 +
89 +
90 def _get_python_implementation() -> str:
91 """
92 Get the Python implementation name.
@@ -242,6 +303,20 @@ class HttpClient(BaseComposio, WithLogger):
303 self._without_retries = self.with_options(max_retries=0)
304 return self._without_retries
305
306 + def _make_status_error(
307 + self,
308 + err_msg: str,
309 + *,
310 + body: object,
311 + response: Response,
312 + ) -> APIStatusError:
313 + """
314 + Build the generated client's status error so it is also a
315 + ``ComposioError``; see ``_with_sdk_error_base``.
316 + """
317 + error = super()._make_status_error(err_msg, body=body, response=response)
318 + return _with_sdk_error_base(type(error))(err_msg, response=response, body=body)
319 +
320 def _prepare_request(self, request: Request) -> None:
321 """
322 Request interceptor to inject request id, provider, and SDK version.
python/tests/test_client_errors.py new
+179
@@ -0,0 +1,179 @@
1 +"""HTTP status errors from the generated client must be ``ComposioError``s.
2 +
3 +The generated client (``composio_client``) has its own exception root, so an
4 +invalid API key or any other 4xx/5xx response used to escape
5 +``except ComposioError`` (issue #4537). ``HttpClient`` now builds those errors
6 +as subclasses of both the generated class and ``ComposioError``, so SDK callers
7 +can catch one root while existing ``except APIStatusError`` handlers, including
8 +the SDK's own, keep working.
9 +"""
10 +
11 +import copy
12 +import pickle
13 +import typing as t
14 +from unittest.mock import Mock
15 +
16 +import composio_client
17 +import httpx
18 +import pytest
19 +
20 +from composio import exceptions
21 +from composio.client import HttpClient
22 +from composio.core.models.base import allow_tracking
23 +from composio.core.models.tools import Tools
24 +from composio.core.models.triggers import Triggers
25 +
26 +
27 +@pytest.fixture(autouse=True)
28 +def disable_telemetry():
29 + """Disable telemetry for all tests to prevent thread issues."""
30 + token = allow_tracking.set(False)
31 + yield
32 + allow_tracking.reset(token)
33 +
34 +
35 +def _client_returning(
36 + status: int,
37 + *,
38 + max_retries: int = 0,
39 + calls: t.Optional[t.List[httpx.Request]] = None,
40 +) -> HttpClient:
41 + def handler(request: httpx.Request) -> httpx.Response:
42 + if calls is not None:
43 + calls.append(request)
44 + return httpx.Response(
45 + status,
46 + json={"error": {"message": "nope"}},
47 + # Keep retry backoff short in tests.
48 + headers={"retry-after-ms": "1"},
49 + )
50 +
51 + return HttpClient(
52 + provider="test",
53 + api_key="sk-test",
54 + base_url="https://backend.invalid",
55 + max_retries=max_retries,
56 + http_client=httpx.Client(transport=httpx.MockTransport(handler)),
57 + )
58 +
59 +
60 +@pytest.mark.parametrize(
61 + ("status", "client_error"),
62 + [
63 + (400, composio_client.BadRequestError),
64 + (401, composio_client.AuthenticationError),
65 + (403, composio_client.PermissionDeniedError),
66 + (404, composio_client.NotFoundError),
67 + (409, composio_client.ConflictError),
68 + (422, composio_client.UnprocessableEntityError),
69 + (429, composio_client.RateLimitError),
70 + (500, composio_client.InternalServerError),
71 + (418, composio_client.APIStatusError),
72 + ],
73 +)
74 +def test_status_errors_are_composio_errors(
75 + status: int, client_error: t.Type[composio_client.APIStatusError]
76 +) -> None:
77 + client = _client_returning(status)
78 +
79 + with pytest.raises(exceptions.ComposioError) as exc_info:
80 + client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
81 +
82 + error = exc_info.value
83 + assert isinstance(error, client_error)
84 + assert isinstance(error, composio_client.APIStatusError)
85 + assert error.status_code == status
86 + assert error.message
87 +
88 +
89 +def test_invalid_api_key_is_catchable_as_composio_error() -> None:
90 + client = _client_returning(401)
91 +
92 + try:
93 + client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
94 + except exceptions.ComposioError as error:
95 + assert isinstance(error, composio_client.AuthenticationError)
96 + else:
97 + pytest.fail("expected the 401 to raise")
98 +
99 +
100 +def test_error_classes_are_reused_across_requests() -> None:
101 + client = _client_returning(401)
102 + raised = []
103 + for _ in range(2):
104 + with pytest.raises(composio_client.AuthenticationError) as exc_info:
105 + client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
106 + raised.append(type(exc_info.value))
107 +
108 + assert raised[0] is raised[1]
109 + assert raised[0].__name__ == "AuthenticationError"
110 +
111 +
112 +def test_tool_not_found_mapping_still_applies() -> None:
113 + tools = Tools(client=_client_returning(404), provider=Mock())
114 +
115 + with pytest.raises(exceptions.ToolNotFoundError) as exc_info:
116 + tools.get_raw_composio_tool_by_slug("NONEXISTENT_TOOL")
117 +
118 + assert isinstance(exc_info.value.__cause__, composio_client.NotFoundError)
119 +
120 +
121 +def test_schema_fetch_auth_error_is_a_composio_error() -> None:
122 + tools = Tools(client=_client_returning(401), provider=Mock())
123 +
124 + with pytest.raises(composio_client.AuthenticationError) as exc_info:
125 + tools.get_raw_composio_tool_by_slug("SLACK_FETCH_CONVERSATION_HISTORY")
126 +
127 + assert isinstance(exc_info.value, exceptions.ComposioError)
128 + assert not isinstance(exc_info.value, exceptions.ToolNotFoundError)
129 +
130 +
131 +def test_trigger_type_not_found_mapping_still_applies() -> None:
132 + triggers = Triggers(client=_client_returning(404))
133 +
134 + with pytest.raises(exceptions.TriggerTypeNotFound) as exc_info:
135 + triggers.create(slug="NONEXISTENT_TRIGGER", user_id="user")
136 +
137 + assert isinstance(exc_info.value.__cause__, composio_client.NotFoundError)
138 +
139 +
140 +def test_without_retries_client_raises_composio_error() -> None:
141 + client = _client_returning(401)
142 +
143 + with pytest.raises(exceptions.ComposioError) as exc_info:
144 + client.without_retries.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
145 +
146 + assert isinstance(exc_info.value, composio_client.AuthenticationError)
147 +
148 +
149 +def test_error_after_exhausted_retries_is_composio_error() -> None:
150 + calls: t.List[httpx.Request] = []
151 + client = _client_returning(503, max_retries=2, calls=calls)
152 +
153 + with pytest.raises(exceptions.ComposioError) as exc_info:
154 + client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
155 +
156 + assert isinstance(exc_info.value, composio_client.InternalServerError)
157 + assert len(calls) == 3
158 +
159 +
160 +@pytest.mark.parametrize(
161 + "clone",
162 + [lambda error: pickle.loads(pickle.dumps(error)), copy.deepcopy],
163 + ids=["pickle", "deepcopy"],
164 +)
165 +def test_status_errors_survive_serialization(
166 + clone: t.Callable[[BaseException], BaseException],
167 +) -> None:
168 + client = _client_returning(401)
169 + with pytest.raises(exceptions.ComposioError) as exc_info:
170 + client.tools.retrieve(tool_slug="GITHUB_CREATE_AN_ISSUE")
171 + error = exc_info.value
172 +
173 + restored = clone(error)
174 +
175 + assert type(restored) is type(error)
176 + assert isinstance(restored, composio_client.AuthenticationError)
177 + assert isinstance(restored, exceptions.ComposioError)
178 + assert t.cast(composio_client.APIStatusError, restored).status_code == 401
179 + assert str(restored) == str(error)