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

next
py 658 lines 18.2 KB
Raw
1 """
2 Composio exceptions.
3 """
4
5 import difflib
6 import re
7 import typing as t
8
9 import typing_extensions as te
10
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."""
50
51 def __init__(
52 self,
53 message: str,
54 *args: t.Any,
55 delegate: bool = False,
56 ) -> None:
57 """
58 Initialize Composio SDK error.
59
60 :param message: Error message
61 :param delegate: Whether to delegate the error message to the log
62 collection server or not
63 """
64 super().__init__(message, *args)
65 self.message = message
66 self.delegate = delegate
67
68
69 class NotFoundError(ComposioError):
70 pass
71
72
73 class HTTPError(ComposioError):
74 """
75 Exception class for HTTP API errors.
76 """
77
78 def __init__(
79 self,
80 message: str,
81 status_code: int,
82 *args: t.Any,
83 delegate: bool = False,
84 ) -> None:
85 """
86 Initialize HTTPError class.
87
88 :param message: Content from the API response
89 :param status_code: HTTP response status code
90 :param delegate: Whether to delegate the error message to the log
91 collection server or not
92 """
93 super().__init__(message, *args, delegate=delegate)
94 self.status_code = status_code
95
96
97 class ComposioClientError(ComposioError):
98 """
99 Exception class for Composio client errors.
100 """
101
102
103 class SDKError(ComposioError):
104 pass
105
106
107 class ProcessorError(SDKError):
108 pass
109
110
111 class EnumError(ComposioError):
112 pass
113
114
115 class ValidationError(ComposioError):
116 pass
117
118
119 class JSONSchemaRefResolutionError(ValidationError):
120 """Raised when an internal JSON Schema ``$ref`` cannot be inlined.
121
122 Covers malformed pointers, missing ``$defs``/``definitions`` targets
123 (strict mode only), and ``$ref`` chains or node nesting that exceed the
124 safety caps in :func:`composio.utils.json_schema.dereference_json_schema`.
125 """
126
127 def __init__(
128 self,
129 message: str,
130 *args: t.Any,
131 meta: t.Optional[t.Dict[str, t.Any]] = None,
132 delegate: bool = False,
133 ) -> None:
134 super().__init__(message, *args, delegate=delegate)
135 self.meta = meta or {}
136
137
138 class ToolkitError(ComposioError):
139 pass
140
141
142 class EntityIDError(ComposioError):
143 pass
144
145
146 class PluginError(ComposioError):
147 pass
148
149
150 class InvalidParams(ComposioError):
151 pass
152
153
154 class FileError(ComposioError):
155 pass
156
157
158 class ComposioSDKTimeoutError(ComposioError, TimeoutError):
159 pass
160
161
162 class SDKFileNotFoundError(ComposioError, FileNotFoundError):
163 pass
164
165
166 class LockFileError(ComposioError):
167 pass
168
169
170 class VersionError(ComposioError):
171 pass
172
173
174 class InvalidLockFile(LockFileError):
175 pass
176
177
178 class InvalidVersionString(EnumError):
179 pass
180
181
182 class VersionSelectionError(LockFileError, VersionError):
183 def __init__(
184 self,
185 action: str,
186 requested: str,
187 locked: str,
188 delegate: bool = False,
189 ) -> None:
190 self.action = action
191 self.requested = requested
192 self.locked = locked
193 super().__init__(
194 message=(
195 f"Error selecting version for action: {action!r}, "
196 f"requested: {requested!r}, locked: {locked!r}"
197 ),
198 delegate=delegate,
199 )
200
201
202 class InvalidEnum(EnumError):
203 pass
204
205
206 class EnumStringNotFound(EnumError):
207 """Raise when user provides invalid enum string."""
208
209 def __init__(self, value: str, enum: str, possible_values: t.List[str]) -> None:
210 error_message = f"Invalid value `{value}` for enum class `{enum}`"
211 matches = difflib.get_close_matches(value, possible_values, n=1)
212 if matches:
213 (match,) = matches
214 error_message += f". Did you mean {match!r}?"
215
216 super().__init__(message=error_message)
217
218
219 class EnumMetadataNotFound(EnumError):
220 pass
221
222
223 class ErrorUploadingFile(FileError):
224 pass
225
226
227 class BlockedInternalUrlError(FileError):
228 """Raised when a URL file input resolves to a non-public network address."""
229
230
231 class SensitiveFilePathBlockedError(FileError):
232 """Raised when a local file path is refused before upload (sensitive directory or credential-like name)."""
233
234
235 class FileUploadPathNotAllowedError(FileError):
236 """
237 Raised when automatic file upload during tool execution is attempted from a
238 path outside the configured ``file_upload_dirs`` allowlist.
239
240 Only fires for auto-upload (enabled via
241 ``dangerously_allow_auto_upload_download_files=True``). Manual upload APIs
242 are not subject to this check.
243 """
244
245
246 class FileUploadAbortedError(FileError):
247 """Raised when a ``before_file_upload`` hook returns ``False``."""
248
249
250 class UnsafePathComponentError(FileError):
251 """
252 Raised when untrusted input (a tool slug, toolkit slug, or server-supplied
253 filename) cannot be safely used as part of a filesystem path.
254
255 Fails closed: the SDK refuses the write rather than sanitizing the value
256 into something that merely looks safe.
257 """
258
259
260 class ErrorDownloadingFile(FileError):
261 pass
262
263
264 class RemoteFileDownloadError(FileError):
265 """Raised when fetching a remote file from a tool router session mount fails.
266
267 Includes HTTP status, URL, and file path context for debugging.
268 """
269
270 def __init__(
271 self,
272 message: str = "Failed to download remote file",
273 *,
274 status_code: t.Optional[int] = None,
275 status_text: t.Optional[str] = None,
276 download_url: t.Optional[str] = None,
277 mount_relative_path: t.Optional[str] = None,
278 filename: t.Optional[str] = None,
279 **kwargs: t.Any,
280 ) -> None:
281 super().__init__(message, **kwargs)
282 self.status_code = status_code
283 self.status_text = status_text
284 self.download_url = download_url
285 self.mount_relative_path = mount_relative_path
286 self.filename = filename
287
288
289 class ResponseTooLargeError(FileError):
290 """Raised when a response exceeds the maximum allowed size."""
291
292 pass
293
294
295 class TriggerError(ToolkitError):
296 pass
297
298
299 class WebhookSignatureVerificationError(TriggerError):
300 """Raised when webhook signature verification fails."""
301
302 pass
303
304
305 class WebhookPayloadError(TriggerError):
306 """Raised when webhook payload is invalid."""
307
308 pass
309
310
311 class TriggerTypeNotFound(TriggerError, NotFoundError):
312 """Raised when a trigger type cannot be found for the given slug.
313
314 Mirrors the TypeScript SDK's ``ComposioTriggerTypeNotFoundError``.
315 """
316
317 pass
318
319
320 class ActionError(ToolkitError):
321 pass
322
323
324 class TriggerSubscriptionError(TriggerError, ComposioClientError):
325 pass
326
327
328 class InvalidTriggerFilters(TriggerSubscriptionError):
329 pass
330
331
332 class TriggerSubscriptionAuthError(TriggerSubscriptionError):
333 """Raised when the realtime channel-auth request fails.
334
335 Covers a transport error, a timeout, a non-200 response, and a response
336 without an ``auth`` token.
337 """
338
339 pass
340
341
342 class InvalidPusherClusterError(TriggerSubscriptionError, ValidationError):
343 """Raised when the realtime credentials carry a malformed pusher cluster."""
344
345 pass
346
347
348 class ApiKeyError(ComposioClientError):
349 pass
350
351
352 class ApiKeyNotProvidedError(ApiKeyError, NotFoundError):
353 """Raise when API key is required but not provided."""
354
355 def __init__(self) -> None:
356 super().__init__(
357 message=(
358 f"API key not provided. Set `{ENV_COMPOSIO_API_KEY}` or pass "
359 "`api_key` to `Composio(api_key=...)`. Get a project API key "
360 "from your project's Settings > API Keys: "
361 "https://docs.composio.dev/docs/quickstart. "
362 "Optional: `composio login` requires installing the CLI separately "
363 "(https://docs.composio.dev/docs/cli#install). CLI login alone "
364 f"does not set `{ENV_COMPOSIO_API_KEY}` for your application."
365 ),
366 )
367
368
369 class UserApiKeyNotProvidedError(ApiKeyError):
370 """Raised when the project key is disabled and no user API key is available."""
371
372 def __init__(self) -> None:
373 super().__init__(
374 message=(
375 "`disable_api_key=True` turns off the project API key, but no user "
376 "API key was provided: pass `user_api_key` or export it as "
377 "`COMPOSIO_USER_API_KEY`"
378 )
379 )
380
381
382 class MCPDestinationError(ComposioClientError):
383 """Raised when a session's hosted MCP endpoint is not a destination the
384 SDK will hand the session headers to.
385
386 The credential and scope headers are only attached when the MCP URL shares
387 the origin of the API base URL the session was created against. The error
388 is raised only when the caller asked for the endpoint with ``mcp=True``;
389 otherwise the session is returned with empty ``mcp.headers`` and a warning
390 is logged instead. The message names both origins and never includes a
391 credential value.
392 """
393
394 def __init__(self, message: str, *, mcp_origin: str, api_origin: str) -> None:
395 super().__init__(message)
396 self.mcp_origin = mcp_origin
397 self.api_origin = api_origin
398
399
400 class SessionConfigConflictError(ComposioClientError):
401 """Raised when a session update is rejected with HTTP 409 because the
402 session configuration changed since it was last read, for example when an
403 ``expected_config_version`` precondition passed to ``update()`` is stale.
404
405 The local session object is left as it was before the call. Re-fetch the
406 session with ``composio.sessions.use(session_id)`` and retry the update
407 against the fresh ``config_version``.
408 """
409
410 status_code = 409
411
412 def __init__(
413 self,
414 message: str,
415 *,
416 session_id: str,
417 expected_config_version: t.Optional[int] = None,
418 ) -> None:
419 super().__init__(message)
420 self.session_id = session_id
421 self.expected_config_version = expected_config_version
422
423
424 class ToolInputRequest(te.TypedDict):
425 """One question a tool asks the user before it can run."""
426
427 type: str
428 """Kind of input requested, currently ``"elicitation"``."""
429 mode: str
430 """How the client collects the input, currently ``"form"``."""
431 message: str
432 """Message to show the user."""
433 requested_schema: t.Dict[str, t.Any]
434 """JSON Schema for the answer: a flat object with string, number, boolean
435 or enum fields."""
436
437
438 class ToolInputRequiredError(ComposioClientError):
439 """Raised when a session tool execution or proxied call did not run
440 because it needs input from the user first, for example an approval. The
441 API answers such a call with ``result_type: "input_required"`` instead of
442 a result.
443
444 ``input_requests`` holds the questions, keyed by the ID the answers must
445 reuse. ``request_state`` is the opaque state the API returned; when present
446 it must be sent back unchanged together with the answers. Nothing was
447 executed and the call is not retried: to answer, repeat the same call with
448 ``input_responses`` and ``request_state``.
449
450 ``request_state`` is continuation state, so it is kept out of logs: read it
451 as an attribute. ``str()``, ``repr()``, ``args`` and a formatted traceback
452 do not include it.
453 """
454
455 def __init__(
456 self,
457 subject: str,
458 *,
459 input_requests: t.Dict[str, ToolInputRequest],
460 request_state: t.Optional[str] = None,
461 ) -> None:
462 count = len(input_requests)
463 super().__init__(
464 f"{subject} requires user input before it can run "
465 f"({count} input request{'' if count == 1 else 's'}) and was not "
466 "executed. The questions are on `input_requests`. Repeat the call "
467 "with the answers in `input_responses` and this error's "
468 "`request_state`."
469 )
470 self.input_requests = input_requests
471 self.request_state = request_state
472
473
474 class ResourceError(ComposioClientError):
475 pass
476
477
478 class NoItemsFound(ResourceError):
479 """
480 Exception class for empty collection values.
481 """
482
483
484 class ErrorFetchingResource(ResourceError):
485 pass
486
487
488 class SchemaError(ToolkitError):
489 pass
490
491
492 class InvalidSchemaError(SchemaError, TypeError):
493 pass
494
495
496 class InvalidEntityIdError(EntityIDError, ValueError):
497 pass
498
499
500 class IntegrationError(ResourceError):
501 pass
502
503
504 class ConnectedAccountError(ResourceError):
505 pass
506
507
508 class ConnectedAccountNotFoundError(NotFoundError, ConnectedAccountError):
509 pass
510
511
512 class InvalidConnectedAccount(ValidationError, ConnectedAccountError):
513 pass
514
515
516 class ComposioMultipleConnectedAccountsError(ConnectedAccountError):
517 """Raised when multiple connected accounts are found for a user and auth config."""
518
519 pass
520
521
522 class ComposioLegacyConnectedAccountsEndpointRetiredError(ConnectedAccountError):
523 """Raised by ``composio.connected_accounts.initiate()`` when the legacy
524 ``POST /api/v3/connected_accounts`` endpoint rejects a Composio-managed
525 OAuth (OAuth1, OAuth2, DCR_OAUTH) auth-config request.
526
527 Cutover dates: 2026-05-08 (new orgs), 2026-07-03 (all remaining orgs).
528 Migrate to ``composio.connected_accounts.link()`` — same return shape,
529 works for every redirectable scheme regardless of whether the auth
530 config is Composio-managed or custom.
531
532 See: https://docs.composio.dev/docs/changelog/2026/04/24
533 """
534
535 pass
536
537
538 class ComposioConnectedAccountRevocationNotSupportedError(ConnectedAccountError):
539 """Raised by ``composio.connected_accounts.revoke()`` when the toolkit
540 behind the connected account does not support programmatic token
541 revocation (API ``400``).
542
543 Fix: delete or disable the connected account instead, and revoke the
544 grant from the provider's own settings page.
545 """
546
547 pass
548
549
550 class ComposioConnectedAccountNotRevokableError(ConnectedAccountError):
551 """Raised by ``composio.connected_accounts.revoke()`` when the connected
552 account is not in a state that can be revoked (API ``409``), for
553 example because it was already revoked or never became ``ACTIVE``.
554 """
555
556 pass
557
558
559 class ComposioAclOnlyForSharedError(ConnectedAccountError):
560 """Raised when ACL fields (``allow_all_users``, ``allowed_user_ids``,
561 ``not_allowed_user_ids``) are sent on a ``PRIVATE`` connection. ACL
562 is only meaningful for ``SHARED`` connections.
563
564 Fix: use ``account_type='SHARED'``, or omit the ACL fields when
565 creating/updating a PRIVATE connection.
566 """
567
568 pass
569
570
571 class ComposioSharedAccessDeniedError(ConnectedAccountError):
572 """Raised when a tool execution attempts to use a SHARED connected
573 account but the requesting ``user_id`` is not allowed by the
574 connection's ACL.
575
576 Surfaces when a SHARED connection is reached directly (e.g. via
577 ``composio.tools.execute(slug, connected_account_id=...)``) without
578 going through a tool-router session.
579
580 Fix: ask the connection's creator to grant access via
581 ``composio.experimental.update_acl()`` — set ``allow_all_users``,
582 add the ``user_id`` to ``allowed_user_ids``, or remove it from
583 ``not_allowed_user_ids``.
584 """
585
586 pass
587
588
589 class ComposioSharedConnectionNotAccessibleError(ConnectedAccountError):
590 """Raised by ``tool_router.session.create()`` / ``session.patch()``
591 when the session's ``user_id`` cannot use a pinned SHARED connection.
592 Raised at session-create time so the session never enters a state
593 that fails mid-execution.
594
595 Fix: grant the session user access via
596 ``composio.experimental.update_acl()`` on the pinned connection,
597 or pin a different connection the user can use.
598 """
599
600 pass
601
602
603 class ErrorProcessingToolExecutionRequest(PluginError):
604 pass
605
606
607 class DescopeAuthError(ComposioError):
608 pass
609
610
611 class DescopeConfigError(ComposioError):
612 pass
613
614
615 class InvalidExecuteFunctionError(ComposioError):
616 pass
617
618
619 class ToolNotFoundError(NotFoundError):
620 """Raised when a tool slug does not exist.
621
622 Mirrors the TypeScript SDK's ``ComposioToolNotFoundError``. Other failures
623 while fetching a tool (invalid API key, server or network errors) are not
624 translated and surface as the underlying ``composio_client`` error.
625 """
626
627
628 class InvalidModifier(ComposioError):
629 pass
630
631
632 class ExecuteToolFnNotSetError(ComposioError):
633 pass
634
635
636 class ToolVersionRequiredError(ComposioError):
637 """Raised when toolkit version is not specified for manual tool execution."""
638
639 def __init__(self) -> None:
640 super().__init__(
641 message=(
642 "Toolkit version not specified. For manual execution of the tool "
643 "please pass a specific toolkit version.\n\n"
644 "Possible fixes:\n"
645 "1. Pass the toolkit version as a parameter to the execute function "
646 '("latest" is not supported in manual execution)\n'
647 "2. Set the toolkit versions in the Composio config "
648 "(toolkit_versions={'<toolkit-slug>': '<toolkit-version>'})\n"
649 "3. Set the toolkit version in the environment variable "
650 "(COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_SLUG>)\n"
651 "4. Set dangerously_skip_version_check to True "
652 "(this might cause unexpected behavior when new versions of the tools are released)"
653 ),
654 )
655
656
657 class UsageError(ComposioError):
658 pass