Technical Documentation: anthropics/anthropic-sdk-typescript
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
Claude SDK for TypeScript
The Claude SDK for TypeScript provides access to the Claude API from server-side TypeScript or JavaScript applications.
Documentation
SDK helpers (streaming, structured outputs, tool helpers and the tool runner) are documented in helpers.md. The browser and computer toolset classes have their own guides, browser-toolset.md and computer-toolset.md.
Full documentation is available at platform.claude.com/docs/en/api/sdks/typescript.
Installation
npm install @anthropic-ai/sdkGetting started
import Anthropic from '@anthropic-ai/sdk';
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-5',
});
console.log(message.content);Requirements
TypeScript >= 5.0 is supported.
The following runtimes are supported:
- Node.js 20 LTS or later (non-EOL) 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). Enable browser support by explicitly setting
dangerouslyAllowBrowsertotrue.
Note that React Native is not supported at this time.
If you are interested in other runtime environments, please open or upvote an issue.
Contributing
See CONTRIBUTING.md.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Overview (`ecosystem-tests/README.md`)
Ecosystem tests
These tests install the SDK from an npm pack tarball into small projects and run them against a local mock server (mock-server.mjs).
This checks what users actually get across runtimes, module systems, TypeScript configs, package managers and bundlers.
pnpm test:ecosystem # build, pack and run every project
pnpm test:ecosystem node-ts-esm 'browser-*' # run projects by name or glob
pnpm test:ecosystem --list # list projects and known failures
pnpm test:ecosystem --skip-build --skip-pack # reuse .pack/anthropic-ai-sdk.tgz
pnpm test:ecosystem --node-versions 20,22,24 # run the Node projects once per installed Node major
pnpm test:ecosystem --only node # only the projects --node-versions repeats; --only non-node is the rest--keep keeps the temp copies (failed projects are always kept) and --jobs N runs projects in parallel.--node-versions finds each major where actions/setup-node, nvm, fnm or volta install it, or in $ECOSYSTEM_NODE_<major> (a bin directory).--only node keeps the projects that set perNodeVersion and --only non-node keeps the others, so the two never overlap and together cover every project.
CI runs these tests from .github/workflows/ecosystem-tests.yml, split into one --only node job per Node major and one --only non-node job.
Shared test cases
shared/cases.ts holds the SDK calls every project runs (they throw on failure and use only web-standard globals) and shared/type-tests.ts the @ts-expect-error checks every project compiles; a project's own files just register the cases with its test runner or harness and add what is specific to that project (module resolution, runtime-specific uploads, extra compiler flags).
The runner copies shared/ into each project's temp copy as ./shared/; it is git-ignored inside project directories, so copy or symlink it there to work on a project in place.
Adding a project
Create ecosystem-tests/<name>/project.json with these fields (the runner picks up any directory that has one):
description: what the project covers.steps: commands (argv arrays) to run in order after install.packageManager:npm,pnpm,yarnorbun. This decides the install command.requires: binaries that must be onPATH, for example["deno"]. If one is missing the project is skipped, unless it was named on the command line.minNodeVersion: optional. The project is skipped on older Node versions.perNodeVersion: optional. With--node-versions, run the project once per listed major instead of once under the currentnode.knownFailure: optional. Why the project currently fails because of an SDK bug. A failing step then reportsXFAILinstead of failing the run (a failing install still fails it), andXPASS(which fails the run) once it passes, so the field gets removed. Put the failing step last so the other steps still run.
Pin every dependency to an exact version and commit the lockfile.
Do not list @anthropic-ai/sdk in package.json: the runner does a frozen install from the lockfile and then adds ../.pack/anthropic-ai-sdk.tgz on top, so the lockfile never pins a previous build of the SDK.
Neither install step runs dependency lifecycle scripts (--ignore-scripts and its equivalents), so a project cannot rely on a postinstall; prebuilt binaries that ship as optionalDependencies (esbuild, workerd, rolldown) still work.
Type-check with skipLibCheck: false so the published types are checked too.
Steps get ANTHROPIC_BASE_URL (the mock server) and ANTHROPIC_API_KEY in their environment, so new Anthropic() needs no options.
The key is not a credential: it is a fixed fake value that only the mock server accepts.
Code that has to name a key explicitly (a bundler define, a Worker binding) reads the same value from ECOSYSTEM_TESTS_FAKE_KEY; never reference ANTHROPIC_API_KEY explicitly in a project.
Import the cases from ./shared/cases (see above) and add the project's shared directory to its tsconfig include so shared/type-tests.ts is checked too.
The mock server answers a request the SDK built incorrectly with a 4xx whose message starts with mock:, so the test fails at the call that sent it.
Each project runs from a temp copy next to a copy of .pack/, so nothing resolves from the repo's node_modules.
Overview (`packages/bedrock-sdk/README.md`)
Claude SDK for AWS Bedrock
This library provides convenient access to the Claude API via AWS Bedrock. See the documentation for more details.
For the direct Claude API at api.anthropic.com, see @anthropic-ai/sdk.
Installation
npm install @anthropic-ai/bedrock-sdkUsage
import { AnthropicBedrock } from '@anthropic-ai/bedrock-sdk';
// Note: this assumes you have configured AWS credentials in a way
// that the AWS Node SDK will recognise, typicaly a shared `~/.aws/credentials`
// file or `AWS_ACCESS_KEY_ID` & `AWS_SECRET_ACCESS_KEY` environment variables.
//
// https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
const client = new AnthropicBedrock();
async function main() {
const message = await client.messages.create({
model: 'global.anthropic.claude-sonnet-5-5',
messages: [
{
role: 'user',
content: 'Hello!',
},
],
max_tokens: 1024,
});
console.log(message);
}
main();Custom Credential Provider (for non-Node environments)
For non-Node environments like Vercel Edge Runtime where the default AWS credential provider chain isn't available, you can provide a custom credential resolver:
import { AnthropicBedrock } from '@anthropic-ai/bedrock-sdk';
const customCredentialProvider = async () => {
// Return an object that implements the AwsCredentialIdentityProvider interface
return {
accessKeyId: 'your-aws-access-key-id',
secretAccessKey: 'your-aws-secret-access-key',
sessionToken: 'your-aws-session-token', // Optional, if using temporary credentials
};
};
const client = new AnthropicBedrock({
awsRegion: 'us-east-1',
providerChainResolver: async () => {
return customCredentialProvider;
},
});For more details on how to use the SDK, see the README.md for the main Claude SDK which this library extends.
Requirements
TypeScript >= 4.5 is supported.
The following runtimes are supported:
- Node.js 18 LTS or later (non-EOL) versions.
- Deno v1.28.0 or higher, using
import { AnthropicBedrock } from "npm:@anthropic-ai/bedrock-sdk". - 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.
Note that React Native is not supported at this time.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.
Overview (`packages/foundry-sdk/README.md`)
Claude SDK for Microsoft Foundry
This library provides convenient access to the Claude API via Microsoft Azure AI Foundry. See the documentation for more details.
For the direct Claude API at api.anthropic.com, see @anthropic-ai/sdk.
Installation
npm install @anthropic-ai/foundry-sdkUsage
Basic Usage with API Key
import { AnthropicFoundry } from '@anthropic-ai/foundry-sdk';
const client = new AnthropicFoundry({
apiKey: process.env.ANTHROPIC_FOUNDRY_API_KEY, // defaults to process.env.ANTHROPIC_FOUNDRY_API_KEY
resource: 'example-resource.azure.anthropic.com', // your Azure resource
});
const message = await client.messages.create({
model: 'claude-sonnet-5-5',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude!' }],
});
console.log(message.content);Using Azure AD Token Provider
For enhanced security, you can use Azure AD (Microsoft Entra) authentication instead of an API key:
import { AnthropicFoundry } from '@anthropic-ai/foundry-sdk';
import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity';
const credential = new DefaultAzureCredential();
const scope = 'https://ai.azure.com/.default';
const azureADTokenProvider = getBearerTokenProvider(credential, scope);
const client = new AnthropicFoundry({
azureADTokenProvider,
resource: 'example-resource.azure.anthropic.com', // your Azure resource
});
const message = await client.messages.create({
model: 'claude-sonnet-5-5',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude!' }],
});
console.log(message.content);Using Model Deployments
If you have a model deployment configured, you can specify it to have the SDK automatically construct the correct URL path:
const client = new AnthropicFoundry({
apiKey: process.env.ANTHROPIC_FOUNDRY_API_KEY,
resource: 'example-resource.azure.anthropic.com',
});
// The SDK will automatically use /deployments/my-claude-deployment/messages
const message = await client.messages.create({
model: 'claude-sonnet-5-5',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello!' }],
});Overview (`packages/google-cloud-sdk/README.md`)
Claude SDK for Claude Platform on Google Cloud
This library provides convenient access to Claude Platform on Google Cloud โ the first-party Claude API served through Google Cloud. It exposes the full Anthropic API surface and authenticates with a Google bearer token.
For the direct Claude API at api.anthropic.com, see @anthropic-ai/sdk. For the :rawPredict publisher-model API, see @anthropic-ai/vertex-sdk.
Installation
npm install @anthropic-ai/google-cloud-sdkUsage
import { AnthropicGoogleCloud } from '@anthropic-ai/google-cloud-sdk';
const client = new AnthropicGoogleCloud({
project: 'my-gcp-project', // or ANTHROPIC_GOOGLE_CLOUD_PROJECT
workspaceId: 'wrkspc_...', // or ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID
});
const message = await client.messages.create({
model: 'claude-haiku-4-5',
max_tokens: 1024,
messages: [{ role: 'user', content: 'Hello, Claude!' }],
});
console.log(message.content);See examples/ for runnable basic and streaming examples.
Configuration
| Option | Environment variable | Notes |
|---|---|---|
project |
ANTHROPIC_GOOGLE_CLOUD_PROJECT |
GCP project id, used to derive the base URL. When neither is set (and no baseURL is given), it is resolved lazily from your Google credentials at or before the first request. |
location |
ANTHROPIC_GOOGLE_CLOUD_LOCATION |
GCP location. Optional โ defaults to global. |
workspaceId |
ANTHROPIC_GOOGLE_CLOUD_WORKSPACE_ID |
Required unless skipAuth is set with an explicit baseURL. |
baseURL |
ANTHROPIC_GOOGLE_CLOUD_BASE_URL |
Overrides the base URL derived from project + location + workspaceId. |
skipAuth |
โ | Skips the bearer token, for gateways that authenticate upstream. A workspaceId is still needed unless baseURL is explicit. |
When the project is resolved lazily, await client.ready to fail fast on misconfiguration instead of waiting for the first request.
Authentication
Authentication uses a Google bearer token, resolved by precedence โ an explicit bearerTokenProvider, then a google-auth-library googleAuth / authClient, then Application Default Credentials.
This client never uses the base SDK's Anthropic credential sources: ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, and profile config files are all ignored, and the only Authorization header it sends is the Google bearer token.
Application Default Credentials
Set up ADC (e.g. gcloud auth application-default login) and the client fetches and refreshes a bearer token for you, no auth options needed.
Custom Google credentials
Pass a GoogleAuth or AuthClient to override the default credential chain (for example to use impersonated credentials):
import { AnthropicGoogleCloud } from '@anthropic-ai/google-cloud-sdk';
import { GoogleAuth } from 'google-auth-library';
const client = new AnthropicGoogleCloud({
project: 'my-gcp-project',
workspaceId: 'wrkspc_...',
googleAuth: new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }),
});Bearer token provider
If you already mint Google access tokens yourself, supply a bearerTokenProvider. It is invoked on every request and takes precedence over googleAuth / authClient and ADC:
const client = new AnthropicGoogleCloud({
project: 'my-gcp-project',
workspaceId: 'wrkspc_...',
bearerTokenProvider: async () => myTokenSource.getAccessToken(),
});Pre-authenticated proxy
If a gateway or proxy authenticates upstream on your behalf, set skipAuth to skip the bearer token (with an explicit baseURL, no workspaceId is needed):
const client = new AnthropicGoogleCloud({
baseURL: 'https://my-proxy.example.com',
skipAuth: true,
});Overview (`packages/vertex-sdk/README.md`)
Claude SDK for Google Vertex
This library provides convenient access to the Claude API via Google Vertex AI. See the documentation for more details.
For the direct Claude API at api.anthropic.com, see @anthropic-ai/sdk.
Installation
npm install @anthropic-ai/vertex-sdkUsage
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Reads from the `CLOUD_ML_REGION` & `ANTHROPIC_VERTEX_PROJECT_ID` environment variables.
// Additionally goes through the standard `google-auth-library` flow.
const client = new AnthropicVertex();
async function main() {
const result = await client.messages.create({
messages: [
{
role: 'user',
content: 'Hey Claude!',
},
],
model: 'claude-sonnet-5-5',
max_tokens: 300,
});
console.log(JSON.stringify(result, null, 2));
}
main();For more details on how to use the SDK, see the README.md for the main Claude SDK which this library extends.
Authentication
This library supports multiple authentication methods:
Default authentication
The client automatically uses the default Google Cloud authentication flow:
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
// Uses default authentication and environment variables
const client = new AnthropicVertex({
region: 'us-central1',
projectId: 'my-project-id',
});Custom GoogleAuth configuration
You can customize the authentication using the googleAuth option:
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
import { GoogleAuth } from 'google-auth-library';
const client = new AnthropicVertex({
googleAuth: new GoogleAuth({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
keyFile: '/path/to/service-account.json',
}),
region: 'us-central1',
projectId: 'my-project-id',
});Pre-configured AuthClient
For advanced use cases like impersonation, you can provide a pre-configured AuthClient:
import { AnthropicVertex } from '@anthropic-ai/vertex-sdk';
import { GoogleAuth, Impersonated } from 'google-auth-library';
// Create an impersonated credential
const authClient = new Impersonated({
sourceClient: await new GoogleAuth().getClient(),
targetPrincipal: '[email protected]',
lifetime: 30,
delegates: [],
targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
});
const client = new AnthropicVertex({
authClient,
region: 'us-central1',
projectId: 'my-project-id',
});Requirements
TypeScript >= 4.5 is supported.
The following runtimes are supported:
- Node.js 18 LTS or later (non-EOL) versions.
- Deno v1.28.0 or higher, using
import { AnthropicVertex } from "npm:@anthropic-ai/vertex-sdk". - 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.
Note that React Native is not supported at this time.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.
Overview (`src/core/README.md`)
`core`
This directory holds public modules implementing non-resource-specific SDK functionality.
Overview (`src/internal/README.md`)
`internal`
The modules in this directory are not importable outside this package and will change between releases.
Overview (`src/_vendor/partial-json-parser/README.md`)
Partial JSON Parser
Vendored from https://www.npmjs.com/package/partial-json-parser and updated to use TypeScript.
Overview (`src/internal/qs/README.md`)
qs
This is a vendored version of neoqs which is a TypeScript rewrite of qs, a query string library.
--- METRICS ---
- Files Extracted: 10
- Estimated Token Budget: ~5336 tokens
- Canonical Reference: https://codewiki.google/github.com/anthropics/anthropic-sdk-typescript