@devries-cameron20 / composio Mirror · read-only / commits / 84fb5ba7f
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, 03:37 UTC

fix(errors): surface API error details on every failure (#5417)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/5413 - moves `apiErrorCode` onto `ComposioError`, derived from the `APIError` cause like `statusCode` and `requestId`, so every SDK wrapper carries it - copies the server message, `suggested_fix`, status, and numeric code into the 429, 1803, tool-fetch, and session/Tool Router paths - makes `ComposioConnectedAccountNotFoundError` accept the server status while keeping 404 for callers that pass no status - adds `api_error_code`, `suggested_fix`, and `possible_fixes` to the Python status errors, preferring the server's `suggested_fix`, then the 1803 hint, then a status-specific fallback - appends the server message to a mapped Python `ToolNotFoundError` ## Context Anshu's report asked the TS SDK to stop replacing API errors with a generic message and asked Python to do the same. #5413 covered the default `tools.execute` path; this PR closes the remaining branches and the Python half. Python's generated client already puts the server message in `str(error)`; the SDK now exposes the rest of the envelope without wrapping the exception in a new type. Commands run from the repository root, all on the final head: - `pnpm --filter @composio/core test`: 2050 passed, 2 expected fail - `pnpm typecheck`: 14/14 tasks passed - `pnpm --filter @composio/core exec prettier --check` on the changed files: passed - `pnpm test`: 26/26 tasks passed; the final `test:examples` step fails on the same four untracked `ts/examples/*` directories as #5413 - `.venv/bin/python -m pytest` on the touched Python suites: 90 passed - full `python/tests`: 2624 passed; the path-join guardrail test fails on nested provider `.venv` directories and the type-inference tests fail in this checkout, both environment-only - `ruff check` and `ruff format --check` with `python/config/ruff.toml`: passed - `mypy --config-file python/config/mypy.ini` on the changed modules: no errors in them (unrelated missing-stub errors remain elsewhere) - `pnpm --filter @composio/core generate:docs` and the Python reference generator: no drift

Alberto Schiabel committed Nov 17, 2026 at 14:12 UTC 84fb5ba7f069278c1c507c9d47f219e65979cd9a
23 files changed +790 -90
.ast-grep/baseline.json
-6
@@ -215,12 +215,6 @@
215 "source": " const openApi3Definition = {\n openapi: '3.1.0',\n components: {\n schemas: {\n [name]: {\n type: 'object',\n properties: processedProperties,\n },\n },\n },\n } as unknown as OpenAPI3;",
216 "count": 1
217 },
218 - {
219 - "ruleId": "ts-double-assertion",
220 - "file": "ts/packages/core/src/errors/ComposioError.ts",
221 - "source": " const { cause, code, stack, statusCode, meta, possibleFixes } = this as unknown as {\n cause: unknown;\n code: string | undefined;\n stack: string | undefined;\n statusCode: number | undefined;\n meta: Record<string, unknown> | undefined;\n possibleFixes: string[] | undefined;\n };",
222 - "count": 1
223 - },
218 {
219 "ruleId": "ts-double-assertion",
220 "file": "ts/packages/core/src/models/Triggers.ts",
.changeset/tool-error-details-parity.md new
+10
@@ -0,0 +1,10 @@
1 +---
2 +'@composio/core': minor
3 +'@composio/python-sdk': minor
4 +---
5 +
6 +Surface the server's error details on every API failure, not only the default `tools.execute` path.
7 +
8 +**TypeScript:** `apiErrorCode` is now on `ComposioError`, derived from the `APIError` cause like `statusCode` and `requestId`, so every SDK wrapper gets it. The 429 branch, the 1803 connected-account branch, tool-fetch failures, and session/Tool Router execution now use the server's message, `suggested_fix`, status, and numeric code. Failures that never reached the API keep their original reason in the message. `ComposioConnectedAccountNotFoundError` keeps its 404 default but uses the server's status when it wraps an API error. Server-controlled error text is stripped of control characters and ANSI/OSC escapes before it reaches a message or terminal output.
9 +
10 +**Python:** status errors raised by the SDK now expose `api_error_code`, `suggested_fix`, and `possible_fixes`, and `api_error_details(error)` gives type checkers a typed view of them. `possible_fixes` uses the server's `suggested_fix` when present and otherwise returns guidance for the HTTP status, so 401, 402, 403, 410, and 5xx no longer suggest checking the tool slug and arguments. Server-controlled text is sanitized before it reaches a message. The message already carries the server's explanation; a regression test now locks that. A tool-fetch 400/404 mapped to `ToolNotFoundError` now appends the server's message.
docs/content/reference/sdk-reference/python/tools.mdx
+1 -1
@@ -183,4 +183,4 @@ def proxy(endpoint: str, method: Literal['GET', 'POST', 'PUT', 'DELETE', 'PATCH'
183
184 ---
185
186 -[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L337)
186 +[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/tools.py#L338)
python/README.md
+25
@@ -84,6 +84,31 @@ Provider helpers have provider-specific return contracts. The [Python Anthropic
84
85 Transport/authentication errors and requests for user input can raise instead of returning a result. Keep authentication recovery separate from returned tool failures. A non-throwing call, empty `error`, or execution-log ID isn't proof of a provider-side action. Check the explicit outcome and tool-specific `data`; your application owns retry and idempotency decisions.
86
87 +## Error handling
88 +
89 +API rejections raise a `composio_client` status error, which is also a `ComposioError`. The message carries the server's explanation, and the error exposes the HTTP status, request id, numeric API error code, and a suggested fix:
90 +
91 +```python
92 +from composio import api_error_details
93 +from composio_client import APIStatusError
94 +
95 +try:
96 + composio.tools.execute(
97 + slug="GMAIL_SEND_EMAIL",
98 + arguments={"to": "user@example.com", "subject": "Hi", "body": "Hello"},
99 + user_id="user_123",
100 + )
101 +except APIStatusError as error:
102 + details = api_error_details(error)
103 + print(details.message) # 410 toolkit GMAIL version 20250114_00 is retired ...
104 + print(details.status_code) # 410
105 + print(details.api_error_code) # 1410
106 + print(details.request_id) # req_...
107 + print(details.possible_fixes) # ["Pin 20261101_00"] or status-specific guidance
108 +```
109 +
110 +`api_error_details()` returns the typed view of the same exception, so type checkers see these fields. `details.possible_fixes` uses the server's `suggested_fix` when present. Without one, it returns a fix chosen for the HTTP status, so a 401, 402, 403, 410, or 5xx doesn't tell you to check the tool slug and arguments. `details.details` still exposes the validated error envelope.
111 +
112 ## Use with an agent framework
113
114 Provider packages adapt `session.tools()` to your framework's native tool format. With [OpenAI Agents](https://github.com/ComposioHQ/composio/tree/next/python/providers/openai_agents):
python/composio/__init__.py
+3 -1
@@ -23,7 +23,7 @@ from .core.models.webhook_events import (
23 WebhookEventType,
24 is_connection_expired_event,
25 )
26 -from .exceptions import ComposioDeprecationWarning
26 +from .exceptions import APIErrorDetails, ComposioDeprecationWarning, api_error_details
27 from .core.types import (
28 ToolkitLatestVersion,
29 ToolkitVersion,
@@ -33,6 +33,7 @@ from .core.types import (
33 from .sdk import Composio
34
35 __all__ = (
36 + "APIErrorDetails",
37 "Composio",
38 "ComposioDeprecationWarning",
39 "CustomTool",
@@ -50,6 +51,7 @@ __all__ = (
51 "WebhookEvent",
52 "WebhookEventType",
53 "after_execute",
54 + "api_error_details",
55 "before_execute",
56 "before_file_upload",
57 "is_connection_expired_event",
python/composio/client/__init__.py
+61 -2
@@ -26,7 +26,7 @@ from composio_client import (
26 from composio_client import Composio as BaseComposio
27 from httpx import URL, Client, Response, Timeout
28
29 -from composio.exceptions import ComposioError
29 +from composio.exceptions import ComposioError, sanitize_error_text
30 from composio.utils.logging import LogLevel, WithLogger, _VerbosityWrapper
31 from composio.utils.toolkit_deprecation import (
32 install_hook as _install_toolkit_deprecation_hook,
@@ -71,6 +71,62 @@ APIEnvironment = te.Literal["production", "staging", "local"]
71
72 _SDK_ERROR_CLASSES: t.Dict[t.Type[APIStatusError], t.Type[APIStatusError]] = {}
73
74 +_STATUS_FALLBACK_FIXES: t.Dict[int, t.List[str]] = {
75 + 401: ["Ensure you are using a valid Composio API key for this project"],
76 + 402: ["Check the plan and billing limits of your Composio organization"],
77 + 403: ["Ensure your API key and the connected account are allowed to run this tool"],
78 + 410: [
79 + "The tool or the resource it acts on is no longer available; see the error message"
80 + ],
81 + 429: [
82 + "Wait before retrying",
83 + "Reduce how many requests your organization sends per minute",
84 + ],
85 +}
86 +_CODE_FALLBACK_FIXES: t.Dict[int, t.List[str]] = {
87 + 1803: [
88 + "Ensure the connected account exists and is active in your Composio dashboard"
89 + ],
90 +}
91 +_SERVER_ERROR_FIXES = [
92 + "The Composio API failed to process the request; retry later",
93 + "If it keeps failing, contact Composio support with the request id",
94 +]
95 +_DEFAULT_FIXES = [
96 + "Ensure the tool slug is correct and the input arguments for the tool is valid",
97 +]
98 +
99 +
100 +def _fallback_fixes(status_code: int) -> t.List[str]:
101 + """What to try when the API rejected the request without a ``suggested_fix``."""
102 + if status_code in _STATUS_FALLBACK_FIXES:
103 + return list(_STATUS_FALLBACK_FIXES[status_code])
104 + if status_code >= 500:
105 + return list(_SERVER_ERROR_FIXES)
106 + return list(_DEFAULT_FIXES)
107 +
108 +
109 +def _api_error_code(error: APIStatusError) -> t.Optional[int]:
110 + details = error.details
111 + return details.get("code") if details is not None else None
112 +
113 +
114 +def _suggested_fix(error: APIStatusError) -> t.Optional[str]:
115 + details = error.details
116 + raw = details.get("suggested_fix") if details is not None else None
117 + return sanitize_error_text(raw) or None if raw else None
118 +
119 +
120 +def _possible_fixes(error: APIStatusError) -> t.List[str]:
121 + fix = _suggested_fix(error)
122 + if fix:
123 + return [fix]
124 + details = error.details
125 + code = details.get("code") if details is not None else None
126 + if code in _CODE_FALLBACK_FIXES:
127 + return list(_CODE_FALLBACK_FIXES[code])
128 + return _fallback_fixes(error.status_code)
129 +
130
131 def _with_sdk_error_base(
132 error_class: t.Type[APIStatusError],
@@ -97,6 +153,9 @@ def _with_sdk_error_base(
153 {
154 "__module__": error_class.__module__,
155 "__reduce__": _reduce_sdk_error,
156 + "api_error_code": property(_api_error_code),
157 + "suggested_fix": property(_suggested_fix),
158 + "possible_fixes": property(_possible_fixes),
159 },
160 ),
161 )
@@ -132,7 +191,7 @@ def _as_sdk_error(error: APIStatusError) -> APIStatusError:
191 if isinstance(error, ComposioError):
192 return error
193 sdk_error = _with_sdk_error_base(type(error))(
135 - error.message, response=error.response, body=error.body
194 + sanitize_error_text(error.message), response=error.response, body=error.body
195 )
196 return sdk_error.with_traceback(error.__traceback__)
197
python/composio/core/models/tools.py
+7 -1
@@ -53,6 +53,7 @@ from composio.exceptions import (
53 ToolNotFoundError,
54 ToolVersionRequiredError,
55 ValidationError,
56 + sanitize_error_text,
57 )
58 from composio.utils.pydantic import none_to_omit
59 from composio.utils.toolkit_version import get_toolkit_version
@@ -429,7 +430,12 @@ class Tools(Resource, t.Generic[TTool, TToolCollection]):
430 )
431 except APIStatusError as error:
432 if error.status_code in (400, 404):
432 - raise ToolNotFoundError(f"Tool with slug {slug} not found") from error
433 + message = f"Tool with slug {slug} not found"
434 + if error.details is not None:
435 + message = (
436 + f"{message}: {sanitize_error_text(error.details['message'])}"
437 + )
438 + raise ToolNotFoundError(message) from error
439 raise
440 return _normalize_tool(response)
441
python/composio/exceptions.py
+34 -1
@@ -3,14 +3,47 @@ Composio exceptions.
3 """
4
5 import difflib
6 +import re
7 import typing as t
8
9 import typing_extensions as te
10
10 -from composio_client import ComposioDeprecationWarning as ComposioDeprecationWarning
11 +from composio_client import (
12 + APIStatusError,
13 + ComposioDeprecationWarning as ComposioDeprecationWarning,
14 +)
15
16 ENV_COMPOSIO_API_KEY = "COMPOSIO_API_KEY"
17
18 +# CSI, OSC, and other ESC sequences a terminal would act on.
19 +_ANSI_ESCAPE = re.compile(
20 + r"\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\)|[@-_])"
21 +)
22 +# C0/C1 controls, DEL, and the Unicode line separators that can forge output lines.
23 +_CONTROL_CHARACTERS = re.compile(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]")
24 +
25 +
26 +def sanitize_error_text(value: str) -> str:
27 + """Make a server-controlled string safe to print in a terminal or one log line."""
28 + return " ".join(_CONTROL_CHARACTERS.sub(" ", _ANSI_ESCAPE.sub(" ", value)).split())
29 +
30 +
31 +class APIErrorDetails(t.Protocol):
32 + """The typed API surface the SDK adds to generated status errors."""
33 +
34 + message: str
35 + status_code: int
36 + request_id: t.Optional[str]
37 + api_error_code: t.Optional[int]
38 + suggested_fix: t.Optional[str]
39 + possible_fixes: t.List[str]
40 + details: t.Optional[t.Dict[str, t.Any]]
41 +
42 +
43 +def api_error_details(error: APIStatusError) -> APIErrorDetails:
44 + """Return the typed API surface of a status error raised by the SDK."""
45 + return t.cast(APIErrorDetails, error)
46 +
47
48 class ComposioError(Exception):
49 """Base composio SDK error."""
python/tests/test_client_errors.py
+130 -2
@@ -18,7 +18,7 @@ import httpx
18 import pytest
19 from composio_client import ProjectAuth
20
21 -from composio import exceptions
21 +from composio import api_error_details, exceptions
22 from composio.client import HttpClient
23 from composio.core.models.base import allow_tracking
24 from composio.core.models.tools import Tools
@@ -38,13 +38,14 @@ def _client_returning(
38 *,
39 max_retries: int = 0,
40 calls: t.Optional[t.List[httpx.Request]] = None,
41 + body: t.Optional[object] = None,
42 ) -> HttpClient:
43 def handler(request: httpx.Request) -> httpx.Response:
44 if calls is not None:
45 calls.append(request)
46 return httpx.Response(
47 status,
47 - json={"error": {"message": "nope"}},
48 + json=body if body is not None else {"error": {"message": "nope"}},
49 # Keep retry backoff short in tests.
50 headers={"retry-after-ms": "1"},
51 )
@@ -87,6 +88,133 @@ def test_status_errors_are_composio_errors(
88 assert error.message
89
90
91 +def test_status_error_exposes_the_server_error_details() -> None:
92 + body = {
93 + "error": {
94 + "message": "toolkit GMAIL version 20250114_00 is retired and can no longer be executed",
95 + "code": 1410,
96 + "slug": "TOOLKIT_VERSION_RETIRED",
97 + "status": 410,
98 + "request_id": "req_body",
99 + "suggested_fix": "Pin 20261101_00",
100 + }
101 + }
102 + client = _client_returning(410, body=body)
103 +
104 + with pytest.raises(composio_client.APIStatusError) as exc_info:
105 + client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
106 +
107 + error = exc_info.value
108 + details = api_error_details(error)
109 + assert error.status_code == 410
110 + assert details.api_error_code == 1410
111 + assert details.suggested_fix == "Pin 20261101_00"
112 + assert details.possible_fixes == ["Pin 20261101_00"]
113 + assert error.request_id == "req_body"
114 + assert "toolkit GMAIL version 20250114_00 is retired" in str(error)
115 + assert "{" not in str(error)
116 +
117 +
118 +def test_status_errors_strip_control_characters() -> None:
119 + body = {
120 + "error": {
121 + "message": "denied\x1b[31m\n[!] run: evil",
122 + "code": 1403,
123 + "slug": "FORBIDDEN",
124 + "status": 403,
125 + "suggested_fix": "retry\x1b]0;owned\x07 now",
126 + }
127 + }
128 + client = _client_returning(403, body=body)
129 +
130 + with pytest.raises(composio_client.PermissionDeniedError) as exc_info:
131 + client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
132 +
133 + error = exc_info.value
134 + details = api_error_details(error)
135 + assert "denied [!] run: evil" in str(error)
136 + assert details.suggested_fix == "retry now"
137 + assert details.possible_fixes == ["retry now"]
138 + assert not any(ord(char) < 32 or 127 <= ord(char) <= 159 for char in str(error))
139 +
140 +
141 +def test_possible_fixes_fall_back_to_the_status() -> None:
142 + body = {
143 + "error": {
144 + "message": "connected account belongs to another project",
145 + "code": 1403,
146 + "slug": "FORBIDDEN",
147 + "status": 403,
148 + }
149 + }
150 + client = _client_returning(403, body=body)
151 +
152 + with pytest.raises(composio_client.PermissionDeniedError) as exc_info:
153 + client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
154 +
155 + details = api_error_details(exc_info.value)
156 + assert details.api_error_code == 1403
157 + assert details.suggested_fix is None
158 + assert details.possible_fixes == [
159 + "Ensure your API key and the connected account are allowed to run this tool"
160 + ]
161 +
162 +
163 +def test_possible_fixes_use_the_api_error_code_for_a_missing_account() -> None:
164 + body = {
165 + "error": {
166 + "message": "No connected account found",
167 + "code": 1803,
168 + "slug": "CONNECTED_ACCOUNT_NOT_FOUND",
169 + "status": 400,
170 + }
171 + }
172 + client = _client_returning(400, body=body)
173 +
174 + with pytest.raises(composio_client.BadRequestError) as exc_info:
175 + client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
176 +
177 + details = api_error_details(exc_info.value)
178 + assert details.possible_fixes == [
179 + "Ensure the connected account exists and is active in your Composio dashboard"
180 + ]
181 +
182 +
183 +def test_possible_fixes_do_not_blame_the_slug_for_a_rate_limit() -> None:
184 + body = {
185 + "error": {
186 + "message": "slow down",
187 + "code": 1429,
188 + "slug": "RATE_LIMITED",
189 + "status": 429,
190 + }
191 + }
192 + client = _client_returning(429, body=body)
193 +
194 + with pytest.raises(composio_client.RateLimitError) as exc_info:
195 + client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
196 +
197 + details = api_error_details(exc_info.value)
198 + assert details.possible_fixes == [
199 + "Wait before retrying",
200 + "Reduce how many requests your organization sends per minute",
201 + ]
202 +
203 +
204 +def test_status_error_without_the_envelope_has_no_api_details() -> None:
205 + client = _client_returning(400, body={"unexpected": True})
206 +
207 + with pytest.raises(composio_client.APIStatusError) as exc_info:
208 + client.tools.execute(tool_slug="GMAIL_SEND_EMAIL", arguments={})
209 +
210 + details = api_error_details(exc_info.value)
211 + assert details.api_error_code is None
212 + assert details.suggested_fix is None
213 + assert details.possible_fixes == [
214 + "Ensure the tool slug is correct and the input arguments for the tool is valid"
215 + ]
216 +
217 +
218 def test_invalid_api_key_is_catchable_as_composio_error() -> None:
219 client = _client_returning(401)
220
python/tests/test_tool_retrieval_errors.py
+52
@@ -51,6 +51,58 @@ def test_malformed_slug_raises_tool_not_found(tools: Tools, mock_client: Mock) -
51 tools.get_raw_composio_tool_by_slug("malformed slug")
52
53
54 +def test_not_found_strips_control_characters(tools: Tools, mock_client: Mock) -> None:
55 + request = httpx.Request("GET", "https://backend.composio.dev/api/v3/tools/X")
56 + response = httpx.Response(404, request=request)
57 + mock_client.tools.retrieve.side_effect = NotFoundError(
58 + "error",
59 + response=response,
60 + body={
61 + "error": {
62 + "message": "missing\x1b[31m\n[!] run: evil",
63 + "code": 1404,
64 + "slug": "TOOL_NOT_FOUND",
65 + "status": 404,
66 + }
67 + },
68 + )
69 +
70 + with pytest.raises(exceptions.ToolNotFoundError) as exc_info:
71 + tools.get_raw_composio_tool_by_slug("GMAIL_SEND_EMAIL")
72 +
73 + assert str(exc_info.value) == (
74 + "Tool with slug GMAIL_SEND_EMAIL not found: missing [!] run: evil"
75 + )
76 +
77 +
78 +def test_not_found_includes_the_server_message(tools: Tools, mock_client: Mock) -> None:
79 + request = httpx.Request("GET", "https://backend.composio.dev/api/v3/tools/X")
80 + response = httpx.Response(404, request=request)
81 + not_found = NotFoundError(
82 + "error",
83 + response=response,
84 + body={
85 + "error": {
86 + "message": "No tool with that slug in the pinned version",
87 + "code": 1404,
88 + "slug": "TOOL_NOT_FOUND",
89 + "status": 404,
90 + "suggested_fix": "Use the latest version",
91 + }
92 + },
93 + )
94 + mock_client.tools.retrieve.side_effect = not_found
95 +
96 + with pytest.raises(exceptions.ToolNotFoundError) as exc_info:
97 + tools.get_raw_composio_tool_by_slug("GMAIL_SEND_EMAIL")
98 +
99 + assert str(exc_info.value) == (
100 + "Tool with slug GMAIL_SEND_EMAIL not found: "
101 + "No tool with that slug in the pinned version"
102 + )
103 + assert exc_info.value.__cause__ is not_found
104 +
105 +
106 def test_invalid_api_key_is_not_tool_not_found(tools: Tools, mock_client: Mock) -> None:
107 unauthorized = _status_error(AuthenticationError, 401)
108 mock_client.tools.retrieve.side_effect = unauthorized
ts/docs/advanced/error-handling.md
+5
@@ -59,6 +59,8 @@ try {
59 }
60 ```
61
62 +The same server details are available when the SDK fetches a tool, executes one through a session or the Tool Router, or hits a rate limit: `statusCode`, `requestId`, `apiErrorCode`, and `possibleFixes` come from the API response. A tool-fetch error keeps the client error as `cause`, like an execution error.
63 +
64 ### Not Found Errors
65
66 Errors that occur when a resource is not found:
@@ -69,6 +71,9 @@ try {
71 } catch (error) {
72 if (error instanceof ComposioToolNotFoundError) {
73 console.error('Tool not found:', error.message);
74 + console.error('HTTP status:', error.statusCode);
75 + console.error('API error code:', error.apiErrorCode);
76 + console.error('Try:', error.possibleFixes);
77 }
78 }
79 ```
ts/packages/core/docs/error-consistency.md
+1 -1
@@ -44,7 +44,7 @@ Some error classes have specific requirements:
44 new ValidationError('Message', { cause: someZodError });
45 ```
46
47 -2. **ComposioToolExecutionError**: Keeps the failure it wraps as `cause`, and accepts an `apiErrorCode` for the numeric code of a Composio API error response.
47 +2. **ComposioToolExecutionError**: Keeps the failure it wraps as `cause`. The base `ComposioError` reads `statusCode`, `requestId`, and `apiErrorCode` from an `APIError` cause.
48 ```typescript
49 new ComposioToolExecutionError('Message', { cause: someError });
50 ```
ts/packages/core/src/errors/ComposioError.ts
+27 -10
@@ -12,6 +12,7 @@ import pc from 'picocolors';
12 import { ZodError } from 'zod/v3';
13 import { APIError } from '@composio/client';
14 import logger from '../utils/logger';
15 +import { sanitizeApiErrorText } from './apiErrorDetails';
16
17 /**
18 * Options for error handling
@@ -35,6 +36,8 @@ export type ComposioErrorOptions = {
36 statusCode?: number;
37 /** Request id the API assigned. Defaults to the request id of an `APIError` cause. */
38 requestId?: string;
39 + /** Numeric `error.code` of a Composio API error response. Defaults to the code of an `APIError` cause. */
40 + apiErrorCode?: number;
41 /** The underlying cause of the error */
42 cause?: unknown;
43 /** Additional metadata associated with the error */
@@ -54,6 +57,7 @@ interface ErrorFormatData {
57 message: string;
58 code?: string;
59 statusCode?: number;
60 + apiErrorCode?: number;
61 cause?: string;
62 meta?: Record<string, unknown>;
63 possibleFixes?: string[];
@@ -73,6 +77,10 @@ export class ComposioError extends Error {
77 declare public readonly statusCode?: number;
78 /** Request id the Composio API assigned to the request behind the error, when it sent one. */
79 declare public readonly requestId?: string;
80 + /** Numeric `error.code` the Composio API sent, when the response carried one. */
81 + declare public readonly apiErrorCode?: number;
82 + /** Additional metadata associated with the error. */
83 + declare public readonly meta?: Record<string, unknown>;
84
85 /**
86 * Creates a new ComposioError
@@ -91,6 +99,7 @@ export class ComposioError extends Error {
99 const apiCause = options.cause instanceof APIError ? options.cause : undefined;
100 const statusCode = options.statusCode ?? apiCause?.status;
101 const requestId = options.requestId ?? apiCause?.requestId;
102 + const apiErrorCode = options.apiErrorCode ?? apiCause?.details?.code;
103
104 this.code = `TS-SDK::${options.code}`;
105 // format the possible fixes
@@ -100,6 +109,7 @@ export class ComposioError extends Error {
109 // Node.js by default shows all the properties of the error object, so we are doing it conditionally
110 this.definePropertyIfExists('statusCode', statusCode);
111 this.definePropertyIfExists('requestId', requestId);
112 + this.definePropertyIfExists('apiErrorCode', apiErrorCode);
113 this.definePropertyIfExists('cause', options.cause);
114
115 const combinedStack =
@@ -163,19 +173,17 @@ export class ComposioError extends Error {
173 message: this.message,
174 };
175
166 - const { cause, code, stack, statusCode, meta, possibleFixes } = this as unknown as {
167 - cause: unknown;
168 - code: string | undefined;
169 - stack: string | undefined;
170 - statusCode: number | undefined;
171 - meta: Record<string, unknown> | undefined;
172 - possibleFixes: string[] | undefined;
173 - };
176 + const { cause, code, stack, statusCode, apiErrorCode, meta, possibleFixes } = this;
177
175 - // Format cause properly if it exists
178 + // Format cause properly if it exists. An API cause is server-controlled text.
179 if (cause !== undefined) {
180 const rawCause = cause;
178 - data.cause = rawCause instanceof Error ? rawCause.message : String(rawCause);
181 + data.cause =
182 + rawCause instanceof APIError
183 + ? sanitizeApiErrorText(rawCause.message)
184 + : rawCause instanceof Error
185 + ? rawCause.message
186 + : sanitizeApiErrorText(String(rawCause));
187 }
188
189 // Add code if exists
@@ -188,6 +196,11 @@ export class ComposioError extends Error {
196 data.statusCode = statusCode;
197 }
198
199 + // Add the API's numeric error code if exists
200 + if (apiErrorCode !== undefined) {
201 + data.apiErrorCode = apiErrorCode;
202 + }
203 +
204 // Add meta if exists
205 if (meta) {
206 data.meta = meta;
@@ -233,6 +246,10 @@ export class ComposioError extends Error {
246 output += pc.yellow(`Status: ${data.statusCode}`) + '\n';
247 }
248
249 + if (data.apiErrorCode !== undefined) {
250 + output += pc.yellow(`API Error Code: ${data.apiErrorCode}`) + '\n';
251 + }
252 +
253 if (data.cause) {
254 output += pc.gray('Reason:') + '\n';
255 output += ' ' + pc.white(data.cause) + '\n';
ts/packages/core/src/errors/ConnectedAccountsErrors.ts
+2 -2
@@ -15,12 +15,12 @@ export const ConnectedAccountErrorCodes = {
15 export class ComposioConnectedAccountNotFoundError extends ComposioError {
16 constructor(
17 message: string = 'Connected account not found',
18 - options: Omit<ComposioErrorOptions, 'code' | 'statusCode'> = {}
18 + options: Omit<ComposioErrorOptions, 'code'> = {}
19 ) {
20 super(message, {
21 ...options,
22 code: ConnectedAccountErrorCodes.CONNECTED_ACCOUNT_NOT_FOUND,
23 - statusCode: 404,
23 + statusCode: options.statusCode ?? 404,
24 possibleFixes: options.possibleFixes || [
25 'Ensure the connected account exists and is active in your Composio dashboard',
26 ],
ts/packages/core/src/errors/ToolErrors.ts
+45 -33
@@ -2,6 +2,11 @@ import { APIError, type APIErrorBody } from '@composio/client';
2 import { ComposioError, ComposioErrorOptions } from './ComposioError';
3 import { ComposioConnectedAccountNotFoundError } from './ConnectedAccountsErrors';
4 import { getRetryAfterSeconds, isRateLimitResponse } from '../utils/rateLimit';
5 +import {
6 + apiErrorSuggestedFixes,
7 + sanitizeApiErrorText,
8 + withApiErrorMessage,
9 +} from './apiErrorDetails';
10
11 export const ToolErrorCodes = {
12 TOOLSET_NOT_DEFINED: 'TOOLSET_NOT_DEFINED',
@@ -103,7 +108,7 @@ const rateLimitOptions = (cause: APIError, meta: Record<string, unknown>) => {
108 cause,
109 statusCode: 429,
110 meta: retryAfterSeconds === undefined ? meta : { ...meta, retryAfterSeconds },
106 - possibleFixes: [
111 + possibleFixes: apiErrorSuggestedFixes(cause.details) ?? [
112 retryAfterSeconds === undefined
113 ? 'Wait before retrying'
114 : `Wait ${Math.ceil(retryAfterSeconds)} seconds, then retry`,
@@ -147,35 +152,22 @@ export class ComposioInvalidModifierError extends ComposioError {
152 }
153
154 /** Options for a `ComposioToolExecutionError`. */
150 -export type ComposioToolExecutionErrorOptions = ComposioErrorOptions & {
151 - /** The numeric `error.code` of the Composio API error response. */
152 - apiErrorCode?: number;
153 -};
155 +export type ComposioToolExecutionErrorOptions = ComposioErrorOptions;
156
157 export class ComposioToolExecutionError extends ComposioError {
156 - /**
157 - * The numeric `error.code` the Composio API sent when it rejected the execution.
158 - * `code` stays the SDK's `TS-SDK::` code.
159 - */
160 - declare public readonly apiErrorCode?: number;
161 -
158 constructor(
159 message: string = 'Tool execution error',
160 options: ComposioToolExecutionErrorOptions = {}
161 ) {
166 - const { apiErrorCode, ...errorOptions } = options;
162 super(message, {
168 - ...errorOptions,
169 - code: errorOptions.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
170 - cause: errorOptions.cause,
171 - possibleFixes: errorOptions.possibleFixes || [
163 + ...options,
164 + code: options.code || ToolErrorCodes.TOOL_EXECUTION_ERROR,
165 + cause: options.cause,
166 + possibleFixes: options.possibleFixes || [
167 'Ensure the tool is correctly configured and the input is valid',
168 'Ensure the userId is correct and has an active connected account for the user in case of non NoAuth toolkits',
169 ],
170 });
176 - if (apiErrorCode !== undefined) {
177 - this.apiErrorCode = apiErrorCode;
178 - }
171
172 this.name = 'ComposioToolExecutionError';
173 }
@@ -342,9 +334,25 @@ export class ComposioToolVersionRequiredError extends ComposioError {
334 /** The error envelope of a Composio API error response, as `@composio/client` validates it. */
335 export type ComposioAPIServerErrorBody = APIErrorBody;
336
337 +type APIErrorDetails = NonNullable<APIError['details']>;
338 +
339 // Map of error codes to their corresponding error constructors
346 -const ERROR_CODE_HANDLERS = new Map<number, (message: string, cause: APIError) => ComposioError>([
347 - [1803, (msg, cause) => new ComposioConnectedAccountNotFoundError(msg, { cause })],
340 +const ERROR_CODE_HANDLERS = new Map<
341 + number,
342 + (details: APIErrorDetails, cause: APIError) => ComposioError
343 +>([
344 + [
345 + 1803,
346 + (details, cause) =>
347 + new ComposioConnectedAccountNotFoundError(
348 + sanitizeApiErrorText(details.message || 'An error occurred'),
349 + {
350 + cause,
351 + statusCode: cause.status,
352 + possibleFixes: apiErrorSuggestedFixes(details),
353 + }
354 + ),
355 + ],
356 // Add more error code handlers here as needed
357 ]);
358
@@ -372,35 +380,39 @@ const fallbackExecutionFixes = (status: number | undefined): string[] => {
380 };
381
382 export const handleToolExecutionError = (tool: string, actualError: Error): ComposioError => {
383 + // Already an SDK error, including a caller cancellation: keep its type.
384 + if (actualError instanceof ComposioError) {
385 + return actualError;
386 + }
387 +
388 const apiError = actualError instanceof APIError ? actualError : undefined;
389 const details = apiError?.details;
390
391 // Handle specific API error codes
392 if (apiError && details && ERROR_CODE_HANDLERS.has(details.code)) {
380 - return ERROR_CODE_HANDLERS.get(details.code)!(details.message || 'An error occurred', apiError);
393 + return ERROR_CODE_HANDLERS.get(details.code)!(details, apiError);
394 }
395
396 if (isRateLimitResponse(actualError)) {
397 return new ComposioToolExecutionRateLimitError(
385 - `Rate limited while executing the tool ${tool}`,
398 + withApiErrorMessage(`Rate limited while executing the tool ${tool}`, actualError.details),
399 actualError,
400 { slug: tool }
401 );
402 }
403
391 - // Default error for all other cases
392 - const serverMessage = details?.message;
404 + // Keep the reason of a failure that never reached the API (timeout,
405 + // connection error, a non-API throw). An HTTP response without the error
406 + // envelope keeps the tool context alone, as its raw body is unvalidated.
407 + const originalMessage = apiError?.status === undefined ? actualError.message : undefined;
408 +
409 + // Default error for all other cases. `statusCode`, `requestId` and `apiErrorCode`
410 + // come from the APIError cause.
411 return new ComposioToolExecutionError(
394 - serverMessage
395 - ? `Error executing the tool ${tool}: ${serverMessage}`
396 - : `Error executing the tool ${tool}`,
412 + withApiErrorMessage(`Error executing the tool ${tool}`, details, originalMessage),
413 {
414 cause: actualError,
399 - statusCode: apiError?.status,
400 - apiErrorCode: details?.code,
401 - possibleFixes: details?.suggested_fix
402 - ? [details.suggested_fix]
403 - : fallbackExecutionFixes(apiError?.status),
415 + possibleFixes: apiErrorSuggestedFixes(details) ?? fallbackExecutionFixes(apiError?.status),
416 }
417 );
418 };
ts/packages/core/src/errors/apiErrorDetails.ts new
+40
@@ -0,0 +1,40 @@
1 +/**
2 + * @fileoverview Helpers for lifting the Composio API error envelope onto SDK errors.
3 + *
4 + * Not exported from the error barrel: these are implementation details shared by
5 + * the tool error classes and the models that wrap API failures.
6 + *
7 + * @module errors/apiErrorDetails
8 + */
9 +import type { APIError } from '@composio/client';
10 +
11 +// CSI, OSC, and other ESC sequences a terminal would act on.
12 +const ANSI_ESCAPE = /\u001b(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007\u001b]*(?:\u0007|\u001b\\)|[@-_])/g;
13 +// C0/C1 controls, DEL, and the Unicode line separators that can forge output lines.
14 +const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g;
15 +
16 +/** Make a server-controlled string safe to print in a terminal or a single log line. */
17 +export const sanitizeApiErrorText = (value: string): string =>
18 + value.replace(ANSI_ESCAPE, ' ').replace(CONTROL_CHARACTERS, ' ').replace(/\s+/g, ' ').trim();
19 +
20 +/**
21 + * Prefix a message with the API's own message, when the response carried one.
22 + * `fallback` is the underlying error's message for failures without an HTTP
23 + * response, such as a timeout or a connection error.
24 + */
25 +export const withApiErrorMessage = (
26 + message: string,
27 + details: APIError['details'],
28 + fallback?: string
29 +): string => {
30 + const reason = details?.message ?? fallback;
31 + const safeReason = reason ? sanitizeApiErrorText(reason) : '';
32 + return safeReason ? `${message}: ${safeReason}` : message;
33 +};
34 +
35 +/** The API's `suggested_fix` as a one-item list, or nothing so the caller's default applies. */
36 +export const apiErrorSuggestedFixes = (details: APIError['details']): string[] | undefined => {
37 + const fix = details?.suggested_fix;
38 + const safeFix = fix ? sanitizeApiErrorText(fix) : '';
39 + return safeFix ? [safeFix] : undefined;
40 +};
ts/packages/core/src/models/SessionContext.ts
+4 -1
@@ -17,6 +17,7 @@ import {
17 ToolRouterSessionExecuteResponseSchema,
18 } from '../types/toolRouter.types';
19 import { ValidationError } from '../errors';
20 +import { handleToolExecutionError } from '../errors/ToolErrors';
21 import { transformProxyParams } from './proxyParamsTransform';
22 import {
23 assertUnambiguousCustomToolSlug,
@@ -108,7 +109,9 @@ export class SessionContextImpl implements SessionContext {
109 withoutRetries(requestOptions)
110 ),
111 requestOptions?.signal
111 - );
112 + ).catch((error: unknown) => {
113 + throw handleToolExecutionError(toolSlug, error as Error);
114 + });
115 return ToolRouterSessionExecuteResponseSchema.parse(
116 transformExecuteResponse(response, toolSlug)
117 );
ts/packages/core/src/models/ToolRouterSession.ts
+7 -2
@@ -6,6 +6,7 @@ import type { ComposioRequestOptions } from '../types/requestOptions.types';
6 import { withCancellation } from '../utils/cancellation';
7 import { withoutRetries } from '../utils/retries';
8 import { ComposioRequestCancelledError } from '../errors/SDKErrors';
9 +import { handleToolExecutionError } from '../errors/ToolErrors';
10 import {
11 ComposioSessionConfigConflictError,
12 ComposioToolInputRequiredError,
@@ -759,7 +760,9 @@ export class ToolRouterSession<
760 withoutRetries(requestOptions)
761 ),
762 requestOptions?.signal
762 - );
763 + ).catch((error: unknown) => {
764 + throw handleToolExecutionError(toolSlug, error as Error);
765 + });
766 const transformed = transformExecuteResponse(response, toolSlug);
767 return ToolRouterSessionExecuteResponseSchema.parse(transformed);
768 }
@@ -808,7 +811,9 @@ export class ToolRouterSession<
811 withoutRetries(requestOptions)
812 ),
813 requestOptions?.signal
811 - );
814 + ).catch((error: unknown) => {
815 + throw handleToolExecutionError(slug, error as Error);
816 + });
817 const transformed = transformExecuteResponse(response, slug);
818 return ToolRouterSessionExecuteResponseSchema.parse(transformed);
819 }
ts/packages/core/src/models/Tools.ts
+30 -9
@@ -55,6 +55,7 @@ import { telemetry } from '../telemetry/Telemetry';
55 import type { ComposioConfig } from '../composio';
56 import { getToolkitVersion } from '../utils/toolkitVersion';
57 import { handleToolExecutionError } from '../errors/ToolErrors';
58 +import { apiErrorSuggestedFixes, withApiErrorMessage } from '../errors/apiErrorDetails';
59 import type { SessionExecuteParams } from '@composio/client/resources/tool-router/session';
60 import { CONFIG_DEFAULTS } from '../utils/config-defaults';
61 import { resolveEffectiveUploadAllowlist } from '../utils/fileDirs';
@@ -876,7 +877,10 @@ export class Tools<
877 }
878 if (isRateLimitResponse(error)) {
879 throw new ComposioToolFetchRateLimitError(
879 - `Rate limited while retrieving tool with slug ${slug}`,
880 + withApiErrorMessage(
881 + `Rate limited while retrieving tool with slug ${slug}`,
882 + error.details
883 + ),
884 error,
885 { slug }
886 );
@@ -885,15 +889,30 @@ export class Tools<
889 // malformed one). Anything else (401, 5xx, network) is not "not found",
890 // so keep the client error reachable as `cause` under a generic error.
891 if (error instanceof APIError && (error.status === 404 || error.status === 400)) {
888 - throw new ComposioToolNotFoundError(`Tool with slug ${slug} not found`, {
892 + throw new ComposioToolNotFoundError(
893 + withApiErrorMessage(`Tool with slug ${slug} not found`, error.details),
894 + {
895 + meta: { slug },
896 + cause: error,
897 + possibleFixes: apiErrorSuggestedFixes(error.details),
898 + }
899 + );
900 + }
901 + const details = error instanceof APIError ? error.details : undefined;
902 + const originalMessage =
903 + error instanceof APIError && error.status !== undefined
904 + ? undefined
905 + : error instanceof Error
906 + ? error.message
907 + : undefined;
908 + throw new ComposioToolFetchError(
909 + withApiErrorMessage(`Unable to retrieve tool with slug ${slug}`, details, originalMessage),
910 + {
911 meta: { slug },
912 cause: error,
891 - });
892 - }
893 - throw new ComposioToolFetchError(`Unable to retrieve tool with slug ${slug}`, {
894 - meta: { slug },
895 - cause: error,
896 - });
913 + possibleFixes: apiErrorSuggestedFixes(details),
914 + }
915 + );
916 }
917
918 // change the case of the tool to camel case and apply default modifiers
@@ -1459,7 +1478,9 @@ export class Tools<
1478 withoutRetries(requestOptions)
1479 ),
1480 requestOptions?.signal
1462 - );
1481 + ).catch((error: unknown) => {
1482 + throw handleToolExecutionError(toolSlug, error as Error);
1483 + });
1484
1485 const { data, error, logId, resultType, instantCharge } = transformExecuteResponse(
1486 response,
ts/packages/core/test/models/customTool.test.ts
+44 -1
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi, beforeEach } from 'vitest';
2 -import ComposioClient, { Auth } from '@composio/client';
2 +import ComposioClient, { APIError, Auth } from '@composio/client';
3 import { z as z4 } from 'zod';
4 import { z } from 'zod/v3';
5 import {
@@ -12,6 +12,7 @@ import {
12 LOCAL_TOOL_PREFIX,
13 } from '../../src/models/CustomTool';
14 import { SessionContextImpl } from '../../src/models/SessionContext';
15 +import { ComposioToolExecutionError } from '../../src/errors/ToolErrors';
16 import type { CustomTool, CustomToolkit, SessionContext } from '../../src/types/customTool.types';
17
18 // ────────────────────────────────────────────────────────────────
@@ -823,6 +824,48 @@ describe('SessionContextImpl', () => {
824 });
825 });
826
827 + it('keeps the original reason when the backend cannot be reached', async () => {
828 + mockClient.toolRouter.session.execute.mockRejectedValue(new Error('socket hang up'));
829 +
830 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
831 + const error = await ctx.execute('GMAIL_SEND_EMAIL', {}).catch(e => e);
832 +
833 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
834 + expect(error.message).toBe('Error executing the tool GMAIL_SEND_EMAIL: socket hang up');
835 + expect(error.cause).toBeInstanceOf(Error);
836 + });
837 +
838 + it('surfaces the server details when the backend rejects the execution', async () => {
839 + mockClient.toolRouter.session.execute.mockRejectedValue(
840 + new APIError(
841 + 410,
842 + {
843 + error: {
844 + message: 'Toolkit version 20250101_00 is retired',
845 + code: 1410,
846 + slug: 'TOOLKIT_VERSION_RETIRED',
847 + status: 410,
848 + suggested_fix: 'Pin 20250909_00',
849 + },
850 + },
851 + undefined,
852 + new Headers({ 'x-request-id': 'req_context_410' })
853 + )
854 + );
855 +
856 + const ctx = new SessionContextImpl(mockClient, 'user_1', 'sess_1');
857 + const error = await ctx.execute('GMAIL_SEND_EMAIL', {}).catch(e => e);
858 +
859 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
860 + expect(error.message).toBe(
861 + 'Error executing the tool GMAIL_SEND_EMAIL: Toolkit version 20250101_00 is retired'
862 + );
863 + expect(error.statusCode).toBe(410);
864 + expect(error.apiErrorCode).toBe(1410);
865 + expect(error.requestId).toBe('req_context_410');
866 + expect(error.possibleFixes).toEqual(['Pin 20250909_00']);
867 + });
868 +
869 it('should pass inline custom tools when delegating execute() to backend', async () => {
870 mockClient.toolRouter.session.execute.mockResolvedValue({
871 result_type: 'completed',
ts/packages/core/test/models/toolRouter.test.ts
+48 -6
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
2 import { z } from 'zod/v3';
3 import { ToolRouter } from '../../src/models/ToolRouter';
4 import ComposioClient, {
5 + APIError,
6 BadRequestError,
7 ConflictError,
8 NotFoundError,
@@ -22,6 +23,7 @@ import { createCustomTool } from '../../src/models/CustomTool';
23 import { DIRECT_CUSTOM_TOOL_DESCRIPTION_PREFIX } from '../../src/models/ToolRouterSession';
24 import { ValidationError } from '../../src/errors/ValidationErrors';
25 import { ComposioSessionConfigConflictError } from '../../src/errors/ToolRouterErrors';
26 +import { ComposioToolExecutionError } from '../../src/errors/ToolErrors';
27
28 // Mock dependencies
29 vi.mock('../../src/telemetry/Telemetry', () => ({
@@ -3053,13 +3055,49 @@ describe('ToolRouter', () => {
3055 expect(result.instantCharge).toEqual({ amount: '0.01', currency: 'USD' });
3056 });
3057
3056 - it('should propagate execute API errors', async () => {
3058 + it('wraps execute API errors with the tool context', async () => {
3059 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
3058 - mockClient.toolRouter.session.execute.mockRejectedValueOnce(new Error('Execute failed'));
3060 + const cause = new Error('Execute failed');
3061 + mockClient.toolRouter.session.execute.mockRejectedValueOnce(cause);
3062
3063 const session = await toolRouter.create(userId);
3064 + const error = await session.execute('GMAIL_SEND_EMAIL').catch(e => e);
3065
3062 - await expect(session.execute('GMAIL_SEND_EMAIL')).rejects.toThrow('Execute failed');
3066 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
3067 + expect(error.message).toBe('Error executing the tool GMAIL_SEND_EMAIL: Execute failed');
3068 + expect(error.cause).toBe(cause);
3069 + });
3070 +
3071 + it('surfaces the server details of a rejected execute', async () => {
3072 + mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
3073 + mockClient.toolRouter.session.execute.mockRejectedValueOnce(
3074 + new APIError(
3075 + 410,
3076 + {
3077 + error: {
3078 + message: 'Toolkit version 20250101_00 is retired',
3079 + code: 1410,
3080 + slug: 'TOOLKIT_VERSION_RETIRED',
3081 + status: 410,
3082 + suggested_fix: 'Pin 20250909_00',
3083 + },
3084 + },
3085 + undefined,
3086 + new Headers({ 'x-request-id': 'req_router_410' })
3087 + )
3088 + );
3089 +
3090 + const session = await toolRouter.create(userId);
3091 + const error = await session.execute('GMAIL_SEND_EMAIL').catch(e => e);
3092 +
3093 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
3094 + expect(error.message).toBe(
3095 + 'Error executing the tool GMAIL_SEND_EMAIL: Toolkit version 20250101_00 is retired'
3096 + );
3097 + expect(error.statusCode).toBe(410);
3098 + expect(error.apiErrorCode).toBe(1410);
3099 + expect(error.requestId).toBe('req_router_410');
3100 + expect(error.possibleFixes).toEqual(['Pin 20250909_00']);
3101 });
3102
3103 it('should default arguments to empty object when omitted', async () => {
@@ -3188,13 +3226,17 @@ describe('ToolRouter', () => {
3226 );
3227 });
3228
3191 - it('should propagate executeMeta API errors', async () => {
3229 + it('wraps executeMeta API errors with the tool context', async () => {
3230 mockClient.toolRouter.session.create.mockResolvedValueOnce(mockSessionCreateResponse);
3193 - mockClient.toolRouter.session.executeMeta.mockRejectedValueOnce(new Error('Execute failed'));
3231 + const cause = new Error('Execute failed');
3232 + mockClient.toolRouter.session.executeMeta.mockRejectedValueOnce(cause);
3233
3234 const session = await toolRouter.create(userId);
3235 + const error = await session.executeMeta('COMPOSIO_SEARCH_TOOLS').catch(e => e);
3236
3197 - await expect(session.executeMeta('COMPOSIO_SEARCH_TOOLS')).rejects.toThrow('Execute failed');
3237 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
3238 + expect(error.message).toBe('Error executing the tool COMPOSIO_SEARCH_TOOLS: Execute failed');
3239 + expect(error.cause).toBe(cause);
3240 });
3241
3242 it('should pass inline custom tools to executeMeta when custom tools are bound', async () => {
ts/packages/core/test/tools/executeSchemaCache.test.ts
+166 -4
@@ -10,6 +10,8 @@ import {
10 ComposioToolExecutionRateLimitError,
11 ComposioToolFetchError,
12 ComposioToolFetchRateLimitError,
13 + ComposioToolNotFoundError,
14 + handleToolExecutionError,
15 isComposioRateLimitError,
16 } from '../../src/errors/ToolErrors';
17
@@ -194,6 +196,7 @@ describe('rate limit errors', () => {
196 expect(isComposioRateLimitError(error)).toBe(true);
197 expect(error.retryAfterSeconds).toBe(7);
198 expect(error.statusCode).toBe(429);
199 + expect(error.message).toBe(`Rate limited while retrieving tool with slug ${SLUG}`);
200 expect(error.possibleFixes).toEqual([
201 'Wait 7 seconds, then retry',
202 'Reduce how many requests your organization sends per minute',
@@ -211,6 +214,7 @@ describe('rate limit errors', () => {
214 expect(isComposioRateLimitError(error)).toBe(true);
215 expect(error.retryAfterSeconds).toBe(7);
216 expect(error.statusCode).toBe(429);
217 + expect(error.message).toBe(`Rate limited while executing the tool ${toolMocks.rawTool.slug}`);
218 expect(execute).toHaveBeenCalledTimes(1);
219 });
220
@@ -336,18 +340,176 @@ describe('tool execution errors', () => {
340 expect(error.possibleFixes).toEqual([SLUG_FIX]);
341 });
342
339 - it('keeps the cause of a missing connected account', async () => {
343 + it('strips terminal escapes and line breaks from server text', async () => {
344 const { tools } = createTools({
341 - execute: () => rejected(400, { message: 'No connected account found', code: 1803 }),
345 + execute: () =>
346 + rejected(403, {
347 + message: 'denied\u001b[31m\n[!] run: evil',
348 + code: 1403,
349 + suggested_fix: 'retry\u001b]0;owned\u0007 now',
350 + }),
351 + });
352 +
353 + const error = await run(tools).catch(e => e);
354 +
355 + expect(error.message).toBe(
356 + `Error executing the tool ${toolMocks.rawTool.slug}: denied [!] run: evil`
357 + );
358 + expect(error.possibleFixes).toEqual(['retry now']);
359 + expect(error.message).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/);
360 + });
361 +
362 + it('keeps the original reason when the failure never reached the API', () => {
363 + const error = handleToolExecutionError(SLUG, new Error('socket hang up\n\u001b[31m'));
364 +
365 + expect(error.message).toBe(`Error executing the tool ${SLUG}: socket hang up`);
366 + });
367 +
368 + it('surfaces the server details of a rate limit', async () => {
369 + const { tools } = createTools({
370 + execute: () =>
371 + rejected(
372 + 429,
373 + { message: 'slow down', code: 1429, suggested_fix: 'Wait an hour' },
374 + { 'retry-after': '7' }
375 + ),
376 + });
377 +
378 + const error = await run(tools).catch(e => e);
379 +
380 + expect(error).toBeInstanceOf(ComposioToolExecutionRateLimitError);
381 + expect(error.message).toBe(
382 + `Rate limited while executing the tool ${toolMocks.rawTool.slug}: slow down`
383 + );
384 + expect(error.statusCode).toBe(429);
385 + expect(error.apiErrorCode).toBe(1429);
386 + expect(error.possibleFixes).toEqual(['Wait an hour']);
387 + expect(error.retryAfterSeconds).toBe(7);
388 + });
389 +
390 + it('strips terminal escapes from the missing-account message', async () => {
391 + const { tools } = createTools({
392 + execute: () =>
393 + rejected(400, {
394 + message: 'No connected account\u001b[31m\n[!] connect',
395 + code: 1803,
396 + }),
397 + });
398 +
399 + const error = await run(tools).catch(e => e);
400 +
401 + expect(error).toBeInstanceOf(ComposioConnectedAccountNotFoundError);
402 + expect(error.message).toBe('No connected account [!] connect');
403 + expect(error.message).not.toMatch(/[\u0000-\u001f\u007f-\u009f]/);
404 + });
405 +
406 + it('keeps the server status, fix and code of a missing connected account', async () => {
407 + const { tools } = createTools({
408 + execute: () =>
409 + rejected(400, {
410 + message: 'No connected account found',
411 + code: 1803,
412 + suggested_fix: 'Connect Gmail first',
413 + }),
414 });
415
416 const error = await run(tools).catch(e => e);
417
418 expect(error).toBeInstanceOf(ComposioConnectedAccountNotFoundError);
419 expect(error.message).toBe('No connected account found');
348 - // The class sets its status itself, and an explicit status wins over the cause's.
349 - expect(error.statusCode).toBe(404);
420 + expect(error.statusCode).toBe(400);
421 + expect(error.apiErrorCode).toBe(1803);
422 + expect(error.possibleFixes).toEqual(['Connect Gmail first']);
423 expect(error.cause).toBeInstanceOf(APIError);
424 expect(error.cause.status).toBe(400);
425 });
426 });
427 +
428 +describe('tool fetch errors', () => {
429 + it('surfaces the server details of a 429', async () => {
430 + const { tools } = createTools({
431 + retrieve: () =>
432 + json(
433 + {
434 + error: {
435 + message: 'slow down',
436 + code: 1429,
437 + slug: 'RATE_LIMITED',
438 + status: 429,
439 + suggested_fix: 'Wait an hour',
440 + },
441 + },
442 + 429,
443 + { 'retry-after': '7', 'retry-after-ms': '1' }
444 + ),
445 + });
446 +
447 + const error = await run(tools).catch(e => e);
448 +
449 + expect(error).toBeInstanceOf(ComposioToolFetchRateLimitError);
450 + expect(error.message).toBe(`Rate limited while retrieving tool with slug ${SLUG}: slow down`);
451 + expect(error.statusCode).toBe(429);
452 + expect(error.apiErrorCode).toBe(1429);
453 + expect(error.possibleFixes).toEqual(['Wait an hour']);
454 + expect(error.retryAfterSeconds).toBe(7);
455 + });
456 +
457 + it('surfaces the server details of a 410', async () => {
458 + const { tools, execute } = createTools({
459 + retrieve: () =>
460 + json(
461 + {
462 + error: {
463 + message: 'Toolkit version 20250101_00 is retired',
464 + code: 1410,
465 + slug: 'TOOLKIT_VERSION_RETIRED',
466 + status: 410,
467 + suggested_fix: 'Pin 20250909_00',
468 + },
469 + },
470 + 410,
471 + { 'x-request-id': 'req_fetch_410' }
472 + ),
473 + });
474 +
475 + const error = await tools.getRawComposioToolBySlug(SLUG).catch(e => e);
476 +
477 + expect(error).toBeInstanceOf(ComposioToolFetchError);
478 + expect(error.message).toBe(
479 + `Unable to retrieve tool with slug ${SLUG}: Toolkit version 20250101_00 is retired`
480 + );
481 + expect(error.statusCode).toBe(410);
482 + expect(error.apiErrorCode).toBe(1410);
483 + expect(error.requestId).toBe('req_fetch_410');
484 + expect(error.possibleFixes).toEqual(['Pin 20250909_00']);
485 + expect(execute).not.toHaveBeenCalled();
486 + });
487 +
488 + it('surfaces the server details of a 404', async () => {
489 + const { tools } = createTools({
490 + retrieve: () =>
491 + json(
492 + {
493 + error: {
494 + message: 'No tool with that slug in the pinned version',
495 + code: 1404,
496 + slug: 'TOOL_NOT_FOUND',
497 + status: 404,
498 + suggested_fix: 'Use the latest version',
499 + },
500 + },
501 + 404
502 + ),
503 + });
504 +
505 + const error = await tools.getRawComposioToolBySlug(SLUG).catch(e => e);
506 +
507 + expect(error).toBeInstanceOf(ComposioToolNotFoundError);
508 + expect(error.message).toBe(
509 + `Tool with slug ${SLUG} not found: No tool with that slug in the pinned version`
510 + );
511 + expect(error.statusCode).toBe(404);
512 + expect(error.apiErrorCode).toBe(1404);
513 + expect(error.possibleFixes).toEqual(['Use the latest version']);
514 + });
515 +});
ts/packages/core/test/tools/tools.test.ts
+48 -7
@@ -1,5 +1,5 @@
1 import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 -import ComposioClient from '@composio/client';
2 +import ComposioClient, { APIError } from '@composio/client';
3 import { mockClient } from '../utils/mocks/client.mock';
4 import { toolMocks } from '../utils/mocks/data.mock';
5 import { Tool, ToolListParams, ToolExecuteParams } from '../../src/types/tool.types';
@@ -14,6 +14,7 @@ import {
14 import { MockProvider } from '../utils/mocks/provider.mock';
15 import { ValidationError } from '../../src/errors/ValidationErrors';
16 import {
17 + ComposioToolExecutionError,
18 ComposioToolFetchError,
19 ComposioToolNotFoundError,
20 ComposioToolSchemaInvalidError,
@@ -738,7 +739,7 @@ describe('Tools', () => {
739 const slug = 'SLACK_FETCH_CONVERSATION_HISTORY';
740 const unauthorized = new ComposioClient.AuthenticationError(
741 401,
741 - { error: { message: 'Invalid API key', code: 801, status: 401 } },
742 + { error: { message: 'Invalid API key', code: 801, slug: 'UNAUTHORIZED', status: 401 } },
743 undefined,
744 new Headers()
745 );
@@ -750,7 +751,9 @@ describe('Tools', () => {
751 expect(error).toBeInstanceOf(ComposioToolFetchError);
752 expect(error).not.toBeInstanceOf(ComposioToolNotFoundError);
753 expect(error.name).toBe('ComposioToolFetchError');
753 - expect(error.message).toBe(`Unable to retrieve tool with slug ${slug}`);
754 + expect(error.message).toBe(`Unable to retrieve tool with slug ${slug}: Invalid API key`);
755 + expect(error.statusCode).toBe(401);
756 + expect(error.apiErrorCode).toBe(801);
757 expect(error.cause).toBe(unauthorized);
758 expect(error.cause.status).toBe(401);
759 });
@@ -1699,16 +1702,54 @@ describe('Tools', () => {
1702 ).rejects.toThrow('Invalid tool execute session parameters');
1703 });
1704
1702 - it('should throw error if tool is not found', async () => {
1705 + it('wraps a failed session execution with the tool context', async () => {
1706 const apiError = new Error('Tool not found');
1707 mockClient.toolRouter.session.execute.mockRejectedValueOnce(apiError);
1708
1706 - await expect(
1707 - context.tools.executeSessionTool('NONEXISTENT_TOOL', {
1709 + const error = await context.tools
1710 + .executeSessionTool('NONEXISTENT_TOOL', {
1711 sessionId,
1712 arguments: { query: 'test' },
1713 })
1711 - ).rejects.toThrow('Tool not found');
1714 + .catch(e => e);
1715 +
1716 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
1717 + expect(error.message).toBe('Error executing the tool NONEXISTENT_TOOL: Tool not found');
1718 + expect(error.cause).toBe(apiError);
1719 + });
1720 +
1721 + it('surfaces the server details of a rejected session execution', async () => {
1722 + const apiError = new APIError(
1723 + 410,
1724 + {
1725 + error: {
1726 + message: 'Toolkit version 20250101_00 is retired',
1727 + code: 1410,
1728 + slug: 'TOOLKIT_VERSION_RETIRED',
1729 + status: 410,
1730 + suggested_fix: 'Pin 20250909_00',
1731 + },
1732 + },
1733 + undefined,
1734 + new Headers({ 'x-request-id': 'req_session_410' })
1735 + );
1736 + mockClient.toolRouter.session.execute.mockRejectedValueOnce(apiError);
1737 +
1738 + const error = await context.tools
1739 + .executeSessionTool('GMAIL_SEND_EMAIL', {
1740 + sessionId,
1741 + arguments: { query: 'test' },
1742 + })
1743 + .catch(e => e);
1744 +
1745 + expect(error).toBeInstanceOf(ComposioToolExecutionError);
1746 + expect(error.message).toBe(
1747 + 'Error executing the tool GMAIL_SEND_EMAIL: Toolkit version 20250101_00 is retired'
1748 + );
1749 + expect(error.statusCode).toBe(410);
1750 + expect(error.apiErrorCode).toBe(1410);
1751 + expect(error.requestId).toBe('req_session_410');
1752 + expect(error.possibleFixes).toEqual(['Pin 20250909_00']);
1753 });
1754
1755 it('should apply beforeExecute modifier', async () => {