@devries-cameron20 / composio-1 / commits / 3d2093fff
Fork 0

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

Add tool router preload examples

Dhawal Upadhyay committed May 6, 2026 at 16:02 UTC 3d2093fffb85afd93834f248a48a8f5de8abf8f7
5 files changed +223 -2
ts/examples/tool-router/.env.example
+6 -1
@@ -1,6 +1,11 @@
1 # Composio API Key - Get it from https://app.composio.dev
2 COMPOSIO_API_KEY=your_composio_api_key_here
3
4 +# OpenAI API Key - Required for OpenAI Agents examples
5 +OPENAI_API_KEY=your_openai_api_key_here
6 +
7 +# Optional: override the model used by OpenAI Agents examples
8 +# OPENAI_MODEL=gpt-5.1
9 +
10 # Add other environment variables as needed for your example
5 -# OPENAI_API_KEY=your_openai_api_key_here
11 # ANTHROPIC_API_KEY=your_anthropic_api_key_here
ts/examples/tool-router/README.md
+14 -1
@@ -5,17 +5,21 @@ This example demonstrates how to use Composio SDK for tool-router.
5 ## Setup
6
7 1. **Install dependencies:**
8 +
9 ```bash
10 pnpm install
11 ```
12
13 2. **Configure environment:**
14 +
15 ```bash
16 cp .env.example .env
17 ```
16 -
18 +
19 Then edit `.env` and add your API keys:
20 - `COMPOSIO_API_KEY`: Get it from [Composio Dashboard](https://app.composio.dev)
21 + - `OPENAI_API_KEY`: Required for OpenAI Agents examples
22 + - `OPENAI_MODEL`: Optional model override for OpenAI Agents examples
23
24 ## Running the Example
25
@@ -25,6 +29,12 @@ pnpm start
29
30 # Run in development mode (with file watching)
31 pnpm dev
32 +
33 +# Explicit preload for app tools and SDK custom tools
34 +pnpm preload
35 +
36 +# Direct-tools preset for sessions where all tools are known upfront
37 +pnpm direct-tools
38 ```
39
40 ## What This Example Does
@@ -32,10 +42,13 @@ pnpm dev
42 - Initializes Composio SDK
43 - Fetches available tools
44 - Demonstrates basic usage patterns
45 +- Shows how to preload selected app tools and SDK-local custom tools into `session.tools()`
46 +- Shows `sessionPreset: "direct_tools"` for loading all tools allowed by session filters without meta/helper tools
47
48 ## Customization
49
50 Edit `src/index.ts` to:
51 +
52 - Add specific apps you want to integrate with
53 - Implement your business logic
54 - Add error handling and logging
ts/examples/tool-router/package.json
+2
@@ -7,6 +7,8 @@
7 "scripts": {
8 "start": "bun src/index.ts",
9 "dev": "bun --watch src/index.ts",
10 + "preload": "bun src/preload.ts",
11 + "direct-tools": "bun src/direct-tools-preset.ts",
12 "test": "echo \"Error: no test specified\" && exit 1"
13 },
14 "keywords": [
ts/examples/tool-router/src/direct-tools-preset.ts new
+64
@@ -0,0 +1,64 @@
1 +/**
2 + * Tool Router direct_tools session preset with OpenAI Agents
3 + *
4 + * `sessionPreset: "direct_tools"` is a shortcut for sessions where the full
5 + * allowed tool set is known upfront. It disables Tool Router meta/helper tools
6 + * by default and loads all tools allowed by the filters directly into
7 + * `session.tools()` and the MCP tool list.
8 + *
9 + * Usage:
10 + * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/direct-tools-preset.ts
11 + */
12 +import 'dotenv/config';
13 +import { Composio } from '@composio/core';
14 +import { OpenAIAgentsProvider } from '@composio/openai-agents';
15 +import { Agent, run } from '@openai/agents';
16 +
17 +function requireEnv(name: 'COMPOSIO_API_KEY' | 'OPENAI_API_KEY'): string {
18 + const value = process.env[name];
19 + if (!value) {
20 + throw new Error(`Set ${name} before running this example.`);
21 + }
22 + return value;
23 +}
24 +
25 +const composioApiKey = requireEnv('COMPOSIO_API_KEY');
26 +requireEnv('OPENAI_API_KEY');
27 +
28 +const composio = new Composio({
29 + apiKey: composioApiKey,
30 + baseURL: process.env.COMPOSIO_BASE_URL || undefined,
31 + provider: new OpenAIAgentsProvider(),
32 +});
33 +
34 +const session = await composio.create(`direct-tools-example-${Date.now()}`, {
35 + sessionPreset: 'direct_tools',
36 + toolkits: ['hackernews'],
37 + tools: {
38 + hackernews: {
39 + enable: ['HACKERNEWS_GET_USER'],
40 + },
41 + },
42 +});
43 +
44 +const tools = await session.tools();
45 +console.log('Direct tools exposed to the agent:');
46 +for (const tool of tools) {
47 + console.log(`- ${tool.name}`);
48 +}
49 +
50 +const agent = new Agent({
51 + name: 'Direct Tools Demo Agent',
52 + instructions:
53 + 'Use the provided direct tools. The session is configured without Tool Router meta/helper tools.',
54 + model: process.env.OPENAI_MODEL ?? 'gpt-5.1',
55 + tools,
56 +});
57 +
58 +const prompt =
59 + process.argv.slice(2).join(' ') ||
60 + 'Use the Hacker News tool to look up user "pg" and report their karma.';
61 +
62 +console.log(`\nUser: ${prompt}\n`);
63 +const result = await run(agent, prompt);
64 +console.log(`Assistant: ${result.finalOutput}`);
ts/examples/tool-router/src/preload.ts new
+137
@@ -0,0 +1,137 @@
1 +/**
2 + * Tool Router preload with OpenAI Agents
3 + *
4 + * Shows direct tool exposure for:
5 + * 1. Composio tools via `preload.tools`
6 + * 2. SDK custom tools via `preload: true` on the custom tool or toolkit
7 + *
8 + * Usage:
9 + * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/preload.ts
10 + */
11 +import 'dotenv/config';
12 +import { Composio, experimental_createTool, experimental_createToolkit } from '@composio/core';
13 +import { OpenAIAgentsProvider } from '@composio/openai-agents';
14 +import { Agent, run } from '@openai/agents';
15 +import { z } from 'zod/v3';
16 +
17 +function requireEnv(name: 'COMPOSIO_API_KEY' | 'OPENAI_API_KEY'): string {
18 + const value = process.env[name];
19 + if (!value) {
20 + throw new Error(`Set ${name} before running this example.`);
21 + }
22 + return value;
23 +}
24 +
25 +const composioApiKey = requireEnv('COMPOSIO_API_KEY');
26 +requireEnv('OPENAI_API_KEY');
27 +
28 +const internalUsers: Record<string, Record<string, unknown>> = {
29 + 'user-1': {
30 + id: 'user-1',
31 + name: 'Ada Lovelace',
32 + email: 'ada@example.com',
33 + team: 'platform',
34 + plan: 'enterprise',
35 + },
36 + 'user-2': {
37 + id: 'user-2',
38 + name: 'Grace Hopper',
39 + email: 'grace@example.com',
40 + team: 'developer-tools',
41 + plan: 'startup',
42 + },
43 +};
44 +
45 +const lookupInternalUser = experimental_createTool('LOOKUP_INTERNAL_USER', {
46 + name: 'Lookup internal user',
47 + description: 'Look up an internal demo user profile by user ID.',
48 + preload: true,
49 + inputParams: z.object({
50 + user_id: z.string().describe('Internal user ID, for example user-1'),
51 + }),
52 + execute: async ({ user_id }) => {
53 + const user = internalUsers[user_id];
54 + if (!user) {
55 + throw new Error(`User "${user_id}" not found`);
56 + }
57 + return user;
58 + },
59 +});
60 +
61 +const searchInternalUsers = experimental_createTool('SEARCH_INTERNAL_USERS', {
62 + name: 'Search internal users',
63 + description:
64 + 'Search demo internal users by team. This custom tool is search-only because preload is not enabled.',
65 + inputParams: z.object({
66 + team: z.string().describe('Team name to search for'),
67 + }),
68 + execute: async ({ team }) => ({
69 + results: Object.values(internalUsers).filter(user => user.team === team),
70 + }),
71 +});
72 +
73 +const getAccountHealth = experimental_createTool('GET_ACCOUNT_HEALTH', {
74 + name: 'Get account health',
75 + description: 'Return internal account health details for a user.',
76 + inputParams: z.object({
77 + user_id: z.string().describe('Internal user ID'),
78 + }),
79 + execute: async ({ user_id }) => ({
80 + user_id,
81 + health: 'green',
82 + open_incidents: 0,
83 + renewal_risk: 'low',
84 + }),
85 +});
86 +
87 +const internalAdmin = experimental_createToolkit('INTERNAL_ADMIN', {
88 + name: 'Internal admin',
89 + description: 'Demo internal administration tools.',
90 + preload: true,
91 + tools: [getAccountHealth],
92 +});
93 +
94 +const composio = new Composio({
95 + apiKey: composioApiKey,
96 + baseURL: process.env.COMPOSIO_BASE_URL || undefined,
97 + provider: new OpenAIAgentsProvider(),
98 +});
99 +
100 +const session = await composio.create(`preload-example-${Date.now()}`, {
101 + toolkits: ['hackernews'],
102 + tools: {
103 + hackernews: {
104 + enable: ['HACKERNEWS_GET_USER'],
105 + },
106 + },
107 + preload: {
108 + tools: ['HACKERNEWS_GET_USER'],
109 + },
110 + manageConnections: false,
111 + experimental: {
112 + customTools: [lookupInternalUser, searchInternalUsers],
113 + customToolkits: [internalAdmin],
114 + },
115 +});
116 +
117 +const tools = await session.tools();
118 +console.log('Direct tools exposed to the agent:');
119 +for (const tool of tools) {
120 + console.log(`- ${tool.name}`);
121 +}
122 +
123 +const agent = new Agent({
124 + name: 'Preload Demo Agent',
125 + instructions:
126 + 'Use the provided direct tools. Do not search for tools first; the needed tools are already loaded.',
127 + model: process.env.OPENAI_MODEL ?? 'gpt-5.1',
128 + tools,
129 +});
130 +
131 +const prompt =
132 + process.argv.slice(2).join(' ') ||
133 + 'Look up Hacker News user "pg", then look up internal user user-1 and their account health. Summarize the useful facts.';
134 +
135 +console.log(`\nUser: ${prompt}\n`);
136 +const result = await run(agent, prompt);
137 +console.log(`Assistant: ${result.finalOutput}`);