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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section SDK Components

Continue reading this section for the full explanation and source context.

Section Primary Commands

Continue reading this section for the full explanation and source context.

Section Development Commands

Continue reading this section for the full explanation and source context.

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] --> C

SDK Components

ComponentLanguagePurpose
Core SDKTypeScriptCentral tool management and execution
Python SDKPythonPython-native integration
CLITypeScriptCommand-line interface for tool management
ProvidersTypeScript/PythonFramework-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

CommandDescription
composio executeExecute a tool with specified parameters
composio linkLink a toolkit to the current project
composio tools listList available tools from a toolkit
composio tools infoGet detailed information about a specific tool
composio triggers listList available triggers
composio triggers infoGet detailed information about a trigger
composio orgs switchSwitch between organizations

**Sources: ts/packages/cli/src/services/command-hints.ts

Development Commands

The CLI includes a dedicated dev namespace for development workflows:

CommandDescription
composio dev initInitialize a new Composio project
composio dev playground-executeExecute tools in playground mode
composio dev logs toolsView tool execution logs
composio dev logs triggersView trigger execution logs
composio dev toolkits listList available toolkits
composio dev toolkits infoGet toolkit information
composio dev toolkits searchSearch for toolkits
composio dev toolkits versionManage 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 run and execute commands
  • 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:

VariableDescription
COMPOSIO_API_KEYYour Composio API key
COMPOSIO_BASE_URLCustom API base URL (optional)
COMPOSIO_LOG_LEVELLogging level: silent, error, warn, info, debug
COMPOSIO_DISABLE_TELEMETRYDisable telemetry when set to "true"
COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>Specific version for a toolkit
DEVELOPMENTDevelopment mode flag
CICI environment flag

**Sources: ts/README.md

Project Initialization

To initialize a new Composio project:

cd <project-directory>
composio dev init

The initialization process:

  1. Creates a .env.local file in the project directory
  2. Sets up the project API key by fetching session information
  3. 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:

  1. Extracts docstrings from composio/**/*.py → structured data
  2. Transforms data → MDX files
  3. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section TypeScript/JavaScript SDK

Continue reading this section for the full explanation and source context.

Section Python SDK

Continue reading this section for the full explanation and source context.

Section CLI Installation

Continue reading this section for the full explanation and source context.

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:

  1. Creates a .composio directory in your project
  2. Generates a .env.local file with your project API key
  3. Sets up local tool configurations
  4. 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

ParameterTypeDescriptionRequired
toolSlugstringUnique identifier for the toolYes
paramsobjectTool-specific input parametersYes
accountIdstringConnected account identifierNo
sessionIdstringExecution session identifierNo

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

CommandDescription
composio dev initInitialize a new Composio project
composio dev playground-executeTest tool execution in playground mode
composio dev logs toolsView tool execution logs
composio dev logs triggersView trigger execution logs

Tool Commands

CommandDescription
composio tools listList available tools
composio tools infoGet detailed tool information
composio executeExecute a specific tool

Toolkit Commands

CommandDescription
composio toolkits listList available toolkits
composio toolkits infoGet toolkit details
composio toolkits searchSearch toolkits
composio toolkits versionManage 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

Troubleshooting

Common Issues

IssueSolution
API key not foundSet COMPOSIO_API_KEY environment variable
Tool not foundVerify the toolkit is installed: composio toolkits list
Permission deniedRun composio link <toolkit> to connect your account
Timeout errorIncrease 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

Sources: ts/packages/core/src/composio.ts:1-50

System Architecture

Related topics: Introduction to Composio, Core Concepts, TypeScript SDK, Python SDK

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Platform Detection

Continue reading this section for the full explanation and source context.

Section Supported Platforms

Continue reading this section for the full explanation and source context.

Section Platform Interface Contract

Continue reading this section for the full explanation and source context.

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

The system consists of three primary layers:

LayerPurposeKey Files
Core SDKPlatform initialization, API client managementts/packages/core/src/index.ts
Tool LayerTool registration, toolkit managementpython/composio/core/models/toolkits.py
Provider LayerExternal 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

PlatformModuleUse Case
Node.jsplatform/node.tsServer-side applications, CLI tools
workerdplatform/workerd.tsCloudflare Workers, edge computing
BunBundled with coreHigh-performance runtime
DenoNative fetch/httpDeno Deploy, standalone execution

Platform Interface Contract

All platform implementations must provide:

  1. HTTP Client - Request/response handling
  2. File System Access - Local artifact storage
  3. Environment Variables - Configuration management
  4. 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:

TypeExecution LocationRegistry
Remote ToolsComposio Cloud APIcomposio-tools
Local ToolsClient-side executioncli-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 ready

TypeScript 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

CommandPurpose
composio executeExecute a tool directly
composio tools listList available tools
composio tools infoGet tool details
composio generate tsGenerate TypeScript types
composio dev initInitialize development environment
composio dev playground-executeTest 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

VariablePurposeDefault
COMPOSIO_API_KEYAuthentication keyRequired
COMPOSIO_BASE_URLAPI endpointapi.composio.dev
COMPOSIO_LOG_LEVELLogging verbosityinfo
COMPOSIO_DISABLE_TELEMETRYOpt-out of telemetryfalse
COMPOSIO_TOOLKIT_VERSION_<NAME>Toolkit version overridelatest

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

Extension 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:

  1. Tool execution request triggers permission check
  2. Browser UI presents allow/deny options
  3. Decision is cached for session or one-time use
  4. 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.local for development

Summary

Composio's architecture provides:

  1. Cross-platform support through runtime detection and abstraction
  2. Type-safe tool access via generated TypeScript indices
  3. Provider flexibility with extensible provider interfaces
  4. Local execution for tools that don't require cloud API calls
  5. Permission management with session-scoped authorization
  6. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Toolkit Structure

Continue reading this section for the full explanation and source context.

Section Toolkit Version Management

Continue reading this section for the full explanation and source context.

Section Toolkit Discovery Commands

Continue reading this section for the full explanation and source context.

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:

PropertyTypeDescription
slugstringUnique identifier for the toolkit
namestringHuman-readable name
descriptionstringDescription of the toolkit's functionality
toolsTool[]Array of tools included in the toolkit
platformsLocalCliPlatform[]Supported platforms (e.g., linux, darwin, windows)
sourcestringSource of the toolkit
setupSetupConfigConfiguration 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:

CommandDescription
composio toolkits listList all available toolkits
composio toolkits infoGet detailed information about a specific toolkit
composio toolkits searchSearch toolkits by keyword
composio toolkits versionView 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

PropertyTypeDescription
slugstringUnique identifier for the tool
namestringHuman-readable name
descriptionstringDescription of what the tool does
inputParamsParameter[]Required and optional input parameters
outputParamsParameter[]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 result

Toolkits 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

PropertyTypeDescription
idstringUnique identifier for the connection
toolkitstringThe toolkit this account belongs to
accountIdstringUser account ID on the external service
accountNamestringDisplay name for the account
authConfigAuthConfigAuthentication configuration
statusConnectionStatusActive, 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| E

Permission Options

OptionDescription
Allow for this sessionGrants permission for the current session
Allow onceGrants permission for a single execution
DenyDenies 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:

ConceptRole
ToolkitsOrganize related tools by domain
ToolsIndividual executable units with defined inputs/outputs
Connected AccountsAuthenticated access to external services
Local CLI ToolsLocally executed tools that extend cloud capabilities
ProvidersWrap and enhance tools with additional functionality
Schema ModifiersTransform tool schemas and execution contexts
PermissionsControl 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Composio Client

Continue reading this section for the full explanation and source context.

Section Tool Management

Continue reading this section for the full explanation and source context.

Section Provider System

Continue reading this section for the full explanation and source context.

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:

PackagePurpose
@composio/coreCore SDK functionality, API clients, and tool management
@composio/cliCommand-line interface for project management and generation
@composio/cli-local-toolsLocal tool execution and toolkit registry
@composio/ts-buildersTypeScript AST generation utilities
@composio/providersBase 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 retrieval
  • toolkits - Toolkit management
  • execute - Direct tool execution
  • files - 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

OptionDescriptionDefault
--compactEmit a single module filefalse
--transpiledAlso emit ESM JavaScript filestrue (if no --output-dir)
--output-dirOutput directory pathnode_modules/@composio/core
--toolkitsFilter to specific toolkitsAll toolkits

Invariants:

  • --output-dir cannot refer to a path inside node_modules
  • Without --output-dir, files are written to @composio/core in node_modules
  • If --transpiled is true, 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 supported
  • disabled - Disabled via ~/composio/local_tools.json
  • unsupported - 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

VariableDescription
COMPOSIO_API_KEYAPI key for Composio services
COMPOSIO_BASE_URLCustom API base URL (optional)
COMPOSIO_LOG_LEVELLogging level: silent, error, warn, info, debug
COMPOSIO_DISABLE_TELEMETRYSet to "true" to disable telemetry
COMPOSIO_TOOLKIT_VERSION_<TOOLKIT_NAME>Specific version for a toolkit (e.g., COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00)
DEVELOPMENTDevelopment mode flag
CICI 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:

  1. TypeDoc extracts JSDoc from src/models/*.ts → JSON AST
  2. generate-docs.ts transforms AST → MDX files
  3. Output written to docs/content/reference/sdk-reference/typescript/

Configuration:

  • Entry points: Auto-discovered from src/models/*.ts
  • Excluded classes: INTERNAL_CLASSES set 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:

ProviderPackageDescription
LangChain@composio/langchainIntegration with LangChain agents
Vercel AI@composio/vercelIntegration 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Composio Main Class

Continue reading this section for the full explanation and source context.

Section Tool Client

Continue reading this section for the full explanation and source context.

Section Type System

Continue reading this section for the full explanation and source context.

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] --> B

The 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

ParameterTypeDefaultDescription
api_keystrEnvironment COMPOSIO_API_KEYYour Composio API key
base_urlstr"https://api.composio.dev"Custom API base URL
timeoutint60Request timeout in seconds
max_retriesint3Maximum retry attempts
allow_trackingboolTrueEnable/disable telemetry
file_download_dirstr"./downloads"Directory for file downloads
providerProviderOpenAIProvider()Custom provider instance
toolkit_versionsdict{}Specific toolkit versions

Sources: python/composio/sdk.py:50-100

Environment Variables

The SDK automatically reads several environment variables for configuration:

VariableDescription
COMPOSIO_API_KEYPrimary API authentication key
COMPOSIO_BASE_URLOverride default API endpoint
COMPOSIO_WORKING_DIRSession working directory
COMPOSIO_LOG_LEVELLogging level (silent, error, warn, info, debug)
COMPOSIO_TOOLKIT_VERSION_<TOOLKITNAME>Version for specific toolkit
DEVELOPMENTDevelopment mode flag
CICI 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

ParameterTypeDescription
base_urlstrComposio API base URL
api_keystrAPI authentication key
tool_calls_max_concurrencyintMaximum concurrent tool calls
default_languagestrDefault 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

ExceptionBase ClassDescription
ComposioErrorExceptionBase exception for all SDK errors
ApiKeyNotProvidedErrorComposioErrorAPI key missing or invalid
ToolNotFoundErrorComposioErrorRequested tool does not exist
ToolkitNotFoundErrorComposioErrorRequested toolkit not available
ConnectionErrorComposioErrorNetwork connectivity issues
TimeoutErrorComposioErrorRequest exceeded timeout

Sources: python/composio/exceptions.py:1-50

Supported AI Frameworks

The SDK provides dedicated integrations for popular AI frameworks:

FrameworkDescriptionProvider Class
OpenAIDirect integration with OpenAI's APIOpenAIProvider()
LangChainTools and agents for LangChain workflowsLangChainProvider()
LangGraphState machine workflowsLangGraphProvider()
CrewAIMulti-agent systemsCrewAIProvider()
AutoGenMicrosoft's AutoGen frameworkAutoGenProvider()
AnthropicClaude integrationAnthropicProvider()
Google AIGemini and Google AI servicesGoogleAIProvider()
LlamaIndexRAG and data frameworkLlamaIndexProvider()
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 FileCoverage
test_mcp.pyMCP functionality and server creation
test_tool_router.pyTool 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

  1. API Key Management: Store your API key in environment variables rather than hardcoding
  2. Timeout Configuration: Adjust timeout based on expected tool execution times
  3. Error Handling: Always wrap SDK calls in try-except blocks for graceful degradation
  4. Modifier Usage: Apply schema and execution modifiers at initialization for consistent behavior
  5. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Provider Hierarchy

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section Non-Agentic Providers

Continue reading this section for the full explanation and source context.

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

Provider 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:

ProviderPackageFramework
OpenAIProvider@composio/openaiOpenAI SDK
AnthropicProvider@composio/anthropicAnthropic SDK
LangChainProvider@composio/langchainLangChain
LlamaIndexProvider@composio/llamaindexLlamaIndex

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:

ProviderPackageFramework
ClaudeAgentSDKProvider@composio/claude-agent-sdkClaude Code Agents SDK
VercelProvider@composio/vercelVercel 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:

ParameterTypeDescription
toolSlugstringUnique identifier for the tool
toolToolThe tool definition to wrap
modifiersSchemaModifiersParamsOptional 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 TypeUse Case
ToolOptionsNon-agentic providers
AgenticToolOptionsAgentic 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Available Commands

Continue reading this section for the full explanation and source context.

Section Command Examples

Continue reading this section for the full explanation and source context.

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

ComponentPurposeLocation
Toolkit IndexGroups tools/triggers by toolkit namets/packages/cli/src/generation/create-toolkit-index.ts
Version OverridesManages toolkit version specificationsts/packages/cli/src/effects/toolkit-version-overrides.ts
Version ValidationValidates toolkit versions against APIts/packages/cli/src/effects/validate-toolkit-versions.ts
Local RegistryManages local toolkit declarationsts/packages/cli-local-tools/src/registry.ts
Readiness CheckDetermines toolkit availability statusts/packages/cli-local-tools/src/readiness.ts
ConfigurationHandles toolkit/tool configurationts/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>
CommandDescription
listList available toolkits
infoDisplay detailed information about a specific toolkit
searchSearch for toolkits by name or keywords
versionManage 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:

  1. Groups tools and trigger types by their toolkit prefix
  2. Converts the grouped data to a Record
  3. Strips the toolkit prefix from individual tool/trigger identifiers
  4. 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

FunctionPurpose
getAllLocalToolkitSlugsReturns all registered local toolkit slugs
isLocalToolkitSlugChecks if a slug corresponds to a local toolkit
isLocalToolSlugChecks if a tool slug is a local tool
getLocalToolkitDeclarationsGets declarations filtered by platform/toolkits
getLocalCustomToolkitsReturns 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

StatusDescription
readyToolkit and all tools are available
disabledToolkit is disabled via local_tools.json metadata
unsupportedToolkit 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| G

Error Handling

Error TypeCauseUser Message
InvalidToolkitsErrorToolkit slug doesn't existInvalid toolkit(s) specified
InvalidToolkitVersionsErrorVersion doesn't exist for toolkitInvalid version for specific toolkit
HttpServerErrorAPI communication failureNetwork 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]
OptionDescription
--commandOverride installation command
--disableDisable the toolkit or tool
--enableEnable the toolkit or tool
--authenticatedMark as authenticated
--unauthenticatedMark 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 --> D

Permission Decision Types

DecisionScopePersistence
ALLOW_SESSIONAll executions in current sessionSession-scoped
ALLOW_ONCESingle executionSingle use
DENYBlock executionSingle 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]
OptionDescriptionDefault
--compactEmit single module filefalse
--transpiledInclude transpiled JStrue (if no --output-dir)
--output-dirOutput directorynode_modules/@composio/core
--toolkitsFilter by toolkit(s)All toolkits

Invariants

  • --output-dir cannot refer to a path inside node_modules
  • If --output-dir is not specified, --transpiled defaults to true
  • If --output-dir is specified, --transpiled defaults to false

Summary

Toolkits Management in Composio provides a comprehensive system for organizing and managing tools with the following key capabilities:

  1. Discovery: CLI commands for listing, searching, and inspecting available toolkits
  2. Indexing: Automatic organization of tools and triggers by toolkit prefix
  3. Local Support: Registry and execution system for locally-defined toolkits
  4. Version Control: Version pinning with validation against the Composio API
  5. Configuration: Flexible configuration of toolkit behavior including installation commands and enable/disable states
  6. Permissions: Security layer for tool execution with session and one-time permission grants
  7. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section High-Level Architecture

Continue reading this section for the full explanation and source context.

Section Component Hierarchy

Continue reading this section for the full explanation and source context.

Section TypeScript Implementation

Continue reading this section for the full explanation and source context.

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

Component 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

PropertyTypeRequiredDescription
slugstringYesUnique identifier for the tool
namestringYesHuman-readable display name
descriptionstringYesDetailed explanation of tool functionality
inputParamsParameter[]NoArray of input parameter definitions
outputParamsParameter[]NoArray of output parameter definitions
executeFunctionYesAsync function that performs the tool action
triggersTrigger[]NoEvent 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

PropertyTypeRequiredDescription
slugstringYesUnique toolkit identifier
namestringYesDisplay name for the toolkit
descriptionstringYesToolkit documentation
toolsCustomTool[]YesCollection of tools in this toolkit
platformsLocalCliPlatform[]YesSupported 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

CommandDescription
composio toolkits listList all available toolkits
composio toolkits info <slug>Display detailed toolkit information
composio toolkits search <query>Search toolkits by name or description
composio toolkits versionManage 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

PropertyTypeDescription
disabledbooleanWhether the tool/kit is disabled
authenticatedbooleanWhether authentication is required
installation.commandstringCustom installation command
metadataPathstringPath 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

StatusDescription
readyTool is fully operational
disabledTool is explicitly disabled in configuration
unsupportedTool not supported on current platform
needs_setupTool 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 reject

Permission Decision Types

DecisionScopePersistence
allow_sessionCurrent sessionTemporary
allow_onceSingle executionSingle use
denyRejectedPermanent 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

FunctionPurpose
modifySchemaTransform input/output schemas
beforeExecutePre-execution hook for parameter manipulation
afterExecutePost-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:

  1. Custom Tools are atomic units of work with defined inputs, outputs, and execution logic
  2. Custom Toolkits organize related tools under common namespaces and platform contexts
  3. Version Management enables pinning toolkits to specific versions
  4. Permission System controls tool execution with browser-based approval flows
  5. CLI Integration provides comprehensive commands for toolkit discovery and management
  6. 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

Section Related Pages

Continue reading this section for the full explanation and source context.

Section Core Components

Continue reading this section for the full explanation and source context.

Section Data Flow

Continue reading this section for the full explanation and source context.

Section Command Structure

Continue reading this section for the full explanation and source context.

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

Data 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 Result

CLI Commands

The Composio CLI provides a dedicated command group for managing connected accounts:

Command Structure

CommandDescriptionEntry Point
linkConnect a new external accountconnected-accounts.link.cmd.ts
listList all connected accountsconnected-accounts.list.cmd.ts
infoGet details of a specific accountconnected-accounts.info.cmd.ts
whoamiShow currently authenticated identityconnected-accounts.whoami.cmd.ts

Sources: ts/packages/cli/src/commands/connected-accounts/connected-accounts.cmd.ts:14-18

The link command initiates the OAuth flow to connect an external service:

composio link <toolkit>

This command:

  1. Retrieves the OAuth configuration for the specified toolkit
  2. Opens a browser window for user authentication
  3. Handles the OAuth callback
  4. 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

FieldTypeDescription
allowAllUsersbooleanGrant access to all users in the organization
allowedUserIdsstring[]Explicit list of user IDs granted access
notAllowedUserIdsstring[]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

NormalizationDescription
Toolkit slugsConverted to lowercase
Auth config IDsValidated as non-empty strings
Connected account IDsValidated 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:

  1. Later declarations override earlier ones
  2. Auth configs are merged object-wise
  3. 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
    end

Permission 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"]
)
CommandDescription
composio connected-accounts link <toolkit>Connect a new account
composio connected-accounts listList all connected accounts
composio connected-accounts info <account-id>Show account details
composio connected-accounts whoamiShow 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

IssueCauseSolution
Account not foundToolkit not connectedRun composio link <toolkit>
Permission deniedACL restricts accessCheck with account owner to update ACL
Token expiredOAuth token needs refreshRe-link the account
Cache staleOld cached dataUse --no-cache flag or update cache settings

Debug Mode

Enable verbose logging to debug connected account issues:

COMPOSIO_LOG_LEVEL=debug composio connected-accounts list

Sources: 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.

high [Bug]: CLI - v0.2.25 release missing binary assets — upgrade command silently no-ops

First-time setup may fail or require extra isolation and rollback planning.

high [Bug]: SLACK_UPLOAD_OR_CREATE_A_FILE_IN_SLACK returns successful but file is never shared to channel (channels:[], shar…

The project may affect permissions, credentials, data exposure, or host boundaries.

high [Feature] Custom auth configs shouldn't require a dev project to use

The project may affect permissions, credentials, data exposure, or host boundaries.

medium Project risk needs validation

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.

Sources 6

Count of project-level external discussion links exposed on this manual page.

Use Review before install

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