Executing Tools

Learn how to execute Composio tools with different providers and frameworks

LLMs on their own can only do generation. Tool calling changes that by letting them interact with external services. Instead of just drafting an email, the model can call GMAIL_SEND_EMAIL to actually send it. The tool's results feed back to the LLM, closing the loop so it can decide, act, observe, and adapt.

In Composio, every tool is a single API action—fully described with schema, parameters, and return type. Tools live inside toolkits like Gmail, Slack, or GitHub, and Composio handles authentication and user scoping.

User Scoping: All tools are scoped to a specific user - that's why every example includes a user_id. Learn how to structure User IDs in User Management. Each user must authenticate with their respective services (Gmail, Calendar, etc.) - see Authentication.

Using Chat Completions

Use the Composio SDK with providers like OpenAI, Anthropic, and Google AI. To learn how to set up these providers, see Providers.

from composio import Composio
from composio_openai import OpenAIProvider
from openai import OpenAI
from datetime import datetime

# Use a unique identifier for each user in your application
user_id = "user-k7334"

# Create composio client
composio = Composio(provider=OpenAIProvider(), api_key="your_composio_api_key")

# Create openai client
openai = OpenAI()

# Get calendar tools for this user
tools = composio.tools.get(
    user_id=user_id,
    tools=["GOOGLECALENDAR_EVENTS_LIST"]
)

# Ask the LLM to check calendar
result = openai.chat.completions.create(
    model="gpt-4o-mini",
    tools=tools,
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": f"What's on my calendar for the next 7 days?"}
    ]
)

# Handle tool calls
result = composio.provider.handle_tool_calls(user_id=user_id, response=result)
print(result)
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 AnthropicProvider
Anthropic Provider implementation for Composio
AnthropicProvider
} from '@composio/anthropic';
import { class Anthropic
API Client for interfacing with the Anthropic API.
Anthropic
} from '@anthropic-ai/sdk';
// Use a unique identifier for each user in your application const const userId: "user-k7334"userId = 'user-k7334'; // Create anthropic client const const anthropic: Anthropicanthropic = new new Anthropic({ baseURL, apiKey, authToken, ...opts }?: ClientOptions): Anthropic
API Client for interfacing with the Anthropic API.
@paramopts.apiKey@paramopts.authToken@paramopts.baseURL ://api.anthropic.com] - Override the default base URL for the API.@paramopts.timeout minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.@paramopts.fetchOptions - Additional `RequestInit` options to be passed to `fetch` calls.@paramopts.fetch - Specify a custom `fetch` function implementation.@paramopts.maxRetries - The maximum number of times the client will retry a request.@paramopts.defaultHeaders - Default headers to include with every request to the API.@paramopts.defaultQuery - Default query parameters to include with every request to the API.@paramopts.dangerouslyAllowBrowser - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
Anthropic
();
// Create Composio client const const composio: Composio<AnthropicProvider>composio = new new Composio<AnthropicProvider>(config?: ComposioConfig<AnthropicProvider> | undefined): Composio<AnthropicProvider>
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
({
apiKey?: string | null | undefined
The API key for the Composio API.
@example'sk-1234567890'
apiKey
: "your-composio-api-key",
provider?: AnthropicProvider | undefined
The tool provider to use for this Composio instance.
@examplenew OpenAIProvider()
provider
: new
new AnthropicProvider(options?: {
    cacheTools?: boolean;
}): AnthropicProvider
Creates a new instance of the AnthropicProvider.
@paramoptions - Configuration options for the provider@paramoptions.cacheTools - Whether to cache tools using Anthropic's ephemeral cache@example```typescript // Initialize with default settings (no caching) const provider = new AnthropicProvider(); // Initialize with tool caching enabled const providerWithCaching = new AnthropicProvider({ cacheTools: true }); // Use with Composio const composio = new Composio({ apiKey: 'your-api-key', provider: new AnthropicProvider({ cacheTools: true }) }); ```
AnthropicProvider
(),
}); // Get calendar tools for this user const const tools: AnthropicToolCollectiontools = await const composio: Composio<AnthropicProvider>composio.Composio<AnthropicProvider>.tools: Tools<unknown, unknown, AnthropicProvider>
List, retrieve, and execute tools
tools
.Tools<unknown, unknown, AnthropicProvider>.get<AnthropicProvider>(userId: string, filters: ToolListParams, options?: ToolOptions | undefined): Promise<AnthropicToolCollection> (+1 overload)
Get a list of tools from Composio based on filters. This method fetches the tools from the Composio API and wraps them using the provider.
@paramuserId - The user id to get the tools for@paramfilters - The filters to apply when fetching tools@paramoptions - Optional provider options including modifiers@returnsThe wrapped tools collection@example```typescript // Get tools from the GitHub toolkit const tools = await composio.tools.get('default', { toolkits: ['github'], limit: 10 }); // Get tools with search const searchTools = await composio.tools.get('default', { search: 'user', limit: 10 }); // Get a specific tool by slug const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER'); // Get a tool with schema modifications const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', { modifySchema: (toolSlug, toolkitSlug, schema) => { // Customize the tool schema return {...schema, description: 'Custom description'}; } }); ```
get
(const userId: "user-k7334"userId, {
tools: string[]tools: ['GOOGLECALENDAR_EVENTS_LIST'], }); // Ask the LLM to check calendar const
const msg: Anthropic.Messages.Message & {
    _request_id?: string | null;
}
msg
= await const anthropic: Anthropicanthropic.Anthropic.messages: Anthropic.Messagesmessages.Messages.create(body: Anthropic.Messages.MessageCreateParamsNonStreaming, options?: RequestOptions): APIPromise<Anthropic.Messages.Message> (+2 overloads)
Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation. The Messages API can be used for either single queries or stateless multi-turn conversations. Learn more about the Messages API in our [user guide](https://docs.claude.com/en/docs/initial-setup)
@example```ts const message = await client.messages.create({ max_tokens: 1024, messages: [{ content: 'Hello, world', role: 'user' }], model: 'claude-sonnet-4-5-20250929', }); ```
create
({
MessageCreateParamsBase.model: Anthropic.Messages.Model
The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options.
model
: 'claude-sonnet-4-20250514',
MessageCreateParamsBase.tools?: Anthropic.Messages.ToolUnion[] | undefined
Definitions of tools that the model may use. If you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks. There are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)). Each tool definition includes: - `name`: Name of the tool. - `description`: Optional, but strongly-recommended description of the tool. - `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks. For example, if you defined `tools` as: ```json [ { "name": "get_stock_price", "description": "Get the current stock price for a given ticker symbol.", "input_schema": { "type": "object", "properties": { "ticker": { "type": "string", "description": "The stock ticker symbol, e.g. AAPL for Apple Inc." } }, "required": ["ticker"] } } ] ``` And then asked the model "What's the S&P 500 at today?", the model might produce `tool_use` content blocks in the response like this: ```json [ { "type": "tool_use", "id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "name": "get_stock_price", "input": { "ticker": "^GSPC" } } ] ``` You might then run your `get_stock_price` tool with `{"ticker": "^GSPC"}` as an input, and return the following back to the model in a subsequent `user` message: ```json [ { "type": "tool_result", "tool_use_id": "toolu_01D7FLrfh4GYq7yT1ULFeyMV", "content": "259.75 USD" } ] ``` Tools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output. See our [guide](https://docs.claude.com/en/docs/tool-use) for more details.
tools
: const tools: AnthropicToolCollectiontools,
MessageCreateParamsBase.messages: Anthropic.Messages.MessageParam[]
Input messages. Our models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn. Each input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages. If the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response. Example with a single `user` message: ```json [{ "role": "user", "content": "Hello, Claude" }] ``` Example with multiple conversational turns: ```json [ { "role": "user", "content": "Hello there." }, { "role": "assistant", "content": "Hi, I'm Claude. How can I help you?" }, { "role": "user", "content": "Can you explain LLMs in plain English?" } ] ``` Example with a partially-filled response from Claude: ```json [ { "role": "user", "content": "What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun" }, { "role": "assistant", "content": "The best answer is (" } ] ``` Each input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `"text"`. The following input messages are equivalent: ```json { "role": "user", "content": "Hello, Claude" } ``` ```json { "role": "user", "content": [{ "type": "text", "text": "Hello, Claude" }] } ``` See [input examples](https://docs.claude.com/en/api/messages-examples). Note that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `"system"` role for input messages in the Messages API. There is a limit of 100,000 messages in a single request.
messages
: [
{ MessageParam.role: "user" | "assistant"role: 'user', MessageParam.content: string | Anthropic.Messages.ContentBlockParam[]content: `What's on my calendar for the next 7 days?`, }, ], MessageCreateParamsBase.max_tokens: number
The maximum number of tokens to generate before stopping. Note that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate. Different models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details.
max_tokens
: 1024,
}); // Handle tool calls const const result: Anthropic.Messages.MessageParam[]result = await const composio: Composio<AnthropicProvider>composio.Composio<AnthropicProvider>.provider: AnthropicProvider
The tool provider instance used for wrapping tools in framework-specific formats
provider
.AnthropicProvider.handleToolCalls(userId: string, message: Anthropic.Message, options?: ExecuteToolFnOptions, modifiers?: ExecuteToolModifiers): Promise<Anthropic.Messages.MessageParam[]>
Handles tool calls from Anthropic's message response. This method processes tool calls from an Anthropic message response, extracts the tool use blocks, executes each tool call, and returns the results.
@paramuserId - The user ID for authentication and tracking@parammessage - The message response from Anthropic@paramoptions - Additional options for tool execution@parammodifiers - Modifiers for tool execution@returnsArray of tool execution results as JSON strings@example```typescript // Handle tool calls from an Anthropic message response const anthropic = new Anthropic({ apiKey: 'your-anthropic-api-key' }); const message = await anthropic.messages.create({ model: 'claude-3-opus-20240229', max_tokens: 1024, tools: provider.wrapTools(composioTools), messages: [ { role: 'user', content: 'Search for information about Composio' } ] }); // Process any tool calls in the response const results = await provider.handleToolCalls( 'user123', message, { connectedAccountId: 'conn_xyz456' } ); // Use the results to continue the conversation console.log(results); ```
handleToolCalls
(const userId: "user-k7334"userId,
const msg: Anthropic.Messages.Message & {
    _request_id?: string | null;
}
msg
);
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
('Results:', var JSON: JSON
An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON
.JSON.stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string (+1 overload)
Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found.
stringify
(const result: Anthropic.Messages.MessageParam[]result, null, 2));

Using Agentic Frameworks

Agentic frameworks automatically handle the tool execution loop. Composio provides support for frameworks like this by making sure the tools are formatted into the correct objects for the agentic framework to execute.

import asyncio
from agents import Agent, Runner
from composio import Composio
from composio_openai_agents import OpenAIAgentsProvider

# Use a unique identifier for each user in your application
user_id = "user-k7334"

# Initialize Composio toolset
composio = Composio(provider=OpenAIAgentsProvider(), api_key="your_composio_api_key")

# Get all tools for the user
tools = composio.tools.get(
    user_id=user_id,
    toolkits=["COMPOSIO_SEARCH"],
)

# Create an agent with the tools
agent = Agent(
    name="Deep Researcher",
    instructions="You are an investigative journalist.",
    tools=tools,
)

async def main():
    result = await Runner.run(
        starting_agent=agent,
        input=("Do a thorough DEEP research on Golden Gate Bridge"),
    )
    print(result.final_output)

# Run the agent
asyncio.run(main())
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 generateText<TOOLS extends ToolSet, OUTPUT extends Output<any, any, any> = Output<string, string, any>>({ model: modelArg, tools, toolChoice, system, prompt, messages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen, experimental_output, output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools, experimental_prepareStep, prepareStep, experimental_repairToolCall: repairToolCall, experimental_download: download, experimental_context, _internal: { generateId }, onStepFinish, onFinish, ...settings }: CallSettings & Prompt & {
    model: LanguageModel;
    tools?: TOOLS;
    toolChoice?: ToolChoice<NoInfer<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;
    experimental_download?: DownloadFunction | undefined;
    experimental_prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;
    prepareStep?: PrepareStepFunction<NoInfer<TOOLS>>;
    experimental_repairToolCall?: ToolCallRepairFunction<NoInfer<TOOLS>>;
    onStepFinish?: GenerateTextOnStepFinishCallback<NoInfer<TOOLS>>;
    onFinish?: GenerateTextOnFinishCallback<NoInfer<TOOLS>>;
    experimental_context?: unknown;
    _internal?: {
        generateId?: IdGenerator;
    };
}): Promise<GenerateTextResult<TOOLS, OUTPUT>>
Generate a text and call tools for a given prompt using a language model. This function does not stream the output. If you want to stream the output, use `streamText` 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.@paramtoolChoice - The tool choice strategy. Default: 'auto'.@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.@paramexperimental_generateMessageId - Generate a unique ID for each message.@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.@returnsA result object that contains the generated text, the results of the tool calls, and additional information.
generateText
} from 'ai';
import { const anthropic: AnthropicProvider
Default Anthropic provider instance.
anthropic
} from '@ai-sdk/anthropic';
import { class VercelProviderVercelProvider } from '@composio/vercel'; // Use a unique identifier for each user in your application const const userId: "user-k7334"userId = 'user-k7334'; // Initialize Composio toolset const const composio: Composio<VercelProvider>composio = new new Composio<VercelProvider>(config?: ComposioConfig<VercelProvider> | undefined): Composio<VercelProvider>
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
({
apiKey?: string | null | undefined
The API key for the Composio API.
@example'sk-1234567890'
apiKey
: var process: NodeJS.Processprocess.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment. See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). An example of this object looks like: ```js { TERM: 'xterm-256color', SHELL: '/usr/local/bin/bash', USER: 'maciej', PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', PWD: '/Users/maciej', EDITOR: 'vim', SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', _: '/usr/local/bin/node' } ``` It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other `Worker` threads. In other words, the following example would not work: ```bash node -e 'process.env.foo = "bar"' &#x26;&#x26; echo $foo ``` While the following will: ```js import { env } from 'node:process'; env.foo = 'bar'; console.log(env.foo); ``` Assigning a property on `process.env` will implicitly convert the value to a string. **This behavior is deprecated.** Future versions of Node.js may throw an error when the value is not a string, number, or boolean. ```js import { env } from 'node:process'; env.test = null; console.log(env.test); // => 'null' env.test = undefined; console.log(env.test); // => 'undefined' ``` Use `delete` to delete a property from `process.env`. ```js import { env } from 'node:process'; env.TEST = 1; delete env.TEST; console.log(env.TEST); // => undefined ``` On Windows operating systems, environment variables are case-insensitive. ```js import { env } from 'node:process'; env.TEST = 1; console.log(env.test); // => 1 ``` Unless explicitly specified when creating a `Worker` instance, each `Worker` thread has its own copy of `process.env`, based on its parent thread's `process.env`, or whatever was specified as the `env` option to the `Worker` constructor. Changes to `process.env` will not be visible across `Worker` threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner unlike the main thread.
@sincev0.1.27
env
.string | undefinedCOMPOSIO_API_KEY,
provider?: VercelProvider | undefined
The tool provider to use for this Composio instance.
@examplenew OpenAIProvider()
provider
: new
new VercelProvider({ strict }?: {
    strict?: boolean;
}): VercelProvider
Creates a new instance of the VercelProvider. This provider enables integration with the Vercel AI SDK, allowing Composio tools to be used with Vercel AI applications.
@example```typescript // Initialize the Vercel provider const provider = new VercelProvider(); // Use with Composio const composio = new Composio({ apiKey: 'your-api-key', provider: new VercelProvider() }); // Use the provider to wrap tools for Vercel AI SDK const vercelTools = provider.wrapTools(composioTools, composio.tools.execute); ```
VercelProvider
(),
}); // Get all tools for the user const const tools: ToolSettools = await const composio: Composio<VercelProvider>composio.Composio<VercelProvider>.tools: Tools<unknown, unknown, VercelProvider>
List, retrieve, and execute tools
tools
.Tools<unknown, unknown, VercelProvider>.get<VercelProvider>(userId: string, filters: ToolListParams, options?: AgenticToolOptions | undefined): Promise<ToolSet> (+1 overload)
Get a list of tools from Composio based on filters. This method fetches the tools from the Composio API and wraps them using the provider.
@paramuserId - The user id to get the tools for@paramfilters - The filters to apply when fetching tools@paramoptions - Optional provider options including modifiers@returnsThe wrapped tools collection@example```typescript // Get tools from the GitHub toolkit const tools = await composio.tools.get('default', { toolkits: ['github'], limit: 10 }); // Get tools with search const searchTools = await composio.tools.get('default', { search: 'user', limit: 10 }); // Get a specific tool by slug const hackerNewsUserTool = await composio.tools.get('default', 'HACKERNEWS_GET_USER'); // Get a tool with schema modifications const tool = await composio.tools.get('default', 'GITHUB_GET_REPOS', { modifySchema: (toolSlug, toolkitSlug, schema) => { // Customize the tool schema return {...schema, description: 'Custom description'}; } }); ```
get
(const userId: "user-k7334"userId, {
toolkits: [string]toolkits: ['HACKERNEWS_GET_LATEST_POSTS'], limit: numberlimit: 10, }); // Generate text with tool use const { const text: string
The text that was generated in the last step.
text
} = await
generateText<ToolSet, Output<string, string, any>>({ model: modelArg, tools, toolChoice, system, prompt, messages, maxRetries: maxRetriesArg, abortSignal, timeout, headers, stopWhen, experimental_output, output, experimental_telemetry: telemetry, providerOptions, experimental_activeTools, activeTools, experimental_prepareStep, prepareStep, experimental_repairToolCall: repairToolCall, experimental_download: download, experimental_context, _internal: { generateId }, onStepFinish, onFinish, ...settings }: CallSettings & (Prompt & {
    model: LanguageModel;
    tools?: ToolSet | undefined;
    toolChoice?: ToolChoice<NoInfer<ToolSet>> | undefined;
    stopWhen?: StopCondition<NoInfer<ToolSet>> | StopCondition<NoInfer<ToolSet>>[] | undefined;
    experimental_telemetry?: TelemetrySettings;
    providerOptions?: ProviderOptions;
    ... 11 more ...;
    _internal?: {
        generateId?: IdGenerator;
    };
})): Promise<...>
Generate a text and call tools for a given prompt using a language model. This function does not stream the output. If you want to stream the output, use `streamText` 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.@paramtoolChoice - The tool choice strategy. Default: 'auto'.@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.@paramexperimental_generateMessageId - Generate a unique ID for each message.@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.@returnsA result object that contains the generated text, the results of the tool calls, and additional information.
generateText
({
model: LanguageModel
The language model to use.
model
: function anthropic(modelId: AnthropicMessagesModelId): LanguageModelV3
Creates a model for text generation.
anthropic
('claude-sonnet-4-20250514'),
messages: ModelMessage[]
A list of messages. You can either use `prompt` or `messages` but not both.
messages
: [
{ role: "user"role: 'user', content: UserContentcontent: 'Do a thorough DEEP research on the top articles on Hacker News about Composio', }, ], tools?: ToolSet | undefined
The tools that the model can call. The model needs to support calling tools.
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
(const text: string
The text that was generated in the last step.
text
);

Direct Tool Execution

If you just want to call a tool without using any framework or LLM provider, you can use the execute method directly.

Finding tool parameters and types:

Platform UI: Auth Configs → Select your toolkit → Tools & Triggers → Select the tool to see its required and optional parameters

CLI: For Python and TypeScript projects, run composio generate to generate types. Learn more →

from composio import Composio

user_id = "user-k7334"
# Configure toolkit versions at SDK level
composio = Composio(
    api_key="your_composio_key",
    toolkit_versions={"github": "20251027_00"}
)

# Find available arguments for any tool in the Composio dashboard
result = composio.tools.execute(
    "GITHUB_LIST_STARGAZERS",
    user_id=user_id,
    arguments={"owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5}
)
print(result)
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";
const const userId: "user-k7334"userId = "user-k7334"; // Configure toolkit versions at SDK level 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
({
apiKey?: string | null | undefined
The API key for the Composio API.
@example'sk-1234567890'
apiKey
: "your_composio_key",
toolkitVersions?: "latest" | Record<string, string> | undefined
The versions of the toolkits to use for tool execution and retrieval. Omit to use 'latest' for all toolkits. **Version Control:** When executing tools manually (via `tools.execute()`), if this resolves to "latest", you must either: - Set `dangerouslySkipVersionCheck: true` in the execute params (not recommended for production) - Specify a concrete version here or in environment variables - Pass a specific `version` parameter to the execute call Defaults to 'latest' if nothing is provided. You can specify individual toolkit versions via environment variables: `COMPOSIO_TOOLKIT_VERSION_GITHUB=20250902_00`
@exampleGlobal version for all toolkits, omit to use 'latest' ```typescript const composio = new Composio(); ```@exampleSpecific versions for different toolkits (recommended for production) ```typescript const composio = new Composio({ toolkitVersions: { github: '20250909_00', slack: '20250902_00' } }); ```@exampleSet via environment variables ```typescript // Set environment variables: // COMPOSIO_TOOLKIT_VERSION_GITHUB=20250909_00 // COMPOSIO_TOOLKIT_VERSION_SLACK=20250902_00 const composio = new Composio(); // Will use env variables ```
toolkitVersions
: { github: stringgithub: "20251027_00" }
}); // Find available arguments for any tool in the Composio dashboard const
const result: {
    error: string | null;
    data: Record<string, unknown>;
    successful: boolean;
    logId?: string | undefined;
    sessionInfo?: unknown;
}
result
= await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.tools: Tools<unknown, unknown, OpenAIProvider>
List, retrieve, and execute tools
tools
.Tools<unknown, unknown, OpenAIProvider>.execute(slug: string, body: ToolExecuteParams, modifiers?: ExecuteToolModifiers): Promise<ToolExecuteResponse>
Executes a given tool with the provided parameters. This method calls the Composio API or a custom tool handler to execute the tool and returns the response. It automatically determines whether to use a custom tool or a Composio API tool based on the slug. **Version Control:** By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest", the execution will throw a `ComposioToolVersionRequiredError` unless `dangerouslySkipVersionCheck` is set to `true`. This helps prevent unexpected behavior when new toolkit versions are released.
@paramslug - The slug/ID of the tool to be executed@parambody - The parameters to be passed to the tool@parambody.version - The specific version of the tool to execute (e.g., "20250909_00")@parambody.dangerouslySkipVersionCheck - Skip version validation for "latest" version (use with caution)@parambody.userId - The user ID to execute the tool for@parambody.connectedAccountId - The connected account ID to use for authenticated tools@parambody.arguments - The arguments to pass to the tool@parammodifiers - Optional modifiers to transform the request or response@returns- The response from the tool execution@throws{ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized@throws{ComposioConnectedAccountNotFoundError} If the connected account is not found@throws{ComposioToolNotFoundError} If the tool with the given slug is not found@throws{ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true@throws{ComposioToolExecutionError} If there is an error during tool execution@exampleExecute with a specific version (recommended for production) ```typescript const result = await composio.tools.execute('GITHUB_GET_REPOS', { userId: 'default', version: '20250909_00', arguments: { owner: 'composio' } }); ```@exampleExecute with dangerouslySkipVersionCheck (not recommended for production) ```typescript const result = await composio.tools.execute('HACKERNEWS_GET_USER', { userId: 'default', arguments: { userId: 'pg' }, dangerouslySkipVersionCheck: true // Allows execution with "latest" version }); ```@exampleExecute with SDK-level toolkit versions configuration ```typescript // If toolkitVersions are set during Composio initialization, no need to pass version const composio = new Composio({ toolkitVersions: { github: '20250909_00' } }); const result = await composio.tools.execute('GITHUB_GET_REPOS', { userId: 'default', arguments: { owner: 'composio' } }); ```@exampleExecute with modifiers ```typescript const result = await composio.tools.execute('GITHUB_GET_ISSUES', { userId: 'default', version: '20250909_00', arguments: { owner: 'composio', repo: 'sdk' } }, { beforeExecute: ({ toolSlug, toolkitSlug, params }) => { console.log(`Executing ${toolSlug} from ${toolkitSlug}`); return params; }, afterExecute: ({ toolSlug, toolkitSlug, result }) => { console.log(`Completed ${toolSlug}`); return result; } }); ```
execute
("GITHUB_LIST_STARGAZERS", {
userId?: string | undefineduserId, arguments?: Record<string, unknown> | undefinedarguments: { "owner": "ComposioHQ", "repo": "composio", "page": 1, "per_page": 5 }, }); 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
('GitHub stargazers:', var JSON: JSON
An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format.
JSON
.JSON.stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string (+1 overload)
Converts a JavaScript value to a JavaScript Object Notation (JSON) string.
@paramvalue A JavaScript value, usually an object or array, to be converted.@paramreplacer An array of strings and numbers that acts as an approved list for selecting the object properties that will be stringified.@paramspace Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read.@throws{TypeError} If a circular reference or a BigInt value is found.
stringify
(
const result: {
    error: string | null;
    data: Record<string, unknown>;
    successful: boolean;
    logId?: string | undefined;
    sessionInfo?: unknown;
}
result
, null, 2));

The examples above configure toolkit versions at SDK initialization. You can also pass versions per-execution or use environment variables. See toolkit versioning for all configuration options.

Proxy Execute

You can proxy requests to any supported toolkit API and let Composio inject the authentication state. This is useful when you need an API endpoint that isn't available as a predefined tool.

The endpoint can be a relative path or absolute URL. Composio uses the connected_account_id to determine the toolkit and resolve relative paths against the appropriate base URL.

# Send a proxy request to the endpoint
response = composio.tools.proxy(
    endpoint="/repos/composiohq/composio/issues/1",
    method="GET",
    connected_account_id="ca_jI6********",  # use connected account for github
    parameters=[
        {
            "name": "Accept",
            "value": "application/vnd.github.v3+json",
            "type": "header",
        },
    ],
)

print(response)
// Send a proxy request to the endpoint
const { const data: unknown
The response data returned from the proxied API
data
} = await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.tools: Tools<unknown, unknown, OpenAIProvider>
List, retrieve, and execute tools
tools
.Tools<unknown, unknown, OpenAIProvider>.proxyExecute(body: ToolProxyParams): Promise<ToolProxyResponse>
Proxies a custom request to a toolkit/integration. This method allows sending custom requests to a specific toolkit or integration when you need more flexibility than the standard tool execution methods provide.
@parambody - The parameters for the proxy request including toolkit slug and custom data@returnsThe response from the proxied request@example```typescript // Send a custom request to a toolkit const response = await composio.tools.proxyExecute({ toolkitSlug: 'github', userId: 'default', data: { endpoint: '/repos/owner/repo/issues', method: 'GET' } }); console.log(response.data); ```
proxyExecute
({
endpoint: stringendpoint:'/repos/composiohq/composio/issues/1', method: "GET" | "POST" | "PUT" | "DELETE" | "PATCH"method: 'GET', connectedAccountId?: string | undefinedconnectedAccountId: 'ca_jI*****', // use connected account for github
parameters?: {
    name: string;
    value: string | number;
    in: "query" | "header";
}[] | undefined
parameters
:[
{ "name": "Accept", "value": "application/vnd.github.v3+json", "in": "header", }, ], }); 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 data: unknown
The response data returned from the proxied API
data
);

Need an API that isn't supported by any Composio toolkit, or want to extend an existing one? Learn how to create custom tools.

Automatic File Handling

Composio handles file operations automatically. Pass file paths to tools that need them, and get local file paths back from tools that return files.

File Upload

Pass local file paths, URLs, or File objects to tools that accept files:

# Upload a local file to Google Drive
result = composio.tools.execute(
    slug="GOOGLEDRIVE_UPLOAD_FILE",
    user_id="user-1235***",
    arguments={"file_to_upload": os.path.join(os.getcwd(), "document.pdf")},
)

print(result)  # Print Google Drive file details
// Upload a local file to Google Drive
const 
const result: {
    error: string | null;
    data: Record<string, unknown>;
    successful: boolean;
    logId?: string | undefined;
    sessionInfo?: unknown;
}
result
= await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.tools: Tools<unknown, unknown, OpenAIProvider>
List, retrieve, and execute tools
tools
.Tools<unknown, unknown, OpenAIProvider>.execute(slug: string, body: ToolExecuteParams, modifiers?: ExecuteToolModifiers): Promise<ToolExecuteResponse>
Executes a given tool with the provided parameters. This method calls the Composio API or a custom tool handler to execute the tool and returns the response. It automatically determines whether to use a custom tool or a Composio API tool based on the slug. **Version Control:** By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest", the execution will throw a `ComposioToolVersionRequiredError` unless `dangerouslySkipVersionCheck` is set to `true`. This helps prevent unexpected behavior when new toolkit versions are released.
@paramslug - The slug/ID of the tool to be executed@parambody - The parameters to be passed to the tool@parambody.version - The specific version of the tool to execute (e.g., "20250909_00")@parambody.dangerouslySkipVersionCheck - Skip version validation for "latest" version (use with caution)@parambody.userId - The user ID to execute the tool for@parambody.connectedAccountId - The connected account ID to use for authenticated tools@parambody.arguments - The arguments to pass to the tool@parammodifiers - Optional modifiers to transform the request or response@returns- The response from the tool execution@throws{ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized@throws{ComposioConnectedAccountNotFoundError} If the connected account is not found@throws{ComposioToolNotFoundError} If the tool with the given slug is not found@throws{ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true@throws{ComposioToolExecutionError} If there is an error during tool execution@exampleExecute with a specific version (recommended for production) ```typescript const result = await composio.tools.execute('GITHUB_GET_REPOS', { userId: 'default', version: '20250909_00', arguments: { owner: 'composio' } }); ```@exampleExecute with dangerouslySkipVersionCheck (not recommended for production) ```typescript const result = await composio.tools.execute('HACKERNEWS_GET_USER', { userId: 'default', arguments: { userId: 'pg' }, dangerouslySkipVersionCheck: true // Allows execution with "latest" version }); ```@exampleExecute with SDK-level toolkit versions configuration ```typescript // If toolkitVersions are set during Composio initialization, no need to pass version const composio = new Composio({ toolkitVersions: { github: '20250909_00' } }); const result = await composio.tools.execute('GITHUB_GET_REPOS', { userId: 'default', arguments: { owner: 'composio' } }); ```@exampleExecute with modifiers ```typescript const result = await composio.tools.execute('GITHUB_GET_ISSUES', { userId: 'default', version: '20250909_00', arguments: { owner: 'composio', repo: 'sdk' } }, { beforeExecute: ({ toolSlug, toolkitSlug, params }) => { console.log(`Executing ${toolSlug} from ${toolkitSlug}`); return params; }, afterExecute: ({ toolSlug, toolkitSlug, result }) => { console.log(`Completed ${toolSlug}`); return result; } }); ```
execute
('GOOGLEDRIVE_UPLOAD_FILE', {
userId?: string | undefineduserId: 'user-4235***', arguments?: Record<string, unknown> | undefinedarguments: { file_to_upload: stringfile_to_upload: const path: path.PlatformPathpath.path.PlatformPath.join(...paths: string[]): string
Join all arguments together and normalize the resulting path.
@parampaths paths to join.@throws{TypeError} if any of the path segments is not a string.
join
(var __dirname: string
The directory name of the current module. This is the same as the `path.dirname()` of the `__filename`.
@sincev0.1.27
__dirname
, 'document.pdf')
} }); 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: {
    error: string | null;
    data: Record<string, unknown>;
    successful: boolean;
    logId?: string | undefined;
    sessionInfo?: unknown;
}
result
.data: Record<string, unknown>data); // Contains Google Drive file details

File Download

When tools return files, Composio downloads them to the local directory and provides the file path in the response:

composio = Composio(
    api_key="your_composio_key",
    file_download_dir="./downloads"  # Optional: Specify download directory
)

result = composio.tools.execute(
    "GOOGLEDRIVE_DOWNLOAD_FILE",
    user_id="user-1235***",
    arguments={"file_id": "your_file_id"},
)

# Result includes local file path
print(result)
// Download a file from Google Drive
const 
const result: {
    error: string | null;
    data: Record<string, unknown>;
    successful: boolean;
    logId?: string | undefined;
    sessionInfo?: unknown;
}
result
= await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.tools: Tools<unknown, unknown, OpenAIProvider>
List, retrieve, and execute tools
tools
.Tools<unknown, unknown, OpenAIProvider>.execute(slug: string, body: ToolExecuteParams, modifiers?: ExecuteToolModifiers): Promise<ToolExecuteResponse>
Executes a given tool with the provided parameters. This method calls the Composio API or a custom tool handler to execute the tool and returns the response. It automatically determines whether to use a custom tool or a Composio API tool based on the slug. **Version Control:** By default, manual tool execution requires a specific toolkit version. If the version resolves to "latest", the execution will throw a `ComposioToolVersionRequiredError` unless `dangerouslySkipVersionCheck` is set to `true`. This helps prevent unexpected behavior when new toolkit versions are released.
@paramslug - The slug/ID of the tool to be executed@parambody - The parameters to be passed to the tool@parambody.version - The specific version of the tool to execute (e.g., "20250909_00")@parambody.dangerouslySkipVersionCheck - Skip version validation for "latest" version (use with caution)@parambody.userId - The user ID to execute the tool for@parambody.connectedAccountId - The connected account ID to use for authenticated tools@parambody.arguments - The arguments to pass to the tool@parammodifiers - Optional modifiers to transform the request or response@returns- The response from the tool execution@throws{ComposioCustomToolsNotInitializedError} If the CustomTools instance is not initialized@throws{ComposioConnectedAccountNotFoundError} If the connected account is not found@throws{ComposioToolNotFoundError} If the tool with the given slug is not found@throws{ComposioToolVersionRequiredError} If version resolves to "latest" and dangerouslySkipVersionCheck is not true@throws{ComposioToolExecutionError} If there is an error during tool execution@exampleExecute with a specific version (recommended for production) ```typescript const result = await composio.tools.execute('GITHUB_GET_REPOS', { userId: 'default', version: '20250909_00', arguments: { owner: 'composio' } }); ```@exampleExecute with dangerouslySkipVersionCheck (not recommended for production) ```typescript const result = await composio.tools.execute('HACKERNEWS_GET_USER', { userId: 'default', arguments: { userId: 'pg' }, dangerouslySkipVersionCheck: true // Allows execution with "latest" version }); ```@exampleExecute with SDK-level toolkit versions configuration ```typescript // If toolkitVersions are set during Composio initialization, no need to pass version const composio = new Composio({ toolkitVersions: { github: '20250909_00' } }); const result = await composio.tools.execute('GITHUB_GET_REPOS', { userId: 'default', arguments: { owner: 'composio' } }); ```@exampleExecute with modifiers ```typescript const result = await composio.tools.execute('GITHUB_GET_ISSUES', { userId: 'default', version: '20250909_00', arguments: { owner: 'composio', repo: 'sdk' } }, { beforeExecute: ({ toolSlug, toolkitSlug, params }) => { console.log(`Executing ${toolSlug} from ${toolkitSlug}`); return params; }, afterExecute: ({ toolSlug, toolkitSlug, result }) => { console.log(`Completed ${toolSlug}`); return result; } }); ```
execute
('GOOGLEDRIVE_DOWNLOAD_FILE', {
userId?: string | undefineduserId: 'user-1235***', arguments?: Record<string, unknown> | undefinedarguments: { file_id: stringfile_id: 'your-file-id' } }); // Result includes local file path 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: {
    error: string | null;
    data: Record<string, unknown>;
    successful: boolean;
    logId?: string | undefined;
    sessionInfo?: unknown;
}
result
);

Disabling Auto File Handling

You can disable automatic file handling when initializing the TypeScript SDK. When disabled, handle file uploads and downloads manually using files.upload and files.download:

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
({
apiKey?: string | null | undefined
The API key for the Composio API.
@example'sk-1234567890'
apiKey
: var process: NodeJS.Processprocess.NodeJS.Process.env: NodeJS.ProcessEnv
The `process.env` property returns an object containing the user environment. See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). An example of this object looks like: ```js { TERM: 'xterm-256color', SHELL: '/usr/local/bin/bash', USER: 'maciej', PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', PWD: '/Users/maciej', EDITOR: 'vim', SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', _: '/usr/local/bin/node' } ``` It is possible to modify this object, but such modifications will not be reflected outside the Node.js process, or (unless explicitly requested) to other `Worker` threads. In other words, the following example would not work: ```bash node -e 'process.env.foo = "bar"' &#x26;&#x26; echo $foo ``` While the following will: ```js import { env } from 'node:process'; env.foo = 'bar'; console.log(env.foo); ``` Assigning a property on `process.env` will implicitly convert the value to a string. **This behavior is deprecated.** Future versions of Node.js may throw an error when the value is not a string, number, or boolean. ```js import { env } from 'node:process'; env.test = null; console.log(env.test); // => 'null' env.test = undefined; console.log(env.test); // => 'undefined' ``` Use `delete` to delete a property from `process.env`. ```js import { env } from 'node:process'; env.TEST = 1; delete env.TEST; console.log(env.TEST); // => undefined ``` On Windows operating systems, environment variables are case-insensitive. ```js import { env } from 'node:process'; env.TEST = 1; console.log(env.test); // => 1 ``` Unless explicitly specified when creating a `Worker` instance, each `Worker` thread has its own copy of `process.env`, based on its parent thread's `process.env`, or whatever was specified as the `env` option to the `Worker` constructor. Changes to `process.env` will not be visible across `Worker` threads, and only the main thread can make changes that are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner unlike the main thread.
@sincev0.1.27
env
.string | undefinedCOMPOSIO_API_KEY,
autoUploadDownloadFiles?: boolean | undefined
Whether to automatically upload and download files during tool execution.
@exampletrue, false@defaulttrue
autoUploadDownloadFiles
: false
}); // Now you need to handle files manually using composio.files API const const fileData: FileUploadDatafileData = await const composio: Composio<OpenAIProvider>composio.Composio<OpenAIProvider>.files: Files
Upload and download files
files
.
Files.upload({ file, toolSlug, toolkitSlug }: {
    file: File | string;
    toolSlug: string;
    toolkitSlug: string;
}): Promise<FileUploadData>
Upload a file to S3 and return the file data.
@paramfilePath - The path to the file to upload or a URL of the file to upload.@paramtoolSlug - The slug of the tool that is uploading the file.@paramtoolkitSlug - The slug of the toolkit that is uploading the file.@returnsThe file data.
upload
({
file: string | Filefile: const path: path.PlatformPathpath.path.PlatformPath.join(...paths: string[]): string
Join all arguments together and normalize the resulting path.
@parampaths paths to join.@throws{TypeError} if any of the path segments is not a string.
join
(var __dirname: string
The directory name of the current module. This is the same as the `path.dirname()` of the `__filename`.
@sincev0.1.27
__dirname
, 'document.pdf'),
toolSlug: stringtoolSlug: 'GOOGLEDRIVE_UPLOAD_FILE', toolkitSlug: stringtoolkitSlug: 'googledrive' });