Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
| 1 | """ |
| 2 | Webhooks module for the Composio SDK. |
| 3 | |
| 4 | Exposes ``composio.webhooks.subscriptions`` (the project-level webhook |
| 5 | subscription used for event delivery) and ``composio.webhooks.endpoints`` |
| 6 | (per toolkit + OAuth app inbound ingress URLs). |
| 7 | """ |
| 8 | |
| 9 | from __future__ import annotations |
| 10 | |
| 11 | import typing as t |
| 12 | from enum import Enum |
| 13 | |
| 14 | import pydantic |
| 15 | |
| 16 | from composio import exceptions |
| 17 | from composio.client import HttpClient |
| 18 | from composio.client.types import ( |
| 19 | webhook_endpoint_create_response, |
| 20 | webhook_endpoint_list_response, |
| 21 | webhook_endpoint_replace_response, |
| 22 | webhook_endpoint_retrieve_response, |
| 23 | webhook_endpoint_update_response, |
| 24 | webhook_subscription_delete_response, |
| 25 | webhook_subscription_list_event_types_response, |
| 26 | webhook_subscription_list_response, |
| 27 | webhook_subscription_retrieve_response, |
| 28 | webhook_subscription_rotate_secret_response, |
| 29 | webhook_subscription_update_response, |
| 30 | ) |
| 31 | from composio.core.models.base import Resource |
| 32 | from composio.utils.pydantic import none_to_omit |
| 33 | |
| 34 | |
| 35 | class WebhookVersion(str, Enum): |
| 36 | """Webhook payload version.""" |
| 37 | |
| 38 | V1 = "V1" |
| 39 | V2 = "V2" |
| 40 | V3 = "V3" |
| 41 | |
| 42 | |
| 43 | WebhookVersionL = t.Literal["V1", "V2", "V3"] |
| 44 | |
| 45 | _WEBHOOK_VERSIONS: t.Dict[str, WebhookVersionL] = {"V1": "V1", "V2": "V2", "V3": "V3"} |
| 46 | |
| 47 | |
| 48 | def _webhook_version(version: t.Union[WebhookVersion, str]) -> WebhookVersionL: |
| 49 | """Narrow a caller-supplied version to the literal the client accepts.""" |
| 50 | value = version.value if isinstance(version, WebhookVersion) else version |
| 51 | literal = _WEBHOOK_VERSIONS.get(value) |
| 52 | if literal is None: |
| 53 | raise exceptions.ValidationError( |
| 54 | f"unsupported webhook version {value!r}; expected one of V1, V2, V3" |
| 55 | ) |
| 56 | return literal |
| 57 | |
| 58 | |
| 59 | class WebhookSubscription(t.TypedDict, total=False): |
| 60 | """Webhook subscription returned by the Composio API.""" |
| 61 | |
| 62 | id: str |
| 63 | webhook_url: str |
| 64 | version: str |
| 65 | enabled_events: t.List[str] |
| 66 | secret: str |
| 67 | created_at: str |
| 68 | updated_at: str |
| 69 | |
| 70 | |
| 71 | DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS = ("composio.trigger.message",) |
| 72 | |
| 73 | |
| 74 | class _WebhookSubscriptionWire(pydantic.BaseModel): |
| 75 | """Boundary schema for a subscription response. |
| 76 | |
| 77 | Accepts snake_case or camelCase wire keys and rejects a payload that |
| 78 | lacks the fields :class:`WebhookSubscription` promises, so a malformed |
| 79 | 2xx surfaces as a :class:`~composio.exceptions.ValidationError` instead |
| 80 | of a typed subscription with empty or defaulted values. |
| 81 | """ |
| 82 | |
| 83 | model_config = pydantic.ConfigDict(extra="ignore", populate_by_name=True) |
| 84 | |
| 85 | id: str = pydantic.Field(min_length=1) |
| 86 | webhook_url: str = pydantic.Field( |
| 87 | min_length=1, |
| 88 | validation_alias=pydantic.AliasChoices("webhook_url", "webhookUrl"), |
| 89 | ) |
| 90 | version: str = pydantic.Field(min_length=1) |
| 91 | enabled_events: t.List[str] = pydantic.Field( |
| 92 | validation_alias=pydantic.AliasChoices("enabled_events", "enabledEvents"), |
| 93 | ) |
| 94 | secret: t.Optional[str] = None |
| 95 | created_at: t.Optional[str] = pydantic.Field( |
| 96 | default=None, |
| 97 | validation_alias=pydantic.AliasChoices("created_at", "createdAt"), |
| 98 | ) |
| 99 | updated_at: t.Optional[str] = pydantic.Field( |
| 100 | default=None, |
| 101 | validation_alias=pydantic.AliasChoices("updated_at", "updatedAt"), |
| 102 | ) |
| 103 | |
| 104 | |
| 105 | def normalize_webhook_subscription(raw: object) -> WebhookSubscription: |
| 106 | """Build a typed :class:`WebhookSubscription` from an API response. |
| 107 | |
| 108 | Accepts either the client's pydantic response models or a plain dict and |
| 109 | validates it against :class:`_WebhookSubscriptionWire`, so the returned |
| 110 | dict always matches the declared shape and a malformed response raises |
| 111 | :class:`~composio.exceptions.ValidationError` at the boundary. |
| 112 | """ |
| 113 | if isinstance(raw, pydantic.BaseModel): |
| 114 | # The client builds response models without validation, so enum |
| 115 | # fields hold plain strings; silence pydantic's serializer warnings. |
| 116 | data: t.Any = raw.model_dump(mode="json", warnings=False) |
| 117 | elif isinstance(raw, dict): |
| 118 | data = raw |
| 119 | else: |
| 120 | raise exceptions.ValidationError( |
| 121 | "malformed webhook subscription response: expected an object, " |
| 122 | f"got {type(raw).__name__}" |
| 123 | ) |
| 124 | |
| 125 | try: |
| 126 | parsed = _WebhookSubscriptionWire.model_validate(data) |
| 127 | except pydantic.ValidationError as error: |
| 128 | raise exceptions.ValidationError( |
| 129 | f"malformed webhook subscription response: {error}" |
| 130 | ) from error |
| 131 | |
| 132 | result: WebhookSubscription = { |
| 133 | "id": parsed.id, |
| 134 | "webhook_url": parsed.webhook_url, |
| 135 | "version": parsed.version, |
| 136 | "enabled_events": list(parsed.enabled_events), |
| 137 | } |
| 138 | if parsed.secret is not None: |
| 139 | result["secret"] = parsed.secret |
| 140 | if parsed.created_at is not None: |
| 141 | result["created_at"] = parsed.created_at |
| 142 | if parsed.updated_at is not None: |
| 143 | result["updated_at"] = parsed.updated_at |
| 144 | return result |
| 145 | |
| 146 | |
| 147 | def first_webhook_subscription_id(response: object) -> t.Optional[str]: |
| 148 | """Return the id of the first subscription in a list response. |
| 149 | |
| 150 | Accepts the client's typed list response (``.items`` of models with an |
| 151 | ``.id``) as well as a plain dict of the same shape. Returns ``None`` only |
| 152 | for an empty list; a payload without an ``items`` list, or whose first |
| 153 | item has no id, raises :class:`~composio.exceptions.ValidationError` so |
| 154 | the upsert never falls through to ``create`` on malformed data. |
| 155 | """ |
| 156 | items = ( |
| 157 | response.get("items") |
| 158 | if isinstance(response, dict) |
| 159 | else getattr(response, "items", None) |
| 160 | ) |
| 161 | if not isinstance(items, list): |
| 162 | raise exceptions.ValidationError( |
| 163 | "malformed webhook subscription list response: missing items" |
| 164 | ) |
| 165 | if len(items) == 0: |
| 166 | return None |
| 167 | |
| 168 | first = items[0] |
| 169 | subscription_id = ( |
| 170 | first.get("id") if isinstance(first, dict) else getattr(first, "id", None) |
| 171 | ) |
| 172 | if not isinstance(subscription_id, str) or not subscription_id: |
| 173 | raise exceptions.ValidationError( |
| 174 | "malformed webhook subscription list response: item without id" |
| 175 | ) |
| 176 | return subscription_id |
| 177 | |
| 178 | |
| 179 | class WebhookSubscriptions(Resource): |
| 180 | """Manage the project webhook subscription. |
| 181 | |
| 182 | The API allows one subscription per project; the signing secret is |
| 183 | returned in responses. |
| 184 | """ |
| 185 | |
| 186 | def list( |
| 187 | self, |
| 188 | *, |
| 189 | limit: t.Optional[float] = None, |
| 190 | cursor: t.Optional[str] = None, |
| 191 | ) -> webhook_subscription_list_response.WebhookSubscriptionListResponse: |
| 192 | """ |
| 193 | List webhook subscriptions for the project. |
| 194 | |
| 195 | :param limit: Maximum number of subscriptions to return. |
| 196 | :param cursor: Pagination cursor from a previous response. |
| 197 | :return: Paginated list of subscriptions. |
| 198 | |
| 199 | Example: |
| 200 | subscriptions = composio.webhooks.subscriptions.list() |
| 201 | """ |
| 202 | return self._client.webhook_subscriptions.list( |
| 203 | limit=none_to_omit(limit), |
| 204 | cursor=none_to_omit(cursor), |
| 205 | ) |
| 206 | |
| 207 | def get( |
| 208 | self, id: str |
| 209 | ) -> webhook_subscription_retrieve_response.WebhookSubscriptionRetrieveResponse: |
| 210 | """ |
| 211 | Retrieve a webhook subscription by id. |
| 212 | |
| 213 | :param id: The subscription id. |
| 214 | :return: The subscription, including its signing secret. |
| 215 | |
| 216 | Example: |
| 217 | subscription = composio.webhooks.subscriptions.get("sub_123") |
| 218 | """ |
| 219 | return self._client.webhook_subscriptions.retrieve(id) |
| 220 | |
| 221 | def set( |
| 222 | self, |
| 223 | *, |
| 224 | webhook_url: str, |
| 225 | enabled_events: t.Optional[t.Sequence[str]] = None, |
| 226 | version: t.Union[WebhookVersion, str] = WebhookVersion.V3, |
| 227 | ) -> WebhookSubscription: |
| 228 | """ |
| 229 | Create or update the project webhook subscription used for webhook delivery. |
| 230 | |
| 231 | If a subscription already exists, the first subscription is updated. Otherwise a |
| 232 | new subscription is created. By default this subscribes to V3 trigger message |
| 233 | events. |
| 234 | |
| 235 | :param webhook_url: The URL Composio delivers events to. |
| 236 | :param enabled_events: Event types to subscribe to. Defaults to |
| 237 | ``composio.trigger.message``. |
| 238 | :param version: Webhook payload version. Defaults to ``V3``. |
| 239 | :return: The normalized subscription. |
| 240 | |
| 241 | Example: |
| 242 | composio.webhooks.subscriptions.set( |
| 243 | webhook_url=f"{APP_URL}/webhooks/composio", |
| 244 | ) |
| 245 | """ |
| 246 | if not webhook_url: |
| 247 | raise exceptions.ValidationError("please provide a valid `webhook_url`") |
| 248 | |
| 249 | events = list( |
| 250 | DEFAULT_WEBHOOK_SUBSCRIPTION_EVENTS |
| 251 | if enabled_events is None |
| 252 | else enabled_events |
| 253 | ) |
| 254 | if len(events) == 0: |
| 255 | raise exceptions.ValidationError( |
| 256 | "please provide at least one enabled event" |
| 257 | ) |
| 258 | |
| 259 | version_value = _webhook_version(version) |
| 260 | |
| 261 | existing = self._client.webhook_subscriptions.list(limit=1) |
| 262 | subscription_id = first_webhook_subscription_id(existing) |
| 263 | |
| 264 | if subscription_id: |
| 265 | return normalize_webhook_subscription( |
| 266 | self._client.webhook_subscriptions.update( |
| 267 | subscription_id, |
| 268 | webhook_url=webhook_url, |
| 269 | enabled_events=events, |
| 270 | version=version_value, |
| 271 | ) |
| 272 | ) |
| 273 | |
| 274 | return normalize_webhook_subscription( |
| 275 | self._client.webhook_subscriptions.create( |
| 276 | webhook_url=webhook_url, |
| 277 | enabled_events=events, |
| 278 | version=version_value, |
| 279 | ) |
| 280 | ) |
| 281 | |
| 282 | def update( |
| 283 | self, |
| 284 | id: str, |
| 285 | *, |
| 286 | webhook_url: t.Optional[str] = None, |
| 287 | enabled_events: t.Optional[t.Sequence[str]] = None, |
| 288 | version: t.Union[WebhookVersion, str, None] = None, |
| 289 | ) -> webhook_subscription_update_response.WebhookSubscriptionUpdateResponse: |
| 290 | """ |
| 291 | Update an existing webhook subscription. Omitted fields are preserved. |
| 292 | |
| 293 | :param id: The subscription id. |
| 294 | :param webhook_url: New delivery URL. |
| 295 | :param enabled_events: New list of subscribed event types. |
| 296 | :param version: New webhook payload version. |
| 297 | :return: The updated subscription. |
| 298 | |
| 299 | Example: |
| 300 | composio.webhooks.subscriptions.update( |
| 301 | "sub_123", |
| 302 | enabled_events=["composio.trigger.message"], |
| 303 | ) |
| 304 | """ |
| 305 | version_value = None if version is None else _webhook_version(version) |
| 306 | return self._client.webhook_subscriptions.update( |
| 307 | id, |
| 308 | webhook_url=none_to_omit(webhook_url), |
| 309 | enabled_events=none_to_omit( |
| 310 | list(enabled_events) if enabled_events is not None else None |
| 311 | ), |
| 312 | version=none_to_omit(version_value), |
| 313 | ) |
| 314 | |
| 315 | def delete( |
| 316 | self, id: str |
| 317 | ) -> webhook_subscription_delete_response.WebhookSubscriptionDeleteResponse: |
| 318 | """ |
| 319 | Delete a webhook subscription. |
| 320 | |
| 321 | :param id: The subscription id. |
| 322 | :return: The deletion response. |
| 323 | |
| 324 | Example: |
| 325 | composio.webhooks.subscriptions.delete("sub_123") |
| 326 | """ |
| 327 | return self._client.webhook_subscriptions.delete(id) |
| 328 | |
| 329 | def rotate_secret( |
| 330 | self, id: str |
| 331 | ) -> webhook_subscription_rotate_secret_response.WebhookSubscriptionRotateSecretResponse: |
| 332 | """ |
| 333 | Rotate the signing secret of a webhook subscription. |
| 334 | |
| 335 | :param id: The subscription id. |
| 336 | :return: The subscription with its new signing secret. |
| 337 | |
| 338 | Example: |
| 339 | rotated = composio.webhooks.subscriptions.rotate_secret("sub_123") |
| 340 | new_secret = rotated.secret |
| 341 | """ |
| 342 | return self._client.webhook_subscriptions.rotate_secret(id) |
| 343 | |
| 344 | def list_event_types( |
| 345 | self, |
| 346 | ) -> webhook_subscription_list_event_types_response.WebhookSubscriptionListEventTypesResponse: |
| 347 | """ |
| 348 | List the event types a subscription can be enabled for. |
| 349 | |
| 350 | :return: The available event types. |
| 351 | |
| 352 | Example: |
| 353 | event_types = composio.webhooks.subscriptions.list_event_types() |
| 354 | """ |
| 355 | return self._client.webhook_subscriptions.list_event_types() |
| 356 | |
| 357 | |
| 358 | class WebhookEndpoints(Resource): |
| 359 | """Manage inbound webhook endpoints (per toolkit + OAuth app ingress URLs).""" |
| 360 | |
| 361 | def list( |
| 362 | self, |
| 363 | *, |
| 364 | toolkit_slug: t.Optional[str] = None, |
| 365 | ) -> webhook_endpoint_list_response.WebhookEndpointListResponse: |
| 366 | """ |
| 367 | List webhook endpoints, optionally filtered by toolkit. |
| 368 | |
| 369 | :param toolkit_slug: Only return endpoints for this toolkit. |
| 370 | :return: The list of endpoints. |
| 371 | |
| 372 | Example: |
| 373 | endpoints = composio.webhooks.endpoints.list(toolkit_slug="github") |
| 374 | """ |
| 375 | return self._client.webhook_endpoints.list( |
| 376 | toolkit_slug=none_to_omit(toolkit_slug), |
| 377 | ) |
| 378 | |
| 379 | def get( |
| 380 | self, nano_id: str |
| 381 | ) -> webhook_endpoint_retrieve_response.WebhookEndpointRetrieveResponse: |
| 382 | """ |
| 383 | Retrieve a webhook endpoint by id. |
| 384 | |
| 385 | :param nano_id: The endpoint id. |
| 386 | :return: The endpoint. |
| 387 | |
| 388 | Example: |
| 389 | endpoint = composio.webhooks.endpoints.get("we_123") |
| 390 | """ |
| 391 | return self._client.webhook_endpoints.retrieve(nano_id) |
| 392 | |
| 393 | def create( |
| 394 | self, |
| 395 | *, |
| 396 | toolkit_slug: str, |
| 397 | client_id: str, |
| 398 | ) -> webhook_endpoint_create_response.WebhookEndpointCreateResponse: |
| 399 | """ |
| 400 | Create a webhook endpoint for a toolkit and OAuth app. |
| 401 | |
| 402 | :param toolkit_slug: The toolkit the endpoint receives events for. |
| 403 | :param client_id: The OAuth app client id the endpoint is bound to. |
| 404 | :return: The created endpoint, including its ingress ``webhook_url``. |
| 405 | |
| 406 | Example: |
| 407 | endpoint = composio.webhooks.endpoints.create( |
| 408 | toolkit_slug="github", |
| 409 | client_id="Iv1.abc123", |
| 410 | ) |
| 411 | """ |
| 412 | return self._client.webhook_endpoints.create( |
| 413 | toolkit_slug=toolkit_slug, |
| 414 | client_id=client_id, |
| 415 | ) |
| 416 | |
| 417 | def replace( |
| 418 | self, |
| 419 | nano_id: str, |
| 420 | *, |
| 421 | data: t.Dict[str, t.Any], |
| 422 | ) -> webhook_endpoint_replace_response.WebhookEndpointReplaceResponse: |
| 423 | """ |
| 424 | Replace the stored data of a webhook endpoint (full replacement). |
| 425 | |
| 426 | :param nano_id: The endpoint id. |
| 427 | :param data: The complete new endpoint data. |
| 428 | :return: The updated endpoint. |
| 429 | |
| 430 | Example: |
| 431 | composio.webhooks.endpoints.replace( |
| 432 | "we_123", |
| 433 | data={"secret": "new-signing-secret"}, |
| 434 | ) |
| 435 | """ |
| 436 | return self._client.webhook_endpoints.replace(nano_id, data=data) |
| 437 | |
| 438 | def update( |
| 439 | self, |
| 440 | nano_id: str, |
| 441 | *, |
| 442 | data: t.Dict[str, t.Any], |
| 443 | ) -> webhook_endpoint_update_response.WebhookEndpointUpdateResponse: |
| 444 | """ |
| 445 | Merge new data into a webhook endpoint (partial update). |
| 446 | |
| 447 | :param nano_id: The endpoint id. |
| 448 | :param data: The fields to merge into the endpoint data. |
| 449 | :return: The updated endpoint. |
| 450 | |
| 451 | Example: |
| 452 | composio.webhooks.endpoints.update( |
| 453 | "we_123", |
| 454 | data={"secret": "new-signing-secret"}, |
| 455 | ) |
| 456 | """ |
| 457 | return self._client.webhook_endpoints.update(nano_id, data=data) |
| 458 | |
| 459 | |
| 460 | class Webhooks(Resource): |
| 461 | """Webhooks namespace, exposed as ``composio.webhooks``.""" |
| 462 | |
| 463 | subscriptions: WebhookSubscriptions |
| 464 | """Project webhook subscription used for event delivery.""" |
| 465 | |
| 466 | endpoints: WebhookEndpoints |
| 467 | """Inbound webhook endpoints (per toolkit + OAuth app).""" |
| 468 | |
| 469 | def __init__(self, client: HttpClient): |
| 470 | super().__init__(client) |
| 471 | self.subscriptions = WebhookSubscriptions(client) |
| 472 | self.endpoints = WebhookEndpoints(client) |