1
---
2
title: Basic Hono Server
3
-description: Build a simple Gmail agent with Composio and Hono.js
3
+description: Build an AI agent with access to 1000+ tools using Composio and Hono.js
4
---
5
6
-With Composio's managed authentication and tool calling, it's easy to build
7
-AI agents that interact with the real world while reducing boilerplate for
8
-setup and authentication management. This cookbook will guide you through
9
-building and serving agents using `Composio`, `OpenAI`, and `Hono.js`.
6
+[View source on GitHub](https://github.com/ComposioHQ/composio/tree/next/docs/examples/hono)
7
11
-## Prerequisites
12
-
13
-* Node.js 18.x or higher
14
-* npm or yarn package manager
15
-* Composio API key
16
-* OpenAI API key
17
-* Basic knowledge of OAuth
18
-* Understanding of building HTTP services (preferably using Hono.js)
8
+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.
9
20
-## Building an AI agent that can interact with `gmail` service
10
+## Prerequisites
11
22
-First, let's start with building a simple AI agent embedded with tools from
23
-Composio that lets the agent interact with the `gmail` service.
12
+* Node.js 18+
13
+* [Composio API key](https://platform.composio.dev/settings)
14
+* [OpenAI API key](https://platform.openai.com/api-keys)
15
25
-```typescript
26
-import { OpenAI } from 'openai';
27
-import { Composio } from '@composio/core';
28
-import { OpenAIProvider } from '@composio/openai';
16
+## Project setup
17
30
-export async function runGmailAgent(
31
- composioClient: Composio<OpenAIProvider>,
32
- openaiClient: OpenAI,
33
- userId: string, // Composio uses the User ID to store and access user-level authentication tokens.
34
- prompt: string,
35
-): Promise<any[]> {
36
- // Step 1: Fetch the necessary Gmail tools list with Composio
37
- const tools = await composioClient.tools.get(
38
- userId,
39
- {
40
- tools: [
41
- "GMAIL_FETCH_EMAILS",
42
- "GMAIL_SEND_EMAIL",
43
- "GMAIL_CREATE_EMAIL_DRAFT"
44
- ]
45
- }
46
- );
47
-
48
- // Step 2: Use OpenAI to generate a response based on the prompt and available tools
49
- const response = await openaiClient.chat.completions.create({
50
- model: "gpt-4.1",
51
- tools,
52
- messages: [{ role: "user", content: prompt }],
53
- });
18
+Create a new project and install dependencies:
19
55
- // Step 3: Handle tool calls with Composio and return the result
56
- const result = await composioClient.provider.handleToolCalls(
57
- userId,
58
- response
59
- );
60
- return result;
61
-}
20
+```bash
21
+mkdir composio-hono && cd composio-hono
22
+npm init -y
23
+npm install hono @hono/node-server openai @composio/core @composio/openai tsx
24
```
25
64
-<Callout>
65
- This is a simple agent without state management and agentic loop implementation,
66
- so the agent can't perform complicated tasks. If you want to understand how
67
- composio can be used with agentic loops, check other cookbooks with more
68
- agentic frameworks.
69
-</Callout>
70
-
71
-To invoke this agent, authenticate your users with Composio's managed authentication service.
26
+Add your API keys to a `.env` file:
27
73
-## Authenticating users
28
+```bash title=".env"
29
+COMPOSIO_API_KEY=your_composio_api_key
30
+OPENAI_API_KEY=your_openai_api_key
31
+```
32
75
-To authenticate your users with Composio you need an authentication config for the given app. In this case you need one for gmail.
33
+## Initializing the clients
34
77
-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`.
35
+`Composio` takes an `OpenAIProvider` so that when we ask for tools later, they come back in the format OpenAI expects.
36
37
```typescript
38
+import { Hono } from 'hono';
39
+import { OpenAI } from 'openai';
40
import { Composio } from '@composio/core';
41
import { OpenAIProvider } from '@composio/openai';
42
83
-export async function createAuthConfig(composioClient: Composio<OpenAIProvider>) {
84
- /**
85
- * Create a auth config for the gmail toolkit.
86
- */
87
- const clientId = process.env.GMAIL_CLIENT_ID;
88
- const clientSecret = process.env.GMAIL_CLIENT_SECRET;
89
- if (!clientId || !clientSecret) {
90
- throw new Error("GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set");
91
- }
43
+const composio = new Composio({ provider: new OpenAIProvider() });
44
+const openai = new OpenAI();
45
93
- return composioClient.authConfigs.create(
94
- "GMAIL",
95
- {
96
- "name": "default_gmail_auth_config",
97
- "type": "use_custom_auth",
98
- "authScheme": "OAUTH2",
99
- "credentials": {
100
- "clientId": clientId,
101
- "clientSecret": clientSecret,
102
- },
103
- },
104
- );
105
-}
46
+const app = new Hono();
47
```
48
108
-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.
49
+## Chat endpoint
50
+
51
+The core of the server is a `/chat` endpoint. A user sends a message, and the agent responds, using whatever tools it needs.
52
+
53
+`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.
54
55
```typescript
56
+import { Hono } from 'hono';
57
+import { OpenAI } from 'openai';
58
import { Composio } from '@composio/core';
59
import { OpenAIProvider } from '@composio/openai';
60
+
61
+declare const composio: Composio<OpenAIProvider>;
62
+declare const openai: OpenAI;
63
+const app = new Hono();
64
// ---cut---
114
-export async function fetchAuthConfig(composioClient: Composio<OpenAIProvider>) {
115
- /**
116
- * Fetch the auth config for a given user id.
117
- */
118
- const authConfigs = await composioClient.authConfigs.list();
119
- for (const authConfig of authConfigs.items) {
120
- if (authConfig.toolkit.slug === "gmail") {
121
- return authConfig;
122
- }
65
+app.post("/chat", async (c) => {
66
+ const { userId, message } = await c.req.json();
67
+
68
+ const session = await composio.create(userId);
69
+ const tools = await session.tools();
70
+
71
+ const messages: OpenAI.ChatCompletionMessageParam[] = [
72
+ { role: "system", content: "You are a helpful assistant. Use tools to help the user." },
73
+ { role: "user", content: message },
74
+ ];
75
+
76
+ while (true) {
77
+ const response = await openai.chat.completions.create({
78
+ model: "gpt-4.1",
79
+ tools,
80
+ messages,
81
+ });
82
+
83
+ const choice = response.choices[0];
84
+ if (!choice.message.tool_calls?.length) {
85
+ return c.json({ response: choice.message.content });
86
}
87
125
- return null;
126
-}
88
+ messages.push(choice.message);
89
+ const toolResults = await composio.provider.handleToolCalls(userId, response);
90
+ messages.push(...toolResults);
91
+ }
92
+});
93
```
94
95
<Callout>
130
- Composio platform provides composio managed authentication for some apps to
131
- fast-track your development, `gmail` being one of them. You can use these
132
- default auth configs for development, but for production, always use your
133
- own oauth app configuration.
96
+If the user hasn't connected the app they're trying to use, the agent will automatically
97
+return an authentication link in its response. The user can complete OAuth and then retry.
98
</Callout>
99
136
-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.
100
+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.
101
+
102
+## Checking connections
103
+
104
+`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.
105
106
```typescript
107
import { Hono } from 'hono';
108
import { Composio } from '@composio/core';
109
import { OpenAIProvider } from '@composio/openai';
110
143
-declare function fetchAuthConfig(client: Composio<OpenAIProvider>): Promise<{ id: string } | null>;
144
-declare function createAuthConfig(client: Composio<OpenAIProvider>): Promise<{ id: string }>;
145
-declare const composioClient: Composio<OpenAIProvider>;
146
-// ---cut---
147
-// Function to initiate a connected account
148
-export async function createConnection(composioClient: Composio<OpenAIProvider>, userId: string) {
149
- /**
150
- * Create a connection for a given user id and auth config id.
151
- */
152
- // Fetch or create the auth config for the gmail toolkit
153
- let authConfig = await fetchAuthConfig(composioClient);
154
- if (!authConfig) {
155
- authConfig = await createAuthConfig(composioClient);
156
- }
157
-
158
- // Create a connection for the user
159
- return composioClient.connectedAccounts.initiate(
160
- userId,
161
- authConfig.id,
162
- );
163
-}
164
-
165
-// Setup Hono
111
+declare const composio: Composio<OpenAIProvider>;
112
const app = new Hono();
167
-
168
-// Connection initiation endpoint
169
-app.post("/connection/create", async (c) => {
170
- /**
171
- * Create a connection for a given user id.
172
- */
173
- // For demonstration, using a default user_id. Replace with real user logic in production.
174
- const userId = "default";
175
-
176
- // Create a new connection for the user
177
- const connectionRequest = await createConnection(composioClient, userId);
178
- return c.json({
179
- "connection_id": connectionRequest.id,
180
- "redirect_url": connectionRequest.redirectUrl,
181
- });
113
+// ---cut---
114
+app.get("/connections/:userId", async (c) => {
115
+ const userId = c.req.param("userId");
116
+
117
+ const session = await composio.create(userId);
118
+ const toolkits = await session.toolkits();
119
+
120
+ return c.json(
121
+ toolkits.items.map((t) => ({
122
+ toolkit: t.slug,
123
+ connected: t.connection?.isActive ?? false,
124
+ }))
125
+ );
126
});
127
```
128
185
-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.
186
-
187
-## Set Up Hono service
188
-
189
-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.
190
-
191
-### Setup dependencies
192
-
193
-Hono allows dependency injection patterns to simplify the usage of SDK clients that must be singletons. We recommend using composio SDK client as singleton.
129
+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:
130
131
```typescript
132
+import { Hono } from 'hono';
133
import { Composio } from '@composio/core';
134
import { OpenAIProvider } from '@composio/openai';
198
-import { OpenAI } from 'openai';
135
200
-let _composioClient: Composio<OpenAIProvider> | null = null;
136
+declare const composio: Composio<OpenAIProvider>;
137
+const app = new Hono();
138
+// ---cut---
139
+app.get("/connections/:userId/:toolkit", async (c) => {
140
+ const userId = c.req.param("userId");
141
+ const toolkit = c.req.param("toolkit");
142
202
-export function provideComposioClient(): Composio<OpenAIProvider> {
203
- /**
204
- * Provide a Composio client.
205
- */
206
- if (_composioClient === null) {
207
- _composioClient = new Composio({
208
- provider: new OpenAIProvider()
209
- });
210
- }
211
- return _composioClient;
212
-}
143
+ const session = await composio.create(userId, { toolkits: [toolkit] });
144
+ const result = await session.toolkits();
145
+ const match = result.items.find((t) => t.slug === toolkit);
146
214
-// A Composio client dependency.
215
-export type ComposioClient = Composio<OpenAIProvider>;
147
+ return c.json({ toolkit, connected: match?.connection?.isActive ?? false });
148
+});
149
```
150
218
-### Invoke agent via Hono
151
+## Connecting an app
152
220
-When invoking an agent, make sure you validate the `user_id`.
153
+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.
154
155
```typescript
156
+import { Hono } from 'hono';
157
import { Composio } from '@composio/core';
158
import { OpenAIProvider } from '@composio/openai';
225
-import { OpenAI } from 'openai';
226
-import { Hono } from 'hono';
159
160
+declare const composio: Composio<OpenAIProvider>;
161
const app = new Hono();
229
-declare const composioClient: Composio<OpenAIProvider>;
230
-declare const openaiClient: OpenAI;
231
-declare function runGmailAgent(c: Composio<OpenAIProvider>, o: OpenAI, u: string, p: string): Promise<any[]>;
162
// ---cut---
233
-export function checkConnectedAccountExists(
234
- composioClient: Composio<OpenAIProvider>,
235
- userId: string,
236
-): Promise<boolean> {
237
- /**
238
- * Check if a connected account exists for a given user id.
239
- */
240
- // Fetch all connected accounts for the user
241
- return composioClient.connectedAccounts.list({ userIds: [userId], toolkitSlugs: ["GMAIL"] }).then(connectedAccounts => {
242
-
243
- // Check if there's an active connected account
244
- for (const account of connectedAccounts.items) {
245
- if (account.status === "ACTIVE") {
246
- return true;
247
- }
248
-
249
- // Ideally you should not have inactive accounts, but if you do, delete them.
250
- console.log(`[warning] inactive account ${account.id} found for user id: ${userId}`);
251
- }
252
- return false;
253
- });
254
-}
255
-
256
-export async function validateUserId(userId: string, composioClient: Composio<OpenAIProvider>): Promise<string> {
257
- /**
258
- * Validate the user id, if no connected account is found, create a new connection.
259
- */
260
- if (await checkConnectedAccountExists(composioClient, userId)) {
261
- return userId;
262
- }
163
+app.post("/connect/:toolkit", async (c) => {
164
+ const toolkit = c.req.param("toolkit");
165
+ const { userId } = await c.req.json();
166
264
- throw new Error("No connected account found for the user id");
265
-}
266
-
267
-// Endpoint: Run the Gmail agent for a given user id and prompt
268
-app.post("/agent", async (c) => {
269
- /**
270
- * Run the Gmail agent for a given user id and prompt.
271
- */
272
- const request = await c.req.json();
273
-
274
- // For demonstration, using a default user_id. Replace with real user logic in production.
275
- const userId = "default";
276
-
277
- // Validate the user id before proceeding
278
- await validateUserId(userId, composioClient);
279
-
280
- // Run the Gmail agent using Composio and OpenAI
281
- const result = await runGmailAgent(
282
- composioClient,
283
- openaiClient,
284
- userId,
285
- request.prompt,
286
- );
287
- return c.json(result);
167
+ const session = await composio.create(userId, { toolkits: [toolkit] });
168
+ const connectionRequest = await session.authorize(toolkit);
169
+
170
+ return c.json({ redirectUrl: connectionRequest.redirectUrl });
171
});
172
```
173
291
-## Putting everything together
292
-
293
-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.
294
-
295
-1. Clone the repository
296
- ```bash
297
- git clone git@github.com:composiohq/composio-hono
298
- cd composio-hono/
299
- ```
300
-2. Setup environment
301
-
302
- ```bash
303
- cp .env.example .env
304
- ```
305
-
306
- Fill the api keys
174
+## Complete app
175
308
- ```dotenv
309
- COMPOSIO_API_KEY=
310
- OPENAI_API_KEY=
311
- ```
176
+Here's everything together:
177
313
- Install dependencies
178
+<include>../../examples/hono/server.ts</include>
179
315
- ```bash
316
- npm install
317
- ```
318
-3. Run the HTTP server
319
- ```bash
320
- npm run dev
321
- ```
322
-
323
-## Testing the API with curl
324
-
325
-Assuming the server is running locally on `http://localhost:8000`.
326
-
327
-### Check if a connection exists
180
+## Running the server
181
182
```bash
330
-curl -X POST http://localhost:8000/connection/exists
183
+npx tsx server.ts
184
```
185
333
-### Create a connection
186
+The server runs at `http://localhost:8000`.
187
335
-Note: The body fields are required by the API schema, but are ignored internally in this example service.
188
+## Testing with cURL
189
+
190
+### Chat with the agent
191
192
```bash
338
-curl -X POST http://localhost:8000/connection/create \
193
+curl -X POST http://localhost:8000/chat \
194
-H "Content-Type: application/json" \
340
- -d '{
341
- "user_id": "default",
342
- "auth_config_id": "AUTH_CONFIG_ID_FOR_GMAIL_FROM_THE_COMPOSIO_DASHBOARD"
343
- }'
195
+ -d '{"userId": "user_123", "message": "Star the composiohq/composio repo on GitHub"}'
196
```
197
346
-Response includes `connection_id` and `redirect_url`. Complete the OAuth flow at the `redirect_url`.
347
-
348
-### Check connection status
349
-
350
-Use the `connection_id` returned from the create step.
198
+### List all connections
199
200
```bash
353
-curl -X POST http://localhost:8000/connection/status \
354
- -H "Content-Type: application/json" \
355
- -d '{
356
- "user_id": "default",
357
- "connection_id": "CONNECTION_ID_FROM_CREATE_RESPONSE"
358
- }'
201
+curl http://localhost:8000/connections/user_123
202
```
203
361
-### Run the Gmail agent
362
-
363
-Requires an active connected account for the `default` user.
204
+### Check a specific connection
205
206
```bash
366
-curl -X POST http://localhost:8000/agent \
367
- -H "Content-Type: application/json" \
368
- -d '{
369
- "user_id": "default",
370
- "prompt": "Summarize my latest unread emails from the last 24 hours."
371
- }'
207
+curl http://localhost:8000/connections/user_123/gmail
208
```
209
374
-### Fetch emails (direct action)
210
+### Connect an app
211
212
```bash
377
-curl -X POST http://localhost:8000/actions/fetch_emails \
213
+curl -X POST http://localhost:8000/connect/gmail \
214
-H "Content-Type: application/json" \
379
- -d '{
380
- "user_id": "default",
381
- "limit": 5
382
- }'
215
+ -d '{"userId": "user_123"}'
216
```
217
385
-These examples are intended solely for testing purposes.
386
-
387
-## Using Composio for managed auth and tools
388
-
389
-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
390
-
391
-* manage Gmail OAuth app
392
-* manage user connections
393
-* tools for your agents to interact with Gmail
394
-
395
-Using Composio simplifies all of the above to a few lines of code as shown in the cookbook.
396
-
397
-## Best practices
398
-
399
-**🎯 Effective Prompts**:
400
-
401
-* Be specific: "Send email to [john@company.com](mailto:john@company.com) about tomorrow's 2pm meeting" works better than "send email"
402
-* Include context: "Reply to Sarah's email about the budget with our approval"
403
-* Use natural language: The agent understands conversational requests
404
-
405
-**🔑 User Management**:
406
-
407
-* Use unique, consistent `user_id` values for each person
408
-* Each user maintains their own Gmail connection
409
-* User IDs can be email addresses, usernames, or any unique identifier
410
-
411
-## Troubleshooting
412
-
413
-**Connection Issues**:
414
-
415
-* Ensure your `.env` file has valid `COMPOSIO_API_KEY` and `OPENAI_API_KEY`
416
-* Check if the user has completed Gmail authorization.
417
-* Verify the user\_id matches exactly between requests
418
-
419
-**API Errors**:
420
-
421
-* Check the server logs for detailed error messages
422
-* Ensure request payloads match the expected format
423
-* Visit `/docs` endpoint for API schema validation
424
-
425
-**Gmail API Limits**:
426
-
427
-* Gmail has rate limits; the agent will handle these gracefully
428
-* For high-volume usage, consider implementing request queuing
\ No newline at end of file
218
+Open the `redirectUrl` from the response in your browser to complete OAuth.