@devries-cameron20 / composio Mirror · read-only / commits / dfbecb2b9
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 22, 02:00 UTC

docs: rewrite custom tools with better examples, single code block

- Standalone tool uses ctx.userId for internal profile lookup - Extension tool sends preset promo email (not generic draft) - Custom toolkit groups user management operations - Single continuous code block: define → bind → use - Same treatment in changelog - Added ctx.userId to SessionContext table Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

Dhawal Upadhyay committed Mar 23, 2026 at 14:08 UTC dfbecb2b9fa1a175dc94a49c1826ce015e82855f
2 files changed +126 -135
docs/content/changelog/03-23-26-custom-tools-and-toolkits.mdx
+48 -59
@@ -16,94 +16,83 @@ You can now create custom tools and toolkits that run locally alongside remote C
16
17 ## What's New
18
19 -### Standalone Tools
20 -
21 -Define tools with no Composio-managed authentication using `experimental_createTool`. Just provide a slug, input schema, and an execute function:
19 +Custom tools support three patterns — standalone tools for internal logic, extension tools that wrap Composio toolkit APIs with business logic, and custom toolkits that group related tools.
20
21 ```ts
22 // @noErrors
25 -import { experimental_createTool } from "@composio/core";
23 +import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
24 import { z } from "zod/v3";
25
28 -const getUser = experimental_createTool("GET_USER", {
29 - name: "Get user",
30 - description: "Look up an internal user by ID",
31 - inputParams: z.object({ user_id: z.string() }),
32 - execute: async ({ user_id }) => ({ name: "Alice", email: "alice@acme.com" }),
26 +// Standalone tool — internal data, no Composio auth needed
27 +const getUserProfile = experimental_createTool("GET_USER_PROFILE", {
28 + name: "Get user profile",
29 + description: "Retrieve the current user's profile from the internal directory",
30 + inputParams: z.object({}),
31 + execute: async (_input, ctx) => {
32 + // ctx.userId identifies which user's session is running
33 + const profiles: Record<string, { name: string; tier: string }> = {
34 + "user_1": { name: "Alice Johnson", tier: "enterprise" },
35 + };
36 + return profiles[ctx.userId] ?? {};
37 + },
38 });
34 -```
35 -
36 -### Extension Tools
39
38 -Tools that inherit authentication from an existing Composio toolkit via `extendsToolkit`. The execute function receives a `SessionContext` with two methods:
39 -
40 -- **`ctx.proxyExecute()`** — make authenticated HTTP requests through Composio's auth layer
41 -- **`ctx.execute()`** — call any Composio native tool from within your custom tool
42 -
43 -```ts
44 -// @noErrors
45 -import { experimental_createTool } from "@composio/core";
46 -import { z } from "zod/v3";
47 -
48 -const createDraft = experimental_createTool("CREATE_DRAFT", {
49 - name: "Create Gmail draft",
50 - description: "Create a Gmail draft via the Gmail API",
40 +// Extension tool — wraps Gmail with preset business logic
41 +// Inherits auth from the session via extendsToolkit
42 +const sendPromoEmail = experimental_createTool("SEND_PROMO_EMAIL", {
43 + name: "Send promo email",
44 + description: "Send the standard promotional email to a recipient",
45 extendsToolkit: "gmail",
52 - inputParams: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
46 + inputParams: z.object({ to: z.string().describe("Recipient email") }),
47 execute: async (input, ctx) => {
48 + const raw = btoa(`To: ${input.to}\r\nSubject: Try Acme Pro\r\n\r\nFree for 14 days.`);
49 const res = await ctx.proxyExecute({
50 toolkit: "gmail",
56 - endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",
51 + endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
52 method: "POST",
58 - body: { message: { raw: btoa(`To: ${input.to}\r\nSubject: ${input.subject}\r\n\r\n${input.body}`) } },
53 + body: { raw },
54 });
60 - return res.data as Record<string, unknown>;
55 + return { status: res.status, to: input.to };
56 },
57 });
63 -```
64 -
65 -### Custom Toolkits
66 -
67 -Group related tools under a namespace with `experimental_createToolkit`:
58
69 -```ts
70 -// @noErrors
71 -import { experimental_createTool, experimental_createToolkit } from "@composio/core";
72 -import { z } from "zod/v3";
73 -
74 -const roleManager = experimental_createToolkit("ROLE_MANAGER", {
75 - name: "Role Manager",
76 - description: "Manage user roles",
59 +// Custom toolkit — groups related tools under a namespace
60 +const userManagement = experimental_createToolkit("USER_MANAGEMENT", {
61 + name: "User management",
62 + description: "Manage user roles and permissions",
63 tools: [
78 - experimental_createTool("SET_ROLE", {
79 - name: "Set role",
80 - description: "Set a user's role",
81 - inputParams: z.object({ user_id: z.string(), role: z.enum(["admin", "developer", "viewer"]) }),
82 - execute: async ({ user_id, role }) => ({ user_id, role, updated: true }),
64 + experimental_createTool("ASSIGN_ROLE", {
65 + name: "Assign role",
66 + description: "Assign a role to a user in the internal system",
67 + inputParams: z.object({
68 + user_id: z.string().describe("Target user ID"),
69 + role: z.enum(["admin", "editor", "viewer"]).describe("Role to assign"),
70 + }),
71 + execute: async ({ user_id, role }) => ({ user_id, role, assigned: true }),
72 }),
73 ],
74 });
86 -```
87 -
88 -### Binding to a Session
89 -
90 -Pass custom tools and toolkits via the `experimental` option when creating a session:
75
92 -```ts
93 -// @noErrors
94 -import { Composio } from "@composio/core";
95 -
96 -const session = await new Composio().create("user_123", {
76 +// Bind everything to a session
77 +const session = await new Composio().create("user_1", {
78 toolkits: ["gmail"],
79 experimental: {
99 - customTools: [getUser, createDraft],
100 - customToolkits: [roleManager],
80 + customTools: [getUserProfile, sendPromoEmail],
81 + customToolkits: [userManagement],
82 },
83 });
84
85 const tools = await session.tools(); // Includes both remote and custom tools
86 ```
87
88 +### SessionContext
89 +
90 +Every custom tool's `execute` receives `(input, ctx)`:
91 +
92 +- **`ctx.userId`** — the user ID for the current session
93 +- **`ctx.proxyExecute(params)`** — authenticated HTTP request via Composio's auth layer
94 +- **`ctx.execute(toolSlug, args)`** — execute any Composio native tool from within your custom tool
95 +
96 ---
97
98 ## Limitations
docs/content/docs/toolkits/custom-tools-and-toolkits.mdx
+78 -76
@@ -12,115 +12,117 @@ Custom tools are experimental. The `experimental_` prefix and `experimental` ses
12 Custom tools work with **native tools** (`session.tools()`). MCP support is coming soon.
13 </Callout>
14
15 -Custom tools let you define local tools that run in-process alongside remote Composio tools within a session.
15 +Custom tools let you define tools that run in-process alongside remote Composio tools within a session. There are three patterns:
16
17 -## Standalone tool
17 +- **Standalone tools** — for internal app logic that doesn't need Composio auth (DB lookups, in-memory data, business rules)
18 +- **Extension tools** — wrap a Composio toolkit's API with custom business logic via `extendsToolkit`, using `ctx.proxyExecute()` for authenticated requests
19 +- **Custom toolkits** — group related standalone tools under a namespace
20
19 -A tool with no Composio-managed authentication:
21 +The example below defines one of each and binds them to a session:
22
23 ```typescript
22 -import { experimental_createTool } from "@composio/core";
24 +import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
25 import { z } from "zod/v3";
26 // ---cut---
25 -const getUser = experimental_createTool("GET_USER", {
26 - name: "Get user",
27 - description: "Look up an internal user by ID",
28 - inputParams: z.object({
29 - user_id: z.string().describe("User ID"),
30 - }),
31 - execute: async ({ user_id }) => {
32 - return { name: "Alice", email: "alice@acme.com" };
27 +
28 +// ── Standalone tool ─────────────────────────────────────────────
29 +// Internal data lookup — no Composio auth needed.
30 +// ctx.userId identifies which user's session is running.
31 +
32 +const profiles: Record<string, { name: string; email: string; tier: string }> = {
33 + "user_1": { name: "Alice Johnson", email: "alice@acme.com", tier: "enterprise" },
34 + "user_2": { name: "Bob Smith", email: "bob@acme.com", tier: "free" },
35 +};
36 +
37 +const getUserProfile = experimental_createTool("GET_USER_PROFILE", {
38 + name: "Get user profile",
39 + description: "Retrieve the current user's profile from the internal directory",
40 + inputParams: z.object({}),
41 + execute: async (_input, ctx) => {
42 + const profile = profiles[ctx.userId];
43 + if (!profile) throw new Error(`No profile found for user "${ctx.userId}"`);
44 + return profile;
45 },
46 });
35 -```
47
37 -## Extension tool
48 +// ── Extension tool ──────────────────────────────────────────────
49 +// Wraps Gmail API with business logic. Inherits Gmail auth from the session
50 +// via extendsToolkit, so ctx.proxyExecute() handles credentials automatically.
51 +// This constrains the agent to send only the approved promo template.
52
39 -Inherits authentication from an existing Composio toolkit via `extendsToolkit`. The second argument to `execute` is a `SessionContext` for authenticated API calls:
40 -
41 -```typescript
42 -import { experimental_createTool } from "@composio/core";
43 -import { z } from "zod/v3";
44 -// ---cut---
45 -const createDraft = experimental_createTool("CREATE_DRAFT", {
46 - name: "Create Gmail draft",
47 - description: "Create a Gmail draft via the Gmail API",
53 +const sendPromoEmail = experimental_createTool("SEND_PROMO_EMAIL", {
54 + name: "Send promo email",
55 + description: "Send the standard promotional email to a recipient",
56 extendsToolkit: "gmail",
57 inputParams: z.object({
50 - to: z.string().describe("Recipient email"),
51 - subject: z.string().describe("Email subject"),
52 - body: z.string().describe("Email body"),
58 + to: z.string().describe("Recipient email address"),
59 }),
60 execute: async (input, ctx) => {
61 + const subject = "You're invited to try Acme Pro";
62 + const body = "Hi there,\n\nWe'd love for you to try Acme Pro — free for 14 days.\n\nBest,\nThe Acme Team";
63 + const raw = btoa(`To: ${input.to}\r\nSubject: ${subject}\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n${body}`);
64 +
65 const res = await ctx.proxyExecute({
66 toolkit: "gmail",
57 - endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",
67 + endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
68 method: "POST",
59 - body: { message: { raw: btoa(`To: ${input.to}\r\nSubject: ${input.subject}\r\n\r\n${input.body}`) } },
69 + body: { raw },
70 });
61 - return res.data as Record<string, unknown>;
71 + return { status: res.status, to: input.to };
72 },
73 });
64 -```
65 -
66 -### SessionContext
67 -
68 -| Method | Description |
69 -|--------|-------------|
70 -| `ctx.proxyExecute(params)` | Authenticated HTTP request via Composio's auth layer. Params: `toolkit`, `endpoint`, `method`, `body?`, `parameters?` (array of `{ in: "query" \| "header", name, value }`). |
71 -| `ctx.execute(toolSlug, args)` | Execute any Composio native tool from within your custom tool. |
72 -
73 -## Custom toolkit
74
75 -Group related tools under a namespace. Tools inside a toolkit must **not** use `extendsToolkit` — they inherit the toolkit identity instead:
76 -
77 -```typescript
78 -import { experimental_createTool, experimental_createToolkit } from "@composio/core";
79 -import { z } from "zod/v3";
80 -// ---cut---
81 -const setRole = experimental_createTool("SET_ROLE", {
82 - name: "Set role",
83 - description: "Set a user's role",
84 - inputParams: z.object({
85 - user_id: z.string().describe("User ID"),
86 - role: z.enum(["admin", "developer", "viewer"]).describe("New role"),
87 - }),
88 - execute: async ({ user_id, role }) => ({ user_id, role, updated: true }),
89 -});
90 -
91 -const roleManager = experimental_createToolkit("ROLE_MANAGER", {
92 - name: "Role Manager",
93 - description: "Manage user roles",
94 - tools: [setRole],
75 +// ── Custom toolkit ──────────────────────────────────────────────
76 +// Groups related tools under a namespace.
77 +// Tools inside a toolkit must NOT use extendsToolkit — they inherit
78 +// the toolkit identity instead.
79 +
80 +const userManagement = experimental_createToolkit("USER_MANAGEMENT", {
81 + name: "User management",
82 + description: "Manage user roles and permissions",
83 + tools: [
84 + experimental_createTool("ASSIGN_ROLE", {
85 + name: "Assign role",
86 + description: "Assign a role to a user in the internal system",
87 + inputParams: z.object({
88 + user_id: z.string().describe("Target user ID"),
89 + role: z.enum(["admin", "editor", "viewer"]).describe("Role to assign"),
90 + }),
91 + execute: async ({ user_id, role }) => ({ user_id, role, assigned: true }),
92 + }),
93 + ],
94 });
96 -```
95
98 -## Binding to a session
96 +// ── Bind to session ─────────────────────────────────────────────
97 +// Pass custom tools and toolkits via the experimental option.
98 +// session.tools() returns both remote Composio tools and your custom tools.
99
100 -Pass custom tools and toolkits via the `experimental` option:
100 +const composio = new Composio({ apiKey: "your_api_key" });
101
102 -```typescript
103 -import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
104 -import { z } from "zod/v3";
105 -
106 -const getUser = experimental_createTool("GET_USER", { name: "Get user", description: "Look up user", inputParams: z.object({ user_id: z.string() }), execute: async () => ({ name: "Alice" }) });
107 -const createDraft = experimental_createTool("CREATE_DRAFT", { name: "Create draft", description: "Create draft", extendsToolkit: "gmail", inputParams: z.object({ to: z.string() }), execute: async (input, ctx) => { const res = await ctx.proxyExecute({ toolkit: "gmail", endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts", method: "POST", body: {} }); return res.data as Record<string, unknown>; } });
108 -const roleManager = experimental_createToolkit("ROLE_MANAGER", { name: "Role Manager", description: "Manage roles", tools: [experimental_createTool("SET_ROLE", { name: "Set role", description: "Set role", inputParams: z.object({ user_id: z.string() }), execute: async () => ({ updated: true }) })] });
109 -const composio = new Composio({ apiKey: 'your_api_key' });
110 -// ---cut---
111 -const session = await composio.create("user_123", {
102 +const session = await composio.create("user_1", {
103 toolkits: ["gmail"],
104 experimental: {
114 - customTools: [getUser, createDraft],
115 - customToolkits: [roleManager],
105 + customTools: [getUserProfile, sendPromoEmail],
106 + customToolkits: [userManagement],
107 },
108 });
109
119 -const tools = await session.tools(); // Includes both remote and custom tools
110 +const tools = await session.tools();
111 ```
112
113 +## SessionContext
114 +
115 +Every custom tool's `execute` function receives `(input, ctx)`. The `ctx` object provides:
116 +
117 +| Method | Description |
118 +|--------|-------------|
119 +| `ctx.userId` | The user ID for the current session. |
120 +| `ctx.proxyExecute(params)` | Authenticated HTTP request via Composio's auth layer. Params: `toolkit`, `endpoint`, `method`, `body?`, `parameters?` (array of `{ in: "query" \| "header", name, value }`). |
121 +| `ctx.execute(toolSlug, args)` | Execute any Composio native tool from within your custom tool. |
122 +
123 ## Slug rules
124
124 -- Slugs are auto-prefixed with `LOCAL_` (e.g. `GET_USER` → `LOCAL_GET_USER`, `LOCAL_ROLE_MANAGER_SET_ROLE`)
125 +- Slugs are auto-prefixed with `LOCAL_` (e.g. `GET_USER_PROFILE` → `LOCAL_GET_USER_PROFILE`)
126 +- Toolkit tools get both prefixes (e.g. `LOCAL_USER_MANAGEMENT_ASSIGN_ROLE`)
127 - Max 60 characters after prefixing
128 - Cannot start with `LOCAL_` or `COMPOSIO_`