---
canonical_url: "https://docs.composio.dev/docs/hooks/webhooks"
markdown_url: "https://docs.composio.dev/docs/hooks/webhooks.md"
product: "platform"
version: null
last_updated: null
---

# Webhooks (/docs/hooks/webhooks)

A webhook sends each tool call to an endpoint you host, before or after the tool runs. You respond to allow the tool call, block it, or modify it.

> Webhooks are available only on the Enterprise plan.

Here are a few examples of what you can do with webhooks:

* **Screen for sensitive data:** Scan tool calls for PII with your own detection service, and block the ones that contain it.
* **Enforce access policies:** Check each tool call against your own permission or approval system.
* **Redact tool results:** Strip secrets from a tool's result before your agent reads it.

## Set up a webhook URL [#set-up-a-webhook-url]

You can configure the webhook URL from the dashboard, under [Project Settings → General](https://dashboard.composio.dev/~/project/settings/general?utm_source=docs\&utm_medium=content\&utm_campaign=session-hooks). In the Configuration section, find **Tool execution webhook** and click **Configure**. This is a project-level setting, so every session in the project that has a webhook uses the same URL. Only organization admins can set or change the URL. Users with the "Developer" or "Viewer" role can only view it.

When you save the URL, the dashboard displays a signing secret. Every request is signed with this secret, so you can verify that a request came from Composio before acting on it. If the secret is ever exposed, rotate it from the same page. The previous secret stops working immediately.

The dashboard shows the secret only once, either when you first save the URL or when you rotate the secret, so copy it and save it in your project's environment. If you change the URL later, the secret stays the same.

## Add a webhook to a session [#add-a-webhook-to-a-session]

Once you've configured the URL, you can add webhooks to your sessions. Add a [hook](/docs/hooks) and set its handler `type` to `webhook`:

**Python:**
```python
session = composio.create(
    user_id="user_123",
    hooks=[
        {
            "id": "check_gmail_calls",
            "type": "before_execute",
            "applies_to": {"toolkits": ["gmail"]},
            "handler": {
                "type": "webhook",
                "fallback_action": "block",
                "timeout_ms": 1000,
            },
        },
    ],
)
```

**TypeScript:**
```typescript
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: 'your_api_key' });
const session = await composio.create('user_123', {
  hooks: [
    {
      id: 'check_gmail_calls',
      type: 'before_execute',
      appliesTo: { toolkits: ['gmail'] },
      handler: {
        type: 'webhook',
        fallbackAction: 'block',
        timeoutMs: 1000,
      },
    },
  ],
});
```

**API:**
{/* code-example: unchecked-api rule="api-body-schema" operation="POST /api/v3.1/tool_router/session" reason="the committed OpenAPI spec doesn't list the webhook hook handler until it ships" */}

```bash
curl -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",
    "hooks": [
      {
        "id": "check_gmail_calls",
        "type": "before_execute",
        "applies_to": {"toolkits": ["gmail"]},
        "handler": {
          "type": "webhook",
          "fallback_action": "block",
          "timeout_ms": 1000
        }
      }
    ]
  }'
```

Set `fallback_action` to choose what happens to a tool call if there's no valid response from your endpoint, and `timeout_ms` to choose how long to wait for one. See [Timeouts](#timeouts) and [Fallback](#fallback).

## Request and response payloads [#request-and-response-payloads]

For every tool call a webhook applies to, your endpoint receives a `POST` request. Read the request, decide what should happen to the tool call, and respond.

### Request payload [#request-payload]

This is the request for a tool call, sent before the tool runs:

```json
{
  "id": "msg_3f2a9c1e-5b7d-4e8a-9c21-7d4e5f6a8b90",
  "type": "composio.session_hook.before_execute",
  "timestamp": "2026-11-20T12:00:00.000Z",
  "metadata": {
    "project_id": "pr_123",
    "session_id": "trs_123",
    "user_id": "user_123",
    "hook_id": "check_gmail_calls",
    "tool_call_id": "tc_V1StGXR8_Z5jdHi6"
  },
  "data": {
    "type": "tool_execute",
    "tool_call": {
      "toolkit_slug": "gmail",
      "tool_slug": "GMAIL_SEND_EMAIL",
      "toolkit_version": "20261101_00",
      "connected_account_id": "ca_123",
      "arguments": {
        "recipient_email": "jane@customer.com",
        "subject": "Pricing"
      }
    }
  }
}
```

The contents of `data` depend on the kind of call and on when the webhook runs:

|                                                                                  | `before_execute` | `after_execute`                    |
| -------------------------------------------------------------------------------- | ---------------- | ---------------------------------- |
| Tool call (`"type": "tool_execute"`)                                             | `tool_call`      | `tool_call` and `tool_response`    |
| [Proxy call](/docs/extending-sessions/proxy-execute) (`"type": "proxy_execute"`) | `http_request`   | `http_request` and `http_response` |

For example, this is `data` for a tool call after it has run:

```json
{
  "type": "tool_execute",
  "tool_call": {
    "toolkit_slug": "gmail",
    "tool_slug": "GMAIL_SEND_EMAIL",
    "toolkit_version": "20261101_00",
    "connected_account_id": "ca_123",
    "arguments": {
      "recipient_email": "jane@customer.com",
      "subject": "Pricing"
    }
  },
  "tool_response": {
    "data": { "id": "19a2b3c4d5e6f7a8" },
    "error": null
  }
}
```

And this is `data` for a proxy call after it has run:

```json
{
  "type": "proxy_execute",
  "http_request": {
    "toolkit_slug": "github",
    "connected_account_id": "ca_456",
    "method": "GET",
    "endpoint": "/user/repos",
    "parameters": [{ "name": "per_page", "value": "10", "type": "query" }]
  },
  "http_response": {
    "status": 200,
    "headers": { "content-type": "application/json" },
    "data": [{ "name": "hello-world", "private": false }]
  }
}
```

Use `metadata.tool_call_id` to match the `before_execute` and `after_execute` requests for the same tool call. Both carry the same ID.

### Response payload [#response-payload]

Respond with HTTP `200` and a JSON body. There are three ways to respond:

| Response                                        | What happens                                |
| ----------------------------------------------- | ------------------------------------------- |
| `{ "action": "continue" }`                      | The tool call goes ahead unchanged.         |
| `{ "action": "block", "message": "..." }`       | The tool call is blocked.                   |
| `{ "action": "continue", "override": { ... } }` | The tool call goes ahead with your changes. |

When you block a tool call, your agent sees it fail, with your `message` as the error. Use the message to explain why you blocked the tool call. This works the same way from `before_execute` and `after_execute`. See [Blocked tool calls](/docs/hooks#blocked-tool-calls) for what's returned.

What goes in `override` also depends on the kind of call and on when the webhook runs:

|            | `before_execute`                            | `after_execute`                            |
| ---------- | ------------------------------------------- | ------------------------------------------ |
| Tool call  | `{ "tool_call": { "arguments": { ... } } }` | `{ "tool_response": { "data": { ... } } }` |
| Proxy call | `{ "http_request": { ... } }`               | `{ "http_response": { ... } }`             |

For a tool call, the arguments or data you return replace the originals entirely, so start from them and change only what you need. For a proxy call, include only the fields you want to change. Each field you include replaces the original in full.

For the full schema of the request and of your response, see the reference for [`before_execute`](/reference/api-reference/session-webhooks/composio_session_hook_before_execute) and [`after_execute`](/reference/api-reference/session-webhooks/composio_session_hook_after_execute).

### Example [#example]

Here's an example that receives a request, verifies it, and responds. The example uses FastAPI.

{/* code-example: single-language reason="the endpoint is written with FastAPI, a Python web framework" */}

```python
import os

from composio import Composio
from fastapi import FastAPI, Request

composio = Composio()
app = FastAPI()

@app.post("/composio/session-webhook")
async def session_webhook(request: Request):
    # parse() verifies the request signature against your secret and returns
    # the typed event. It raises an error if verification fails.
    # Pass the raw body: the signature is computed over its exact bytes.
    hook = composio.sessions.webhooks.parse(
        body=await request.body(),
        headers=request.headers,
        verify_secret=os.environ["COMPOSIO_SESSION_WEBHOOK_SECRET"],
    )

    # Decide if the tool call in `hook` should run.
    # To block it: return {"action": "block", "message": "..."}
    # To change it: return {"action": "continue", "override": {...}}
    return {"action": "continue"}
```

## Timeouts [#timeouts]

By default, you have 3 seconds to respond. You can change this by setting `timeout_ms` on the handler to any value between `100` and `5000` milliseconds.

```json
{ "type": "webhook", "fallback_action": "block", "timeout_ms": 1000 }
```

## Fallback [#fallback]

`fallback_action` is a required field. Set it to choose what happens to a tool call when there's no valid response from your endpoint:

* `block`: The tool call is blocked. Use this when a tool call must never go through unchecked.
* `continue`: The tool call goes ahead without your check. Use this when your agent should keep working even if your endpoint is down.

The fallback applies when:

* The request times out, or your endpoint can't be reached.
* You respond with a status other than `200`.
* Your response doesn't match the [expected format](/reference/api-reference/session-webhooks).

Your endpoint receives each request once, with no retries. When the fallback applies, the webhook shows as `unavailable` in the tool call's `hook_results`:

```json
{ "id": "check_gmail_calls", "status": "unavailable", "detail": "The webhook endpoint timed out" }
```

## Limits [#limits]

You can add one `before_execute` webhook and one `after_execute` webhook to a session.

## Order of execution [#order-of-execution]

A webhook can modify a tool call, so it always runs before custom prompt check and prompt injection detection hooks. That way, those hooks evaluate the tool call with your changes. This is the same for `before_execute` and `after_execute`.

---

📚 **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.

