Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

docs: rewrite Hono cookbook to use session paradigm

Sushmitha Malleshf02f9e67b6f5
diff --git a/docs/content/cookbooks/hono.mdx b/docs/content/cookbooks/hono.mdx
index a1891bad8..da3e7b50d 100644
--- a/docs/content/cookbooks/hono.mdx
+++ b/docs/content/cookbooks/hono.mdx
@@ -1,428 +1,218 @@
---
title: Basic Hono Server
-description: Build a simple Gmail agent with Composio and Hono.js
+description: Build an AI agent with access to 1000+ tools using Composio and Hono.js
---
-With Composio's managed authentication and tool calling, it's easy to build
-AI agents that interact with the real world while reducing boilerplate for
-setup and authentication management. This cookbook will guide you through
-building and serving agents using `Composio`, `OpenAI`, and `Hono.js`.
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/hono)
-## Prerequisites
-
-* Node.js 18.x or higher
-* npm or yarn package manager
-* Composio API key
-* OpenAI API key
-* Basic knowledge of OAuth
-* Understanding of building HTTP services (preferably using Hono.js)
+This cookbook builds a Hono.js server where users can chat with an AI agent that has access to over 1000 tools like Gmail, GitHub, Slack, Notion, and more. Along the way we'll add endpoints to manage which apps a user has connected.
-## Building an AI agent that can interact with `gmail` service
+## Prerequisites
-First, let's start with building a simple AI agent embedded with tools from
-Composio that lets the agent interact with the `gmail` service.
+* Node.js 18+
+* [Composio API key](https://platform.composio.dev/settings)
+* [OpenAI API key](https://platform.openai.com/api-keys)
-```typescript
-import { OpenAI } from 'openai';
-import { Composio } from '@composio/core';
-import { OpenAIProvider } from '@composio/openai';
+## Project setup
-export async function runGmailAgent(
- composioClient: Composio<OpenAIProvider>,
- openaiClient: OpenAI,
- userId: string, // Composio uses the User ID to store and access user-level authentication tokens.
- prompt: string,
-): Promise<any[]> {
- // Step 1: Fetch the necessary Gmail tools list with Composio
- const tools = await composioClient.tools.get(
- userId,
- {
- tools: [
- "GMAIL_FETCH_EMAILS",
- "GMAIL_SEND_EMAIL",
- "GMAIL_CREATE_EMAIL_DRAFT"
- ]
- }
- );
-
- // Step 2: Use OpenAI to generate a response based on the prompt and available tools
- const response = await openaiClient.chat.completions.create({
- model: "gpt-4.1",
- tools,
- messages: [{ role: "user", content: prompt }],
- });
+Create a new project and install dependencies:
- // Step 3: Handle tool calls with Composio and return the result
- const result = await composioClient.provider.handleToolCalls(
- userId,
- response
- );
- return result;
-}
+```bash
+mkdir composio-hono && cd composio-hono
+npm init -y
+npm install hono @hono/node-server openai @composio/core @composio/openai tsx
```
-<Callout>
- This is a simple agent without state management and agentic loop implementation,
- so the agent can't perform complicated tasks. If you want to understand how
- composio can be used with agentic loops, check other cookbooks with more
- agentic frameworks.
-</Callout>
-
-To invoke this agent, authenticate your users with Composio's managed authentication service.
+Add your API keys to a `.env` file:
-## Authenticating users
+```bash title=".env"
+COMPOSIO_API_KEY=your_composio_api_key
+OPENAI_API_KEY=your_openai_api_key
+```
-To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
+## Initializing the clients
-To create an authentication config for `gmail` you need `client_id` and `client_secret` from your [Google OAuth Console](https://developers.google.com/identity/protocols/oauth2). Once you have the credentials, use the following piece of code to set up authentication for `gmail`.
+`Composio` takes an `OpenAIProvider` so that when we ask for tools later, they come back in the format OpenAI expects.
```typescript
+import { Hono } from 'hono';
+import { OpenAI } from 'openai';
import { Composio } from '@composio/core';
import { OpenAIProvider } from '@composio/openai';
-export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {
- /**
- * Create a auth config for the gmail toolkit.
- */
- const clientId = process.env.GMAIL_CLIENT_ID;
- const clientSecret = process.env.GMAIL_CLIENT_SECRET;
- if (!clientId || !clientSecret) {
- throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");
- }
+const composio = new Composio({ provider: new OpenAIProvider() });
+const openai = new OpenAI();
- return composioClient.authConfigs.create(
- "GMAIL",
- {
- "name": "default_gmail_auth_config",
- "type": "use_custom_auth",
- "authScheme": "OAUTH2",
- "credentials": {
- "clientId": clientId,
- "clientSecret": clientSecret,
- },
- },
- );
-}
+const app = new Hono();
```
-This will create a Gmail authentication config to authenticate your app's users. Ideally, create one authentication object per project, so check for an existing auth config before creating a new one.
+## Chat endpoint
+
+The core of the server is a `/chat` endpoint. A user sends a message, and the agent responds, using whatever tools it needs.
+
+`composio.create()` creates a **session** scoped to a user. Calling `session.tools()` returns a set of meta tools that let the agent discover tools across all apps, handle OAuth when needed, and execute actions. We pass these to OpenAI and loop until the model stops calling tools.
```typescript
+import { Hono } from 'hono';
+import { OpenAI } from 'openai';
import { Composio } from '@composio/core';
import { OpenAIProvider } from '@composio/openai';
+
+declare const composio: Composio<OpenAIProvider>;
+declare const openai: OpenAI;
+const app = new Hono();
// ---cut---
-export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {
- /**
- * Fetch the auth config for a given user id.
- */
- const authConfigs = await composioClient.authConfigs.list();
- for (const authConfig of authConfigs.items) {
- if (authConfig.toolkit.slug === "gmail") {
- return authConfig;
- }
+app.post("/chat", async (c) => {
+ const { userId, message } = await c.req.json();
+
+ const session = await composio.create(userId);
+ const tools = await session.tools();
+
+ const messages: OpenAI.ChatCompletionMessageParam[] = [
+ { role: "system", content: "You are a helpful assistant. Use tools to help the user." },
+ { role: "user", content: message },
+ ];
+
+ while (true) {
+ const response = await openai.chat.completions.create({
+ model: "gpt-4.1",
+ tools,
+ messages,
+ });
+
+ const choice = response.choices[0];
+ if (!choice.message.tool_calls?.length) {
+ return c.json({ response: choice.message.content });
}
- return null;
-}
+ messages.push(choice.message);
+ const toolResults = await composio.provider.handleToolCalls(userId, response);
+ messages.push(...toolResults);
+ }
+});
```
<Callout>
- Composio platform provides composio managed authentication for some apps to
- fast-track your development, `gmail` being one of them. You can use these
- default auth configs for development, but for production, always use your
- own oauth app configuration.
+If the user hasn't connected the app they're trying to use, the agent will automatically
+return an authentication link in its response. The user can complete OAuth and then retry.
</Callout>
-Once you have authentication management in place, we can start with connecting your users to your `gmail` app. Let's implement a function to connect users to your `gmail` app via composio.
+That's a working agent. But in most apps you'll also want to manage connections outside of chat, for example to show users what's connected or let them connect new apps from a settings page.
+
+## Checking connections
+
+`session.toolkits()` returns every toolkit in the session along with its connection status. We can expose this as a simple GET endpoint so your frontend can render a connections UI.
```typescript
import { Hono } from 'hono';
import { Composio } from '@composio/core';
import { OpenAIProvider } from '@composio/openai';
-declare function fetchAuthConfig(client: Composio<OpenAIProvider>): Promise<{ id: string } | null>;
-declare function createAuthConfig(client: Composio<OpenAIProvider>): Promise<{ id: string }>;
-declare const composioClient: Composio<OpenAIProvider>;
-// ---cut---
-// Function to initiate a connected account
-export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {
- /**
- * Create a connection for a given user id and auth config id.
- */
- // Fetch or create the auth config for the gmail toolkit
- let authConfig = await fetchAuthConfig(composioClient);
- if (!authConfig) {
- authConfig = await createAuthConfig(composioClient);
- }
-
- // Create a connection for the user
- return composioClient.connectedAccounts.initiate(
- userId,
- authConfig.id,
- );
-}
-
-// Setup Hono
+declare const composio: Composio<OpenAIProvider>;
const app = new Hono();
-
-// Connection initiation endpoint
-app.post("/connection/create", async (c) => {
- /**
- * Create a connection for a given user id.
- */
- // For demonstration, using a default user_id. Replace with real user logic in production.
- const userId = "default";
-
- // Create a new connection for the user
- const connectionRequest = await createConnection(composioClient, userId);
- return c.json({
- "connection_id": connectionRequest.id,
- "redirect_url": connectionRequest.redirectUrl,
- });
+// ---cut---
+app.get("/connections/:userId", async (c) => {
+ const userId = c.req.param("userId");
+
+ const session = await composio.create(userId);
+ const toolkits = await session.toolkits();
+
+ return c.json(
+ toolkits.items.map((t) => ({
+ toolkit: t.slug,
+ connected: t.connection?.isActive ?? false,
+ }))
+ );
});
```
-Now, you can make a request to this endpoint on your client app, and your user will get a URL which they can use to authenticate.
-
-## Set Up Hono service
-
-We will use [`Hono.js`](https://hono.dev/) to build an HTTP service that authenticates your users and lets them interact with your agent. This guide will provide best practices for using composio client in production environments.
-
-### Setup dependencies
-
-Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
+If you just need to check a single toolkit, say before kicking off a workflow that requires Gmail, you can scope the session to that toolkit:
```typescript
+import { Hono } from 'hono';
import { Composio } from '@composio/core';
import { OpenAIProvider } from '@composio/openai';
-import { OpenAI } from 'openai';
-let _composioClient: Composio<OpenAIProvider> | null = null;
+declare const composio: Composio<OpenAIProvider>;
+const app = new Hono();
+// ---cut---
+app.get("/connections/:userId/:toolkit", async (c) => {
+ const userId = c.req.param("userId");
+ const toolkit = c.req.param("toolkit");
-export function provideComposioClient(): Composio<OpenAIProvider> {
- /**
- * Provide a Composio client.
- */
- if (_composioClient === null) {
- _composioClient = new Composio({
- provider: new OpenAIProvider()
- });
- }
- return _composioClient;
-}
+ const session = await composio.create(userId, { toolkits: [toolkit] });
+ const result = await session.toolkits();
+ const match = result.items.find((t) => t.slug === toolkit);
-// A Composio client dependency.
-export type ComposioClient = Composio<OpenAIProvider>;
+ return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
+});
```
-### Invoke agent via Hono
+## Connecting an app
-When invoking an agent, make sure you validate the `user_id`.
+When a user wants to connect a new app, `session.authorize()` starts the OAuth flow and returns a redirect URL. Your frontend sends the user there, and once they complete auth, they're connected.
```typescript
+import { Hono } from 'hono';
import { Composio } from '@composio/core';
import { OpenAIProvider } from '@composio/openai';
-import { OpenAI } from 'openai';
-import { Hono } from 'hono';
+declare const composio: Composio<OpenAIProvider>;
const app = new Hono();
-declare const composioClient: Composio<OpenAIProvider>;
-declare const openaiClient: OpenAI;
-declare function runGmailAgent(c: Composio<OpenAIProvider>, o: OpenAI, u: string, p: string): Promise<any[]>;
// ---cut---
-export function checkConnectedAccountExists(
- composioClient: Composio<OpenAIProvider>,
- userId: string,
-): Promise<boolean> {
- /**
- * Check if a connected account exists for a given user id.
- */
- // Fetch all connected accounts for the user
- return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {
-
- // Check if there's an active connected account
- for (const account of connectedAccounts.items) {
- if (account.status === "ACTIVE") {
- return true;
- }
-
- // Ideally you should not have inactive accounts, but if you do, delete them.
- console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);
- }
- return false;
- });
-}
-
-export async function validateUserId(userId: string, composioClient: Composio<OpenAIProvider>): Promise<string> {
- /**
- * Validate the user id, if no connected account is found, create a new connection.
- */
- if (await checkConnectedAccountExists(composioClient, userId)) {
- return userId;
- }
+app.post("/connect/:toolkit", async (c) => {
+ const toolkit = c.req.param("toolkit");
+ const { userId } = await c.req.json();
- throw new Error("No connected account found for the user id");
-}
-
-// Endpoint: Run the Gmail agent for a given user id and prompt
-app.post("/agent", async (c) => {
- /**
- * Run the Gmail agent for a given user id and prompt.
- */
- const request = await c.req.json();
-
- // For demonstration, using a default user_id. Replace with real user logic in production.
- const userId = "default";
-
- // Validate the user id before proceeding
- await validateUserId(userId, composioClient);
-
- // Run the Gmail agent using Composio and OpenAI
- const result = await runGmailAgent(
- composioClient,
- openaiClient,
- userId,
- request.prompt,
- );
- return c.json(result);
+ const session = await composio.create(userId, { toolkits: [toolkit] });
+ const connectionRequest = await session.authorize(toolkit);
+
+ return c.json({ redirectUrl: connectionRequest.redirectUrl });
});
```
-## Putting everything together
-
-So far, we have created an agent with ability to interact with `gmail` using the `composio` SDK, functions to manage connected accounts for users and a Hono service. Now let's run the service.
-
-1. Clone the repository
- ```bash
- git clone [email protected]:composiohq/composio-hono
- cd composio-hono/
- ```
-2. Setup environment
-
- ```bash
- cp .env.example .env
- ```
-
- Fill the api keys
+## Complete app
- ```dotenv
- COMPOSIO_API_KEY=
- OPENAI_API_KEY=
- ```
+Here's everything together:
- Install dependencies
+<include>../../examples/hono/server.ts</include>
- ```bash
- npm install
- ```
-3. Run the HTTP server
- ```bash
- npm run dev
- ```
-
-## Testing the API with curl
-
-Assuming the server is running locally on `http://localhost:8000`.
-
-### Check if a connection exists
+## Running the server
```bash
-curl -X POST http://localhost:8000/connection/exists
+npx tsx server.ts
```
-### Create a connection
+The server runs at `http://localhost:8000`.
-Note: The body fields are required by the API schema, but are ignored internally in this example service.
+## Testing with cURL
+
+### Chat with the agent
```bash
-curl -X POST http://localhost:8000/connection/create \
+curl -X POST http://localhost:8000/chat \
-H "Content-Type: application/json" \
- -d '{
- "user_id": "default",
- "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
- }'
+ -d '{"userId": "user_123", "message": "Star the composiohq/composio repo on GitHub"}'
```
-Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
-
-### Check connection status
-
-Use the `connection_id` returned from the create step.
+### List all connections
```bash
-curl -X POST http://localhost:8000/connection/status \
- -H "Content-Type: application/json" \
- -d '{
- "user_id": "default",
- "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
- }'
+curl http://localhost:8000/connections/user_123
```
-### Run the Gmail agent
-
-Requires an active connected account for the `default` user.
+### Check a specific connection
```bash
-curl -X POST http://localhost:8000/agent \
- -H "Content-Type: application/json" \
- -d '{
- "user_id": "default",
- "prompt": "Summarize my latest unread emails from the last 24 hours."
- }'
+curl http://localhost:8000/connections/user_123/gmail
```
-### Fetch emails (direct action)
+### Connect an app
```bash
-curl -X POST http://localhost:8000/actions/fetch_emails \
+curl -X POST http://localhost:8000/connect/gmail \
-H "Content-Type: application/json" \
- -d '{
- "user_id": "default",
- "limit": 5
- }'
+ -d '{"userId": "user_123"}'
```
-These examples are intended solely for testing purposes.
-
-## Using Composio for managed auth and tools
-
-Composio reduces boilerplate for building AI agents that access and use various apps. In this cookbook, to build Gmail integration without Composio, you would have to write code to
-
-* manage Gmail OAuth app
-* manage user connections
-* tools for your agents to interact with Gmail
-
-Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
-
-## Best practices
-
-**🎯 Effective Prompts**:
-
-* Be specific: "Send email to [[email protected]](mailto:[email protected]) about tomorrow's 2pm meeting" works better than "send email"
-* Include context: "Reply to Sarah's email about the budget with our approval"
-* Use natural language: The agent understands conversational requests
-
-**🔑 User Management**:
-
-* Use unique, consistent `user_id` values for each person
-* Each user maintains their own Gmail connection
-* User IDs can be email addresses, usernames, or any unique identifier
-
-## Troubleshooting
-
-**Connection Issues**:
-
-* Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
-* Check if the user has completed Gmail authorization.
-* Verify the user\_id matches exactly between requests
-
-**API Errors**:
-
-* Check the server logs for detailed error messages
-* Ensure request payloads match the expected format
-* Visit `/docs` endpoint for API schema validation
-
-**Gmail API Limits**:
-
-* Gmail has rate limits; the agent will handle these gracefully
-* For high-volume usage, consider implementing request queuing
\ No newline at end of file
+Open the `redirectUrl` from the response in your browser to complete OAuth.
diff --git a/docs/examples/hono/server.ts b/docs/examples/hono/server.ts
new file mode 100644
index 000000000..640f9b815
--- /dev/null
+++ b/docs/examples/hono/server.ts
@@ -0,0 +1,81 @@
+import { serve } from "@hono/node-server";
+import { Hono } from "hono";
+import { OpenAI } from "openai";
+import { Composio } from "@composio/core";
+import { OpenAIProvider } from "@composio/openai";
+
+const composio = new Composio({ provider: new OpenAIProvider() });
+const openai = new OpenAI();
+
+const app = new Hono();
+
+// Send a message to an AI agent with access to all tools.
+app.post("/chat", async (c) => {
+ const { userId, message } = await c.req.json();
+
+ const session = await composio.create(userId);
+ const tools = await session.tools();
+
+ const messages: OpenAI.ChatCompletionMessageParam[] = [
+ { role: "system", content: "You are a helpful assistant. Use tools to help the user." },
+ { role: "user", content: message },
+ ];
+
+ while (true) {
+ const response = await openai.chat.completions.create({
+ model: "gpt-4.1",
+ tools,
+ messages,
+ });
+
+ const choice = response.choices[0];
+ if (!choice.message.tool_calls?.length) {
+ return c.json({ response: choice.message.content });
+ }
+
+ messages.push(choice.message);
+ const toolResults = await composio.provider.handleToolCalls(userId, response);
+ messages.push(...toolResults);
+ }
+});
+
+// List all toolkits and their connection status for a user.
+app.get("/connections/:userId", async (c) => {
+ const userId = c.req.param("userId");
+
+ const session = await composio.create(userId);
+ const toolkits = await session.toolkits();
+
+ return c.json(
+ toolkits.items.map((t) => ({
+ toolkit: t.slug,
+ connected: t.connection?.isActive ?? false,
+ }))
+ );
+});
+
+// Check if a specific toolkit is connected for a user.
+app.get("/connections/:userId/:toolkit", async (c) => {
+ const userId = c.req.param("userId");
+ const toolkit = c.req.param("toolkit");
+
+ const session = await composio.create(userId, { toolkits: [toolkit] });
+ const result = await session.toolkits();
+ const match = result.items.find((t) => t.slug === toolkit);
+
+ return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
+});
+
+// Start OAuth for a toolkit. Returns a URL to redirect the user to.
+app.post("/connect/:toolkit", async (c) => {
+ const toolkit = c.req.param("toolkit");
+ const { userId } = await c.req.json();
+
+ const session = await composio.create(userId, { toolkits: [toolkit] });
+ const connectionRequest = await session.authorize(toolkit);
+
+ return c.json({ redirectUrl: connectionRequest.redirectUrl });
+});
+
+serve({ fetch: app.fetch, port: 8000 });
+console.log("Server running on http://localhost:8000");