Using with MCP clients

View as markdown

Every Tool Router session provides a unique MCP server URL. This URL exposes the exact session you created - with the specific user, toolkits, and auth configs you configured. Any MCP client that supports HTTP transport can connect using just the URL and your API key.

Jump to examples for:

Claude Agent SDK

Installation

pip install python-dotenv composio claude-agent-sdk
npm install dotenv @composio/core @anthropic-ai/claude-agent-sdk

Usage

Create a Tool Router session and execute tasks with Claude:

  • Set your COMPOSIO_API_KEY environment variable with your API key from Settings.
  • Set your ANTHROPIC_API_KEY environment variable with your Anthropic API key.
import asyncio
from dotenv import load_dotenv
from claude_agent_sdk.client import ClaudeSDKClient
from claude_agent_sdk.types import (
    ClaudeAgentOptions,
    AssistantMessage,
    TextBlock,
    ToolUseBlock,
)
from composio import Composio

load_dotenv()

# Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly)
composio = Composio()

# Unique identifier of the user
user_id = "user_123"
# Create a tool router session for the user
session = composio.create(user_id=user_id)

# Configure Claude with Composio MCP server
options = ClaudeAgentOptions(
    system_prompt=(
        "You are a helpful assistant with access to external tools. "
        "Always use the available tools to complete user requests."
    ),
    mcp_servers={
        "composio": {
            "type": "http",
            "url": session.mcp.url,
            "headers": session.mcp.headers,  # Authentication headers for the Composio MCP server
        }
    },
    permission_mode="bypassPermissions",  # Auto-approve tools (demo only)
)

async def main():
    print("""
What task would you like me to help you with?
I can use tools like Gmail, GitHub, Linear, Notion, and more.
(Type 'exit' to exit)
Example tasks:
  • 'Summarize my emails from today'
  • 'List all open issues on the composio github repository and create a notion page with the issues'
""")

    async with ClaudeSDKClient(options) as client:
        # Multi-turn conversation with agentic tool calling
        while True:
            user_input = input("\nYou: ").strip()
            if user_input.lower() == "exit":
                break

            print("\nClaude: ", end="", flush=True)
            try:
                await client.query(user_input)
                async for msg in client.receive_response():
                    if isinstance(msg, AssistantMessage):
                        for block in msg.content:
                            if isinstance(block, ToolUseBlock):
                                print(f"\n[Using tool: {block.name}]", end="")
                            elif isinstance(block, TextBlock):
                                print(block.text, end="", flush=True)
            except Exception as e:
                print(f"\n[Error]: {e}")

if __name__ == "__main__":
    asyncio.run(main())
import "dotenv/config";
import { 
function query(_params: {
    prompt: string | AsyncIterable<SDKUserMessage>;
    options?: Options;
}): Query
query
, type
type Options = {
    abortController?: AbortController;
    additionalDirectories?: string[];
    agents?: Record<string, AgentDefinition>;
    allowedTools?: string[];
    canUseTool?: CanUseTool;
    continue?: boolean;
    cwd?: string;
    disallowedTools?: string[];
    tools?: string[] | {
        type: "preset";
        preset: "claude_code";
    };
    env?: {
        [envVar: string]: string | undefined;
    };
    executable?: "bun" | "deno" | "node";
    executableArgs?: string[];
    extraArgs?: Record<string, string | null>;
    fallbackModel?: string;
    ... 24 more ...;
    spawnClaudeCodeProcess?: (options: SpawnOptions) => SpawnedProcess;
}
Options for the query function. Contains callbacks and other non-serializable fields.
Options
} from "@anthropic-ai/claude-agent-sdk";
import { class Composio<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider>
This is the core class for Composio. It is used to initialize the Composio SDK and provide a global configuration.
Composio
} from "@composio/core";
import { function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface (+1 overload)
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. ```js import readlinePromises from 'node:readline/promises'; const rl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout, }); ``` Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: ```js rl.on('line', (line) => { console.log(`Received: ${line}`); }); ``` If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property and emits a `'resize'` event on the `output` if or when the columns ever change (`process.stdout` does this automatically when it is a TTY).
@sincev17.0.0
createInterface
} from "readline/promises";
// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" }) const const composio: Composio<OpenAIProvider>composio = new new Composio<OpenAIProvider>(config?: ComposioConfig<OpenAIProvider> | undefined): Composio<OpenAIProvider>
Creates a new instance of the Composio SDK. The constructor initializes the SDK with the provided configuration options, sets up the API client, and initializes all core models (tools, toolkits, etc.).
@paramconfig - Configuration options for the Composio SDK@paramconfig.apiKey - The API key for authenticating with the Composio API@paramconfig.baseURL - The base URL for the Composio API (defaults to production URL)@paramconfig.allowTracking - Whether to allow anonymous usage analytics@paramconfig.provider - The provider to use for this Composio instance (defaults to OpenAIProvider)@example```typescript // Initialize with default configuration const composio = new Composio(); // Initialize with custom API key and base URL const composio = new Composio({ apiKey: 'your-api-key', baseURL: 'https://api.composio.dev' }); // Initialize with custom provider const composio = new Composio({ apiKey: 'your-api-key', provider: new CustomProvider() }); ```
Composio
();
// Unique identifier of the user const const userId: "user_123"userId = "user_123"; // Create a tool router session for the user const const session: ToolRouterSession<unknown, unknown, OpenAIProvider>session = await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.create: (userId: string, routerConfig?: ToolRouterCreateSessionConfig) => Promise<ToolRouterSession<unknown, unknown, OpenAIProvider>>
Creates a new tool router session for a user.
@paramuserId The user id to create the session for@paramconfig The config for the tool router session@returnsThe tool router session@example```typescript import { Composio } from '@composio/core'; const composio = new Composio(); const userId = 'user_123'; const session = await composio.create(userId, { manageConnections: true, }); console.log(session.sessionId); console.log(session.url); console.log(session.tools()); ```
create
(const userId: "user_123"userId);
const const options: Optionsoptions:
type Options = {
    abortController?: AbortController;
    additionalDirectories?: string[];
    agents?: Record<string, AgentDefinition>;
    allowedTools?: string[];
    canUseTool?: CanUseTool;
    continue?: boolean;
    cwd?: string;
    disallowedTools?: string[];
    tools?: string[] | {
        type: "preset";
        preset: "claude_code";
    };
    env?: {
        [envVar: string]: string | undefined;
    };
    executable?: "bun" | "deno" | "node";
    executableArgs?: string[];
    extraArgs?: Record<string, string | null>;
    fallbackModel?: string;
    ... 24 more ...;
    spawnClaudeCodeProcess?: (options: SpawnOptions) => SpawnedProcess;
}
Options for the query function. Contains callbacks and other non-serializable fields.
Options
= {
systemPrompt?: string | {
    type: "preset";
    preset: "claude_code";
    append?: string;
} | undefined
System prompt configuration. - `string` - Use a custom system prompt - `{ type: 'preset', preset: 'claude_code' }` - Use Claude Code's default system prompt - `{ type: 'preset', preset: 'claude_code', append: '...' }` - Use default prompt with appended instructions
@exampleCustom prompt ```typescript systemPrompt: 'You are a helpful coding assistant.' ```@exampleDefault with additions ```typescript systemPrompt: { type: 'preset', preset: 'claude_code', append: 'Always explain your reasoning.' } ```
systemPrompt
: `You are a helpful assistant with access to external tools. ` +
`Always use the available tools to complete user requests.`, mcpServers?: Record<string, McpServerConfig> | undefined
MCP (Model Context Protocol) server configurations. Keys are server names, values are server configurations.
@example```typescript mcpServers: { 'my-server': { command: 'node', args: ['./my-mcp-server.js'] } } ```
mcpServers
: {
composio: {
    type: "http";
    url: string;
    headers: Record<string, string> | undefined;
}
composio
: {
type: "http"type: "http", url: stringurl: const session: ToolRouterSession<unknown, unknown, OpenAIProvider>session.
ToolRouterSession<unknown, unknown, OpenAIProvider>.mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
.url: stringurl,
headers?: Record<string, string> | undefinedheaders: const session: ToolRouterSession<unknown, unknown, OpenAIProvider>session.
ToolRouterSession<unknown, unknown, OpenAIProvider>.mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
.headers?: Record<string, string> | undefinedheaders // Authentication headers for the Composio MCP server
}, }, permissionMode?: PermissionMode | undefined
Permission mode for the session. - `'default'` - Standard permission behavior, prompts for dangerous operations - `'acceptEdits'` - Auto-accept file edit operations - `'bypassPermissions'` - Bypass all permission checks (requires `allowDangerouslySkipPermissions`) - `'plan'` - Planning mode, no execution of tools - `'dontAsk'` - Don't prompt for permissions, deny if not pre-approved
permissionMode
: "bypassPermissions", // Auto-approve tools (demo only - use "default" in production)
}; // Set up interactive terminal input/output for the conversation const const readline: Interfacereadline = function createInterface(options: ReadLineOptions): Interface (+1 overload)
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. ```js import readlinePromises from 'node:readline/promises'; const rl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout, }); ``` Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: ```js rl.on('line', (line) => { console.log(`Received: ${line}`); }); ``` If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property and emits a `'resize'` event on the `output` if or when the columns ever change (`process.stdout` does this automatically when it is a TTY).
@sincev17.0.0
createInterface
({ input: NodeJS.ReadableStream
The [`Readable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream to listen to
input
: var process: NodeJS.Processprocess.
NodeJS.Process.stdin: NodeJS.ReadStream & {
    fd: 0;
}
The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is a `Readable` stream. For details of how to read from `stdin` see `readable.read()`. As a `Duplex` stream, `process.stdin` can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10\. For more information see `Stream compatibility`. In "old" streams mode the `stdin` stream is paused by default, so one must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode.
stdin
, output?: NodeJS.WritableStream | undefined
The [`Writable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream to write readline data to.
output
: var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
});
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
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 let isFirstQuery: booleanisFirstQuery = true; // Multi-turn conversation with agentic tool calling while (true) { const const answer: stringanswer = await const readline: Interfacereadline.Interface.question(query: string): Promise<string> (+1 overload)
The `rl.question()` method displays the `query` by writing it to the `output`, waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. When called, `rl.question()` will resume the `input` stream if it has been paused. If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. If the question is called after `rl.close()`, it returns a rejected promise. Example usage: ```js const answer = await rl.question('What is your favorite food? '); console.log(`Oh, so your favorite food is ${answer}`); ``` Using an `AbortSignal` to cancel a question. ```js const signal = AbortSignal.timeout(10_000); signal.addEventListener('abort', () => { console.log('The food question timed out'); }, { once: true }); const answer = await rl.question('What is your favorite food? ', { signal }); console.log(`Oh, so your favorite food is ${answer}`); ```
@sincev17.0.0@paramquery A statement or query to write to `output`, prepended to the prompt.@returnA promise that is fulfilled with the user's input in response to the `query`.
question
('You: ');
const const input: stringinput = const answer: stringanswer.String.trim(): string
Removes the leading and trailing white space and line terminator characters from a string.
trim
();
if (const input: stringinput.String.toLowerCase(): string
Converts all the alphabetic characters in a string to lowercase.
toLowerCase
() === "exit") break;
var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
.Socket.write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean (+1 overload)
Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. The optional `callback` parameter will be executed when the data is finally written out, which may not be immediately. See `Writable` stream `write()` method for more information.
@sincev0.1.90@paramencoding Only used when data is `string`.
write
("Claude: ");
const const queryOptions: OptionsqueryOptions = let isFirstQuery: booleanisFirstQuery ? const options: Optionsoptions : { ...const options: Optionsoptions, continue: booleancontinue: true }; let isFirstQuery: booleanisFirstQuery = false; try { for await (const const stream: SDKMessagestream of
function query(_params: {
    prompt: string | AsyncIterable<SDKUserMessage>;
    options?: Options;
}): Query
query
({ prompt: string | AsyncIterable<SDKUserMessage>prompt: const input: stringinput, options?: Options | undefinedoptions: const queryOptions: OptionsqueryOptions })) {
// Only process assistant messages (the SDK also sends result/error messages) if (const stream: SDKMessagestream.type: "user" | "assistant" | "result" | "system" | "stream_event" | "tool_progress" | "auth_status"type === "assistant") { const { const content: BetaContentBlock[]
Content generated by the model. This is an array of content blocks, each of which has a `type` that determines its shape. Example: ```json [{ "type": "text", "text": "Hi, I'm Claude." }] ``` If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output. For example, if the input `messages` were: ```json [ { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" }, { "role": "assistant", "content": "The best answer is (" } ] ``` Then the response `content` might be: ```json [{ "type": "text", "text": "B)" }] ```
content
} = const stream: SDKAssistantMessagestream.message: BetaMessagemessage;
for (const const block: BetaContentBlockblock of const content: BetaContentBlock[]
Content generated by the model. This is an array of content blocks, each of which has a `type` that determines its shape. Example: ```json [{ "type": "text", "text": "Hi, I'm Claude." }] ``` If the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output. For example, if the input `messages` were: ```json [ { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" }, { "role": "assistant", "content": "The best answer is (" } ] ``` Then the response `content` might be: ```json [{ "type": "text", "text": "B)" }] ```
content
) {
if (const block: BetaContentBlockblock.type: "text" | "thinking" | "redacted_thinking" | "tool_use" | "server_tool_use" | "web_search_tool_result" | "web_fetch_tool_result" | "code_execution_tool_result" | "bash_code_execution_tool_result" | "text_editor_code_execution_tool_result" | "tool_search_tool_result" | "mcp_tool_use" | "mcp_tool_result" | "container_upload"type === "tool_use") { var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
.Socket.write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean (+1 overload)
Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. The optional `callback` parameter will be executed when the data is finally written out, which may not be immediately. See `Writable` stream `write()` method for more information.
@sincev0.1.90@paramencoding Only used when data is `string`.
write
(`\n[Using tool: ${const block: BetaToolUseBlockblock.BetaToolUseBlock.name: stringname}]`);
} else if (const block: BetaTextBlock | BetaThinkingBlock | BetaRedactedThinkingBlock | BetaServerToolUseBlock | BetaWebSearchToolResultBlock | BetaWebFetchToolResultBlock | BetaCodeExecutionToolResultBlock | BetaBashCodeExecutionToolResultBlock | BetaTextEditorCodeExecutionToolResultBlock | BetaToolSearchToolResultBlock | BetaMCPToolUseBlock | BetaMCPToolResultBlock | BetaContainerUploadBlockblock.type: "text" | "thinking" | "redacted_thinking" | "server_tool_use" | "web_search_tool_result" | "web_fetch_tool_result" | "code_execution_tool_result" | "bash_code_execution_tool_result" | "text_editor_code_execution_tool_result" | "tool_search_tool_result" | "mcp_tool_use" | "mcp_tool_result" | "container_upload"type === "text") { var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
.Socket.write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean (+1 overload)
Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. The optional `callback` parameter will be executed when the data is finally written out, which may not be immediately. See `Writable` stream `write()` method for more information.
@sincev0.1.90@paramencoding Only used when data is `string`.
write
(const block: BetaTextBlockblock.BetaTextBlock.text: stringtext);
} } } } } catch (var error: unknownerror) { var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
error
("\n[Error]:", var error: unknownerror instanceof var Error: ErrorConstructorError ? var error: Errorerror.Error.message: stringmessage : var error: unknownerror);
} var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
.Socket.write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean (+1 overload)
Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. The optional `callback` parameter will be executed when the data is finally written out, which may not be immediately. See `Writable` stream `write()` method for more information.
@sincev0.1.90@paramencoding Only used when data is `string`.
write
("\n");
} const readline: Interfacereadline.Interface.close(): void
The `rl.close()` method closes the `Interface` instance and relinquishes control over the `input` and `output` streams. When called, the `'close'` event will be emitted. Calling `rl.close()` does not immediately stop other events (including `'line'`) from being emitted by the `Interface` instance.
@sincev0.1.98
close
();

OpenAI Agents SDK

Installation

pip install python-dotenv composio openai-agents
npm install dotenv @composio/core @openai/agents zod@3

Usage

Create a Tool Router session and execute tasks with OpenAI agents:

  • Set COMPOSIO_API_KEY environment variable with your API key from Settings.
  • Set OPENAI_API_KEY environment variable with your OpenAI API key.
from dotenv import load_dotenv
from composio import Composio
from agents import Agent, Runner, HostedMCPTool

load_dotenv()

# Initialize Composio (API key from env var COMPOSIO_API_KEY)
composio = Composio()
# Unique identifier of the user
user_id = "user_123"

# Create a Tool Router session for the user
session = composio.create(user_id=user_id)

# Configure OpenAI agent with Composio MCP server
agent = Agent(
    name="Personal Assistant",
    instructions="You are a helpful personal assistant. Use Composio tools to take action.",
    model="gpt-5.2",
    tools=[
        HostedMCPTool(
            tool_config={
                "type": "mcp",
                "server_label": "composio",
                "server_url": session.mcp.url,
                "require_approval": "never",
                "headers": session.mcp.headers,
            }
        )
    ],
)

# Execute the task
print("Fetching GitHub issues from the Composio repository @ComposioHQ/composio...\n")
try:
    result = Runner.run_sync(
        starting_agent=agent,
        input="Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.",
    )
    print(result.final_output)
except Exception as e:
    print(f"[Error]: {e}")

print("\n\n---")
print("Tip: If prompted to authenticate, complete the auth flow and run again.")
import "dotenv/config";
import { class Composio<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider>
This is the core class for Composio. It is used to initialize the Composio SDK and provide a global configuration.
Composio
} from "@composio/core";
import { class Agent<TContext = unknown, TOutput extends AgentOutputType = "text">
The class representing an AI agent configured with instructions, tools, guardrails, handoffs and more. We strongly recommend passing `instructions`, which is the "system prompt" for the agent. In addition, you can pass `handoffDescription`, which is a human-readable description of the agent, used when the agent is used inside tools/handoffs. Agents are generic on the context type. The context is a (mutable) object you create. It is passed to tool functions, handoffs, guardrails, etc.
Agent
,
function hostedMcpTool<Context = unknown>(options: {
    allowedTools?: string[] | {
        toolNames?: string[];
    };
} & ({
    serverLabel: string;
    serverUrl?: string;
    authorization?: string;
    headers?: Record<string, string>;
} | {
    serverLabel: string;
    connectorId: string;
    authorization?: string;
    headers?: Record<string, string>;
}) & ({
    requireApproval?: never;
} | {
    requireApproval: "never";
} | {
    requireApproval: "always" | {
        never?: {
            toolNames: string[];
        };
        always?: {
            toolNames: string[];
        };
    };
    onApproval?: HostedMCPApprovalFunction<Context>;
})): HostedMCPTool<Context>
Creates a hosted MCP tool definition.
@paramoptions - Configuration for the hosted MCP tool, including server connection details and approval requirements.
hostedMcpTool
, function run<TAgent extends Agent<any, any>, TContext = undefined>(agent: TAgent, input: string | AgentInputItem[] | RunState<TContext, TAgent>, options?: NonStreamRunOptions<TContext>): Promise<RunResult<TContext, TAgent>> (+1 overload)
Executes an agent workflow with the shared default `Runner` instance.
@paramagent - The entry agent to invoke.@paraminput - A string utterance, structured input items, or a resumed `RunState`.@paramoptions - Controls streaming mode, context, session handling, and turn limits.@returnsA `RunResult` when `stream` is false, otherwise a `StreamedRunResult`.
run
, class MemorySession
Simple in-memory session store intended for demos or tests. Not recommended for production use.
MemorySession
} from "@openai/agents";
import { function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer, terminal?: boolean): Interface (+1 overload)
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. ```js import readlinePromises from 'node:readline/promises'; const rl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout, }); ``` Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: ```js rl.on('line', (line) => { console.log(`Received: ${line}`); }); ``` If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property and emits a `'resize'` event on the `output` if or when the columns ever change (`process.stdout` does this automatically when it is a TTY).
@sincev17.0.0
createInterface
} from "readline/promises";
// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" }) const const composio: Composio<OpenAIProvider>composio = new new Composio<OpenAIProvider>(config?: ComposioConfig<OpenAIProvider> | undefined): Composio<OpenAIProvider>
Creates a new instance of the Composio SDK. The constructor initializes the SDK with the provided configuration options, sets up the API client, and initializes all core models (tools, toolkits, etc.).
@paramconfig - Configuration options for the Composio SDK@paramconfig.apiKey - The API key for authenticating with the Composio API@paramconfig.baseURL - The base URL for the Composio API (defaults to production URL)@paramconfig.allowTracking - Whether to allow anonymous usage analytics@paramconfig.provider - The provider to use for this Composio instance (defaults to OpenAIProvider)@example```typescript // Initialize with default configuration const composio = new Composio(); // Initialize with custom API key and base URL const composio = new Composio({ apiKey: 'your-api-key', baseURL: 'https://api.composio.dev' }); // Initialize with custom provider const composio = new Composio({ apiKey: 'your-api-key', provider: new CustomProvider() }); ```
Composio
();
// Unique identifier of the user const const userId: "user_123"userId = "user_123"; // Create a tool router session for the user const const session: ToolRouterSession<unknown, unknown, OpenAIProvider>session = await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.create: (userId: string, routerConfig?: ToolRouterCreateSessionConfig) => Promise<ToolRouterSession<unknown, unknown, OpenAIProvider>>
Creates a new tool router session for a user.
@paramuserId The user id to create the session for@paramconfig The config for the tool router session@returnsThe tool router session@example```typescript import { Composio } from '@composio/core'; const composio = new Composio(); const userId = 'user_123'; const session = await composio.create(userId, { manageConnections: true, }); console.log(session.sessionId); console.log(session.url); console.log(session.tools()); ```
create
(const userId: "user_123"userId);
const const agent: Agent<unknown, "text">agent = new
new Agent<unknown, "text">(config: {
    name: string;
    instructions?: string | ((runContext: RunContext<unknown>, agent: Agent<unknown, "text">) => Promise<string> | string) | undefined;
    prompt?: Prompt | ((runContext: RunContext<unknown>, agent: Agent<unknown, "text">) => Promise<Prompt> | Prompt) | undefined;
    handoffDescription?: string | undefined;
    handoffs?: (Agent<any, any> | Handoff<any, "text">)[] | undefined;
    handoffOutputTypeWarningEnabled?: boolean | undefined;
    model?: string | Model | undefined;
    ... 7 more ...;
    resetToolChoice?: boolean | undefined;
}): Agent<...>
The class representing an AI agent configured with instructions, tools, guardrails, handoffs and more. We strongly recommend passing `instructions`, which is the "system prompt" for the agent. In addition, you can pass `handoffDescription`, which is a human-readable description of the agent, used when the agent is used inside tools/handoffs. Agents are generic on the context type. The context is a (mutable) object you create. It is passed to tool functions, handoffs, guardrails, etc.
Agent
({
name: stringname: "Personal Assistant", instructions?: string | ((runContext: RunContext<unknown>, agent: Agent<unknown, "text">) => Promise<string> | string) | undefined
The instructions for the agent. Will be used as the "system prompt" when this agent is invoked. Describes what the agent should do, and how it responds. Can either be a string, or a function that dynamically generates instructions for the agent. If you provide a function, it will be called with the context and the agent instance. It must return a string.
instructions
: "You are a helpful personal assistant. Use Composio tools to take action.",
model?: string | Model | undefined
The model implementation to use when invoking the LLM. By default, if not set, the agent will use the default model returned by getDefaultModel (currently "gpt-4.1").
model
: "gpt-5.2",
tools?: Tool<unknown>[] | undefined
A list of tools the agent can use.
tools
: [
hostedMcpTool<unknown>(options: {
    allowedTools?: string[] | {
        toolNames?: string[];
    };
} & (({
    serverLabel: string;
    serverUrl?: string;
    authorization?: string;
    headers?: Record<string, string>;
} | {
    serverLabel: string;
    connectorId: string;
    authorization?: string;
    headers?: Record<string, string>;
}) & ({
    requireApproval?: never;
} | {
    requireApproval: "never";
} | {
    requireApproval: "always" | {
        never?: {
            toolNames: string[];
        };
        always?: {
            toolNames: string[];
        };
    };
    onApproval?: HostedMCPApprovalFunction<unknown> | undefined;
}))): HostedMCPTool<...>
Creates a hosted MCP tool definition.
@paramoptions - Configuration for the hosted MCP tool, including server connection details and approval requirements.
hostedMcpTool
({
serverLabel: stringserverLabel: "composio", serverUrl?: string | undefinedserverUrl: const session: ToolRouterSession<unknown, unknown, OpenAIProvider>session.
ToolRouterSession<unknown, unknown, OpenAIProvider>.mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
.url: stringurl,
headers: Record<string, string> | undefinedheaders: const session: ToolRouterSession<unknown, unknown, OpenAIProvider>session.
ToolRouterSession<unknown, unknown, OpenAIProvider>.mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
.headers?: Record<string, string> | undefinedheaders, // Authentication headers for the Composio MCP server
}), ], }); // Create a memory session for persistent multi-turn conversation const const memory: MemorySessionmemory = new new MemorySession(options?: MemorySessionOptions): MemorySession
Simple in-memory session store intended for demos or tests. Not recommended for production use.
MemorySession
();
// Execute an initial task var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("Fetching GitHub issues from the Composio repository...\n");
try { const const initialResult: RunResult<undefined, Agent<unknown, "text">>initialResult = await run<Agent<unknown, "text">, undefined>(agent: Agent<unknown, "text">, input: string | any[] | RunState<undefined, Agent<unknown, "text">>, options?: NonStreamRunOptions<undefined> | undefined): Promise<RunResult<undefined, Agent<unknown, "text">>> (+1 overload)
Executes an agent workflow with the shared default `Runner` instance.
@paramagent - The entry agent to invoke.@paraminput - A string utterance, structured input items, or a resumed `RunState`.@paramoptions - Controls streaming mode, context, session handling, and turn limits.@returnsA `RunResult` when `stream` is false, otherwise a `StreamedRunResult`.
run
(
const agent: Agent<unknown, "text">agent, "Fetch all the open GitHub issues on the composio repository and group them by bugs/features/docs.", { session?: Session | undefinedsession: const memory: MemorySessionmemory } ); var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`${const initialResult: RunResult<undefined, Agent<unknown, "text">>initialResult.RunResultBase<undefined, Agent<unknown, "text">>.finalOutput: string | undefined
The final output of the agent. If the output type was set to anything other than `text`, this will be parsed either as JSON or using the Zod schema you provided.
finalOutput
}\n`);
} catch (var error: unknownerror) { var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
error
("[Error]:", var error: unknownerror instanceof var Error: ErrorConstructorError ? var error: Errorerror.Error.message: stringmessage : var error: unknownerror);
} // Continue with interactive conversation const const readline: Interfacereadline = function createInterface(options: ReadLineOptions): Interface (+1 overload)
The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. ```js import readlinePromises from 'node:readline/promises'; const rl = readlinePromises.createInterface({ input: process.stdin, output: process.stdout, }); ``` Once the `readlinePromises.Interface` instance is created, the most common case is to listen for the `'line'` event: ```js rl.on('line', (line) => { console.log(`Received: ${line}`); }); ``` If `terminal` is `true` for this instance then the `output` stream will get the best compatibility if it defines an `output.columns` property and emits a `'resize'` event on the `output` if or when the columns ever change (`process.stdout` does this automatically when it is a TTY).
@sincev17.0.0
createInterface
({ input: NodeJS.ReadableStream
The [`Readable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#readable-streams) stream to listen to
input
: var process: NodeJS.Processprocess.
NodeJS.Process.stdin: NodeJS.ReadStream & {
    fd: 0;
}
The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is a `Readable` stream. For details of how to read from `stdin` see `readable.read()`. As a `Duplex` stream, `process.stdin` can also be used in "old" mode that is compatible with scripts written for Node.js prior to v0.10\. For more information see `Stream compatibility`. In "old" streams mode the `stdin` stream is paused by default, so one must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode.
stdin
, output?: NodeJS.WritableStream | undefined
The [`Writable`](https://nodejs.org/docs/latest-v24.x/api/stream.html#writable-streams) stream to write readline data to.
output
: var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
});
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`
What else would you like me to do? (Type 'exit' to exit) `); while (true) { const const input: stringinput = (await const readline: Interfacereadline.Interface.question(query: string): Promise<string> (+1 overload)
The `rl.question()` method displays the `query` by writing it to the `output`, waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. When called, `rl.question()` will resume the `input` stream if it has been paused. If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. If the question is called after `rl.close()`, it returns a rejected promise. Example usage: ```js const answer = await rl.question('What is your favorite food? '); console.log(`Oh, so your favorite food is ${answer}`); ``` Using an `AbortSignal` to cancel a question. ```js const signal = AbortSignal.timeout(10_000); signal.addEventListener('abort', () => { console.log('The food question timed out'); }, { once: true }); const answer = await rl.question('What is your favorite food? ', { signal }); console.log(`Oh, so your favorite food is ${answer}`); ```
@sincev17.0.0@paramquery A statement or query to write to `output`, prepended to the prompt.@returnA promise that is fulfilled with the user's input in response to the `query`.
question
("You: ")).String.trim(): string
Removes the leading and trailing white space and line terminator characters from a string.
trim
();
if (const input: stringinput.String.toLowerCase(): string
Converts all the alphabetic characters in a string to lowercase.
toLowerCase
() === "exit") break;
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("Assistant: ");
try { const const result: RunResult<undefined, Agent<unknown, "text">>result = await run<Agent<unknown, "text">, undefined>(agent: Agent<unknown, "text">, input: string | any[] | RunState<undefined, Agent<unknown, "text">>, options?: NonStreamRunOptions<undefined> | undefined): Promise<RunResult<undefined, Agent<unknown, "text">>> (+1 overload)
Executes an agent workflow with the shared default `Runner` instance.
@paramagent - The entry agent to invoke.@paraminput - A string utterance, structured input items, or a resumed `RunState`.@paramoptions - Controls streaming mode, context, session handling, and turn limits.@returnsA `RunResult` when `stream` is false, otherwise a `StreamedRunResult`.
run
(const agent: Agent<unknown, "text">agent, const input: stringinput, { session?: Session | undefinedsession: const memory: MemorySessionmemory });
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`${const result: RunResult<undefined, Agent<unknown, "text">>result.RunResultBase<undefined, Agent<unknown, "text">>.finalOutput: string | undefined
The final output of the agent. If the output type was set to anything other than `text`, this will be parsed either as JSON or using the Zod schema you provided.
finalOutput
}\n`);
} catch (var error: unknownerror) { var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.error(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stderr` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const code = 5; console.error('error #%d', code); // Prints: error #5, to stderr console.error('error', code); // Prints: error 5, to stderr ``` If formatting elements (e.g. `%d`) are not found in the first string then [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options) is called on each argument and the resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
error
("\n[Error]:", var error: unknownerror instanceof var Error: ErrorConstructorError ? var error: Errorerror.Error.message: stringmessage : var error: unknownerror);
} } const readline: Interfacereadline.Interface.close(): void
The `rl.close()` method closes the `Interface` instance and relinquishes control over the `input` and `output` streams. When called, the `'close'` event will be emitted. Calling `rl.close()` does not immediately stop other events (including `'line'`) from being emitted by the `Interface` instance.
@sincev0.1.98
close
();

Vercel AI SDK

Installation

npm install dotenv @composio/core ai @ai-sdk/anthropic @ai-sdk/mcp

Usage

Use Tool Router with Vercel AI SDK's generateText for single completions:

  • Set COMPOSIO_API_KEY environment variable with your API key from Settings.
  • Set ANTHROPIC_API_KEY environment variable with your Anthropic API key.
import "dotenv/config";
import { const anthropic: AnthropicProvider
Default Anthropic provider instance.
anthropic
} from "@ai-sdk/anthropic";
import {
function experimental_createMCPClient(config: MCPClientConfig): Promise<MCPClient>
export experimental_createMCPClient
experimental_createMCPClient
as function createMCPClient(config: MCPClientConfig): Promise<MCPClient>createMCPClient } from "@ai-sdk/mcp";
import { class Composio<TProvider extends BaseComposioProvider<unknown, unknown, unknown> = OpenAIProvider>
This is the core class for Composio. It is used to initialize the Composio SDK and provide a global configuration.
Composio
} from "@composio/core";
import { function stepCountIs(stepCount: number): StopCondition<any>stepCountIs,
function streamText<TOOLS extends ToolSet, OUTPUT extends Output<any, any, any> = Output<string, string, never>>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, timeout, headers, stopWhen, experimental_output, output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError, onFinish, onAbort, onStepFinish, experimental_context, _internal: { now, generateId }, ...settings }: CallSettings & Prompt & {
    model: LanguageModel;
    tools?: TOOLS;
    toolChoice?: ToolChoice<TOOLS>;
    stopWhen?: StopCondition<NoInfer<TOOLS>> | Array<StopCondition<NoInfer<TOOLS>>>;
    experimental_telemetry?: TelemetrySettings;
    providerOptions?: ProviderOptions;
    experimental_activeTools?: Array<keyof NoInfer<TOOLS>>;
    activeTools?: Array<keyof NoInfer<TOOLS>>;
    output?: OUTPUT;
    experimental_output?: OUTPUT;
    prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;
    experimental_repairToolCall?: ToolCallRepairFunction<TOOLS>;
    experimental_transform?: StreamTextTransform<TOOLS> | Array<StreamTextTransform<TOOLS>>;
    experimental_download?: DownloadFunction | undefined;
    includeRawChunks?: boolean;
    onChunk?: StreamTextOnChunkCallback<TOOLS>;
    onError?: StreamTextOnErrorCallback;
    onFinish?: StreamTextOnFinishCallback<TOOLS>;
    onAbort?: StreamTextOnAbortCallback<...>;
    onStepFinish?: StreamTextOnStepFinishCallback<TOOLS>;
    experimental_context?: unknown;
    _internal?: {
        now?: () => number;
        generateId?: IdGenerator;
    };
}): StreamTextResult<TOOLS, OUTPUT>
Generate a text and call tools for a given prompt using a language model. This function streams the output. If you do not want to stream the output, use `generateText` instead.
@parammodel - The language model to use.@paramtools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.@paramsystem - A system message that will be part of the prompt.@paramprompt - A simple text prompt. You can either use `prompt` or `messages` but not both.@parammessages - A list of messages. You can either use `prompt` or `messages` but not both.@parammaxOutputTokens - Maximum number of tokens to generate.@paramtemperature - Temperature setting. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.@paramtopP - Nucleus sampling. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.@paramtopK - Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.@parampresencePenalty - Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The value is passed through to the provider. The range depends on the provider and model.@paramfrequencyPenalty - Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The value is passed through to the provider. The range depends on the provider and model.@paramstopSequences - Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.@paramseed - The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results.@parammaxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.@paramabortSignal - An optional abort signal that can be used to cancel the call.@paramtimeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.@paramheaders - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.@paramonChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.@paramonError - Callback that is called when an error occurs during streaming. You can use it to log errors.@paramonStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.@paramonFinish - Callback that is called when all steps are finished and the response is complete.@returnA result object for accessing different stream types and additional information.
streamText
} from "ai";
// Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly: { apiKey: "your-key" }) const const composio: Composio<OpenAIProvider>composio = new new Composio<OpenAIProvider>(config?: ComposioConfig<OpenAIProvider> | undefined): Composio<OpenAIProvider>
Creates a new instance of the Composio SDK. The constructor initializes the SDK with the provided configuration options, sets up the API client, and initializes all core models (tools, toolkits, etc.).
@paramconfig - Configuration options for the Composio SDK@paramconfig.apiKey - The API key for authenticating with the Composio API@paramconfig.baseURL - The base URL for the Composio API (defaults to production URL)@paramconfig.allowTracking - Whether to allow anonymous usage analytics@paramconfig.provider - The provider to use for this Composio instance (defaults to OpenAIProvider)@example```typescript // Initialize with default configuration const composio = new Composio(); // Initialize with custom API key and base URL const composio = new Composio({ apiKey: 'your-api-key', baseURL: 'https://api.composio.dev' }); // Initialize with custom provider const composio = new Composio({ apiKey: 'your-api-key', provider: new CustomProvider() }); ```
Composio
();
// Unique identifier of the user const const userId: "user_123"userId = "user_123"; // Create a tool router session for the user const {
const mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
} = await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.create: (userId: string, routerConfig?: ToolRouterCreateSessionConfig) => Promise<ToolRouterSession<unknown, unknown, OpenAIProvider>>
Creates a new tool router session for a user.
@paramuserId The user id to create the session for@paramconfig The config for the tool router session@returnsThe tool router session@example```typescript import { Composio } from '@composio/core'; const composio = new Composio(); const userId = 'user_123'; const session = await composio.create(userId, { manageConnections: true, }); console.log(session.sessionId); console.log(session.url); console.log(session.tools()); ```
create
(const userId: "user_123"userId);
// Create an MCP client to connect to the Composio tool router const const client: MCPClientclient = await function createMCPClient(config: MCPClientConfig): Promise<MCPClient>createMCPClient({ MCPClientConfig.transport: MCPTransportConfig | MCPTransport
Transport configuration for connecting to the MCP server
transport
: {
type: "http" | "sse"type: "http", url: string
The URL of the MCP server.
url
:
const mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
.url: stringurl,
headers?: Record<string, string> | undefined
Additional HTTP headers to be sent with requests.
headers
:
const mcp: {
    type: "http" | "sse";
    url: string;
    headers?: Record<string, string> | undefined;
}
The MCP server config of the tool router session. Contains the URL, type ('http' or 'sse'), and headers for authentication.
mcp
.headers?: Record<string, string> | undefinedheaders, // Authentication headers for the Composio MCP server
}, }); const
const tools: Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>
tools
= await const client: MCPClientclient.
MCPClient.tools<"automatic">(options?: {
    schemas?: "automatic" | undefined;
} | undefined): Promise<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>
tools
();
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("Summarizing your emails from today");
const
const stream: StreamTextResult<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>, Output<...>>
stream
= await
streamText<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>, Output<...>>({ model, tools, toolChoice, system, prompt, messages, maxRetries, abortSignal, timeout, headers, stopWhen, experimental_output, output, experimental_telemetry: telemetry, prepareStep, providerOptions, experimental_activeTools, activeTools, experimental_repairToolCall: repairToolCall, experimental_transform: transform, experimental_download: download, includeRawChunks, onChunk, onError, onFinish, onAbort, onStepFinish, experimental_context, _internal: { now, generateId }, ...settings }: CallSettings & (Prompt & {
    ...;
})): StreamTextResult<...>
Generate a text and call tools for a given prompt using a language model. This function streams the output. If you do not want to stream the output, use `generateText` instead.
@parammodel - The language model to use.@paramtools - Tools that are accessible to and can be called by the model. The model needs to support calling tools.@paramsystem - A system message that will be part of the prompt.@paramprompt - A simple text prompt. You can either use `prompt` or `messages` but not both.@parammessages - A list of messages. You can either use `prompt` or `messages` but not both.@parammaxOutputTokens - Maximum number of tokens to generate.@paramtemperature - Temperature setting. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.@paramtopP - Nucleus sampling. The value is passed through to the provider. The range depends on the provider and model. It is recommended to set either `temperature` or `topP`, but not both.@paramtopK - Only sample from the top K options for each subsequent token. Used to remove "long tail" low probability responses. Recommended for advanced use cases only. You usually only need to use temperature.@parampresencePenalty - Presence penalty setting. It affects the likelihood of the model to repeat information that is already in the prompt. The value is passed through to the provider. The range depends on the provider and model.@paramfrequencyPenalty - Frequency penalty setting. It affects the likelihood of the model to repeatedly use the same words or phrases. The value is passed through to the provider. The range depends on the provider and model.@paramstopSequences - Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated.@paramseed - The seed (integer) to use for random sampling. If set and supported by the model, calls will generate deterministic results.@parammaxRetries - Maximum number of retries. Set to 0 to disable retries. Default: 2.@paramabortSignal - An optional abort signal that can be used to cancel the call.@paramtimeout - An optional timeout in milliseconds. The call will be aborted if it takes longer than the specified timeout.@paramheaders - Additional HTTP headers to be sent with the request. Only applicable for HTTP-based providers.@paramonChunk - Callback that is called for each chunk of the stream. The stream processing will pause until the callback promise is resolved.@paramonError - Callback that is called when an error occurs during streaming. You can use it to log errors.@paramonStepFinish - Callback that is called when each step (LLM call) is finished, including intermediate steps.@paramonFinish - Callback that is called when all steps are finished and the response is complete.@returnA result object for accessing different stream types and additional information.
streamText
({
system?: string | SystemModelMessage | SystemModelMessage[] | undefined
System message to include in the prompt. Can be used with `prompt` or `messages`.
system
: "You are a helpful personal assistant. Use Composio tools to take action.",
model: LanguageModel
The language model to use.
model
: function anthropic(modelId: AnthropicMessagesModelId): LanguageModelV3
Creates a model for text generation.
anthropic
("claude-sonnet-4-5"),
prompt: string | ModelMessage[]
A prompt. It can be either a text prompt or a list of messages. You can either use `prompt` or `messages` but not both.
prompt
: "Summarize my emails from today",
stopWhen?: StopCondition<NoInfer<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>> | StopCondition<...>[] | undefined
Condition for stopping the generation when there are tool results in the last step. When the condition is an array, any of the conditions can be met to stop the generation.
@defaultstepCountIs(1)
stopWhen
: function stepCountIs(stepCount: number): StopCondition<any>stepCountIs(10),
onStepFinish?: StreamTextOnStepFinishCallback<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>> | undefined
Callback that is called when each step (LLM call) is finished, including intermediate steps.
onStepFinish
: (
step: StepResult<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>
step
) => {
for (const
const toolCall: TypedToolCall<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>
toolCall
of
step: StepResult<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>
step
.
toolCalls: TypedToolCall<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>[]
The tool calls that were made during the generation.
toolCalls
) {
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`[Using tool: ${
const toolCall: TypedToolCall<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>>
toolCall
.toolName: stringtoolName}]`);
} },
tools?: Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})> | undefined
The tools that the model can call. The model needs to support calling tools.
tools
,
}); for await (const const textPart: stringtextPart of
const stream: StreamTextResult<Record<string, ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
}) | ({
    description?: string;
    title?: string;
    providerOptions?: ProviderOptions;
    inputSchema: FlexibleSchema<unknown>;
    inputExamples?: {
        input: unknown;
    }[] | undefined;
    needsApproval?: boolean | ToolNeedsApprovalFunction<unknown> | undefined;
    strict?: boolean;
    onInputStart?: (options: ToolExecutionOptions) => void | PromiseLike<void>;
    onInputDelta?: (options: {
        inputTextDelta: string;
    } & ToolExecutionOptions) => void | PromiseLike<void>;
    onInputAvailable?: ((options: {
        ...;
    } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined;
} & ... 4 more ... & {
    ...;
})>, Output<...>>
stream
.StreamTextResult<Record<string, ({ description?: string; title?: string; providerOptions?: ProviderOptions; inputSchema: FlexibleSchema<unknown>; ... 5 more ...; onInputAvailable?: ((options: { ...; } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined; } & ... 4 more ... & { ...; }) | ({ description?: string; title?: string; providerOptions?: ProviderOptions; inputSchema: FlexibleSchema<unknown>; ... 5 more ...; onInputAvailable?: ((options: { ...; } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined; } & ... 4 more ... & { ...; }) | ({ description?: string; title?: string; providerOptions?: ProviderOptions; inputSchema: FlexibleSchema<unknown>; ... 5 more ...; onInputAvailable?: ((options: { ...; } & ToolExecutionOptions) => void | PromiseLike<void>) | undefined; } & ... 4 more ... & { ...; })>, Output<...>>.textStream: AsyncIterableStream<string>
A text stream that returns only the generated text deltas. You can use it as either an AsyncIterable or a ReadableStream. When an error occurs, the stream will throw the error.
textStream
) {
var process: NodeJS.Processprocess.
NodeJS.Process.stdout: NodeJS.WriteStream & {
    fd: 1;
}
The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is a `Writable` stream. For example, to copy `process.stdin` to `process.stdout`: ```js import { stdin, stdout } from 'node:process'; stdin.pipe(stdout); ``` `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information.
stdout
.Socket.write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean (+1 overload)
Sends data on the socket. The second parameter specifies the encoding in the case of a string. It defaults to UTF8 encoding. Returns `true` if the entire data was flushed successfully to the kernel buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. The optional `callback` parameter will be executed when the data is finally written out, which may not be immediately. See `Writable` stream `write()` method for more information.
@sincev0.1.90@paramencoding Only used when data is `string`.
write
(const textPart: stringtextPart);
} var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("\n\n---");
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v24.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v24.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v24.x/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
("Tip: If prompted to authenticate, complete the auth flow and run again.")