# Custom Tools and Toolkits (Experimental) (/docs/toolkits/custom-tools-and-toolkits)

> Custom tools are experimental. The `experimental_` prefix and `experimental` session option may change in future releases. TypeScript only.

> Custom tools work with **native tools** (`session.tools()`). MCP support is coming soon — custom tools are not available via the MCP server URL yet.

Custom tools let you define tools that run in-process alongside remote Composio tools within a session. There are three patterns:

* **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

The example below defines one of each and binds them to a session:

```typescript
import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
import { z } from "zod/v3";

// ── 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: "alice@myapp.com", tier: "enterprise" },
  "user_2": { name: "Bob Smith", email: "bob@myapp.com", 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 ──────────────────────────────────────────────
// Wraps Gmail API with business logic. Inherits auth via extendsToolkit,
// so ctx.proxyExecute() handles credentials automatically.
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 address"),
  }),
  execute: async (input, ctx) => {
    const subject = "You're invited to try MyApp Pro";
    const body = "Hi there,\n\nWe'd love for you to try MyApp Pro — free for 14 days.\n\nBest,\nThe MyApp 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/messages/send",
      method: "POST",
      body: { raw },
    });
    return { status: res.status, to: input.to };
  },
});

// ── Custom toolkit ──────────────────────────────────────────────
// Groups standalone tools that don't need Composio auth under a toolkit.
// Tools inside a toolkit cannot use extendsToolkit.
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 }),
    }),
  ],
});

// ── Bind to session ─────────────────────────────────────────────
// Pass custom tools and toolkits via the experimental option.
// session.tools() returns both remote Composio tools and your custom tools.
const composio = new Composio({ apiKey: "your_api_key" });

const session = await composio.create("user_1", {
  toolkits: ["gmail"],
  experimental: {
    customTools: [getUserProfile, sendPromoEmail],
    customToolkits: [userManagement],
  },
});

const tools = await session.tools();
```

# How custom tools work with meta tools

Custom tools integrate seamlessly with Composio's meta tools:

* **`COMPOSIO_SEARCH_TOOLS`** automatically includes your custom tools and toolkits in search results, giving slight priority to tools that don't require auth or are already connected
* **`COMPOSIO_GET_TOOL_SCHEMAS`** returns schemas for custom tools alongside remote tools — the agent sees them as first-class tools
* **`COMPOSIO_MULTI_EXECUTE_TOOL`** intelligently splits execution — custom tools run in-process while remote tools go to the backend, results are merged transparently
* **`COMPOSIO_MANAGE_CONNECTIONS`** handles auth for extension tools — if a tool extends `gmail`, the agent can prompt the user to connect Gmail just like any other toolkit
* Custom tools are **not supported in Workbench** — the LLM is made aware of this and will not attempt to use them there

# Best practices

* **Descriptive names and slugs** — The agent sees your tool's name and description to decide when to use it. Be specific: "Send weekly promo email" is better than "Send email". Slugs should be uppercase with underscores: `SEND_PROMO_EMAIL`.
* **Detailed descriptions** — Include what the tool does, when to use it, and what it returns. The agent relies on this to pick the right tool.
* **Use `extendsToolkit` for auth** — If your tool needs Gmail/GitHub/etc. auth for `ctx.proxyExecute()` or `ctx.execute()`, set `extendsToolkit` so connection management is handled seamlessly via `COMPOSIO_MANAGE_CONNECTIONS`.
* **Tool names get prefixed** — Slugs exposed to the agent are automatically prefixed with `LOCAL_` and the toolkit name (if any). `GET_USER_PROFILE` becomes `LOCAL_GET_USER_PROFILE`, `ASSIGN_ROLE` in `USER_MANAGEMENT` becomes `LOCAL_USER_MANAGEMENT_ASSIGN_ROLE`. Your slugs cannot start with `LOCAL_` — this prefix is reserved.

For more best practices, see [How to Build Tools for AI Agents: A Field Guide](https://composio.dev/blog/how-to-build-tools-for-ai-agents-a-field-guide).

# Verifying registration

Use `session.customTools()` to list registered tools (with their final `LOCAL_` prefixed slugs), or filter by toolkit with `session.customTools({ toolkit: "USER_MANAGEMENT" })`. Use `session.customToolkits()` to list registered toolkits.

# Programmatic execution

Use `session.execute()` to run custom tools directly, outside of an agent loop (e.g. `session.execute("GET_USER_PROFILE")`). Custom tools execute in-process; remote tools are sent to the backend automatically.

# 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.                                                                                                               |

---

📚 **More documentation:** [View all docs](https://docs.composio.dev/llms.txt) | [Glossary](https://docs.composio.dev/llms.mdx/docs/glossary) | [Cookbooks](https://docs.composio.dev/llms.mdx/cookbooks) | [API Reference](https://docs.composio.dev/llms.mdx/reference)

---

# Composio SDK — Instructions for AI Code Generators

**Purpose:** Enforce only the **current** and **correct** patterns for integrating [Composio](https://composio.dev/) tools into AI agents.
**Scope:** All AI-generated code using Composio must follow these guardrails.

---

## 1. Correct Composio Integration

Composio supports two integration modes: **Native Tools** (with a provider package) and **MCP** (no provider package needed).

### Native Tools

```python
# ✅ CORRECT — Python (defaults to OpenAI)
from composio import Composio

composio = Composio()
session = composio.create(user_id="user_123")
tools = session.tools()
# Pass tools to your agent/LLM framework
```

```typescript
// ✅ CORRECT — TypeScript (defaults to OpenAI)
import { Composio } from "@composio/core";

const composio = new Composio();
const session = await composio.create("user_123");
const tools = await session.tools();
// Pass tools to your agent/LLM framework
```

For other providers, pass the provider explicitly. Provider packages follow the naming convention: `composio_<provider>` for Python, `@composio/<provider>` for TypeScript.

### MCP

Use `session.mcp.url` and `session.mcp.headers` with any MCP-compatible client (Claude Desktop, Cursor, OpenAI Agents, etc.). No provider package needed.

---

## 2. CRITICAL INSTRUCTIONS FOR AI MODELS

### 2.1 — ALWAYS DO THE FOLLOWING

1. **Use `composio.create(user_id)`** to create a session — this is the entry point for all Composio integrations.
2. **Use `session.tools()`** for native tool integration or **`session.mcp.url`** for MCP integration.
3. **Import** from the correct provider package (`composio_<provider>` for Python, `@composio/<provider>` for TypeScript).
4. **Pass `user_id` to `composio.create()`**, not to individual tool calls.

### 2.2 — NEVER DO THE FOLLOWING

1. **Do not** instruct users to manually create auth configs or connected accounts before running.
2. **Do not** import from `composio_openai` / `@composio/openai` when using OpenAI Agents SDK — use `composio_openai_agents` / `@composio/openai-agents` instead.

### 2.3 — DISCOURAGED (do not use unless user explicitly asks)

Do **not** generate `composio.tools.get()`, `composio.tools.execute()`, or `composio.provider.handle_tool_calls()` unless the user explicitly requests direct tool execution. These are a supported but **not recommended** low-level interface.


---

## Terminology Migration (old → current)

If you encounter these terms in error messages, old documentation, or user prompts, translate them to the current equivalents. **Do not use the old terms in generated code or explanations.**

| Old term (v1/v2) | Current term (v3) | In code |
|---|---|---|
| entity ID | user ID | `user_id` parameter |
| actions | tools | e.g., `GITHUB_CREATE_ISSUE` is a *tool* |
| apps / appType | toolkits | e.g., `github` is a *toolkit* |
| integration / integration ID | auth config / auth config ID | `auth_config_id` parameter |
| connection | connected account | `connected_accounts` namespace |
| ComposioToolSet / OpenAIToolSet | `Composio` class with a provider | `Composio(provider=...)` |
| toolset | provider | e.g., `OpenAIProvider` |

If a user says "entity ID", they mean `user_id`. If they say "integration", they mean "auth config". Always respond using the current terminology.

