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 asynciofrom dotenv import load_dotenvfrom claude_agent_sdk.client import ClaudeSDKClientfrom claude_agent_sdk.types import ( ClaudeAgentOptions, AssistantMessage, TextBlock, ToolUseBlock,)from composio import Composioload_dotenv()# Initialize Composio (API key from env var COMPOSIO_API_KEY or pass explicitly)composio = Composio()# Unique identifier of the useruser_id = "user_123"# Create a tool router session for the usersession = composio.create(user_id=user_id)# Configure Claude with Composio MCP serveroptions = 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
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" })constconst composio: Composio<OpenAIProvider>composio = newnew 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 userconstconst userId: "user_123"userId = "user_123";// Create a tool router session for the userconstconst session: ToolRouterSession<unknown, unknown, OpenAIProvider>session = awaitconst 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());
```
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.
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 conversationconstconst 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
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.
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
```
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'`);letlet isFirstQuery: booleanisFirstQuery= true;// Multi-turn conversation with agentic tool callingwhile (true) { constconst answer: stringanswer = awaitconst 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`.
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.
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`.
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 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)" }]
```
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.
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`.
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.
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`.
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
```
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.
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.
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`.
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.
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()
});
```
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
})
});
```
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.
# Define your user IDuser_id = "your-user-id"# Get GitHub tool for listing stargazerstools = composio.tools.get(user_id=user_id, tools=["GITHUB_LIST_STARGAZERS"])# Get response from the LLMresponse = anthropic_client.messages.create( model="claude-sonnet-4-5", max_tokens=1024, tools=tools, messages=[ {"role": "user", "content": "List my github stargazers. for the repo composiohq/composio"}, ],)# Execute the function calls.result = composio.provider.handle_tool_calls(user_id=user_id, response=response)print(result)
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'};
}
});
```
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)
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: "List my github stargazers. for the repo composiohq/composio", }, ],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.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.
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);
```
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
```
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.