Convex
@composio/convex is a Convex component. 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
Install
npm install @composio/convex @convex-dev/agent ai @ai-sdk/openaiai is only needed for agent tools. Any AI SDK model provider works; this guide uses OpenAI.
Configure credentials
Set your API key from Settings on your deployment:
npx convex env set COMPOSIO_API_KEY <your-api-key>
npx convex env set OPENAI_API_KEY <your-openai-api-key>Mount the components
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.
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.
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
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.
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
Register https://<deployment>.convex.site/composio/webhook as your project's webhook URL, then store its signing secret:
npx convex env set COMPOSIO_WEBHOOK_SECRET <your-webhook-secret>Mount the route:
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
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
Convex example app
A runnable Convex app with an agent, connect flow, webhooks, and cron jobs.
What is a session?
How sessions scope users, tools, and auth.