Skip to content

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

Sushmithamallesh2eb8258b7ee7
diff --git a/fern/pages/src/tool-router/quickstart.mdx b/fern/pages/src/tool-router/quickstart.mdx
index 435600023..15ec9ea13 100644
--- a/fern/pages/src/tool-router/quickstart.mdx
+++ b/fern/pages/src/tool-router/quickstart.mdx
@@ -21,7 +21,7 @@ Choose how you want to integrate Tool Router:
pip install composio claude-agent-sdk
```
```bash title="TypeScript" for="typescript"
-npm install @composio/core @anthropic-ai/claude-agent-sdk
+npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk
```
</CodeGroup>
</Step>
@@ -55,7 +55,7 @@ When the agent needs authentication, it will prompt the user with a link to conn
pip install composio openai-agents
```
```bash title="TypeScript" for="typescript"
-npm install @composio/core @openai/agents
+npm install dotenv @composio/core @openai/agents zod@3
```
</CodeGroup>
</Step>
@@ -86,7 +86,7 @@ When the agent needs authentication, it will prompt the user with a link to conn
<Steps>
<Step title="Install Composio SDK">
```bash
-npm install @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
+npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
```
</Step>
diff --git a/fern/pages/src/tool-router/using-with-mcp-clients.mdx b/fern/pages/src/tool-router/using-with-mcp-clients.mdx
index 5a9736b39..b38fc909f 100644
--- a/fern/pages/src/tool-router/using-with-mcp-clients.mdx
+++ b/fern/pages/src/tool-router/using-with-mcp-clients.mdx
@@ -23,7 +23,7 @@ Jump to examples for:
pip install composio claude-agent-sdk
```
```bash title="TypeScript" for="typescript"
-npm install @composio/core @anthropic-ai/claude-agent-sdk
+npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk
```
</CodeGroup>
@@ -50,7 +50,7 @@ Create a Tool Router session and execute tasks with Claude:
pip install composio openai-agents
```
```bash title="TypeScript" for="typescript"
-npm install @composio/core @openai/agents
+npm install dotenv @composio/core @openai/agents zod@3
```
</CodeGroup>
@@ -73,7 +73,7 @@ Create a Tool Router session and execute tasks with OpenAI agents:
### Installation
```bash
-npm install @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
+npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp
```
### Usage
diff --git a/fern/snippets/tool-router/typescript/mcp-claude.ts b/fern/snippets/tool-router/typescript/mcp-claude.ts
index d7f3853b9..62b2ce8e5 100644
--- a/fern/snippets/tool-router/typescript/mcp-claude.ts
+++ b/fern/snippets/tool-router/typescript/mcp-claude.ts
@@ -1,89 +1,73 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
import { Composio } from "@composio/core";
import { createInterface } from "readline/promises";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-if (!composioApiKey) {
- console.warn("⚠️ Warning: COMPOSIO_API_KEY not set - Claude won't be able to use Composio tools");
-}
-const userId = "user_123"; // Your user's unique identifier
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
+const composio = new Composio();
+
+// Unique identifier of the user
+const userId = "user-1234";
-// Initialize Composio and create a Tool Router session
-const composio = new Composio({ apiKey: composioApiKey });
+// Create a tool router session for the user
const session = await composio.create(userId);
-// Configure Claude with Composio MCP server
const options: Options = {
- systemPrompt: "You are a helpful assistant with access to external tools. " +
- "Always use the available tools to complete user requests.",
+ 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: { "x-api-key": composioApiKey }
+ headers: session.mcp.headers // Authentication headers for the Composio MCP server
},
},
- permissionMode: "bypassPermissions",
- allowDangerouslySkipPermissions: true,
+ permissionMode: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)
};
-async function main() {
- console.log("Starting Claude agent with Composio Tool Router...\n");
-
- const rl = createInterface({ input: process.stdin, output: process.stdout });
-
- // Initial task
- const task = "Fetch all open issues from the composio GitHub repository " +
- "and create a Google Sheet with issue number, title, labels, and author";
-
- console.log(`Task: ${task}\n`);
-
- let isFirstQuery = true;
-
- for await (const msg of query({ prompt: task, options })) {
- if (msg.type === "assistant") {
- for (const block of msg.message.content) {
- if (block.type === "tool_use") {
- console.log(`\n[🔧 Using tool: ${block.name}]`);
- } else if (block.type === "text") {
- process.stdout.write(block.text);
- }
- }
- } else if (msg.type === "result" && msg.subtype === "success") {
- console.log(`\n${msg.result}\n`);
- }
- }
- console.log("\n");
+// 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;
- // If authentication is needed, Claude will provide a link
- console.log("\nOptions:");
- console.log(" - Type 'quit' to exit");
- console.log(" - Say 'connected' or enter a new task\n");
-
- const userInput = await rl.question("You: ");
-
- if (userInput.toLowerCase() !== "quit" && userInput.toLowerCase() !== "exit" && userInput) {
- // Continue the conversation with the same context
- for await (const msg of query({ prompt: userInput, options: { ...options, continue: true } })) {
- if (msg.type === "assistant") {
- for (const block of msg.message.content) {
+ 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") {
- console.log(`\n[🔧 Using tool: ${block.name}]`);
+ process.stdout.write(`\n[Using tool: ${block.name}]`);
} else if (block.type === "text") {
process.stdout.write(block.text);
}
}
- } else if (msg.type === "result" && msg.subtype === "success") {
- console.log(`\n${msg.result}\n`);
}
}
- console.log();
+ } catch (error) {
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
}
-
- rl.close();
+ process.stdout.write("\n");
}
-main().catch(console.error);
\ No newline at end of file
+readline.close();
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/mcp-openai.ts b/fern/snippets/tool-router/typescript/mcp-openai.ts
index 8d1661849..613b8682e 100644
--- a/fern/snippets/tool-router/typescript/mcp-openai.ts
+++ b/fern/snippets/tool-router/typescript/mcp-openai.ts
@@ -1,41 +1,65 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { Composio } from "@composio/core";
-import { Agent, hostedMcpTool, run } from "@openai/agents";
+import { Agent, hostedMcpTool, run, MemorySession } from "@openai/agents";
+import { createInterface } from "readline/promises";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-const userId = "user_123"; // Your user's unique identifier
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
+const composio = new Composio();
-// Initialize Composio and create a Tool Router session
-const composio = new Composio({ apiKey: composioApiKey });
+// Unique identifier of the user
+const userId = "user-1234";
+
+// Create a tool router session for the user
const session = await composio.create(userId);
-// Configure OpenAI agent with Composio MCP server
const agent = new Agent({
- name: "AI Assistant",
- 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.",
+ name: "Personal Assistant",
+ instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
model: "gpt-5.2",
tools: [
hostedMcpTool({
serverLabel: "composio",
serverUrl: session.mcp.url,
- headers: { "x-api-key": composioApiKey },
+ headers: session.mcp.headers, // Authentication headers for the Composio MCP server
}),
],
});
-// Optional: Pre-authorize tools before use (otherwise you'll get a link during execution)
-// const connectionRequest = await session.authorize("github");
-// console.log(connectionRequest.redirectUrl);
-// const connectedAccount = await connectionRequest.waitForConnection(60000);
-// console.log(`Connected: ${connectedAccount.id}`);
+// Create a memory session for persistent multi-turn conversation
+const memory = new MemorySession();
+
+// Execute an initial task
+console.log("Fetching GitHub issues from the Composio repository...\n");
+try {
+ const initialResult = await run(
+ agent,
+ "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
+ { session: memory }
+ );
+ console.log(`${initialResult.finalOutput}\n`);
+} catch (error) {
+ console.error("[Error]:", error instanceof Error ? error.message : error);
+}
+
+// Continue with interactive conversation
+const readline = createInterface({ input: process.stdin, output: process.stdout });
+
+console.log(`
+What else would you like me to do?
+(Type 'exit' to exit)
+`);
+
+while (true) {
+ const input = (await readline.question("You: ")).trim();
+ if (input.toLowerCase() === "exit") break;
-// Execute a task that requires GitHub access
-const result = await run(
- agent,
- "Fetch all the open GitHub issues on the composio repository " +
- "and group them by bugs/features/docs."
-);
+ console.log("Assistant: ");
-console.log(`Result: ${result.finalOutput}`);
\ No newline at end of file
+ try {
+ const result = await run(agent, input, { session: memory });
+ console.log(`${result.finalOutput}\n`);
+ } catch (error) {
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
+ }
+}
+readline.close();
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/mcp-vercel.ts b/fern/snippets/tool-router/typescript/mcp-vercel.ts
index 498aca044..9144739b5 100644
--- a/fern/snippets/tool-router/typescript/mcp-vercel.ts
+++ b/fern/snippets/tool-router/typescript/mcp-vercel.ts
@@ -1,38 +1,38 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { anthropic } from "@ai-sdk/anthropic";
import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";
import { Composio } from "@composio/core";
import { stepCountIs, streamText } from "ai";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-const userId = "user-1234"; // Your user's unique identifier
-const composio = new Composio({ apiKey: composioApiKey });
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
+const composio = new Composio();
+// Unique identifier of the user
+const userId = "user-1234";
+
+// Create a tool router session for the user
const { mcp } = await composio.create(userId);
-console.log(`Tool Router session created: ${mcp.url}`);
+// Create an MCP client to connect to the Composio tool router
const client = await createMCPClient({
transport: {
type: "http",
url: mcp.url,
- headers: {
- "x-api-key": composioApiKey,
- },
+ headers: mcp.headers, // Authentication headers for the Composio MCP server
},
});
-
const tools = await client.tools();
+console.log("Summarizing your emails from today");
+
const stream = await streamText({
- system: "You are a helpful personal assistant. You should use composio MCP tools to take action.",
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
model: anthropic("claude-sonnet-4-5"),
- prompt: "Summarize all the emails in my Gmail inbox today",
+ prompt: "Summarize my emails from today",
stopWhen: stepCountIs(10),
onStepFinish: (step) => {
- if (step.toolCalls.length > 0) {
- for (const toolCall of step.toolCalls) {
- console.log(`Executed ${toolCall.toolName}`);
- }
+ for (const toolCall of step.toolCalls) {
+ console.log(`[Using tool: ${toolCall.toolName}]`);
}
},
tools,
@@ -40,4 +40,7 @@ const stream = await streamText({
for await (const textPart of stream.textStream) {
process.stdout.write(textPart);
-}
\ No newline at end of file
+}
+
+console.log("\n\n---");
+console.log("Tip: If prompted to authenticate, complete the auth flow and run again.")
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/native-tools-openai.ts b/fern/snippets/tool-router/typescript/native-tools-openai.ts
index 42e312e52..5991edf79 100644
--- a/fern/snippets/tool-router/typescript/native-tools-openai.ts
+++ b/fern/snippets/tool-router/typescript/native-tools-openai.ts
@@ -1,50 +1,62 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { Composio } from "@composio/core";
import { Agent, run, MemorySession } from "@openai/agents";
import { OpenAIAgentsProvider } from "@composio/openai-agents";
import { createInterface } from "readline/promises";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-const userId = "user_123"; // Your user's unique identifier
+// Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
+const composio = new Composio({ provider: new OpenAIAgentsProvider() });
-const composio = new Composio({ apiKey: composioApiKey, provider: new OpenAIAgentsProvider() });
-const session = await composio.create(userId);
+// Unique identifier of the user
+const userId = "user-1234";
-// Get native tools from Composio
+// Create a session and get native tools for the user
+const session = await composio.create(userId);
const tools = await session.tools();
-// Create OpenAI agent with Composio tools
const agent = new Agent({
- name: "AI Assistant",
- 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.",
+ name: "Personal Assistant",
+ instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
model: "gpt-5.2",
- tools: tools,
+ tools,
});
-// Create session for multi-turn conversation
-const conversationSession = new MemorySession();
-
-// Execute an initial task that requires GitHub access
-console.log("Executing initial task: Fetching GitHub issues...\n");
-const initialResult = await run(
- agent,
- "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
- { session: conversationSession }
-);
-console.log(`Result: ${initialResult.finalOutput}\n`);
+// Create a memory session for persistent multi-turn conversation
+const memory = new MemorySession();
+
+// Execute an initial task
+console.log("Fetching GitHub issues from the Composio repository...\n");
+try {
+ const initialResult = await run(
+ agent,
+ "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
+ { session: memory }
+ );
+ console.log(`${initialResult.finalOutput}\n`);
+} catch (error) {
+ console.error("[Error]:", error instanceof Error ? error.message : error);
+}
// Continue with interactive conversation
-const rl = createInterface({ input: process.stdin, output: process.stdout });
-console.log("Assistant: What else would you like me to do? Type 'exit' to end the conversation.\n");
+const readline = createInterface({ input: process.stdin, output: process.stdout });
+
+console.log(`
+What else would you like me to do?
+(Type 'exit' to exit)
+`);
+
while (true) {
- const userInput = await rl.question("> ");
- if (userInput.toLowerCase() === "exit") break;
-
- // Run agent with session to maintain context
- const result = await run(agent, userInput, { session: conversationSession });
- console.log(`Assistant: ${result.finalOutput}\n`);
+ const input = (await readline.question("You: ")).trim();
+ if (input.toLowerCase() === "exit") break;
+
+ console.log("Assistant: ");
+
+ try {
+ const result = await run(agent, input, { session: memory });
+ console.log(`${result.finalOutput}\n`);
+ } catch (error) {
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
+ }
}
-rl.close();
\ No newline at end of file
+readline.close();
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/native-tools-vercel.ts b/fern/snippets/tool-router/typescript/native-tools-vercel.ts
index bc8fc31cf..8d39eaa6d 100644
--- a/fern/snippets/tool-router/typescript/native-tools-vercel.ts
+++ b/fern/snippets/tool-router/typescript/native-tools-vercel.ts
@@ -1,40 +1,38 @@
import "dotenv/config";
+import { anthropic } from "@ai-sdk/anthropic";
import { Composio } from "@composio/core";
import { VercelProvider } from "@composio/vercel";
-import { generateText, stepCountIs, ModelMessage } from "ai";
-import { createInterface } from "readline/promises";
-import { anthropic } from "@ai-sdk/anthropic";
+import { stepCountIs, streamText } from "ai";
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
- provider: new VercelProvider(),
-});
+// Initialize Composio with Vercel provider (API key from env var COMPOSIO_API_KEY)
+const composio = new Composio({ provider: new VercelProvider() });
-const session = await composio.create("user_123");
+// Unique identifier of the user
+const userId = "user-1234";
+
+// Create a session and get native tools for the user
+const session = await composio.create(userId);
const tools = await session.tools();
-const rl = createInterface({ input: process.stdin, output: process.stdout });
-const messages: ModelMessage[] = [];
+console.log("Fetching GitHub issues from the Composio repository...");
-// Initial task
-const initialPrompt = "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.";
-console.log("Executing initial task: Fetching GitHub issues...\n");
+// Stream the response with tool calling
+const stream = await streamText({
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
+ model: anthropic("claude-sonnet-4-5"),
+ prompt: "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
+ stopWhen: stepCountIs(10),
+ onStepFinish: (step) => {
+ for (const toolCall of step.toolCalls) {
+ console.log(`[Using tool: ${toolCall.toolName}]`);
+ }
+ },
+ tools,
+});
-while (true) {
- const userInput = messages.length === 0 ? initialPrompt : await rl.question("> ");
- if (userInput.toLowerCase() === "exit") break;
-
- messages.push({ role: "user", content: userInput });
-
- const result = await generateText({
- model: anthropic("claude-sonnet-4-5"),
- messages: messages,
- tools: tools,
- stopWhen: stepCountIs(10),
- });
-
- messages.push({ role: "assistant", content: result.text });
- console.log(`Assistant: ${result.text}\n`);
+for await (const textPart of stream.textStream) {
+ process.stdout.write(textPart);
}
-rl.close();
\ No newline at end of file
+console.log("\n\n---");
+console.log("Tip: If prompted to authenticate, complete the auth flow and run again.");
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/quickstart-mcp-claude.ts b/fern/snippets/tool-router/typescript/quickstart-mcp-claude.ts
index 6000de6e5..a30788dd3 100644
--- a/fern/snippets/tool-router/typescript/quickstart-mcp-claude.ts
+++ b/fern/snippets/tool-router/typescript/quickstart-mcp-claude.ts
@@ -1,61 +1,74 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { query, type Options } from "@anthropic-ai/claude-agent-sdk";
import { Composio } from "@composio/core";
import { createInterface } from "readline/promises";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-if (!composioApiKey) {
- console.warn("⚠️ Warning: COMPOSIO_API_KEY not set - Claude won't be able to use Composio tools");
-}
-const userId = "user_123"; // Your user's unique identifier
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
+const composio = new Composio();
+
+// Unique identifier of the user
+const userId = "user_123";
-const composio = new Composio({ apiKey: composioApiKey });
+// 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 instead of just explaining how to do them.",
+ 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: { "x-api-key": composioApiKey }
+ headers: session.mcp.headers // Authentication headers for the Composio MCP server
},
},
- permissionMode: "bypassPermissions",
- allowDangerouslySkipPermissions: true,
+ permissionMode: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)
};
-const rl = createInterface({ input: process.stdin, output: process.stdout });
+// 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?");
-console.log("(Type 'quit' to exit)\n");
+console.log(`
+What task would you like me to help you with?
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
+(Type 'exit' to exit)
+Example tasks:
+ • 'Summarize my emails from today'
+ • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
+`);
let isFirstQuery = true;
+// Multi-turn conversation with agentic tool calling
while (true) {
- const input = (await rl.question("You: ")).trim();
- if (input.toLowerCase() === "quit" || input.toLowerCase() === "exit") break;
+ const answer = await readline.question('You: ');
+ const input = answer.trim();
+ if (input.toLowerCase() === "exit") break;
process.stdout.write("Claude: ");
- // First query starts a new conversation, subsequent queries continue it
+
+ // Use `continue: true` to maintain conversation context
const queryOptions = isFirstQuery ? options : { ...options, continue: true };
isFirstQuery = false;
- for await (const msg of query({ prompt: input, options: queryOptions })) {
- if (msg.type === "assistant") {
- for (const block of msg.message.content) {
- if (block.type === "tool_use") {
- console.log(`\n[Using tool: ${block.name}]`);
- } else if (block.type === "text") {
- process.stdout.write(block.text);
+ 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);
+ }
}
}
- } else if (msg.type === "result" && msg.subtype === "success") {
- console.log(`\n[Tool Result: ${msg.result}]`);
}
+ } catch (error) {
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
}
- console.log();
+ process.stdout.write("\n");
}
-rl.close();
\ No newline at end of file
+readline.close();
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/quickstart-mcp-openai.ts b/fern/snippets/tool-router/typescript/quickstart-mcp-openai.ts
index 6feffa94d..01f7d550f 100644
--- a/fern/snippets/tool-router/typescript/quickstart-mcp-openai.ts
+++ b/fern/snippets/tool-router/typescript/quickstart-mcp-openai.ts
@@ -1,13 +1,16 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { Composio } from "@composio/core";
import { Agent, run, hostedMcpTool, MemorySession } from "@openai/agents";
import { createInterface } from "readline/promises";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-const userId = "user-1234"; // Your user's unique identifier
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
+const composio = new Composio();
-const composio = new Composio({ apiKey: composioApiKey });
-const { mcp } = await composio.create(userId);
+// Unique identifier of the user
+const userId = "user-1234";
+
+// Create a tool router session for the user
+const session = await composio.create(userId);
const agent = new Agent({
name: "Personal Assistant",
@@ -16,23 +19,40 @@ const agent = new Agent({
tools: [
hostedMcpTool({
serverLabel: "composio",
- serverUrl: mcp.url,
- headers: {
- "x-api-key": composioApiKey,
- },
+ serverUrl: session.mcp.url,
+ headers: session.mcp.headers // Authentication headers for the Composio MCP server
}),
],
});
-// Create a session for persistent multi-turn conversation memory
-const session = new MemorySession();
+// Create a memory session for persistent multi-turn conversation
+const memory = new MemorySession();
+
+// Set up interactive terminal input/output for the conversation
+const readline = createInterface({ input: process.stdin, output: process.stdout });
-const rl = createInterface({ input: process.stdin, output: process.stdout });
-console.log("Assistant: What would you like me to do today?\n");
+console.log(`
+What task would you like me to help you with?
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
+(Type 'exit' to exit)
+Example tasks:
+ • 'Summarize my emails from today'
+ • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
+`);
+
+// Multi-turn conversation with agentic tool calling
while (true) {
- const input = await rl.question("> ");
- if (input === "exit") break;
- const result = await run(agent, input, { session });
- console.log(`Assistant: ${result.finalOutput}\n`);
+ const input = (await readline.question("You: ")).trim();
+ if (input.toLowerCase() === "exit") break;
+
+ console.log("Assistant: ");
+
+ try {
+ // Multi-turn agentic loop: GPT calls tools and reasons until task is complete
+ const result = await run(agent, input, { session: memory });
+ console.log(`${result.finalOutput}`);
+ } catch (error) {
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
+ }
}
-rl.close();
+readline.close();
diff --git a/fern/snippets/tool-router/typescript/quickstart-mcp-vercel.ts b/fern/snippets/tool-router/typescript/quickstart-mcp-vercel.ts
index abfdf2deb..1656f9a7d 100644
--- a/fern/snippets/tool-router/typescript/quickstart-mcp-vercel.ts
+++ b/fern/snippets/tool-router/typescript/quickstart-mcp-vercel.ts
@@ -1,38 +1,38 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { anthropic } from "@ai-sdk/anthropic";
import { experimental_createMCPClient as createMCPClient } from "@ai-sdk/mcp";
import { Composio } from "@composio/core";
import { stepCountIs, streamText } from "ai";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-const userId = "user-1234"; // Your user's unique identifier
-const composio = new Composio({ apiKey: composioApiKey });
+// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" })
+const composio = new Composio();
+// Unique identifier of the user
+const userId = "user-1234";
+
+// Create a tool router session for the user
const { mcp } = await composio.create(userId);
-console.log(`Tool Router session created: ${mcp.url}`);
+// Create an MCP client to connect to the Composio tool router
const client = await createMCPClient({
transport: {
type: "http",
url: mcp.url,
- headers: {
- "x-api-key": composioApiKey,
- },
+ headers: mcp.headers, // Authentication headers for the Composio MCP server
},
});
-
const tools = await client.tools();
+console.log("Summarizing your emails from today");
+
const stream = await streamText({
- system: "You are a helpful personal assistant. You should use composio MCP tools to take action.",
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
model: anthropic("claude-sonnet-4-5"),
- prompt: "Summarize all the emails in my Gmail inbox today",
+ prompt: "Summarize my emails from today",
stopWhen: stepCountIs(10),
onStepFinish: (step) => {
- if (step.toolCalls.length > 0) {
- for (const toolCall of step.toolCalls) {
- console.log(`Executed ${toolCall.toolName}`);
- }
+ for (const toolCall of step.toolCalls) {
+ console.log(`[Using tool: ${toolCall.toolName}]`);
}
},
tools,
@@ -41,3 +41,6 @@ const stream = await streamText({
for await (const textPart of stream.textStream) {
process.stdout.write(textPart);
}
+
+console.log("\n\n---");
+console.log("Tip: If prompted to authenticate, complete the auth flow and run again.");
diff --git a/fern/snippets/tool-router/typescript/quickstart-native-openai.ts b/fern/snippets/tool-router/typescript/quickstart-native-openai.ts
index a920250c0..4c1c27838 100644
--- a/fern/snippets/tool-router/typescript/quickstart-native-openai.ts
+++ b/fern/snippets/tool-router/typescript/quickstart-native-openai.ts
@@ -1,38 +1,52 @@
-import "dotenv/config"; // Load environment variables from .env file
+import "dotenv/config";
import { Composio } from "@composio/core";
import { Agent, run, MemorySession } from "@openai/agents";
import { OpenAIAgentsProvider } from "@composio/openai-agents";
import { createInterface } from "readline/promises";
-const composioApiKey = process.env.COMPOSIO_API_KEY;
-const userId = "user_123"; // Your user's unique identifier
+// Initialize Composio with OpenAI Agents provider (API key from env var COMPOSIO_API_KEY)
+const composio = new Composio({ provider: new OpenAIAgentsProvider() });
-const composio = new Composio({ apiKey: composioApiKey, provider: new OpenAIAgentsProvider() });
+// Unique identifier of the user
+const userId = "user-123aer4";
+// Create a tool router session for the user
const session = await composio.create(userId);
-
-// Get native tools from Composio
const tools = await session.tools();
-// Create OpenAI agent with Composio tools
const agent = new Agent({
- name: "AI Assistant",
- instructions: "You are a helpful assistant with access to external tools. Use the available tools to complete user requests.",
+ name: "Personal Assistant",
+ instructions: "You are a helpful personal assistant. Use Composio tools to take action.",
model: "gpt-5.2",
- tools: tools,
+ tools,
});
-// Create session for multi-turn conversation
-const conversationSession = new MemorySession();
+// Set up interactive terminal input/output for the conversation
+const readline = createInterface({ input: process.stdin, output: process.stdout });
+// Create a memory session for persistent multi-turn conversation
+const memory = new MemorySession();
-const rl = createInterface({ input: process.stdin, output: process.stdout });
-console.log("Assistant: What would you like me to do today? Type 'exit' to end the conversation.\n");
+console.log(`
+What task would you like me to help you with?
+I can use tools like Gmail, GitHub, Linear, Notion, and more.
+(Type 'exit' to exit)
+Example tasks:
+ • 'Summarize my emails from today'
+ • 'List all open issues on the composio github repository and create a Google Sheet with the issues'
+`);
+// Multi-turn conversation with agentic tool calling
while (true) {
- const userInput = await rl.question("> ");
- if (userInput.toLowerCase() === "exit") break;
-
- // Run agent with session to maintain context
- const result = await run(agent, userInput, { session: conversationSession });
- console.log(`Assistant: ${result.finalOutput}\n`);
+ const query = await readline.question("You: ");
+ const input = query.trim();
+
+ if (input.toLowerCase() === "exit") break;
+ process.stdout.write("Assistant: ");
+
+ try {
+ const result = await run(agent, input, { session: memory });
+ process.stdout.write(`${result.finalOutput}`);
+ } catch (error) {
+ console.error("\n[Error]:", error instanceof Error ? error.message : error);
+ }
}
-rl.close();
\ No newline at end of file
+readline.close();
\ No newline at end of file
diff --git a/fern/snippets/tool-router/typescript/quickstart-native-vercel.ts b/fern/snippets/tool-router/typescript/quickstart-native-vercel.ts
index e7e47c34c..73c34de76 100644
--- a/fern/snippets/tool-router/typescript/quickstart-native-vercel.ts
+++ b/fern/snippets/tool-router/typescript/quickstart-native-vercel.ts
@@ -1,38 +1,39 @@
import "dotenv/config";
+import { anthropic } from "@ai-sdk/anthropic";
import { Composio } from "@composio/core";
import { VercelProvider } from "@composio/vercel";
-import { generateText, stepCountIs, ModelMessage } from "ai";
-import { createInterface } from "readline/promises";
-import { anthropic } from "@ai-sdk/anthropic";
+import { stepCountIs, streamText } from "ai";
-const composio = new Composio({
- apiKey: process.env.COMPOSIO_API_KEY,
- provider: new VercelProvider(),
-});
+// Initialize Composio with Vercel provider (API key from env var COMPOSIO_API_KEY)
+const composio = new Composio({ provider: new VercelProvider() });
-const session = await composio.create("user_123");
+// Unique identifier of the user
+const userId = "user-1234";
+
+// Create a session and get native tools for the user
+const session = await composio.create(userId);
const tools = await session.tools();
-const rl = createInterface({ input: process.stdin, output: process.stdout });
-const messages: ModelMessage[] = [];
+process.stdout.write("Summarizing your emails from today");
+process.stdout.write("\n");
-console.log("Assistant: What would you like me to do today?\n");
+const stream = await streamText({
+ system: "You are a helpful personal assistant. Use Composio tools to take action.",
+ model: anthropic("claude-sonnet-4-5"),
+ prompt: "Summarize my emails from today",
+ stopWhen: stepCountIs(10),
+ onStepFinish: (step) => {
+ for (const toolCall of step.toolCalls) {
+ process.stdout.write(`[Using tool: ${toolCall.toolName}]`);
+ process.stdout.write("\n");
+ }
+ },
+ tools,
+});
-while (true) {
- const userInput = await rl.question("> ");
- if (userInput === "exit") break;
-
- messages.push({ role: "user", content: userInput });
-
- const result = await generateText({
- model: anthropic("claude-sonnet-4-5") ,
- messages: messages,
- tools: tools,
- stopWhen: stepCountIs(10),
- });
-
- messages.push({ role: "assistant", content: result.text });
- console.log(`Assistant: ${result.text}\n`);
+for await (const textPart of stream.textStream) {
+ process.stdout.write(textPart);
}
-rl.close();
\ No newline at end of file
+process.stdout.write("\n");
+process.stdout.write("Tip: If prompted to authenticate, complete the auth flow and run again.");