Sandbox
@ben-vargas/ai-sdk-provider-claude-code

AI SDK provider for Claude Code

This package lets you use Claude through Vercel AI SDK by routing model calls to the Claude Agent SDK and Claude Code CLI. It handles streaming, multi-turn conversation, structured outputs, tools, sessions, and callback hooks so your app can treat Claude like a standard AI SDK model.

365 stars55 forksTypeScriptUpdated 9d ago
Who it's for

Builders who use Vercel AI SDK and want Claude Code as the model backend.

What it delivers

You can add Claude-powered generation, tool use, and session control to an AI SDK app with one provider import.

What it does

AI SDK model provider

Exports `claudeCode()` so AI SDK apps can call Claude like a normal model.

Streaming and multi-turn chat

Supports `streamText()`, conversation history, and session resume or fork flows.

Structured outputs

Works with AI SDK output schemas and constrained decoding for object, array, and choice outputs.

Tool and MCP support

Handles tool management, MCP servers, permissions, and tool streaming events.

Callbacks and query control

Exposes `onSdkMessage`, hook and task events, `canUseTool`, `onElicitation`, and query-controller access.

Versioned compatibility

Documents support lines for AI SDK v7, v6, v5, and legacy Claude SDK versions.

How to get it

  1. 1See the official docs for platform-specific options.
    curl -fsSL https://claude.ai/install.sh | bash
    claude auth login

README

stable status npm version install size npm downloads Node.js ≥ 22 License: MIT

AI SDK Provider for Claude Agent SDK

Latest Release: Version 4.x supports AI SDK v7 stable with the Claude Agent SDK. Version 3.x moves to maintenance for AI SDK v6 under the ai-sdk-v6 tag.

ai-sdk-provider-claude-code lets you use Claude via the Vercel AI SDK through the official @anthropic-ai/claude-agent-sdk and the Claude Code CLI.

Version Compatibility

Provider VersionAI SDK VersionUnderlying SDKNPM TagStatusBranch
4.x.xv7@anthropic-ai/claude-agent-sdklatestStablemain
3.x.xv6@anthropic-ai/claude-agent-sdkai-sdk-v6Maintenanceai-sdk-v6
2.x.xv5@anthropic-ai/claude-agent-sdkai-sdk-v5Legacyai-sdk-v5
1.x.xv5@anthropic-ai/claude-codev1-claude-code-sdkLegacyv1
0.x.xv4@anthropic-ai/claude-codeai-sdk-v4Legacyai-sdk-v4

Install commands for each line are listed under Installation below.

Zod Compatibility

The 4.x line requires Zod ^4.1.8. Version 3.x remains available for AI SDK v6 under the ai-sdk-v6 tag.

npm install ai-sdk-provider-claude-code ai zod@^4.1.8

Note: Zod 3 support was dropped in v3.2.0 due to the underlying @anthropic-ai/claude-agent-sdk@0.2.x requiring Zod 4. If you need Zod 3 support, use ai-sdk-provider-claude-code@3.1.x.

Installation

1. Install and authenticate the CLI

See the official docs for platform-specific options.

curl -fsSL https://claude.ai/install.sh | bash
claude auth login

2. Add the provider

# For AI SDK v7 (4.x; current latest tag)
npm install ai-sdk-provider-claude-code ai

# For AI SDK v6 maintenance (3.x)
npm install ai-sdk-provider-claude-code@ai-sdk-v6 ai@^6.0.0

# For AI SDK v5
npm install ai-sdk-provider-claude-code@ai-sdk-v5 ai@^5.0.0

# For AI SDK v4 (legacy)
npm install ai-sdk-provider-claude-code@ai-sdk-v4 ai@^4.3.16
# or use a specific version: npm install ai-sdk-provider-claude-code@^0.2.2

Disclaimer

This is an unofficial community provider and is not affiliated with or endorsed by Anthropic or Vercel. By using this provider:

  • You understand that your data will be sent to Anthropic's servers through the Claude Agent SDK
  • You agree to comply with Anthropic's Terms of Service
  • You acknowledge this software is provided "as is" without warranties of any kind

Please ensure you have appropriate permissions and comply with all applicable terms when using this provider.

Quick Start

AI SDK v7 (latest)

// npm install ai-sdk-provider-claude-code ai
import { streamText } from 'ai';
import { claudeCode } from 'ai-sdk-provider-claude-code';

const result = streamText({
  model: claudeCode('haiku'),
  prompt: 'Hello, Claude!',
});

const text = await result.text;
console.log(text);

AI SDK v6 (maintenance)

// npm install ai-sdk-provider-claude-code@ai-sdk-v6 ai@^6.0.0
import { streamText } from 'ai';
import { claudeCode } from 'ai-sdk-provider-claude-code';

const result = streamText({
  model: claudeCode('haiku'),
  prompt: 'Hello, Claude!',
});

const text = await result.text;
console.log(text);

AI SDK v5

// npm install ai-sdk-provider-claude-code@ai-sdk-v5 ai@^5.0.0
import { streamText } from 'ai';
import { claudeCode } from 'ai-sdk-provider-claude-code';

const result = streamText({
  model: claudeCode('haiku'),
  prompt: 'Hello, Claude!',
});

const text = await result.text;
console.log(text);

Breaking Changes

Version 4.0.0 (AI SDK v7)

This release ports the provider to AI SDK v7 / LanguageModelV4, adds first-class Claude Agent SDK callback, query-controller, MCP, and image support, and keeps the v7 support boundaries explicit:

  • Requires Node.js ≥ 22 and Zod ^4.1.8
  • ESM-only package output; CommonJS require() is no longer available
  • Tool failures now use spec tool-result parts/events with isError: true instead of the provider-specific tool-error stream extension

Optional AI SDK v7 surfaces not implemented

Version 4.0.0 intentionally keeps optional provider surfaces absent unless the Claude Agent SDK has a durable provider-reference mapping:

  • ProviderV4.files() is not implemented yet. The AI SDK interface uploads { type: 'data' } or { type: 'text' } bytes and returns a reusable provider reference, but Claude Agent SDK 0.3.263 exposes no direct upload/reuse API for that contract. This provider forwards inline image file parts in prompts; non-image inline files (for example PDFs) emit an unsupported-file call warning and are not forwarded. It does not upload files into durable provider references.
  • Canonical V4 tool-result file parts are replayed into conversation history as text markers like [File <name>: <mediaType>]; raw file bytes are not re-sent on replay. Richer tool-result file replay, such as re-sending actual image/file bytes for tool-result file parts, is deferred.
  • ProviderV4.skills() is not implemented yet. Claude Code skills are loaded from configured user/project/local skill directories with the existing skills setting below; there is no Agent SDK API that uploads a skill bundle and returns an AI SDK provider reference.
  • Workflow serialization is deferred. @ai-sdk/provider-utils@5.0.27 exposes WORKFLOW_SERIALIZE, WORKFLOW_DESERIALIZE, and serializeModelOptions() for provider model classes in the AI SDK v7 stack, but this provider has not added a serialization contract for provider instances or settings. Callback/function settings such as canUseTool, hooks, logger, spawnClaudeCodeProcess, and SessionStore methods are not JSON-serializable and must be recreated by the application.
  • V4 custom and reasoning-file parts are not emitted as provider output yet. Claude Agent SDK 0.3.263 has no durable reasoning-file artifact output that maps to AI SDK reasoning-file; assistant-history custom and reasoning-file parts have no Claude Code replay representation and are skipped (unknown unsupported content variants still warn).

Version 3.0.0 (AI SDK v6 Stable)

This version upgrades to AI SDK v6 stable with updated provider types:

  • usage.raw now contains raw provider usage (previously in providerMetadata['claude-code'].rawUsage)
  • Internal type changes for LanguageModelV3Usage and LanguageModelV3FinishReason (transparent to most users)

Version 2.0.0 (Claude Agent SDK Migration)

This version migrates to @anthropic-ai/claude-agent-sdk with new defaults for better control:

  • System prompt is no longer applied by default
  • Filesystem settings (CLAUDE.md, settings.json) are no longer loaded by default
  • See Migrating to Claude Agent SDK section below for migration details

Version 1.x (AI SDK v5)

See Breaking Changes Guide for details on migrating from v0.x to v1.x.

Key changes:

  • Requires AI SDK v5
  • New streaming API pattern
  • Updated token usage properties
  • Changed message types

Models

  • fable - Claude Fable (most capable)
  • opus - Claude Opus (highly capable)
  • sonnet - Claude Sonnet (balanced performance)
  • haiku - Claude Haiku (fastest, most cost-effective)

You can also use full model identifiers directly (e.g., claude-fable-5, claude-sonnet-4-6, claude-opus-4-8).

Documentation

  • Session Management - Creating, resuming, forking, inspecting, and deleting sessions
  • Examples - Sample scripts and patterns
  • Usage Guide - Comprehensive examples and configuration (written for provider 2.x / AI SDK v5; most patterns still apply)
  • Troubleshooting - Common issues and solutions (written for provider 2.x / AI SDK v5)
  • Tool Streaming Support - Event semantics and performance notes (written for provider 2.x / AI SDK v5)
  • Breaking Changes - v0.x to v1.x migration guide (historical)

The docs/ai-sdk-v4/ and docs/ai-sdk-v5/ directories cover legacy provider versions (0.x and 1.x–2.x respectively) and are kept for reference.

Migrating to Claude Agent SDK (v2.0.0)

Version 2.0.0 migrates from @anthropic-ai/claude-code to @anthropic-ai/claude-agent-sdk. Two defaults changed:

  • System prompt is no longer applied by default.
  • Filesystem settings (CLAUDE.md, settings.json) are not loaded by default.

Restore old behavior explicitly:

import { claudeCode } from 'ai-sdk-provider-claude-code';

const model = claudeCode('sonnet', {
  systemPrompt: { type: 'preset', preset: 'claude_code' },
  settingSources: ['user', 'project', 'local'],
});

CLAUDE.md requires:

  • systemPrompt: { type: 'preset', preset: 'claude_code' }
  • settingSources includes 'project'

New recommended behavior (explicit config):

const model = claudeCode('sonnet', {
  systemPrompt: 'You are a helpful assistant specialized in ...',
  settingSources: ['project'], // or omit for no filesystem settings
});

CLI install and auth are unchanged:

curl -fsSL https://claude.ai/install.sh | bash
claude auth login

Migrating from v1.x to v2.0.0

If you're upgrading from version 1.x:

  1. Update the package: npm install ai-sdk-provider-claude-code@ai-sdk-v5
  2. If you relied on default system prompt or CLAUDE.md, add explicit configuration:
    const model = claudeCode('sonnet', {
      systemPrompt: { type: 'preset', preset: 'claude_code' },
      settingSources: ['user', 'project', 'local'],
    });
    
  3. If you never used CLAUDE.md or custom system prompts, no changes needed - v2.0.0 works the same for you.

Benefits of v2.0.0:

  • Predictable behavior across environments (no hidden filesystem settings)
  • Better suited for CI/CD and multi-tenant applications
  • Explicit configuration over implicit defaults
  • Future-proof alignment with Claude Agent SDK design

Structured Outputs

This provider supports native structured outputs via Claude Agent SDK constrained decoding. On the 4.x line (AI SDK v7), use generateText() with an output specification such as Output.object({ schema }), then destructure output from the result. For streaming structured output, use streamText() with the same output setting and read partialOutputStream as partial objects arrive.

import { generateText, Output } from 'ai';
import { claudeCode } from 'ai-sdk-provider-claude-code';
import { z } from 'zod';

const UserProfileSchema = z.object({
  name: z.string(),
  age: z.number(),
  email: z.string().describe('Email address (validate client-side)'),
});

const { output } = await generateText({
  model: claudeCode('sonnet'),
  output: Output.object({ schema: UserProfileSchema }),
  prompt: 'Generate a user profile for a software developer',
});

console.log(output); // Matches the schema above
// { name: "Alex Chen", age: 28, email: "alex@example.com" }

Benefits:

  • Schema compliance (supported features) - Constrained decoding ensures valid output
  • No JSON parsing errors - AI SDK handles validation against your schema
  • No prompt engineering - Schema enforcement is native to the SDK
  • Better performance - No retry/extraction logic needed

Note: Schema-less JSON output (AI SDK v7 Output.json()) is not supported by Claude Code; use Output.object() / Output.array() / Output.choice() with a schema or choices. The provider emits a V4 unsupported warning with feature: 'responseFormat' and treats the call as plain text.

Current CLI limitation: Some JSON Schema features can cause the Claude Code CLI to silently fall back to prose (no structured_output). The provider mitigates the most common case: format keywords (date-time, email, uri, uuid, ... — produced by Zod's .datetime(), .email(), .url(), .uuid()) are stripped client-side before the schema is sent, with the hint folded into the field's description (e.g., (expected format: email)). Server-side enforcement of format still does not exist in the CLI, but the AI SDK validates output against your original Zod schema client-side, so nothing is lost. Complex regex patterns (lookaheads/backreferences) remain unmitigated — pattern is passed through untouched because the CLI genuinely rejects some patterns. Keep generation schemas simple and enforce stricter invariants after generation.

If you are staying on the 3.x (AI SDK v6) line, its legacy structured-output examples may still use generateObject() / streamObject(); new 4.x code should use generateText() / streamText() with Output.

Core Features

  • 🚀 Vercel AI SDK compatibility
  • 🔄 Streaming support
  • 💬 Multi-turn conversations
  • 🎯 Native structured outputs with schema compliance for supported features
  • 🛑 AbortSignal support
  • 🔧 Tool management (MCP servers, permissions)
  • 🧩 Callbacks (onSdkMessage, task/hook/MCP status events, canUseTool, onElicitation)
  • 🎛️ Query controller access for safe live-session controls

AI SDK v7 app-level features

DevTools and OpenTelemetry/OTel telemetry registration are app-level ai package features. This provider exposes standard AI SDK v7 metadata and stream parts for them, but adds no runtime dependencies for DevTools or OTel.

Agent SDK Options (Advanced)

This provider exposes Agent SDK options directly. Key options include:

OptionDescription
betasEnable beta features (e.g., ['context-1m-2025-08-07'])
sandboxConfigure sandbox behavior ({ enabled: true }). Cannot be combined with a settings file path (inline settings objects are fine)
pluginsLoad custom plugins from local paths
resumeSessionAtResume session at a specific message UUID
resumeDropsTurnGuard resume + resumeSessionAt with the discarded prompt UUID; consumed after success. See guarded rewind
enableFileCheckpointingEnable file rewind support
maxBudgetUsdMaximum budget in USD for the query
toolsTool configuration (array of names or preset)
allowDangerouslySkipPermissionsAllow bypassing permissions
persistSessionWhen false, disables session persistence to disk (v3.2.0+)
spawnClaudeCodeProcessCustom process spawner for VMs/containers (v3.2.0+)
permissionModePermission mode: 'default', 'acceptEdits', 'bypassPermissions', 'plan', 'dontAsk', 'auto' ('auto' and 'dontAsk' added in SDK 0.3.x; 'delegate' was removed in SDK 0.3.x and the CLI rejects it, so the provider rejects it at validation time)
sessionIdUse a specific session ID for deterministic tracking and correlation (v3.4.0+). Must be a valid UUID; cannot be combined with continue/resume unless forkSession is also set
debugEnable programmatic debug logging from the SDK (v3.4.0+)
debugFilePath to a file for SDK debug log output (v3.4.0+)
effortEffort level: 'low', 'medium', 'high', 'xhigh', or 'max'
thinkingThinking config: { type: 'adaptive' }, { type: 'enabled', budgetTokens?: number }, or { type: 'disabled' }
promptSuggestionsEnable prompt suggestions (boolean)
skillsEnable skills for the session: 'all' or an array of skill names (v3.5.0+)
settingsInline Settings object or path to a settings JSON file (v3.5.0+)
managedSettingsRestrictive policy-tier settings enforced on the subprocess (v3.5.0+)

Files in the repo

Repository payload17 top-level entries
  • .github
  • docs
  • examples
  • src
  • .gitignore
  • .prettierrc
  • AGENTS.md
  • CHANGELOG.md
  • eslint.config.js
  • LICENSE
  • package-lock.json
  • package.json
  • README.md
  • run-all-examples.sh
  • tsconfig.json
  • tsup.config.ts
  • vitest.config.ts

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More frameworks & sdks

HKUDS/nanobotFrameworks & SDKs

Ultra-lightweight, open-source, self-hosted personal AI agent framework in Python with WebUI, tools, memory, MCP, multi-agent workflows, automation, and chat apps

48k
microsoft/
SkillOpt
microsoft/SkillOptFrameworks & SDKs

SkillOpt is a text-space optimizer that trains reusable natural-language skills for frozen LLM agents through trajectory-driven edits, validation-gated updates, and deployable best_skill.md artifacts.

17k
omnigent-ai/omnigentFrameworks & SDKs

Omnigent is an open-source AI agent framework and meta-harness: orchestrate Claude Code, Codex, Cursor, Pi, and custom agents — swap harnesses without rewriting, enforce policies and sandboxing, and collaborate in real time from any device.

9.8k
kyegomez/
OpenMythos
kyegomez/OpenMythosFrameworks & SDKs

A theoretical reconstruction of the Claude Mythos architecture, built from first principles using the available research literature.

15k
D4Vinci/ScraplingFrameworks & SDKs

🕷️ An adaptive Web Scraping framework that handles everything from a single request to a full-scale crawl!

80k