Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
Fix tool router Typscript snippets
Sushmithamallesh committed
Dec 22, 2025 at 05:21 UTC
2eb8258b7ee7ddf18b6d89396781750d5529326e
12 files changed
+349
-277
fern/pages/src/tool-router/quickstart.mdx
+3
-3
@@ -21,7 +21,7 @@ Choose how you want to integrate Tool Router:
21
pip install composio claude-agent-sdk
22
```
23
```bash title="TypeScript" for="typescript"
24
-npm install @composio/core @anthropic-ai/claude-agent-sdk
24
+npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk
25
```
26
</CodeGroup>
27
</Step>
@@ -55,7 +55,7 @@ When the agent needs authentication, it will prompt the user with a link to conn
55
pip install composio openai-agents
56
```
57
```bash title="TypeScript" for="typescript"
58
-npm install @composio/core @openai/agents
58
+npm install dotenv @composio/core @openai/agents zod@3
59
```
60
</CodeGroup>
61
</Step>
@@ -86,7 +86,7 @@ When the agent needs authentication, it will prompt the user with a link to conn
86
<Steps>
87
<Step title="Install Composio SDK">
88
```bash
89
-npm install @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
89
+npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
90
```
91
</Step>
92
fern/pages/src/tool-router/using-with-mcp-clients.mdx
+3
-3
@@ -23,7 +23,7 @@ Jump to examples for:
23
pip install composio claude-agent-sdk
24
```
25
```bash title="TypeScript" for="typescript"
26
-npm install @composio/core @anthropic-ai/claude-agent-sdk
26
+npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk
27
```
28
</CodeGroup>
29
@@ -50,7 +50,7 @@ Create a Tool Router session and execute tasks with Claude:
50
pip install composio openai-agents
51
```
52
```bash title="TypeScript" for="typescript"
53
-npm install @composio/core @openai/agents
53
+npm install dotenv @composio/core @openai/agents zod@3
54
```
55
</CodeGroup>
56
@@ -73,7 +73,7 @@ Create a Tool Router session and execute tasks with OpenAI agents:
73
### Installation
74
75
```bash
76
-npm install @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
76
+npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
77
```
78
79
### Usage
fern/snippets/tool-router/typescript/mcp-claude.ts
+44
-60
@@ -1,89 +1,73 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
3
import { Composio } from "@composio/core";
4
import { createInterface } from "readline/promises";
5
6
-const composioApiKey = process.env.COMPOSIO_API_KEY;
7
-if (!composioApiKey) {
8
- console.warn("⚠️ Warning: COMPOSIO_API_KEY not set - Claude won't be able to use Composio tools");
9
-}
10
-const userId = "user_123"; // Your user's unique identifier
6
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
7
+const composio = new Composio();
8
+
9
+// Unique identifier of the user
10
+const userId = "user-1234";
11
12
-// Initialize Composio and create a Tool Router session
13
-const composio = new Composio({ apiKey: composioApiKey });
12
+// Create a tool router session for the user
13
const session = await composio.create(userId);
14
16
-// Configure Claude with Composio MCP server
15
const options: Options = {
18
- systemPrompt: "You are a helpful assistant with access to external tools. " +
19
- "Always use the available tools to complete user requests.",
16
+ systemPrompt: `You are a helpful assistant with access to external tools. ` +
17
+ `Always use the available tools to complete user requests.`,
18
mcpServers: {
19
composio: {
20
type: "http",
21
url: session.mcp.url,
24
- headers: { "x-api-key": composioApiKey }
22
+ headers: session.mcp.headers // Authentication headers for the Composio MCP server
23
},
24
},
27
- permissionMode: "bypassPermissions",
28
- allowDangerouslySkipPermissions: true,
25
+ permissionMode: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)
26
};
27
31
-async function main() {
32
- console.log("Starting Claude agent with Composio Tool Router...\n");
33
-
34
- const rl = createInterface({ input: process.stdin, output: process.stdout });
35
-
36
- // Initial task
37
- const task = "Fetch all open issues from the composio GitHub repository " +
38
- "and create a Google Sheet with issue number, title, labels, and author";
39
-
40
- console.log(`Task: ${task}\n`);
41
-
42
- let isFirstQuery = true;
43
-
44
- for await (const msg of query({ prompt: task, options })) {
45
- if (msg.type === "assistant") {
46
- for (const block of msg.message.content) {
47
- if (block.type === "tool_use") {
48
- console.log(`\n[🔧 Using tool: ${block.name}]`);
49
- } else if (block.type === "text") {
50
- process.stdout.write(block.text);
51
- }
52
- }
53
- } else if (msg.type === "result" && msg.subtype === "success") {
54
- console.log(`\n${msg.result}\n`);
55
- }
56
- }
57
- console.log("\n");
28
+// Set up interactive terminal input/output for the conversation
29
+const readline = createInterface({ input: process.stdin, output: process.stdout });
30
+
31
+console.log(`
32
+What task would you like me to help you with?
33
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
34
+(Type 'exit' to exit)
35
+Example tasks:
36
+ • 'Summarize my emails from today'
37
+ • 'List all open issues on the composio github repository and create a notion page with the issues'
38
+`);
39
+
40
+let isFirstQuery = true;
41
+
42
+// Multi-turn conversation with agentic tool calling
43
+while (true) {
44
+ const answer = await readline.question('You: ');
45
+ const input = answer.trim();
46
+ if (input.toLowerCase() === "exit") break;
47
+
48
+ process.stdout.write("Claude: ");
49
50
+ const queryOptions = isFirstQuery ? options : { ...options, continue: true };
51
isFirstQuery = false;
52
61
- // If authentication is needed, Claude will provide a link
62
- console.log("\nOptions:");
63
- console.log(" - Type 'quit' to exit");
64
- console.log(" - Say 'connected' or enter a new task\n");
65
-
66
- const userInput = await rl.question("You: ");
67
-
68
- if (userInput.toLowerCase() !== "quit" && userInput.toLowerCase() !== "exit" && userInput) {
69
- // Continue the conversation with the same context
70
- for await (const msg of query({ prompt: userInput, options: { ...options, continue: true } })) {
71
- if (msg.type === "assistant") {
72
- for (const block of msg.message.content) {
53
+ try {
54
+ for await (const stream of query({ prompt: input, options: queryOptions })) {
55
+ // Only process assistant messages (the SDK also sends result/error messages)
56
+ if (stream.type === "assistant") {
57
+ const { content } = stream.message;
58
+ for (const block of content) {
59
if (block.type === "tool_use") {
74
- console.log(`\n[🔧 Using tool: ${block.name}]`);
60
+ process.stdout.write(`\n[Using tool: ${block.name}]`);
61
} else if (block.type === "text") {
62
process.stdout.write(block.text);
63
}
64
}
79
- } else if (msg.type === "result" && msg.subtype === "success") {
80
- console.log(`\n${msg.result}\n`);
65
}
66
}
83
- console.log();
67
+ } catch (error) {
68
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
69
}
85
-
86
- rl.close();
70
+ process.stdout.write("\n");
71
}
72
89
-main().catch(console.error);
\ No newline at end of file
73
+readline.close();
\ No newline at end of file
fern/snippets/tool-router/typescript/mcp-openai.ts
+48
-24
@@ -1,41 +1,65 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { Composio } from "@composio/core";
3
-import { Agent, hostedMcpTool, run } from "@openai/agents";
3
+import { Agent, hostedMcpTool, run, MemorySession } from "@openai/agents";
4
+import { createInterface } from "readline/promises";
5
5
-const composioApiKey = process.env.COMPOSIO_API_KEY;
6
-const userId = "user_123"; // Your user's unique identifier
6
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
7
+const composio = new Composio();
8
8
-// Initialize Composio and create a Tool Router session
9
-const composio = new Composio({ apiKey: composioApiKey });
9
+// Unique identifier of the user
10
+const userId = "user-1234";
11
+
12
+// Create a tool router session for the user
13
const session = await composio.create(userId);
14
12
-// Configure OpenAI agent with Composio MCP server
15
const agent = new Agent({
14
- name: "AI Assistant",
15
- instructions:
16
- "You are a helpful assistant with access to external tools. " +
17
- "Always use the available tools to complete user requests instead of just explaining how to do them.",
16
+ name: "Personal Assistant",
17
+ instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
18
model: "gpt-5.2",
19
tools: [
20
hostedMcpTool({
21
serverLabel: "composio",
22
serverUrl: session.mcp.url,
23
- headers: { "x-api-key": composioApiKey },
23
+ headers: session.mcp.headers, // Authentication headers for the Composio MCP server
24
}),
25
],
26
});
27
28
-// Optional: Pre-authorize tools before use (otherwise you'll get a link during execution)
29
-// const connectionRequest = await session.authorize("github");
30
-// console.log(connectionRequest.redirectUrl);
31
-// const connectedAccount = await connectionRequest.waitForConnection(60000);
32
-// console.log(`Connected: ${connectedAccount.id}`);
28
+// Create a memory session for persistent multi-turn conversation
29
+const memory = new MemorySession();
30
+
31
+// Execute an initial task
32
+console.log("Fetching GitHub issues from the Composio repository...\n");
33
+try {
34
+ const initialResult = await run(
35
+ agent,
36
+ "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
37
+ { session: memory }
38
+ );
39
+ console.log(`${initialResult.finalOutput}\n`);
40
+} catch (error) {
41
+ console.error("[Error]:", error instanceof Error ? error.message : error);
42
+}
43
+
44
+// Continue with interactive conversation
45
+const readline = createInterface({ input: process.stdin, output: process.stdout });
46
+
47
+console.log(`
48
+What else would you like me to do?
49
+(Type 'exit' to exit)
50
+`);
51
+
52
+while (true) {
53
+ const input = (await readline.question("You: ")).trim();
54
+ if (input.toLowerCase() === "exit") break;
55
34
-// Execute a task that requires GitHub access
35
-const result = await run(
36
- agent,
37
- "Fetch all the open GitHub issues on the composio repository " +
38
- "and group them by bugs/features/docs."
39
-);
56
+ console.log("Assistant: ");
57
41
-console.log(`Result: ${result.finalOutput}`);
\ No newline at end of file
58
+ try {
59
+ const result = await run(agent, input, { session: memory });
60
+ console.log(`${result.finalOutput}\n`);
61
+ } catch (error) {
62
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
63
+ }
64
+}
65
+readline.close();
\ No newline at end of file
fern/snippets/tool-router/typescript/mcp-vercel.ts
+19
-16
@@ -1,38 +1,38 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { anthropic } from "@ai-sdk/anthropic";
3
import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";
4
import { Composio } from "@composio/core";
5
import { stepCountIs, streamText } from "ai";
6
-const composioApiKey = process.env.COMPOSIO_API_KEY;
7
-const userId = "user-1234"; // Your user's unique identifier
6
9
-const composio = new Composio({ apiKey: composioApiKey });
7
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
8
+const composio = new Composio();
9
10
+// Unique identifier of the user
11
+const userId = "user-1234";
12
+
13
+// Create a tool router session for the user
14
const { mcp } = await composio.create(userId);
12
-console.log(`Tool Router session created: ${mcp.url}`);
15
16
+// Create an MCP client to connect to the Composio tool router
17
const client = await createMCPClient({
18
transport: {
19
type: "http",
20
url: mcp.url,
18
- headers: {
19
- "x-api-key": composioApiKey,
20
- },
21
+ headers: mcp.headers, // Authentication headers for the Composio MCP server
22
},
23
});
23
-
24
const tools = await client.tools();
25
26
+console.log("Summarizing your emails from today");
27
+
28
const stream = await streamText({
27
- system: "You are a helpful personal assistant. You should use composio MCP tools to take action.",
29
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
30
model: anthropic("claude-sonnet-4-5"),
29
- prompt: "Summarize all the emails in my Gmail inbox today",
31
+ prompt: "Summarize my emails from today",
32
stopWhen: stepCountIs(10),
33
onStepFinish: (step) => {
32
- if (step.toolCalls.length > 0) {
33
- for (const toolCall of step.toolCalls) {
34
- console.log(`Executed ${toolCall.toolName}`);
35
- }
34
+ for (const toolCall of step.toolCalls) {
35
+ console.log(`[Using tool: ${toolCall.toolName}]`);
36
}
37
},
38
tools,
@@ -40,4 +40,7 @@ const stream = await streamText({
40
41
for await (const textPart of stream.textStream) {
42
process.stdout.write(textPart);
43
-}
\ No newline at end of file
43
+}
44
+
45
+console.log("\n\n---");
46
+console.log("Tip: If prompted to authenticate, complete the auth flow and run again.")
\ No newline at end of file
fern/snippets/tool-router/typescript/native-tools-openai.ts
+44
-32
@@ -1,50 +1,62 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { Composio } from "@composio/core";
3
import { Agent, run, MemorySession } from "@openai/agents";
4
import { OpenAIAgentsProvider } from "@composio/openai-agents";
5
import { createInterface } from "readline/promises";
6
7
-const composioApiKey = process.env.COMPOSIO_API_KEY;
8
-const userId = "user_123"; // Your user's unique identifier
7
+// Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
8
+const composio = new Composio({ provider: new OpenAIAgentsProvider() });
9
10
-const composio = new Composio({ apiKey: composioApiKey, provider: new OpenAIAgentsProvider() });
11
-const session = await composio.create(userId);
10
+// Unique identifier of the user
11
+const userId = "user-1234";
12
13
-// Get native tools from Composio
13
+// Create a session and get native tools for the user
14
+const session = await composio.create(userId);
15
const tools = await session.tools();
16
16
-// Create OpenAI agent with Composio tools
17
const agent = new Agent({
18
- name: "AI Assistant",
19
- instructions:
20
- "You are a helpful assistant with access to external tools. " +
21
- "Always use the available tools to complete user requests instead of just explaining how to do them.",
18
+ name: "Personal Assistant",
19
+ instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
20
model: "gpt-5.2",
23
- tools: tools,
21
+ tools,
22
});
23
26
-// Create session for multi-turn conversation
27
-const conversationSession = new MemorySession();
28
-
29
-// Execute an initial task that requires GitHub access
30
-console.log("Executing initial task: Fetching GitHub issues...\n");
31
-const initialResult = await run(
32
- agent,
33
- "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
34
- { session: conversationSession }
35
-);
36
-console.log(`Result: ${initialResult.finalOutput}\n`);
24
+// Create a memory session for persistent multi-turn conversation
25
+const memory = new MemorySession();
26
+
27
+// Execute an initial task
28
+console.log("Fetching GitHub issues from the Composio repository...\n");
29
+try {
30
+ const initialResult = await run(
31
+ agent,
32
+ "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
33
+ { session: memory }
34
+ );
35
+ console.log(`${initialResult.finalOutput}\n`);
36
+} catch (error) {
37
+ console.error("[Error]:", error instanceof Error ? error.message : error);
38
+}
39
40
// Continue with interactive conversation
39
-const rl = createInterface({ input: process.stdin, output: process.stdout });
40
-console.log("Assistant: What else would you like me to do? Type 'exit' to end the conversation.\n");
41
+const readline = createInterface({ input: process.stdin, output: process.stdout });
42
+
43
+console.log(`
44
+What else would you like me to do?
45
+(Type 'exit' to exit)
46
+`);
47
+
48
49
while (true) {
43
- const userInput = await rl.question("> ");
44
- if (userInput.toLowerCase() === "exit") break;
45
-
46
- // Run agent with session to maintain context
47
- const result = await run(agent, userInput, { session: conversationSession });
48
- console.log(`Assistant: ${result.finalOutput}\n`);
50
+ const input = (await readline.question("You: ")).trim();
51
+ if (input.toLowerCase() === "exit") break;
52
+
53
+ console.log("Assistant: ");
54
+
55
+ try {
56
+ const result = await run(agent, input, { session: memory });
57
+ console.log(`${result.finalOutput}\n`);
58
+ } catch (error) {
59
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
60
+ }
61
}
50
-rl.close();
\ No newline at end of file
62
+readline.close();
\ No newline at end of file
fern/snippets/tool-router/typescript/native-tools-vercel.ts
+27
-29
@@ -1,40 +1,38 @@
1
import "dotenv/config";
2
+import { anthropic } from "@ai-sdk/anthropic";
3
import { Composio } from "@composio/core";
4
import { VercelProvider } from "@composio/vercel";
4
-import { generateText, stepCountIs, ModelMessage } from "ai";
5
-import { createInterface } from "readline/promises";
6
-import { anthropic } from "@ai-sdk/anthropic";
5
+import { stepCountIs, streamText } from "ai";
6
8
-const composio = new Composio({
9
- apiKey: process.env.COMPOSIO_API_KEY,
10
- provider: new VercelProvider(),
11
-});
7
+// Initialize Composio with Vercel provider (API key from env var COMPOSIO_API_KEY)
8
+const composio = new Composio({ provider: new VercelProvider() });
9
13
-const session = await composio.create("user_123");
10
+// Unique identifier of the user
11
+const userId = "user-1234";
12
+
13
+// Create a session and get native tools for the user
14
+const session = await composio.create(userId);
15
const tools = await session.tools();
16
16
-const rl = createInterface({ input: process.stdin, output: process.stdout });
17
-const messages: ModelMessage[] = [];
17
+console.log("Fetching GitHub issues from the Composio repository...");
18
19
-// Initial task
20
-const initialPrompt = "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.";
21
-console.log("Executing initial task: Fetching GitHub issues...\n");
19
+// Stream the response with tool calling
20
+const stream = await streamText({
21
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
22
+ model: anthropic("claude-sonnet-4-5"),
23
+ prompt: "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
24
+ stopWhen: stepCountIs(10),
25
+ onStepFinish: (step) => {
26
+ for (const toolCall of step.toolCalls) {
27
+ console.log(`[Using tool: ${toolCall.toolName}]`);
28
+ }
29
+ },
30
+ tools,
31
+});
32
23
-while (true) {
24
- const userInput = messages.length === 0 ? initialPrompt : await rl.question("> ");
25
- if (userInput.toLowerCase() === "exit") break;
26
-
27
- messages.push({ role: "user", content: userInput });
28
-
29
- const result = await generateText({
30
- model: anthropic("claude-sonnet-4-5"),
31
- messages: messages,
32
- tools: tools,
33
- stopWhen: stepCountIs(10),
34
- });
35
-
36
- messages.push({ role: "assistant", content: result.text });
37
- console.log(`Assistant: ${result.text}\n`);
33
+for await (const textPart of stream.textStream) {
34
+ process.stdout.write(textPart);
35
}
36
40
-rl.close();
\ No newline at end of file
37
+console.log("\n\n---");
38
+console.log("Tip: If prompted to authenticate, complete the auth flow and run again.");
\ No newline at end of file
fern/snippets/tool-router/typescript/quickstart-mcp-claude.ts
+42
-29
@@ -1,61 +1,74 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
3
import { Composio } from "@composio/core";
4
import { createInterface } from "readline/promises";
5
6
-const composioApiKey = process.env.COMPOSIO_API_KEY;
7
-if (!composioApiKey) {
8
- console.warn("⚠️ Warning: COMPOSIO_API_KEY not set - Claude won't be able to use Composio tools");
9
-}
10
-const userId = "user_123"; // Your user's unique identifier
6
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
7
+const composio = new Composio();
8
+
9
+// Unique identifier of the user
10
+const userId = "user_123";
11
12
-const composio = new Composio({ apiKey: composioApiKey });
12
+// Create a tool router session for the user
13
const session = await composio.create(userId);
14
15
const options: Options = {
16
- systemPrompt: "You are a helpful assistant with access to external tools. " +
17
- "Always use the available tools to complete user requests instead of just explaining how to do them.",
16
+ systemPrompt: `You are a helpful assistant with access to external tools. ` +
17
+ `Always use the available tools to complete user requests.`,
18
mcpServers: {
19
composio: {
20
type: "http",
21
url: session.mcp.url,
22
- headers: { "x-api-key": composioApiKey }
22
+ headers: session.mcp.headers // Authentication headers for the Composio MCP server
23
},
24
},
25
- permissionMode: "bypassPermissions",
26
- allowDangerouslySkipPermissions: true,
25
+ permissionMode: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)
26
};
27
29
-const rl = createInterface({ input: process.stdin, output: process.stdout });
28
+// Set up interactive terminal input/output for the conversation
29
+const readline = createInterface({ input: process.stdin, output: process.stdout });
30
31
-console.log("What task would you like me to help you with?");
32
-console.log("(Type 'quit' to exit)\n");
31
+console.log(`
32
+What task would you like me to help you with?
33
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
34
+(Type 'exit' to exit)
35
+Example tasks:
36
+ • 'Summarize my emails from today'
37
+ • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
38
+`);
39
40
let isFirstQuery = true;
41
42
+// Multi-turn conversation with agentic tool calling
43
while (true) {
37
- const input = (await rl.question("You: ")).trim();
38
- if (input.toLowerCase() === "quit" || input.toLowerCase() === "exit") break;
44
+ const answer = await readline.question('You: ');
45
+ const input = answer.trim();
46
+ if (input.toLowerCase() === "exit") break;
47
48
process.stdout.write("Claude: ");
41
- // First query starts a new conversation, subsequent queries continue it
49
+
50
+ // Use `continue: true` to maintain conversation context
51
const queryOptions = isFirstQuery ? options : { ...options, continue: true };
52
isFirstQuery = false;
53
45
- for await (const msg of query({ prompt: input, options: queryOptions })) {
46
- if (msg.type === "assistant") {
47
- for (const block of msg.message.content) {
48
- if (block.type === "tool_use") {
49
- console.log(`\n[Using tool: ${block.name}]`);
50
- } else if (block.type === "text") {
51
- process.stdout.write(block.text);
54
+ try {
55
+ for await (const stream of query({ prompt: input, options: queryOptions })) {
56
+ // Only process assistant messages (the SDK also sends result/error messages)
57
+ if (stream.type === "assistant") {
58
+ const { content } = stream.message;
59
+ for (const block of content) {
60
+ if (block.type === "tool_use") {
61
+ process.stdout.write(`\n[Using tool: ${block.name}]`);
62
+ } else if (block.type === "text") {
63
+ process.stdout.write(block.text);
64
+ }
65
}
66
}
54
- } else if (msg.type === "result" && msg.subtype === "success") {
55
- console.log(`\n[Tool Result: ${msg.result}]`);
67
}
68
+ } catch (error) {
69
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
70
}
58
- console.log();
71
+ process.stdout.write("\n");
72
}
73
61
-rl.close();
\ No newline at end of file
74
+readline.close();
\ No newline at end of file
fern/snippets/tool-router/typescript/quickstart-mcp-openai.ts
+38
-18
@@ -1,13 +1,16 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { Composio } from "@composio/core";
3
import { Agent, run, hostedMcpTool, MemorySession } from "@openai/agents";
4
import { createInterface } from "readline/promises";
5
6
-const composioApiKey = process.env.COMPOSIO_API_KEY;
7
-const userId = "user-1234"; // Your user's unique identifier
6
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
7
+const composio = new Composio();
8
9
-const composio = new Composio({ apiKey: composioApiKey });
10
-const { mcp } = await composio.create(userId);
9
+// Unique identifier of the user
10
+const userId = "user-1234";
11
+
12
+// Create a tool router session for the user
13
+const session = await composio.create(userId);
14
15
const agent = new Agent({
16
name: "Personal Assistant",
@@ -16,23 +19,40 @@ const agent = new Agent({
19
tools: [
20
hostedMcpTool({
21
serverLabel: "composio",
19
- serverUrl: mcp.url,
20
- headers: {
21
- "x-api-key": composioApiKey,
22
- },
22
+ serverUrl: session.mcp.url,
23
+ headers: session.mcp.headers // Authentication headers for the Composio MCP server
24
}),
25
],
26
});
27
27
-// Create a session for persistent multi-turn conversation memory
28
-const session = new MemorySession();
28
+// Create a memory session for persistent multi-turn conversation
29
+const memory = new MemorySession();
30
+
31
+// Set up interactive terminal input/output for the conversation
32
+const readline = createInterface({ input: process.stdin, output: process.stdout });
33
30
-const rl = createInterface({ input: process.stdin, output: process.stdout });
31
-console.log("Assistant: What would you like me to do today?\n");
34
+console.log(`
35
+What task would you like me to help you with?
36
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
37
+(Type 'exit' to exit)
38
+Example tasks:
39
+ • 'Summarize my emails from today'
40
+ • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
41
+`);
42
+
43
+// Multi-turn conversation with agentic tool calling
44
while (true) {
33
- const input = await rl.question("> ");
34
- if (input === "exit") break;
35
- const result = await run(agent, input, { session });
36
- console.log(`Assistant: ${result.finalOutput}\n`);
45
+ const input = (await readline.question("You: ")).trim();
46
+ if (input.toLowerCase() === "exit") break;
47
+
48
+ console.log("Assistant: ");
49
+
50
+ try {
51
+ // Multi-turn agentic loop: GPT calls tools and reasons until task is complete
52
+ const result = await run(agent, input, { session: memory });
53
+ console.log(`${result.finalOutput}`);
54
+ } catch (error) {
55
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
56
+ }
57
}
38
-rl.close();
58
+readline.close();
fern/snippets/tool-router/typescript/quickstart-mcp-vercel.ts
+18
-15
@@ -1,38 +1,38 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { anthropic } from "@ai-sdk/anthropic";
3
import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";
4
import { Composio } from "@composio/core";
5
import { stepCountIs, streamText } from "ai";
6
-const composioApiKey = process.env.COMPOSIO_API_KEY;
7
-const userId = "user-1234"; // Your user's unique identifier
6
9
-const composio = new Composio({ apiKey: composioApiKey });
7
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
8
+const composio = new Composio();
9
10
+// Unique identifier of the user
11
+const userId = "user-1234";
12
+
13
+// Create a tool router session for the user
14
const { mcp } = await composio.create(userId);
12
-console.log(`Tool Router session created: ${mcp.url}`);
15
16
+// Create an MCP client to connect to the Composio tool router
17
const client = await createMCPClient({
18
transport: {
19
type: "http",
20
url: mcp.url,
18
- headers: {
19
- "x-api-key": composioApiKey,
20
- },
21
+ headers: mcp.headers, // Authentication headers for the Composio MCP server
22
},
23
});
23
-
24
const tools = await client.tools();
25
26
+console.log("Summarizing your emails from today");
27
+
28
const stream = await streamText({
27
- system: "You are a helpful personal assistant. You should use composio MCP tools to take action.",
29
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
30
model: anthropic("claude-sonnet-4-5"),
29
- prompt: "Summarize all the emails in my Gmail inbox today",
31
+ prompt: "Summarize my emails from today",
32
stopWhen: stepCountIs(10),
33
onStepFinish: (step) => {
32
- if (step.toolCalls.length > 0) {
33
- for (const toolCall of step.toolCalls) {
34
- console.log(`Executed ${toolCall.toolName}`);
35
- }
34
+ for (const toolCall of step.toolCalls) {
35
+ console.log(`[Using tool: ${toolCall.toolName}]`);
36
}
37
},
38
tools,
@@ -41,3 +41,6 @@ const stream = await streamText({
41
for await (const textPart of stream.textStream) {
42
process.stdout.write(textPart);
43
}
44
+
45
+console.log("\n\n---");
46
+console.log("Tip: If prompted to authenticate, complete the auth flow and run again.");
fern/snippets/tool-router/typescript/quickstart-native-openai.ts
+35
-21
@@ -1,38 +1,52 @@
1
-import "dotenv/config"; // Load environment variables from .env file
1
+import "dotenv/config";
2
import { Composio } from "@composio/core";
3
import { Agent, run, MemorySession } from "@openai/agents";
4
import { OpenAIAgentsProvider } from "@composio/openai-agents";
5
import { createInterface } from "readline/promises";
6
7
-const composioApiKey = process.env.COMPOSIO_API_KEY;
8
-const userId = "user_123"; // Your user's unique identifier
7
+// Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
8
+const composio = new Composio({ provider: new OpenAIAgentsProvider() });
9
10
-const composio = new Composio({ apiKey: composioApiKey, provider: new OpenAIAgentsProvider() });
10
+// Unique identifier of the user
11
+const userId = "user-123aer4";
12
+// Create a tool router session for the user
13
const session = await composio.create(userId);
12
-
13
-// Get native tools from Composio
14
const tools = await session.tools();
15
16
-// Create OpenAI agent with Composio tools
16
const agent = new Agent({
18
- name: "AI Assistant",
19
- instructions: "You are a helpful assistant with access to external tools. Use the available tools to complete user requests.",
17
+ name: "Personal Assistant",
18
+ instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
19
model: "gpt-5.2",
21
- tools: tools,
20
+ tools,
21
});
22
24
-// Create session for multi-turn conversation
25
-const conversationSession = new MemorySession();
23
+// Set up interactive terminal input/output for the conversation
24
+const readline = createInterface({ input: process.stdin, output: process.stdout });
25
+// Create a memory session for persistent multi-turn conversation
26
+const memory = new MemorySession();
27
27
-const rl = createInterface({ input: process.stdin, output: process.stdout });
28
-console.log("Assistant: What would you like me to do today? Type 'exit' to end the conversation.\n");
28
+console.log(`
29
+What task would you like me to help you with?
30
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
31
+(Type 'exit' to exit)
32
+Example tasks:
33
+ • 'Summarize my emails from today'
34
+ • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
35
+`);
36
37
+// Multi-turn conversation with agentic tool calling
38
while (true) {
31
- const userInput = await rl.question("> ");
32
- if (userInput.toLowerCase() === "exit") break;
33
-
34
- // Run agent with session to maintain context
35
- const result = await run(agent, userInput, { session: conversationSession });
36
- console.log(`Assistant: ${result.finalOutput}\n`);
39
+ const query = await readline.question("You: ");
40
+ const input = query.trim();
41
+
42
+ if (input.toLowerCase() === "exit") break;
43
+ process.stdout.write("Assistant: ");
44
+
45
+ try {
46
+ const result = await run(agent, input, { session: memory });
47
+ process.stdout.write(`${result.finalOutput}`);
48
+ } catch (error) {
49
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
50
+ }
51
}
38
-rl.close();
\ No newline at end of file
52
+readline.close();
\ No newline at end of file
fern/snippets/tool-router/typescript/quickstart-native-vercel.ts
+28
-27
@@ -1,38 +1,39 @@
1
import "dotenv/config";
2
+import { anthropic } from "@ai-sdk/anthropic";
3
import { Composio } from "@composio/core";
4
import { VercelProvider } from "@composio/vercel";
4
-import { generateText, stepCountIs, ModelMessage } from "ai";
5
-import { createInterface } from "readline/promises";
6
-import { anthropic } from "@ai-sdk/anthropic";
5
+import { stepCountIs, streamText } from "ai";
6
8
-const composio = new Composio({
9
- apiKey: process.env.COMPOSIO_API_KEY,
10
- provider: new VercelProvider(),
11
-});
7
+// Initialize Composio with Vercel provider (API key from env var COMPOSIO_API_KEY)
8
+const composio = new Composio({ provider: new VercelProvider() });
9
13
-const session = await composio.create("user_123");
10
+// Unique identifier of the user
11
+const userId = "user-1234";
12
+
13
+// Create a session and get native tools for the user
14
+const session = await composio.create(userId);
15
const tools = await session.tools();
16
16
-const rl = createInterface({ input: process.stdin, output: process.stdout });
17
-const messages: ModelMessage[] = [];
17
+process.stdout.write("Summarizing your emails from today");
18
+process.stdout.write("\n");
19
19
-console.log("Assistant: What would you like me to do today?\n");
20
+const stream = await streamText({
21
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
22
+ model: anthropic("claude-sonnet-4-5"),
23
+ prompt: "Summarize my emails from today",
24
+ stopWhen: stepCountIs(10),
25
+ onStepFinish: (step) => {
26
+ for (const toolCall of step.toolCalls) {
27
+ process.stdout.write(`[Using tool: ${toolCall.toolName}]`);
28
+ process.stdout.write("\n");
29
+ }
30
+ },
31
+ tools,
32
+});
33
21
-while (true) {
22
- const userInput = await rl.question("> ");
23
- if (userInput === "exit") break;
24
-
25
- messages.push({ role: "user", content: userInput });
26
-
27
- const result = await generateText({
28
- model: anthropic("claude-sonnet-4-5") ,
29
- messages: messages,
30
- tools: tools,
31
- stopWhen: stepCountIs(10),
32
- });
33
-
34
- messages.push({ role: "assistant", content: result.text });
35
- console.log(`Assistant: ${result.text}\n`);
34
+for await (const textPart of stream.textStream) {
35
+ process.stdout.write(textPart);
36
}
37
38
-rl.close();
\ No newline at end of file
38
+process.stdout.write("\n");
39
+process.stdout.write("Tip: If prompted to authenticate, complete the auth flow and run again.");