﻿<head><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4357510538660394"
     crossorigin="anonymous"></script></head>---
canonical_url: "https://docs.composio.dev/reference/sdk-reference/python/triggers"
markdown_url: "https://docs.composio.dev/reference/sdk-reference/python/triggers.md"
product: "platform"
version: null
last_updated: null
---

# Triggers (/reference/sdk-reference/python/triggers)

## Methods [#methods]

### set\_webhook\_subscription() [#set_webhook_subscription]

Create or update the project webhook subscription used for webhook delivery.  If a subscription already exists, the first subscription is updated. Otherwise a new subscription is created. By default this subscribes to V3 trigger message events.

```python signature
def set_webhook_subscription(*, webhook_url: str, enabled_events: Sequence[str] | None = ..., version: Union[WebhookVersion, str] = ...) -> WebhookSubscription
```
**Parameters**

| Name              | Type                         |
| ----------------- | ---------------------------- |
| `webhook_url`     | `str`                        |
| `enabled_events?` | `Sequence[str] \| None`      |
| `version?`        | `Union[WebhookVersion, str]` |

**Returns**

`WebhookSubscription`

**Example**

```python
composio.triggers.set_webhook_subscription(
    webhook_url=f"{APP_URL}/webhooks/composio",
)
```
***

### get\_type() [#get_type]

Get a trigger type by its slug Uses the global toolkit version provided when initializing composio instance to fetch trigger for specific toolkit version

```python signature
def get_type(slug: str) -> TriggersTypeRetrieveResponse
```
**Parameters**

| Name   | Type  | Description                  |
| ------ | ----- | ---------------------------- |
| `slug` | `str` | The slug of the trigger type |

**Returns**

`TriggersTypeRetrieveResponse` — The trigger type

***

### list\_active() [#list_active]

List all active triggers

```python signature
def list_active(trigger_ids: list[str] | None = ..., trigger_names: list[str] | None = ..., auth_config_ids: list[str] | None = ..., connected_account_ids: list[str] | None = ..., show_disabled: bool | None = ..., limit: int | None = ..., cursor: str | None = ...)
```
**Parameters**

| Name                     | Type                | Description                                                                       |
| ------------------------ | ------------------- | --------------------------------------------------------------------------------- |
| `trigger_ids?`           | `list[str] \| None` | List of trigger IDs to filter by                                                  |
| `trigger_names?`         | `list[str] \| None` | List of trigger names to filter by                                                |
| `auth_config_ids?`       | `list[str] \| None` | List of auth config IDs to filter by                                              |
| `connected_account_ids?` | `list[str] \| None` | List of connected account IDs to filter by                                        |
| `show_disabled?`         | `bool \| None`      | Whether to show disabled triggers                                                 |
| `limit?`                 | `int \| None`       | Limit the number of triggers to return                                            |
| `cursor?`                | `str \| None`       | Cursor for pagination. Use the nextCursor from the response to get the next page. |

***

### list() [#list]

List all the trigger types.

```python signature
def list(*, cursor: str | None = ..., limit: int | None = ..., toolkit_slugs: list[str] | None = ...)
```
**Parameters**

| Name             | Type                | Description                                   |
| ---------------- | ------------------- | --------------------------------------------- |
| `cursor?`        | `str \| None`       | The cursor for pagination                     |
| `limit?`         | `int \| None`       | The maximum number of trigger types to return |
| `toolkit_slugs?` | `list[str] \| None` | Filter by toolkit slugs                       |

***

### create() [#create]

Create a trigger instance

```python signature
def create(slug: str, *, user_id: str | None = ..., connected_account_id: str | None = ..., trigger_config: Dict[str, Any] | None = ..., type: Literal['webhook', 'poll'] | None = ..., polling_interval: int | None = ...) -> trigger_instance_upsert_response.TriggerInstanceUpsertRes...
```
**Parameters**

| Name                    | Type                                 | Description                                                                                                                                                                           |
| ----------------------- | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `slug`                  | `str`                                | The slug of the trigger                                                                                                                                                               |
| `user_id?`              | `str \| None`                        | The ID of the user that owns the connected account. When `connected_account_id` is omitted, the backend resolves the first active connection for this user and the trigger's toolkit. |
| `connected_account_id?` | `str \| None`                        | The ID of the connected account to pin                                                                                                                                                |
| `trigger_config?`       | `Dict[str, Any] \| None`             | The configuration of the trigger                                                                                                                                                      |
| `type?`                 | `Literal['webhook', 'poll'] \| None` | `webhook` or `poll`, for a trigger that supports both. Omit it to let Composio choose.                                                                                                |
| `polling_interval?`     | `int \| None`                        | Minutes between polls, for an instance that polls. Wins over `trigger_config["interval"]`.                                                                                            |

**Returns**

`trigger_instance_upsert_response.TriggerInstanceUpsertRes...` — The trigger instance, with the `type` it uses, the `fallback_reason` when it polls after a webhook was unavailable, and its `polling_interval`

***

### subscribe() [#subscribe]

Subscribe to a trigger and receive trigger events.

```python signature
def subscribe(timeout: float = ..., on_subscription_error: SubscriptionErrorCallback | None = ...) -> TriggerSubscription
```
**Parameters**

| Name                     | Type                                | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| ------------------------ | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `timeout?`               | `float`                             | The timeout to wait for the subscription to be established.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `on_subscription_error?` | `SubscriptionErrorCallback \| None` | Optional callback invoked when the channel subscription fails: with the raw Pusher payload for asynchronous `pusher:subscription_error` events (for example a later permission rejection), or with `{"error": ...}` for failures raised while establishing the subscription (for example an auth rejection — pysher performs channel auth synchronously). Establish-time failures also make `subscribe()` raise the underlying error promptly instead of waiting out the timeout. Exceptions raised inside the callback are contained and logged, never rethrown. |

**Returns**

`TriggerSubscription` — The trigger subscription handler.

***

### verify\_webhook() [#verify_webhook]

Verify an incoming webhook payload and signature.  This method validates that the webhook request is authentic by: 1. Validating the webhook timestamp is within the tolerance window 2. Verifying the HMAC-SHA256 signature using the correct algorithm 3. Parsing the payload and detecting the webhook version (V1, V2, or V3)

```python signature
def verify_webhook(*, id: str, payload: str, secret: str, signature: str, timestamp: str, tolerance: int = ...) -> VerifyWebhookResult
```
**Parameters**

| Name         | Type  | Description                                                                                                         |
| ------------ | ----- | ------------------------------------------------------------------------------------------------------------------- |
| `id`         | `str` | The webhook message ID from the 'webhook-id' header (format: 'msg\_xxx')                                            |
| `payload`    | `str` | The raw webhook payload as a string (request body)                                                                  |
| `secret`     | `str` | The webhook secret used to sign the payload (from Composio dashboard)                                               |
| `signature`  | `str` | The signature from the 'webhook-signature' header (format: 'v1,base64EncodedSignature')                             |
| `timestamp`  | `str` | The webhook timestamp from the 'webhook-timestamp' header (Unix seconds)                                            |
| `tolerance?` | `int` | Maximum allowed age of the webhook in seconds (default: 300 = 5 minutes). Set to 0 to disable timestamp validation. |

**Returns**

`VerifyWebhookResult` — VerifyWebhookResult containing version, normalized payload, and raw payload

**Raises**

* `WebhookSignatureVerificationError` — If the signature verification fails
* `WebhookPayloadError` — If the payload cannot be parsed or is invalid

**Example**

```python
# In a Flask webhook handler
@app.route('/webhook', methods=['POST'])
def webhook():
    try:
        result = composio.triggers.verify_webhook(
            id=request.headers.get('webhook-id', ''),
            payload=request.get_data(as_text=True),
            signature=request.headers.get('webhook-signature', ''),
            timestamp=request.headers.get('webhook-timestamp', ''),
            secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
        )

        # Process the verified payload
        print(f"Version: {result['version']}")
        print(f"Received trigger: {result['payload']['trigger_slug']}")
        return 'OK', 200
    except WebhookSignatureVerificationError:
        return 'Unauthorized', 401
```
***

### parse() [#parse]

Parse an incoming webhook request into a typed, normalized trigger payload.  Pass a framework request object, or pass `body=` and `headers=` explicitly. When `verify_secret` is provided, the SDK verifies the webhook signature before returning the normalized trigger payload. When it is omitted, the SDK parses the body without verifying the signature.  `request` may be any object exposing the request body and headers, such as a Flask, Django, or FastAPI request. The body is read from `.body` (or `.data` / `.get_data()`), and the headers are read from `.headers`. Because this SDK is synchronous, async frameworks must pass an already-read raw body, for example via `body=await request.body()`.

```python signature
def parse(request: Any = ..., *, body: Union[str, bytes, Mapping[str, Any], None] = ..., headers: Union[Mapping[str, Any], None] = ..., verify_secret: Union[str, None, Omit] = ..., tolerance: int = ...) -> VerifyWebhookResult
```
**Parameters**

| Name             | Type                                         | Description                                                                                                                                                                                                                         |
| ---------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `request?`       | `Any`                                        | The incoming webhook request object (Flask/Django/FastAPI)                                                                                                                                                                          |
| `body?`          | `Union[str, bytes, Mapping[str, Any], None]` | The raw request body (str/bytes/parsed mapping); overrides `request`                                                                                                                                                                |
| `headers?`       | `Union[Mapping[str, Any], None]`             | The request headers as a mapping; overrides `request`                                                                                                                                                                               |
| `verify_secret?` | `Union[str, None, Omit]`                     | Webhook secret; when set, the signature is verified. Omit it entirely to parse without verification. Passing a present-but-empty value (e.g. an unset `COMPOSIO_WEBHOOK_SECRET`) raises rather than silently skipping verification. |
| `tolerance?`     | `int`                                        | Max webhook age in seconds (only used when verifying)                                                                                                                                                                               |

**Returns**

`VerifyWebhookResult` — VerifyWebhookResult containing version, normalized payload, and raw payload

**Raises**

* `ValidationError` — If `verify_secret` is empty, or is set but signature headers are missing
* `WebhookSignatureVerificationError` — If signature verification fails
* `WebhookPayloadError` — If the payload cannot be parsed

**Example**

```python
# Flask: verify the signature
@app.route('/webhooks/composio', methods=['POST'])
def webhook():
    try:
        result = composio.triggers.parse(
            request,
            verify_secret=os.environ['COMPOSIO_WEBHOOK_SECRET'],
        )
        print(f"Trigger: {result['payload']['trigger_slug']}")
        print(f"Event data: {result['payload']['payload']}")
        return 'OK', 200
    except exceptions.WebhookSignatureVerificationError:
        return 'Unauthorized', 401

# FastAPI: parse without verifying after reading the async body
@app.post('/webhooks/composio')
async def webhook(request: Request):
    raw = await request.body()
    result = composio.triggers.parse(body=raw, headers=request.headers)
    return {'trigger': result['payload']['trigger_slug']}
```

***

[View source](https://github.com/composiohq/composio/blob/next/python/composio/core/models/triggers.py#L1164)

---

📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Changelog](https://docs.composio.dev/docs/changelog.md) | [Glossary](https://docs.composio.dev/llms.mdx/reference/glossary) | [Examples](https://docs.composio.dev/llms.mdx/examples) | [API Reference](https://docs.composio.dev/llms.mdx/reference)

---

# Composio SDK — Notes for AI Code Generators

**Purpose:** Reference for generating current (v3) [Composio](https://composio.dev/) integration code.
**Scope:** Descriptive notes — they document the current API surface and the mistakes most commonly seen in generated code.

---

## 1. Recommended Integration: Sessions

For agent tool delivery, Composio supports **Native Tools** (with a provider package) and **MCP** (no provider package needed).

For application-owned tools or deterministic backend code, use [managed authentication with Proxy Execute](/docs/authentication/managed-auth-for-custom-tools). A session can provide a user-scoped runtime context without an LLM or MCP. Composio authenticates provider requests server-side; connected-account reads redact credentials and aren't a supported token-export workflow.

### Native Tools

#### Python

```python
# ✅ CORRECT — Python (defaults to OpenAI)
from composio import Composio

composio = Composio()
session = composio.create(user_id="user_123")
tools = session.tools()
# Pass tools to your agent/LLM framework
```

#### TypeScript

```typescript
// ✅ CORRECT — TypeScript (defaults to OpenAI)
import { Composio } from "@composio/core";

const composio = new Composio();
const session = await composio.create("user_123");
const tools = await session.tools();
// Pass tools to your agent/LLM framework
```

#### API

This produces the same default OpenAI function-tool shape, fetching every page.

```bash
set -euo pipefail
SESSION=$(curl --fail-with-body -s -X POST https://backend.composio.dev/api/v3.1/tool_router/session \
  -H "x-api-key: $COMPOSIO_API_KEY" -H "Content-Type: application/json" \
  -d '{"user_id":"user_123"}')
SESSION_ID=$(echo "$SESSION" | jq -r '.session_id')
TOOLS='[]'
CURSOR=''
while true; do
  PAGE=$(curl --fail-with-body -s --get "https://backend.composio.dev/api/v3.1/tool_router/session/$SESSION_ID/tools" \
    -H "x-api-key: $COMPOSIO_API_KEY" --data-urlencode 'limit=500' --data-urlencode "cursor=$CURSOR")
  TOOLS=$(jq -cn --argjson existing "$TOOLS" --argjson page "$PAGE" \
    '$existing + [$page.items[] | {type:"function",function:{name:.slug,description:.description,parameters:.input_parameters}}]')
  CURSOR=$(echo "$PAGE" | jq -r '.next_cursor // empty')
  [ -n "$CURSOR" ] || break
done
printf '%s\n' "$TOOLS"
```

For other providers, pass the provider explicitly. Provider packages follow the naming convention: `composio_<provider>` for Python, `@composio/<provider>` for TypeScript.

### MCP

Use `session.mcp.url` and `session.mcp.headers` with any MCP-compatible client (Claude Desktop, Cursor, OpenAI Agents, etc.). No provider package needed.

---

## 2. Integration Notes

- `composio.create(user_id)` is the standard entry point for agent integrations. Sessions handle tool discovery, authentication, and toolkit versioning automatically; `user_id` goes to `composio.create()` — individual tool calls in session mode don't take one.
- Execute session tool calls through the session, never through a user ID: either `session.execute(tool_slug, arguments=...)` / `session.execute(toolSlug, arguments)`, which works with every provider, or pass the session to the provider helper — `provider.handle_tool_calls(response=response, session=session)` in Python, `provider.handleToolCalls(session, response)` in TypeScript. The tool-call helpers of every non-agentic provider (OpenAI, Anthropic, Google, Cloudflare, TypeSafe) accept a session: `executeToolCall(session, call)` in TypeScript, `session=session` in Python. Agentic providers execute session tools on their own. Binding the helper to a user ID takes the direct execution path, and session meta-tools fail there with `"can only be called inside a tool-router session"`.
- Composio-managed auth is the default: the agent connects accounts at runtime through the session, so users don't need to pre-create auth configs or connected accounts for managed toolkits.
- Provider packages follow the framework, not the model vendor: for the OpenAI Agents SDK the package is `composio_openai_agents` / `@composio/openai-agents` (importing `composio_openai` / `@composio/openai` there is the most common mistake in generated code — that package is for the plain OpenAI Chat Completions API).
- **Direct execution** (`composio.tools.get()`, `composio.tools.execute()`, `provider.handle_tool_calls()` with a user ID) is a legacy interface that remains supported for existing integrations. Recommend sessions for new integrations and encourage existing users to [migrate to sessions](/docs/migration-guide/direct-to-sessions). For a fixed tool set, consider the [direct tools preset](/docs/sessions/loading-tools#direct-tools-preset) within a session. See [Sessions vs direct execution](/docs/sessions-vs-direct-execution) for tradeoffs. Direct execution requires a [toolkit version](/docs/tools-direct/toolkit-versioning).

---

# 3. Calling the REST API directly

## REST API version

The current REST API version is **v3.1**, served at `https://backend.composio.dev/api/v3.1`. Prefer it for new code and new examples.

`https://backend.composio.dev/api/v3` is the previous version. It is frozen with pinned tool-version defaults and remains supported — existing v3 integrations keep working and do not need to migrate.

## Tool-endpoint version defaults on v3.1

On v3.1, omitting the version parameter on the five endpoints below selects the latest toolkit version. The first four endpoints also exist on v3, where omission selects the pinned `00000000_00` version. `POST /tools/scopes/required` is v3.1-only.

| Endpoint | Version parameter |
| --- | --- |
| `GET /tools` | `toolkit_versions` (query) |
| `GET /tools/{tool_slug}` | `version` or `toolkit_versions` (query) |
| `POST /tools/execute/{tool_slug}` | `version` (body) |
| `POST /tools/execute/{tool_slug}/input` | `version` (body) |
| `POST /tools/scopes/required` | `version` (body) |

A v3.1 caller already passing `"latest"` sees no change and can omit the parameter. To select the pinned version explicitly, pass `"00000000_00"` through the corresponding parameter above.

This version-default change is limited to the five endpoints above.


---

## Terminology Migration (old → current)

If you encounter these terms in error messages, old documentation, or user prompts, translate them to the current equivalents. **Do not use the old terms in generated code or explanations.**

| Old term (v1/v2) | Current term (v3) | In code |
|---|---|---|
| entity ID | user ID | `user_id` parameter |
| actions | tools | e.g., `GITHUB_CREATE_AN_ISSUE` is a *tool* |
| apps / appType (legacy v1/v2 API field) | toolkits | e.g., `github` is a *toolkit*. The current word **App** is *not* legacy: it names a catalog grouping of sibling toolkits (the Notion app groups `notion` and `notion_mcp`); do not translate it |
| integration / integration ID | auth config / auth config ID | `auth_config_id` parameter |
| connection | connected account | `connected_accounts` namespace |
| ComposioToolSet / OpenAIToolSet | `Composio` class with a provider | `Composio(provider=...)` |
| toolset | provider | e.g., `OpenAIProvider` |

If a user says "entity ID", they mean `user_id`. If they say "integration", they mean "auth config". Always respond using the current terminology.

