npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

claude-agent-sdk-provider

v0.1.0

Published

Vercel AI SDK v5 provider for Claude Agent SDK

Readme

Claude Agent SDK Provider

Vercel AI SDK v5 provider for Claude Agent SDK.

Overview

This package provides a community provider that integrates Claude Agent SDK with Vercel AI SDK v5, enabling seamless communication between the two frameworks.

Installation

npm install claude-agent-sdk-provider

Requirements

  • Node.js >= 18
  • Vercel AI SDK v5
  • Claude Agent SDK ^0.1.51
  • Zod ^3.0.0 or ^4.0.0

Quick Start

Non-streaming Generation

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

const { text } = await generateText({
  model: claudeCode('sonnet'),
  prompt: 'Hello, how are you?',
});

console.log(text);

Streaming Generation

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

const { textStream } = streamText({
  model: claudeCode('sonnet'),
  prompt: 'Write a short story',
});

for await (const chunk of textStream) {
  process.stdout.write(chunk);
}

Custom Settings

import { createClaudeCode } from 'claude-agent-sdk-provider';
import { generateText } from 'ai';

const provider = createClaudeCode({
  defaultSettings: {
    maxTurns: 10,
    verbose: true,
    permissionMode: 'bypassPermissions',
  }
});

const { text } = await generateText({
  model: provider('opus'),
  prompt: 'Explain quantum computing',
});

console.log(text);

Convenience Functions

import { claudeCodeSonnet, claudeCodeOpus, claudeCodeHaiku } from 'claude-agent-sdk-provider';
import { generateText } from 'ai';

// Quick model access
const sonnetResult = await generateText({
  model: claudeCodeSonnet({ maxTurns: 5 }),
  prompt: 'Hello!',
});

const opusResult = await generateText({
  model: claudeCodeOpus({ verbose: true }),
  prompt: 'Complex task',
});

const haikuResult = await generateText({
  model: claudeCodeHaiku(),
  prompt: 'Quick answer',
});

Built-in Tools

This provider includes pre-defined tools that match all 19 Claude Agent SDK built-in tools. Pre-defining these tools eliminates "tool-error" messages when using AI SDK, while Claude Agent SDK continues to execute them internally.

Quick Usage

import { claudeCode, claudeCodeTools } from 'claude-agent-sdk-provider';
import { generateText } from 'ai';

const result = await generateText({
  model: claudeCode('sonnet'),
  tools: [
    claudeCodeTools.read({}),
    claudeCodeTools.write({}),
    claudeCodeTools.bash({}),
    claudeCodeTools.grep({}),
    claudeCodeTools.glob({}),
  ],
  prompt: 'Find and read all TypeScript files in the src directory',
});

Available Tools

All 19 built-in tools are pre-defined as provider tools:

File Operations

  • read({}) - Read file contents with optional offset/limit
  • write({}) - Write content to files
  • edit({}) - Edit existing files with exact string replacement
  • notebookEdit({}) - Edit Jupyter notebook cells

Search & Discovery

  • glob({}) - Pattern-based file matching (e.g., **/*.ts)
  • grep({}) - Search file contents with regex

Execution & Control

  • bash({}) - Execute shell commands in persistent session
  • killShell({}) - Terminate background shell processes
  • taskOutput({}) - Retrieve output from background tasks
  • agent({}) - Spawn specialized subagents

Organization & Planning

  • todoWrite({}) - Manage task lists with status tracking
  • exitPlanMode({}) - Exit planning mode, optionally launch swarm
  • askUserQuestion({}) - Ask multiple-choice questions (1-4 questions)

Web Access

  • webFetch({}) - Fetch and process web content with AI
  • webSearch({}) - Perform web searches with domain filtering

MCP Integration

  • listMcpResources({}) - List resources from MCP servers
  • readMcpResource({}) - Read specific MCP resource
  • mcp({}) - Generic MCP tool interface

Skills

  • skill({}) - Execute specialized skills

Helper Functions

Convenient groupings for common use cases:

import {
  getAllTools,      // All 19 tools
  getFileTools,     // read, write, edit, notebookEdit
  getSearchTools,   // glob, grep
  getExecutionTools,// bash, killShell, taskOutput, agent
  getWebTools,      // webFetch, webSearch
  getMcpTools,      // listMcpResources, readMcpResource, mcp
} from 'claude-agent-sdk-provider';

// Get all file operation tools
const result = await generateText({
  model: claudeCode('sonnet'),
  tools: getFileTools(),
  prompt: 'Read package.json and update the version',
});

Tool Namespace

Access tools through the claudeCodeTools namespace:

import { claudeCodeTools } from 'claude-agent-sdk-provider';

// Individual tools
const readTool = claudeCodeTools.read({});
const bashTool = claudeCodeTools.bash({});

// All tools
const allToolNames = Object.keys(claudeCodeTools);
// => ['agent', 'askUserQuestion', 'bash', 'edit', ...]

Important Notes

  • No Execution: These tool definitions are for AI SDK awareness only. Claude Agent SDK executes them internally with providerExecuted: true.
  • No Breaking Changes: Existing code without tools parameter continues working unchanged.
  • Eliminates Errors: Pre-defining tools removes "tool-error" messages while maintaining full functionality.
  • Tool Factory Pattern: All tools are factory functions requiring an empty object {} argument.

Features

Core Capabilities

  • Full AI SDK v5 Support: Implements LanguageModelV2 interface
  • Streaming: Token-by-token streaming with streamText and streamObject
  • Non-streaming: Complete response generation with generateText and generateObject
  • Tool Calling: Provider-executed tools with automatic state management
  • SubAgent Support: Nested agent execution with parent tracking
  • Structured Output: JSON schema validation with native support

Advanced Features

  • Session Management: Multi-turn conversation continuity with session IDs
  • MCP Server Integration: Connect to Model Context Protocol servers
  • Permission System: Flexible permission modes (bypassPermissions, enforce, custom)
  • Hooks System: Custom hooks for message interception and modification
  • Custom Agents: Configure inline agents with specific capabilities
  • Sandbox Settings: Fine-grained filesystem and network access control

Developer Experience

  • TypeScript: Full type safety with strict mode
  • Logging: Configurable logging with verbose mode and custom loggers
  • Error Handling: Comprehensive error types (LoadAPIKeyError, APICallError, etc.)
  • Image Support: Base64, data URLs, and binary image inputs
  • Metadata: Rich provider metadata including costs, performance, and tool usage

Available Models

  • sonnet - Claude Sonnet 4.5 (balanced performance and capability)
  • opus - Claude Opus 4.5 (maximum capability)
  • haiku - Claude Haiku 3.5 (fast and efficient)

API Reference

Provider Functions

  • claudeCode(modelId, settings?) - Default provider instance
  • createClaudeCode(options?) - Create custom provider with default settings
  • claudeCodeSonnet(settings?) - Quick Sonnet model access
  • claudeCodeOpus(settings?) - Quick Opus model access
  • claudeCodeHaiku(settings?) - Quick Haiku model access

Settings

See the ClaudeCodeSettings interface for all available options including:

  • maxTurns - Maximum conversation turns (default: 25)
  • permissionMode - Permission handling mode
  • verbose - Enable debug logging
  • mcpServers - MCP server configurations
  • hooks - Custom hook callbacks
  • And 40+ more options

Documentation

Complete Examples

Comprehensive examples are available in the examples/ directory:

  1. Basic Generation - Simple text generation, system prompts, multi-turn conversations
  2. Streaming Text - Real-time streaming, progress indicators, data stream responses
  3. Tool Calling - Custom tools, validation, error handling
  4. Image Handling - Image analysis, multiple images, data URLs
  5. Error Handling - API key errors, timeouts, retry logic, graceful degradation

Each example includes detailed comments and demonstrates best practices.

Wiki Documentation

Full documentation (in Korean) is available in the docs/wiki/ directory:

시작하기 (Getting Started)

핵심 기능 (Core Features)

설정 (Configuration)

고급 기능 (Advanced Features)

API Reference

유틸리티 (Utilities)

예제 및 모범 사례 (Examples & Best Practices)

고급 주제 (Advanced Topics)

Test Coverage

This provider is thoroughly tested with 114/120 tests passing (95%) across 8 test categories:

  • Text Generation (11 tests) - Basic generation, system prompts, token usage, finish reasons
  • Text Streaming (13 tests) - Token streaming, text deduplication, stream parts order
  • Tool Calling (9 tests) - Single/multiple tools, lifecycle, nested calls
  • Error Handling (8 tests) - API key errors, timeouts, validation
  • Multi-turn (6 tests) - Conversation history, maxTurns, turn limits
  • Image Handling (6 tests) - Data URLs, multiple images, mixed content
  • SubAgent (4 tests) - Single/multi-level nesting, parent tracking
  • ⏭️ Stream Object (6 tests skipped) - Functionality verified manually

See Test Summary for detailed test results.

Running Examples

# Install dependencies
npm install

# Run any example
npx tsx examples/01-basic-generation.ts

# Or compile and run
npm run build
node dist/examples/01-basic-generation.js

Quick Examples

Example 1: Tool Calling

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

const weatherTool = tool({
  description: 'Get the weather for a location',
  parameters: z.object({
    location: z.string(),
  }),
  execute: async ({ location }) => {
    return { temperature: 72, condition: 'Sunny' };
  },
});

const result = await generateText({
  model: claudeCode('sonnet'),
  prompt: "What's the weather in San Francisco?",
  tools: { getWeather: weatherTool },
});

console.log(result.text);

Example 2: Image Analysis

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

const result = await generateText({
  model: claudeCode('sonnet'),
  messages: [
    {
      role: 'user',
      content: [
        { type: 'text', text: 'What is in this image?' },
        { type: 'image', image: 'data:image/png;base64,...' },
      ],
    },
  ],
});

console.log(result.text);

Example 3: Provider Metadata

Access rich metadata including costs, session info, and performance metrics:

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

const result = await generateText({
  model: claudeCode('sonnet'),
  prompt: 'Explain TypeScript',
});

// Access provider-specific metadata
const metadata = result.providerMetadata?.['claude-code'];

console.log(`Session ID: ${metadata?.sessionId}`);
console.log(`Cost: $${metadata?.costUsd}`);
console.log(`Duration: ${metadata?.durationMs}ms`);
console.log(`Turns: ${metadata?.numTurns}`);
console.log(`Tokens: ${metadata?.rawUsage.input_tokens} input, ${metadata?.rawUsage.output_tokens} output`);

Example 4: Error Handling

import { generateText } from 'ai';
import { claudeCode } from 'claude-agent-sdk-provider';
import { LoadAPIKeyError } from 'ai';

try {
  const result = await generateText({
    model: claudeCode('sonnet'),
    prompt: 'Hello',
  });
  console.log(result.text);
} catch (error) {
  if (error instanceof LoadAPIKeyError) {
    console.error('Please set ANTHROPIC_API_KEY');
  } else {
    console.error('Error:', error);
  }
}

Development

Running Tests

# Run all tests
npm test

# Run integration tests only
npm test -- tests/ai-sdk-integration/

# Run specific test file
npm test -- tests/ai-sdk-integration/generate-text.test.ts

# Watch mode
npm test -- --watch

Building

# Build the project
npm run build

# Type check
npm run typecheck

# Lint
npm run lint

Contributing

Contributions are welcome! Please read the contributing guidelines before submitting a PR.

License

MIT