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

# Convex (/docs/providers/convex)
> Documentation index: https://docs.composio.dev/llms.txt. Fetch it to find every page.

{/* code-example: single-language-page reason="Convex components and @composio/convex are TypeScript-only" */}

{/* TODO: remove the `@errors` twoslash markers below once docs/package.json installs @composio/convex, convex, and @convex-dev/agent. The 7006 and 7031 errors follow from the unresolved imports. */}

`@composio/convex` is a [Convex component](https://docs.convex.dev/components). It runs in Convex's default runtime and keeps its state in its own tables:

* Tool Router sessions, one per user and session config.
* Connected accounts and their status.
* Verified trigger webhook events, recorded once per delivery.

Your Composio API key stays in your deployment's environment. The component never stores it.

## Usage [#usage]

**Install**

```bash
npm install @composio/convex @convex-dev/agent ai @ai-sdk/openai
```

`ai` is only needed for agent tools. Any AI SDK model provider works; this guide uses OpenAI.

**Configure credentials**

Set your API key from [Settings](https://dashboard.composio.dev/~/project/settings/api-keys?utm_source=docs\&utm_medium=content\&utm_campaign=docs-providers-convex) on your deployment:

```bash
npx convex env set COMPOSIO_API_KEY <your-api-key>
npx convex env set OPENAI_API_KEY <your-openai-api-key>
```

**Mount the components**

```typescript title="convex/convex.config.ts"
// @errors: 2307
import composio from '@composio/convex/convex.config';
import agent from '@convex-dev/agent/convex.config';
import { defineApp } from 'convex/server';

const app = defineApp();
app.use(agent);
app.use(composio);

export default app;
```
**Create the client**

`identify` maps the signed-in user to a Composio user id. `composio.api()` returns functions the browser can call. Each one derives the user with `identify` and never accepts a user id from the caller.

Set `allowedCallbackOrigins` to your frontend origin to let the browser supply the custom callback URL used below.

```typescript title="convex/composio.ts"
// @errors: 2307 7006
import { Composio } from '@composio/convex';
import { components } from './_generated/api';

export const composio = new Composio(components.composio, {
  allowedCallbackOrigins: ['https://your.app'],
  identify: async ctx => {
    const identity = await ctx.auth.getUserIdentity();
    return identity ? { userId: identity.subject } : null;
  },
});

export const {
  createConnectLink,
  syncConnection,
  syncUserConnections,
  listConnections,
  disconnectAccount,
  listTriggerEvents,
} = composio.api();
```
**Give the agent Composio tools**

`getTools` builds AI SDK tools for the user's Tool Router session. They search for the right tool, run it, and return a connect link when an app isn't connected yet.

```typescript title="convex/agent.ts"
// @errors: 2307 7006 7031
import { openai } from '@ai-sdk/openai';
import { Agent } from '@convex-dev/agent';
import { jsonSchema, stepCountIs } from 'ai';
import { v } from 'convex/values';
import { components } from './_generated/api';
import { action } from './_generated/server';
import { composio } from './composio';

const agent = new Agent(components.agent, {
  name: 'Assistant',
  languageModel: openai('gpt-5'),
});

export const chat = action({
  args: { threadId: v.string(), prompt: v.string() },
  handler: async (ctx, { threadId, prompt }) => {
    const identity = await ctx.auth.getUserIdentity();
    if (!identity) throw new Error('Not authenticated');
    const userId = identity.subject;

    const metadata = await agent.getThreadMetadata(ctx, { threadId });
    if (metadata.userId !== userId) throw new Error('Thread not found');

    const composioTools = await composio.getTools(ctx, { userId, jsonSchema });
    const { thread } = await agent.continueThread(ctx, { threadId, userId });
    const result = await thread.generateText({
      prompt,
      tools: composioTools,
      stopWhen: stepCountIs(8),
    });
    return result.text;
  },
});
```
To keep your own tools, spread both sets: `tools: { ...myTools, ...composioTools }`. Pass `config` to `getTools` to scope the session, for example `{ toolkits: ['gmail', 'github'] }`.

> Don't call `waitForConnections` or turn on `manageConnections.waitForConnections` inside a Convex
action. A user finishing OAuth can take longer than an action's time limit. Let the agent send the
connect link, end the turn, and continue on the user's next message.

## Connect accounts from your app [#connect-accounts-from-your-app]

`createConnectLink` starts OAuth and returns the saved account status. Use a `callbackUrl` on an origin listed in `allowedCallbackOrigins`, or omit it to use Composio's default redirect. Send the user to `redirectUrl`.

```typescript
// @errors: 2307
import { useAction } from 'convex/react';
import { api } from '../convex/_generated/api';

export function useConnectGmail() {
  const createConnectLink = useAction(api.composio.createConnectLink);
  const syncConnection = useAction(api.composio.syncConnection);

  const connect = async () => {
    const { redirectUrl } = await createConnectLink({
      target: { kind: 'toolkit', toolkit: 'gmail' },
      callbackUrl: 'https://your.app/connected',
    });
    window.location.href = redirectUrl;
  };

  // Call on your callback page with the `connected_account_id` query parameter.
  const confirm = (connectedAccountId: string) => syncConnection({ connectedAccountId });

  return { connect, confirm };
}
```
The callback's query parameters aren't signed. `syncConnection` reads the account's status from the Composio API and rejects accounts that belong to another user. `listConnections` is a reactive query over the stored connections.

## Receive trigger webhooks [#receive-trigger-webhooks]

Register `https://<deployment>.convex.site/composio/webhook` as your project's [webhook URL](/docs/setting-up-triggers/subscribing-to-events#receive-events-in-production), then store its signing secret:

```bash
npx convex env set COMPOSIO_WEBHOOK_SECRET <your-webhook-secret>
```
Mount the route:

```typescript title="convex/http.ts"
// @errors: 2307 7006
import { httpRouter } from 'convex/server';
import { composio } from './composio';

const http = httpRouter();

composio.registerRoutes(http, {
  path: '/composio/webhook',
  events: {
    'composio.trigger.message': async (ctx, event) => {
      console.log('Trigger event', event.metadata.trigger_slug);
    },
  },
});

export default http;
```

The route verifies the `webhook-signature` header and rejects timestamps older than five minutes. It records each `webhook-id` once, so a redelivery doesn't run your handlers again. `composio.connected_account.activated` and `composio.connected_account.expired` events also update the stored connections.

If a handler throws, the event stays recorded and its claim is released before returning `500`, so a retry runs the handler again without repeating the connection update. If the HTTP action terminates unexpectedly, its claim lease expires after 60 seconds so Composio retries can run the handler again. Keep handlers short and idempotent, and hand longer work to `ctx.scheduler`.

## Housekeeping [#housekeeping]

Schedule `composio.expireStaleConnections(ctx)` to mark abandoned connect flows `EXPIRED`, and `composio.pruneTriggerEvents(ctx)` to delete old webhook events. Call each from an internal mutation that a cron job runs. The example app runs them every 10 minutes and daily.

## Next [#next]

- [Convex example app](https://github.com/ComposioHQ/composio/tree/next/ts/examples/convex): A runnable Convex app with an agent, connect flow, webhooks, and cron jobs.

- [What is a session?](/docs/sessions): How sessions scope users, tools, and auth.

---

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

