Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
TypeScript agentic-aiagentsaiai-agentsaiagentsdeveloper-toolsfunction-callinggpt-4javascriptjsllmllmopsmcppythonremote-mcp-serverssetypescript
docs: restructure Users & Sessions, flatten guides, add Configuring Sessions
Sushmithamalleshade05f2060ba
diff --git a/docs/content/docs/configuring-sessions.mdx b/docs/content/docs/configuring-sessions.mdxnew file mode 100644index 000000000..9bceab526--- /dev/null+++ b/docs/content/docs/configuring-sessions.mdx@@ -0,0 +1,162 @@+---+title: Configuring Sessions+description: Enable toolkits, set auth configs, and select connected accounts+keywords: [session, toolkits, auth configs, connected accounts]+---++## Creating a session++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(user_id="user_123")+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123");+```+</Tab>+</Tabs>++## Enabling toolkits++Restrict the session to specific toolkits:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+# Using array format+session = composio.create(+ user_id="user_123",+ toolkits=["github", "gmail", "slack"]+)++# Using object format with enable key+session = composio.create(+ user_id="user_123",+ toolkits={"enable": ["github", "gmail", "slack"]}+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+// Using array format+const session = await composio.create("user_123", {+ toolkits: ["github", "gmail", "slack"],+});++// Using object format with enable key+const session2 = await composio.create("user_123", {+ toolkits: { enable: ["github", "gmail", "slack"] },+});+```+</Tab>+</Tabs>++## Disabling toolkits++Keep all toolkits enabled except specific ones:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(+ user_id="user_123",+ toolkits={"disable": ["exa", "firecrawl"]}+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123", {+ toolkits: { disable: ["exa", "firecrawl"] },+});+```+</Tab>+</Tabs>++## Custom auth configs++Use your own OAuth credentials instead of Composio's defaults:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(+ user_id="user_123",+ auth_configs={+ "github": "ac_your_github_config",+ "slack": "ac_your_slack_config"+ }+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123", {+ authConfigs: {+ github: "ac_your_github_config",+ slack: "ac_your_slack_config",+ },+});+```+</Tab>+</Tabs>++See [White-labeling authentication](/docs/guides/white-labeling-authentication) for branding, or [Using custom auth configs](/docs/guides/using-custom-auth-configuration) for toolkits that require your own credentials.++## Account selection++If a user has multiple connected accounts for the same toolkit, you can specify which one to use:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(+ user_id="user_123",+ connected_accounts={+ "gmail": "ca_work_gmail",+ "github": "ca_personal_github"+ }+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123", {+ connectedAccounts: {+ gmail: "ca_work_gmail",+ github: "ca_personal_github",+ },+});+```+</Tab>+</Tabs>++### Precedence++When executing a tool, the connected account is selected in this order:++1. `connectedAccounts` override if provided in session config+2. `authConfigs` override - finds or creates connection on that config+3. Auth config previously created for this toolkit+4. Creates new auth config using Composio managed auth+5. Error if no Composio managed auth scheme exists for the toolkit++If a user has multiple connected accounts for a toolkit, the most recently connected one is used.diff --git a/docs/content/docs/guides/multitenancy.mdx b/docs/content/docs/guides/multitenancy.mdxdeleted file mode 100644index 06c537946..000000000--- a/docs/content/docs/guides/multitenancy.mdx+++ /dev/null@@ -1,5 +0,0 @@-----title: Multitenancy-description: Build multi-tenant applications with Composio-----diff --git a/docs/content/docs/guides/managing-multiple-connected-accounts.mdx b/docs/content/docs/managing-multiple-connected-accounts.mdxsimilarity index 100%rename from docs/content/docs/guides/managing-multiple-connected-accounts.mdxrename to docs/content/docs/managing-multiple-connected-accounts.mdxdiff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex d3405aa78..81d8dde3b 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -6,17 +6,18 @@"quickstart-tool-router","providers","---Core Concepts---",+ "users-and-sessions-temporary","users-and-sessions","authentication","tools-and-toolkits","---Getting Started---",+ "configuring-sessions","authenticating-users","toolkits","---Guides---",- "guides/white-labeling-authentication",- "guides/managing-multiple-connected-accounts",- "guides/using-custom-auth-configuration",- "guides/multitenancy",+ "white-labeling-authentication",+ "managing-multiple-connected-accounts",+ "using-custom-auth-configuration","---Tools---","fetching-tools","authenticating-tools",@@ -29,7 +30,6 @@"programmatic-auth-configs","custom-auth-params","connected-accounts",- "user-management","---Features---","triggers","cli",diff --git a/docs/content/docs/providers/anthropic.mdx b/docs/content/docs/providers/anthropic.mdxindex 69a2a17a2..0182d9c75 100644--- a/docs/content/docs/providers/anthropic.mdx+++ b/docs/content/docs/providers/anthropic.mdx@@ -4,261 +4,422 @@ description: Use Composio tools with Claudekeywords: [claude]----The Anthropic Provider transforms Composio tools into a format compatible with Anthropic's function calling capabilities through its Messages API.+## Claude Agents SDK-## Usage with MCP+<ToolTypeFlow>-Use Composio Tool Router with the Claude Agent SDK for a fully managed MCP experience.--### Installation+<ToolTypeOption id="native" name="Native Tools" icon="native">+<Steps>+<Step>+**Install**<Tabs groupId="language" items={['Python', 'TypeScript']} persist><Tab value="Python">```bash-pip install python-dotenv composio claude-agent-sdk+pip install composio composio-claude-agent-sdk claude-agent-sdk```</Tab><Tab value="TypeScript">```bash-npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk+npm install dotenv @composio/core @composio/claude-agent-sdk @anthropic-ai/claude-agent-sdk```</Tab></Tabs>+</Step>-### Usage--Create a Tool Router session and execute tasks with Claude:+<Step>+**Configure API Keys**<Callout type="info">-- Set your `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).-- Set your `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://platform.claude.com/settings/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).</Callout>+```txt title=".env"+COMPOSIO_API_KEY=xxxxxxxxx+ANTHROPIC_API_KEY=xxxxxxxxx+```+</Step>++<Step>+**Create session and run agent**+<Tabs groupId="language" items={['Python', 'TypeScript']} persist><Tab value="Python">```pythonimport asynciofrom dotenv import load_dotenv-from claude_agent_sdk.client import ClaudeSDKClient-from claude_agent_sdk.types import (- ClaudeAgentOptions,- AssistantMessage,- TextBlock,- ToolUseBlock,-)+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 = "[email protected]"++# 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())+```+</Tab>+<Tab value="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 = "[email protected]";++// 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");+```+</Tab>+</Tabs>+</Step>+</Steps>+</ToolTypeOption>++<ToolTypeOption id="mcp" name="MCP" icon="mcp">+<Steps>+<Step>+**Install**++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```bash+pip install composio claude-agent-sdk+```+</Tab>+<Tab value="TypeScript">+```bash+npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk+```+</Tab>+</Tabs>+</Step>++<Step>+**Configure API Keys**++<Callout type="info">+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).+</Callout>++```txt title=".env"+COMPOSIO_API_KEY=xxxxxxxxx+ANTHROPIC_API_KEY=xxxxxxxxx+```+</Step>+<Step>+**Create session and run agent**++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+import asyncio+from dotenv import load_dotenvload_dotenv()-# Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly)+from composio import Composio+from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions++# Initialize Composiocomposio = Composio()-# Unique identifier of the user-user_id = "user_123"-# Create a tool router session for the user-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, # Authentication headers for the Composio MCP server- }- },- permission_mode="bypassPermissions", # Auto-approve tools (demo only)-)+external_user_id = "user_2nFh83Hde"+recipient_email = "[email protected]"++# Create a session+session = composio.create(user_id=external_user_id)+# Run the agentasync 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("\nYou: ").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)- except Exception as e:- print(f"\n[Error]: {e}")--if __name__ == "__main__":- asyncio.run(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())```</Tab><Tab value="TypeScript">```typescriptimport "dotenv/config";-import { query, type Options } from "@anthropic-ai/claude-agent-sdk";import { Composio } from "@composio/core";-import { createInterface } from "readline/promises";+import { query } from "@anthropic-ai/claude-agent-sdk";-// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })+// Initialize Composioconst composio = new Composio();-// Unique identifier of the user-const userId = "user_123";--// Create a tool router session for the user-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 // Authentication headers for the Composio MCP server+const externalUserId = "user_2nFh83Hde";+const recipientEmail = "[email protected]";++// 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",},- permissionMode: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)-};--// Set up interactive terminal input/output for the conversation-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 notion page 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: ");-- const queryOptions = isFirstQuery ? options : { ...options, continue: true };- isFirstQuery = false;-- try {- for await (const stream of query({ prompt: input, options: queryOptions })) {- // Only process assistant messages (the SDK also sends result/error messages)- 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);+})) {+ if (content.type === "assistant") {+ console.log("Claude:", content.message);}- process.stdout.write("\n");}-readline.close();+console.log("Received response from Claude");```</Tab></Tabs>+</Step>+</Steps>+</ToolTypeOption>-## Usage with direct tools+</ToolTypeFlow>-### Setup+## Anthropic API-<Tabs items={["Python", "TypeScript"]}>+<Steps>+<Step>+**Install**++<Tabs groupId="language" items={['Python', 'TypeScript']} persist><Tab value="Python">```bash-pip install composio composio-anthropic+pip install composio composio-anthropic anthropic```</Tab><Tab value="TypeScript">```bash-npm install @composio/anthropic @anthropic-ai/sdk+npm install dotenv @composio/core @composio/anthropic @anthropic-ai/sdk```</Tab></Tabs>+</Step>-You can specify the provider in the constructor. The constructor also takes in an optional `cacheTools` parameter.+<Step>+**Configure API Keys**-<Tabs items={["Python", "TypeScript"]}>+<Callout type="info">+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).+</Callout>++```txt title=".env"+COMPOSIO_API_KEY=xxxxxxxxx+ANTHROPIC_API_KEY=xxxxxxxxx+```+</Step>++<Step>+**Create session and run agent**++<Tabs groupId="language" items={['Python', 'TypeScript']} persist><Tab value="Python">```pythonimport anthropic+from dotenv import load_dotenv+load_dotenv()from composio import Composiofrom composio_anthropic import AnthropicProvider-# Initialize tools.+# Initialize Composio with Anthropic provideranthropic_client = anthropic.Anthropic()composio = Composio(provider=AnthropicProvider())++external_user_id = "user_2nFh83Hde"+recipient_email = "[email protected]"++# 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)```</Tab><Tab value="TypeScript">```typescript+import "dotenv/config";import { Composio } from "@composio/core";import { AnthropicProvider } from "@composio/anthropic";-import Anthropic from '@anthropic-ai/sdk';+import Anthropic from "@anthropic-ai/sdk";+// Initialize Composio with Anthropic providerconst composio = new Composio({- provider: new AnthropicProvider({- cacheTools: false, // default- }),+ provider: new AnthropicProvider(),});-const anthropic = new Anthropic();++const externalUserId = "user_2nFh83Hde";+const recipientEmail = "[email protected]";++// 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);+```+</Tab>+</Tabs>+</Step>+</Steps>++<Accordions>+<Accordion title="Direct tool usage">+<Callout type="info">+Only use this if you want to use a single, direct tool with your AI Agent.+</Callout>++**Install**++<Tabs items={["Python", "TypeScript"]}>+<Tab value="Python">+```bash+pip install composio composio-anthropic anthropic+```+</Tab>+<Tab value="TypeScript">+```bash+npm install @composio/core @composio/anthropic @anthropic-ai/sdk```</Tab></Tabs>-### Usage+**Usage**<Tabs items={["Python", "TypeScript"]}><Tab value="Python">```python-# Define your user ID-user_id = "your-user-id"+import anthropic+from composio import Composio+from composio_anthropic import AnthropicProvider-# Get GitHub tool for listing stargazers-tools = composio.tools.get(user_id=user_id, tools=["GITHUB_LIST_STARGAZERS"])+anthropic_client = anthropic.Anthropic()+composio = Composio(provider=AnthropicProvider())++external_user_id = "user_2nFh83Hde"+recipient_email = "[email protected]"++# Get a specific tool+tools = composio.tools.get(user_id=external_user_id, tools=["GMAIL_SEND_EMAIL"])-# Get response from the LLMresponse = anthropic_client.messages.create(model="claude-sonnet-4-5",max_tokens=1024,tools=tools,messages=[- {"role": "user", "content": "List my github stargazers. for the repo composiohq/composio"},+ {"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=user_id, response=response)+result = composio.provider.handle_tool_calls(user_id=external_user_id, response=response)print(result)```</Tab>@@ -266,30 +427,37 @@ print(result)```typescriptimport { Composio } from "@composio/core";import { AnthropicProvider } from "@composio/anthropic";-import Anthropic from '@anthropic-ai/sdk';-const composio = new Composio({ provider: new AnthropicProvider() });+import Anthropic from "@anthropic-ai/sdk";++const composio = new Composio({+ provider: new AnthropicProvider(),+});const anthropic = new Anthropic();-// ---cut----const userId = "your-user-id";-const tools = await composio.tools.get(userId, {- tools: ["GITHUB_LIST_STARGAZERS"]-})++const externalUserId = "user_2nFh83Hde";+const recipientEmail = "[email protected]";++// 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: "List my github stargazers. for the repo composiohq/composio",+ 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 res = await composio.provider.handleToolCalls(userId, msg);--console.log(res[0].content);+const result = await composio.provider.handleToolCalls(externalUserId, msg);+console.log(result);```</Tab></Tabs>+</Accordion>+</Accordions>diff --git a/docs/content/docs/user-management.mdx b/docs/content/docs/user-management.mdxdeleted file mode 100644index 3dde2c249..000000000--- a/docs/content/docs/user-management.mdx+++ /dev/null@@ -1,142 +0,0 @@-----title: User Management-description: Manage users and their connected accounts-keywords: [user id, multi-user]------## What are User IDs?--User IDs determine whose connected accounts and data you're accessing in Composio. Every tool execution, connection authorization, and account operation requires a `userId` parameter that identifies which context to use.--User IDs act as containers that group connected accounts together across toolkits. Each user connects and manages their own accounts.--## Choosing User IDs--**Recommended:** Database UUID or primary key (`user.id`)--**Acceptable:** Unique username (`user.username`)--**Avoid:** Email addresses (emails can change)--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>- <Tab value="Python">-```python-# Use your database's user ID (UUID, primary key, etc.)-user_id = user.id; # e.g., "550e8400-e29b-41d4-a716-446655440000"--tools = composio.tools.get(- user_id=user_id,- toolkits=["GITHUB"],-)--result = composio.tools.execute(- "GITHUB_GET_REPO",- user_id=user_id,- arguments={- "owner": 'example',- "repo": 'repo'- }-)-```- </Tab>- <Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-declare const user: { id: string };-// ---cut----// Use your database's user ID (UUID, primary key, etc.)-const userId = user.id; // e.g., "550e8400-e29b-41d4-a716-446655440000"--const tools = await composio.tools.get(userId, {- toolkits: ['github'],-});--const result = await composio.tools.execute('GITHUB_GET_REPO', {- userId: userId,- arguments: { owner: 'example', repo: 'repo' },-});-```- </Tab>-</Tabs>--<Callout type="warn">-Never use 'default' as a User ID in production with users. This could expose other users' data.-</Callout>--## Multiple Connected Accounts--A single User ID can have multiple connected accounts for the same toolkit. For example, a user might connect both their personal and work Gmail accounts.--**Key concepts:**-- Each connected account gets a unique Connected Account ID-- Multiple accounts can exist under the same User ID for any toolkit-- You can specify which account to use when executing tools--**Account selection:**-- **Explicit:** Specify the Connected Account ID to target a specific account-- **Default:** If no Connected Account ID is provided, the most recently connected account is used--## Example: Multi-User Application--In applications with multiple users, each user connects and manages their own accounts. Every user goes through their own OAuth flow and their data remains completely isolated.--**Key concepts:**-- Each user authorizes their own accounts using their unique user ID-- Connections are isolated - users can only access their own connected accounts-- No permission checks needed since users only access their own data--```typescript-declare const app: { get: (path: string, handler: (req: any, res: any) => Promise<any>) => void };-// ---cut----import { Composio } from '@composio/core';-const composio = new Composio({- apiKey: process.env.COMPOSIO_API_KEY,-});--// 1. User initiates GitHub connection-async function connectUserToGitHub(userId: string) {- const connectionRequest = await composio.toolkits.authorize(userId, 'github');- return connectionRequest.redirectUrl;-}--// 2. Get user's connected GitHub tools-async function getUserGitHubTools(userId: string) {- return await composio.tools.get(userId, {- toolkits: ['github'],- });-}--// 3. Execute tool for specific user-async function getUserRepos(userId: string) {- return await composio.tools.execute('GITHUB_LIST_REPOS', {- userId: userId,- arguments: {- per_page: 10,- },- });-}--// Usage in your API endpoint-app.get('/api/github/repos', async (req, res) => {- const userId = req.user.id; // Get from your auth system-- try {- const repos = await getUserRepos(userId);- res.json(repos.data);- } catch (error) {- res.status(500).json({ error: 'Failed to fetch repos' });- }-});-```--**Data isolation**: Composio ensures each userId's connections and data are completely separate. User A can never access User B's repositories.--## Best Practices--- Pass the correct User ID for each user-- Never use 'default' in production with multiple users-- Keep User IDs consistent across your application and Composio-- Use stable identifiers that won't change over time--**Data isolation:** Composio ensures complete isolation between User IDs. Users cannot access another ID's connections or data.diff --git a/docs/content/docs/users-and-sessions-temporary.mdx b/docs/content/docs/users-and-sessions-temporary.mdxnew file mode 100644index 000000000..b7880a76d--- /dev/null+++ b/docs/content/docs/users-and-sessions-temporary.mdx@@ -0,0 +1,286 @@+---+title: Users & Sessions Temporary+description: Understand how Tool Router scopes tools and connections per user+keywords: [session, user id, enable toolkits, disable toolkits]+---++A **user ID** is an identifier from your system (database ID, UUID, or any unique string) that scopes connected accounts and tool access to a specific user. See [User Management](/docs/user-management) for best practices.++A **session** is an ephemeral configuration that combines:+- Which user's connected accounts to use+- Which toolkits are available+- Which auth configs to use++Tool Router's meta-tools are the same for everyone. The session determines the context they operate within.++## Creating a session++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(user_id="user_123")+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123");+```+</Tab>+</Tabs>++### Enabling toolkits++Restrict the session to specific toolkits:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+# Using array format+session = composio.create(+ user_id="user_123",+ toolkits=["github", "gmail", "slack"]+)++# Using object format with enable key+session = composio.create(+ user_id="user_123",+ toolkits={"enable": ["github", "gmail", "slack"]}+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+// Using array format+const session = await composio.create("user_123", {+ toolkits: ["github", "gmail", "slack"],+});++// Using object format with enable key+const session2 = await composio.create("user_123", {+ toolkits: { enable: ["github", "gmail", "slack"] },+});+```+</Tab>+</Tabs>++### Disabling toolkits++Keep all toolkits enabled except specific ones:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(+ user_id="user_123",+ toolkits={"disable": ["exa", "firecrawl"]}+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123", {+ toolkits: { disable: ["exa", "firecrawl"] },+});+```+</Tab>+</Tabs>++### Custom auth configs++Use your own OAuth credentials instead of Composio's defaults:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(+ user_id="user_123",+ auth_configs={+ "github": "ac_your_github_config",+ "slack": "ac_your_slack_config"+ }+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123", {+ authConfigs: {+ github: "ac_your_github_config",+ slack: "ac_your_slack_config",+ },+});+```+</Tab>+</Tabs>++See [White-labeling authentication](/docs/guides/white-labeling-authentication) for branding, or [Using custom auth configs](/docs/guides/using-custom-auth-configuration) for toolkits that require your own credentials.++## Connected accounts++Connected accounts are stored in Composio and persist across sessions. When a user connects their GitHub account in one session, it remains available in future sessions. Sessions configure *which* connections to use, but don't own the connections themselves.++### Account selection++If a user has multiple connected accounts for the same toolkit, you can specify which one to use:++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+session = composio.create(+ user_id="user_123",+ connected_accounts={+ "gmail": "ca_work_gmail",+ "github": "ca_personal_github"+ }+)+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+// ---cut---+const session = await composio.create("user_123", {+ connectedAccounts: {+ gmail: "ca_work_gmail",+ github: "ca_personal_github",+ },+});+```+</Tab>+</Tabs>++### Precedence++When executing a tool, Tool Router selects the connected account in this order:++1. `connectedAccounts` override if provided in session config+2. `authConfigs` override - finds or creates connection on that config+3. Auth config previously created by Tool Router for this toolkit+4. Creates new auth config using Composio managed auth (tagged as Tool Router created)+5. Error if no Composio managed auth scheme exists for the toolkit++If a user has multiple connected accounts for a toolkit, the most recently connected one is used.++## Session methods++### mcp++Get the MCP server URL to use with any MCP-compatible client.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+mcp_url = session.mcp.url+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+const session = await composio.create("user_123");+// ---cut---+const { mcp } = session;+console.log(mcp.url);+```+</Tab>+</Tabs>++For framework examples, see provider-specific documentation like [OpenAI Agents](/docs/providers/openai-agents) or [Vercel AI SDK](/docs/providers/vercel).++### tools()++Get native tools from the session for use with AI frameworks.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+tools = session.tools()+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+const session = await composio.create("user_123");+// ---cut---+const tools = await session.tools();+```+</Tab>+</Tabs>++### authorize()++Manually authenticate a user to a toolkit outside of the chat flow.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+connection_request = session.authorize("github")++print(connection_request.redirect_url)++connected_account = connection_request.wait_for_connection()+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+const session = await composio.create("user_123");+// ---cut---+const connectionRequest = await session.authorize("github", {+ callbackUrl: "https://myapp.com/callback",+});++console.log(connectionRequest.redirectUrl);++const connectedAccount = await connectionRequest.waitForConnection();+```+</Tab>+</Tabs>++For more details, see [Manually authenticating users](/docs/authenticating-users/manually-authenticating).++### toolkits()++List available toolkits and their connection status. You can use this to build a UI showing which apps are connected.++<Tabs groupId="language" items={['Python', 'TypeScript']} persist>+<Tab value="Python">+```python+toolkits = session.toolkits()++for toolkit in toolkits.items:+ status = toolkit.connection.connected_account.id if toolkit.connection.is_active else "Not connected"+ print(f"{toolkit.name}: {status}")+```+</Tab>+<Tab value="TypeScript">+```typescript+import { Composio } from '@composio/core';+const composio = new Composio({ apiKey: 'your_api_key' });+const session = await composio.create("user_123");+// ---cut---+const toolkits = await session.toolkits();++toolkits.items.forEach((toolkit) => {+ console.log(`${toolkit.name}: ${toolkit.connection?.connectedAccount?.id ?? "Not connected"}`);+});+```+</Tab>+</Tabs>++Returns the first 20 toolkits by default.diff --git a/docs/content/docs/users-and-sessions.mdx b/docs/content/docs/users-and-sessions.mdxindex 3851d001f..70517f1e3 100644--- a/docs/content/docs/users-and-sessions.mdx+++ b/docs/content/docs/users-and-sessions.mdx@@ -1,286 +1,58 @@----title: Users and sessions-description: Understand how Tool Router scopes tools and connections per user-keywords: [session, user id, enable toolkits, disable toolkits]+title: Users & Sessions+description: How Composio scopes tools and connections to your users+keywords: [session, user id, concepts]----A **user ID** is an identifier from your system (database ID, UUID, or any unique string) that scopes connected accounts and tool access to a specific user. See [User Management](/docs/user-management) for best practices.+When building AI agents for multiple users, each user needs their own connections and context. This is represented through **users** and **sessions**.-A **session** is an ephemeral configuration that combines:-- Which user's connected accounts to use-- Which toolkits are available-- Which auth configs to use+## Users-Tool Router's meta-tools are the same for everyone. The session determines the context they operate within.+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.-## Creating a session+<Accordions>+<Accordion title="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)+</Accordion>+</Accordions>-<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-session = composio.create(user_id="user_123")-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-// ---cut----const session = await composio.create("user_123");-```-</Tab>-</Tabs>--### Enabling toolkits--Restrict the session to specific toolkits:--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-# Using array format-session = composio.create(- user_id="user_123",- toolkits=["github", "gmail", "slack"]-)--# Using object format with enable key-session = composio.create(- user_id="user_123",- toolkits={"enable": ["github", "gmail", "slack"]}-)-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-// ---cut----// Using array format-const session = await composio.create("user_123", {- toolkits: ["github", "gmail", "slack"],-});--// Using object format with enable key-const session2 = await composio.create("user_123", {- toolkits: { enable: ["github", "gmail", "slack"] },-});-```-</Tab>-</Tabs>--### Disabling toolkits--Keep all toolkits enabled except specific ones:--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-session = composio.create(- user_id="user_123",- toolkits={"disable": ["exa", "firecrawl"]}-)-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-// ---cut----const session = await composio.create("user_123", {- toolkits: { disable: ["exa", "firecrawl"] },-});-```-</Tab>-</Tabs>--### Custom auth configs--Use your own OAuth credentials instead of Composio's defaults:--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-session = composio.create(- user_id="user_123",- auth_configs={- "github": "ac_your_github_config",- "slack": "ac_your_slack_config"- }-)-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-// ---cut----const session = await composio.create("user_123", {- authConfigs: {- github: "ac_your_github_config",- slack: "ac_your_slack_config",- },-});-```-</Tab>-</Tabs>--See [White-labeling authentication](/docs/guides/white-labeling-authentication) for branding, or [Using custom auth configs](/docs/guides/using-custom-auth-configuration) for toolkits that require your own credentials.--## Connected accounts--Connected accounts are stored in Composio and persist across sessions. When a user connects their GitHub account in one session, it remains available in future sessions. Sessions configure *which* connections to use, but don't own the connections themselves.--### Account selection--If a user has multiple connected accounts for the same toolkit, you can specify which one to use:--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-session = composio.create(- user_id="user_123",- connected_accounts={- "gmail": "ca_work_gmail",- "github": "ca_personal_github"- }-)-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-// ---cut----const session = await composio.create("user_123", {- connectedAccounts: {- gmail: "ca_work_gmail",- github: "ca_personal_github",- },-});-```-</Tab>-</Tabs>--### Precedence--When executing a tool, Tool Router selects the connected account in this order:+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.-1. `connectedAccounts` override if provided in session config-2. `authConfigs` override - finds or creates connection on that config-3. Auth config previously created by Tool Router for this toolkit-4. Creates new auth config using Composio managed auth (tagged as Tool Router created)-5. Error if no Composio managed auth scheme exists for the toolkit+Here is a detailed guide on how to manage such connections:+<Card title="Managing Multiple Connections" href="/docs/managing-multiple-connected-accounts" description="Handle multiple accounts per toolkit for a single user" />-If a user has multiple connected accounts for a toolkit, the most recently connected one is used.-## Session methods--### mcp--Get the MCP server URL to use with any MCP-compatible client.--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-mcp_url = session.mcp.url-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-const session = await composio.create("user_123");-// ---cut----const { mcp } = session;-console.log(mcp.url);-```-</Tab>-</Tabs>+## Sessions-For framework examples, see provider-specific documentation like [OpenAI Agents](/docs/providers/openai-agents) or [Vercel AI SDK](/docs/providers/vercel).+A session is an ephemeral configuration. You specify:-### tools()+- Which user's authorization and data the agent will access+- What toolkits are enabled or disabled+- What authentication method, scopes, and credentials to use-Get native tools from the session for use with AI frameworks.+### Creating a session<Tabs groupId="language" items={['Python', 'TypeScript']} persist><Tab value="Python">```python-tools = session.tools()+session = composio.create(user_id="user_123")```</Tab><Tab value="TypeScript">```typescriptimport { Composio } from '@composio/core';const composio = new Composio({ apiKey: 'your_api_key' });-const session = await composio.create("user_123");// ---cut----const tools = await session.tools();-```-</Tab>-</Tabs>--### authorize()--Manually authenticate a user to a toolkit outside of the chat flow.--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-connection_request = session.authorize("github")--print(connection_request.redirect_url)--connected_account = connection_request.wait_for_connection()-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });const session = await composio.create("user_123");-// ---cut----const connectionRequest = await session.authorize("github", {- callbackUrl: "https://myapp.com/callback",-});--console.log(connectionRequest.redirectUrl);--const connectedAccount = await connectionRequest.waitForConnection();```</Tab></Tabs>-For more details, see [Manually authenticating users](/docs/authenticating-users/manually-authenticating).--### toolkits()--List available toolkits and their connection status. You can use this to build a UI showing which apps are connected.--<Tabs groupId="language" items={['Python', 'TypeScript']} persist>-<Tab value="Python">-```python-toolkits = session.toolkits()--for toolkit in toolkits.items:- status = toolkit.connection.connected_account.id if toolkit.connection.is_active else "Not connected"- print(f"{toolkit.name}: {status}")-```-</Tab>-<Tab value="TypeScript">-```typescript-import { Composio } from '@composio/core';-const composio = new Composio({ apiKey: 'your_api_key' });-const session = await composio.create("user_123");-// ---cut----const toolkits = await session.toolkits();--toolkits.items.forEach((toolkit) => {- console.log(`${toolkit.name}: ${toolkit.connection?.connectedAccount?.id ?? "Not connected"}`);-});-```-</Tab>-</Tabs>+For details on enabling toolkits, setting auth configs, and selecting connected accounts:-Returns the first 20 toolkits by default.+<Card title="Configuring Sessions" href="/docs/configuring-sessions" description="Enable toolkits, set auth configs, and select connected accounts" />diff --git a/docs/content/docs/guides/using-custom-auth-configuration.mdx b/docs/content/docs/using-custom-auth-configuration.mdxsimilarity index 100%rename from docs/content/docs/guides/using-custom-auth-configuration.mdxrename to docs/content/docs/using-custom-auth-configuration.mdxdiff --git a/docs/content/docs/guides/white-labeling-authentication.mdx b/docs/content/docs/white-labeling-authentication.mdxsimilarity index 100%rename from docs/content/docs/guides/white-labeling-authentication.mdxrename to docs/content/docs/white-labeling-authentication.mdxdiff --git a/docs/next.config.mjs b/docs/next.config.mjsindex 7fd9716c2..94a1a5e5f 100644--- a/docs/next.config.mjs+++ b/docs/next.config.mjs@@ -84,22 +84,22 @@ const config = {},{source: '/tool-router/using-custom-auth-configs',- destination: '/docs/guides/using-custom-auth-configuration',+ destination: '/docs/using-custom-auth-configuration',permanent: true,},{source: '/docs/authenticating-users/using-custom-auth-configs',- destination: '/docs/guides/using-custom-auth-configuration',+ destination: '/docs/using-custom-auth-configuration',permanent: true,},{source: '/tool-router/white-labeling-authentication',- destination: '/docs/guides/white-labeling-authentication',+ destination: '/docs/white-labeling-authentication',permanent: true,},{source: '/tool-router/managing-multiple-accounts',- destination: '/docs/guides/managing-multiple-connected-accounts',+ destination: '/docs/managing-multiple-connected-accounts',permanent: true,},// Provider redirects (old fern URLs -> new docs URLs)@@ -176,6 +176,11 @@ const config = {},// Features section redirects{+ source: '/docs/user-management',+ destination: '/docs/users-and-sessions#users',+ permanent: true,+ },+ {source: '/docs/using-triggers',destination: '/docs/triggers',permanent: true,