@clawnet/template-minimal 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.agents/skills/claude-agent-sdk/.claude-plugin/plugin.json +13 -0
- package/.agents/skills/claude-agent-sdk/SKILL.md +954 -0
- package/.agents/skills/claude-agent-sdk/references/mcp-servers-guide.md +387 -0
- package/.agents/skills/claude-agent-sdk/references/permissions-guide.md +429 -0
- package/.agents/skills/claude-agent-sdk/references/query-api-reference.md +437 -0
- package/.agents/skills/claude-agent-sdk/references/session-management.md +419 -0
- package/.agents/skills/claude-agent-sdk/references/subagents-patterns.md +464 -0
- package/.agents/skills/claude-agent-sdk/references/top-errors.md +503 -0
- package/.agents/skills/claude-agent-sdk/rules/claude-agent-sdk.md +96 -0
- package/.agents/skills/claude-agent-sdk/scripts/check-versions.sh +55 -0
- package/.agents/skills/claude-agent-sdk/templates/basic-query.ts +55 -0
- package/.agents/skills/claude-agent-sdk/templates/custom-mcp-server.ts +161 -0
- package/.agents/skills/claude-agent-sdk/templates/error-handling.ts +283 -0
- package/.agents/skills/claude-agent-sdk/templates/filesystem-settings.ts +211 -0
- package/.agents/skills/claude-agent-sdk/templates/multi-agent-workflow.ts +318 -0
- package/.agents/skills/claude-agent-sdk/templates/package.json +30 -0
- package/.agents/skills/claude-agent-sdk/templates/permission-control.ts +211 -0
- package/.agents/skills/claude-agent-sdk/templates/query-with-tools.ts +54 -0
- package/.agents/skills/claude-agent-sdk/templates/session-management.ts +151 -0
- package/.agents/skills/claude-agent-sdk/templates/subagents-orchestration.ts +166 -0
- package/.agents/skills/claude-agent-sdk/templates/tsconfig.json +22 -0
- package/.claude/settings.local.json +70 -0
- package/.claude/skills/moltbook-example/SKILL.md +79 -0
- package/.claude/skills/post/SKILL.md +130 -0
- package/.env.example +4 -0
- package/.vercel/README.txt +11 -0
- package/.vercel/project.json +1 -0
- package/AGENTS.md +114 -0
- package/CLAUDE.md +532 -0
- package/README.md +44 -0
- package/api/index.ts +3 -0
- package/biome.json +14 -0
- package/clark_avatar.jpeg +0 -0
- package/package.json +21 -0
- package/scripts/wake.ts +38 -0
- package/skills/clawbook/HEARTBEAT.md +142 -0
- package/skills/clawbook/SKILL.md +219 -0
- package/skills/moltbook-example/SKILL.md +79 -0
- package/skills/moltbook-example/bot/index.ts +61 -0
- package/src/agent/prompts.ts +98 -0
- package/src/agent/runner.ts +526 -0
- package/src/agent/tool-definitions.ts +1151 -0
- package/src/agent-options.ts +14 -0
- package/src/bot-identity.ts +41 -0
- package/src/constants.ts +15 -0
- package/src/handlers/heartbeat.ts +21 -0
- package/src/handlers/openai-compat.ts +95 -0
- package/src/handlers/post.ts +21 -0
- package/src/identity.ts +83 -0
- package/src/index.ts +30 -0
- package/src/middleware/cron-auth.ts +53 -0
- package/src/middleware/sigma-auth.ts +147 -0
- package/src/runs.ts +49 -0
- package/tests/agent/prompts.test.ts +172 -0
- package/tests/agent/runner.test.ts +353 -0
- package/tests/agent/tool-definitions.test.ts +171 -0
- package/tests/constants.test.ts +24 -0
- package/tests/handlers/openai-compat.test.ts +128 -0
- package/tests/handlers.test.ts +133 -0
- package/tests/identity.test.ts +66 -0
- package/tests/index.test.ts +108 -0
- package/tests/middleware/cron-auth.test.ts +99 -0
- package/tests/middleware/sigma-auth.test.ts +198 -0
- package/tests/runs.test.ts +56 -0
- package/tests/skill.test.ts +71 -0
- package/tsconfig.json +14 -0
- package/vercel.json +9 -0
|
@@ -0,0 +1,954 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: claude-agent-sdk
|
|
3
|
+
description: |
|
|
4
|
+
Build autonomous AI agents with Claude Agent SDK. Structured outputs guarantee JSON schema validation, with plugins system and hooks for event-driven workflows. Prevents 14 documented errors.
|
|
5
|
+
|
|
6
|
+
Use when: building coding agents, SRE systems, security auditors, or troubleshooting CLI not found, structured output validation, session forking errors, MCP config issues, subagent cleanup.
|
|
7
|
+
user-invocable: true
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Claude Agent SDK - Structured Outputs & Error Prevention Guide
|
|
11
|
+
|
|
12
|
+
**Package**: @anthropic-ai/claude-agent-sdk@0.2.12
|
|
13
|
+
**Breaking Changes**: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
## What's New in v0.1.45+ (Nov 2025)
|
|
18
|
+
|
|
19
|
+
**Major Features:**
|
|
20
|
+
|
|
21
|
+
### 1. Structured Outputs (v0.1.45, Nov 14, 2025)
|
|
22
|
+
- **JSON schema validation** - Guarantees responses match exact schemas
|
|
23
|
+
- **`outputFormat` parameter** - Define output structure with JSON schema or Zod
|
|
24
|
+
- **Access validated results** - Via `message.structured_output`
|
|
25
|
+
- **Beta header required**: `structured-outputs-2025-11-13`
|
|
26
|
+
- **Type safety** - Full TypeScript inference with Zod schemas
|
|
27
|
+
|
|
28
|
+
**Example:**
|
|
29
|
+
```typescript
|
|
30
|
+
import { query } from "@anthropic-ai/claude-agent-sdk";
|
|
31
|
+
import { z } from "zod";
|
|
32
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
33
|
+
|
|
34
|
+
const schema = z.object({
|
|
35
|
+
summary: z.string(),
|
|
36
|
+
sentiment: z.enum(['positive', 'neutral', 'negative']),
|
|
37
|
+
confidence: z.number().min(0).max(1)
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const response = query({
|
|
41
|
+
prompt: "Analyze this code review feedback",
|
|
42
|
+
options: {
|
|
43
|
+
model: "claude-sonnet-4-5",
|
|
44
|
+
outputFormat: {
|
|
45
|
+
type: "json_schema",
|
|
46
|
+
json_schema: {
|
|
47
|
+
name: "AnalysisResult",
|
|
48
|
+
strict: true,
|
|
49
|
+
schema: zodToJsonSchema(schema)
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
for await (const message of response) {
|
|
56
|
+
if (message.type === 'result' && message.structured_output) {
|
|
57
|
+
// Guaranteed to match schema
|
|
58
|
+
const validated = schema.parse(message.structured_output);
|
|
59
|
+
console.log(`Sentiment: ${validated.sentiment}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
**Zod Compatibility (v0.1.71+):** SDK supports both Zod v3.24.1+ and Zod v4.0.0+ as peer dependencies. Import remains `import { z } from "zod"` for either version.
|
|
65
|
+
|
|
66
|
+
### 2. Plugins System (v0.1.27)
|
|
67
|
+
- **`plugins` array** - Load local plugin paths
|
|
68
|
+
- **Custom plugin support** - Extend agent capabilities
|
|
69
|
+
|
|
70
|
+
### 3. Hooks System (v0.1.0+)
|
|
71
|
+
|
|
72
|
+
**All 12 Hook Events:**
|
|
73
|
+
|
|
74
|
+
| Hook | When Fired | Use Case |
|
|
75
|
+
|------|------------|----------|
|
|
76
|
+
| `PreToolUse` | Before tool execution | Validate, modify, or block tool calls |
|
|
77
|
+
| `PostToolUse` | After tool execution | Log results, trigger side effects |
|
|
78
|
+
| `Notification` | Agent notifications | Display status updates |
|
|
79
|
+
| `UserPromptSubmit` | User prompt received | Pre-process or validate input |
|
|
80
|
+
| `SubagentStart` | Subagent spawned | Track delegation, log context |
|
|
81
|
+
| `SubagentStop` | Subagent completed | Aggregate results, cleanup |
|
|
82
|
+
| `PreCompact` | Before context compaction | Save state before truncation |
|
|
83
|
+
| `PermissionRequest` | Permission needed | Custom approval workflows |
|
|
84
|
+
| `Stop` | Agent stopping | Cleanup, final logging |
|
|
85
|
+
| `SessionStart` | Session begins | Initialize state |
|
|
86
|
+
| `SessionEnd` | Session ends | Persist state, cleanup |
|
|
87
|
+
| `Error` | Error occurred | Custom error handling |
|
|
88
|
+
|
|
89
|
+
**Hook Configuration:**
|
|
90
|
+
```typescript
|
|
91
|
+
const response = query({
|
|
92
|
+
prompt: "...",
|
|
93
|
+
options: {
|
|
94
|
+
hooks: {
|
|
95
|
+
PreToolUse: async (input) => {
|
|
96
|
+
console.log(`Tool: ${input.toolName}`);
|
|
97
|
+
return { allow: true }; // or { allow: false, message: "..." }
|
|
98
|
+
},
|
|
99
|
+
PostToolUse: async (input) => {
|
|
100
|
+
await logToolUsage(input.toolName, input.result);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### 4. Additional Options
|
|
108
|
+
- **`fallbackModel`** - Automatic model fallback on failures
|
|
109
|
+
- **`maxThinkingTokens`** - Control extended thinking budget
|
|
110
|
+
- **`strictMcpConfig`** - Strict MCP configuration validation
|
|
111
|
+
- **`continue`** - Resume with new prompt (differs from `resume`)
|
|
112
|
+
- **`permissionMode: 'plan'`** - New permission mode for planning workflows
|
|
113
|
+
|
|
114
|
+
📚 **Docs**: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
|
|
115
|
+
|
|
116
|
+
---
|
|
117
|
+
|
|
118
|
+
## The Complete Claude Agent SDK Reference
|
|
119
|
+
|
|
120
|
+
## Table of Contents
|
|
121
|
+
|
|
122
|
+
1. [Core Query API](#core-query-api)
|
|
123
|
+
2. [Tool Integration](#tool-integration-built-in--custom)
|
|
124
|
+
3. [MCP Servers](#mcp-servers-model-context-protocol)
|
|
125
|
+
4. [Subagent Orchestration](#subagent-orchestration)
|
|
126
|
+
5. [Session Management](#session-management)
|
|
127
|
+
6. [Permission Control](#permission-control)
|
|
128
|
+
7. [Sandbox Settings](#sandbox-settings-security-critical)
|
|
129
|
+
8. [File Checkpointing](#file-checkpointing)
|
|
130
|
+
9. [Filesystem Settings](#filesystem-settings)
|
|
131
|
+
10. [Query Object Methods](#query-object-methods)
|
|
132
|
+
11. [Message Types & Streaming](#message-types--streaming)
|
|
133
|
+
12. [Error Handling](#error-handling)
|
|
134
|
+
13. [Known Issues](#known-issues-prevention)
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Core Query API
|
|
139
|
+
|
|
140
|
+
**Key signature:**
|
|
141
|
+
```typescript
|
|
142
|
+
query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)
|
|
143
|
+
-> AsyncGenerator<SDKMessage>
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
**Critical Options:**
|
|
147
|
+
- `outputFormat` - Structured JSON schema validation (v0.1.45+)
|
|
148
|
+
- `settingSources` - Filesystem settings loading ('user'|'project'|'local')
|
|
149
|
+
- `canUseTool` - Custom permission logic callback
|
|
150
|
+
- `agents` - Programmatic subagent definitions
|
|
151
|
+
- `mcpServers` - MCP server configuration
|
|
152
|
+
- `permissionMode` - 'default'|'acceptEdits'|'bypassPermissions'|'plan'
|
|
153
|
+
- `betas` - Enable beta features (e.g., 1M context window)
|
|
154
|
+
- `sandbox` - Sandbox settings for secure execution
|
|
155
|
+
- `enableFileCheckpointing` - Enable file state snapshots
|
|
156
|
+
- `systemPrompt` - System prompt (string or preset object)
|
|
157
|
+
|
|
158
|
+
### Extended Context (1M Tokens)
|
|
159
|
+
|
|
160
|
+
Enable 1 million token context window:
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
const response = query({
|
|
164
|
+
prompt: "Analyze this large codebase",
|
|
165
|
+
options: {
|
|
166
|
+
betas: ['context-1m-2025-08-07'], // Enable 1M context
|
|
167
|
+
model: "claude-sonnet-4-5"
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### System Prompt Configuration
|
|
173
|
+
|
|
174
|
+
Two forms of systemPrompt:
|
|
175
|
+
|
|
176
|
+
```typescript
|
|
177
|
+
// 1. Simple string
|
|
178
|
+
systemPrompt: "You are a helpful coding assistant."
|
|
179
|
+
|
|
180
|
+
// 2. Preset with optional append (preserves Claude Code defaults)
|
|
181
|
+
systemPrompt: {
|
|
182
|
+
type: 'preset',
|
|
183
|
+
preset: 'claude_code',
|
|
184
|
+
append: "\n\nAdditional context: Focus on security."
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
**Use preset form** when you want Claude Code's default behaviors plus custom additions.
|
|
189
|
+
|
|
190
|
+
---
|
|
191
|
+
|
|
192
|
+
## Tool Integration (Built-in + Custom)
|
|
193
|
+
|
|
194
|
+
**Tool Control:**
|
|
195
|
+
- `allowedTools` - Whitelist (takes precedence)
|
|
196
|
+
- `disallowedTools` - Blacklist
|
|
197
|
+
- `canUseTool` - Custom permission callback (see Permission Control section)
|
|
198
|
+
|
|
199
|
+
**Built-in Tools:** Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion
|
|
200
|
+
|
|
201
|
+
### AskUserQuestion Tool (v0.1.71+)
|
|
202
|
+
|
|
203
|
+
Enable user interaction during agent execution:
|
|
204
|
+
|
|
205
|
+
```typescript
|
|
206
|
+
const response = query({
|
|
207
|
+
prompt: "Review and refactor the codebase",
|
|
208
|
+
options: {
|
|
209
|
+
allowedTools: ["Read", "Write", "Edit", "AskUserQuestion"]
|
|
210
|
+
}
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// Agent can now ask clarifying questions
|
|
214
|
+
// Questions appear in message stream as tool_call with name "AskUserQuestion"
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
**Use cases:**
|
|
218
|
+
- Clarify ambiguous requirements mid-task
|
|
219
|
+
- Get user approval before destructive operations
|
|
220
|
+
- Present options and get selection
|
|
221
|
+
|
|
222
|
+
### Tools Configuration (v0.1.57+)
|
|
223
|
+
|
|
224
|
+
**Three forms of tool configuration:**
|
|
225
|
+
|
|
226
|
+
```typescript
|
|
227
|
+
// 1. Exact allowlist (string array)
|
|
228
|
+
tools: ["Read", "Write", "Grep"]
|
|
229
|
+
|
|
230
|
+
// 2. Disable all tools (empty array)
|
|
231
|
+
tools: []
|
|
232
|
+
|
|
233
|
+
// 3. Preset with defaults (object form)
|
|
234
|
+
tools: { type: 'preset', preset: 'claude_code' }
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
**Note:** `allowedTools` and `disallowedTools` still work but `tools` provides more flexibility.
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
241
|
+
## MCP Servers (Model Context Protocol)
|
|
242
|
+
|
|
243
|
+
**Server Types:**
|
|
244
|
+
- **In-process** - `createSdkMcpServer()` with `tool()` definitions
|
|
245
|
+
- **External** - stdio, HTTP, SSE transport
|
|
246
|
+
|
|
247
|
+
**Tool Definition:**
|
|
248
|
+
```typescript
|
|
249
|
+
tool(name: string, description: string, zodSchema, handler)
|
|
250
|
+
```
|
|
251
|
+
|
|
252
|
+
**Handler Return:**
|
|
253
|
+
```typescript
|
|
254
|
+
{ content: [{ type: "text", text: "..." }], isError?: boolean }
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
### External MCP Servers (stdio)
|
|
258
|
+
|
|
259
|
+
```typescript
|
|
260
|
+
const response = query({
|
|
261
|
+
prompt: "List files and analyze Git history",
|
|
262
|
+
options: {
|
|
263
|
+
mcpServers: {
|
|
264
|
+
// Filesystem server
|
|
265
|
+
"filesystem": {
|
|
266
|
+
command: "npx",
|
|
267
|
+
args: ["@modelcontextprotocol/server-filesystem"],
|
|
268
|
+
env: {
|
|
269
|
+
ALLOWED_PATHS: "/Users/developer/projects:/tmp"
|
|
270
|
+
}
|
|
271
|
+
},
|
|
272
|
+
// Git operations server
|
|
273
|
+
"git": {
|
|
274
|
+
command: "npx",
|
|
275
|
+
args: ["@modelcontextprotocol/server-git"],
|
|
276
|
+
env: {
|
|
277
|
+
GIT_REPO_PATH: "/Users/developer/projects/my-repo"
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
},
|
|
281
|
+
allowedTools: [
|
|
282
|
+
"mcp__filesystem__list_files",
|
|
283
|
+
"mcp__filesystem__read_file",
|
|
284
|
+
"mcp__git__log",
|
|
285
|
+
"mcp__git__diff"
|
|
286
|
+
]
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
```
|
|
290
|
+
|
|
291
|
+
### External MCP Servers (HTTP/SSE)
|
|
292
|
+
|
|
293
|
+
```typescript
|
|
294
|
+
const response = query({
|
|
295
|
+
prompt: "Analyze data from remote service",
|
|
296
|
+
options: {
|
|
297
|
+
mcpServers: {
|
|
298
|
+
"remote-service": {
|
|
299
|
+
url: "https://api.example.com/mcp",
|
|
300
|
+
headers: {
|
|
301
|
+
"Authorization": "Bearer your-token-here",
|
|
302
|
+
"Content-Type": "application/json"
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
allowedTools: ["mcp__remote-service__analyze"]
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
### MCP Tool Naming Convention
|
|
312
|
+
|
|
313
|
+
**Format**: `mcp__<server-name>__<tool-name>`
|
|
314
|
+
|
|
315
|
+
**CRITICAL:**
|
|
316
|
+
- Server name and tool name MUST match configuration
|
|
317
|
+
- Use double underscores (`__`) as separators
|
|
318
|
+
- Include in `allowedTools` array
|
|
319
|
+
|
|
320
|
+
**Examples:** `mcp__weather-service__get_weather`, `mcp__filesystem__read_file`
|
|
321
|
+
|
|
322
|
+
---
|
|
323
|
+
|
|
324
|
+
## Subagent Orchestration
|
|
325
|
+
|
|
326
|
+
### AgentDefinition Type
|
|
327
|
+
|
|
328
|
+
```typescript
|
|
329
|
+
type AgentDefinition = {
|
|
330
|
+
description: string; // When to use this agent
|
|
331
|
+
prompt: string; // System prompt for agent
|
|
332
|
+
tools?: string[]; // Allowed tools (optional)
|
|
333
|
+
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit'; // Model (optional)
|
|
334
|
+
skills?: string[]; // Skills to load (v0.2.10+)
|
|
335
|
+
maxTurns?: number; // Maximum turns before stopping (v0.2.10+)
|
|
336
|
+
}
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
**Field Details:**
|
|
340
|
+
|
|
341
|
+
- **description**: When to use agent (used by main agent for delegation)
|
|
342
|
+
- **prompt**: System prompt (defines role, inherits main context)
|
|
343
|
+
- **tools**: Allowed tools (if omitted, inherits from main agent)
|
|
344
|
+
- **model**: Model override (`haiku`/`sonnet`/`opus`/`inherit`)
|
|
345
|
+
- **skills**: Skills to load for agent (v0.2.10+)
|
|
346
|
+
- **maxTurns**: Limit agent to N turns before returning control (v0.2.10+)
|
|
347
|
+
|
|
348
|
+
**Usage:**
|
|
349
|
+
```typescript
|
|
350
|
+
agents: {
|
|
351
|
+
"security-checker": {
|
|
352
|
+
description: "Security audits and vulnerability scanning",
|
|
353
|
+
prompt: "You check security. Scan for secrets, verify OWASP compliance.",
|
|
354
|
+
tools: ["Read", "Grep", "Bash"],
|
|
355
|
+
model: "sonnet",
|
|
356
|
+
skills: ["security-best-practices"], // Load specific skills
|
|
357
|
+
maxTurns: 10 // Limit to 10 turns
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### ⚠️ Subagent Cleanup Warning
|
|
363
|
+
|
|
364
|
+
**Known Issue**: Subagents don't stop when parent agent stops ([Issue #132](https://github.com/anthropics/claude-agent-sdk-typescript/issues/132))
|
|
365
|
+
|
|
366
|
+
When a parent agent is stopped (via cancellation or error), spawned subagents continue running as orphaned processes. This can lead to:
|
|
367
|
+
- Resource leaks
|
|
368
|
+
- Continued tool execution after parent stopped
|
|
369
|
+
- RAM out-of-memory in recursive scenarios ([Claude Code Issue #4850](https://github.com/anthropics/claude-code/issues/4850))
|
|
370
|
+
|
|
371
|
+
**Workaround**: Implement cleanup in Stop hooks:
|
|
372
|
+
|
|
373
|
+
```typescript
|
|
374
|
+
const response = query({
|
|
375
|
+
prompt: "Deploy to production",
|
|
376
|
+
options: {
|
|
377
|
+
agents: {
|
|
378
|
+
"deployer": {
|
|
379
|
+
description: "Handle deployments",
|
|
380
|
+
prompt: "Deploy the application",
|
|
381
|
+
tools: ["Bash"]
|
|
382
|
+
}
|
|
383
|
+
},
|
|
384
|
+
hooks: {
|
|
385
|
+
Stop: async (input) => {
|
|
386
|
+
// Manual cleanup of spawned processes
|
|
387
|
+
console.log("Parent stopped - cleaning up subagents");
|
|
388
|
+
// Implement process tracking and termination
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
});
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
**Enhancement Tracking**: [Issue #142](https://github.com/anthropics/claude-agent-sdk-typescript/issues/142) proposes auto-termination
|
|
396
|
+
|
|
397
|
+
---
|
|
398
|
+
|
|
399
|
+
## Session Management
|
|
400
|
+
|
|
401
|
+
**Options:**
|
|
402
|
+
- `resume: sessionId` - Continue previous session
|
|
403
|
+
- `forkSession: true` - Create new branch from session
|
|
404
|
+
- `continue: prompt` - Resume with new prompt (differs from `resume`)
|
|
405
|
+
|
|
406
|
+
**Session Forking Pattern (Unique Capability):**
|
|
407
|
+
|
|
408
|
+
```typescript
|
|
409
|
+
// Explore alternative without modifying original
|
|
410
|
+
const forked = query({
|
|
411
|
+
prompt: "Try GraphQL instead of REST",
|
|
412
|
+
options: {
|
|
413
|
+
resume: sessionId,
|
|
414
|
+
forkSession: true // Creates new branch, original session unchanged
|
|
415
|
+
}
|
|
416
|
+
});
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
**Capture Session ID:**
|
|
420
|
+
```typescript
|
|
421
|
+
for await (const message of response) {
|
|
422
|
+
if (message.type === 'system' && message.subtype === 'init') {
|
|
423
|
+
sessionId = message.session_id; // Save for later resume/fork
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
### V2 Session APIs (Preview - v0.1.54+)
|
|
429
|
+
|
|
430
|
+
**Simpler multi-turn conversation pattern:**
|
|
431
|
+
|
|
432
|
+
```typescript
|
|
433
|
+
import {
|
|
434
|
+
unstable_v2_createSession,
|
|
435
|
+
unstable_v2_resumeSession,
|
|
436
|
+
unstable_v2_prompt
|
|
437
|
+
} from "@anthropic-ai/claude-agent-sdk";
|
|
438
|
+
|
|
439
|
+
// Create a new session
|
|
440
|
+
const session = await unstable_v2_createSession({
|
|
441
|
+
model: "claude-sonnet-4-5",
|
|
442
|
+
workingDirectory: process.cwd(),
|
|
443
|
+
allowedTools: ["Read", "Grep", "Glob"]
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
// Send prompts and stream responses
|
|
447
|
+
const stream = unstable_v2_prompt(session, "Analyze the codebase structure");
|
|
448
|
+
for await (const message of stream) {
|
|
449
|
+
console.log(message);
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// Continue conversation in same session
|
|
453
|
+
const stream2 = unstable_v2_prompt(session, "Now suggest improvements");
|
|
454
|
+
for await (const message of stream2) {
|
|
455
|
+
console.log(message);
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// Resume a previous session
|
|
459
|
+
const resumedSession = await unstable_v2_resumeSession(session.sessionId);
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
**Note:** V2 APIs are in preview (`unstable_` prefix). The `.receive()` method was renamed to `.stream()` in v0.1.72.
|
|
463
|
+
|
|
464
|
+
---
|
|
465
|
+
|
|
466
|
+
## Permission Control
|
|
467
|
+
|
|
468
|
+
**Permission Modes:**
|
|
469
|
+
```typescript
|
|
470
|
+
type PermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan";
|
|
471
|
+
```
|
|
472
|
+
|
|
473
|
+
- `default` - Standard permission checks
|
|
474
|
+
- `acceptEdits` - Auto-approve file edits
|
|
475
|
+
- `bypassPermissions` - Skip ALL checks (use in CI/CD only)
|
|
476
|
+
- `plan` - Planning mode (v0.1.45+)
|
|
477
|
+
|
|
478
|
+
### Custom Permission Logic
|
|
479
|
+
|
|
480
|
+
```typescript
|
|
481
|
+
const response = query({
|
|
482
|
+
prompt: "Deploy application to production",
|
|
483
|
+
options: {
|
|
484
|
+
permissionMode: "default",
|
|
485
|
+
canUseTool: async (toolName, input) => {
|
|
486
|
+
// Allow read-only operations
|
|
487
|
+
if (['Read', 'Grep', 'Glob'].includes(toolName)) {
|
|
488
|
+
return { behavior: "allow" };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// Deny destructive bash commands
|
|
492
|
+
if (toolName === 'Bash') {
|
|
493
|
+
const dangerous = ['rm -rf', 'dd if=', 'mkfs', '> /dev/'];
|
|
494
|
+
if (dangerous.some(pattern => input.command.includes(pattern))) {
|
|
495
|
+
return {
|
|
496
|
+
behavior: "deny",
|
|
497
|
+
message: "Destructive command blocked for safety"
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// Require confirmation for deployments
|
|
503
|
+
if (input.command?.includes('deploy') || input.command?.includes('kubectl apply')) {
|
|
504
|
+
return {
|
|
505
|
+
behavior: "ask",
|
|
506
|
+
message: "Confirm deployment to production?"
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// Allow by default
|
|
511
|
+
return { behavior: "allow" };
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
});
|
|
515
|
+
```
|
|
516
|
+
|
|
517
|
+
### canUseTool Callback
|
|
518
|
+
|
|
519
|
+
```typescript
|
|
520
|
+
type CanUseToolCallback = (
|
|
521
|
+
toolName: string,
|
|
522
|
+
input: any
|
|
523
|
+
) => Promise<PermissionDecision>;
|
|
524
|
+
|
|
525
|
+
type PermissionDecision =
|
|
526
|
+
| { behavior: "allow" }
|
|
527
|
+
| { behavior: "deny"; message?: string }
|
|
528
|
+
| { behavior: "ask"; message?: string };
|
|
529
|
+
```
|
|
530
|
+
|
|
531
|
+
**Examples:**
|
|
532
|
+
|
|
533
|
+
```typescript
|
|
534
|
+
// Block all file writes
|
|
535
|
+
canUseTool: async (toolName, input) => {
|
|
536
|
+
if (toolName === 'Write' || toolName === 'Edit') {
|
|
537
|
+
return { behavior: "deny", message: "No file modifications allowed" };
|
|
538
|
+
}
|
|
539
|
+
return { behavior: "allow" };
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// Require confirmation for specific files
|
|
543
|
+
canUseTool: async (toolName, input) => {
|
|
544
|
+
const sensitivePaths = ['/etc/', '/root/', '.env', 'credentials.json'];
|
|
545
|
+
if ((toolName === 'Write' || toolName === 'Edit') &&
|
|
546
|
+
sensitivePaths.some(path => input.file_path?.includes(path))) {
|
|
547
|
+
return {
|
|
548
|
+
behavior: "ask",
|
|
549
|
+
message: `Modify sensitive file ${input.file_path}?`
|
|
550
|
+
};
|
|
551
|
+
}
|
|
552
|
+
return { behavior: "allow" };
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// Log all tool usage
|
|
556
|
+
canUseTool: async (toolName, input) => {
|
|
557
|
+
console.log(`Tool requested: ${toolName}`, input);
|
|
558
|
+
await logToDatabase(toolName, input);
|
|
559
|
+
return { behavior: "allow" };
|
|
560
|
+
}
|
|
561
|
+
```
|
|
562
|
+
|
|
563
|
+
---
|
|
564
|
+
|
|
565
|
+
## Sandbox Settings (Security-Critical)
|
|
566
|
+
|
|
567
|
+
**Enable sandboxed execution for Bash commands:**
|
|
568
|
+
|
|
569
|
+
```typescript
|
|
570
|
+
const response = query({
|
|
571
|
+
prompt: "Run system diagnostics",
|
|
572
|
+
options: {
|
|
573
|
+
sandbox: {
|
|
574
|
+
enabled: true,
|
|
575
|
+
autoAllowBashIfSandboxed: true, // Auto-approve bash in sandbox
|
|
576
|
+
excludedCommands: ["rm", "dd", "mkfs"], // Never auto-approve these
|
|
577
|
+
allowUnsandboxedCommands: false // Deny unsandboxable commands
|
|
578
|
+
}
|
|
579
|
+
}
|
|
580
|
+
});
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
### SandboxSettings Type
|
|
584
|
+
|
|
585
|
+
```typescript
|
|
586
|
+
type SandboxSettings = {
|
|
587
|
+
enabled: boolean;
|
|
588
|
+
autoAllowBashIfSandboxed?: boolean; // Default: false
|
|
589
|
+
excludedCommands?: string[];
|
|
590
|
+
allowUnsandboxedCommands?: boolean; // Default: false
|
|
591
|
+
network?: NetworkSandboxSettings;
|
|
592
|
+
ignoreViolations?: SandboxIgnoreViolations;
|
|
593
|
+
};
|
|
594
|
+
|
|
595
|
+
type NetworkSandboxSettings = {
|
|
596
|
+
enabled: boolean;
|
|
597
|
+
proxyUrl?: string; // HTTP proxy for network requests
|
|
598
|
+
};
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
**Key Options:**
|
|
602
|
+
- `enabled` - Activate sandbox isolation
|
|
603
|
+
- `autoAllowBashIfSandboxed` - Skip permission prompts for safe bash commands
|
|
604
|
+
- `excludedCommands` - Commands that always require permission
|
|
605
|
+
- `allowUnsandboxedCommands` - Allow commands that can't be sandboxed (risky)
|
|
606
|
+
- `network.proxyUrl` - Route network through proxy for monitoring
|
|
607
|
+
|
|
608
|
+
**Best Practice:** Always use sandbox in production agents handling untrusted input.
|
|
609
|
+
|
|
610
|
+
---
|
|
611
|
+
|
|
612
|
+
## File Checkpointing
|
|
613
|
+
|
|
614
|
+
**Enable file state snapshots for rollback capability:**
|
|
615
|
+
|
|
616
|
+
```typescript
|
|
617
|
+
const response = query({
|
|
618
|
+
prompt: "Refactor the authentication module",
|
|
619
|
+
options: {
|
|
620
|
+
enableFileCheckpointing: true // Enable file snapshots
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
// Later: rewind file changes to a specific point
|
|
625
|
+
for await (const message of response) {
|
|
626
|
+
if (message.type === 'user' && message.uuid) {
|
|
627
|
+
// Can rewind to this point later
|
|
628
|
+
const userMessageUuid = message.uuid;
|
|
629
|
+
|
|
630
|
+
// To rewind (call on Query object)
|
|
631
|
+
await response.rewindFiles(userMessageUuid);
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
```
|
|
635
|
+
|
|
636
|
+
**Use cases:**
|
|
637
|
+
- Undo failed refactoring attempts
|
|
638
|
+
- A/B test code changes
|
|
639
|
+
- Safe exploration of alternatives
|
|
640
|
+
|
|
641
|
+
---
|
|
642
|
+
|
|
643
|
+
## Filesystem Settings
|
|
644
|
+
|
|
645
|
+
**Setting Sources:**
|
|
646
|
+
```typescript
|
|
647
|
+
type SettingSource = 'user' | 'project' | 'local';
|
|
648
|
+
```
|
|
649
|
+
|
|
650
|
+
- `user` - `~/.claude/settings.json` (global)
|
|
651
|
+
- `project` - `.claude/settings.json` (team-shared)
|
|
652
|
+
- `local` - `.claude/settings.local.json` (gitignored overrides)
|
|
653
|
+
|
|
654
|
+
**Default:** NO settings loaded (`settingSources: []`)
|
|
655
|
+
|
|
656
|
+
### Settings Priority
|
|
657
|
+
|
|
658
|
+
When multiple sources loaded, settings merge in this order (highest priority first):
|
|
659
|
+
|
|
660
|
+
1. **Programmatic options** (passed to `query()`) - Always win
|
|
661
|
+
2. **Local settings** (`.claude/settings.local.json`)
|
|
662
|
+
3. **Project settings** (`.claude/settings.json`)
|
|
663
|
+
4. **User settings** (`~/.claude/settings.json`)
|
|
664
|
+
|
|
665
|
+
**Example:**
|
|
666
|
+
|
|
667
|
+
```typescript
|
|
668
|
+
// .claude/settings.json
|
|
669
|
+
{
|
|
670
|
+
"allowedTools": ["Read", "Write", "Edit"]
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
// .claude/settings.local.json
|
|
674
|
+
{
|
|
675
|
+
"allowedTools": ["Read"] // Overrides project settings
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// Programmatic
|
|
679
|
+
const response = query({
|
|
680
|
+
options: {
|
|
681
|
+
settingSources: ["project", "local"],
|
|
682
|
+
allowedTools: ["Read", "Grep"] // ← This wins
|
|
683
|
+
}
|
|
684
|
+
});
|
|
685
|
+
|
|
686
|
+
// Actual allowedTools: ["Read", "Grep"]
|
|
687
|
+
```
|
|
688
|
+
|
|
689
|
+
**Best Practice:** Use `settingSources: ["project"]` in CI/CD for consistent behavior.
|
|
690
|
+
|
|
691
|
+
---
|
|
692
|
+
|
|
693
|
+
## Query Object Methods
|
|
694
|
+
|
|
695
|
+
The `query()` function returns a `Query` object with these methods:
|
|
696
|
+
|
|
697
|
+
```typescript
|
|
698
|
+
const q = query({ prompt: "..." });
|
|
699
|
+
|
|
700
|
+
// Async iteration (primary usage)
|
|
701
|
+
for await (const message of q) { ... }
|
|
702
|
+
|
|
703
|
+
// Runtime model control
|
|
704
|
+
await q.setModel("claude-opus-4-5"); // Change model mid-session
|
|
705
|
+
await q.setMaxThinkingTokens(4096); // Set thinking budget
|
|
706
|
+
|
|
707
|
+
// Introspection
|
|
708
|
+
const models = await q.supportedModels(); // List available models
|
|
709
|
+
const commands = await q.supportedCommands(); // List available commands
|
|
710
|
+
const account = await q.accountInfo(); // Get account details
|
|
711
|
+
|
|
712
|
+
// MCP status
|
|
713
|
+
const status = await q.mcpServerStatus(); // Check MCP server status
|
|
714
|
+
// Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }
|
|
715
|
+
|
|
716
|
+
// File operations (requires enableFileCheckpointing)
|
|
717
|
+
await q.rewindFiles(userMessageUuid); // Rewind to checkpoint
|
|
718
|
+
```
|
|
719
|
+
|
|
720
|
+
**Use cases:**
|
|
721
|
+
- Dynamic model switching based on task complexity
|
|
722
|
+
- Monitoring MCP server health
|
|
723
|
+
- Adjusting thinking budget for reasoning tasks
|
|
724
|
+
|
|
725
|
+
---
|
|
726
|
+
|
|
727
|
+
## Message Types & Streaming
|
|
728
|
+
|
|
729
|
+
**Message Types:**
|
|
730
|
+
- `system` - Session init/completion (includes `session_id`)
|
|
731
|
+
- `assistant` - Agent responses
|
|
732
|
+
- `tool_call` - Tool execution requests
|
|
733
|
+
- `tool_result` - Tool execution results
|
|
734
|
+
- `error` - Error messages
|
|
735
|
+
- `result` - Final result (includes `structured_output` for v0.1.45+)
|
|
736
|
+
|
|
737
|
+
**Streaming Pattern:**
|
|
738
|
+
```typescript
|
|
739
|
+
for await (const message of response) {
|
|
740
|
+
if (message.type === 'system' && message.subtype === 'init') {
|
|
741
|
+
sessionId = message.session_id; // Capture for resume/fork
|
|
742
|
+
}
|
|
743
|
+
if (message.type === 'result' && message.structured_output) {
|
|
744
|
+
// Structured output available (v0.1.45+)
|
|
745
|
+
const validated = schema.parse(message.structured_output);
|
|
746
|
+
}
|
|
747
|
+
}
|
|
748
|
+
```
|
|
749
|
+
|
|
750
|
+
---
|
|
751
|
+
|
|
752
|
+
## Error Handling
|
|
753
|
+
|
|
754
|
+
**Error Codes:**
|
|
755
|
+
|
|
756
|
+
| Error Code | Cause | Solution |
|
|
757
|
+
|------------|-------|----------|
|
|
758
|
+
| `CLI_NOT_FOUND` | Claude Code not installed | Install: `npm install -g @anthropic-ai/claude-code` |
|
|
759
|
+
| `AUTHENTICATION_FAILED` | Invalid API key | Check ANTHROPIC_API_KEY env var |
|
|
760
|
+
| `RATE_LIMIT_EXCEEDED` | Too many requests | Implement retry with backoff |
|
|
761
|
+
| `CONTEXT_LENGTH_EXCEEDED` | Prompt too long | Use session compaction, reduce context |
|
|
762
|
+
| `PERMISSION_DENIED` | Tool blocked | Check permissionMode, canUseTool |
|
|
763
|
+
| `TOOL_EXECUTION_FAILED` | Tool error | Check tool implementation |
|
|
764
|
+
| `SESSION_NOT_FOUND` | Invalid session ID | Verify session ID |
|
|
765
|
+
| `MCP_SERVER_FAILED` | Server error | Check server configuration |
|
|
766
|
+
|
|
767
|
+
---
|
|
768
|
+
|
|
769
|
+
## Known Issues Prevention
|
|
770
|
+
|
|
771
|
+
This skill prevents **14** documented issues:
|
|
772
|
+
|
|
773
|
+
### Issue #1: CLI Not Found Error
|
|
774
|
+
**Error**: `"Claude Code CLI not installed"`
|
|
775
|
+
**Source**: SDK requires Claude Code CLI
|
|
776
|
+
**Why It Happens**: CLI not installed globally
|
|
777
|
+
**Prevention**: Install before using SDK: `npm install -g @anthropic-ai/claude-code`
|
|
778
|
+
|
|
779
|
+
### Issue #2: Authentication Failed
|
|
780
|
+
**Error**: `"Invalid API key"`
|
|
781
|
+
**Source**: Missing or incorrect ANTHROPIC_API_KEY
|
|
782
|
+
**Why It Happens**: Environment variable not set
|
|
783
|
+
**Prevention**: Always set `export ANTHROPIC_API_KEY="sk-ant-..."`
|
|
784
|
+
|
|
785
|
+
### Issue #3: Permission Denied Errors
|
|
786
|
+
**Error**: Tool execution blocked
|
|
787
|
+
**Source**: `permissionMode` restrictions
|
|
788
|
+
**Why It Happens**: Tool not allowed by permissions
|
|
789
|
+
**Prevention**: Use `allowedTools` or custom `canUseTool` callback
|
|
790
|
+
|
|
791
|
+
### Issue #4: Context Length Exceeded (Session-Breaking)
|
|
792
|
+
**Error**: `"Prompt too long"`
|
|
793
|
+
**Source**: Input exceeds model context window ([Issue #138](https://github.com/anthropics/claude-agent-sdk-typescript/issues/138))
|
|
794
|
+
**Why It Happens**: Large codebase, long conversations
|
|
795
|
+
|
|
796
|
+
**⚠️ Critical Behavior**: Once a session hits context limit:
|
|
797
|
+
1. All subsequent requests to that session return "Prompt too long"
|
|
798
|
+
2. `/compact` command fails with same error
|
|
799
|
+
3. **Session is permanently broken and must be abandoned**
|
|
800
|
+
|
|
801
|
+
**Prevention Strategies**:
|
|
802
|
+
|
|
803
|
+
```typescript
|
|
804
|
+
// 1. Proactive session forking (create checkpoints before hitting limit)
|
|
805
|
+
const checkpoint = query({
|
|
806
|
+
prompt: "Checkpoint current state",
|
|
807
|
+
options: {
|
|
808
|
+
resume: sessionId,
|
|
809
|
+
forkSession: true // Create branch before hitting limit
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
|
|
813
|
+
// 2. Monitor time and rotate sessions proactively
|
|
814
|
+
const MAX_SESSION_TIME = 80 * 60 * 1000; // 80 minutes (before 90-min crash)
|
|
815
|
+
let sessionStartTime = Date.now();
|
|
816
|
+
|
|
817
|
+
function shouldRotateSession() {
|
|
818
|
+
return Date.now() - sessionStartTime > MAX_SESSION_TIME;
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
// 3. Start new sessions before hitting context limits
|
|
822
|
+
if (shouldRotateSession()) {
|
|
823
|
+
const summary = await getSummary(currentSession);
|
|
824
|
+
const newSession = query({
|
|
825
|
+
prompt: `Continue with context: ${summary}`
|
|
826
|
+
});
|
|
827
|
+
sessionStartTime = Date.now();
|
|
828
|
+
}
|
|
829
|
+
```
|
|
830
|
+
|
|
831
|
+
**Note**: SDK auto-compacts, but if limit is reached, session becomes unrecoverable
|
|
832
|
+
|
|
833
|
+
### Issue #5: Tool Execution Timeout
|
|
834
|
+
**Error**: Tool doesn't respond
|
|
835
|
+
**Source**: Long-running tool execution
|
|
836
|
+
**Why It Happens**: Tool takes too long (>5 minutes default)
|
|
837
|
+
**Prevention**: Implement timeout handling in tool implementations
|
|
838
|
+
|
|
839
|
+
### Issue #6: Session Not Found
|
|
840
|
+
**Error**: `"Invalid session ID"`
|
|
841
|
+
**Source**: Session expired or invalid
|
|
842
|
+
**Why It Happens**: Session ID incorrect or too old
|
|
843
|
+
**Prevention**: Capture `session_id` from `system` init message
|
|
844
|
+
|
|
845
|
+
### Issue #7: MCP Server Connection Failed
|
|
846
|
+
**Error**: Server not responding
|
|
847
|
+
**Source**: Server not running or misconfigured
|
|
848
|
+
**Why It Happens**: Command/URL incorrect, server crashed
|
|
849
|
+
**Prevention**: Test MCP server independently, verify command/URL
|
|
850
|
+
|
|
851
|
+
### Issue #8: Subagent Definition Errors
|
|
852
|
+
**Error**: Invalid AgentDefinition
|
|
853
|
+
**Source**: Missing required fields
|
|
854
|
+
**Why It Happens**: `description` or `prompt` missing
|
|
855
|
+
**Prevention**: Always include `description` and `prompt` fields
|
|
856
|
+
|
|
857
|
+
### Issue #9: Settings File Not Found
|
|
858
|
+
**Error**: `"Cannot read settings"`
|
|
859
|
+
**Source**: Settings file doesn't exist
|
|
860
|
+
**Why It Happens**: `settingSources` includes non-existent file
|
|
861
|
+
**Prevention**: Check file exists before including in sources
|
|
862
|
+
|
|
863
|
+
### Issue #10: Tool Name Collision
|
|
864
|
+
**Error**: Duplicate tool name
|
|
865
|
+
**Source**: Multiple tools with same name
|
|
866
|
+
**Why It Happens**: Two MCP servers define same tool name
|
|
867
|
+
**Prevention**: Use unique tool names, prefix with server name
|
|
868
|
+
|
|
869
|
+
### Issue #11: Zod Schema Validation Error
|
|
870
|
+
**Error**: Invalid tool input
|
|
871
|
+
**Source**: Input doesn't match Zod schema
|
|
872
|
+
**Why It Happens**: Agent provided wrong data type
|
|
873
|
+
**Prevention**: Use descriptive Zod schemas with `.describe()`
|
|
874
|
+
|
|
875
|
+
### Issue #12: Filesystem Permission Denied
|
|
876
|
+
**Error**: Cannot access path
|
|
877
|
+
**Source**: Restricted filesystem access
|
|
878
|
+
**Why It Happens**: Path outside `workingDirectory` or no permissions
|
|
879
|
+
**Prevention**: Set correct `workingDirectory`, check file permissions
|
|
880
|
+
|
|
881
|
+
### Issue #13: MCP Server Config Missing `type` Field
|
|
882
|
+
**Error**: `"Claude Code process exited with code 1"` (cryptic, no context)
|
|
883
|
+
**Source**: [GitHub Issue #131](https://github.com/anthropics/claude-agent-sdk-typescript/issues/131)
|
|
884
|
+
**Why It Happens**: URL-based MCP servers require explicit `type: "http"` or `type: "sse"` field
|
|
885
|
+
**Prevention**: Always specify transport type for URL-based MCP servers
|
|
886
|
+
|
|
887
|
+
```typescript
|
|
888
|
+
// ❌ Wrong - missing type field (causes cryptic exit code 1)
|
|
889
|
+
mcpServers: {
|
|
890
|
+
"my-server": {
|
|
891
|
+
url: "https://api.example.com/mcp"
|
|
892
|
+
}
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
// ✅ Correct - type field required for URL-based servers
|
|
896
|
+
mcpServers: {
|
|
897
|
+
"my-server": {
|
|
898
|
+
url: "https://api.example.com/mcp",
|
|
899
|
+
type: "http" // or "sse" for Server-Sent Events
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
```
|
|
903
|
+
|
|
904
|
+
**Diagnostic Clue**: If you see "process exited with code 1" with no other context, check your MCP server configuration for missing `type` fields.
|
|
905
|
+
|
|
906
|
+
### Issue #14: MCP Tool Result with Unicode Line Separators
|
|
907
|
+
**Error**: JSON parse error, agent hangs
|
|
908
|
+
**Source**: [GitHub Issue #137](https://github.com/anthropics/claude-agent-sdk-typescript/issues/137)
|
|
909
|
+
**Why It Happens**: Unicode U+2028 (line separator) and U+2029 (paragraph separator) are valid in JSON but break JavaScript parsing
|
|
910
|
+
**Prevention**: Escape these characters in MCP tool results
|
|
911
|
+
|
|
912
|
+
```typescript
|
|
913
|
+
// MCP tool handler - sanitize external data
|
|
914
|
+
tool("fetch_content", "Fetch text content", {}, async (args) => {
|
|
915
|
+
const content = await fetchExternalData();
|
|
916
|
+
|
|
917
|
+
// ✅ Sanitize Unicode line/paragraph separators
|
|
918
|
+
const sanitized = content
|
|
919
|
+
.replace(/\u2028/g, '\\u2028')
|
|
920
|
+
.replace(/\u2029/g, '\\u2029');
|
|
921
|
+
|
|
922
|
+
return {
|
|
923
|
+
content: [{ type: "text", text: sanitized }]
|
|
924
|
+
};
|
|
925
|
+
});
|
|
926
|
+
```
|
|
927
|
+
|
|
928
|
+
**When This Matters**: External data sources (APIs, web scraping, user input) that may contain these characters
|
|
929
|
+
|
|
930
|
+
**Related**: [MCP Python SDK Issue #1356](https://github.com/modelcontextprotocol/python-sdk/issues/1356)
|
|
931
|
+
|
|
932
|
+
---
|
|
933
|
+
|
|
934
|
+
## Official Documentation
|
|
935
|
+
|
|
936
|
+
- **Agent SDK Overview**: https://platform.claude.com/docs/en/api/agent-sdk/overview
|
|
937
|
+
- **TypeScript API**: https://platform.claude.com/docs/en/api/agent-sdk/typescript
|
|
938
|
+
- **Structured Outputs**: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
|
|
939
|
+
- **GitHub (TypeScript)**: https://github.com/anthropics/claude-agent-sdk-typescript
|
|
940
|
+
- **CHANGELOG**: https://github.com/anthropics/claude-agent-sdk-typescript/blob/main/CHANGELOG.md
|
|
941
|
+
|
|
942
|
+
---
|
|
943
|
+
|
|
944
|
+
**Token Efficiency**:
|
|
945
|
+
- **Without skill**: ~15,000 tokens (MCP setup, permission patterns, session APIs, sandbox config, hooks, structured outputs, error handling)
|
|
946
|
+
- **With skill**: ~4,500 tokens (comprehensive v0.2.12 coverage + error prevention + advanced patterns)
|
|
947
|
+
- **Savings**: ~70% (~10,500 tokens)
|
|
948
|
+
|
|
949
|
+
**Errors prevented**: 14 documented issues with exact solutions (including 2 community-sourced gotchas)
|
|
950
|
+
**Key value**: V2 Session APIs, Sandbox Settings, File Checkpointing, Query methods, AskUserQuestion tool, structured outputs (v0.1.45+), session forking, canUseTool patterns, complete hooks system (12 events), Zod v4 support, subagent cleanup patterns
|
|
951
|
+
|
|
952
|
+
---
|
|
953
|
+
|
|
954
|
+
**Last verified**: 2026-01-20 | **Skill version**: 3.1.0 | **Changes**: Added Issue #13 (MCP type field), Issue #14 (Unicode U+2028/U+2029), expanded Issue #4 (session-breaking), added subagent cleanup warning with Stop hook pattern
|