### Install Composio CLI and SDKs Source: https://context7.com/composiohq/skills/llms.txt Install the Composio CLI using a curl script and then install the core SDK and provider packages for TypeScript or Python. Ensure you log in and initialize your project to store API keys. ```bash # Install CLI curl -fsSL https://composio.dev/install | bash composio login # OAuth flow composio whoami # verify org_id, project_id # Initialize project (stores API key) composio init # TypeScript SDK pnpm install @composio/core@latest # Provider packages (choose based on AI framework) pnpm install @composio/vercel # Vercel AI SDK pnpm install @composio/openai-agents # OpenAI Agents pnpm install @composio/mastra # Mastra pnpm install @composio/claude-agent-sdk # Claude Agent SDK # Python SDK pip install composio composio-langchain composio-crewai ``` -------------------------------- ### Complete .env File Example Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/setup-api-keys.md An example of a complete .env file including Composio and LLM provider API keys, along with other optional configurations. ```bash # Composio Configuration COMPOSIO_API_KEY=your_composio_api_key_here # LLM Provider (choose one or both based on your needs) OPENAI_API_KEY=your_openai_api_key_here ANTHROPIC_API_KEY=your_anthropic_api_key_here # Optional: Other configurations NODE_ENV=development PORT=3000 ``` -------------------------------- ### Install Composio CLI Source: https://github.com/composiohq/skills/blob/main/skills/composio/SKILL.md Install the Composio CLI by downloading and executing the installation script. Ensure your terminal is restarted or shell configuration is sourced after installation. ```bash curl -fsSL https://composio.dev/install | bash ``` -------------------------------- ### Install and Authenticate Composio CLI Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Install the CLI using curl, verify the version, and authenticate your account via OAuth. Use `upgrade` to resolve potential errors. ```bash # Install curl -fsSL https://composio.dev/install | bash composio --version # verify # Authenticate composio login # OAuth flow; interactive org/project picker after login (use -y to skip) composio whoami # verify org_id, project_id, user_id (API keys are never displayed) # Run upgrade in case you run into errors or starting with a new project composio upgrade ``` -------------------------------- ### Trigger Configuration Examples Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/triggers-create.md Examples demonstrating how to configure triggers for different services like Gmail, GitHub, and Slack. Each example specifies the trigger slug and its corresponding `triggerConfig` parameters. ```typescript // Gmail - New messages in specific label await composio.triggers.create('user_123', 'GMAIL_NEW_GMAIL_MESSAGE', { triggerConfig: { labelIds: 'INBOX', userId: 'me', interval: 60 } }); // GitHub - New commits await composio.triggers.create('user_123', 'GITHUB_COMMIT_EVENT', { triggerConfig: { owner: 'composio', repo: 'sdk', branch: 'main' } }); // Slack - New messages in channel await composio.triggers.create('user_123', 'SLACK_NEW_MESSAGE', { triggerConfig: { channelId: 'C123456', botUserId: 'U123456' } }); ``` -------------------------------- ### Install Composio SDK (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/building-with-composio.md Install the core Composio SDK for Python projects using pip. ```bash pip install composio ``` -------------------------------- ### Install Composio SDK (TypeScript) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/building-with-composio.md Install the core Composio SDK for TypeScript projects using pnpm. ```bash pnpm install @composio/core@latest ``` -------------------------------- ### Example Integration with Composio Link/Authorize Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-auth-popup-ui.md Demonstrates how to initiate a Composio auth link on the backend and then handle the popup flow in the frontend using the `initiateComposioAuthFlow` helper. This example shows how to destructure specific parameters like 'status' and 'connected_account_id' from the returned query parameters. ```typescript // in the backend const connectionRequest = await composio.connectedAccounts.link( userId, authConfigId, { callbackUrl: 'https://your-app.com/auth/composio/callback' } ); // in the frontend const params = await initiateComposioAuthFlow( connectionRequest.redirectUrl, 'status' ); ``` ```typescript const { status, connected_account_id } = await initiateComposioAuthFlow( authLink, 'status' ); ``` -------------------------------- ### Implement Logging and Monitoring Hooks Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-modifiers.md An example of creating reusable `beforeExecute` and `afterExecute` hooks for logging tool execution start and end times, along with parameters and success status. ```typescript const monitor = { beforeExecute: ({ toolSlug, params }) => { console.log(`[START] ${toolSlug}`, params.arguments); return params; }, afterExecute: ({ toolSlug, result }) => { console.log(`[END] ${toolSlug} - Success: ${result.successful}`); return result; }, }; ``` -------------------------------- ### Install Composio and Vercel AI SDK Dependencies Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-framework-ai-sdk.md Install the necessary packages for Composio, Vercel AI SDK, and OpenAI. Include `@ai-sdk/mcp` if you plan to use MCP tools. ```bash npm install @composio/core @composio/vercel ai @ai-sdk/openai # For MCP (optional) npm install @ai-sdk/mcp ``` -------------------------------- ### Verify Composio API Key Setup (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/setup-api-keys.md Test your Composio API key setup by listing available applications using the Composio SDK in Python. ```python from composio import Composio composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"]) # Test the connection apps = composio.apps.list() print("✅ Composio API key is working!") ``` -------------------------------- ### Get help for login command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Provides detailed help and options for the `composio login` command. ```bash composio login --help ``` -------------------------------- ### Get GitHub Tools (Provider-Based) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-fetch-tools.md Use `tools.get()` to fetch tools for provider-based applications. This example retrieves important GitHub tools, automatically applying the 'important' filter. ```typescript const importantGithubTools = await composio.tools.get('default', { toolkits: ['github'] }); ``` -------------------------------- ### Get general help Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Displays general help information for the Composio CLI, listing all top-level commands. ```bash composio --help ``` -------------------------------- ### Install Composio and Mastra Dependencies Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-framework-mastra.md Install the necessary packages for Composio and Mastra integration, including optional packages for MCP support. ```bash npm install @mastra/core@latest @ai-sdk/openai @composio/core@latest @composio/mastra@latest # For MCP (optional) npm install @mastra/mcp@latest ``` -------------------------------- ### Fetch All GitHub Tools (Python) Source: https://context7.com/composiohq/skills/llms.txt Retrieve all available GitHub tools using the Python SDK. This example demonstrates fetching tools and printing their names. ```python # Python all_github_tools = composio.tools.get(user_id="default", toolkits=["github"], limit=100) print("Available tools:", [t.name for t in all_github_tools]) ``` -------------------------------- ### Composio CLI: Discover Tools and Toolkits Source: https://context7.com/composiohq/skills/llms.txt Discover available tools and toolkits using the Composio CLI. You can list all toolkits, get information about a specific toolkit, list tools within a toolkit, or get detailed information about a specific tool. ```bash # Discover tools and toolkits composio manage toolkits list composio manage toolkits info "gmail" composio manage tools list --toolkits "gmail" composio manage tools info "GMAIL_SEND_EMAIL" ``` -------------------------------- ### Correct Python Example Source: https://github.com/composiohq/skills/blob/main/CONTRIBUTING.md Illustrates the correct way to implement a concept, with comments explaining the solution. This is part of the rule template. ```python # Show the right way with explanatory comments good = "example" ``` -------------------------------- ### Correct Python Example Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/_template.md This code demonstrates the correct pattern in Python. Use this to improve code quality. ```python # Explain why this is correct good = "example" ``` -------------------------------- ### Install Composio Agent Skills Source: https://github.com/composiohq/skills/blob/main/README.md Use this command to install the Composio agent skills, granting your AI assistant access to Tool Router best practices, Triggers & Events, and production patterns. ```bash npx skills add composiohq/skills ``` -------------------------------- ### Verify Composio API Key Setup (TypeScript) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/setup-api-keys.md Test your Composio API key setup by listing available applications using the Composio SDK in TypeScript. ```typescript import { Composio } from '@composio/core'; const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY }); // Test the connection const apps = await composio.apps.list(); console.log('✅ Composio API key is working!'); ``` -------------------------------- ### Get help for manage toolkits command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Provides detailed help and options for managing toolkits via the `composio manage toolkits` subcommand. ```bash composio manage toolkits --help ``` -------------------------------- ### Get Tool Help Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Display the input parameters for a specific tool by appending the `--help` flag to the execute command. ```bash composio execute GMAIL_SEND_EMAIL --help ``` -------------------------------- ### Get help for listen command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Provides detailed help and options for the `composio listen` command, likely used for event listening or monitoring. ```bash composio listen --help ``` -------------------------------- ### Get help for execute command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Provides detailed help and options for the `composio execute` command, used for running tools. ```bash composio execute --help ``` -------------------------------- ### Get help for link command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Displays detailed help and options for the `composio link` command, used for connecting accounts. ```bash composio link --help ``` -------------------------------- ### Correct TypeScript Example Source: https://github.com/composiohq/skills/blob/main/CONTRIBUTING.md Illustrates the correct way to implement a concept, with comments explaining the solution. This is part of the rule template. ```typescript // Show the right way with explanatory comments const good = 'example'; ``` -------------------------------- ### Get help for manage tools command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Displays detailed help and options for managing tools via the `composio manage tools` subcommand. ```bash composio manage tools --help ``` -------------------------------- ### Get help for search command Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Displays detailed help and options for the `composio search` command, which is used for finding tools. ```bash composio search --help ``` -------------------------------- ### Development Pattern Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/triggers-subscribe.md This example shows a common pattern for using `subscribe` in a development environment, including handling graceful shutdown by calling `unsubscribe` on SIGINT. ```APIDOC ## Development Pattern ```typescript async function devMode() { console.log('Starting development mode...'); // Subscribe to events const unsubscribe = await composio.triggers.subscribe((event) => { console.log(` [${event.triggerSlug}]`); console.log('User:', event.userId); console.log('Payload:', JSON.stringify(event.payload, null, 2)); }); // Handle shutdown process.on('SIGINT', async () => { console.log('\nShutting down...'); await unsubscribe(); process.exit(0); }); console.log('Listening for events. Press Ctrl+C to stop.'); } devMode(); ``` ``` -------------------------------- ### Create LangChain Agent with MCP Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-framework-integration.md Integrate Composio's MCP with LangChain to create a Gmail assistant. Requires installing `@langchain/mcp-adapters` and `@composio/core`. ```typescript // DO: Use LangChain with MCP import { MultiServerMCPClient } from '@langchain/mcp-adapters'; import { ChatOpenAI } from '@langchain/openai'; import { createAgent } from 'langchain'; import { Composio } from '@composio/core'; const composio = new Composio(); async function createLangChainAgent(userId: string) { // Create session const session = await composio.create(userId, { toolkits: ['gmail'] }); // Create MCP client const client = new MultiServerMCPClient({ composio: { transport: 'http', url: session.mcp.url, headers: session.mcp.headers } }); // Get tools const tools = await client.getTools(); // Create agent const llm = new ChatOpenAI({ model: 'gpt-5.2' }); const agent = createAgent({ name: 'Gmail Assistant', systemPrompt: 'You help users manage their Gmail.', model: llm, tools }); return agent; } const agent = await createLangChainAgent('user_123'); const result = await agent.invoke({ messages: [{ role: 'user', content: 'Fetch my last email' }] }); console.log(result); ``` -------------------------------- ### Initialize Composio SDK Source: https://github.com/composiohq/skills/blob/main/skills/composio/SKILL.md Initialize the Composio SDK within your project directory by running the `composio init` command. This command sets up the necessary API key for your project. ```bash composio init ``` -------------------------------- ### Configure API Keys Securely with dotenv (Python) Source: https://context7.com/composiohq/skills/llms.txt Load API keys from environment variables using dotenv to avoid hardcoding. This example shows how to configure Composio and LangchainProvider. ```python import os from dotenv import load_dotenv from composio import Composio from composio_langchain import LangchainProvider load_dotenv() composio = Composio( api_key=os.environ["COMPOSIO_API_KEY"], provider=LangchainProvider() ) print("✅ Composio API key is working!") ``` -------------------------------- ### Get Important Tools (Standalone) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-fetch-tools.md Use `getRawComposioTools()` to fetch raw tool metadata for standalone applications or UI development. This example retrieves important GitHub tools, auto-applying the 'important' filter. ```typescript // Get important tools (auto-applies important filter) const importantTools = await composio.tools.getRawComposioTools({ toolkits: ['github'] }); ``` -------------------------------- ### Get tool names from a toolkit using jq Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md This example shows how to filter the output of `composio manage tools list` for a specific toolkit and extract the `name` of each tool using `jq`. This is helpful for quickly finding tool names. ```bash composio manage tools list --toolkits "gmail" | jq -r '.[].name' ``` -------------------------------- ### Create a Tool Router Session with Composio Source: https://context7.com/composiohq/skills/llms.txt Creates an isolated, per-user session with scoped tool access and automatic auth management. Sessions should be short-lived and disposable. This example shows API route handler setup for a fresh session per request. ```typescript import { Composio } from '@composio/core'; import { VercelProvider } from '@composio/vercel'; import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY, provider: new VercelProvider() }); // API route handler — creates a fresh session per request export async function POST(req: Request) { const { messages, userId, selectedToolkits } = await req.json(); // Per-user isolated session — never use 'default' in multi-user production apps const session = await composio.create(userId, { toolkits: selectedToolkits, // e.g. ['gmail', 'slack', 'github'] manageConnections: true, // agent prompts for OAuth on-demand tools: { gmail: ['GMAIL_FETCH_EMAILS', 'GMAIL_SEND_EMAIL'], slack: { disable: ['SLACK_DELETE_MESSAGE'] } // prevent destructive ops }, tags: ['readOnlyHint'], // global tag filter (optional) }); console.log('Session ID:', session.sessionId); // use as trace/correlation ID console.log('MCP URL:', session.mcp.url); const tools = await session.tools(); // returns provider-formatted tools const result = await streamText({ model: openai('gpt-4o'), messages, tools, maxSteps: 10 }); return result.toDataStreamResponse(); } ``` -------------------------------- ### Run an Agent with Composio in Python Source: https://context7.com/composiohq/skills/llms.txt Creates a Composio session and runs a personal assistant agent. This example demonstrates setting up an agent with specific instructions and tools, then executing it with user input. ```python from composio import Composio from composio_openai_agents import OpenAIAgentsProvider from agents import Agent, Runner composio = Composio(provider=OpenAIAgentsProvider()) async def run_agent(user_id: str, message: str): session = composio.create( user_id=user_id, toolkits=["gmail", "slack"], manage_connections=True ) tools = session.tools() agent = Agent( name="Personal Assistant", model="gpt-4o", instructions="You are a helpful assistant.", tools=tools ) result = await Runner.run(starting_agent=agent, input=message) print(result.final_output) ``` -------------------------------- ### Express.js Webhook Server with Composio Triggers Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/triggers-webhook.md This example demonstrates a complete Express.js server setup for handling Composio webhook events. It includes automatic verification, event processing logic, idempotency checks, and error handling. Ensure your server is accessible via HTTPS and responds within 30 seconds. ```typescript import express from 'express'; import { Composio } from '@composio/core'; const app = express(); const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY }); await composio.triggers.listenToTriggers(app, async (event) => { try { // Idempotency check if (await isProcessed(event.metadata.webhookId)) { return; } // Process switch (event.triggerSlug) { case 'GMAIL_NEW_GMAIL_MESSAGE': await sendNotification(event.userId, { title: 'New Email', body: event.payload.subject }); break; } // Mark processed await markProcessed(event.metadata.webhookId); } catch (error) { console.error('Error:', error); } }); app.get('/health', (req, res) => res.json({ status: 'ok' })); app.listen(3000, () => { console.log('Webhook server running on port 3000'); }); ``` -------------------------------- ### Examples of Toolkit Querying Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-toolkits.md Demonstrates various ways to query toolkits using different filter combinations, such as filtering by 'composio' management, a specific category, sorting by usage with a limit, and basic pagination. ```typescript // Composio-managed only const composio = await composio.toolkits.get({ managedBy: 'composio' }); // By category const devTools = await composio.toolkits.get({ category: 'developer-tools' }); // Popular toolkits const popular = await composio.toolkits.get({ sortBy: 'usage', limit: 10 }); // Paginated const page1 = await composio.toolkits.get({ limit: 10 }); const page2 = await composio.toolkits.get({ limit: 10, cursor: page1Cursor }); ``` -------------------------------- ### List all toolkits Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Use this command to list all available toolkits. This is useful for discovering the scope of available tools. ```bash composio manage toolkits list ``` -------------------------------- ### Get Toolkit Metadata Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-toolkits.md Retrieve metadata for a specific toolkit by its slug, or fetch all available toolkits. The `get()` method returns an array of toolkit objects. ```APIDOC ## Get Toolkit Metadata ### Description Retrieve metadata for a specific toolkit by its slug, or fetch all available toolkits. The `get()` method returns an array of toolkit objects. ### Method `toolkits.get(slug?: string, options?: object)` ### Parameters #### Path Parameters - **slug** (string) - Optional - The unique identifier for the toolkit. #### Query Parameters - **category** (string) - Optional - Filter by category ID. - **managedBy** (string) - Optional - Filter by management type ('all', 'composio', 'project'). - **sortBy** (string) - Optional - Sort order ('usage', 'alphabetically'). - **limit** (number) - Optional - Maximum number of results per page. - **cursor** (string) - Optional - Pagination cursor for fetching the next page. ### Request Example ```typescript // Get specific toolkit const github = await composio.toolkits.get('github'); console.log(github.name); // GitHub console.log(github.authConfigDetails); // Auth details console.log(github.meta.toolsCount); // Number of tools console.log(github.meta.triggersCount); // Number of triggers // Get all toolkits const all = await composio.toolkits.get(); console.log(all.length); // Number of toolkits // With query parameters const toolkits = await composio.toolkits.get({ category: 'developer-tools', managedBy: 'composio', sortBy: 'usage', limit: 10, cursor: 'next_page_cursor', }); ``` ### Response #### Success Response (200) - **Array of Toolkit Objects**: Each object contains properties like `name`, `slug`, `meta` (with `toolsCount`, `triggersCount`, `createdAt`, `updatedAt`), `authConfigDetails`, `composioManagedAuthSchemes`, `baseUrl`, and `getCurrentUserEndpoint`. #### Response Example ```json [ { "name": "GitHub", "slug": "github", "meta": { "toolsCount": 50, "triggersCount": 10, "createdAt": "2023-01-01T00:00:00Z", "updatedAt": "2023-01-01T00:00:00Z" }, "authConfigDetails": { ... }, "composioManagedAuthSchemes": ["OAUTH2"], "baseUrl": "https://api.github.com", "getCurrentUserEndpoint": "/user" } ] ``` ``` -------------------------------- ### Best Practice: Discover Tool Versions (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-fetch-tools.md Discover available toolkits and their versions first. This helps in understanding available options before selecting and using tools. ```python # DO: Discover available versions and tools first toolkit = composio.toolkits.get("github") print(f"Available versions: {toolkit.versions}") tools = composio.tools.get( user_id="default", toolkits=["github"], limit=100 ) ``` -------------------------------- ### Basic Tool Execution Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-execute-tools.md Demonstrates the fundamental usage of `composio.tools.execute()` to run a specific tool with required arguments and a version. ```APIDOC ## Basic Tool Execution Execute with a specific version (REQUIRED) ```typescript // Execute with a specific version (REQUIRED) const result = await composio.tools.execute('GITHUB_GET_ISSUES', { userId: 'default', arguments: { owner: 'composio', repo: 'sdk' }, version: '12082025_00', // Specific version required }); ``` ``` -------------------------------- ### Correct Version Pinning Procedure Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-tool-versions.md Illustrates the recommended process for version pinning: first list available versions, then choose and test a specific one, and finally pin it in the configuration. ```typescript // 1. List available versions to find valid options const githubToolkit = await composio.toolkits.get('github'); console.log('Available versions:', githubToolkit.versions); // 2. Choose and test a specific version from the list // 3. Pin that tested version in your code or environment variables const composio = new Composio({ toolkitVersions: { github: '12082025_00', // Specific tested version slack: '10082025_01', // Specific tested version } }); ``` -------------------------------- ### Link an account Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Connect a new account using its authentication configuration and user ID. Ensure you have the correct configuration details. ```bash composio manage connected-accounts link --auth-config "ac_..." --user-id "user_123" ``` -------------------------------- ### Get Auth Config Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-auth-configs.md Retrieve details for a specific authentication configuration by its ID. ```APIDOC ## Get Auth Config ### Description Retrieves the details of a specific authentication configuration using its unique identifier. ### Method `composio.authConfigs.get(authConfigId: string)` ### Parameters #### Path Parameters - **authConfigId** (string) - Required - The unique identifier of the authentication configuration. ### Response Example ```json { "id": "auth_config_123", "name": "GitHub Auth Config", "authScheme": "OAUTH2", "toolkit": { "slug": "github" }, "isComposioManaged": true } ``` ``` -------------------------------- ### Get Trigger Details Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/triggers-manage.md Fetch detailed information about a specific trigger using its unique ID. ```APIDOC ## Get Trigger Details ### Description Retrieves comprehensive details for a single trigger identified by its unique ID. ### Method - `getTriggerById(triggerId: string)` ### Parameters - **triggerId** (string) - Required - The unique identifier of the trigger to retrieve. ### Response Example ```json { "triggerId": "trigger_id_123", "status": "enabled", "triggerSlug": "GMAIL_NEW_GMAIL_MESSAGE", "config": { "triggerConfig": { "labelIds": "INBOX", "interval": 60 } }, "userId": "user_123", "connectedAccountId": "conn_abc123", "createdAt": "2023-01-01T10:00:00Z", "updatedAt": "2023-01-01T10:05:00Z" } ``` ``` -------------------------------- ### Complete Tool Discovery Workflow (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-fetch-tools.md Follow these steps to discover available toolkits, list tools within a toolkit, find a specific tool, and execute it with a pinned version for stability. ```python # Step 1: Get toolkit information (to discover available versions) github_toolkit = composio.toolkits.get("github") print(f"Toolkit: {github_toolkit.name}") print(f"Available versions: {github_toolkit.versions}") print(f"Current version: {github_toolkit.version}") print(f"Description: {github_toolkit.description}") # Step 2: Discover all available tools in the toolkit all_github_tools = composio.tools.get( user_id="default", toolkits=["github"], limit=100 # Adjust based on your needs ) print("\nAvailable tools:") for tool in all_github_tools: print(f"- {tool.name}: {tool.description}") # Step 3: Find the tool you need repo_tool = next((t for t in all_github_tools if t.name == "GITHUB_GET_REPO"), None) if not repo_tool: raise Exception("Tool not found") # Step 4: Execute the tool with a pinned version string result = composio.tools.execute( tool="GITHUB_GET_REPO", user_id="user_123", arguments={"owner": "composio", "repo": "sdk"}, version="12082025_00" # ✅ Pinned version string for stability ) ``` -------------------------------- ### Querying and Displaying Toolkit Connection States (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-toolkit-query.md Query connection states using `session.toolkits()` to build a comprehensive connection management UI. This example demonstrates how to fetch and process toolkit connection information, including active status and authentication needs. ```python # DO: Query connection states to build connection UI from composio import Composio composio = Composio() session = composio.create( user_id="user_123", toolkits=["gmail", "slack", "github"], manage_connections=True # Agent handles auth automatically ) # Get connection states for building UI result = session.toolkits() # Build connection management UI connection_ui = [] for toolkit in result.items: connection_ui.append({ "slug": toolkit.slug, "name": toolkit.name, "logo": toolkit.logo, "is_connected": toolkit.connection.is_active if toolkit.connection else False, "status": toolkit.connection.connected_account.status if toolkit.connection.connected_account else None, # Show "Connect" button if not connected "needs_auth": not (toolkit.connection.is_active if toolkit.connection else False) and not toolkit.is_no_auth }) print(f"Connection Status: {connection_ui}") # Use this to render connection cards in your UI ``` -------------------------------- ### Setup User Triggers for Onboarding Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/triggers-create.md Iterates through a user's connected accounts and creates specific triggers for services like Gmail. Requires a connected account to be authenticated first. ```typescript async function setupUserTriggers(userId: string) { // Check connected accounts const accounts = await composio.connectedAccounts.list({ userIds: [userId] }); // Create triggers for each service for (const account of accounts.items) { if (account.toolkit.slug === 'gmail') { await composio.triggers.create(userId, 'GMAIL_NEW_GMAIL_MESSAGE', { connectedAccountId: account.id, triggerConfig: { labelIds: 'INBOX' } }); } } } ``` -------------------------------- ### Get auth config info Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Retrieve details about a specific authentication configuration using its ID. ```bash composio manage auth-configs info ``` -------------------------------- ### Load Environment Variables in Python Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/setup-api-keys.md Install the 'python-dotenv' package and load environment variables in your Python code. ```bash pip install python-dotenv ``` ```python from dotenv import load_dotenv load_dotenv() ``` -------------------------------- ### Composio CLI: Search, Link, and Execute Tools Source: https://context7.com/composiohq/skills/llms.txt Perform direct tool execution using the Composio CLI. The workflow involves searching for a tool, linking an account if necessary (which may open an OAuth flow or provide a redirect URL), and then executing the tool with specified data. Use `--no-wait` for agent/scripted modes. ```bash # Step 1 — Find the right tool (never trim/head this output) composio search "send an email" composio search "create github issue" # Step 2 — Connect an account if not already connected composio link gmail # opens OAuth browser flow composio link github --no-wait # scripted/agent mode: prints redirect_url and exits # Step 3 — Execute the tool composio execute GMAIL_SEND_EMAIL --data \ '{"recipient_email":"you@example.com","subject":"Hello","body":"Test"}' composio execute GITHUB_CREATE_AN_ISSUE --data \ '{"owner":"acme","repo":"my-repo","title":"Bug report"}' # Act as a specific user composio execute GMAIL_SEND_EMAIL --user-id "user_123" \ --data '{"recipient_email":"them@example.com","subject":"Hi"}' ``` -------------------------------- ### Correct TypeScript Example Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/_template.md This code demonstrates the correct pattern in TypeScript. Use this to improve code quality. ```typescript // Explain why this is correct const good = 'example'; ``` -------------------------------- ### Framework Switching with Composio MCP Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-framework-integration.md Demonstrates how to use the same Composio session with different frameworks by switching clients. This highlights the flexibility of the MCP for integrating with Vercel AI SDK, LangChain, and OpenAI Agents. ```typescript const composio = new Composio(); const session = await composio.create('user_123', { toolkits: ['gmail'] }); // Use with Vercel AI SDK const client1 = await createMCPClient({ transport: { type: 'http', url: session.mcp.url, headers: session.mcp.headers } }); // Use with LangChain const client2 = new MultiServerMCPClient({ composio: { transport: 'http', url: session.mcp.url, headers: session.mcp.headers } }); // Use with OpenAI Agents const client3 = hostedMcpTool({ serverUrl: session.mcp.url, headers: session.mcp.headers }); ``` -------------------------------- ### Load Environment Variables in Node.js/TypeScript Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/setup-api-keys.md Install the 'dotenv' package and load environment variables at the top of your entry file. ```bash npm install dotenv ``` ```typescript import 'dotenv/config'; // Or require('dotenv').config(); ``` -------------------------------- ### Incorrect Python Example Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/_template.md This code demonstrates an incorrect pattern in Python. Use the correct pattern to avoid issues. ```python # Explain why this is wrong bad = "example" ``` -------------------------------- ### Search for Tools Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Find available tools by searching for keywords related to the desired action. The output indicates connection status to the required app. ```bash composio search "send an email" composio search "create github issue" composio search "post slack message" ``` -------------------------------- ### Incorrect TypeScript Example Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/_template.md This code demonstrates an incorrect pattern in TypeScript. Use the correct pattern to avoid issues. ```typescript // Explain why this is wrong const bad = 'example'; ``` -------------------------------- ### Incorrect Python Example Source: https://github.com/composiohq/skills/blob/main/CONTRIBUTING.md Illustrates the incorrect way to implement a concept, with comments explaining the issue. This is part of the rule template. ```python # Show the wrong way with explanatory comments bad = "example" ``` -------------------------------- ### Initialize Composio with LangchainProvider (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/building-with-composio.md Initialize the Composio client with the LangchainProvider for Python applications. ```python from composio import Composio from composio_langchain import LangchainProvider composio = Composio(provider=LangchainProvider()) ``` -------------------------------- ### Incorrect TypeScript Example Source: https://github.com/composiohq/skills/blob/main/CONTRIBUTING.md Illustrates the incorrect way to implement a concept, with comments explaining the issue. This is part of the rule template. ```typescript // Show the wrong way with explanatory comments const bad = 'example'; ``` -------------------------------- ### Initialize Composio with Toolkit Versions Source: https://context7.com/composiohq/skills/llms.txt Initialize the Composio SDK specifying versions for different toolkits. This ensures consistent behavior across toolkit updates. ```python composio = Composio(toolkit_versions={"github": "12082025_00", "slack": "10082025_01"}) result = composio.tools.execute( tool="GITHUB_GET_ISSUES", user_id="user_123", arguments={"owner": "composio", "repo": "sdk"} ) if result.successful: print("Issues:", result.data) else: print("Error:", result.error) ``` -------------------------------- ### Best Practice: Discover and Pin Tool Versions (TypeScript) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-fetch-tools.md Discover available toolkits and tools first. Then, use discovered tool names and pin to a specific version string for stable execution. ```typescript // DO: Discover available versions and tools first const toolkit = await composio.toolkits.get('github'); console.log('Available versions:', toolkit.versions); const tools = await composio.tools.get('default', { toolkits: ['github'], limit: 100 }); // DO: Use discovered tool names and pin to a specific version string const toolName = tools.find(t => t.description.includes('repository'))?.name; if (toolName) { const result = composio.tools.execute(toolName, { userId: 'user_123', arguments: { owner: 'composio', repo: 'sdk' }, version: '12082025_00' // ✅ Pinned version string for stability }); } ``` -------------------------------- ### Get trigger status Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Check the current status of trigger instances. This command helps in monitoring the operational state of your triggers. ```bash composio manage triggers status ``` -------------------------------- ### Get trigger info Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Retrieve detailed information about a specific trigger type. This provides insights into how the trigger functions and its parameters. ```bash composio manage triggers info "GMAIL_NEW_GMAIL_MESSAGE" ``` -------------------------------- ### Deploy New Toolkit Version to Production Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-tool-versions.md Initialize Composio with the updated toolkit version for the production environment after successful testing and validation. ```typescript // Production environment const prodComposio = new Composio({ toolkitVersions: { github: '20082025_00' } // Deploy new version }); ``` -------------------------------- ### Get Specific Tool by Slug (Provider-Based) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/app-fetch-tools.md Use `tools.get()` to retrieve a single, specific tool by its slug for provider-based applications. ```typescript const tool = await composio.tools.get('default', 'GITHUB_GET_REPO'); ``` -------------------------------- ### Recommended Native Tool Usage (Python) Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-mcp-vs-native.md Leverage native tools in Python by configuring a provider for efficient, controlled execution with direct access to tool functionalities. ```python # DO: Use native tools for performance and control from composio import Composio from composio_openai import OpenAIProvider # Add provider for native tools composio = Composio(provider=OpenAIProvider()) session = composio.create( user_id="user_123", toolkits=["gmail", "slack"] ) # ✅ Direct tool execution (no MCP overhead) # ✅ Full modifier support # ✅ Logging and telemetry # ✅ Faster performance tools = session.tools() ``` -------------------------------- ### Enable a trigger instance Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/composio-cli.md Activate a specific trigger instance using its ID. This allows the trigger to start monitoring for events. ```bash composio manage triggers enable ``` -------------------------------- ### Create MCP Agent with OpenAI Agents Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-framework-integration.md Use Composio's HostedMCPTool to create an agent with OpenAI Agents. This approach is framework-independent but may result in slower execution. ```python from composio import Composio from agents import Agent, Runner, HostedMCPTool composio = Composio() def create_assistant_mcp(user_id: str): # Create session session = composio.create(user_id=user_id, toolkits=["gmail"]) # Create agent with MCP tool composio_mcp = HostedMCPTool( tool_config={ "type": "mcp", "server_label": "composio", "server_url": session.mcp.url, "require_approval": "never", "headers": session.mcp.headers } ) agent = Agent( name="Gmail Assistant", instructions="Help users manage their Gmail.", tools=[composio_mcp] ) # ✅ Framework independent # ⚠️ Slower execution return agent agent = create_assistant_mcp("user_123") result = Runner.run_sync(starting_agent=agent, input="Fetch my last email") print(result.final_output) ``` -------------------------------- ### Integrating with Express.js and Passport Source: https://github.com/composiohq/skills/blob/main/skills/composio/rules/tr-userid-best-practices.md Example of creating a Composio session using the user ID obtained from Passport authentication in an Express.js application. ```typescript // Express.js with Passport app.post('/api/agent', authenticateUser, async (req, res) => { const userId = req.user.id; // From Passport const session = await composio.create(userId, config); }); ```