Doramagic Project Pack · Human Manual
composio
Composio is a comprehensive platform for managing Python and TypeScript projects that enables AI agents to interact with external tools and services. It provides a unified interface for to...
Introduction to Composio
Related topics: Getting Started, System Architecture, Core Concepts
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Getting Started, System Architecture, Core Concepts
Introduction to Composio
Overview
Composio is a comprehensive platform for managing Python and TypeScript projects that enables AI agents to interact with external tools and services. It provides a unified interface for tool execution, toolkit management, and agent integration across multiple AI frameworks.
**Sources: ts/packages/cli/src/commands/$default.cmd.ts:7
export const $defaultCmd = Command.make('composio', { logLevel }).pipe(
Command.withDescription(
`Composio CLI - A tool for managing Python and TypeScript composio.dev projects.`
)
);
Core Architecture
Composio operates through a layered architecture that separates concerns between the CLI interface, core SDK, provider system, and tool execution layer.
graph TD
A[User/Agent] --> B[Composio CLI]
B --> C[Core SDK]
C --> D[Providers]
D --> E[Tool Execution Layer]
E --> F[External Services]
G[Python SDK] --> C
H[TypeScript SDK] --> CSDK Components
| Component | Language | Purpose |
|---|---|---|
| Core SDK | TypeScript | Central tool management and execution |
| Python SDK | Python | Python-native integration |
| CLI | TypeScript | Command-line interface for tool management |
| Providers | TypeScript/Python | Framework-specific integrations |
**Sources: ts/README.md
Composio CLI
The Composio CLI is the primary interface for managing tools, executing actions, and administering projects. It provides commands for both runtime operations and development workflows.
**Sources: ts/packages/cli/src/commands/root-help.ts:1-50
Primary Commands
| Command | Description |
|---|---|
composio execute | Execute a tool with specified parameters |
composio link | Link a toolkit to the current project |
composio tools list | List available tools from a toolkit |
composio tools info | Get detailed information about a specific tool |
composio triggers list | List available triggers |
composio triggers info | Get detailed information about a trigger |
composio orgs switch | Switch between organizations |
**Sources: ts/packages/cli/src/services/command-hints.ts
Development Commands
The CLI includes a dedicated dev namespace for development workflows:
| Command | Description |
|---|---|
composio dev init | Initialize a new Composio project |
composio dev playground-execute | Execute tools in playground mode |
composio dev logs tools | View tool execution logs |
composio dev logs triggers | View trigger execution logs |
composio dev toolkits list | List available toolkits |
composio dev toolkits info | Get toolkit information |
composio dev toolkits search | Search for toolkits |
composio dev toolkits version | Manage toolkit versions |
**Sources: ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts
Tool Execution Flow
Tools in Composio follow a structured execution pipeline that handles permission requests, parameter validation, and result processing.
graph TD
A[User Request] --> B[CLI Command]
B --> C{Auth Required?}
C -->|Yes| D[Permission Request]
C -->|No| E[Execute Tool]
D --> F{Permission Granted?}
F -->|Session| E
F -->|Once| E
F -->|Deny| G[Abort]
E --> H[Tool Execution]
H --> I[Return Result]
I --> J[Log Execution]**Sources: ts/packages/cli/src/services/tool-permissions.ts
Provider System
Composio uses a provider-based architecture to support different AI frameworks and agent implementations. Providers wrap tools with framework-specific logic and execution handlers.
**Sources: ts/packages/providers/README.md
Provider Types
#### Non-Agentic Providers
Non-agentic providers provide basic tool wrapping without autonomous decision-making:
class NonAgenticProvider extends BaseNonAgenticProvider {
async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool>;
async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]>;
async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<Tool>;
}
#### Agentic Providers
Agentic providers support autonomous agent behavior with extended capabilities:
class AgenticProvider extends BaseAgenticProvider {
async wrapTool(toolSlug: string, tool: Tool, modifiers?: ModifiersParams): Promise<Tool>;
async getTools(modifiers?: ModifiersParams): Promise<Tool[]>;
// Additional execution handlers for autonomous behavior
}
**Sources: ts/packages/providers/README.md
Creating New Providers
To create a new provider, use the CLI scripts:
# Create a non-agentic provider (default)
pnpm run create-provider <your-provider-name>
# Create an agentic provider
pnpm run create-provider <your-provider-name> --agentic
The script creates a new provider with the following structure:
<provider-name>/
├── src/
│ └── index.ts # Provider implementation
├── package.json # Package configuration
├── tsconfig.json # TypeScript configuration
├── tsup.config.ts # Build configuration
└── README.md # Provider documentation
**Sources: ts/README.md
Session Management
Each CLI session operates within an isolated environment, providing secure and organized execution contexts.
graph TD
A[CLI Session Start] --> B[Create Session Directory]
B --> C[Initialize Session State]
C --> D[Execute Commands]
D --> E[Store Artifacts]
E --> F[Log History]
D --> G{Command Type}
G -->|run| H[Create Artifacts in cwd]
G -->|execute| I[Download Attachments]**Sources: ts/packages/cli/src/commands/root-help.ts
Session Artifacts
Each CLI session gets a unique subdirectory, scoped to your working directory, which stores:
- Session history
- Files created during
runandexecutecommands - Downloaded attachments
- Generated outputs
Use composio artifacts cwd to print the path for the current directory's session.
SDK Integration
Composio provides SDKs for both Python and TypeScript, enabling integration with various AI frameworks.
**Sources: python/providers/claude_agent_sdk/README.md
Python SDK Example
import asyncio
from composio import Composio
from composio_claude_agent_sdk import ClaudeAgentSDKProvider
from claude_agent_sdk import query, ClaudeAgentOptions
# Initialize Composio with the Claude Code Agents provider
composio = Composio(provider=ClaudeAgentSDKProvider())
async def main():
# Get tools from Composio
tools = composio.tools.get(
user_id="default",
toolkits=["gmail"],
)
# Create an MCP server configuration with the tools
mcp_server = composio.provider.create_mcp_server(tools)
**Sources: python/providers/claude_agent_sdk/README.md
Environment Configuration
Composio supports various environment variables for configuration:
| Variable | Description |
|---|---|
COMPOSIO_API_KEY | Your Composio API key |
COMPOSIO_BASE_URL | Custom API base URL (optional) |
COMPOSIO_LOG_LEVEL | Logging level: silent, error, warn, info, debug |
COMPOSIO_DISABLE_TELEMETRY | Disable telemetry when set to "true" |
COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME> | Specific version for a toolkit |
DEVELOPMENT | Development mode flag |
CI | CI environment flag |
**Sources: ts/README.md
Project Initialization
To initialize a new Composio project:
cd <project-directory>
composio dev init
The initialization process:
- Creates a
.env.localfile in the project directory - Sets up the project API key by fetching session information
- Validates the connection to Composio services
**Sources: ts/packages/cli/src/commands/init.cmd.ts
Error Handling
Composio uses a structured error handling system based on the Effect framework:
export const captureErrorsFrom = <E>(cause: Cause<E>): readonly PrettyError[] =>
reduceWithContext(cause, undefined, {
emptyCase: (): readonly PrettyError[] => [],
dieCase: (_, unknownError) => [parseError(unknownError)],
failCase: (_, error) => [parseError(error)],
interruptCase: () => [],
parallelCase: (_, l, r) => [...l, ...r],
sequentialCase: (_, l, r) => [...l, ...r],
});
**Sources: ts/packages/cli/src/effect-errors/logic/errors/capture-errors-from-cause.ts
Local Tools
Composio supports local tool execution through the cli-local-tools package, which provides a registry of locally available tools independent of remote API calls.
export const isLocalToolSlug = (
toolSlug: string,
options: { readonly declarations?: ReadonlyArray<LocalToolkitDeclaration> } = {}
): boolean => {
const upper = toolSlug.toUpperCase();
if (!upper.startsWith(LOCAL_TOOL_PREFIX)) return false;
return (
resolveLocalTool(toolSlug, { includeUnsupported: true, declarations: options.declarations }) !==
null
);
};
**Sources: ts/packages/cli-local-tools/src/registry.ts
Documentation Generation
The Python SDK includes automated documentation generation using Griffe:
cd python
uv run --with griffe python scripts/generate-docs.py
This process:
- Extracts docstrings from
composio/**/*.py→ structured data - Transforms data → MDX files
- Outputs written to
docs/content/reference/sdk-reference/python/
**Sources: python/scripts/README.md
Further Reading
Source: https://github.com/ComposioHQ/composio / Human Manual
Getting Started
Related topics: Introduction to Composio, TypeScript SDK, Python SDK
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Introduction to Composio, TypeScript SDK, Python SDK
Getting Started
Overview
Composio is a platform that provides a unified interface for managing and executing tools across multiple agent frameworks. The Getting Started guide provides developers with the essential steps to install, configure, and begin using Composio SDK in their projects. Whether you're using TypeScript/JavaScript or Python, this guide covers the complete setup process from installation through your first tool execution.
Installation
TypeScript/JavaScript SDK
Install the Composio SDK using your preferred package manager:
# Using npm
npm install @composio/core
# Using pnpm
pnpm add @composio/core
# Using yarn
yarn add @composio/core
Python SDK
Install the Python SDK using pip:
pip install composio-core
CLI Installation
The Composio CLI provides tools for managing toolkits, executing tools locally, and inspecting execution logs. Install globally for command-line access:
# Using npm
npm install -g @composio/cli
# Using bun (recommended)
bun install -g @composio/cli
Environment Configuration
API Key Setup
Composio requires API key authentication. Set up your environment variables before using the SDK:
# Required
export COMPOSIO_API_KEY="your-api-key-here"
# Optional: Custom API base URL
export COMPOSIO_BASE_URL="https://api.composio.dev"
# Optional: Logging level (silent, error, warn, info, debug)
export COMPOSIO_LOG_LEVEL="info"
# Optional: Disable telemetry
export COMPOSIO_DISABLE_TELEMETRY="true"
Project Initialization
For TypeScript projects, initialize Composio in your working directory:
composio init
The initialization process:
- Creates a
.composiodirectory in your project - Generates a
.env.localfile with your project API key - Sets up local tool configurations
- Validates your API credentials
// Example: composio.ts initialization
import { Composio } from "@composio/core";
const client = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
baseURL: process.env.COMPOSIO_BASE_URL,
});
Sources: ts/packages/core/src/composio.ts:1-50
SDK Initialization
TypeScript SDK
Initialize the Composio client with configuration options:
import { Composio } from "@composio/core";
// Basic initialization
const client = new Composio();
// With explicit configuration
const client = new Composio({
apiKey: "your-api-key",
baseURL: "https://api.composio.dev",
logLevel: "info",
timeout: 30000,
});
Sources: ts/packages/core/src/composio.ts:50-80
Python SDK
Initialize the Python client:
from composio import Composio
# Basic initialization
client = Composio()
# With explicit configuration
client = Composio(
api_key="your-api-key",
base_url="https://api.composio.dev",
log_level="info",
timeout=30
)
Sources: python/composio/sdk.py:1-100
Core Concepts
Tools
Tools are the fundamental building blocks in Composio. Each tool represents a specific action that can be executed through the platform.
// Get available tools
const tools = await client.tools.list();
// Get a specific tool by slug
const tool = await client.tools.get("github_create_issue");
Toolkits
Toolkits are collections of related tools organized by service or functionality:
// List available toolkits
const toolkits = await client.toolkits.list();
// Get tools within a toolkit
const githubTools = await client.toolkits.get("github");
Actions
Actions are specific operations that can be performed using tools:
// Execute a tool action
const result = await client.execute("github_create_issue", {
title: "Bug report",
body: "Description of the issue",
repository: "owner/repo"
});
Working with Tools
Listing Available Tools
// List all available tools
const allTools = await client.getTools();
// Filter tools by toolkit
const slackTools = await client.getTools({ toolkit: "slack" });
// Filter tools by search query
const searchResults = await client.getTools({ query: "message" });
Executing Tools
// Execute a single tool
const result = await client.execute("slack_send_message", {
channel: "#general",
text: "Hello from Composio!"
});
Sources: ts/examples/tool-router/src/index.ts:1-50
Tool Execution Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
toolSlug | string | Unique identifier for the tool | Yes |
params | object | Tool-specific input parameters | Yes |
accountId | string | Connected account identifier | No |
sessionId | string | Execution session identifier | No |
Local Tools (CLI)
The Composio CLI enables local tool execution for development and testing.
Local Toolkit Registry
import { getLocalToolkitDeclarations, getAllLocalToolkitSlugs } from "@composio/cli";
// Get all available local toolkits
const slugs = getAllLocalToolkitSlugs();
// Check if a toolkit is local
const isLocal = isLocalToolkitSlug("local_filesystem");
Local Tool Execution
# Execute a local tool
composio execute local_filesystem_read --path ./README.md
# Get tool schema
composio execute <tool-slug> --get-schema
CLI Commands Reference
Development Commands
| Command | Description |
|---|---|
composio dev init | Initialize a new Composio project |
composio dev playground-execute | Test tool execution in playground mode |
composio dev logs tools | View tool execution logs |
composio dev logs triggers | View trigger execution logs |
Tool Commands
| Command | Description |
|---|---|
composio tools list | List available tools |
composio tools info | Get detailed tool information |
composio execute | Execute a specific tool |
Toolkit Commands
| Command | Description |
|---|---|
composio toolkits list | List available toolkits |
composio toolkits info | Get toolkit details |
composio toolkits search | Search toolkits |
composio toolkits version | Manage toolkit versions |
Sources: ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts:1-30
Tool Router Pattern
The tool router enables intelligent routing of agent requests to appropriate tools:
import { Composio } from "@composio/core";
import { OpenAI } from "openai";
const client = new Composio();
const openai = new OpenAI();
async function handleAgentRequest(userMessage: string) {
// Get available tools from Composio
const tools = await client.getTools({
filtered_tools: ["github", "slack", "jira"]
});
// Create a system prompt with tool schemas
const systemPrompt = `
You have access to the following tools:
${tools.map(t => `- ${t.name}: ${t.description}`).join('\n')}
`;
// Process with OpenAI
const response = await openai.chat.completions.create({
model: "gpt-4",
messages: [
{ role: "system", content: systemPrompt },
{ role: "user", content: userMessage }
],
tools: tools.map(tool => tool.schema),
});
// Execute the selected tool
if (response.choices[0].message.tool_calls) {
for (const call of response.choices[0].message.tool_calls) {
const result = await client.execute(call.function.name,
JSON.parse(call.function.arguments)
);
console.log("Tool result:", result);
}
}
}
Sources: ts/examples/tool-router/src/index.ts:50-100
Permission Management
When executing tools that require user authentication, Composio provides a permission flow:
// Request permission for tool execution
const permission = await client.requestPermission({
toolSlug: "github_create_issue",
params: {
title: "New Issue",
body: "Issue description"
}
});
// Permission states:
// - pending: Waiting for user approval
// - approved: Permission granted
// - denied: Permission rejected
Sources: ts/packages/cli/src/services/tool-permissions.ts:1-50
Logging and Debugging
CLI Logging
The CLI provides structured logging for debugging:
# View tool execution logs
composio dev logs tools <log-id>
# View trigger logs
composio dev logs triggers <log-id>
SDK Logging
const client = new Composio({
logLevel: "debug",
// Custom logger
logger: {
info: (msg) => console.log(`[INFO] ${msg}`),
error: (msg) => console.error(`[ERROR] ${msg}`),
debug: (msg) => console.debug(`[DEBUG] ${msg}`),
}
});
Workflow Diagram
graph TD
A[Install SDK] --> B[Set API Key]
B --> C[Initialize Client]
C --> D[Get Available Tools]
D --> E{Choose Toolkit}
E -->|GitHub| F[GitHub Tools]
E -->|Slack| G[Slack Tools]
E -->|Jira| H[Jira Tools]
F --> I[Execute Tool]
G --> I
H --> I
I --> J[Check Permission]
J -->|Approved| K[Return Result]
J -->|Denied| L[Raise Error]Next Steps
- Explore Toolkits: Browse the available toolkits documentation
- API Reference: View the complete SDK API reference
- Examples: Check out example projects for real-world implementations
- CLI Commands: Review the CLI command reference
Troubleshooting
Common Issues
| Issue | Solution |
|---|---|
API key not found | Set COMPOSIO_API_KEY environment variable |
Tool not found | Verify the toolkit is installed: composio toolkits list |
Permission denied | Run composio link <toolkit> to connect your account |
Timeout error | Increase timeout in client config or check network connectivity |
Getting Help
- Documentation: https://docs.composio.dev
- Discord Community: https://discord.gg/composio
- GitHub Issues: https://github.com/ComposioHQ/composio/issues
System Architecture
Related topics: Introduction to Composio, Core Concepts, TypeScript SDK, Python SDK
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Introduction to Composio, Core Concepts, TypeScript SDK, Python SDK
System Architecture
Composio is a multi-platform tool integration framework that enables AI agents to interact with external tools and services. The system is architected as a cross-language SDK with TypeScript/JavaScript as the primary implementation and Python bindings, supporting multiple runtime environments including Node.js, Deno, Bun, and Cloudflare Workers (workerd).
Core Components Overview
graph TD
subgraph "TypeScript SDK"
A[composio-core] --> B[Platform Abstraction]
B --> C[Node.js Runtime]
B --> D[workerd Runtime]
B --> E[Bun Runtime]
end
subgraph "Tool Integration"
F[Tool Registry] --> G[Toolkits]
G --> H[Individual Tools]
end
subgraph "Providers"
I[BaseNonAgenticProvider]
J[BaseAgenticProvider]
K[MCP Server]
end
A --> F
A --> I
A --> J
A --> KThe system consists of three primary layers:
| Layer | Purpose | Key Files |
|---|---|---|
| Core SDK | Platform initialization, API client management | ts/packages/core/src/index.ts |
| Tool Layer | Tool registration, toolkit management | python/composio/core/models/toolkits.py |
| Provider Layer | External SDK integration (Claude, OpenAI, etc.) | ts/packages/providers/*/src/index.ts |
Platform Abstraction Architecture
Composio implements a platform-agnostic design through a platform abstraction layer that detects and adapts to different JavaScript runtimes.
Platform Detection
The platform system uses conditional imports to provide runtime-specific implementations:
// ts/packages/core/src/platform/node.ts
import { NodeRuntime } from './implementations/node';
export const platform = NodeRuntime;
Supported Platforms
| Platform | Module | Use Case |
|---|---|---|
| Node.js | platform/node.ts | Server-side applications, CLI tools |
| workerd | platform/workerd.ts | Cloudflare Workers, edge computing |
| Bun | Bundled with core | High-performance runtime |
| Deno | Native fetch/http | Deno Deploy, standalone execution |
Platform Interface Contract
All platform implementations must provide:
- HTTP Client - Request/response handling
- File System Access - Local artifact storage
- Environment Variables - Configuration management
- Console/Logging - Output handling
Tool System Architecture
Tool Classification
Tools in Composio are organized hierarchically:
graph TD
A[Toolkit] --> B[Gmail Toolkit]
A --> C[Slack Toolkit]
A --> D[GitHub Toolkit]
B --> E[send_email]
B --> F[read_emails]
C --> G[send_message]
D --> H[create_issue]Tool Data Model
The Python toolkit model (python/composio/core/models/toolkits.py) defines:
class Toolkit:
slug: str # Unique identifier
name: str # Display name
description: str # Human-readable description
tools: List[Tool] # Contained tools
triggers: List[Trigger] # Event triggers
version: str # Version string
Local vs Remote Tools
Composio distinguishes between local and remote tool execution:
| Type | Execution Location | Registry |
|---|---|---|
| Remote Tools | Composio Cloud API | composio-tools |
| Local Tools | Client-side execution | cli-local-tools |
Local tools are registered via LocalToolkitDeclaration and execute directly on the client, supporting multiple platforms (Node.js, workerd, Bun).
Provider System Architecture
Provider Types
graph TD
A[BaseComposioProvider] --> B[BaseNonAgenticProvider]
A --> C[BaseAgenticProvider]
B --> D[Custom Non-Agentic Providers]
C --> E[Claude Agent SDK Provider]
C --> F[OpenAI Provider]
C --> G[Custom Agentic Providers]Provider Interface
Non-agentic providers implement:
class NonAgenticProvider extends BaseNonAgenticProvider {
async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool>;
async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]>;
async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<Tool>;
}
Agentic providers extend with execution handling:
class AgenticProvider extends BaseAgenticProvider {
async wrapTool(toolSlug: string, tool: Tool, modifiers?: ModifiersParams): Promise<Tool>;
async getTools(modifiers?: ModifiersParams): Promise<Tool[]>;
async execute(toolSlug: string, params: any): Promise<any>;
}
MCP Server Integration
Providers can create MCP (Model Context Protocol) server configurations:
mcp_server = composio.provider.create_mcp_server(tools)
This enables interoperability with any MCP-compatible client.
SDK Initialization Flow
sequenceDiagram
participant User
participant Composio
participant Platform
participant API
User->>Composio: Composio(config)
Composio->>Platform: detectRuntime()
Platform-->>Composio: RuntimeType
Composio->>API: initializeClient(apiKey, baseURL)
API-->>Composio: Authenticated client
Composio-->>User: SDK instance readyTypeScript Initialization
// ts/packages/core/src/index.ts
import { Composio } from "@composio/core";
const client = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
baseURL: "https://api.composio.dev"
});
Python Initialization
# python/composio/__init__.py
from composio import Composio
client = Composio(
api_key=os.getenv("COMPOSIO_API_KEY")
)
CLI Architecture
The Composio CLI is built using the Effect framework for functional command handling:
Command Structure
| Command | Purpose |
|---|---|
composio execute | Execute a tool directly |
composio tools list | List available tools |
composio tools info | Get tool details |
composio generate ts | Generate TypeScript types |
composio dev init | Initialize development environment |
composio dev playground-execute | Test tool execution |
Core Dependency Management
The CLI detects project environments and suggests appropriate installation commands:
graph TD
A[Project Detection] --> B{Python vs JS?}
B -->|Python| C[Detect Package Manager]
B -->|JS| D[Detect Package Manager]
C --> E[uv pip install composio]
D --> F[npm install @composio/core]Toolkit Index Generation
The TypeScript SDK generates type-safe toolkit indices for compile-time safety:
graph LR
A[Toolkit Definitions] --> B[createToolkitIndex]
B --> C[Type-safe Enum]
C --> D[Tool Wrappers]The createToolkitIndex function transforms raw toolkit data into structured indices with version overrides and type-safe tool accessors.
Configuration and Environment
Environment Variables
| Variable | Purpose | Default |
|---|---|---|
COMPOSIO_API_KEY | Authentication key | Required |
COMPOSIO_BASE_URL | API endpoint | api.composio.dev |
COMPOSIO_LOG_LEVEL | Logging verbosity | info |
COMPOSIO_DISABLE_TELEMETRY | Opt-out of telemetry | false |
COMPOSIO_TOOLKIT_VERSION_<NAME> | Toolkit version override | latest |
Project-Scoped Configuration
The CLI creates .env.local files scoped to working directories for session management and project-specific API keys.
Error Handling Architecture
Composio uses the Effect library for typed error handling:
const captureErrorsFrom = <E>(cause: Cause<E>): readonly PrettyError[] =>
reduceWithContext(cause, undefined, {
emptyCase: () => [],
failCase: (_, error) => [parseError(error)],
interruptCase: () => [],
// ...
});
This provides structured error reporting with context preservation across asynchronous operations.
Data Flow: Tool Execution
graph TD
A[User Code] --> B[Composio Client]
B --> C[Tool Request]
C --> D{Local or Remote?}
D -->|Local| E[Local Toolkit Registry]
D -->|Remote| F[Composio API]
E --> G[Direct Execution]
F --> H[API Validation]
H --> I[Remote Execution]
I --> J[Result Return]
G --> J
J --> K[Response Processing]
K --> AExtension Points
Creating Custom Providers
Developers can create new providers using the provided scaffolding:
# Non-agentic provider
pnpm create:provider my-provider
# Agentic provider with execution handlers
pnpm create:provider my-provider --agentic
This generates the standard provider structure with required methods pre-scaffolded.
Local Tool Development
Local tools can be registered in cli-local-tools/src/registry.ts with platform-specific execution logic.
Security Model
Tool Permissions
Tool execution requires user consent, managed through a browser-based permission flow:
- Tool execution request triggers permission check
- Browser UI presents allow/deny options
- Decision is cached for session or one-time use
- Token-based verification prevents CSRF attacks
API Key Management
- User API Keys: Global authentication tokens
- Project API Keys: Scoped to specific projects
- Environment Variables:
.env.localfor development
Summary
Composio's architecture provides:
- Cross-platform support through runtime detection and abstraction
- Type-safe tool access via generated TypeScript indices
- Provider flexibility with extensible provider interfaces
- Local execution for tools that don't require cloud API calls
- Permission management with session-scoped authorization
- CLI tooling for development and tool management
The system balances convenience (automatic platform detection) with flexibility (custom providers and local tools), making it suitable for both production deployments and development workflows.
Source: https://github.com/ComposioHQ/composio / Human Manual
Core Concepts
Related topics: System Architecture, Toolkits Management, Connected Accounts
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: System Architecture, Toolkits Management, Connected Accounts
Core Concepts
Composio is a platform that provides a collection of tools and toolkits for AI agents. Understanding the core concepts is essential for effectively using and extending Composio. This page covers the fundamental building blocks: Tools, Toolkits, Connected Accounts, and the Provider system.
Toolkits
Toolkits are collections of related tools that enable AI agents to perform actions within specific domains. Each toolkit focuses on a particular service or functionality area, such as Gmail, Slack, GitHub, or Google Calendar.
Toolkit Structure
A toolkit consists of:
| Property | Type | Description |
|---|---|---|
slug | string | Unique identifier for the toolkit |
name | string | Human-readable name |
description | string | Description of the toolkit's functionality |
tools | Tool[] | Array of tools included in the toolkit |
platforms | LocalCliPlatform[] | Supported platforms (e.g., linux, darwin, windows) |
source | string | Source of the toolkit |
setup | SetupConfig | Configuration for setting up the toolkit |
Toolkit Version Management
Composio supports version overrides for toolkits. The version system allows specifying different versions for different toolkits:
// From toolkit-version-overrides.ts
export interface ToolkitVersionSpec {
toolkitSlug: string;
toolkitVersion: string; // e.g., '20250901_00' or 'latest'
}
export type ToolkitVersionOverrides = Map<Lowercase<string>, string>;
The system groups toolkits by version and builds version maps from specifications:
graph TD
A[ToolkitVersionSpec Array] --> B[groupByVersion]
B --> C[Map: version -> toolkitSlug[]]
A --> D[buildVersionMapFromSpecs]
D --> E[ToolkitVersionOverrides Map]
E --> F[ toolkitSlug -> version]Toolkit Discovery Commands
The CLI provides commands for discovering and inspecting toolkits:
| Command | Description |
|---|---|
composio toolkits list | List all available toolkits |
composio toolkits info | Get detailed information about a specific toolkit |
composio toolkits search | Search toolkits by keyword |
composio toolkits version | View and manage toolkit versions |
Tools
Tools are the fundamental execution units in Composio. Each tool represents a specific action that can be performed by an AI agent.
Tool Properties
| Property | Type | Description |
|---|---|---|
slug | string | Unique identifier for the tool |
name | string | Human-readable name |
description | string | Description of what the tool does |
inputParams | Parameter[] | Required and optional input parameters |
outputParams | Parameter[] | Output parameters (optional) |
Tool Execution Flow
sequenceDiagram
participant Agent
participant Composio as Composio Core
participant Tool as Tool Executor
participant API as External API
Agent->>Composio: Execute tool(slug, params)
Composio->>Tool: Create execution context
Tool->>API: Make API request
API-->>Tool: API response
Tool-->>Composio: Formatted result
Composio-->>Agent: Return resultToolkits Index
The toolkit index organizes all tools by their parent toolkit:
// From create-toolkit-index.ts
export interface CreateToolkitIndexInput {
slug: string;
version?: string;
typeableTools:
| { withTypes: false; value: Record<`${ToolkitName}_${string}`, ToolAsEnum> }
| { withTypes: true; value: Record<`${ToolkitName}_${string}`, Tool> };
triggerTypes: Record<`${ToolkitName}_${string}`, TriggerType>;
}
export type ToolkitIndex = Record<ToolkitName, ToolkitIndexData>;
Connected Accounts
Connected Accounts represent authenticated access to external services. They enable tools to interact with user-specific data and perform authorized actions.
Account Model
| Property | Type | Description |
|---|---|---|
id | string | Unique identifier for the connection |
toolkit | string | The toolkit this account belongs to |
accountId | string | User account ID on the external service |
accountName | string | Display name for the account |
authConfig | AuthConfig | Authentication configuration |
status | ConnectionStatus | Active, inactive, or error state |
Authentication Flow
graph LR
A[User] -->|Link Account| B[CLI Command]
B --> C{Auth Required?}
C -->|Yes| D[OAuth/Browser Auth]
D --> E[Token Exchange]
E --> F[Store Credentials]
C -->|No| F
F --> G[Connected Account Created]Local CLI Tools
Local CLI tools are tools that execute locally on the user's machine rather than through the Composio cloud API. They provide additional capabilities for local development and execution.
Local Toolkit Declaration
interface LocalToolkitDeclaration {
slug: string;
name: string;
description: string;
platforms: LocalCliPlatform[];
tools: LocalToolDeclaration[];
source: string;
setup?: SetupConfig;
}
Local Tool Registry
The registry manages local tools and provides functions for toolkit discovery:
// From registry.ts
export const getAllLocalToolkitSlugs = (
options: { readonly declarations?: ReadonlyArray<LocalCliPlatform> } = {}
): ReadonlyArray<string>;
export const isLocalToolkitSlug = (
toolkitSlug: string | undefined,
options: { readonly declarations?: ReadonlyArray<LocalToolDeclaration> } = {}
): boolean;
export const getLocalCustomToolkits = (
options: {
readonly currentPlatform?: LocalCliPlatform;
readonly toolkits?: ReadonlyArray<string>;
readonly declarations?: ReadonlyArray<LocalToolDeclaration>;
} = {}
): ReadonlyArray<CustomToolkit>;
Platform Support
Local tools can specify which platforms they support:
type LocalCliPlatform = 'linux' | 'darwin' | 'windows';
Provider System
Composio uses a provider system to wrap and manage tools. Providers add functionality like schema modification and parameter handling.
Provider Types
// From modifiers.types.ts
export type ProviderOptions<TProvider> =
TProvider extends BaseComposioProvider<infer TToolCollection, infer TTool, infer TMcpResponse>
? TProvider extends BaseAgenticProvider<TToolCollection, TTool, TMcpResponse>
? AgenticToolOptions
: ToolOptions
: never;
Provider Interface
Non-agentic providers must implement:
class NonAgenticProvider extends BaseNonAgenticProvider {
// Wrap a tool with schema modifiers
async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool>;
// Get all available tools
async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]>;
// Get a specific tool by slug
async getToolBySlug(slug: string, modifiers?: SchemaModifiersParams): Promise<Tool>;
}
Agentic providers extend the interface with additional agentic-specific options.
Schema Modifiers
Schema modifiers allow providers to transform tool schemas before execution:
interface SchemaModifiersParams {
modifySchema?: (context: { schema: z.ZodSchema }) => z.ZodSchema;
beforeExecute?: (context: { params: Record<string, unknown> }) => Record<string, unknown>;
afterExecute?: (context: { result: unknown }) => unknown;
}
Modifier Execution Flow
graph TD
A[Raw Tool Schema] --> B[modifySchema]
B --> C[Modified Schema]
C --> D[User Params]
D --> E[beforeExecute]
E --> F[Processed Params]
F --> G[Tool Execution]
G --> H[Raw Result]
H --> I[afterExecute]
I --> J[Final Result]Tool Permissions
Composio implements a permission system for tool execution, especially for local tools that may have access to sensitive local resources.
Permission Flow
graph TD
A[Tool Execution Request] --> B{Permission Check}
B -->|Session Allowed| C[Execute Tool]
B -->|One-time| D[Prompt User]
D -->|Allow| C
D -->|Deny| E[Access Denied]
B -->|Denied| EPermission Options
| Option | Description |
|---|---|
Allow for this session | Grants permission for the current session |
Allow once | Grants permission for a single execution |
Deny | Denies the execution |
Error Handling
Composio uses Effect-based error handling for predictable error management:
// From capture-errors-from-cause.ts
export const captureErrorsFrom = <E>(cause: Cause<E>): readonly PrettyError[] =>
reduceWithContext(cause, undefined, {
emptyCase: (): readonly PrettyError[] => [],
dieCase: (_, unknownError) => [parseError(unknownError)],
failCase: (_, error) => [parseError(error)],
interruptCase: () => [],
parallelCase: (_, l, r) => [...l, ...r],
sequentialCase: (_, l, r) => [...l, ...r],
});
Summary
The Composio architecture is built on several interconnected concepts:
| Concept | Role |
|---|---|
| Toolkits | Organize related tools by domain |
| Tools | Individual executable units with defined inputs/outputs |
| Connected Accounts | Authenticated access to external services |
| Local CLI Tools | Locally executed tools that extend cloud capabilities |
| Providers | Wrap and enhance tools with additional functionality |
| Schema Modifiers | Transform tool schemas and execution contexts |
| Permissions | Control access to tool execution |
Together, these concepts provide a flexible and extensible system for AI agent tool integration.
Source: https://github.com/ComposioHQ/composio / Human Manual
TypeScript SDK
Related topics: Python SDK, AI Framework Providers, Getting Started
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Python SDK, AI Framework Providers, Getting Started
TypeScript SDK
The Composio TypeScript SDK provides a comprehensive toolkit for integrating third-party services and tools into AI agent applications. It enables developers to programmatically interact with tools, manage toolkits, execute actions, and handle file operations across multiple platforms.
Overview
The SDK is organized as a monorepo under ts/ containing multiple packages that work together to provide a complete development experience:
| Package | Purpose |
|---|---|
@composio/core | Core SDK functionality, API clients, and tool management |
@composio/cli | Command-line interface for project management and generation |
@composio/cli-local-tools | Local tool execution and toolkit registry |
@composio/ts-builders | TypeScript AST generation utilities |
@composio/providers | Base provider implementations |
Sources: ts/README.md
Architecture
graph TD
A[Developer Application] --> B[@composio/core]
B --> C[ComposioToolkitsRepository]
B --> D[ToolRouter]
B --> E[Files Module]
C --> F[Composio API]
G[@composio/cli] --> H[generate command]
H --> I[TypeScript Type Stubs]
H --> J[transpiled JS]
G --> K[execute command]
K --> L[LocalToolRegistry]
L --> M[Tool Execution]
N[Providers] --> B
N --> O[BaseNonAgenticProvider]
N --> P[BaseAgenticProvider]The SDK follows a layered architecture where the core package handles all API interactions while the CLI provides tooling support for project setup and execution.
Sources: ts/packages/ts-builders/README.md Sources: ts/packages/cli/src/commands/generate/generate.cmd.ts
Core Components
Composio Client
The main entry point for interacting with the Composio platform:
import { Composio } from '@composio/core';
const client = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
baseUrl: process.env.COMPOSIO_BASE_URL, // optional
});
The client provides access to:
tools- Tool listing and retrievaltoolkits- Toolkit managementexecute- Direct tool executionfiles- File upload and management
Tool Management
Tools are fetched and wrapped using providers that modify their schemas and execution behavior:
// Get all tools
const tools = await client.tools.list();
// Get tools with type safety
const typedTools = await client.tools.list({
type: 'typed',
filterParams: { tags: ['github'] }
});
// Get a specific tool
const tool = await client.tools.get('default', 'GITHUB_GET_REPOS');
Sources: ts/packages/core/src/models/Tools.ts Sources: ts/packages/core/src/types/modifiers.types.ts
Provider System
Providers enable integration with different AI frameworks and modify tool behavior:
#### Non-Agentic Providers
For frameworks that handle tool execution externally:
import { BaseNonAgenticProvider } from '@composio/core';
class CustomProvider extends BaseNonAgenticProvider {
async wrapTool(toolSlug: string, tool: Tool, modifiers?: SchemaModifiersParams): Promise<Tool> {
if (modifiers?.schema) {
return modifiers.schema(toolSlug, tool);
}
return tool;
}
async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]> {
const response = await this.client.getTools();
return Promise.all(response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers)));
}
}
#### Agentic Providers
For frameworks requiring full control over execution:
import { BaseAgenticProvider } from '@composio/core';
class AgenticProvider extends BaseAgenticProvider {
async wrapTool(toolSlug: string, tool: Tool, modifiers?: ModifiersParams): Promise<Tool>;
async getTools(modifiers?: ModifiersParams): Promise<Tool[]>;
}
Sources: ts/packages/providers/README.md
Modifiers System
Schema and execution modifiers allow runtime customization of tool behavior:
const tools = await composio.tools.list('default', {
modifySchema: (toolSlug, toolkitSlug, schema) => {
return { ...schema, description: 'Custom description' };
},
beforeExecute: (toolSlug, toolkitSlug, params) => params,
afterExecute: (toolSlug, toolkitSlug, result) => result
});
Sources: ts/packages/core/src/types/modifiers.types.ts Sources: ts/packages/core/src/models/Tools.ts
CLI Commands
Type Stub Generation
The composio generate ts command generates TypeScript type definitions:
# Generate with transpiled JS (default when no --output-dir)
composio generate ts
# Specify output directory
composio generate ts --output-dir ./types
# Compact single module output
composio generate ts --compact
# Filter by specific toolkits
composio generate ts --toolkits github --toolkits slack
#### Command Options
| Option | Description | Default |
|---|---|---|
--compact | Emit a single module file | false |
--transpiled | Also emit ESM JavaScript files | true (if no --output-dir) |
--output-dir | Output directory path | node_modules/@composio/core |
--toolkits | Filter to specific toolkits | All toolkits |
Invariants:
--output-dircannot refer to a path insidenode_modules- Without
--output-dir, files are written to@composio/coreinnode_modules - If
--transpiledistrue, sources are transpiled to ESM JavaScript alongside TypeScript files (CJS not supported)
Sources: ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts
Tool Execution
# Execute a tool
composio execute "GITHUB_GET_REPOS" -d '{}'
# Get tool schema
composio execute "GITHUB_GET_REPOS" --get-schema
# Dry run
composio execute "GITHUB_GET_REPOS" -d '{}' --dry-run
Tool Information
# View tool details
composio tools info "GITHUB_GET_REPOS"
# List tools in a toolkit
composio tools list "github"
Sources: ts/packages/cli/src/commands/tools/commands/tools.info.cmd.ts Sources: ts/packages/cli/src/services/command-hints.ts
Local Tools
The CLI supports local tool execution through the cli-local-tools package:
import { getLocalCustomToolkits, isLocalToolSlug } from '@composio/cli-local-tools';
// Check if a slug is a local tool
if (isLocalToolSlug('LOCAL_MY_TOOL')) {
// Handle local tool
}
// Get all local toolkits
const toolkits = getLocalCustomToolkits({
currentPlatform: 'linux',
toolkits: ['my-toolkit']
});
Toolkit Readiness
Check platform compatibility and readiness status:
import { getReadinessReport } from '@composio/cli-local-tools';
const report = await getReadinessReport({
currentPlatform: detectCliPlatform(),
toolkits: ['github', 'slack']
});
Status values:
ready- Toolkit and tools fully supporteddisabled- Disabled via~/composio/local_tools.jsonunsupported- Platform not supported by toolkit
Sources: ts/packages/cli-local-tools/src/registry.ts Sources: ts/packages/cli-local-tools/src/readiness.ts
Toolkit Index
The SDK creates a toolkit index for efficient tool and trigger type lookup:
import { createToolkitIndex } from '@composio/cli/src/generation/create-toolkit-index';
type ToolkitIndex = Record<ToolkitName, ToolkitIndexData>;
The index maps toolkit names to their tools and trigger types, enabling fast lookups by slug prefix matching.
Sources: ts/packages/cli/src/generation/create-toolkit-index.ts
Environment Configuration
| Variable | Description |
|---|---|
COMPOSIO_API_KEY | API key for Composio services |
COMPOSIO_BASE_URL | Custom API base URL (optional) |
COMPOSIO_LOG_LEVEL | Logging level: silent, error, warn, info, debug |
COMPOSIO_DISABLE_TELEMETRY | Set to "true" to disable telemetry |
COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME> | Specific version for a toolkit (e.g., COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00) |
DEVELOPMENT | Development mode flag |
CI | CI environment flag |
Sources: ts/README.md
Version Validation
The CLI validates toolkit version overrides against the API:
import { validateToolkitVersionOverrides } from '@composio/cli/src/effects/validate-toolkit-versions';
const { validatedOverrides, warnings } = yield* client
.validateToolkitVersions(versionOverrides, toolkitSlugsFilter);
Invalid versions are caught and reported with helpful error messages including correct toolkit slug format guidance.
Sources: ts/packages/cli/src/effects/validate-toolkit-versions.ts
SDK Documentation Generation
Documentation is auto-generated from TypeScript source using TypeDoc:
pnpm generate:docs
Process:
- TypeDoc extracts JSDoc from
src/models/*.ts→ JSON AST generate-docs.tstransforms AST → MDX files- Output written to
docs/content/reference/sdk-reference/typescript/
Configuration:
- Entry points: Auto-discovered from
src/models/*.ts - Excluded classes:
INTERNAL_CLASSESset in script - User-instantiated classes:
USER_INSTANTIATED_CLASSES(shows constructor)
Sources: ts/packages/core/scripts/README.md
Provider Creation
Create new providers using the provided script:
# Non-agentic provider (default)
pnpm run create-provider my-provider
# Agentic provider
pnpm run create-provider my-provider --agentic
The script creates a new provider with structure:
<provider-name>/
├── src/index.ts # Provider implementation
├── package.json # Package configuration
├── tsconfig.json # TypeScript configuration
├── tsup.config.ts # Build configuration
└── README.md # Provider documentation
Sources: ts/packages/providers/README.md
Error Handling
The SDK provides structured error handling through the errors module:
import { ComposioError, InvalidToolkitVersionsError } from '@composio/core/errors';
// Errors include:
// - ComposioError: Base error class
// - InvalidToolkitVersionsError: Version validation failures
// - InvalidToolkitsError: Invalid toolkit slugs
// - HttpServerError: API communication errors
Sources: ts/packages/core/src/errors/index.ts
Framework Integrations
The SDK includes pre-built providers for common AI frameworks:
| Provider | Package | Description |
|---|---|---|
| LangChain | @composio/langchain | Integration with LangChain agents |
| Vercel AI | @composio/vercel | Integration with Vercel AI SDK |
Provider dependencies:
{
"@composio/core": ">=0.10.0 <1.0.0",
"ai": "^5.0.0 || ^6.0.0"
}
Sources: ts/packages/providers/langchain/package.json Sources: ts/packages/providers/vercel/package.json
Sources: ts/README.md
Python SDK
Related topics: TypeScript SDK, AI Framework Providers, Getting Started
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: TypeScript SDK, AI Framework Providers, Getting Started
Python SDK
The Composio Python SDK provides a comprehensive interface for integrating external tools and services into AI applications. It enables developers to fetch, configure, and execute tools from the Composio platform while supporting advanced features like schema modification, execution hooks, and MCP (Model Context Protocol) server creation.
Architecture Overview
graph TD
A[Application Code] --> B[Composio SDK]
B --> C[Tool Client]
B --> D[Tool Router]
B --> E[MCP Server]
C --> F[Composio API]
D --> F
E --> F
G[Schema Modifiers] --> B
H[Execution Modifiers] --> B
I[Providers] --> BThe SDK is structured around several core components that work together to provide a seamless integration experience. The primary entry point is the Composio class, which orchestrates all tool-related operations including fetching tools from the API, managing local tool configurations, and handling execution with modifiers. Sources: python/composio/sdk.py:1-100
Core Components
Composio Main Class
The Composio class serves as the central interface for SDK operations. It handles initialization, tool retrieval, and configuration management through a fluent API design.
from composio import Composio
composio = Composio(
api_key="your-api-key",
base_url="https://api.composio.dev",
timeout=60,
max_retries=3,
allow_tracking=True,
file_download_dir="./downloads",
provider=OpenAIProvider(),
toolkit_versions={"github": "12202025_01"}
)
Sources: python/README.md:1-50
Tool Client
The tool client module (composio/client/__init__.py) manages all interactions with tools, including retrieval, filtering, and execution. It provides a typed interface for working with tools and toolkits through the types defined in client/types.py. Sources: python/composio/client/__init__.py:1-50
Type System
The SDK uses Pydantic models for type safety and validation. All tool schemas, parameters, and return types are strongly typed through the Tool and related classes in client/types.py. Sources: python/composio/client/types.py:1-100
Configuration
Initialization Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
api_key | str | Environment COMPOSIO_API_KEY | Your Composio API key |
base_url | str | "https://api.composio.dev" | Custom API base URL |
timeout | int | 60 | Request timeout in seconds |
max_retries | int | 3 | Maximum retry attempts |
allow_tracking | bool | True | Enable/disable telemetry |
file_download_dir | str | "./downloads" | Directory for file downloads |
provider | Provider | OpenAIProvider() | Custom provider instance |
toolkit_versions | dict | {} | Specific toolkit versions |
Sources: python/composio/sdk.py:50-100
Environment Variables
The SDK automatically reads several environment variables for configuration:
| Variable | Description |
|---|---|
COMPOSIO_API_KEY | Primary API authentication key |
COMPOSIO_BASE_URL | Override default API endpoint |
COMPOSIO_WORKING_DIR | Session working directory |
COMPOSIO_LOG_LEVEL | Logging level (silent, error, warn, info, debug) |
COMPOSIO_TOOLKIT_VERSION_<TOOLKITNAME> | Version for specific toolkit |
DEVELOPMENT | Development mode flag |
CI | CI environment flag |
Sources: python/README.md:100-150
Tool Management
Retrieving Tools
# Get all tools from a specific toolkit
tools = composio.tools.get(
user_id="default",
toolkits=["gmail", "github"]
)
# Get a specific tool by slug
tool = composio.tools.get(
user_id="default",
slug="GITHUB_CREATE_ISSUE"
)
Sources: python/README.md:50-80
Tool Structure
Tools in the Composio SDK follow a standardized structure that includes:
- Slug: Unique identifier for the tool
- Name: Human-readable display name
- Description: Detailed explanation of tool functionality
- Parameters: JSON schema for input validation
- Toolkit: Parent toolkit grouping
- Triggers: Associated trigger configurations
Sources: python/composio/client/types.py:50-100
Schema Modifiers
Schema modifiers allow transformation of tool schemas before they are used by AI models. This enables customization of parameter descriptions, adding defaults, or restructuring schemas.
graph LR
A[Raw Tool Schema] --> B[Schema Modifier Function]
B --> C[Modified Schema]
C --> D[AI Model / Tool Execution]Usage Example
from composio import schema_modifier
from composio.types import Tool
@schema_modifier(tools=["HACKERNEWS_GET_USER"])
def modify_schema(tool: str, toolkit: str, schema: Tool) -> Tool:
schema["description"] = "Enhanced HackerNews user lookup with additional features"
schema["parameters"]["properties"]["include_karma"] = {
"type": "boolean",
"description": "Include user karma in response",
"default": True
}
return schema
# Apply modifier when retrieving tools
tools = composio.tools.get(
user_id="default",
slug="HACKERNEWS_GET_USER",
modifiers=[modify_schema]
)
Sources: python/README.md:80-120
Execution Modifiers
Execution modifiers provide hooks for transforming tool execution behavior. They come in two flavors: before_execute and after_execute.
graph TD
A[Tool Call Request] --> B[Before Execute Hook]
B --> C{Continue?}
C -->|Yes| D[Execute Tool]
C -->|No| E[Return Modified Response]
D --> F[After Execute Hook]
F --> G[Final Response]Before Execute Hook
from composio import before_execute
@before_execute(tools=["GITHUB_CREATE_ISSUE"])
def validate_issue_input(tool: str, toolkit: str, params: dict) -> dict:
# Validate or transform parameters before execution
if "title" in params and len(params["title"]) > 100:
params["title"] = params["title"][:97] + "..."
return params
After Execute Hook
from composio import after_execute
@after_execute(tools=["GITHUB_CREATE_ISSUE"])
def log_issue_creation(tool: str, toolkit: str, params: dict, response: dict) -> dict:
# Post-process the response
print(f"Issue created: {response.get('html_url')}")
return response
Sources: python/README.md:120-180
Tool Router (Experimental)
The Tool Router is an experimental feature that enables intelligent tool routing and session management. It provides capabilities for dynamic tool selection, retry logic, and stateful interactions.
graph TD
A[User Request] --> B[Tool Router]
B --> C[Session Manager]
C --> D{Route Decision}
D -->|Tool A| E[Execute Tool A]
D -->|Tool B| F[Execute Tool B]
E --> G[Response Handler]
F --> G
G --> H[User Response]Tool Router Configuration
| Parameter | Type | Description |
|---|---|---|
base_url | str | Composio API base URL |
api_key | str | API authentication key |
tool_calls_max_concurrency | int | Maximum concurrent tool calls |
default_language | str | Default language for responses |
Sources: python/composio/core/models/tool_router.py:1-100
Tool Router Session
The session management system (tool_router_session.py) maintains state across multiple tool interactions, enabling complex multi-step workflows:
from composio.core.models.tool_router_session import ToolRouterSession
session = ToolRouterSession(
user_id="user123",
session_id="session456",
tool_calls=[]
)
Sources: python/composio/core/models/tool_router_session.py:1-50
Tool Definitions
Custom tool definitions can be provided to the Tool Router for specialized behavior:
from composio.core.models.tool_router import ToolDefinition
tools = [
ToolDefinition(
name="custom_tool",
description="A custom tool implementation",
parameters={"type": "object", "properties": {}}
)
]
Sources: python/examples/tool_router/tools.py:1-50
MCP (Model Context Protocol) Support
The SDK provides native MCP server creation for seamless integration with Claude, Cursor, and other MCP-compatible tools.
graph LR
A[Composio SDK] --> B[MCP Server]
B --> C[Claude Desktop]
B --> D[Cursor]
B --> E[Other MCP Clients]Creating an MCP Server
from composio import Composio
composio = Composio()
# Create MCP server with specified toolkits
mcp_server = composio.mcp.create(
"my-mcp-server",
toolkits=["github", "gmail"],
manually_manage_connections=False
)
# Generate server instance for a user
server_instance = mcp_server.generate("user123")
print(f"MCP Server URL: {server_instance['url']}")
Sources: python/README.md:200-230
Error Handling
The SDK defines specific exception types for different error scenarios, enabling precise error handling in application code.
from composio import Composio
from composio.exceptions import ComposioError, ApiKeyNotProvidedError
try:
composio = Composio() # Will raise ApiKeyNotProvidedError if no API key
tools = composio.tools.get(user_id="default", toolkits=["github"])
except ApiKeyNotProvidedError:
print("Please provide your COMPOSIO_API_KEY")
except ComposioError as e:
print(f"Composio error: {e}")
Exception Hierarchy
| Exception | Base Class | Description |
|---|---|---|
ComposioError | Exception | Base exception for all SDK errors |
ApiKeyNotProvidedError | ComposioError | API key missing or invalid |
ToolNotFoundError | ComposioError | Requested tool does not exist |
ToolkitNotFoundError | ComposioError | Requested toolkit not available |
ConnectionError | ComposioError | Network connectivity issues |
TimeoutError | ComposioError | Request exceeded timeout |
Sources: python/composio/exceptions.py:1-50
Supported AI Frameworks
The SDK provides dedicated integrations for popular AI frameworks:
| Framework | Description | Provider Class |
|---|---|---|
| OpenAI | Direct integration with OpenAI's API | OpenAIProvider() |
| LangChain | Tools and agents for LangChain workflows | LangChainProvider() |
| LangGraph | State machine workflows | LangGraphProvider() |
| CrewAI | Multi-agent systems | CrewAIProvider() |
| AutoGen | Microsoft's AutoGen framework | AutoGenProvider() |
| Anthropic | Claude integration | AnthropicProvider() |
| Google AI | Gemini and Google AI services | GoogleAIProvider() |
| LlamaIndex | RAG and data framework | LlamaIndexProvider() |
from composio import Composio
from composio_providers import OpenAIProvider
composio = Composio(provider=OpenAIProvider())
Sources: python/README.md:180-200
Development and Testing
Development Setup
For local development, ensure you have the required dependencies installed:
cd python
uv sync
Integration Testing
Integration tests are located in python/composio/integration_test/ and require a valid Composio API key:
export COMPOSIO_API_KEY="your_api_key_here"
pytest python/composio/integration_test/ -v
Sources: python/composio/integration_test/README.md:1-30
Available Test Modules
| Test File | Coverage |
|---|---|
test_mcp.py | MCP functionality and server creation |
test_tool_router.py | Tool Router experimental features |
Quick Start Example
from composio import Composio
from composio_claude_agent_sdk import ClaudeAgentSDKProvider
# Initialize with a provider
composio = Composio(provider=ClaudeAgentSDKProvider())
# Get tools from specific toolkits
tools = composio.tools.get(
user_id="default",
toolkits=["gmail", "github"]
)
# Create MCP server configuration
mcp_server = composio.provider.create_mcp_server(tools)
# Tools are now available to your AI agent
Sources: python/providers/claude_agent_sdk/README.md:1-50
Best Practices
- API Key Management: Store your API key in environment variables rather than hardcoding
- Timeout Configuration: Adjust timeout based on expected tool execution times
- Error Handling: Always wrap SDK calls in try-except blocks for graceful degradation
- Modifier Usage: Apply schema and execution modifiers at initialization for consistent behavior
- Tool Filtering: Use specific toolkits rather than fetching all tools to reduce latency
Sources: python/README.md:1-50
AI Framework Providers
Related topics: TypeScript SDK, Python SDK, Core Concepts
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: TypeScript SDK, Python SDK, Core Concepts
AI Framework Providers
Overview
AI Framework Providers are adapter layers that integrate Composio's tool ecosystem with various AI agent frameworks. They act as bridges between Composio's standardized tool definitions and the specific formats expected by different AI SDKs and frameworks such as OpenAI, Anthropic Claude Code, LangChain, LlamaIndex, and CrewAI.
Providers enable agents to:
- Access Composio tools in their native format
- Transform tool schemas for framework-specific requirements
- Handle tool execution with custom modifiers
- Create MCP (Model Context Protocol) servers from Composio tool definitions
Sources: ts/docs/api/providers.md
Architecture
Provider Hierarchy
graph TD
A[BaseComposioProvider] --> B[BaseNonAgenticProvider]
A --> C[BaseAgenticProvider]
B --> D[OpenAIProvider]
B --> E[AnthropicProvider]
B --> F[LangChainProvider]
B --> G[LlamaIndexProvider]
C --> H[ClaudeAgentSDKProvider]
C --> I[VercelProvider]Data Flow
graph LR
A[Composio SDK] -->|Tool Requests| B[Provider]
B -->|Schema Transform| C[Framework-Specific Format]
C --> D[AI Agent/Framework]
D -->|Execution| E[Modifier Chain]
E -->|Result| F[Response Transform]
F -->|ToolExecuteResponse| AProvider Types
Non-Agentic Providers
Non-agentic providers wrap tools for frameworks that handle tool execution externally. They focus on schema transformation without managing execution flow.
Available Non-Agentic Providers:
| Provider | Package | Framework |
|---|---|---|
| OpenAIProvider | @composio/openai | OpenAI SDK |
| AnthropicProvider | @composio/anthropic | Anthropic SDK |
| LangChainProvider | @composio/langchain | LangChain |
| LlamaIndexProvider | @composio/llamaindex | LlamaIndex |
Sources: ts/packages/providers/openai/src/index.ts
Core Interface:
class NonAgenticProvider extends BaseNonAgenticProvider {
async wrapTool(
toolSlug: string,
tool: Tool,
modifiers?: SchemaModifiersParams
): Promise<Tool>;
async getTools(
modifiers?: SchemaModifiersParams
): Promise<Tool[]>;
async getToolBySlug(
slug: string,
modifiers?: SchemaModifiersParams
): Promise<Tool>;
}
Sources: ts/docs/providers/custom.md
Agentic Providers
Agentic providers manage both schema transformation and execution flow. They support before/after execute modifiers for full control over tool behavior.
Core Interface:
class AgenticProvider extends BaseAgenticProvider {
async wrapTool(
toolSlug: string,
tool: Tool,
modifiers?: ModifiersParams
): Promise<Tool>;
async getTools(
modifiers?: ModifiersParams
): Promise<Tool[]>;
async getToolBySlug(
slug: string,
modifiers?: ModifiersParams
): Promise<Tool>;
}
Sources: ts/docs/providers/custom.md
Available Agentic Providers:
| Provider | Package | Framework |
|---|---|---|
| ClaudeAgentSDKProvider | @composio/claude-agent-sdk | Claude Code Agents SDK |
| VercelProvider | @composio/vercel | Vercel AI SDK |
Core Methods
wrapTool
Transforms a single tool with optional modifiers for framework-specific formatting.
async wrapTool(
toolSlug: string,
tool: Tool,
modifiers?: SchemaModifiersParams
): Promise<Tool>
Parameters:
| Parameter | Type | Description |
|---|---|---|
| toolSlug | string | Unique identifier for the tool |
| tool | Tool | The tool definition to wrap |
| modifiers | SchemaModifiersParams | Optional schema transformation functions |
Returns: Promise<Tool> - The transformed tool
getTools
Retrieves all available tools, optionally filtered by toolkit and transformed with modifiers.
async getTools(
modifiers?: SchemaModifiersParams
): Promise<Tool[]>
getToolBySlug
Retrieves a specific tool by its slug identifier.
async getToolBySlug(
slug: string,
modifiers?: SchemaModifiersParams
): Promise<Tool>
Sources: ts/packages/providers/openai/src/index.ts
Modifiers System
Modifiers enable runtime transformation of tool schemas and execution behavior.
Schema Modifiers
Transform tool schemas before they are used by the agent:
type schemaModifier = (
toolSlug: string,
tool: Tool
) => Tool;
Execution Modifiers
Control tool execution flow:
type beforeExecuteModifier = (
toolSlug: string,
params: Record<string, unknown>
) => Record<string, unknown>;
type afterExecuteModifier = (
toolSlug: string,
response: ToolExecuteResponse
) => ToolExecuteResponse;
Modifier Application Flow
graph TD
A[Request Tool] --> B{Modifier Chain}
B --> C[Schema Modifier]
C --> D[Before Execute Modifier]
D --> E[Tool Execution]
E --> F[After Execute Modifier]
F --> G[Return Response]Sources: ts/packages/core/src/types/modifiers.types.ts
Python Providers
OpenAI Provider
from composio_openai import ComposioOpenAI
client = ComposioOpenAI(api_key="your-api-key")
# Get tools
tools = client.tools.get()
# Execute a tool
result = client.tools.execute(
action="HACKERNEWS_GET_USER",
params={"username": "user123"}
)
Sources: python/providers/openai/composio_openai/provider.py
LangChain Provider
from composio_langchain import ComposioToolkit, Action
# Initialize with LangChain adapter
toolkit = ComposioToolkit(
actions=[Action.HACKERNEWS_GET_USER]
)
# Get LangChain tools
langchain_tools = toolkit.get_tools()
Sources: python/providers/langchain/composio_langchain/provider.py
CrewAI Provider
from composio_crewai import ComposioTool, Action
from crewai import Agent
# Create Composio tool for CrewAI
composio_tool = ComposioTool(
action=Action.HACKERNEWS_GET_USER
)
# Attach to CrewAI agent
agent = Agent(
role="Researcher",
goal="Fetch user data",
tools=[composio_tool]
)
Sources: python/providers/crewai/composio_crewai/providers.py
TypeScript Provider Implementation
OpenAI Provider
import { BaseNonAgenticProvider } from '@composio/core';
import type { Tool, SchemaModifiersParams } from '@composio/core';
export class OpenAIProvider extends BaseNonAgenticProvider {
async wrapTool(
toolSlug: string,
tool: Tool,
modifiers?: SchemaModifiersParams
): Promise<Tool> {
if (modifiers?.schema) {
return modifiers.schema(toolSlug, tool);
}
return tool;
}
async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]> {
const response = await this.client.getTools();
return Promise.all(
response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers))
);
}
async getToolBySlug(
slug: string,
modifiers?: SchemaModifiersParams
): Promise<Tool> {
const response = await this.client.getToolBySlug(slug);
return this.wrapTool(slug, response.data, modifiers);
}
}
Sources: ts/packages/providers/openai/src/index.ts
Anthropic Provider
import { BaseNonAgenticProvider } from '@composio/core';
import type { Tool, SchemaModifiersParams } from '@composio/core';
export class AnthropicProvider extends BaseNonAgenticProvider {
// Similar implementation to OpenAIProvider
// Framework-specific adaptations applied in wrapTool
}
Sources: ts/packages/providers/anthropic/src/index.ts
LlamaIndex Provider
import { BaseNonAgenticProvider } from '@composio/core';
import type { Tool, SchemaModifiersParams } from '@composio/core';
export class LlamaIndexProvider extends BaseNonAgenticProvider {
// LlamaIndex-specific implementation
}
Sources: ts/packages/providers/llamaindex/src/index.ts
Creating Custom Providers
Project Structure
my-provider/
├── src/
│ └── index.ts # Provider implementation
├── package.json # Package configuration
├── tsconfig.json # TypeScript configuration
├── tsup.config.ts # Build configuration
└── README.md # Provider documentation
Generation Command
# Non-agentic provider (default)
pnpm create:provider my-provider
# Agentic provider
pnpm create:provider my-provider --agentic
Required Methods
#### For Non-Agentic Providers
import { BaseNonAgenticProvider } from '@composio/core';
import type { Tool, SchemaModifiersParams } from '@composio/core';
export class MyProvider extends BaseNonAgenticProvider {
async wrapTool(
toolSlug: string,
tool: Tool,
modifiers?: SchemaModifiersParams
): Promise<Tool> {
// Apply schema modifiers if provided
if (modifiers?.schema) {
return modifiers.schema(toolSlug, tool);
}
return tool;
}
async getTools(
modifiers?: SchemaModifiersParams
): Promise<Tool[]> {
const response = await this.client.getTools();
return Promise.all(
response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers))
);
}
async getToolBySlug(
slug: string,
modifiers?: SchemaModifiersParams
): Promise<Tool> {
const response = await this.client.getToolBySlug(slug);
return this.wrapTool(slug, response.data, modifiers);
}
}
#### For Agentic Providers
import { BaseAgenticProvider } from '@composio/core';
import type { Tool, ModifiersParams, ToolExecuteResponse } from '@composio/core';
export class MyAgenticProvider extends BaseAgenticProvider {
async wrapTool(
toolSlug: string,
tool: Tool,
modifiers?: ModifiersParams
): Promise<Tool> {
if (modifiers?.schema) {
return modifiers.schema(toolSlug, tool);
}
return tool;
}
async getTools(
modifiers?: ModifiersParams
): Promise<Tool[]> {
const response = await this.client.getTools();
return Promise.all(
response.data.map(tool => this.wrapTool(tool.slug, tool, modifiers))
);
}
async getToolBySlug(
slug: string,
modifiers?: ModifiersParams
): Promise<Tool> {
const response = await this.client.getToolBySlug(slug);
return this.wrapTool(slug, response.data, modifiers);
}
}
Best Practices
Type Safety
Always use TypeScript and ensure proper type definitions for all methods and parameters. Leverage the existing type definitions from @composio/core:
import type {
Tool,
SchemaModifiersParams,
ModifiersParams,
ToolExecuteResponse
} from '@composio/core';
Error Handling
Implement proper error handling for API calls and tool execution:
async getTools(modifiers?: SchemaModifiersParams): Promise<Tool[]> {
try {
const response = await this.client.getTools();
return response.data;
} catch (error) {
throw new ComposioProviderError(
`Failed to fetch tools: ${error.message}`,
{ cause: error }
);
}
}
Modifier Support
- Non-agentic providers: Implement schema modifiers to transform tool schemas
- Agentic providers: Implement both schema and execution modifiers for full control
Testing
Write comprehensive tests covering:
- Tool wrapping with and without modifiers
- Error scenarios for API failures
- Edge cases in modifier application
- Framework-specific format compliance
Provider Options
Provider behavior can be configured through ProviderOptions:
type ProviderOptions<TProvider> =
TProvider extends BaseComposioProvider<infer TToolCollection, infer TTool, infer TMcpResponse>
? TProvider extends BaseAgenticProvider<TToolCollection, TTool, TMcpResponse>
? AgenticToolOptions
: ToolOptions
: never;
| Option Type | Use Case |
|---|---|
ToolOptions | Non-agentic providers |
AgenticToolOptions | Agentic providers with execution control |
Sources: ts/packages/core/src/types/modifiers.types.ts
Summary
AI Framework Providers are essential integration layers that enable Composio tools to work seamlessly with various AI agent frameworks. They provide:
- Abstraction: Unified interface for diverse AI frameworks
- Transformation: Schema adaptation for framework-specific formats
- Extensibility: Custom provider creation for unsupported frameworks
- Control: Modifier system for runtime behavior customization
The provider architecture supports both simple schema wrapping (non-agentic) and full execution control (agentic), making it adaptable to a wide range of AI framework requirements.
Sources: ts/docs/api/providers.md
Toolkits Management
Related topics: Custom Tools and Toolkits, Core Concepts, AI Framework Providers
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Custom Tools and Toolkits, Core Concepts, AI Framework Providers
Toolkits Management
Overview
Toolkits Management is the system responsible for organizing, discovering, and configuring collections of tools and triggers within Composio. Toolkits serve as the fundamental unit of organization for functionality, grouping related tools under a common namespace with shared metadata, versioning, and configuration options.
The management system encompasses both remote toolkits (hosted and managed by Composio) and local toolkits (user-defined or third-party tools executed locally via the CLI). This dual approach provides flexibility for different use cases while maintaining a consistent interface for tool execution and configuration.
Sources: ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts:1-16
Architecture
graph TD
A[Toolkits Management] --> B[Remote Toolkits]
A --> C[Local Toolkits]
B --> B1[Toolkit Index]
B --> B2[Version Overrides]
B --> B3[Validation]
C --> C1[Registry]
C --> C2[Readiness Check]
C --> C3[Configuration]
B1 --> D[createToolkitIndex]
B2 --> E[buildVersionMapFromSpecs]
B3 --> F[validateToolkitVersions]
C1 --> G[getLocalCustomToolkits]
C2 --> H[LocalToolkitReadiness]
C3 --> I[localToolsCmd$Configure]Core Components
| Component | Purpose | Location |
|---|---|---|
| Toolkit Index | Groups tools/triggers by toolkit name | ts/packages/cli/src/generation/create-toolkit-index.ts |
| Version Overrides | Manages toolkit version specifications | ts/packages/cli/src/effects/toolkit-version-overrides.ts |
| Version Validation | Validates toolkit versions against API | ts/packages/cli/src/effects/validate-toolkit-versions.ts |
| Local Registry | Manages local toolkit declarations | ts/packages/cli-local-tools/src/registry.ts |
| Readiness Check | Determines toolkit availability status | ts/packages/cli-local-tools/src/readiness.ts |
| Configuration | Handles toolkit/tool configuration | ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts |
Toolkit Discovery (CLI Commands)
The Composio CLI provides a comprehensive set of commands for toolkit discovery under the toolkits command group.
Sources: ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts:14-23
Available Commands
composio toolkits <command>
| Command | Description |
|---|---|
list | List available toolkits |
info | Display detailed information about a specific toolkit |
search | Search for toolkits by name or keywords |
version | Manage toolkit version information |
Command Examples
# List all available toolkits
composio toolkits list
# Get info about a specific toolkit
composio toolkits info gmail
# Search for toolkits
composio toolkits search "email"
# Check toolkit versions
composio toolkits version
Toolkit Index System
The toolkit index is a structured mapping that organizes tools and trigger types by their corresponding toolkit name.
Sources: ts/packages/cli/src/generation/create-toolkit-index.ts:1-30
Data Model
interface CreateToolkitIndexInput {
readonly slug: string;
readonly version?: string;
readonly typeableTools:
| { withTypes: false; value: Record<`${ToolkitName}_${string}`, ToolAsEnum> }
| { withTypes: true; value: Record<`${ToolkitName}_${string}`, Tool> };
readonly triggerTypes: Record<`${ToolkitName}_${string}`, TriggerType>;
}
type ToolkitIndex = Record<ToolkitName, ToolkitIndexData>;
Index Creation Process
graph LR
A[Input Data] --> B[groupByToolkits]
B --> C[Record.fromEntries]
C --> D[stripPrefix]
D --> E[ToolkitIndex]The createToolkitIndex function performs the following operations:
- Groups tools and trigger types by their toolkit prefix
- Converts the grouped data to a Record
- Strips the toolkit prefix from individual tool/trigger identifiers
- Applies version overrides when specified
Sources: ts/packages/cli/src/generation/create-toolkit-index.ts:23-45
Local Toolkit Registry
The local toolkit registry manages toolkits that are executed locally through the CLI rather than through the Composio API.
Sources: ts/packages/cli-local-tools/src/registry.ts:1-50
Registry Functions
| Function | Purpose |
|---|---|
getAllLocalToolkitSlugs | Returns all registered local toolkit slugs |
isLocalToolkitSlug | Checks if a slug corresponds to a local toolkit |
isLocalToolSlug | Checks if a tool slug is a local tool |
getLocalToolkitDeclarations | Gets declarations filtered by platform/toolkits |
getLocalCustomToolkits | Returns CustomToolkit objects for local toolkits |
Filtering Logic
const toolkitMatchesFilter = (
toolkit: LocalToolkitDeclaration,
requestedToolkits?: ReadonlyArray<string>
): boolean => {
if (!requestedToolkits || requestedToolkits.length === 0) return true;
const requested = new Set(requestedToolkits.map(slug => slug.toLowerCase()));
return requested.has(toolkit.slug.toLowerCase());
};
The filtering is case-insensitive, supporting flexible user input while maintaining consistent internal representation.
Sources: ts/packages/cli-local-tools/src/registry.ts:15-23
Toolkit Declaration Structure
Local toolkit declarations follow this structure:
interface LocalToolkitDeclaration {
slug: string;
name: string;
description: string;
platforms: ReadonlyArray<LocalCliPlatform>;
tools: ReadonlyArray<LocalToolDeclaration>;
source: string;
setup?: ToolkitSetup;
}
Toolkit Readiness Assessment
The readiness system evaluates whether local toolkits and their tools are available for use based on platform support and configuration state.
Sources: ts/packages/cli-local-tools/src/readiness.ts:1-50
Readiness States
| Status | Description |
|---|---|
ready | Toolkit and all tools are available |
disabled | Toolkit is disabled via local_tools.json metadata |
unsupported | Toolkit platforms do not include current platform |
Readiness Report Structure
interface LocalToolkitReadiness {
slug: string;
name: string;
description: string;
platforms: ReadonlyArray<LocalCliPlatform>;
supported: boolean;
status: 'ready' | 'disabled' | 'unsupported';
source: string;
setup?: ToolkitSetup;
tools: LocalToolReadiness[];
messages: string[];
hints: SetupHint[];
}
Platform Support Check
The system detects the current platform and filters toolkits based on platform compatibility:
const currentPlatform = options.currentPlatform ?? detectCliPlatform();
return declarationsFor(options.declarations)
.filter(toolkit => supportsCliPlatform(toolkit.platforms, currentPlatform))
.filter(toolkit => toolkit.tools.length > 0);
Toolkit Version Management
Composio supports version pinning for toolkits to ensure consistent behavior across environments.
Sources: ts/packages/cli/src/effects/toolkit-version-overrides.ts:1-60
Version Specification
interface ToolkitVersionSpec {
toolkitSlug: string;
toolkitVersion: string; // e.g., '20250901_00' or 'latest'
}
Grouping by Version
export const groupByVersion = (
specs: ReadonlyArray<ToolkitVersionSpec>
): Map<string, Lowercase<string>[]> => {
const grouped = new Map<string, Lowercase<string>[]>();
for (const spec of specs) {
const existing = grouped.get(spec.toolkitVersion);
if (existing) {
existing.push(spec.toolkitSlug);
} else {
grouped.set(spec.toolkitVersion, [spec.toolkitSlug]);
}
}
return grouped;
};
This produces a mapping like:
"20250901_00" => ["gmail"]
"latest" => ["slack", "github"]
Version Map Building
export const buildVersionMapFromSpecs = (
specs: ReadonlyArray<ToolkitVersionSpec>
): ToolkitVersionOverrides => {
const versionMap = new Map<Lowercase<string>, string>();
for (const spec of specs) {
if (spec.toolkitVersion !== 'latest') {
versionMap.set(spec.toolkitSlug, spec.toolkitVersion);
}
}
return versionMap;
};
Note: 'latest' versions are excluded from the version map since they represent the default behavior.
Toolkit Version Validation
Before applying version overrides, the system validates them against the Composio API.
Sources: ts/packages/cli/src/effects/validate-toolkit-versions.ts:1-60
Validation Process
graph TD
A[Version Overrides] --> B{validateToolkitVersions}
B --> C[Check toolkit existence]
B --> D[Verify version availability]
C -->|Invalid| E[InvalidToolkitsError]
D -->|Invalid| F[InvalidToolkitVersionsError]
C -->|Valid| G[Return validated overrides]
D -->|Valid| GError Handling
| Error Type | Cause | User Message |
|---|---|---|
InvalidToolkitsError | Toolkit slug doesn't exist | Invalid toolkit(s) specified |
InvalidToolkitVersionsError | Version doesn't exist for toolkit | Invalid version for specific toolkit |
HttpServerError | API communication failure | Network or server error |
Toolkit Configuration
Local toolkits can be configured through the CLI, allowing users to customize installation commands, enable/disable tools, and manage authentication.
Sources: ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts:1-50
Configuration Options
composio local-tools configure --selector <toolkit-or-tool> [options]
| Option | Description |
|---|---|
--command | Override installation command |
--disable | Disable the toolkit or tool |
--enable | Enable the toolkit or tool |
--authenticated | Mark as authenticated |
--unauthenticated | Mark as not authenticated |
Metadata Storage
Configuration is stored in ~/composio/local_tools.json with the following structure:
interface LocalToolMetadata {
disabled?: boolean;
authenticated?: boolean;
installation?: {
command?: string;
};
}
Display Configuration Info
When configuring a toolkit or tool, the CLI displays:
Name: <toolkit/tool name>
Kind: <toolkit|tool>
Path: <metadata path>
Command: <installation command or '-'>
Disabled: <true/false/->
Authenticated: <true/false/->
Tool Permission System
Composio implements a permission system for tool execution to ensure security and user control.
Sources: ts/packages/cli/src/services/tool-permissions.ts:1-60
Permission Flow
graph TD
A[Tool Execution Request] --> B{Permission Check}
B -->|First time| C[Browser Prompt]
B -->|Previously allowed| D[Execute Tool]
C --> E[Allow for session]
C --> F[Allow once]
C --> G[Deny]
E --> D
F --> H[Execute once]
H --> DPermission Decision Types
| Decision | Scope | Persistence |
|---|---|---|
ALLOW_SESSION | All executions in current session | Session-scoped |
ALLOW_ONCE | Single execution | Single use |
DENY | Block execution | Single use |
Browser-based Permission Request
When permission is required, a local HTTP server is started on port 127.0.0.1 (configurable) with an HTML interface presenting the three options.
Integration with TypeScript Generation
The toolkit system integrates with Composio's TypeScript type generation to provide type-safe tool access.
Sources: ts/packages/cli/src/commands/ts/commands/ts.generate.cmd.ts:1-30
Generation Options
composio generate ts [options]
| Option | Description | Default |
|---|---|---|
--compact | Emit single module file | false |
--transpiled | Include transpiled JS | true (if no --output-dir) |
--output-dir | Output directory | node_modules/@composio/core |
--toolkits | Filter by toolkit(s) | All toolkits |
Invariants
--output-dircannot refer to a path insidenode_modules- If
--output-diris not specified,--transpileddefaults to true - If
--output-diris specified,--transpileddefaults to false
Summary
Toolkits Management in Composio provides a comprehensive system for organizing and managing tools with the following key capabilities:
- Discovery: CLI commands for listing, searching, and inspecting available toolkits
- Indexing: Automatic organization of tools and triggers by toolkit prefix
- Local Support: Registry and execution system for locally-defined toolkits
- Version Control: Version pinning with validation against the Composio API
- Configuration: Flexible configuration of toolkit behavior including installation commands and enable/disable states
- Permissions: Security layer for tool execution with session and one-time permission grants
- Type Safety: Integration with TypeScript generation for type-safe tool usage
The architecture separates concerns between remote toolkits (API-managed) and local toolkits (CLI-managed), while providing a unified interface for tool execution and configuration.
Sources: ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts:1-16
Custom Tools and Toolkits
Related topics: Toolkits Management, Core Concepts
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Toolkits Management, Core Concepts
Custom Tools and Toolkits
Overview
Custom Tools and Toolkits are the fundamental building blocks in Composio that enable agents to interact with external services and perform specific actions. A Custom Tool represents a single executable action with defined input parameters and output schemas, while a Custom Toolkit is a collection of related tools grouped under a common namespace.
The Composio framework provides both TypeScript (@composio/core) and Python (composio-core) SDKs for defining, creating, and managing custom tools and toolkits. This architecture allows developers to extend Composio's capabilities by creating specialized tools for their specific use cases.
Sources: ts/packages/providers/README.md
Architecture
High-Level Architecture
graph TD
A[Developer] --> B[Custom Tool Definition]
B --> C[CustomTool Instance]
C --> D[CustomToolkit Container]
D --> E[Composio Client]
E --> F[Tool Execution Engine]
G[Agent] --> E
E --> H[Tool Response]
H --> GComponent Hierarchy
graph TD
A[CustomToolkit] --> B[Tool 1]
A --> C[Tool 2]
A --> D[Tool N]
B --> E[Name]
B --> F[Description]
B --> G[InputParams]
B --> H[OutputParams]
B --> I[Execute Function]
E --> J[slug]
J --> K[displayName]Custom Tool Structure
TypeScript Implementation
Custom tools in TypeScript are created using the createCustomTool factory function, which accepts a tool slug and a configuration object.
Sources: ts/packages/cli-local-tools/src/registry.ts:65-79
const toCustomTool = (
toolkit: LocalToolkitDeclaration,
tool: LocalToolDeclaration,
currentPlatform: LocalCliPlatform
) =>
createCustomTool(tool.slug, {
name: tool.name,
description: descriptionWithPlatform(tool.description, tool.platforms),
inputParams: tool.inputParams,
...(tool.outputParams ? { outputParams: tool.outputParams } : {}),
execute: async input =>
executeLocalTool(tool.execution, input as Record<string, unknown>, {
toolkit,
tool,
finalSlug: normalizeLocalToolSlug(tool.slug, toolkit.slug),
platform: currentPlatform,
}),
});
Tool Properties
| Property | Type | Required | Description |
|---|---|---|---|
slug | string | Yes | Unique identifier for the tool |
name | string | Yes | Human-readable display name |
description | string | Yes | Detailed explanation of tool functionality |
inputParams | Parameter[] | No | Array of input parameter definitions |
outputParams | Parameter[] | No | Array of output parameter definitions |
execute | Function | Yes | Async function that performs the tool action |
triggers | Trigger[] | No | Event triggers associated with the tool |
Input/Output Parameters
Parameters define the schema for tool inputs and outputs using a structured format:
interface Parameter {
name: string; // Parameter identifier
type: 'string' | 'number' | 'boolean' | 'object' | 'array';
description: string; // Human-readable explanation
required: boolean; // Whether the parameter is mandatory
default?: any; // Optional default value
enum?: string[]; // For restricted value sets
}
Custom Toolkit Structure
Creating a Toolkit
Toolkits group related tools under a common namespace and platform context.
Sources: ts/packages/cli-local-tools/src/registry.ts:81-88
const toCustomToolkit = (
toolkit: LocalToolkitDeclaration,
currentPlatform: LocalCliPlatform
): CustomToolkit =>
createCustomToolkit(toolkit.slug, {
name: toolkit.name,
description: descriptionWithPlatform(toolkit.description, toolkit.platforms),
tools: toolkit.tools.map(tool => toCustomTool(toolkit, tool, currentPlatform)),
});
Toolkit Properties
| Property | Type | Required | Description |
|---|---|---|---|
slug | string | Yes | Unique toolkit identifier |
name | string | Yes | Display name for the toolkit |
description | string | Yes | Toolkit documentation |
tools | CustomTool[] | Yes | Collection of tools in this toolkit |
platforms | LocalCliPlatform[] | Yes | Supported platforms (e.g., linux, darwin, windows) |
Toolkit Discovery and Filtering
Filtering by Platform
Composio provides functions to filter toolkits and tools based on the current platform:
Sources: ts/packages/cli-local-tools/src/registry.ts:55-63
const toolkitMatchesFilter = (
toolkit: LocalToolkitDeclaration,
requestedToolkits?: ReadonlyArray<string>
): boolean => {
if (!requestedToolkits || requestedToolkits.length === 0) return true;
const requested = new Set(requestedToolkits.map(slug => slug.toLowerCase()));
return requested.has(toolkit.slug.toLowerCase());
};
Getting Local Toolkit Declarations
export const getLocalToolkitDeclarations = (
options: {
readonly currentPlatform?: LocalCliPlatform;
readonly toolkits?: ReadonlyArray<string>;
readonly declarations?: ReadonlyArray<LocalToolkitDeclaration>;
} = {}
): ReadonlyArray<LocalToolkitDeclaration> => {
const currentPlatform = options.currentPlatform ?? detectCliPlatform();
return declarationsFor(options.declarations)
.filter(toolkit => toolkitMatchesFilter(toolkit, options.toolkits))
.filter(toolkit => supportsCliPlatform(toolkit.platforms, currentPlatform))
.map(toolkit => ({
...toolkit,
tools: toolkit.tools.filter(tool => supportsCliPlatform(tool.platforms, currentPlatform)),
}))
.filter(toolkit => toolkit.tools.length > 0);
};
Toolkit Index Generation
The toolkit index creates a structured mapping of all tools organized by their parent toolkit.
Sources: ts/packages/cli/src/generation/create-toolkit-index.ts:22-45
export function createToolkitIndex(input: CreateToolkitIndexInput): Simplify<ToolkitIndex> {
const { versionMap } = input;
return pipe(
input,
groupByToolkits,
Record.fromEntries,
Record.mapEntries((value, key) => {
const stripPrefix = String.slice(key.length + 1);
const { slug } = value.toolkit;
// Look up version override for this toolkit (lowercase key lookup)
const version = versionMap?.get(String.toLowerCase(slug));
// ... further processing
})
);
}
CLI Commands for Toolkits
Composio CLI provides comprehensive commands for toolkit management:
Sources: ts/packages/cli/src/commands/toolkits/toolkits.cmd.ts
| Command | Description |
|---|---|
composio toolkits list | List all available toolkits |
composio toolkits info <slug> | Display detailed toolkit information |
composio toolkits search <query> | Search toolkits by name or description |
composio toolkits version | Manage toolkit version overrides |
Command Examples
# List toolkits
composio toolkits list
# Get toolkit information
composio toolkits info "gmail"
# Search for toolkits
composio toolkits search "email"
Sources: ts/packages/cli/src/services/command-hints.ts:15-30
Version Management
Toolkit Version Overrides
Composio supports version pinning for toolkits, allowing specific versions to be used instead of the latest release.
Sources: ts/packages/cli/src/effects/toolkit-version-overrides.ts:16-35
export const buildVersionMapFromSpecs = (
specs: ReadonlyArray<ToolkitVersionSpec>
): ToolkitVersionOverrides => {
const versionMap = new Map<Lowercase<string>, string>();
for (const spec of specs) {
if (spec.toolkitVersion !== 'latest') {
versionMap.set(spec.toolkitSlug, spec.toolkitVersion);
}
}
return versionMap;
};
Version Grouping
Toolkits can be grouped by their version specification:
export const groupByVersion = (
specs: ReadonlyArray<ToolkitVersionSpec>
): Map<string, Lowercase<string>[]> => {
const grouped = new Map<string, Lowercase<string>[]>();
// Groups toolkits by version string
return grouped;
};
Version Validation
Before applying version overrides, Composio validates that all specified versions and toolkit slugs are valid:
Sources: ts/packages/cli/src/effects/validate-toolkit-versions.ts
export const validateToolkitVersionOverrides = ({
versionOverrides,
toolkitSlugsFilter,
client,
}): Effect.Effect<ValidateVersionsResult, Error, TerminalUI> =>
Effect.gen(function* () {
const ui = yield* TerminalUI;
// Skip if no overrides
if (versionOverrides.size === 0) {
return { validatedOverrides: versionOverrides };
}
// ... validation logic
});
Local Tools Configuration
Configuration File
Local tools can be configured via ~/composio/local_tools.json:
Sources: ts/packages/cli/src/commands/local-tools/commands/local-tools.configure.cmd.ts
# Configure a toolkit
composio local-tools configure --selector <toolkit-slug> --command "<install-command>"
# Disable a tool
composio local-tools configure --selector <tool-name> --disable
# Enable authentication
composio local-tools configure --selector <tool-name> --authenticated
Configuration Properties
| Property | Type | Description |
|---|---|---|
disabled | boolean | Whether the tool/kit is disabled |
authenticated | boolean | Whether authentication is required |
installation.command | string | Custom installation command |
metadataPath | string | Path to local metadata file |
Tool Readiness and Status
Readiness Checks
Composio performs readiness checks on local tools to determine their operational status:
Sources: ts/packages/cli-local-tools/src/readiness.ts
const status = toolkitSupported
? toolkitDisabled
? 'disabled'
: aggregateStatus(tools.map(tool => tool.status))
: 'unsupported';
Status Values
| Status | Description |
|---|---|
ready | Tool is fully operational |
disabled | Tool is explicitly disabled in configuration |
unsupported | Tool not supported on current platform |
needs_setup | Tool requires additional configuration |
Permission System
Tool Permission Flow
sequenceDiagram
participant Agent
participant ComposioCLI
participant HTTPServer
participant User
Agent->>ComposioCLI: Execute tool request
ComposioCLI->>HTTPServer: Start permission server
HTTPServer->>User: Show permission dialog
User->>HTTPServer: Allow/Deny decision
HTTPServer->>ComposioCLI: Return decision
ComposioCLI->>Agent: Execute or rejectPermission Decision Types
| Decision | Scope | Persistence |
|---|---|---|
allow_session | Current session | Temporary |
allow_once | Single execution | Single use |
deny | Rejected | Permanent for request |
Sources: ts/packages/cli/src/services/tool-permissions.ts
Logs and Monitoring
Log Commands
Composio provides commands to monitor tool and trigger execution:
Sources: ts/packages/cli/src/commands/logs-cmd/logs.cmd.ts
# View tool execution logs
composio dev logs tools <log_id>
# View trigger execution logs
composio dev logs triggers <log_id>
Provider Integration
Schema Modifiers
Custom tools support schema modification through provider options, enabling dynamic schema transformation:
Sources: ts/packages/core/src/types/modifiers.types.ts
export type ProviderOptions<TProvider> =
TProvider extends BaseComposioProvider<infer TToolCollection, infer TTool, infer TMcpResponse>
? TProvider extends BaseAgenticProvider<TToolCollection, TTool, TMcpResponse>
? AgenticToolOptions
: ToolOptions
: never;
Modifier Functions
| Function | Purpose |
|---|---|
modifySchema | Transform input/output schemas |
beforeExecute | Pre-execution hook for parameter manipulation |
afterExecute | Post-execution hook for result processing |
Usage Example
TypeScript
import { createCustomTool, createCustomToolkit } from '@composio/core';
const myTool = createCustomTool('fetch_data', {
name: 'Fetch Data',
description: 'Retrieves data from the specified endpoint',
inputParams: [
{
name: 'url',
type: 'string',
description: 'The URL to fetch data from',
required: true,
},
],
execute: async (input) => {
const response = await fetch(input.url);
return await response.json();
},
});
const myToolkit = createCustomToolkit('data_fetchers', {
name: 'Data Fetchers',
description: 'Tools for fetching various data sources',
tools: [myTool],
});
Python
from composio.core.models.custom_tool import CustomTool
from composio.core.models.custom_tool_types import Parameter
my_tool = CustomTool(
name="fetch_data",
description="Retrieves data from the specified endpoint",
input_params=[
Parameter(
name="url",
type="string",
description="The URL to fetch data from",
required=True
)
]
)
Summary
Custom Tools and Toolkits in Composio provide a flexible, extensible system for defining and managing agent capabilities:
- Custom Tools are atomic units of work with defined inputs, outputs, and execution logic
- Custom Toolkits organize related tools under common namespaces and platform contexts
- Version Management enables pinning toolkits to specific versions
- Permission System controls tool execution with browser-based approval flows
- CLI Integration provides comprehensive commands for toolkit discovery and management
- Provider Integration supports schema modification and transformation through modifier functions
This architecture allows developers to extend Composio's functionality while maintaining consistency with the framework's patterns for tool definition, execution, and monitoring.
Sources: ts/packages/providers/README.md
Connected Accounts
Related topics: Core Concepts
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Continue reading this section for the full explanation and source context.
Related Pages
Related topics: Core Concepts
Connected Accounts
Overview
Connected Accounts in Composio represent the integration layer between external third-party services (such as Gmail, Slack, GitHub) and the Composio platform. They manage authentication credentials, authorization scopes, and access control for tools that require external service authentication.
A Connected Account is essentially a stored authentication configuration that links a user's external service account to Composio's tool ecosystem. This abstraction allows Composio to handle OAuth flows, token refresh, and permission management across multiple integrations while providing a unified interface for tool execution.
The Connected Accounts system serves as the foundation for:
- OAuth-based authentication with external services
- Access control and permission management at the account level
- Caching and optimization of authentication data
- Cross-toolkit credential sharing
- Consumer-level account routing
Architecture
Core Components
graph TD
subgraph "CLI Layer"
CMD[connected-accounts.cmd.ts<br>CLI Commands]
HINTS[command-hints.ts<br>Command Hints]
end
subgraph "Effects Layer"
CTRS[create-tool-router-session.ts<br>Tool Router Session]
PERMS[tool-permissions.ts<br>Permission Handler]
end
subgraph "Core Models"
CA[ConnectedAccounts.ts<br>Python Model]
CAC[connectedAccounts.types.ts<br>Type Definitions]
end
subgraph "Services"
CACHE[consumer-short-term-cache.ts<br>Cache Service]
LINK[Link Command<br>OAuth Flow]
end
CMD --> CTRS
CTRS --> CACHE
CTRS --> CAC
PERMS --> CAC
LINK --> CA
CA --> CACData Flow
sequenceDiagram
participant User
participant CLI
participant Cache as Cache Service
participant API as Composio API
participant External as External Service
User->>CLI: composio connected-accounts link gmail
CLI->>API: Initiate OAuth Flow
API->>External: Redirect to OAuth Provider
External-->>API: OAuth Callback + Auth Code
API->>External: Exchange Code for Tokens
External-->>API: Access Token + Refresh Token
API->>API: Store Connected Account
API-->>CLI: Connected Account Created
Note over CLI,Cache: Subsequent Requests
CLI->>Cache: Check Cache
alt Cache Hit
Cache-->>CLI: Return Cached Accounts
else Cache Miss
Cache->>API: Fetch Fresh Data
API-->>Cache: Connected Account Data
Cache-->>CLI: Return Data
end
CLI->>API: Execute Tool with Account
API->>External: Use Account Credentials
External-->>API: Service Response
API-->>CLI: Tool ResultCLI Commands
The Composio CLI provides a dedicated command group for managing connected accounts:
Command Structure
| Command | Description | Entry Point |
|---|---|---|
link | Connect a new external account | connected-accounts.link.cmd.ts |
list | List all connected accounts | connected-accounts.list.cmd.ts |
info | Get details of a specific account | connected-accounts.info.cmd.ts |
whoami | Show currently authenticated identity | connected-accounts.whoami.cmd.ts |
Sources: ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts:14-18
Link Command
The link command initiates the OAuth flow to connect an external service:
composio link <toolkit>
This command:
- Retrieves the OAuth configuration for the specified toolkit
- Opens a browser window for user authentication
- Handles the OAuth callback
- Stores the resulting connected account
List Command
Display all connected accounts with their status:
composio connected-accounts list
The output includes:
- Account ID
- Associated toolkit
- Authentication status
- Last used timestamp
Access Control (ACL)
Connected Accounts support fine-grained access control through ACL (Access Control List) configurations.
ACL Parameters
export const UpdateConnectedAccountAclParamsSchema = ConnectedAccountAclConfigSchema.refine(
acl =>
acl.allowAllUsers !== undefined ||
acl.allowedUserIds !== undefined ||
acl.notAllowedUserIds !== undefined,
{
message: 'At least one of allowAllUsers, allowedUserIds, or notAllowedUserIds must be provided',
}
);
Sources: ts/packages/core/src/types/connectedAccounts.types.ts:1-10
ACL Configuration Fields
| Field | Type | Description |
|---|---|---|
allowAllUsers | boolean | Grant access to all users in the organization |
allowedUserIds | string[] | Explicit list of user IDs granted access |
notAllowedUserIds | string[] | Explicit list of user IDs denied access |
Validation Rule: At least one of these fields must be provided when updating ACL.
Tool Router Integration
Connected Accounts are integrated into the Tool Router system, which manages tool execution and authentication routing.
Session Creation Flow
graph TD
Start([Create Tool Router Session]) --> CheckCache{Cache Scope<br>Provided?}
CheckCache -->|Yes| FetchAuth[Fetch Auth Configs<br>from Cache]
CheckCache -->|No| SkipCache[Skip Cache]
FetchAuth --> CacheExists{Cached Data<br>Available?}
CacheExists -->|Yes| UseCache[Use Cached Auth Configs]
CacheExists -->|No| FetchLive[Fetch Live from API]
SkipCache --> BuildContext[Build Connection Context]
UseCache --> BuildContext
FetchLive --> BuildContext
BuildContext --> MergeAccounts[Merge Connected Accounts]
MergeAccounts --> FilterAccounts[Filter Available Accounts]
FilterAccounts --> ReturnContext[Return Connection Context]
ReturnContext --> End([Session Ready])Connection Context Structure
The connection context aggregates authentication data for tool execution:
interface ConnectionContext {
connectedToolkits: string[];
authConfigs: Record<string, AuthConfig>;
connectedAccounts: ConnectedAccount[];
availableConnectedAccounts: AvailableConnectedAccount[];
}
Sources: ts/packages/cli/src/effects/create-tool-router-session.ts:1-30
Connected Account Mapping
Connected accounts are mapped to word IDs for efficient lookup:
const wordIds = Object.fromEntries(
Object.entries(selected).flatMap(([toolkit, connectedAccountId]) => {
const account = available[toolkit.toLowerCase()]?.find(
item => item.id === connectedAccountId
);
return account?.wordId ? [[toolkit, account.wordId]] : [];
})
);
Sources: ts/packages/cli/src/effects/create-tool-router-session.ts:8-15
Caching System
The Connected Accounts system includes a sophisticated caching layer to optimize API calls and improve performance.
Cache Key Normalization
| Normalization | Description |
|---|---|
| Toolkit slugs | Converted to lowercase |
| Auth config IDs | Validated as non-empty strings |
| Connected account IDs | Validated as non-empty strings |
Sources: ts/packages/cli/src/services/consumer-short-term-cache.ts:1-30
Cache Merge Strategy
When multiple sources provide connected account mappings, they are merged with the following precedence:
- Later declarations override earlier ones
- Auth configs are merged object-wise
- Empty configurations are filtered out
const mergeAuthConfigMappings = (params) => {
const current = normalizeAuthConfigMappings(params.current);
const next = normalizeAuthConfigMappings(params.next);
if (!current) return next;
if (!next) return current;
return normalizeAuthConfigMappings({
authConfigs: {
...(current.authConfigs ?? {}),
...(next.authConfigs ?? {}),
},
});
};
Sources: ts/packages/cli/src/services/consumer-short-term-cache.ts:50-70
Tool Permission System
When executing tools that require connected account authentication, Composio provides a permission confirmation flow.
Permission Flow
sequenceDiagram
participant Agent
participant CLI
participant Browser
participant Server
Agent->>CLI: Execute Tool with Account
CLI->>Server: Start Permission Server
CLI->>Browser: Open Permission Dialog
Note over Browser: "Allow gmail?"
Browser->>Server: User Decision
alt Allow for Session
Server-->>CLI: Allow with Token
CLI->>Agent: Execute Tool
else Allow Once
Server-->>CLI: Allow Once Token
CLI->>Agent: Execute Tool
else Deny
Server-->>CLI: Deny
CLI-->>Agent: Permission Denied
endPermission Dialog
The permission dialog is rendered as an HTML page served on localhost:
<h1>Allow ${toolSlug}?</h1>
<p>Composio CLI is requesting permission to execute this tool${accountLabel ? ` for ${accountLabel}` : ''}.</p>
提供三个选项:
- Allow for this session - 持续授权直到会话结束
- Allow once - 仅本次执行授权
- Deny - 拒绝执行
Sources: ts/packages/cli/src/services/tool-permissions.ts:1-50
Python SDK Integration
Model Definition
class ConnectedAccount(BaseModel):
id: str
name: str
integration_id: str
connected_account_type: str
connection_metadata: dict
enabled: bool
active: bool
auth_scheme: str
auth_expiry: Optional[datetime] = None
redirect_uri: Optional[str] = None
entity_id: Optional[str] = None
user_id: Optional[str] = None
scopes: list[str] = []
account_id: Optional[str] = None
Sources: python/composio/core/models/connected_accounts.py:1-20
Usage Example
from composio import Composio
from composio.client.components import ConnectedAcocunts
composio_client = Composio()
# List all connected accounts
accounts = composio_client.connected_accounts.list()
# Get info for a specific account
account = composio_client.connected_accounts.get(account_id="acc_xxx")
# Link a new account
new_account = composio_client.connected_accounts.link(
integration_id="int_xxx",
entity_id="entity_xxx"
)
Common Use Cases
1. Multi-Account Management
Users can connect multiple accounts from the same service provider:
# Connect personal Gmail
composio link gmail --account personal
# Connect work Gmail
composio link gmail --account work
2. Cross-Toolkit Sharing
One connected account can provide authentication for multiple toolkits if they share the same OAuth provider.
3. Organization-Level Accounts
Enterprise users can share connected accounts across team members using ACL configurations:
# Share account with entire organization
composio_client.connected_accounts.update_acl(
account_id="acc_xxx",
allow_all_users=True
)
# Share with specific users only
composio_client.connected_accounts.update_acl(
account_id="acc_xxx",
allowed_user_ids=["user_1", "user_2"]
)
Related Commands Reference
| Command | Description |
|---|---|
composio connected-accounts link <toolkit> | Connect a new account |
composio connected-accounts list | List all connected accounts |
composio connected-accounts info <account-id> | Show account details |
composio connected-accounts whoami | Show current identity |
composio dev playground-execute <tool> | Test tool with connected account |
composio link <toolkit> | Quick link command (alias) |
Sources: ts/packages/cli/src/services/command-hints.ts:1-50
Troubleshooting
Common Issues
| Issue | Cause | Solution |
|---|---|---|
| Account not found | Toolkit not connected | Run composio link <toolkit> |
| Permission denied | ACL restricts access | Check with account owner to update ACL |
| Token expired | OAuth token needs refresh | Re-link the account |
| Cache stale | Old cached data | Use --no-cache flag or update cache settings |
Debug Mode
Enable verbose logging to debug connected account issues:
COMPOSIO_LOG_LEVEL=debug composio connected-accounts listSources: ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts:14-18
Doramagic Pitfall Log
Source-linked risks stay visible on the manual page so the preview does not read like a recommendation.
First-time setup may fail or require extra isolation and rollback planning.
The project may affect permissions, credentials, data exposure, or host boundaries.
The project may affect permissions, credentials, data exposure, or host boundaries.
The project should not be treated as fully validated until this signal is reviewed.
Doramagic Pitfall Log
Doramagic extracted 12 source-linked risk signals. Review them before installing or handing real data to the project.
1. Installation risk: [Bug]: CLI - v0.2.25 release missing binary assets — upgrade command silently no-ops
- Severity: high
- Finding: Installation risk is backed by a source signal: [Bug]: CLI - v0.2.25 release missing binary assets — upgrade command silently no-ops. Treat it as a review item until the current version is checked.
- User impact: First-time setup may fail or require extra isolation and rollback planning.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/ComposioHQ/composio/issues/3269
2. Security or permission risk: [Bug]: SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK returns successful but file is never shared to channel (channels:[], shar…
- Severity: high
- Finding: Security or permission risk is backed by a source signal: [Bug]: SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK returns successful but file is never shared to channel (channels:[], shar…. Treat it as a review item until the current version is checked.
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/ComposioHQ/composio/issues/3422
3. Security or permission risk: [Feature] Custom auth configs shouldn't require a dev project to use
- Severity: high
- Finding: Security or permission risk is backed by a source signal: [Feature] Custom auth configs shouldn't require a dev project to use. Treat it as a review item until the current version is checked.
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/ComposioHQ/composio/issues/3271
4. Project risk: Project risk needs validation
- Severity: medium
- Finding: Project risk is backed by a source signal: Project risk needs validation. Treat it as a review item until the current version is checked.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: identity.distribution | github_repo:762304524 | https://github.com/ComposioHQ/composio | repo=composio; install=@composio/core
5. Capability assumption: README/documentation is current enough for a first validation pass.
- Severity: medium
- Finding: README/documentation is current enough for a first validation pass.
- User impact: The project should not be treated as fully validated until this signal is reviewed.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: capability.assumptions | github_repo:762304524 | https://github.com/ComposioHQ/composio | README/documentation is current enough for a first validation pass.
6. Maintenance risk: Maintainer activity is unknown
- Severity: medium
- Finding: Maintenance risk is backed by a source signal: Maintainer activity is unknown. Treat it as a review item until the current version is checked.
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:762304524 | https://github.com/ComposioHQ/composio | last_activity_observed missing
7. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: downstream_validation.risk_items | github_repo:762304524 | https://github.com/ComposioHQ/composio | no_demo; severity=medium
8. Security or permission risk: No sandbox install has been executed yet; downstream must verify before user use.
- Severity: medium
- Finding: No sandbox install has been executed yet; downstream must verify before user use.
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: risks.safety_notes | github_repo:762304524 | https://github.com/ComposioHQ/composio | No sandbox install has been executed yet; downstream must verify before user use.
9. Security or permission risk: no_demo
- Severity: medium
- Finding: no_demo
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: risks.scoring_risks | github_repo:762304524 | https://github.com/ComposioHQ/composio | no_demo; severity=medium
10. Security or permission risk: @composio/[email protected]
- Severity: medium
- Finding: Security or permission risk is backed by a source signal: @composio/[email protected]. Treat it as a review item until the current version is checked.
- User impact: The project may affect permissions, credentials, data exposure, or host boundaries.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: Source-linked evidence: https://github.com/ComposioHQ/composio/releases/tag/%40composio/core%400.10.0
11. Maintenance risk: issue_or_pr_quality=unknown
- Severity: low
- Finding: issue_or_pr_quality=unknown。
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:762304524 | https://github.com/ComposioHQ/composio | issue_or_pr_quality=unknown
12. Maintenance risk: release_recency=unknown
- Severity: low
- Finding: release_recency=unknown。
- User impact: Users cannot judge support quality until recent activity, releases, and issue response are checked.
- Recommended check: Open the linked source, confirm whether it still applies to the current version, and keep the first run isolated.
- Evidence: evidence.maintainer_signals | github_repo:762304524 | https://github.com/ComposioHQ/composio | release_recency=unknown
Source: Doramagic discovery, validation, and Project Pack records
Community Discussion Evidence
These external discussion links are review inputs, not standalone proof that the project is production-ready.
Count of project-level external discussion links exposed on this manual page.
Open the linked issues or discussions before treating the pack as ready for your environment.
Community Discussion Evidence
Doramagic exposes project-level community discussion separately from official documentation. Review these links before using composio with real data or production workflows.
- [[Bug]: SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK returns successful but fil](https://github.com/ComposioHQ/composio/issues/3422) - github / github_issue
- [[Feature] Custom auth configs shouldn't require a dev project to use](https://github.com/ComposioHQ/composio/issues/3271) - github / github_issue
- [[Bug]: CLI - v0.2.25 release missing binary assets — upgrade command sil](https://github.com/ComposioHQ/composio/issues/3269) - github / github_issue
- @composio/[email protected] - github / github_release
- Open Claude Cowork: AI Agent Automation Across Desktop & Apps ... - x / searxng_indexed
- Project risk needs validation - GitHub / issue
Source: Project Pack community evidence and pitfall evidence