# Composio Documentation > Composio powers 800+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action. # Documentation --- # Quickstart (/docs/quickstart) Build your first AI agent with Composio Tools. ## OpenAI Agents ### Native Tools #### Install **Python:** ```bash pip install python-dotenv composio composio-openai-agents openai-agents ``` **TypeScript:** ```bash npm install @composio/core @composio/openai-agents @openai/agents ``` #### Configure API Keys > Get your `COMPOSIO_API_KEY` from [Settings](https://platform.composio.dev/settings) and `OPENAI_API_KEY` from [OpenAI](https://platform.openai.com/api-keys). ```bash title=".env" COMPOSIO_API_KEY=your_composio_api_key OPENAI_API_KEY=your_openai_api_key ``` #### Create session and run agent **Python:** ```python from dotenv import load_dotenv from composio import Composio from agents import Agent, Runner, SQLiteSession from composio_openai_agents import OpenAIAgentsProvider load_dotenv() # Initialize Composio with OpenAI Agents provider composio = Composio(provider=OpenAIAgentsProvider()) # Create a session for your user user_id = "user_123" session = composio.create(user_id=user_id) tools = session.tools() # Configure agent with Composio tools agent = Agent( name="Personal Assistant", instructions="You are a helpful personal assistant. Use Composio tools to take action.", model="gpt-5", tools=tools, ) # Memory for multi-turn conversation memory = SQLiteSession("conversation") print(""" What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository' """) while True: user_input = input("You: ").strip() if user_input.lower() == "exit": break print("Assistant: ", end="", flush=True) try: result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory) print(f"{result.final_output}\n") except Exception as e: print(f"\n[Error]: {e}") ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { Agent, run, MemorySession } from "@openai/agents"; import { OpenAIAgentsProvider } from "@composio/openai-agents"; import { createInterface } from "readline/promises"; // Initialize Composio with OpenAI Agents provider const composio = new Composio({ provider: new OpenAIAgentsProvider() }); // Create a session for your user const userId = "user_123"; const session = await composio.create(userId); const tools = await session.tools(); const agent = new Agent({ name: "Personal Assistant", instructions: "You are a helpful personal assistant. Use Composio tools to take action.", model: "gpt-5", tools, }); // Memory for multi-turn conversation const memory = new MemorySession(); const readline = createInterface({ input: process.stdin, output: process.stdout }); console.log(` What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository and create a Google Sheet with the issues' `); // Multi-turn conversation with agentic tool calling while (true) { const query = await readline.question("You: "); const input = query.trim(); if (input.toLowerCase() === "exit") break; process.stdout.write("Assistant: "); try { const result = await run(agent, input, { session: memory }); process.stdout.write(`${result.finalOutput}\n`); } catch (error) { console.error("\n[Error]:", error instanceof Error ? error.message : error); readline.close(); ``` ### MCP #### Install **Python:** ```bash pip install python-dotenv composio openai-agents ``` **TypeScript:** ```bash npm install dotenv @composio/core @openai/agents zod@3 ``` #### Configure API Keys > Get your `COMPOSIO_API_KEY` from [Settings](https://platform.composio.dev/settings) and `OPENAI_API_KEY` from [OpenAI](https://platform.openai.com/api-keys). ```bash title=".env" COMPOSIO_API_KEY=your_composio_api_key OPENAI_API_KEY=your_openai_api_key ``` #### Create session and run agent **Python:** ```python from dotenv import load_dotenv from composio import Composio from agents import Agent, Runner, HostedMCPTool, SQLiteSession load_dotenv() # Initialize Composio composio = Composio() # Create a session for your user user_id = "user_123" session = composio.create(user_id=user_id) # Configure agent with Composio MCP server agent = Agent( name="Personal Assistant", instructions="You are a helpful personal assistant. Use Composio tools to take action.", model="gpt-5", tools=[ HostedMCPTool( tool_config={ "type": "mcp", "server_label": "composio", "server_url": session.mcp.url, "require_approval": "never", "headers": session.mcp.headers, ) ], ) # Memory for multi-turn conversation memory = SQLiteSession(user_id) print(""" What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository' """) while True: user_input = input("You: ").strip() if user_input.lower() == "exit": break print("Assistant: ", end="", flush=True) try: result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory) print(f"{result.final_output}\n") except Exception as e: print(f"\n[Error]: {e}") ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { Agent, run, hostedMcpTool, MemorySession } from "@openai/agents"; import { createInterface } from "readline/promises"; // Initialize Composio const composio = new Composio(); // Create a session for your user const userId = "user_123"; const session = await composio.create(userId); const agent = new Agent({ name: "Personal Assistant", instructions: "You are a helpful personal assistant. Use Composio tools to take action.", model: "gpt-5", tools: [ hostedMcpTool({ serverLabel: "composio", serverUrl: session.mcp.url, headers: session.mcp.headers, }), ], }); // Memory for multi-turn conversation const memory = new MemorySession(); const readline = createInterface({ input: process.stdin, output: process.stdout }); console.log(` What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository and create a Google Sheet with the issues' `); // Multi-turn conversation with agentic tool calling while (true) { const input = (await readline.question("You: ")).trim(); if (input.toLowerCase() === "exit") break; console.log("Assistant: "); try { const result = await run(agent, input, { session: memory }); console.log(`${result.finalOutput}`); } catch (error) { console.error("\n[Error]:", error instanceof Error ? error.message : error); readline.close(); ``` ## Claude Agent SDK ### Native Tools #### Install **Python:** ```bash pip install python-dotenv composio composio-claude-agent-sdk claude-agent-sdk ``` **TypeScript:** ```bash npm install dotenv @composio/core @composio/claude-agent-sdk @anthropic-ai/claude-agent-sdk ``` #### Configure API Keys > Get your `COMPOSIO_API_KEY` from [Settings](https://platform.composio.dev/settings) and `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys). ```bash title=".env" COMPOSIO_API_KEY=your_composio_api_key ANTHROPIC_API_KEY=your_anthropic_api_key ``` #### Create session and run agent **Python:** ```python import asyncio from dotenv import load_dotenv from composio import Composio from composio_claude_agent_sdk import ClaudeAgentSDKProvider from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, create_sdk_mcp_server, AssistantMessage, TextBlock load_dotenv() # Initialize Composio with Claude Agent SDK provider composio = Composio(provider=ClaudeAgentSDKProvider()) # Create a session for your user user_id = "user_123" session = composio.create(user_id=user_id) tools = session.tools() custom_server = create_sdk_mcp_server(name="composio", version="1.0.0", tools=tools) async def main(): options = ClaudeAgentOptions( system_prompt="You are a helpful assistant. Use tools to complete tasks.", permission_mode="bypassPermissions", mcp_servers={"composio": custom_server}, ) async with ClaudeSDKClient(options=options) as client: print("Assistant ready! Type 'exit' to quit.") while True: user_input = input("You: ").strip() if user_input.lower() == "exit": break await client.query(user_input) print("Claude: ", end="") async for message in client.receive_response(): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): print(block.text, end="", flush=True) print() asyncio.run(main()) ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { ClaudeAgentSDKProvider } from "@composio/claude-agent-sdk"; import { createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk"; import { createInterface } from "readline/promises"; // Initialize Composio with Claude Agent SDK provider const composio = new Composio({ provider: new ClaudeAgentSDKProvider() }); // Create a session for your user const userId = "user_123"; const session = await composio.create(userId); const tools = await session.tools(); const customServer = createSdkMcpServer({ name: "composio", version: "1.0.0", tools: tools, }); const readline = createInterface({ input: process.stdin, output: process.stdout }); console.log(` What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository and create a Google Sheet with the issues' `); let isFirstQuery = true; const options = { mcpServers: { composio: customServer }, permissionMode: "bypassPermissions" as const, }; while (true) { const input = (await readline.question("You: ")).trim(); if (input.toLowerCase() === "exit") break; process.stdout.write("Claude: "); const queryOptions = isFirstQuery ? options : { ...options, continue: true }; isFirstQuery = false; for await (const stream of query({ prompt: input, options: queryOptions })) { if (stream.type === "assistant") { for (const block of stream.message.content) { if (block.type === "text") { process.stdout.write(block.text); console.log(); readline.close(); ``` ### MCP #### Install **Python:** ```bash pip install python-dotenv composio claude-agent-sdk ``` **TypeScript:** ```bash npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk ``` #### Configure API Keys > Get your `COMPOSIO_API_KEY` from [Settings](https://platform.composio.dev/settings) and `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys). ```bash title=".env" COMPOSIO_API_KEY=your_composio_api_key ANTHROPIC_API_KEY=your_anthropic_api_key ``` #### Create session and run agent **Python:** ```python import asyncio from dotenv import load_dotenv from claude_agent_sdk.client import ClaudeSDKClient from claude_agent_sdk.types import ( ClaudeAgentOptions, AssistantMessage, TextBlock, ToolUseBlock, ) from composio import Composio load_dotenv() # Initialize Composio composio = Composio() # Create a session for your user user_id = "user_123" session = composio.create(user_id=user_id) # Configure Claude with Composio MCP server options = ClaudeAgentOptions( system_prompt=( "You are a helpful assistant with access to external tools. " "Always use the available tools to complete user requests." ), mcp_servers={ "composio": { "type": "http", "url": session.mcp.url, "headers": session.mcp.headers, }, permission_mode="bypassPermissions", ) async def main(): print(""" What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository and create a notion page with the issues' """) async with ClaudeSDKClient(options) as client: # Multi-turn conversation with agentic tool calling while True: user_input = input("You: ").strip() if user_input.lower() == "exit": break print("\nClaude: ", end="", flush=True) try: await client.query(user_input) async for msg in client.receive_response(): if isinstance(msg, AssistantMessage): for block in msg.content: if isinstance(block, ToolUseBlock): print(f"\n[Using tool: {block.name}]", end="") elif isinstance(block, TextBlock): print(block.text, end="", flush=True) print() except Exception as e: print(f"\n[Error]: {e}") if __name__ == "__main__": asyncio.run(main()) ``` **TypeScript:** ```typescript import "dotenv/config"; import { query, type Options } from "@anthropic-ai/claude-agent-sdk"; import { Composio } from "@composio/core"; import { createInterface } from "readline/promises"; // Initialize Composio const composio = new Composio(); // Create a session for your user const userId = "user_123"; const session = await composio.create(userId); const options: Options = { systemPrompt: `You are a helpful assistant with access to external tools. ` + `Always use the available tools to complete user requests.`, mcpServers: { composio: { type: "http", url: session.mcp.url, headers: session.mcp.headers, }, }, permissionMode: "bypassPermissions", }; const readline = createInterface({ input: process.stdin, output: process.stdout }); console.log(` What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository and create a Google Sheet with the issues' `); let isFirstQuery = true; // Multi-turn conversation with agentic tool calling while (true) { const answer = await readline.question('You: '); const input = answer.trim(); if (input.toLowerCase() === "exit") break; process.stdout.write("Claude: "); // Use `continue: true` to maintain conversation context const queryOptions = isFirstQuery ? options : { ...options, continue: true }; isFirstQuery = false; try { for await (const stream of query({ prompt: input, options: queryOptions })) { if (stream.type === "assistant") { const { content } = stream.message; for (const block of content) { if (block.type === "tool_use") { process.stdout.write(`\n[Using tool: ${block.name}]`); } else if (block.type === "text") { process.stdout.write(block.text); } catch (error) { console.error("\n[Error]:", error instanceof Error ? error.message : error); process.stdout.write("\n"); readline.close(); ``` ## Vercel AI ### Native Tools #### Install ```bash npm install @composio/core @composio/vercel ai @ai-sdk/anthropic ``` #### Configure API Keys > Get your `COMPOSIO_API_KEY` from [Settings](https://platform.composio.dev/settings) and `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys). ```bash title=".env" COMPOSIO_API_KEY=your_composio_api_key ANTHROPIC_API_KEY=your_anthropic_api_key ``` #### Create session and run agent ```typescript // @noErrors import "dotenv/config"; import { anthropic } from "@ai-sdk/anthropic"; import { Composio } from "@composio/core"; import { VercelProvider } from "@composio/vercel"; import { streamText, stepCountIs, type ModelMessage } from "ai"; import { createInterface } from "readline/promises"; // Initialize Composio with Vercel provider const composio = new Composio({ provider: new VercelProvider() }); // Create a session for your user const userId = "user_123"; const session = await composio.create(userId); const tools = await session.tools(); const readline = createInterface({ input: process.stdin, output: process.stdout }); console.log(` What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository' `); // Message history for multi-turn conversation const messages: ModelMessage[] = []; while (true) { const input = (await readline.question("You: ")).trim(); if (input.toLowerCase() === "exit") break; messages.push({ role: "user", content: input }); process.stdout.write("Assistant: "); try { const result = await streamText({ system: "You are a helpful personal assistant. Use Composio tools to take action.", model: anthropic("claude-sonnet-4-5"), messages, stopWhen: stepCountIs(10), onStepFinish: (step) => { for (const toolCall of step.toolCalls) { process.stdout.write(`\n[Using tool: ${toolCall.toolName}]`); }, tools, }); let assistantResponse = ""; for await (const textPart of result.textStream) { process.stdout.write(textPart); assistantResponse += textPart; console.log(); // Add assistant response to history for context messages.push({ role: "assistant", content: assistantResponse }); } catch (error) { console.error("\n[Error]:", error instanceof Error ? error.message : error); readline.close(); ``` ### MCP #### Install ```bash npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp ``` #### Configure API Keys > Get your `COMPOSIO_API_KEY` from [Settings](https://platform.composio.dev/settings) and `ANTHROPIC_API_KEY` from [Anthropic](https://console.anthropic.com/settings/keys). ```bash title=".env" COMPOSIO_API_KEY=your_composio_api_key ANTHROPIC_API_KEY=your_anthropic_api_key ``` #### Create session and run agent ```typescript // @noErrors import "dotenv/config"; import { anthropic } from "@ai-sdk/anthropic"; import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp"; import { Composio } from "@composio/core"; import { streamText, stepCountIs, type ModelMessage } from "ai"; import { createInterface } from "readline/promises"; // Initialize Composio const composio = new Composio(); // Create a session for your user const userId = "user_123"; const { mcp } = await composio.create(userId); // Create an MCP client to connect to Composio const client = await createMCPClient({ transport: { type: "http", url: mcp.url, headers: mcp.headers, }, }); const tools = await client.tools(); const readline = createInterface({ input: process.stdin, output: process.stdout }); console.log(` What task would you like me to help you with? I can use tools like Gmail, GitHub, Linear, Notion, and more. (Type 'exit' to exit) Example tasks: - 'Summarize my emails from today' - 'List all open issues on the composio github repository' `); // Message history for multi-turn conversation const messages: ModelMessage[] = []; while (true) { const input = (await readline.question("You: ")).trim(); if (input.toLowerCase() === "exit") break; messages.push({ role: "user", content: input }); process.stdout.write("Assistant: "); try { const result = await streamText({ system: "You are a helpful personal assistant. Use Composio tools to take action.", model: anthropic("claude-sonnet-4-5"), messages, stopWhen: stepCountIs(10), onStepFinish: (step) => { for (const toolCall of step.toolCalls) { process.stdout.write(`\n[Using tool: ${toolCall.toolName}]`); }, tools, }); let assistantResponse = ""; for await (const textPart of result.textStream) { process.stdout.write(textPart); assistantResponse += textPart; console.log(); // Add assistant response to history for context messages.push({ role: "assistant", content: assistantResponse }); } catch (error) { console.error("\n[Error]:", error instanceof Error ? error.message : error); readline.close(); ``` --- # OpenAI Agents (/docs/providers/openai-agents) ### Native Tools **Install** **Python:** ```bash pip install composio composio-openai-agents openai-agents ``` **TypeScript:** ```bash npm install dotenv @composio/core @composio/openai-agents @openai/agents ``` **Configure API Keys** > Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `OPENAI_API_KEY` with your [OpenAI API key](https://platform.openai.com/api-keys). ```txt title=".env" COMPOSIO_API_KEY=xxxxxxxxx OPENAI_API_KEY=xxxxxxxxx ``` **Create session and run agent** **Python:** ```python import asyncio from dotenv import load_dotenv load_dotenv() from composio import Composio from agents import Agent, Runner from composio_openai_agents import OpenAIAgentsProvider # Initialize Composio with OpenAI Agents provider composio = Composio(provider=OpenAIAgentsProvider()) external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Create a session session = composio.create(user_id=external_user_id) # Get tools from the session tools = session.tools() # Create agent with tools agent = Agent( name="Email Manager", instructions="You are a helpful assistant.", tools=tools, ) # Run the agent async def main(): result = await Runner.run( starting_agent=agent, input=f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'Hello from the other side!'", ) print(result.final_output) asyncio.run(main()) ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { Agent, run } from "@openai/agents"; import { OpenAIAgentsProvider } from "@composio/openai-agents"; // Initialize Composio with OpenAI Agents provider const composio = new Composio({ provider: new OpenAIAgentsProvider(), }); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Create a session const session = await composio.create(externalUserId); // Get tools from the session const tools = await session.tools(); // Create agent with tools const agent = new Agent({ name: "Email Manager", instructions: "You are a helpful assistant.", tools: tools, }); // Run the agent console.log("Running agent..."); const result = await run( agent, `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'` ); console.log("Received response from agent"); if (result.finalOutput) { console.log(result.finalOutput); ``` ### MCP **Install** **Python:** ```bash pip install composio openai-agents ``` **TypeScript:** ```bash npm install dotenv @composio/core @openai/agents ``` **Configure API Keys** > Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `OPENAI_API_KEY` with your [OpenAI API key](https://platform.openai.com/api-keys). ```txt title=".env" COMPOSIO_API_KEY=xxxxxxxxx OPENAI_API_KEY=xxxxxxxxx ``` **Create session and run agent** **Python:** ```python import asyncio from dotenv import load_dotenv load_dotenv() from composio import Composio from agents import Agent, Runner, HostedMCPTool # Initialize Composio composio = Composio() external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Create a session session = composio.create(user_id=external_user_id) # Create MCP tool composio_mcp = HostedMCPTool( tool_config={ "type": "mcp", "server_label": "composio", "server_url": session.mcp.url, "require_approval": "never", "headers": session.mcp.headers, ) # Create agent with MCP tool agent = Agent( name="Email Manager", instructions="You are a helpful assistant.", tools=[composio_mcp], ) # Run the agent async def main(): result = await Runner.run( starting_agent=agent, input=f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'", ) print(result.final_output) asyncio.run(main()) ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { Agent, run, hostedMcpTool } from "@openai/agents"; // Initialize Composio const composio = new Composio(); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Create a session const session = await composio.create(externalUserId); // Create agent with MCP tool const agent = new Agent({ name: "Email Manager", instructions: "You are a helpful assistant.", tools: [ hostedMcpTool({ serverLabel: "composio", serverUrl: session.mcp.url, headers: session.mcp.headers, }), ], }); // Run the agent console.log("Running agent..."); const result = await run( agent, `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'` ); console.log("Received response from agent"); if (result.finalOutput) { console.log(result.finalOutput); ``` **Direct tool usage** > Only use this if you want to use a single, direct tool with your AI Agent. **Install** **Python:** ```bash pip install composio openai-agents composio-openai-agents ``` **TypeScript:** ```bash npm install @composio/core @openai/agents @composio/openai-agents ``` **Usage** **Python:** ```python import asyncio from composio import Composio from agents import Agent, Runner from composio_openai_agents import OpenAIAgentsProvider composio = Composio(provider=OpenAIAgentsProvider()) external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Get a specific tool tools = composio.tools.get(user_id=external_user_id, tools=["GMAIL_SEND_EMAIL"]) agent = Agent( name="Email Manager", instructions="You are a helpful assistant.", tools=tools, ) async def main(): result = await Runner.run( starting_agent=agent, input=f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'", ) print(result.final_output) asyncio.run(main()) ``` **TypeScript:** ```typescript import { Composio } from "@composio/core"; import { Agent, run } from "@openai/agents"; import { OpenAIAgentsProvider } from "@composio/openai-agents"; const composio = new Composio({ provider: new OpenAIAgentsProvider(), }); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Get a specific tool const tools = await composio.tools.get(externalUserId, { tools: ["GMAIL_SEND_EMAIL"], }); const agent = new Agent({ name: "Email Manager", instructions: "You are a helpful assistant.", tools: tools, }); console.log("Running agent..."); const result = await run( agent, `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'` ); console.log("Received response from agent"); if (result.finalOutput) { console.log(result.finalOutput); ``` --- # Anthropic (/docs/providers/anthropic) # Claude Agents SDK ### Native Tools **Install** **Python:** ```bash pip install composio composio-claude-agent-sdk claude-agent-sdk ``` **TypeScript:** ```bash npm install dotenv @composio/core @composio/claude-agent-sdk @anthropic-ai/claude-agent-sdk ``` **Configure API Keys** > Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `ANTHROPIC_API_KEY` with your [Anthropic API key](https://console.anthropic.com/settings/keys). ```txt title=".env" COMPOSIO_API_KEY=xxxxxxxxx ANTHROPIC_API_KEY=xxxxxxxxx ``` **Create session and run agent** **Python:** ```python import asyncio from dotenv import load_dotenv load_dotenv() from composio import Composio from composio_claude_agent_sdk import ClaudeAgentSDKProvider from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions, create_sdk_mcp_server # Initialize Composio with Claude Agent SDK provider composio = Composio(provider=ClaudeAgentSDKProvider()) external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Create a session session = composio.create(user_id=external_user_id) # Get tools from the session tools = session.tools() custom_server = create_sdk_mcp_server(name="composio", version="1.0.0", tools=tools) # Run the agent async def main(): options = ClaudeAgentOptions( system_prompt="You are a helpful assistant.", permission_mode="bypassPermissions", mcp_servers={"composio": custom_server}, ) async with ClaudeSDKClient(options=options) as client: await client.query(f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'") async for msg in client.receive_response(): print(msg) asyncio.run(main()) ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { ClaudeAgentSDKProvider } from "@composio/claude-agent-sdk"; import { createSdkMcpServer, query } from "@anthropic-ai/claude-agent-sdk"; // Initialize Composio with Claude Agent SDK provider const composio = new Composio({ provider: new ClaudeAgentSDKProvider(), }); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Create a session const session = await composio.create(externalUserId); // Get tools from the session const tools = await session.tools(); const customServer = createSdkMcpServer({ name: "composio", version: "1.0.0", tools: tools, }); // Run the agent console.log("Running agent..."); for await (const content of query({ prompt: `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`, options: { mcpServers: { composio: customServer }, permissionMode: "bypassPermissions", }, })) { if (content.type === "assistant") { console.log("Claude:", content.message); console.log("Received response from Claude"); ``` ### MCP **Install** **Python:** ```bash pip install composio claude-agent-sdk ``` **TypeScript:** ```bash npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk ``` **Configure API Keys** > Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `ANTHROPIC_API_KEY` with your [Anthropic API key](https://console.anthropic.com/settings/keys). ```txt title=".env" COMPOSIO_API_KEY=xxxxxxxxx ANTHROPIC_API_KEY=xxxxxxxxx ``` **Create session and run agent** **Python:** ```python import asyncio from dotenv import load_dotenv load_dotenv() from composio import Composio from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions # Initialize Composio composio = Composio() external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Create a session session = composio.create(user_id=external_user_id) # Run the agent async def main(): options = ClaudeAgentOptions( system_prompt="You are a helpful assistant.", permission_mode="bypassPermissions", mcp_servers={ "composio": { "type": "http", "url": session.mcp.url, "headers": session.mcp.headers, }, ) async with ClaudeSDKClient(options=options) as client: await client.query(f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'") async for msg in client.receive_response(): print(msg) asyncio.run(main()) ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { query } from "@anthropic-ai/claude-agent-sdk"; // Initialize Composio const composio = new Composio(); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Create a session const session = await composio.create(externalUserId); // Run the agent console.log("Running agent..."); for await (const content of query({ prompt: `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`, options: { mcpServers: { composio: { type: "http", url: session.mcp.url, headers: session.mcp.headers, }, }, permissionMode: "bypassPermissions", }, })) { if (content.type === "assistant") { console.log("Claude:", content.message); console.log("Received response from Claude"); ``` # Anthropic API **Install** **Python:** ```bash pip install composio composio-anthropic anthropic ``` **TypeScript:** ```bash npm install dotenv @composio/core @composio/anthropic @anthropic-ai/sdk ``` **Configure API Keys** > Set `COMPOSIO_API_KEY` with your API key from [Settings](https://platform.composio.dev/?next_page=/settings) and `ANTHROPIC_API_KEY` with your [Anthropic API key](https://console.anthropic.com/settings/keys). ```txt title=".env" COMPOSIO_API_KEY=xxxxxxxxx ANTHROPIC_API_KEY=xxxxxxxxx ``` **Create session and run agent** **Python:** ```python import anthropic from dotenv import load_dotenv load_dotenv() from composio import Composio from composio_anthropic import AnthropicProvider # Initialize Composio with Anthropic provider anthropic_client = anthropic.Anthropic() composio = Composio(provider=AnthropicProvider()) external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Create a session session = composio.create(user_id=external_user_id) # Get tools from the session tools = session.tools() # Get response from the LLM response = anthropic_client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=tools, messages=[ {"role": "user", "content": f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'"}, ], ) # Execute the function calls result = composio.provider.handle_tool_calls(user_id=external_user_id, response=response) print(result) ``` **TypeScript:** ```typescript import "dotenv/config"; import { Composio } from "@composio/core"; import { AnthropicProvider } from "@composio/anthropic"; import Anthropic from "@anthropic-ai/sdk"; // Initialize Composio with Anthropic provider const composio = new Composio({ provider: new AnthropicProvider(), }); const anthropic = new Anthropic(); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Create a session const session = await composio.create(externalUserId); // Get tools from the session const tools = await session.tools(); // Get response from the LLM const msg = await anthropic.messages.create({ model: "claude-sonnet-4-5", messages: [ role: "user", content: `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`, }, ], tools: tools, max_tokens: 1000, }); // Execute the function calls const result = await composio.provider.handleToolCalls(externalUserId, msg); console.log(result); ``` **Direct tool usage** > Only use this if you want to use a single, direct tool with your AI Agent. **Install** **Python:** ```bash pip install composio composio-anthropic anthropic ``` **TypeScript:** ```bash npm install @composio/core @composio/anthropic @anthropic-ai/sdk ``` **Usage** **Python:** ```python import anthropic from composio import Composio from composio_anthropic import AnthropicProvider anthropic_client = anthropic.Anthropic() composio = Composio(provider=AnthropicProvider()) external_user_id = "user_2nFh83Hde" recipient_email = "soham.g@composio.dev" # Get a specific tool tools = composio.tools.get(user_id=external_user_id, tools=["GMAIL_SEND_EMAIL"]) response = anthropic_client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=tools, messages=[ {"role": "user", "content": f"Send an email to {recipient_email} with the subject 'Hello from Composio' and the body 'This is a test email!'"}, ], ) result = composio.provider.handle_tool_calls(user_id=external_user_id, response=response) print(result) ``` **TypeScript:** ```typescript import { Composio } from "@composio/core"; import { AnthropicProvider } from "@composio/anthropic"; import Anthropic from "@anthropic-ai/sdk"; const composio = new Composio({ provider: new AnthropicProvider(), }); const anthropic = new Anthropic(); const externalUserId = "user_2nFh83Hde"; const recipientEmail = "soham.g@composio.dev"; // Get a specific tool const tools = await composio.tools.get(externalUserId, { tools: ["GMAIL_SEND_EMAIL"], }); const msg = await anthropic.messages.create({ model: "claude-sonnet-4-5", messages: [ role: "user", content: `Send an email to ${recipientEmail} with the subject 'Hello from Composio' and the body 'This is a test email!'`, }, ], tools: tools, max_tokens: 1000, }); const result = await composio.provider.handleToolCalls(externalUserId, msg); console.log(result); ``` --- # Vercel AI SDK (/docs/providers/vercel) Vercel AI SDK allows you to configure an optional async `execute` function that the framework uses to execute the tool calls. The Vercel provider for Composio formats the Composio tools and adds this `execute` function to the tool calls. # Usage with Tools Use Composio as a native tool with the Vercel AI SDK. ## Installation ```bash npm install @composio/core @composio/vercel ai @ai-sdk/anthropic ``` ## Usage Create a session and use it as a native tool with Vercel AI SDK: > * Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings). * Set `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://console.anthropic.com/settings/keys). ```typescript // @noErrors import "dotenv/config"; import { anthropic } from "@ai-sdk/anthropic"; import { Composio } from "@composio/core"; import { VercelProvider } from "@composio/vercel"; import { stepCountIs, streamText } from "ai"; // Initialize Composio with Vercel provider (API key from env var COMPOSIO_API_KEY) const composio = new Composio({ provider: new VercelProvider() }); // Unique identifier of the user const userId = "user_123"; // Create a session and get native tools for the user const session = await composio.create(userId); const tools = await session.tools(); console.log("Fetching GitHub issues from the Composio repository..."); // Stream the response with tool calling const stream = await streamText({ system: "You are a helpful personal assistant. Use Composio tools to take action.", model: anthropic("claude-sonnet-4-5"), prompt: "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.", stopWhen: stepCountIs(10), onStepFinish: (step) => { for (const toolCall of step.toolCalls) { console.log(`[Using tool: ${toolCall.toolName}]`); }, tools, }); for await (const textPart of stream.textStream) { process.stdout.write(textPart); console.log("\n\n---"); console.log("Tip: If prompted to authenticate, complete the auth flow and run again."); ``` # Usage with MCP Use Composio with the Vercel AI SDK for a fully managed MCP experience. ## Installation ```bash npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp ``` ## Usage Use Composio with Vercel AI SDK's `streamText` for completions: > * Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings). * Set `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://platform.claude.com/settings/keys). ```typescript // @noErrors import "dotenv/config"; import { anthropic } from "@ai-sdk/anthropic"; import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp"; import { Composio } from "@composio/core"; import { stepCountIs, streamText } from "ai"; // Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" }) const composio = new Composio(); // Unique identifier of the user const userId = "user_123"; // Create a session for the user const { mcp } = await composio.create(userId); // Create an MCP client to connect to the Composio MCP server const client = await createMCPClient({ transport: { type: "http", url: mcp.url, headers: mcp.headers, // Authentication headers for the Composio MCP server }, }); const tools = await client.tools(); console.log("Summarizing your emails from today"); const stream = await streamText({ system: "You are a helpful personal assistant. Use Composio tools to take action.", model: anthropic("claude-sonnet-4-5"), prompt: "Summarize my emails from today", stopWhen: stepCountIs(10), onStepFinish: (step) => { for (const toolCall of step.toolCalls) { console.log(`[Using tool: ${toolCall.toolName}]`); }, tools, }); for await (const textPart of stream.textStream) { process.stdout.write(textPart); console.log("\n\n---"); console.log("Tip: If prompted to authenticate, complete the auth flow and run again.") ``` # Usage with direct tools ## Setup Vercel AI SDK and the provider are only available for the TypeScript SDK. ```bash npm install @composio/vercel ``` You can specify and import the provider in the constructor. ```typescript import { Composio } from '@composio/core'; import { VercelProvider } from '@composio/vercel'; import { generateText } from 'ai'; import { openai } from "@ai-sdk/openai"; const composio = new Composio({ provider: new VercelProvider(), }); ``` ## Usage ```typescript import { Composio } from '@composio/core'; import { VercelProvider } from '@composio/vercel'; import { generateText } from 'ai'; import { openai } from "@ai-sdk/openai"; const composio = new Composio({ provider: new VercelProvider() }); // ---cut--- // create an auth config for gmail // then create a connected account with an external user id that identifies the user const externalUserId = "your-external-user-id"; const tools = await composio.tools.get(externalUserId, "GMAIL_SEND_EMAIL"); // env: OPENAI_API_KEY const { text } = await generateText({ model: openai("gpt-5"), messages: [ role: "user", content: `Send an email to soham.g@composio.dev with the subject 'Hello from composio' and the body 'Congratulations on sending your first email using AI Agents and Composio!'`, }, ], tools, }); console.log("Email sent successfully!", { text }); ``` --- # LangChain (/docs/providers/langchain) The LangChain Provider transforms Composio tools into a format compatible with LangChain's function calling capabilities. # Setup **Python:** ```bash pip install composio_langchain==0.8.0 langchain ``` **TypeScript:** ```bash npm install @composio/langchain ``` # Usage **Python:** ```python from composio import Composio from composio_langchain import LangchainProvider from langchain import hub # type: ignore from langchain.agents import AgentExecutor, create_openai_functions_agent from langchain_openai import ChatOpenAI # Pull relevant agent model. prompt = hub.pull("hwchase17/openai-functions-agent") # Initialize tools. openai_client = ChatOpenAI(model="gpt-5") composio = Composio(provider=LangchainProvider()) # Get All the tools tools = composio.tools.get(user_id="default", toolkits=["GITHUB"]) # Define task task = "Star a repo composiohq/composio on GitHub" # Define agent agent = create_openai_functions_agent(openai_client, tools, prompt) agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True) # Execute using agent_executor agent_executor.invoke({"input": task}) ``` **TypeScript:** ```typescript import { ChatOpenAI } from '@langchain/openai'; import { HumanMessage, AIMessage } from '@langchain/core/messages'; import { ToolNode } from '@langchain/langgraph/prebuilt'; import { StateGraph, MessagesAnnotation } from '@langchain/langgraph'; import { Composio } from '@composio/core'; import { LangchainProvider } from '@composio/langchain'; // initiate composio const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY, provider: new LangchainProvider(), }); // fetch the tool console.log(`šŸ”„ Fetching the tool...`); const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER'); // Define the tools for the agent to use const toolNode = new ToolNode(tools); // Create a model and give it access to the tools const model = new ChatOpenAI({ model: 'gpt-4o-mini', temperature: 0, }).bindTools(tools); // Define the function that determines whether to continue or not function shouldContinue({ messages }: typeof MessagesAnnotation.State) { const lastMessage = messages[messages.length - 1] as AIMessage; // If the LLM makes a tool call, then we route to the "tools" node if (lastMessage.tool_calls?.length) { return 'tools'; // Otherwise, we stop (reply to the user) using the special "__end__" node return '__end__'; // Define the function that calls the model async function callModel(state: typeof MessagesAnnotation.State) { console.log(`šŸ”„ Calling the model...`); const response = await model.invoke(state.messages); // We return a list, because this will get added to the existing list return { messages: [response] }; // Define a new graph const workflow = new StateGraph(MessagesAnnotation) .addNode('agent', callModel) .addEdge('__start__', 'agent') // __start__ is a special name for the entrypoint .addNode('tools', toolNode) .addEdge('tools', 'agent') .addConditionalEdges('agent', shouldContinue); // Finally, we compile it into a LangChain Runnable. const app = workflow.compile(); // Use the agent const finalState = await app.invoke({ messages: [new HumanMessage('Find the details of the user `pg` on HackerNews')], }); console.log(`āœ… Message recieved from the model`); console.log(finalState.messages[finalState.messages.length - 1].content); const nextState = await app.invoke({ // Including the messages from the previous run gives the LLM context. // This way it knows we're asking about the weather in NY messages: [...finalState.messages, new HumanMessage('what about haxzie')], }); console.log(`āœ… Message recieved from the model`); console.log(nextState.messages[nextState.messages.length - 1].content); ``` --- # Mastra (/docs/providers/mastra) Mastra is a TypeScript native framework for building agents with tools and MCPs. It expects tools to be in the following format: * Inputs: What information the tool needs to run (defined with an `inputSchema`, often using Zod). * Outputs: The structure of the data the tool returns (defined with an `outputSchema`). * Execution Logic: The code that performs the tool's action. * Description: Text that helps the agent understand what the tool does and when to use it. More documentation [here](https://mastra.ai/en/docs/tools-mcp/overview#creating-tools) The Mastra provider formats the Composio tools into this format along with the execution logic so that agents can call and execute the Composio tools. # Setup ```bash npm install @composio/mastra ``` You can specify the provider in the constructor. ```typescript import { Composio } from "@composio/core"; import { MastraProvider } from "@composio/mastra"; import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; const composio = new Composio({ provider: new MastraProvider(), }); ``` # Usage The tools are passed to the agent as a parameter. ```typescript import { Composio } from "@composio/core"; import { MastraProvider } from "@composio/mastra"; import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; const composio = new Composio({ provider: new MastraProvider() }); // ---cut--- const userId = "john doe"; const tools = await composio.tools.get( userId, toolkits: ["SUPABASE"], ); const agent = new Agent({ id: "supabase-agent", name: "Supabase Agent", instructions: "You think therefore you are.", model: openai("gpt-4.1"), tools: tools, }); const { text } = await agent.generate([ { role: "user", content: "Tell me about my Supabase project" }, ]); console.log("\nšŸ¤– Agent Response:\n"); console.log(text); ``` # Usage: Direct MCP Servers You can also use Composio MCP servers directly with Mastra's MCPClient. > Composio MCP servers only support Streamable HTTP transport. ```typescript // @noErrors import { MCPClient } from "@mastra/mcp"; import { openai } from "@ai-sdk/openai"; import { Agent } from "@mastra/core/agent"; import { Composio } from "@composio/core"; // Initialize Composio const composio = new Composio(); // Create MCP server with GitHub, Linear, and Notion tools const server = await composio.mcp.create( "dev-automation-server", toolkits: [ { toolkit: "github", authConfigId: "ac_github_id" }, { toolkit: "linear", authConfigId: "ac_linear_id" }, { toolkit: "notion", authConfigId: "ac_notion_id" } ], allowedTools: [ "GITHUB_LIST_ISSUES", "GITHUB_CREATE_ISSUE", "LINEAR_CREATE_ISSUE", "LINEAR_UPDATE_ISSUE", "NOTION_CREATE_PAGE", "NOTION_UPDATE_PAGE" ] ); // Generate MCP instance for user const instance = await server.generate("user@example.com"); // Create MCP client with Composio server export const mcpClient = new MCPClient({ id: "composio-mcp-client", servers: { composio: { url: new URL(instance.url) }, }); // Create a development workflow agent export const devAgent = new Agent({ id: "dev-assistant", name: "Dev Assistant", description: "AI assistant for development workflow automation", instructions: "Help manage GitHub repos, Linear issues, and Notion documentation.", model: openai("gpt-4-turbo"), tools: await mcpClient.getTools() }); // Example: Automate development workflow (async () => { const response = await devAgent.generate( "Review open GitHub issues, create Linear tasks for bugs labeled 'priority', and update the Notion roadmap page" ); console.log(response.text); })(); ``` --- # OpenAI (/docs/providers/openai) The OpenAI Provider is the default provider for the Composio SDK. It transforms Composio tools into a format compatible with OpenAI's function calling capabilities through both the Responses and Chat Completion APIs. # Setup By default, the OpenAI Provider is installed when you install the Composio SDK. You can also install it manually: **Python:** ```bash pip install composio_openai ``` **TypeScript:** ```bash npm install @composio/openai ``` # Responses API The Responses API is the recommended way to build more agentic flows with the OpenAI API. Read more about it in the [OpenAI documentation](https://platform.openai.com/docs/api-reference/responses) > Before executing any tools that require authentication (like Gmail), you'll need to: 1. [Create an Auth Configuration](/docs/authenticating-tools#creating-an-auth-config) for your app 2. [Set up a Connected Account](/docs/authenticating-tools#connecting-an-account) for the user. **Python:** ```python from openai import OpenAI from composio import Composio from composio_openai import OpenAIResponsesProvider # Initialize Composio client with OpenAI Provider composio = Composio(provider=OpenAIResponsesProvider()) openai = OpenAI() # Make sure to create an auth config and a connected account for the user with gmail toolkit # Make sure to replace "your-user-id" with the actual user ID user_id = "your-user-id" tools = composio.tools.get(user_id=user_id, tools=["GMAIL_SEND_EMAIL"]) response = openai.responses.create( model="gpt-5", tools=tools, input=[ "role": "user", "content": "Send an email to soham.g@composio.dev with the subject 'Running OpenAI Provider snippet' and body 'Hello from the code snippet in openai docs'" ] ) # Execute the function calls result = composio.provider.handle_tool_calls(response=response, user_id=user_id) print(result) ``` **TypeScript:** ```typescript import OpenAI from 'openai'; import { Composio } from '@composio/core'; import { OpenAIResponsesProvider } from '@composio/openai'; // Initialize Composio client with OpenAI Provider const composio = new Composio({ provider: new OpenAIResponsesProvider(), }); const openai = new OpenAI({}); // Make sure to create an auth config and a connected account for the user with gmail toolkit // Make sure to replace "your-user-id" with the actual user ID const userId = "your-user-id"; async function main() { try { const tools = await composio.tools.get(userId, {tools: ["GMAIL_SEND_EMAIL"]}); const response = await openai.responses.create({ model: "gpt-5", tools: tools, input: [ role: "user", content: "Send an email to soham.g@composio.dev with the subject 'Running OpenAI Provider snippet' and body 'Hello from the code snippet in openai docs'" }, ], }); // Execute the function calls const result = await composio.provider.handleToolCalls(userId, response.output); console.log(result); } catch (error) { console.error('Error:', error); main(); ``` # Chat Completion API The Chat Completion API generates a model response from a list of messages. Read more about it in the [OpenAI documentation](https://platform.openai.com/docs/api-reference/chat). The OpenAI Chat Provider is the default provider used by Composio SDK, but you can also explicitly initialise it. > Before executing any tools that require authentication (like Gmail), you'll need to: 1. [Create an Auth Configuration](/docs/authenticating-tools#creating-an-auth-config) for your app 2. [Set up a Connected Account](/docs/authenticating-tools#connecting-an-account) for the user. **Python:** ```python from openai import OpenAI from composio import Composio from composio_openai import OpenAIProvider # Initialize Composio client with OpenAI Provider composio = Composio(provider=OpenAIProvider()) openai = OpenAI() # Make sure to create an auth config and a connected account for the user with gmail toolkit # Make sure to replace "your-user-id" with the actual user ID user_id = "your-user-id" tools = composio.tools.get(user_id=user_id, tools=["GMAIL_SEND_EMAIL"]) response = openai.chat.completions.create( model="gpt-5", tools=tools, messages=[ {"role": "user", "content": "Send an email to soham.g@composio.dev with the subject 'Running OpenAI Provider snippet' and body 'Hello from the code snippet in openai docs'"}, ], ) # Execute the function calls result = composio.provider.handle_tool_calls(response=response, user_id=user_id) print(result) ``` **TypeScript:** ```typescript import OpenAI from 'openai'; import { Composio } from '@composio/core'; import { OpenAIProvider } from '@composio/openai'; // Initialize Composio client with OpenAI Provider const composio = new Composio({ provider: new OpenAIProvider(), }); const openai = new OpenAI(); // Make sure to create an auth config and a connected account for the user with gmail toolkit // Make sure to replace "your-user-id" with the actual user ID const userId = "your-user-id"; async function main() { try { const tools = await composio.tools.get(userId, {tools: ["GMAIL_SEND_EMAIL"]}); const response = await openai.chat.completions.create({ model: "gpt-5", tools: tools, messages: [ role: "user", content: "Send an email to soham.g@composio.dev with the subject 'Running OpenAI Provider snippet' and body 'Hello from the code snippet in openai docs'" }, ], }); // Execute the function calls const result = await composio.provider.handleToolCalls(userId, response); console.log(result); } catch (error) { console.error('Error:', error); main(); ``` --- # Google Gen AI (/docs/providers/google) The Google provider transforms Composio tools into a format compatible with Gemini's function calling capabilities through it's API # Setup **Python:** ```bash pip install google-genai composio_google ``` **TypeScript:** ```bash npm install @google/genai npm i @composio/core @composio/gemini ``` **Python:** ```python from composio import Composio from composio_gemini import GeminiProvider from google import genai from google.genai import types # Create composio client composio = Composio(provider=GeminiProvider()) # Create google client client = genai.Client() ``` **TypeScript:** ```typescript import {Composio} from '@composio/core'; import {GoogleProvider} from '@composio/google' import {GoogleGenAI} from '@google/genai' const composio = new Composio({ apiKey: "your-composio-api-key", provider: new GoogleProvider() }) const ai = new GoogleGenAI({ apiKey: "your-gemini-api-key" }) ``` # Usage **Python:** ```python user_id = "0000-1111-2222" tools = composio.tools.get(user_id, tools=["COMPOSIO_SEARCH_DUCK_DUCK_GO_SEARCH"]) # Create genai client config config = types.GenerateContentConfig(tools=tools) # Use the chat interface. chat = client.chats.create(model="gemini-2.0-flash", config=config) response = chat.send_message("search about the latest info on windsurf acquisition.") print(response.text) ``` **TypeScript:** ```typescript import {Composio} from '@composio/core'; import {GoogleProvider} from '@composio/google' import {GoogleGenAI} from '@google/genai' const composio = new Composio({ apiKey: "key", provider: new GoogleProvider() }); const ai = new GoogleGenAI({ apiKey: "key" }); // ---cut--- // Use a unique identifier for each user in your application const user_id = "your-external-user-id" // Get tools - this returns already wrapped tools when using GoogleProvider const tools = await composio.tools.get(user_id, 'HACKERNEWS_GET_USER') const response = await ai.models.generateContent({ model: 'gemini-2.0-flash-001', contents: "Search for the user 'pg's", config: { tools: [{ functionDeclarations: tools }], }, }); if (response.functionCalls && response.functionCalls.length > 0) { console.log(`Calling tool ${response.functionCalls[0].name}`); const functionCall = { name: response.functionCalls[0].name || '', args: response.functionCalls[0].args || {}, }; const result = await composio.provider.executeToolCall(user_id, functionCall); console.log(`Result: ${result}`); } else { console.log('No function calls in the response'); console.log(response.text); ``` --- # LlamaIndex (/docs/providers/llamaindex) The LlamaIndex Provider transforms Composio tools into a format compatible with LlamaIndex's function calling capabilities. # Setup **Python:** ```bash pip install composio_llamaindex==0.8.0 llama-index ``` **TypeScript:** ```bash npm install @composio/llamaindex @llamaindex/openai @llamaindex/workflow ``` # Usage **Python:** ```python import asyncio import dotenv from composio_llamaindex import LlamaIndexProvider from llama_index.core.agent.workflow import FunctionAgent from llama_index.llms.openai import OpenAI from composio import Composio # Load environment variables from .env dotenv.load_dotenv() # Setup client llm = OpenAI(model="gpt-5") composio = Composio(provider=LlamaIndexProvider()) tools = composio.tools.get( user_id="user@acme.com", tools=["GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER"], ) workflow = FunctionAgent( tools=tools, llm=llm, system_prompt="You are an agent that performs github actions.", ) async def main(): result = await workflow.run( user_msg="Hello! I would like to star a repo composiohq/composio on GitHub" ) print(result) if __name__ == "__main__": asyncio.run(main()) ``` **TypeScript:** ```typescript import { Composio } from '@composio/core'; import { LlamaindexProvider } from '@composio/llamaindex'; import { openai } from '@llamaindex/openai'; import { agent } from '@llamaindex/workflow'; import 'dotenv/config'; // Initialize Composio with LlamaIndex provider const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY, provider: new LlamaindexProvider(), }); async function main() { // Get tools const tools = await composio.tools.get('user@acme.com', { tools: ['GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER'], }); // Create LlamaIndex agent with Composio tools const githubAgent = agent({ name: 'GitHub Agent', description: 'An agent that performs GitHub actions', llm: openai({ model: 'gpt-4o-mini' }), systemPrompt: 'You are an agent that performs github actions.', tools, }); // Run the agent const result = await githubAgent.run( 'Hello! I would like to star a repo composiohq/composio on GitHub' ); console.log(result); main().catch(console.error); ``` # Advanced Usage ## Streaming Agent with Multiple Toolkits ```typescript import { Composio } from '@composio/core'; import { LlamaindexProvider } from '@composio/llamaindex'; import { openai } from '@llamaindex/openai'; import { agent, agentStreamEvent } from '@llamaindex/workflow'; import 'dotenv/config'; const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY, provider: new LlamaindexProvider(), }); async function streamingExample() { // Get tools from multiple toolkits with execution modifiers const tools = await composio.tools.get( 'default', toolkits: ['gmail', 'googlecalendar', 'slack'], limit: 20, }, beforeExecute: ({ toolSlug, params }) => { console.log(`šŸ”„ Executing ${toolSlug} with:`, params); return params; }, afterExecute: ({ toolSlug, result }) => { console.log(`āœ… ${toolSlug} completed:`, result); return result; }, ); // Create streaming agent const assistantAgent = agent({ name: 'Personal Assistant', description: 'A helpful personal assistant', llm: openai({ model: 'gpt-4o-mini' }), systemPrompt: 'You are a helpful personal assistant that can manage emails, calendar events, and slack messages.', tools, }); // Stream the response const stream = await assistantAgent.runStream( 'Schedule a meeting for tomorrow at 2 PM and send a slack message about it' ); for await (const event of stream) { if (agentStreamEvent.include(event)) { process.stdout.write(event.data.delta); streamingExample().catch(console.error); ``` --- # CrewAI (/docs/providers/crewai) The CrewAI Provider formats the Composio tools into an object compatible with CrewAI's tool calling capabilities. Agents and LLM workflows built with this can call and execute the Composio tools. # Setup The CrewAI provider is available for only the Python SDK. ```bash pip install composio_crewai==0.8.0 ``` # Usage ```python from crewai import Agent, Crew, Task from langchain_openai import ChatOpenAI from composio import Composio from composio_crewai import CrewAIProvider # Initialize tools. openai_client = ChatOpenAI() composio = Composio(provider=CrewAIProvider()) # Get All the tools tools = composio.tools.get(user_id="default", toolkits=["GITHUB"]) # Define agent crewai_agent = Agent( role="Github Agent", goal="""You take action on Github using Github APIs""", backstory=( "You are AI agent that is responsible for taking actions on Github " "on users' behalf. You need to take action on Github using Github APIs" ), verbose=True, tools=tools, llm=openai_client, ) # Define task task = Task( description=( "Star a repo composiohq/composio on GitHub, if the action is successful " "include Action executed successfully" ), agent=crewai_agent, expected_output="if the star happened", ) my_crew = Crew(agents=[crewai_agent], tasks=[task]) result = my_crew.kickoff() print(result) ``` --- # Custom Providers (/docs/providers/custom-providers) Providers transform Composio tools into the format your AI framework expects. If your framework isn't listed in our supported providers, you can build your own. } /> } /> --- # Users & Sessions (/docs/users-and-sessions) When building AI agents for multiple users, each user needs their own connections and context. This is represented through **users** and **sessions**. # Users A user is an identifier from your app. When someone connects their Gmail or GitHub, that connection is stored under their user ID, so tools always run with the right authentication. Every tool execution and authorization uses the user ID to identify the context. Connections are fully isolated between user IDs. **Best practices for User IDs** * **Recommended:** Database UUID or primary key (`user.id`) * **Acceptable:** Unique username (`user.username`) * **Avoid:** Email addresses (they can change) * **Never:** `default` in production (exposes other users' data) A user can have multiple connections to the same toolkit. Let's say you want to allow users to connect both their work and personal email. You can represent the user with the same user ID but differentiate between the two with the connected account ID. Here is a detailed guide on how to manage such connections: - [Managing Multiple Connections](/docs/managing-multiple-connected-accounts): Handle multiple accounts per toolkit for a single user # Sessions A session is an ephemeral configuration. You specify: * Which user's authorization and data the agent will access * What toolkits are enabled or disabled * What authentication method, scopes, and credentials to use ## Creating a session **Python:** ```python session = composio.create(user_id="user_123") ``` **TypeScript:** ```typescript import { Composio } from '@composio/core'; const composio = new Composio({ apiKey: 'your_api_key' }); // ---cut--- const session = await composio.create("user_123"); ``` ## Session methods Once created, a session provides methods to get tools and manage connections: **Python:** ```python # Get tools for your AI framework tools = session.tools() # Get MCP server URL mcp_url = session.mcp.url # Authenticate a user to a toolkit connection_request = session.authorize("github") # List available toolkits and their connection status toolkits = session.toolkits() ``` **TypeScript:** ```typescript import { Composio } from '@composio/core'; const composio = new Composio({ apiKey: 'your_api_key' }); const session = await composio.create("user_123"); // ---cut--- // Get tools for your AI framework const tools = await session.tools(); // Get MCP server URL const mcpUrl = session.mcp.url; // Authenticate a user to a toolkit const connectionRequest = await session.authorize("github"); // List available toolkits and their connection status const toolkits = await session.toolkits(); ``` For details on enabling toolkits, setting auth configs, and using session methods: - [Configuring Sessions](/docs/configuring-sessions): Enable toolkits, set auth configs, and select connected accounts --- # Authentication (/docs/authentication) Composio simplifies authentication with Connect Links: hosted pages where users securely connect their accounts.