typescript
cli-sdks-libraries/sdks/typescript
History
cli-sdks-libraries/sdks/typescript Changed · +1 / -1 lines
} ``` -For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). +For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication). If your API key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, set the workspace ID in the `anthropic-workspace-id` request header; [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace) shows the per-request option for this SDK. ## Request and response types
cli-sdks-libraries/sdks/typescript Changed · +9 / -23 lines
// Upload MCP resources as files const fileResource = await mcpClient.readResource({ uri: "file:///path/to/data.json" }); -await anthropic.beta.files.upload({ file: mcpResourceToFile(fileResource) }); +await anthropic.files.upload({ file: mcpResourceToFile(fileResource) }); ``` ### MCP error handling
const client = new Anthropic(); // If you have access to Node `fs`, use `fs.createReadStream()`: -await client.beta.files.upload({ +await client.files.upload({ file: await toFile(fs.createReadStream("/path/to/file"), undefined, { type: "application/json" })
}); // Or if you have the web `File` API you can pass a `File` instance: -await client.beta.files.upload({ +await client.files.upload({ file: new File(["my bytes"], "file.txt", { type: "text/plain" }) }); // You can also pass a `fetch` `Response`: -await client.beta.files.upload({ +await client.files.upload({ file: await fetch("https://somesite/file") }); // Or a `Buffer` / `Uint8Array` -await client.beta.files.upload({ +await client.files.upload({ file: await toFile(Buffer.from("my bytes"), "file", { type: "text/plain" }) }); -await client.beta.files.upload({ +await client.files.upload({ file: await toFile(new Uint8Array([0, 1, 2]), "file", { type: "text/plain" }) }); ```
You can access most beta API features through the beta property of the client. To enable a particular beta feature, you need to add the appropriate [beta header](https://platform.claude.com/docs/en/api/beta-headers) to the `betas` field when creating a message. -For example, to use the [Files API](https://platform.claude.com/docs/en/build-with-claude/files): +For example, to enable [context editing](https://platform.claude.com/docs/en/build-with-claude/context-editing): ```typescript const client = new Anthropic();
const response = await client.beta.messages.create({ model: "claude-opus-5", max_tokens: 1024, - messages: [ - { - role: "user", - content: [ - { type: "text", text: "Please summarize this document for me." }, - { - type: "document", - source: { - type: "file", - file_id: "file_abc123" - } - } - ] - } - ], - betas: ["files-api-2025-04-14"] + messages: [{ role: "user", content: "Hello, Claude" }], + betas: ["context-management-2025-06-27"] }); ```
cli-sdks-libraries/sdks/typescript First recorded · 812 lines, first recorded
## Installation ## Requirements ## Usage ## Request and response types ## Counting tokens ## Streaming responses ## Streaming helpers ## Tool helpers ### Tool errors ## Tool use ## MCP helpers ### MCP error handling ## Message batches ### Creating a batch ### Getting results from a batch ## File uploads ## Handling errors ## Request IDs ## Retries ## Timeouts ## Long requests ## Auto-pagination ## Default headers ## Advanced usage ### Accessing raw Response data (for example, headers) ### Logging #### Log levels #### Custom logger ### Making custom/undocumented requests #### Undocumented endpoints #### Undocumented request parameters #### Undocumented response properties ### Customizing the fetch client ### Fetch options ### Configuring proxies ## Beta features ## Runtime support ## Platform integrations ## Semantic versioning ## Frequently asked questions ## Additional resources
The first capture of this source. The page was already there, and this is what it said.
---
title: TypeScript SDK
url: https://platform.claude.com/docs/en/cli-sdks-libraries/sdks/typescript
description: Install and configure the Anthropic TypeScript SDK for Node.js, Deno, Bun, and browser environments
---
This library provides convenient access to the Claude API from TypeScript or JavaScript.
<Info>
For API feature documentation with code examples, see the [API reference](https://platform.claude.com/docs/en/api/overview). This page covers TypeScript-specific SDK features and configuration.
</Info>
## Installation
```bash
npm install @anthropic-ai/sdk
```
## Requirements
TypeScript >= 4.9 is supported.
The following runtimes are supported:
* Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) versions.
* Deno v1.28.0 or higher.
* Bun 1.0 or later.
* Cloudflare Workers.
* Vercel Edge Runtime.
* Jest 28 or greater with the `"node"` environment (`"jsdom"` is not supported at this time).
* Nitro v2.6 or greater.
* Web browsers: disabled by default to avoid exposing your secret API credentials (see [API key best practices](https://support.claude.com/en/articles/9767949-api-key-best-practices-keeping-your-keys-safe-and-secure)). Enable browser support by explicitly setting `dangerouslyAllowBrowser` to `true`.
Note that React Native is not supported at this time.
If you are interested in other runtime environments, open or upvote an issue on the [GitHub repository](https://github.com/anthropics/anthropic-sdk-typescript).
## Usage
```typescript
const client = new Anthropic({
apiKey: process.env["ANTHROPIC_API_KEY"] // This is the default and can be omitted
});
const message = await client.messages.create({
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: "claude-opus-5"
});
for (const block of message.content) {
if (block.type === "text") {
console.log(block.text);
}
}
```
For authentication options including Workload Identity Federation, see [Authentication](https://platform.claude.com/docs/en/manage-claude/authentication).
## Request and response types
This library includes TypeScript definitions for all request parameters and response fields. You may import and use them like so:
```typescript
const client = new Anthropic({
apiKey: process.env["ANTHROPIC_API_KEY"] // This is the default and can be omitted
});
const params: Anthropic.MessageCreateParams = {
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: "claude-opus-5"
};
const message: Anthropic.Message = await client.messages.create(params);
```
Documentation for each method, request parameter, and response field is available in docstrings and appears on hover in most modern editors.
## Counting tokens
You can see the exact usage for a given request through the `usage` response property, for example:
```typescript
const message = await client.messages.create(/* ... */);
console.log(message.usage);
// { input_tokens: 25, output_tokens: 13 }
```
## Streaming responses
The SDK provides support for streaming responses using Server Sent Events (SSE).
```typescript
const client = new Anthropic();
const stream = await client.messages.create({
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, Claude" }],
model: "claude-opus-5",
stream: true
});
for await (const messageStreamEvent of stream) {
console.log(messageStreamEvent.type);
}
```
If you need to cancel a stream, you can `break` from the loop or call `stream.controller.abort()`.
## Streaming helpers
This library provides several conveniences for streaming messages, for example:
```typescript
const anthropic = new Anthropic();
const stream = anthropic.messages
.stream({
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: "Say hello there!"
}
]
})
.on("text", (text) => {
console.log(text);
});
const message = await stream.finalMessage();
console.log(message);
```
Streaming with `client.messages.stream(...)` exposes various helpers for your convenience including event handlers and accumulation.
Alternatively, you can use `client.messages.create({ ..., stream: true })` which only returns an async iterable of the events in the stream and thus uses less memory (it does not build up a final message object for you).
## Tool helpers
This SDK provides helpers for making it easy to create and run tools in the Messages API. You can use Zod schemas or JSON Schemas to describe the input to a tool. You can then run those tools using the `client.beta.messages.toolRunner()` method. This method handles passing the inputs generated by the chosen model into the right tool and passing the result back to the model.
For more details on tool use, see [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
```typescript
import { betaZodTool } from "@anthropic-ai/sdk/helpers/beta/zod";
import { z } from "zod";
const anthropic = new Anthropic();
const weatherTool = betaZodTool({
name: "get_weather",
inputSchema: z.object({
location: z.string()
}),
description: "Get the current weather in a given location",
run: (input) => {
return `The weather in ${input.location} is foggy and 60°F`;
}
});
const finalMessage = await anthropic.beta.messages.toolRunner({
model: "claude-opus-5",
max_tokens: 1000,
messages: [{ role: "user", content: "What is the weather in San Francisco?" }],
tools: [weatherTool]
});
console.log(finalMessage.content);
```
### Tool errors
To report an error from a tool back to the model, throw a `ToolError` from the `run` function. Unlike a plain `Error`, `ToolError` accepts content blocks, allowing you to include images or other structured content in the error response:
```typescript
import { ToolError } from "@anthropic-ai/sdk/lib/tools/BetaRunnableTool";
const screenshotTool = betaZodTool({
name: "take_screenshot",
inputSchema: z.object({ url: z.string() }),
run: async (input) => {
if (!isValidUrl(input.url)) {
throw new ToolError(`Invalid URL: ${input.url}`);
}
const result = await takeScreenshot(input.url);
if (result.error) {
// Include the error screenshot so the model can see what went wrong
throw new ToolError([
{ type: "text", text: `Failed to load page: ${result.error}` },
{
type: "image",
source: { type: "base64", data: result.screenshot, media_type: "image/png" }
}
]);
}
return {
type: "image",
source: { type: "base64", data: result.screenshot, media_type: "image/png" }
};
}
});
```
If a plain `Error` is thrown, the message will be converted to a text content block.
## Tool use
This SDK provides support for tool use, also known as function calling. For more details, see [Tool use with Claude](https://platform.claude.com/docs/en/agents-and-tools/tool-use/overview).
## MCP helpers
This SDK provides helpers for integrating with [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) servers. These helpers convert MCP types to Claude API types, reducing boilerplate when working with MCP tools, prompts, and resources.
<Tip>
The Claude API also supports an [`mcp_servers` parameter](https://platform.claude.com/docs/en/agents-and-tools/mcp-connector) that lets Claude connect directly to remote MCP servers. Use `mcp_servers` when you have remote servers accessible by URL and only need tool support. Use the MCP helpers when you need local MCP servers, prompts, resources, or more control over the MCP connection.
</Tip>
```typescript
import {
mcpTools,
mcpMessages,
mcpResourceToContent,
mcpResourceToFile
} from "@anthropic-ai/sdk/helpers/beta/mcp";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
const anthropic = new Anthropic();
// Connect to an MCP server
const transport = new StdioClientTransport({ command: "mcp-server", args: [] });
const mcpClient = new Client({ name: "my-client", version: "1.0.0" });
await mcpClient.connect(transport);
// Use MCP prompts
const { messages } = await mcpClient.getPrompt({ name: "my-prompt" });
const response = await anthropic.beta.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: mcpMessages(messages)
});
console.log(response.content);
// Use MCP tools with toolRunner
const { tools } = await mcpClient.listTools();
const finalMessage = await anthropic.beta.messages.toolRunner({
model: "claude-opus-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Use the available tools" }],
tools: mcpTools(tools, mcpClient)
});
console.log(finalMessage.content);
// Use MCP resources as content
const resource = await mcpClient.readResource({ uri: "file:///path/to/doc.txt" });
await anthropic.beta.messages.create({
model: "claude-opus-5",
max_tokens: 1024,
messages: [
{
role: "user",
content: [
mcpResourceToContent(resource),
{ type: "text", text: "Summarize this document" }
]
}
]
});
// Upload MCP resources as files
const fileResource = await mcpClient.readResource({ uri: "file:///path/to/data.json" });
await anthropic.beta.files.upload({ file: mcpResourceToFile(fileResource) });
```
### MCP error handling
The conversion functions throw `UnsupportedMCPValueError` if an MCP value isn't supported by the Claude API (for example, unsupported content type, unsupported MIME type, non-http/https resource link).
## Message batches
This SDK provides support for [Batch processing](https://platform.claude.com/docs/en/build-with-claude/batch-processing) under the `client.messages.batches` namespace.
### Creating a batch
Message Batches takes an array of requests, where each object has a `custom_id` identifier, and the exact same request `params` as the standard Messages API:
```typescript
const batch = await client.messages.batches.create({
requests: [
{
custom_id: "my-first-request",
params: {
model: "claude-opus-5",
max_tokens: 1024,
messages: [{ role: "user", content: "Hello, world" }]
}
},
{
custom_id: "my-second-request",
Cut at 300 lines.