Skip to content

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

docs: add python custom tools docs

Dhawal Upadhyayf278e6272d1c
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.mdx
index 781f95c95..c39cbcc61 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
@@ -11,12 +11,16 @@ You can now create custom tools and toolkits that run locally alongside remote C
| Package | Version |
|---------|---------|
| @composio/core | v0.6.6 |
+| composio | v0.11.4 |
---
## What's New
-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.
+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. TypeScript uses builder functions with Zod schemas; Python uses decorators with Pydantic annotations.
+
+<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
+<Tab value="TypeScript">
```typescript
import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
@@ -86,18 +90,101 @@ const session = await composio.create("user_1", {
const tools = await session.tools(); // Includes both remote and custom tools
```
+</Tab>
+<Tab value="Python">
+
+```python
+import base64
+
+from pydantic import BaseModel, Field
+
+from composio import Composio
+
+
+composio = Composio(api_key="your_api_key")
+
+
+class UserLookupInput(BaseModel):
+ user_id: str = Field(description="User ID")
+
+
+def get_user_profile(input: UserLookupInput, ctx):
+ """Retrieve the current user's profile from the internal directory."""
+ profiles = {
+ "user_1": {"name": "Alice Johnson", "tier": "enterprise"},
+ }
+ return profiles.get(input.user_id, {})
+
+
+class PromoEmailInput(BaseModel):
+ to: str = Field(description="Recipient email")
+
+
[email protected](extends_toolkit="gmail")
+def send_promo_email(input: PromoEmailInput, ctx):
+ """Send the standard promotional email to a recipient."""
+ raw = base64.urlsafe_b64encode(
+ (
+ f"To: {input.to}\r\n"
+ "Subject: Try MyApp Pro\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
+ "Free for 14 days."
+ ).encode()
+ ).decode().rstrip("=")
+ res = ctx.proxy_execute(
+ toolkit="gmail",
+ endpoint="https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
+ method="POST",
+ body={"raw": raw},
+ )
+ return {"status": res.status, "to": input.to}
+
+
+user_management = composio.experimental.Toolkit(
+ slug="USER_MANAGEMENT",
+ name="User management",
+ description="Manage user roles and permissions",
+)
+
+
+class AssignRoleInput(BaseModel):
+ user_id: str = Field(description="Target user ID")
+ role: str = Field(description="Role to assign")
+
+
+@user_management.tool()
+def assign_role(input: AssignRoleInput, ctx):
+ """Assign a role to a user in the internal system."""
+ return {"user_id": input.user_id, "role": input.role, "assigned": True}
+
+
+session = composio.create(
+ user_id="user_1",
+ toolkits=["gmail"],
+ experimental={
+ "custom_tools": [get_user_profile, send_promo_email],
+ "custom_toolkits": [user_management],
+ },
+)
+
+tools = session.tools() # Includes both remote and custom tools
+```
+
+</Tab>
+</Tabs>
+
### 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
+- **TypeScript** — `ctx.userId`, `ctx.proxyExecute(params)`, `ctx.execute(toolSlug, args)`
+- **Python** — `ctx.user_id`, `ctx.proxy_execute(...)`, `ctx.execute(tool_slug, arguments)`
---
## Limitations
- **Native tools only** — custom tools work with `session.tools()`. MCP support is coming soon.
-- **TypeScript only** — Python support is not yet available.
-- **Experimental API** — the `experimental_` prefix and session option may change.
\ No newline at end of file
+- **Experimental API** — the custom tool APIs and session `experimental` option may change.
+- **SDK-specific DX is intentional** — TypeScript uses builder helpers and Zod. Python uses decorators, docstrings, and Pydantic annotations.
diff --git a/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx b/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx
index 5b4834b87..675337605 100644
--- a/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx
+++ b/docs/content/docs/toolkits/custom-tools-and-toolkits.mdx
@@ -5,7 +5,7 @@ keywords: [custom tools, custom toolkits, experimental, local tools, proxy execu
---
<Callout type="warn">
-Custom tools are experimental. The `experimental_` prefix and `experimental` session option may change in future releases. TypeScript only.
+Custom tool APIs are experimental. TypeScript uses `experimental_createTool()` / `experimental_createToolkit()`. Python uses `@composio.experimental.tool()` / `composio.experimental.Toolkit(...)`. The session `experimental` option may change in future releases.
</Callout>
<Callout type="info">
@@ -15,11 +15,14 @@ Custom tools work with **native tools** (`session.tools()`). MCP support is comi
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
+- **Extension tools** — wrap a Composio toolkit's API with custom business logic via `extendsToolkit` / `extends_toolkit`, using `ctx.proxyExecute()` / `ctx.proxy_execute()` 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:
+<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
+<Tab value="TypeScript">
+
```typescript
import { Composio, experimental_createTool, experimental_createToolkit } from "@composio/core";
import { z } from "zod/v3";
@@ -104,6 +107,102 @@ const session = await composio.create("user_1", {
const tools = await session.tools();
```
+</Tab>
+<Tab value="Python">
+
+```python
+import base64
+
+from pydantic import BaseModel, Field
+
+from composio import Composio
+
+
+composio = Composio(api_key="your_api_key")
+
+
+class UserLookupInput(BaseModel):
+ user_id: str = Field(description="User ID")
+
+
+USERS = {
+ "user_1": {"name": "Alice Johnson", "email": "[email protected]", "tier": "enterprise"},
+ "user_2": {"name": "Bob Smith", "email": "[email protected]", "tier": "free"},
+}
+
+
+def get_user_profile(input: UserLookupInput, ctx):
+ """Retrieve the current user's profile from the internal directory."""
+ profile = USERS.get(input.user_id)
+ if not profile:
+ raise ValueError(f'No profile found for user "{input.user_id}"')
+ return profile
+
+
+class PromoEmailInput(BaseModel):
+ to: str = Field(description="Recipient email address")
+
+
[email protected](extends_toolkit="gmail")
+def send_promo_email(input: PromoEmailInput, ctx):
+ """Send the standard promotional email to a recipient."""
+ subject = "You're invited to try MyApp Pro"
+ body = (
+ "Hi there,\n\n"
+ "We'd love for you to try MyApp Pro — free for 14 days.\n\n"
+ "Best,\nThe MyApp Team"
+ )
+ raw_msg = (
+ f"To: {input.to}\r\n"
+ f"Subject: {subject}\r\n"
+ "Content-Type: text/plain; charset=UTF-8\r\n\r\n"
+ f"{body}"
+ )
+ raw = base64.urlsafe_b64encode(raw_msg.encode()).decode().rstrip("=")
+
+ res = ctx.proxy_execute(
+ toolkit="gmail",
+ endpoint="https://gmail.googleapis.com/gmail/v1/users/me/messages/send",
+ method="POST",
+ body={"raw": raw},
+ )
+ return {"status": res.status, "to": input.to}
+
+
+user_management = composio.experimental.Toolkit(
+ slug="USER_MANAGEMENT",
+ name="User management",
+ description="Manage user roles and permissions",
+)
+
+
+class AssignRoleInput(BaseModel):
+ user_id: str = Field(description="Target user ID")
+ role: str = Field(description="Role to assign")
+
+
+@user_management.tool()
+def assign_role(input: AssignRoleInput, ctx):
+ """Assign a role to a user in the internal system."""
+ return {"user_id": input.user_id, "role": input.role, "assigned": True}
+
+
+session = composio.create(
+ user_id="user_1",
+ toolkits=["gmail"],
+ experimental={
+ "custom_tools": [get_user_profile, send_promo_email],
+ "custom_toolkits": [user_management],
+ },
+)
+
+tools = session.tools()
+```
+
+</Tab>
+</Tabs>
+
## How custom tools work with meta tools
Custom tools integrate seamlessly with Composio's meta tools:
@@ -116,16 +215,17 @@ Custom tools integrate seamlessly with Composio's meta tools:
## 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`.
+- **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". In TypeScript, define uppercase slugs like `SEND_PROMO_EMAIL`. In Python, inferred slugs come from the function name, so `snake_case` function names produce the cleanest defaults; or pass `slug=` / `name=` explicitly.
- **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`.
+- **Use `extendsToolkit` / `extends_toolkit` for auth** — If your tool needs Gmail/GitHub/etc. auth for `ctx.proxyExecute()` / `ctx.proxy_execute()` or `ctx.execute()`, set the toolkit extension so connection management is handled seamlessly via `COMPOSIO_MANAGE_CONNECTIONS`.
+- **In Python, annotations are the schema** — The first parameter must be a Pydantic `BaseModel`, and its field descriptions become the input schema. Docstrings are used as the default tool description unless you pass `description=`.
- **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.
+Use `session.customTools()` / `session.customToolkits()` in TypeScript or `session.custom_tools()` / `session.custom_toolkits()` in Python to list registered tools and toolkits. Registered tool slugs include their final `LOCAL_` prefix, and toolkit-scoped tools also include the toolkit slug.
## Programmatic execution
@@ -135,8 +235,29 @@ Use `session.execute()` to run custom tools directly, outside of an agent loop (
Every custom tool's `execute` function receives `(input, ctx)`. The `ctx` object provides:
+<Tabs groupId="language" items={['TypeScript', 'Python']} persist>
+<Tab value="TypeScript">
+
| 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. |
+
+</Tab>
+<Tab value="Python">
+
+| Method | Description |
+|--------|-------------|
+| `ctx.user_id` | The user ID for the current session. |
+| `ctx.proxy_execute(...)` | Authenticated HTTP request via Composio's auth layer. Params: `toolkit`, `endpoint`, `method`, `body=None`, `parameters=[{"type": "query" \| "header", "name": ..., "value": ...}]`. |
+| `ctx.execute(tool_slug, arguments)` | Execute any Composio native tool from within your custom tool. |
+
+</Tab>
+</Tabs>
+
+## Related reference
+
+- [Tool Router API Reference](/reference/api-reference/tool-router)
+- [TypeScript ToolRouterSession Reference](/reference/sdk-reference/typescript/tool-router-session)
+- [Python SDK Reference](/reference/sdk-reference/python)