Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
docs: rewrite custom tools with better examples, single code block
Dhawal Upadhyaydfbecb2b9fa1
diff --git a/docs/content/changelog/03-23-26-custom-tools-and-toolkits.mdx b/docs/content/changelog/03-23-26-custom-tools-and-toolkits.mdxindex 1242979a6..2fb45adbd 100644--- a/docs/content/changelog/03-23-26-custom-tools-and-toolkits.mdx+++ b/docs/content/changelog/03-23-26-custom-tools-and-toolkits.mdx@@ -16,94 +16,83 @@ You can now create custom tools and toolkits that run locally alongside remote C## What's New-### Standalone Tools--Define tools with no Composio-managed authentication using `experimental_createTool`. Just provide a slug, input schema, and an execute function:+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.```ts// @noErrors-import { experimental_createTool } from "@composio/core";+import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";import { z } from "zod/v3";-const getUser = experimental_createTool("GET_USER", {- name: "Get user",- description: "Look up an internal user by ID",- inputParams: z.object({ user_id: z.string() }),- execute: async ({ user_id }) => ({ name: "Alice", email: "[email protected]" }),+// Standalone tool — internal data, no Composio auth needed+const getUserProfile = experimental_createTool("GET_USER_PROFILE", {+ name: "Get user profile",+ description: "Retrieve the current user's profile from the internal directory",+ inputParams: z.object({}),+ execute: async (_input, ctx) => {+ // ctx.userId identifies which user's session is running+ const profiles: Record<string, { name: string; tier: string }> = {+ "user_1": { name: "Alice Johnson", tier: "enterprise" },+ };+ return profiles[ctx.userId] ?? {};+ },});-```--### Extension Tools-Tools that inherit authentication from an existing Composio toolkit via `extendsToolkit`. The execute function receives a `SessionContext` with two methods:--- **`ctx.proxyExecute()`** — make authenticated HTTP requests through Composio's auth layer-- **`ctx.execute()`** — call any Composio native tool from within your custom tool--```ts-// @noErrors-import { experimental_createTool } from "@composio/core";-import { z } from "zod/v3";--const createDraft = experimental_createTool("CREATE_DRAFT", {- name: "Create Gmail draft",- description: "Create a Gmail draft via the Gmail API",+// Extension tool — wraps Gmail with preset business logic+// Inherits auth from the session via extendsToolkit+const sendPromoEmail = experimental_createTool("SEND_PROMO_EMAIL", {+ name: "Send promo email",+ description: "Send the standard promotional email to a recipient",extendsToolkit: "gmail",- inputParams: z.object({ to: z.string(), subject: z.string(), body: z.string() }),+ inputParams: z.object({ to: z.string().describe("Recipient email") }),execute: async (input, ctx) => {+ const raw = btoa(`To: ${input.to}\r\nSubject: Try Acme Pro\r\n\r\nFree for 14 days.`);const res = await ctx.proxyExecute({toolkit: "gmail",- endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",+ endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/messages/send",method: "POST",- body: { message: { raw: btoa(`To: ${input.to}\r\nSubject: ${input.subject}\r\n\r\n${input.body}`) } },+ body: { raw },});- return res.data as Record<string, unknown>;+ return { status: res.status, to: input.to };},});-```--### Custom Toolkits--Group related tools under a namespace with `experimental_createToolkit`:-```ts-// @noErrors-import { experimental_createTool, experimental_createToolkit } from "@composio/core";-import { z } from "zod/v3";--const roleManager = experimental_createToolkit("ROLE_MANAGER", {- name: "Role Manager",- description: "Manage user roles",+// Custom toolkit — groups related tools under a namespace+const userManagement = experimental_createToolkit("USER_MANAGEMENT", {+ name: "User management",+ description: "Manage user roles and permissions",tools: [- experimental_createTool("SET_ROLE", {- name: "Set role",- description: "Set a user's role",- inputParams: z.object({ user_id: z.string(), role: z.enum(["admin", "developer", "viewer"]) }),- execute: async ({ user_id, role }) => ({ user_id, role, updated: true }),+ experimental_createTool("ASSIGN_ROLE", {+ name: "Assign role",+ description: "Assign a role to a user in the internal system",+ inputParams: z.object({+ user_id: z.string().describe("Target user ID"),+ role: z.enum(["admin", "editor", "viewer"]).describe("Role to assign"),+ }),+ execute: async ({ user_id, role }) => ({ user_id, role, assigned: true }),}),],});-```--### Binding to a Session--Pass custom tools and toolkits via the `experimental` option when creating a session:-```ts-// @noErrors-import { Composio } from "@composio/core";--const session = await new Composio().create("user_123", {+// Bind everything to a session+const session = await new Composio().create("user_1", {toolkits: ["gmail"],experimental: {- customTools: [getUser, createDraft],- customToolkits: [roleManager],+ customTools: [getUserProfile, sendPromoEmail],+ customToolkits: [userManagement],},});const tools = await session.tools(); // Includes both remote and custom tools```+### SessionContext++Every custom tool's `execute` receives `(input, ctx)`:++- **`ctx.userId`** — the user ID for the current session+- **`ctx.proxyExecute(params)`** — authenticated HTTP request via Composio's auth layer+- **`ctx.execute(toolSlug, args)`** — execute any Composio native tool from within your custom tool+---## Limitationsdiff --git a/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx b/docs/content/docs/toolkits/custom-tools-and-toolkits.mdxindex 15dc2f924..994c682a8 100644--- a/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx+++ b/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx@@ -12,115 +12,117 @@ Custom tools are experimental. The `experimental_` prefix and `experimental` sesCustom tools work with **native tools** (`session.tools()`). MCP support is coming soon.</Callout>-Custom tools let you define local tools that run in-process alongside remote Composio tools within a session.+Custom tools let you define tools that run in-process alongside remote Composio tools within a session. There are three patterns:-## Standalone tool+- **Standalone tools** — for internal app logic that doesn't need Composio auth (DB lookups, in-memory data, business rules)+- **Extension tools** — wrap a Composio toolkit's API with custom business logic via `extendsToolkit`, using `ctx.proxyExecute()` for authenticated requests+- **Custom toolkits** — group related standalone tools under a namespace-A tool with no Composio-managed authentication:+The example below defines one of each and binds them to a session:```typescript-import { experimental_createTool } from "@composio/core";+import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";import { z } from "zod/v3";// ---cut----const getUser = experimental_createTool("GET_USER", {- name: "Get user",- description: "Look up an internal user by ID",- inputParams: z.object({- user_id: z.string().describe("User ID"),- }),- execute: async ({ user_id }) => {- return { name: "Alice", email: "[email protected]" };++// ── Standalone tool ─────────────────────────────────────────────+// Internal data lookup — no Composio auth needed.+// ctx.userId identifies which user's session is running.++const profiles: Record<string, { name: string; email: string; tier: string }> = {+ "user_1": { name: "Alice Johnson", email: "[email protected]", tier: "enterprise" },+ "user_2": { name: "Bob Smith", email: "[email protected]", tier: "free" },+};++const getUserProfile = experimental_createTool("GET_USER_PROFILE", {+ name: "Get user profile",+ description: "Retrieve the current user's profile from the internal directory",+ inputParams: z.object({}),+ execute: async (_input, ctx) => {+ const profile = profiles[ctx.userId];+ if (!profile) throw new Error(`No profile found for user "${ctx.userId}"`);+ return profile;},});-```-## Extension tool+// ── Extension tool ──────────────────────────────────────────────+// Wraps Gmail API with business logic. Inherits Gmail auth from the session+// via extendsToolkit, so ctx.proxyExecute() handles credentials automatically.+// This constrains the agent to send only the approved promo template.-Inherits authentication from an existing Composio toolkit via `extendsToolkit`. The second argument to `execute` is a `SessionContext` for authenticated API calls:--```typescript-import { experimental_createTool } from "@composio/core";-import { z } from "zod/v3";-// ---cut----const createDraft = experimental_createTool("CREATE_DRAFT", {- name: "Create Gmail draft",- description: "Create a Gmail draft via the Gmail API",+const sendPromoEmail = experimental_createTool("SEND_PROMO_EMAIL", {+ name: "Send promo email",+ description: "Send the standard promotional email to a recipient",extendsToolkit: "gmail",inputParams: z.object({- to: z.string().describe("Recipient email"),- subject: z.string().describe("Email subject"),- body: z.string().describe("Email body"),+ to: z.string().describe("Recipient email address"),}),execute: async (input, ctx) => {+ const subject = "You're invited to try Acme Pro";+ const body = "Hi there,\n\nWe'd love for you to try Acme Pro — free for 14 days.\n\nBest,\nThe Acme Team";+ const raw = btoa(`To: ${input.to}\r\nSubject: ${subject}\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\n${body}`);+const res = await ctx.proxyExecute({toolkit: "gmail",- endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/drafts",+ endpoint: "https://gmail.googleapis.com/gmail/v1/users/me/messages/send",method: "POST",- body: { message: { raw: btoa(`To: ${input.to}\r\nSubject: ${input.subject}\r\n\r\n${input.body}`) } },+ body: { raw },});- return res.data as Record<string, unknown>;+ return { status: res.status, to: input.to };},});-```--### SessionContext--| Method | Description |-|--------|-------------|-| `ctx.proxyExecute(params)` | Authenticated HTTP request via Composio's auth layer. Params: `toolkit`, `endpoint`, `method`, `body?`, `parameters?` (array of `{ in: "query" \| "header", name, value }`). |-| `ctx.execute(toolSlug, args)` | Execute any Composio native tool from within your custom tool. |--## Custom toolkit-Group related tools under a namespace. Tools inside a toolkit must **not** use `extendsToolkit` — they inherit the toolkit identity instead:--```typescript-import { experimental_createTool, experimental_createToolkit } from "@composio/core";-import { z } from "zod/v3";-// ---cut----const setRole = experimental_createTool("SET_ROLE", {- name: "Set role",- description: "Set a user's role",- inputParams: z.object({- user_id: z.string().describe("User ID"),- role: z.enum(["admin", "developer", "viewer"]).describe("New role"),- }),- execute: async ({ user_id, role }) => ({ user_id, role, updated: true }),-});--const roleManager = experimental_createToolkit("ROLE_MANAGER", {- name: "Role Manager",- description: "Manage user roles",- tools: [setRole],+// ── Custom toolkit ──────────────────────────────────────────────+// Groups related tools under a namespace.+// Tools inside a toolkit must NOT use extendsToolkit — they inherit+// the toolkit identity instead.++const userManagement = experimental_createToolkit("USER_MANAGEMENT", {+ name: "User management",+ description: "Manage user roles and permissions",+ tools: [+ experimental_createTool("ASSIGN_ROLE", {+ name: "Assign role",+ description: "Assign a role to a user in the internal system",+ inputParams: z.object({+ user_id: z.string().describe("Target user ID"),+ role: z.enum(["admin", "editor", "viewer"]).describe("Role to assign"),+ }),+ execute: async ({ user_id, role }) => ({ user_id, role, assigned: true }),+ }),+ ],});-```-## Binding to a session+// ── Bind to session ─────────────────────────────────────────────+// Pass custom tools and toolkits via the experimental option.+// session.tools() returns both remote Composio tools and your custom tools.-Pass custom tools and toolkits via the `experimental` option:+const composio = new Composio({ apiKey: "your_api_key" });-```typescript-import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";-import { z } from "zod/v3";--const getUser = experimental_createTool("GET_USER", { name: "Get user", description: "Look up user", inputParams: z.object({ user_id: z.string() }), execute: async () => ({ name: "Alice" }) });-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>; } });-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 }) })] });-const composio = new Composio({ apiKey: 'your_api_key' });-// ---cut----const session = await composio.create("user_123", {+const session = await composio.create("user_1", {toolkits: ["gmail"],experimental: {- customTools: [getUser, createDraft],- customToolkits: [roleManager],+ customTools: [getUserProfile, sendPromoEmail],+ customToolkits: [userManagement],},});-const tools = await session.tools(); // Includes both remote and custom tools+const tools = await session.tools();```+## SessionContext++Every custom tool's `execute` function receives `(input, ctx)`. The `ctx` object provides:++| Method | Description |+|--------|-------------|+| `ctx.userId` | The user ID for the current session. |+| `ctx.proxyExecute(params)` | Authenticated HTTP request via Composio's auth layer. Params: `toolkit`, `endpoint`, `method`, `body?`, `parameters?` (array of `{ in: "query" \| "header", name, value }`). |+| `ctx.execute(toolSlug, args)` | Execute any Composio native tool from within your custom tool. |+## Slug rules-- Slugs are auto-prefixed with `LOCAL_` (e.g. `GET_USER` → `LOCAL_GET_USER`, `LOCAL_ROLE_MANAGER_SET_ROLE`)+- Slugs are auto-prefixed with `LOCAL_` (e.g. `GET_USER_PROFILE` → `LOCAL_GET_USER_PROFILE`)+- Toolkit tools get both prefixes (e.g. `LOCAL_USER_MANAGEMENT_ASSIGN_ROLE`)- Max 60 characters after prefixing- Cannot start with `LOCAL_` or `COMPOSIO_`