@devries-cameron20 / composio-1 / commits / de88244c6
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.

chore: update custom-tools example with multi-task prompt and logging

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 18, 2026 at 16:22 UTC de88244c629f0854ab04fc17799d05e7d390cabc
1 file changed +71 -23
ts/examples/tool-router/src/custom-tools.ts
+71 -23
@@ -5,6 +5,11 @@
5 * remote Composio tools. Includes a tool that calls the Gmail API
6 * directly via ctx.proxyExecute().
7 *
8 + * Three tool types demonstrated:
9 + * 1. Standalone — no auth, pure local logic
10 + * 2. Extension — inherits auth from a Composio toolkit (Gmail)
11 + * 3. Toolkit — groups related tools under a namespace
12 + *
13 * Usage:
14 * COMPOSIO_API_KEY=... OPENAI_API_KEY=... bun src/custom-tools.ts
15 */
@@ -14,16 +19,16 @@ import { OpenAIAgentsProvider } from "@composio/openai-agents";
19 import { Agent, run } from "@openai/agents";
20 import { z } from "zod/v3";
21
17 -// ── Custom tools ────────────────────────────────────────────────
22 +// ── 1. Standalone tool (no auth) ────────────────────────────────
23
19 -/** Standalone tool (no auth needed) */
24 const getUser = experimental_createTool("GET_USER", {
25 name: "Get user",
22 - description: "Look up an internal user by ID",
26 + description: "Look up an internal user by ID. Returns name, email, and role.",
27 inputParams: z.object({
24 - user_id: z.string().describe("User ID (e.g. user-1)"),
28 + user_id: z.string().describe("User ID (e.g. user-1, user-2)"),
29 }),
30 execute: async ({ user_id }) => {
31 + // In a real app, this would query your database
32 const users: Record<string, Record<string, string>> = {
33 "user-1": { name: "Alice Johnson", email: "alice@acme.com", role: "admin" },
34 "user-2": { name: "Bob Smith", email: "bob@acme.com", role: "developer" },
@@ -34,46 +39,61 @@ const getUser = experimental_createTool("GET_USER", {
39 },
40 });
41
37 -/** Extension tool — inherits Gmail auth, calls the real API via proxy */
38 -const createDraft = experimental_createTool("CREATE_DRAFT", {
39 - name: "Create Gmail draft",
40 - description: "Create a real Gmail draft via the Gmail API. Appears in the user's drafts folder.",
42 +// ── 2. Extension tool (inherits Gmail auth via proxy execute) ───
43 +
44 +const sendCompanyEmail = experimental_createTool("SEND_COMPANY_EMAIL", {
45 + name: "Send company formatted email",
46 + description:
47 + "Draft a company-branded email via Gmail. Adds a standard signature " +
48 + "and formats the body with the company template. The draft appears " +
49 + "in the authenticated user's Gmail drafts folder.",
50 extendsToolkit: "gmail",
51 inputParams: z.object({
52 to: z.string().describe("Recipient email address"),
53 subject: z.string().describe("Email subject"),
45 - body: z.string().describe("Email body (plain text)"),
54 + body: z.string().describe("Email body content (plain text)"),
55 }),
56 execute: async (input, ctx) => {
48 - const raw = Buffer.from(
49 - `To: ${input.to}\r\nSubject: ${input.subject}\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n${input.body}`
50 - )
57 + // Add company branding to the email
58 + const branded = [
59 + input.body,
60 + "",
61 + "---",
62 + "Sent via Acme Corp Internal Tools",
63 + `Drafted by: ${ctx.userId}`,
64 + ].join("\r\n");
65 +
66 + // Build RFC 2822 email and base64url encode
67 + const rawEmail = `To: ${input.to}\r\nSubject: ${input.subject}\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n${branded}`;
68 + const encoded = Buffer.from(rawEmail)
69 .toString("base64")
70 .replace(/\+/g, "-")
71 .replace(/\//g, "_")
72 .replace(/=+$/, "");
73
74 + // Create draft via Gmail API using session's auth
75 const res = await ctx.proxyExecute({
76 toolkit: "gmail",
77 endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",
78 method: "POST",
60 - body: { message: { raw } },
79 + body: { message: { raw: encoded } },
80 });
81
82 if (res.status !== 200) throw new Error(`Gmail API error ${res.status}`);
83 const data = res.data as { id: string; message: { id: string } };
65 - return { draft_id: data.id, message_id: data.message.id, to: input.to, subject: input.subject };
84 + return { draft_id: data.id, to: input.to, subject: input.subject };
85 },
86 });
87
69 -/** Custom toolkit — groups related tools under one namespace */
88 +// ── 3. Custom toolkit (groups tools under a namespace) ──────────
89 +
90 const roleManager = experimental_createToolkit("ROLE_MANAGER", {
91 name: "Role Manager",
72 - description: "Manage user roles",
92 + description: "Manage internal user roles and permissions",
93 tools: [
94 experimental_createTool("SET_ROLE", {
95 name: "Set role",
76 - description: "Set a user's role",
96 + description: "Assign a new role to a user",
97 inputParams: z.object({
98 user_id: z.string().describe("User ID"),
99 role: z.enum(["admin", "developer", "viewer"]).describe("New role"),
@@ -83,20 +103,24 @@ const roleManager = experimental_createToolkit("ROLE_MANAGER", {
103 ],
104 });
105
86 -// ── Agent ────────────────────────────────────────────────────────
106 +// ── Agent setup ─────────────────────────────────────────────────
107
108 const composio = new Composio({
109 provider: new OpenAIAgentsProvider(),
110 });
111
92 -const session = await composio.create("default", {
93 - toolkits: ["gmail"],
112 +const session = await composio.create(process.env.COMPOSIO_USER_ID ?? "default", {
113 + toolkits: ["gmail", "weathermap"],
114 experimental: {
95 - customTools: [getUser, createDraft],
115 + customTools: [getUser, sendCompanyEmail],
116 customToolkits: [roleManager],
117 },
118 });
119
120 +console.log(`Session: ${session.sessionId}`);
121 +console.log("Custom tools:", session.customTools().map(t => t.slug).join(", "));
122 +console.log();
123 +
124 const tools = await session.tools();
125
126 const agent = new Agent({
@@ -108,8 +132,32 @@ const agent = new Agent({
132 tools,
133 });
134
111 -const prompt = process.argv[2] ?? "Get user-1's info and draft an email to them saying hello";
135 +// Tool call logging
136 +agent.on("agent_tool_start", (_ctx, tool, details: Record<string, unknown>) => {
137 + const input = (details as { toolCall?: { arguments?: unknown } }).toolCall?.arguments ?? {};
138 + const json = JSON.stringify(typeof input === "string" ? JSON.parse(input) : input, null, 2);
139 + console.log(`\n ┌─ ${tool.name}`);
140 + console.log(` │ INPUT: ${json.length > 500 ? json.slice(0, 500) + "..." : json}`);
141 +});
142 +agent.on("agent_tool_end", (_ctx, tool, result: unknown) => {
143 + let output: unknown;
144 + try { output = typeof result === "string" ? JSON.parse(result as string) : result; } catch { output = result; }
145 + const json = JSON.stringify(output, null, 2);
146 + console.log(` │ OUTPUT: ${json.length > 500 ? json.slice(0, 500) + "..." : json}`);
147 + console.log(` └─ ${tool.name} done`);
148 +});
149 +
150 +// Multi-task prompt that exercises all tool types:
151 +// - Standalone local tool (get user)
152 +// - Toolkit local tool (set role)
153 +// - Remote Composio tool (weather)
154 +// - Extension local tool with proxy execute (company email)
155 +const prompt = process.argv[2] ?? `Do all of these:
156 +1. Look up user-1's profile
157 +2. Promote user-2 to admin
158 +3. What's the weather in Tokyo right now?
159 +4. Send a company formatted email to myself summarizing the above results`;
160
161 console.log(`> ${prompt}\n`);
162 const result = await run(agent, prompt);
115 -console.log(result.finalOutput);
163 +console.log(`\n${result.finalOutput}`);