@ag-ui/claude-agent-sdk

中文文档
0.0.8发布于 2026/10/21MITTypeScriptESM + CJS构建来源已验证近 30 天下载 7672

AG-UI integration for Anthropic Claude Agent SDK

原始使用文档
文档目录8 节
  1. Installation
  2. Usage
  3. Features
  4. Examples
  5. Running the Examples
  6. Links
  7. Content and state preservation
  8. Session recovery (PNI-659, unreleased)

@ag-ui/claude-agent-sdk

Implementation of the AG-UI protocol for the Anthropic Claude Agent SDK (TypeScript).

Installation

npm install @ag-ui/claude-agent-sdk @anthropic-ai/claude-agent-sdk zod

Usage

The adapter manages the SDK lifecycle internally — just call adapter.run(input):

import { ClaudeAgentAdapter } from "@ag-ui/claude-agent-sdk";

const adapter = new ClaudeAgentAdapter({
  agentId: "my_agent",
  model: "claude-haiku-4-5",
  systemPrompt: "You are helpful",
});

const events$ = adapter.run(input);
events$.subscribe({
  next: (event) => sendEvent(event),
  complete: () => res.end(),
});

Features

  • Full lifecycle management - Handles message extraction, option building, and SDK querying internally
  • Interrupt support - Call adapter.interrupt() to stop a running query
  • Dynamic frontend tools - Client-provided tools automatically added as MCP server
  • Frontend tool halting - Streams pause after frontend tool calls for client-side execution (human-in-the-loop)
  • Streaming tool arguments - Real-time TOOL_CALL_ARGS emission as JSON arguments stream in
  • Bidirectional state sync - Shared state management via ag_ui_update_state tool
  • Context injection - Context and state injected into prompts for agent awareness
  • Event cleanup - Hanging events (tool calls, reasoning blocks) automatically closed on stream end
  • Observable pattern - RxJS Observable for event streaming
  • Custom tools via MCP - Define custom tools using Claude SDK's tool() function
  • Forwarded props - Per-run option overrides with security whitelist

Examples

The integration includes 5 example agents:

RouteDescriptionFeatures
/agentic_chatBasic conversational assistantSimple chat
/backend_tool_renderingWeather tool (backend MCP)Backend tool execution, tool rendering
/shared_stateRecipe collaborationBidirectional state sync, ag_ui_update_state
/human_in_the_loopTask planning with approvalFrontend tools, step tracking, approval workflow
/tool_based_generative_uiFrontend tool renderingDynamic frontend tools, generative UI

Running the Examples

# Install dependencies
cd integrations/claude-agent-sdk/typescript
pnpm install

# Start server (port 8889)
ANTHROPIC_API_KEY=sk-ant-xxx npx tsx examples/server.ts

# Start Dojo (in another terminal)
cd apps/dojo
pnpm dev

Visit http://localhost:3000 and select "Claude Agent SDK (Typescript)"

Content and state preservation

The adapter emits AG-UI 1.0 content parts for supported tool-result media. It preserves every block in order, including bytes and MIME type; each projected part retains the original SDK block in metadata.claude.block. Parts without an AG-UI equivalent retain their JSON payload and an explicit metadata.claude.unsupportedType. Tool-result events and final message snapshots use the same projection and error indication. Single plain-text results remain strings, including their original whitespace.

The claude:assistant_content custom event retains complete assistant blocks received from the SDK, including reasoning/signatures and richer blocks that the text transcript cannot represent. Its value contains messageId, the SDK record uuid when available, parentToolUseId, and content. Streamed message IDs use the native message ID when supplied. Only mcp__ag_ui__ tool names map to frontend names; external MCP names remain qualified to avoid collisions.

Input uploads remain in RUN_STARTED.input with their original metadata. Image and PDF data/URLs are forwarded to Claude; inline UTF-8 text/plain documents are decoded from base64, and document metadata.filename is forwarded as the document title. Audio/video inputs and unresolved provider file handles emit claude:unsupported_input diagnostics and are omitted from the model prompt. Recording those uploads is separate from model comprehension. Native SDK transcripts do not necessarily retain every AG-UI metadata field.

input.state is the complete state at the start of a run. The ag_ui_update_state tool shallow-merges state_updates object keys; nested objects and arrays replace the previous value at that key. The adapter emits the full merged STATE_SNAPSHOT, and invalid updates leave the prior state intact. The native state tool result is an acknowledgement, not a saved complete state snapshot. A native transcript with only partial updates cannot establish the missing initial state.

Frontend tool proxies require a result resolver armed for the original tool call by the deferred-tool/session recovery integration. The resolver returns the real frontend result to that call; absent resolution fails explicitly instead of saving a placeholder. Strings retain their bytes; supported structured results become MCP content. This content change must ship with the PNI-659 lifecycle companion. It does not repair historical placeholder results or make arbitrary historical approvals resumable.

Protocol regression tests exercise synthetic SDK streams and proxy callbacks without model calls. They do not establish released support, native persistence across restart, or end-to-end Intelligence replay; those require the lifecycle companion and product validation.

Session recovery (PNI-659, unreleased)

Use sessionRecovery: { store, profile, resolveProfile, deferTools? } to retain thread-to-SDK-session bindings across adapter restarts. store.load(threadId) returns { sessionId, profile, pending?: { id, name, input } }; store.save must durably commit that record before resolving. resolveProfile(profile) returns trusted SDK options, including the original cwd, native sessionStore (if used), tools/MCP configuration, permission mode and credential environment. Store a profile key, not credentials or serialized callbacks. The default in-memory bindings do not survive a process restart.

For imported sessions the host must resolve the imported thread ID to the original UUID and execution profile, including a confirmed saved deferral when present. Missing imported records must throw rather than return undefined (which means a new thread). Never infer pending approvals from an unfinished tool_use or a callback that was waiting in a dead process. PNI-657 owns native history extraction and routing. Session binding access requires the same tenant and authorization boundary as the native transcript. Serialize runs across replicas with an application lock; the adapter only excludes overlapping local runs. Reconcile bindings against native storage after an interrupted save or out-of-band SDK activity before exposing a pending decision.

Use deferTools: ["Read"] (exact native names) for native approval policy. A confirmed native deferral emits RUN_FINISHED.outcome = { type: "interrupt", interrupts: [...] }. Answer with resume: [{ interruptId: originalCallId, status: "resolved", payload: { behavior: "allow" | "deny", message?, updatedInput? } }]; status: "cancelled" denies the call. The adapter resumes the original UUID without forking, preserves the original call ID, and leaves actual execution/result persistence to the SDK. Existing host hooks still apply; do not configure a second unconditional deferral hook for the same call.

The tested baseline is Agent SDK 0.3.296, its bundled CLI 2.1.296, and AG-UI 1.0. Recovery requires the CLI --await-initialize barrier, which the adapter sets before resume, so SDK hooks exist before a saved call can execute. A held, empty input stream avoids enqueueing an extra user/model turn. Custom CLI binaries older than 2.1.261 do not support that barrier. For local transcript lookup, set the same CLAUDE_CONFIG_DIR in the host process and query environment. Missing transcripts/configuration and unavailable tools surface as run errors; there is no fallback to a new session.

Frontend deferrals under mcp__ag_ui__ use an authenticated loopback HTTP MCP endpoint, connected with alwaysLoad before native replay. The endpoint exists only for the query and closes afterward. The binding also stores the original frontend tool declarations (frontendTools in TypeScript, frontend_tools in Python); persist these fields unchanged so a delta-only ToolMessage with tools: [] can resume the original call after restart. Tool errors retain their native failure flag. Other host-provided in-process SDK MCP deferrals remain guarded because those servers register too late for replay. Durable deferral supports one tool call at a time, not parallel calls.

Focused tests cover binding restoration, allow/deny mapping, missing sessions, identity mismatches and callback-history rejection. Run pnpm exec tsx scripts/probe-durable-resume.mjs and repeat with --allow from this package to exercise two actual SDK processes against a localhost fake provider and disposable synthetic native files. The probe checks original UUID, call ID, native/AG-UI result equality and exactly two model requests total. This is synthetic adapter validation; remote stores, production credentials, Intelligence/browser replay and the six-row product matrix remain unvalidated.

The frontend probe (scripts/probe-frontend-resume.mjs, with optional --error, in TypeScript; scripts/probe_frontend_resume.py in Python) additionally checks original-session frontend results with omitted tool definitions, native saved results, and a fresh SDK history read. It uses the same isolated fake-provider setup as the native approval probe. The real SDK block-ordering probe uses a synthetic localhost provider (no model credentials or external inference):

pnpm exec tsx integrations/claude-agent-sdk/typescript/scripts/probe-assistant-blocks.mjs

It checks two text blocks and text followed by a native tool call, each with partial messages enabled and disabled, against the final message snapshot.

Unsupported pending batches

Once multiple deferrals are observed, the adapter persists their diagnostic metadata before acknowledging the hook. Concurrent hook writes are serialized. A stream exception or cancellation before the terminal SDK result therefore leaves the acknowledged batch blocked when a fresh adapter loads the binding.

If several calls are deferred before a result is available, the adapter saves all observed original IDs, names and arguments in SessionBinding.unsupportedPendingTools, retains the SDK's pending call, and emits RUN_ERROR. Persist this optional field in custom binding stores. A new adapter/process refuses to resume that binding. For older singleton bindings, the adapter reads native history before continuation and retains unresolved siblings when the saved call is among them. Completed native results, including empty results, are excluded from that diagnostic. Failed history reads fail the run rather than skipping the check.

This is failure containment, not batch recovery: no sibling results are fabricated, no native transcript is rewritten, and no submitted answer or next user message is sent to the SDK on rejection. The caller must retain rejected input. Do not clear the diagnostic field or replay each sibling independently to bypass the guard. Existing batches require upstream SDK recovery support; missing historical calls or results cannot be reconstructed by this adapter. See the SDK's single-call deferral limitation.

No provider configuration is changed automatically. A trusted deployment may configure sequential generation for future turns, but must verify the actual provider request and respect organization policy. Such prevention does not repair existing batches. Single-call continuation still requires the original session, tool configuration, result ownership and approval checks.

Unresolved child calls

Parent completion, an Agent launch result, and task completion notifications do not resolve a child's tool call. The adapter tracks observed child tool uses until a native result matches both the tool ID and parent_tool_use_id. At parent completion, unresolved calls are retained in unsupportedPendingTools with their original ID, name, input and parentToolUseId; the run emits RUN_ERROR. Persist this field unchanged. Cold continuation is rejected before starting the SDK, even when only one child call is unresolved. Child identities are never exposed as actionable parent-session approvals.

The SDK documents subagent continuation through a new prompt naming the agent, but this is not a verified exact-call deferral replay contract. This adapter therefore does not attempt child recovery, synthesize results, or modify transcripts. Already-lost diagnostics in older bindings cannot be reconstructed from parent completion alone.

版本与发布记录

@ag-ui/claude-agent-sdk 共发布 8 个版本,首次发布于 2026/04/25;过去 12 个月发布了 8 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.0.8latest2026/10/2117 天前
0.0.72026/10/1622 天前
0.0.62026/10/1326 天前
0.0.52026/10/1226 天前
0.0.42026/09/171 个月前
0.0.32026/05/275 个月前

其他发布通道:canary → 0.0.2-canary.1777061096.0。

关于 @ag-ui/claude-agent-sdk 的常见问题

@ag-ui/claude-agent-sdk 是什么?

AG-UI integration for Anthropic Claude Agent SDK

如何安装 @ag-ui/claude-agent-sdk?

在项目目录运行 npm install @ag-ui/claude-agent-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:zod(>=3.0.0)、@ag-ui/core(>=1.0.0)、@ag-ui/client(>=1.0.0)、@anthropic-ai/sdk(>=0.50.0)、@anthropic-ai/claude-agent-sdk(0.3.296)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@ag-ui/claude-agent-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@ag-ui/claude-agent-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@ag-ui/claude-agent-sdk 可以商用吗?

@ag-ui/claude-agent-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@ag-ui/claude-agent-sdk 的下载量有多少?

根据 npm 官方下载统计,@ag-ui/claude-agent-sdk 在 2026/10/05 – 2026/11/03 这 30 天内被下载 7,672 次,日均约 256 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@ag-ui/claude-agent-sdk 还在维护吗?

最新版本 0.0.8 发布于 2026/10/21(17 天前);至今共发布 8 个版本,其中过去 12 个月发布了 8 个;首次发布于 2026/04/25。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。