Basic Hono Server

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.

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)

Building an AI agent that can interact with gmail service

First, let’s start with building a simple AI agent embedded with tools from Composio that lets the agent interact with the gmail service.

1import { OpenAI } from 'openai';
2import { Composio } from '@composio/core';
3import { OpenAIProvider } from '@composio/openai';
4
5export async function runGmailAgent(
6 composioClient: Composio<OpenAIProvider>,
7 openaiClient: OpenAI,
8 userId: string, // Composio uses the User ID to store and access user-level authentication tokens.
9 prompt: string,
10): Promise<any[]> {
11 // Step 1: Fetch the necessary Gmail tools list with Composio
12 const tools = await composioClient.tools.get(
13 userId,
14 {
15 tools: [
16 "GMAIL_FETCH_EMAILS",
17 "GMAIL_SEND_EMAIL",
18 "GMAIL_CREATE_EMAIL_DRAFT"
19 ]
20 }
21 );
22
23 // Step 2: Use OpenAI to generate a response based on the prompt and available tools
24 const response = await openaiClient.chat.completions.create({
25 model: "gpt-4.1",
26 tools,
27 messages: [{ role: "user", content: prompt }],
28 });
29
30 // Step 3: Handle tool calls with Composio and return the result
31 const result = await composioClient.provider.handleToolCalls(
32 userId,
33 response
34 );
35 return result;
36}

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.

To invoke this agent, authenticate your users with Composio’s managed authentication service.

Authenticating users

To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.

To create an authentication config for gmail you need client_id and client_secret from your Google OAuth Console. Once you have the credentials, use the following piece of code to set up authentication for gmail.

1import { Composio } from '@composio/core';
2import { OpenAIProvider } from '@composio/openai';
3
4export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {
5 /**
6 * Create a auth config for the gmail toolkit.
7 */
8 const clientId = process.env.GMAIL_CLIENT_ID;
9 const clientSecret = process.env.GMAIL_CLIENT_SECRET;
10 if (!clientId || !clientSecret) {
11 throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");
12 }
13
14 return composioClient.authConfigs.create(
15 "GMAIL",
16 {
17 "name": "default_gmail_auth_config",
18 "type": "use_custom_auth",
19 "authScheme": "OAUTH2",
20 "credentials": {
21 "clientId": clientId,
22 "clientSecret": clientSecret,
23 },
24 },
25 );
26}

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.

1export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {
2 /**
3 * Fetch the auth config for a given user id.
4 */
5 const authConfigs = await composioClient.authConfigs.list();
6 for (const authConfig of authConfigs.items) {
7 if (authConfig.toolkit.slug === "gmail") {
8 return authConfig;
9 }
10 }
11
12 return null;
13}

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.

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.

1import { Hono } from 'hono';
2
3// Function to initiate a connected account
4export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {
5 /**
6 * Create a connection for a given user id and auth config id.
7 */
8 // Fetch or create the auth config for the gmail toolkit
9 let authConfig = await fetchAuthConfig(composioClient);
10 if (!authConfig) {
11 authConfig = await createAuthConfig(composioClient);
12 }
13
14 // Create a connection for the user
15 return composioClient.connectedAccounts.initiate(
16 userId,
17 authConfig.id,
18 );
19}
20
21// Setup Hono
22const app = new Hono();
23
24// Connection initiation endpoint
25app.post("/connection/create", async (c) => {
26 /**
27 * Create a connection for a given user id.
28 */
29 // For demonstration, using a default user_id. Replace with real user logic in production.
30 const userId = "default";
31
32 // Create a new connection for the user
33 const connectionRequest = await createConnection(composioClient, userId);
34 return c.json({
35 "connection_id": connectionRequest.id,
36 "redirect_url": connectionRequest.redirectUrl,
37 });
38});

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

1import { Composio } from '@composio/core';
2import { OpenAIProvider } from '@composio/openai';
3import { OpenAI } from 'openai';
4
5let _composioClient: Composio<OpenAIProvider> | null = null;
6
7export function provideComposioClient(): Composio<OpenAIProvider> {
8 /**
9 * Provide a Composio client.
10 */
11 if (_composioClient === null) {
12 _composioClient = new Composio({
13 provider: new OpenAIProvider()
14 });
15 }
16 return _composioClient;
17}
18
19// A Composio client dependency.
20export type ComposioClient = Composio<OpenAIProvider>;

Check config/composio.ts module for more details.

Invoke agent via Hono

When invoking an agent, make sure you validate the user_id.

1export function checkConnectedAccountExists(
2 composioClient: Composio<OpenAIProvider>,
3 userId: string,
4): Promise<boolean> {
5 /**
6 * Check if a connected account exists for a given user id.
7 */
8 // Fetch all connected accounts for the user
9 return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {
10
11 // Check if there's an active connected account
12 for (const account of connectedAccounts.items) {
13 if (account.status === "ACTIVE") {
14 return true;
15 }
16
17 // Ideally you should not have inactive accounts, but if you do, delete them.
18 console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);
19 }
20 return false;
21 });
22}
23
24export async function validateUserId(userId: string, composioClient: ComposioClient): Promise<string> {
25 /**
26 * Validate the user id, if no connected account is found, create a new connection.
27 */
28 if (await checkConnectedAccountExists(composioClient, userId)) {
29 return userId;
30 }
31
32 throw new Error("No connected account found for the user id");
33}
34
35// Endpoint: Run the Gmail agent for a given user id and prompt
36app.post("/agent", async (c) => {
37 /**
38 * Run the Gmail agent for a given user id and prompt.
39 */
40 const request = await c.req.json();
41
42 // For demonstration, using a default user_id. Replace with real user logic in production.
43 const userId = "default";
44
45 // Validate the user id before proceeding
46 await validateUserId(userId, composioClient);
47
48 // Run the Gmail agent using Composio and OpenAI
49 const result = await runGmailAgent(
50 composioClient,
51 openaiClient,
52 userId,
53 request.prompt,
54 );
55 return c.json(result);
56});

Check src/api.ts module for service implementation

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.

Before proceeding, check the code for utility endpoints not discussed in the cookbook

  1. Clone the repository

    $git clone git@github.com:composiohq/composio-hono
    >cd composio-hono/
  2. Setup environment

    $cp .env.example .env

    Fill the api keys

    1COMPOSIO_API_KEY=
    2OPENAI_API_KEY=

    Install dependencies

    $npm install
  3. Run the HTTP server

    $npm run dev

Testing the API with curl

Assuming the server is running locally on http://localhost:8000.

Check if a connection exists

$curl -X POST http://localhost:8000/connection/exists

Create a connection

Note: The body fields are required by the API schema, but are ignored internally in this example service.

$curl -X POST http://localhost:8000/connection/create \
> -H "Content-Type: application/json" \
> -d '{
> "user_id": "default",
> "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
> }'

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.

$curl -X POST http://localhost:8000/connection/status \
> -H "Content-Type: application/json" \
> -d '{
> "user_id": "default",
> "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
> }'

Run the Gmail agent

Requires an active connected account for the default user.

$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."
> }'

Fetch emails (direct action)

$curl -X POST http://localhost:8000/actions/fetch_emails \
> -H "Content-Type: application/json" \
> -d '{
> "user_id": "default",
> "limit": 5
> }'

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 john@company.com 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