@devries-cameron20 / composio-1 / commits / 88229dbd6
Fork 0

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

Docs: Python snippets fix tool router

Sushmithamallesh committed Dec 22, 2025 at 06:47 UTC 88229dbd6ef221b7b2c53c0046eb67097db6c50d
9 files changed +205 -178
fern/pages/src/tool-router/quickstart.mdx
+3 -3
@@ -18,7 +18,7 @@ Choose how you want to integrate Tool Router:
18 <Step title="Install">
19 <CodeGroup>
20 ```bash title="Python" for="python"
21 -pip install composio claude-agent-sdk
21 +pip install python-dotenv composio claude-agent-sdk
22 ```
23 ```bash title="TypeScript" for="typescript"
24 npm install @composio/core @anthropic-ai/claude-agent-sdk
@@ -52,7 +52,7 @@ When the agent needs authentication, it will prompt the user with a link to conn
52 <Step title="Install">
53 <CodeGroup>
54 ```bash title="Python" for="python"
55 -pip install composio openai-agents
55 +pip install python-dotenv composio openai-agents
56 ```
57 ```bash title="TypeScript" for="typescript"
58 npm install @composio/core @openai/agents
@@ -127,7 +127,7 @@ When you run this agent, Tool Router:
127 <Step title="Install">
128 <CodeGroup>
129 ```bash title="Python" for="python"
130 -pip install composio composio-openai-agents openai-agents
130 +pip install python-dotenv composio composio-openai-agents openai-agents
131 ```
132 ```bash title="TypeScript" for="typescript"
133 npm install @composio/core @composio/openai-agents @openai/agents
fern/pages/src/tool-router/using-as-a-native-tool.mdx
+1 -1
@@ -19,7 +19,7 @@ Jump to examples for:
19
20 <CodeGroup>
21 ```bash title="Python" for="python"
22 -pip install composio composio-openai-agents openai-agents
22 +pip install python-dotenv composio composio-openai-agents openai-agents
23 ```
24 ```bash title="TypeScript" for="typescript"
25 npm install @composio/core @composio/openai-agents @openai/agents
fern/pages/src/tool-router/using-with-mcp-clients.mdx
+6 -6
@@ -20,7 +20,7 @@ Jump to examples for:
20
21 <CodeGroup>
22 ```bash title="Python" for="python"
23 -pip install composio claude-agent-sdk
23 +pip install python-dotenv composio claude-agent-sdk
24 ```
25 ```bash title="TypeScript" for="typescript"
26 npm install @composio/core @anthropic-ai/claude-agent-sdk
@@ -47,7 +47,7 @@ Create a Tool Router session and execute tasks with Claude:
47
48 <CodeGroup>
49 ```bash title="Python" for="python"
50 -pip install composio openai-agents
50 +pip install python-dotenv composio openai-agents
51 ```
52 ```bash title="TypeScript" for="typescript"
53 npm install @composio/core @openai/agents
@@ -59,8 +59,8 @@ npm install @composio/core @openai/agents
59 Create a Tool Router session and execute tasks with OpenAI agents:
60
61 <Info>
62 -- Set your `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
63 -- Set your `OPENAI_API_KEY` environment variable with your [OpenAI API key](https://platform.openai.com/api-keys).
62 +- Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
63 +- Set `OPENAI_API_KEY` environment variable with your [OpenAI API key](https://platform.openai.com/api-keys).
64 </Info>
65
66 <CodeGroup>
@@ -81,8 +81,8 @@ npm install @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
81 Use Tool Router with Vercel AI SDK's `generateText` for single completions:
82
83 <Info>
84 -- Set your `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
85 -- Set your `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://platform.claude.com/settings/keys).
84 +- Set `COMPOSIO_API_KEY` environment variable with your API key from [Settings](https://platform.composio.dev/?next_page=/settings).
85 +- Set `ANTHROPIC_API_KEY` environment variable with your [Anthropic API key](https://platform.claude.com/settings/keys).
86 </Info>
87
88 <SnippetCode src="fern/snippets/tool-router/typescript/mcp-vercel.ts" />
\ No newline at end of file
fern/snippets/tool-router/python/mcp-claude.py
+45 -43
@@ -1,67 +1,69 @@
1 import asyncio
2 -import os
2 from dotenv import load_dotenv
3 from claude_agent_sdk.client import ClaudeSDKClient
5 -from claude_agent_sdk.types import ClaudeAgentOptions, AssistantMessage, TextBlock, ToolUseBlock
4 +from claude_agent_sdk.types import (
5 + ClaudeAgentOptions,
6 + AssistantMessage,
7 + TextBlock,
8 + ToolUseBlock,
9 +)
10 from composio import Composio
11
12 load_dotenv()
13
10 -# Initialize Composio and create a Tool Router session
11 -composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
12 -user_id = "user_123" # Your user's unique identifier
14 +# Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly)
15 +composio = Composio()
16 +
17 +# Unique identifier of the user
18 +user_id = "user_123"
19 +# Create a tool router session for the user
20 session = composio.create(user_id=user_id)
21
22 # Configure Claude with Composio MCP server
23 options = ClaudeAgentOptions(
17 - system_prompt=("You are a helpful assistant with access to external tools. "
18 - "Always use the available tools to complete user requests."),
24 + system_prompt=(
25 + "You are a helpful assistant with access to external tools. "
26 + "Always use the available tools to complete user requests."
27 + ),
28 mcp_servers={
29 "composio": {
30 "type": "http",
31 "url": session.mcp.url,
23 - "headers": {"x-api-key": os.environ["COMPOSIO_API_KEY"]},
32 + "headers": session.mcp.headers, # Authentication headers for the Composio MCP server
33 }
34 },
26 - permission_mode="bypassPermissions",
35 + permission_mode="bypassPermissions", # Auto-approve tools (demo only)
36 )
37
29 -
38 async def main():
31 - print("Starting Claude agent with Composio Tool Router...\n")
32 -
33 - async with ClaudeSDKClient(options) as client:
34 - # Initial task
35 - query = ("Fetch all open issues from the composio GitHub repository "
36 - "and create a Google Sheet with issue number, title, labels, and author")
37 -
38 - print(f"Task: {query}\n")
39 - print("Claude: ", end="")
40 -
41 - await client.query(query)
42 - async for msg in client.receive_response():
43 - if isinstance(msg, AssistantMessage):
44 - for block in msg.content:
45 - if isinstance(block, ToolUseBlock):
46 - print(f"\n[🔧 Using tool: {block.name}]")
47 - elif isinstance(block, TextBlock):
48 - print(block.text, end="")
49 - print("\n")
50 -
51 - # If authentication is needed, Claude will provide a link
52 - # You can paste it back or type 'quit' to exit
53 - user_input = input("\nYou (confirm connection or new task or quit): ").strip()
54 -
55 - if user_input.lower() not in ("quit", "exit") and user_input:
56 - await client.query(user_input)
57 - print("\nClaude: ", end="")
58 - async for msg in client.receive_response():
59 - if isinstance(msg, AssistantMessage):
60 - for block in msg.content:
61 - if isinstance(block, TextBlock):
62 - print(block.text, end="")
63 - print()
39 + print("""
40 +What task would you like me to help you with?
41 +I can use tools like Gmail, GitHub, Linear, Notion, and more.
42 +(Type 'exit' to exit)
43 +Example tasks:
44 + • 'Summarize my emails from today'
45 + • 'List all open issues on the composio github repository and create a notion page with the issues'
46 +""")
47
48 + async with ClaudeSDKClient(options) as client:
49 + # Multi-turn conversation with agentic tool calling
50 + while True:
51 + user_input = input("\nYou: ").strip()
52 + if user_input.lower() == "exit":
53 + break
54 +
55 + print("\nClaude: ", end="", flush=True)
56 + try:
57 + await client.query(user_input)
58 + async for msg in client.receive_response():
59 + if isinstance(msg, AssistantMessage):
60 + for block in msg.content:
61 + if isinstance(block, ToolUseBlock):
62 + print(f"\n[Using tool: {block.name}]", end="")
63 + elif isinstance(block, TextBlock):
64 + print(block.text, end="", flush=True)
65 + except Exception as e:
66 + print(f"\n[Error]: {e}")
67
68 if __name__ == "__main__":
69 asyncio.run(main())
\ No newline at end of file
fern/snippets/tool-router/python/mcp-openai.py
+23 -31
@@ -1,28 +1,22 @@
1 -import os
1 from dotenv import load_dotenv
2 from composio import Composio
4 -from agents import Agent, Runner, HostedMCPTool, ModelSettings
3 +from agents import Agent, Runner, HostedMCPTool
4
6 -# Load environment variables from .env file
5 load_dotenv()
6
9 -composio_api_key = os.environ["COMPOSIO_API_KEY"]
10 -user_id = "user_123" # Your user's unique identifier
7 +# Initialize Composio (API key from env var COMPOSIO_API_KEY)
8 +composio = Composio()
9 +# Unique identifier of the user
10 +user_id = "user_123"
11
12 -print("Starting OpenAI agent with Composio...\n")
13 -
14 -# Initialize Composio and create a Tool Router session
15 -composio = Composio(api_key=composio_api_key)
12 +# Create a Tool Router session for the user
13 session = composio.create(user_id=user_id)
14
15 # Configure OpenAI agent with Composio MCP server
16 agent = Agent(
20 - name="AI Assistant",
21 - instructions=(
22 - "You are a helpful assistant with access to external tools. "
23 - "Always use the available tools to complete user requests instead of just explaining how to do them."
24 - ),
25 - model="gpt-5.2",
17 + name="Personal Assistant",
18 + instructions="You are a helpful personal assistant. Use Composio tools to take action.",
19 + model="gpt-5.2",
20 tools=[
21 HostedMCPTool(
22 tool_config={
@@ -30,24 +24,22 @@ agent = Agent(
24 "server_label": "composio",
25 "server_url": session.mcp.url,
26 "require_approval": "never",
33 - "headers": {"x-api-key": composio_api_key},
27 + "headers": session.mcp.headers,
28 }
29 )
30 ],
31 )
32
39 -# Optional: Pre-authorize tools before use (otherwise you'll get a link during execution)
40 -# connection_request = session.authorize("github")
41 -# print(connection_request.redirect_url)
42 -# connected_account = connection_request.wait_for_connection(timeout=60000)
43 -# print(f"Connected: {connected_account.id}")
44 -
45 -print("Running the OpenAI agent to fetch GitHub issues...\n")
46 -
47 -# Execute a task that requires GitHub access
48 -result = Runner.run_sync(
49 - starting_agent=agent,
50 - input=("Fetch all the open GitHub issues on the composio repository "
51 - "and group them by bugs/features/docs.")
52 -)
53 -print(f"Result: {result.final_output}")
\ No newline at end of file
33 +# Execute the task
34 +print("Fetching GitHub issues from the Composio repository @ComposioHQ/composio...\n")
35 +try:
36 + result = Runner.run_sync(
37 + starting_agent=agent,
38 + input="Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
39 + )
40 + print(result.final_output)
41 +except Exception as e:
42 + print(f"[Error]: {e}")
43 +
44 +print("\n\n---")
45 +print("Tip: If prompted to authenticate, complete the auth flow and run again.")
\ No newline at end of file
fern/snippets/tool-router/python/native-tools-openai.py
+33 -30
@@ -1,51 +1,54 @@
1 -import os
1 from dotenv import load_dotenv
2 from composio import Composio
3 from agents import Agent, Runner, SQLiteSession
4 from composio_openai_agents import OpenAIAgentsProvider
5
7 -# Load environment variables from .env file
6 load_dotenv()
7
10 -composio = Composio(api_key=os.environ.get("COMPOSIO_API_KEY"), provider=OpenAIAgentsProvider())
11 -session = composio.create(user_id="user_123")
8 +# Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
9 +composio = Composio(provider=OpenAIAgentsProvider())
10
13 -# Get native tools from Composio
11 +# Unique identifier of the user
12 +user_id = "user_123"
13 +
14 +# Create a session and get native tools for the user
15 +session = composio.create(user_id=user_id)
16 tools = session.tools()
17
16 -# Create OpenAI agent with Composio tools
18 +# Configure OpenAI agent with Composio tools
19 agent = Agent(
18 - name="AI Assistant",
19 - instructions="You are a helpful assistant with access to external tools. Always use the available tools to complete user requests instead of just explaining how to do them.",
20 - model="gpt-5.2",
20 + name="Personal Assistant",
21 + instructions="You are a helpful personal assistant. Use Composio tools to take action.",
22 + model="gpt-4o",
23 tools=tools,
24 )
25
24 -# Create session for multi-turn conversation
25 -conversation_session = SQLiteSession("conversation_example")
26 +# Memory for multi-turn conversation
27 +memory = SQLiteSession("conversation")
28
27 -# Execute an initial task that requires GitHub access
28 -print("Executing initial task: Fetching GitHub issues...\n")
29 -result = Runner.run_sync(
30 - starting_agent=agent,
31 - input="Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
32 - session=conversation_session,
33 -)
34 -print(f"Result: {result.final_output}\n")
29 +# Execute an initial task
30 +print("Fetching GitHub issues from the Composio repository...\n")
31 +try:
32 + result = Runner.run_sync(
33 + starting_agent=agent,
34 + input="Fetch all the open GitHub issues on the @ComposioHQ/composio repository and group them by bugs/features/docs.",
35 + session=memory,
36 + )
37 + print(f"{result.final_output}\n")
38 +except Exception as e:
39 + print(f"[Error]: {e}")
40
41 # Continue with interactive conversation
37 -print("Assistant: What else would you like me to do? Type 'exit' to end the conversation.\n")
42 +print("\nWhat else would you like me to do? (Type 'exit' to exit)")
43
44 while True:
40 - user_input = input("> ")
45 + user_input = input("You: ").strip()
46 if user_input.lower() == "exit":
47 break
43 -
44 - # Run agent with session to maintain context
45 - result = Runner.run_sync(
46 - starting_agent=agent,
47 - input=user_input,
48 - session=conversation_session,
49 - )
50 -
51 - print(f"Assistant: {result.final_output}\n")
\ No newline at end of file
48 +
49 + print("Assistant: ", end="", flush=True)
50 + try:
51 + result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory)
52 + print(f"{result.final_output}\n")
53 + except Exception as e:
54 + print(f"\n[Error]: {e}")
\ No newline at end of file
fern/snippets/tool-router/python/quickstart-mcp-claude.py
+37 -23
@@ -1,35 +1,36 @@
1 import asyncio
2 -import os
2 from dotenv import load_dotenv
3 from claude_agent_sdk.client import ClaudeSDKClient
4 from claude_agent_sdk.types import (
6 - ClaudeAgentOptions,
7 - ResultMessage,
8 - AssistantMessage,
9 - TextBlock,
10 - ToolUseBlock
5 + ClaudeAgentOptions,
6 + AssistantMessage,
7 + TextBlock,
8 + ToolUseBlock,
9 )
10 from composio import Composio
11
14 -# Load environment variables from .env file
12 load_dotenv()
13
17 -# Initialize Composio and create a Tool Router session
18 -composio = Composio(api_key=os.environ["COMPOSIO_API_KEY"])
19 -user_id = "user_123" # Your user's unique identifier
14 +# Initialize Composio (API key from env var COMPOSIO_API_KEY)
15 +composio = Composio()
16 +
17 +# Unique identifier of the user
18 +user_id = "user_123"
19 +
20 +# Create a tool router session for the user
21 session = composio.create(user_id=user_id)
22
23 # Configure Claude with Composio MCP server
24 options = ClaudeAgentOptions(
25 system_prompt=(
26 "You are a helpful assistant with access to external tools. "
26 - "Always use the available tools to complete user requests instead of just explaining how to do them."
27 + "Always use the available tools to complete user requests."
28 ),
29 mcp_servers={
30 "composio": {
31 "type": "http",
32 "url": session.mcp.url,
32 - "headers": {"x-api-key": os.environ["COMPOSIO_API_KEY"]},
33 + "headers": session.mcp.headers,
34 }
35 },
36 permission_mode="bypassPermissions",
@@ -37,22 +38,35 @@ options = ClaudeAgentOptions(
38
39
40 async def main():
41 + print("""
42 +What task would you like me to help you with?
43 +I can use tools like Gmail, GitHub, Linear, Notion, and more.
44 +(Type 'exit' to exit)
45 +Example tasks:
46 + • 'Summarize my emails from today'
47 + • 'List all open issues on the composio github repository and create a notion page with the issues'
48 +""")
49 +
50 async with ClaudeSDKClient(options) as client:
51 + # Multi-turn conversation with agentic tool calling
52 while True:
53 user_input = input("You: ").strip()
43 - if user_input.lower() in ("quit", "exit"):
54 + if user_input.lower() == "exit":
55 break
56
46 - await client.query(user_input)
47 - async for msg in client.receive_response():
48 - if isinstance(msg, AssistantMessage):
49 - for block in msg.content:
50 - if isinstance(block, ToolUseBlock):
51 - print(f"[Using tool: {block.name}]")
52 - elif isinstance(block, TextBlock):
53 - print(block.text, end="")
54 - elif isinstance(msg, ResultMessage) and msg.result:
55 - print(f"\n{msg.result}\n")
57 + print("\nClaude: ", end="", flush=True)
58 + try:
59 + await client.query(user_input)
60 + async for msg in client.receive_response():
61 + if isinstance(msg, AssistantMessage):
62 + for block in msg.content:
63 + if isinstance(block, ToolUseBlock):
64 + print(f"\n[Using tool: {block.name}]", end="")
65 + elif isinstance(block, TextBlock):
66 + print(block.text, end="", flush=True)
67 + print()
68 + except Exception as e:
69 + print(f"\n[Error]: {e}")
70
71
72 if __name__ == "__main__":
fern/snippets/tool-router/python/quickstart-mcp-openai.py
+29 -21
@@ -1,48 +1,56 @@
1 -import os
1 from dotenv import load_dotenv
2 from composio import Composio
3 from agents import Agent, Runner, HostedMCPTool, SQLiteSession
4
5 load_dotenv()
6
8 -composio_api_key = os.environ.get("COMPOSIO_API_KEY")
9 -user_id = "user_123" # Your user's unique identifier
7 +# Initialize Composio (API key from env var COMPOSIO_API_KEY)
8 +composio = Composio()
9
11 -composio = Composio(api_key=composio_api_key)
12 -composio_session = composio.create(user_id=user_id)
10 +# Unique identifier of the user
11 +user_id = "user_123"
12
13 +# Create a Tool Router session for the user
14 +session = composio.create(user_id=user_id)
15 +
16 +# Configure OpenAI agent with Composio MCP server
17 agent = Agent(
18 name="Personal Assistant",
19 instructions="You are a helpful personal assistant. Use Composio tools to take action.",
17 - model="gpt-5.2",
20 + model="gpt-5.2",
21 tools=[
22 HostedMCPTool(
23 tool_config={
24 "type": "mcp",
25 "server_label": "composio",
23 - "server_url": composio_session.mcp.url,
26 + "server_url": session.mcp.url,
27 "require_approval": "never",
25 - "headers": {"x-api-key": composio_api_key},
28 + "headers": session.mcp.headers,
29 }
30 )
31 ],
32 )
33
31 -# Create a session for multi-turn conversation memory
32 -conversation_session = SQLiteSession(user_id)
34 +# Memory for multi-turn conversation
35 +memory = SQLiteSession(user_id)
36
34 -print("Assistant: What would you like me to do today?\n")
37 +print("""
38 +What task would you like me to help you with?
39 +I can use tools like Gmail, GitHub, Linear, Notion, and more.
40 +(Type 'exit' to exit)
41 +Example tasks:
42 + • 'Summarize my emails from today'
43 + • 'List all open issues on the composio github repository'
44 +""")
45
46 while True:
37 - user_input = input("> ")
38 - if user_input == "exit":
47 + user_input = input("You: ").strip()
48 + if user_input.lower() == "exit":
49 break
40 -
41 - result = Runner.run_sync(
42 - starting_agent=agent,
43 - input=user_input,
44 - session=conversation_session
45 - )
46 -
47 - print(f"Assistant: {result.final_output}\n")
50
51 + print("Assistant: ", end="", flush=True)
52 + try:
53 + result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory)
54 + print(f"{result.final_output}\n")
55 + except Exception as e:
56 + print(f"\n[Error]: {e}")
fern/snippets/tool-router/python/quickstart-native-openai.py
+28 -20
@@ -1,4 +1,3 @@
1 -import os
1 from dotenv import load_dotenv
2 from composio import Composio
3 from agents import Agent, Runner, SQLiteSession
@@ -6,35 +5,44 @@ from composio_openai_agents import OpenAIAgentsProvider
5
6 load_dotenv()
7
9 -composio = Composio(api_key=os.environ.get("COMPOSIO_API_KEY"), provider=OpenAIAgentsProvider())
10 -session = composio.create(user_id="user_123")
8 +# Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
9 +composio = Composio(provider=OpenAIAgentsProvider())
10
12 -# Get native tools from Composio
11 +# Unique identifier of the user
12 +user_id = "user_123"
13 +
14 +# Create a session and get native tools for the user
15 +session = composio.create(user_id=user_id)
16 tools = session.tools()
17
15 -# Create OpenAI agent with Composio tools
18 +# Configure OpenAI agent with Composio tools
19 agent = Agent(
17 - name="AI Assistant",
18 - instructions="You are a helpful assistant with access to external tools. Use the available tools to complete user requests.",
20 + name="Personal Assistant",
21 + instructions="You are a helpful personal assistant. Use Composio tools to take action.",
22 model="gpt-5.2",
23 tools=tools,
24 )
25
23 -# Create session for multi-turn conversation
24 -conversation_session = SQLiteSession("conversation_example")
26 +# Memory for multi-turn conversation
27 +memory = SQLiteSession("conversation")
28
26 -print("Assistant: What would you like me to do today? Type 'exit' to end the conversation.\n")
29 +print("""
30 +What task would you like me to help you with?
31 +I can use tools like Gmail, GitHub, Linear, Notion, and more.
32 +(Type 'exit' to exit)
33 +Example tasks:
34 + • 'Summarize my emails from today'
35 + • 'List all open issues on the composio github repository'
36 +""")
37
38 while True:
29 - user_input = input("> ")
39 + user_input = input("You: ").strip()
40 if user_input.lower() == "exit":
41 break
32 -
33 - # Run agent with session to maintain context
34 - result = Runner.run_sync(
35 - starting_agent=agent,
36 - input=user_input,
37 - session=conversation_session,
38 - )
39 -
40 - print(f"Assistant: {result.final_output}\n")
\ No newline at end of file
42 +
43 + print("Assistant: ", end="", flush=True)
44 + try:
45 + result = Runner.run_sync(starting_agent=agent, input=user_input, session=memory)
46 + print(f"{result.final_output}\n")
47 + except Exception as e:
48 + print(f"\n[Error]: {e}")
\ No newline at end of file