MCP Server Patterns
affaan-m/ECC
Build MCP servers with Node/TypeScript SDK — tools, resources, prompts, Zod validation, stdio vs Streamable HTTP.
Build autonomous AI agents with Claude Agent SDK. An agent skill from LeoYeAI/openclaw-master-skills.
$ npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a claude-codeProject install by default; add -g for ~/.claude/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills claude-agent-sdk --agent claude-codeProject scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/claude-agent-sdk .claude/skills/claude-agent-sdk && rm -rf skills-srcUse ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.
Claude Code skills documentation · loads skills from .claude/skills/
Install the "claude-agent-sdk" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdk into .claude/skills/claude-agent-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "claude-agent-sdk", then confirm the skill loads.Claude Code copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$skill-installer install https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdkType this inside Codex. $skill-installer <name> installs a curated skill from openai/skills. The installer writes to $CODEX_HOME/skills (default ~/.codex/skills). Restart Codex if the skill does not show up.
$ npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a codexProject install goes to .agents/skills/; add -g for ~/.codex/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills claude-agent-sdk --agent codexProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .agents/skills && cp -r skills-src/skills/claude-agent-sdk .agents/skills/claude-agent-sdk && rm -rf skills-srcUse ~/.agents/skills/ instead of .agents/skills for a personal install.
Codex skills documentation · loads skills from .agents/skills/
Install the "claude-agent-sdk" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdk into .agents/skills/claude-agent-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "claude-agent-sdk", then confirm the skill loads.Codex copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a cursorProject install goes to .agents/skills/; add -g for ~/.cursor/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills claude-agent-sdk --agent cursorProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .cursor/skills && cp -r skills-src/skills/claude-agent-sdk .cursor/skills/claude-agent-sdk && rm -rf skills-srcUse ~/.cursor/skills/ instead of .cursor/skills for a personal install.
Cursor skills documentation · loads skills from .cursor/skills/, .agents/skills/, .claude/skills/, .codex/skills/
Install the "claude-agent-sdk" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdk into .cursor/skills/claude-agent-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "claude-agent-sdk", then confirm the skill loads.Cursor copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gemini skills install https://github.com/LeoYeAI/openclaw-master-skills.git --path skills/claude-agent-sdk--scope user (default) or --scope workspace; --path is the subfolder of the repo that holds the skill; --consent skips the security confirmation prompt.
$ npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a gemini-cliProject install goes to .agents/skills/; add -g for ~/.gemini/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills claude-agent-sdk --agent gemini-cliProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .gemini/skills && cp -r skills-src/skills/claude-agent-sdk .gemini/skills/claude-agent-sdk && rm -rf skills-srcUse ~/.gemini/skills/ instead of .gemini/skills for a personal install, then run /skills reload.
Gemini CLI skills documentation · loads skills from .gemini/skills/, .agents/skills/
Install the "claude-agent-sdk" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdk into .gemini/skills/claude-agent-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "claude-agent-sdk", then confirm the skill loads.Gemini CLI copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ gh skill install LeoYeAI/openclaw-master-skills claude-agent-sdkInstalls for Copilot at project scope by default; add --scope user for a personal install. Preview a skill first with gh skill preview. Needs GitHub CLI 2.90.0 or later (public preview).
$ npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a github-copilotProject install goes to .agents/skills/; add -g for ~/.copilot/skills/.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .github/skills && cp -r skills-src/skills/claude-agent-sdk .github/skills/claude-agent-sdk && rm -rf skills-srcUse ~/.copilot/skills/ instead of .github/skills for a personal install. Commit .github/skills so cloud agent and code review can use it.
GitHub Copilot skills documentation · loads skills from .github/skills/, .claude/skills/, .agents/skills/
Install the "claude-agent-sdk" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdk into .github/skills/claude-agent-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "claude-agent-sdk", then confirm the skill loads.GitHub Copilot copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
$ npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a opencodeOpenCode documents no install command of its own. Project install goes to .agents/skills/; add -g for ~/.config/opencode/skills/.
$ gh skill install LeoYeAI/openclaw-master-skills claude-agent-sdk --agent opencodeProject scope by default (.agents/skills/); add --scope user for a personal install.
$ git clone --depth 1 https://github.com/LeoYeAI/openclaw-master-skills.git skills-src && mkdir -p .opencode/skills && cp -r skills-src/skills/claude-agent-sdk .opencode/skills/claude-agent-sdk && rm -rf skills-srcUse ~/.config/opencode/skills/ instead of .opencode/skills for a personal install.
OpenCode skills documentation · loads skills from .opencode/skills/, .claude/skills/, .agents/skills/
Install the "claude-agent-sdk" agent skill from https://github.com/LeoYeAI/openclaw-master-skills/tree/main/skills/claude-agent-sdk into .opencode/skills/claude-agent-sdk/ in this project. Copy the whole folder (SKILL.md and every file beside it), keep the folder name "claude-agent-sdk", then confirm the skill loads.OpenCode copies the folder itself, the same result as the manual copy. Check what it changed before you commit it.
claude-agent-sdkBuild autonomous AI agents with Claude Agent SDK. An agent skill from LeoYeAI/openclaw-master-skills.
Claude Agent SDK is an agent skill from LeoYeAI/openclaw-master-skills. 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. 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.
Its SKILL.md is about 7.3k tokens, which your agent loads only when the skill is triggered. The skill folder holds 27 other files, including scripts and reference files (for example `.claude-plugin/plugin.json`, `README.md` and `_meta.json`).
It sits in AI & LLM Engineering, covering Structured output and tool calling, Forms and validation and MCP servers. It works with Claude Agent SDK, Model Context Protocol and Zod. The repository describes itself as: 🧠 Curated collection of 1209+ best OpenClaw skills — weekly updated by MyClaw.ai. The licence is MIT.
4 steps, taken from the step headings in SKILL.md.
Read from SKILL.md and the folder at commit e5199b5. It shows what the files ask for, not the result of running them.
Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.
From allowed-tools in the SKILL.md frontmatter.
Ships 1 file in scripts/ (TypeScript and Shell, from the files we listed), which the agent can run.
Shell commands in SKILL.md call:
npmFrom the folder's file list and the shell code blocks in SKILL.md.
Links to these hosts (documentation or services it may open):
github.complatform.claude.comFrom URLs in SKILL.md, links to its own repository left out.
Names these keys or tokens, usually read from environment variables:
ANTHROPIC_API_KEYFrom names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.
Claude Agent SDK loads about 7.3k tokens when it runs, and up to ~20k if it reads all its reference files. Until then it costs about 100 tokens; SKILL.md has 1,680 words of instructions outside code blocks.
Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.
The automated check noted patterns worth knowing about, such as sudo or a known installer.
st sensitivePaths = ['/etc/', '/root/', '.env', 'credentials.json'];Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.
The full file from LeoYeAI/openclaw-master-skills at commit e5199b5, republished under its MIT licence (© LeoYeAI). 1,680 words, ~7,312 tokens.
.claude/skills/claude-agent-sdk/SKILL.md (or your agent's skills folder). This skill also uses 22 other files; get the full folder from GitHub.Package: @anthropic-ai/claude-agent-sdk@0.2.12 Breaking Changes: v0.1.45 - Structured outputs (Nov 2025), v0.1.0 - No default system prompt, settingSources required
Major Features:
outputFormat parameter - Define output structure with JSON schema or Zodmessage.structured_outputstructured-outputs-2025-11-13Example:
import { query } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
const schema = z.object({
summary: z.string(),
sentiment: z.enum(['positive', 'neutral', 'negative']),
confidence: z.number().min(0).max(1)
});
const response = query({
prompt: "Analyze this code review feedback",
options: {
model: "claude-sonnet-4-5",
outputFormat: {
type: "json_schema",
json_schema: {
name: "AnalysisResult",
strict: true,
schema: zodToJsonSchema(schema)
}
}
}
});
for await (const message of response) {
if (message.type === 'result' && message.structured_output) {
// Guaranteed to match schema
const validated = schema.parse(message.structured_output);
console.log(`Sentiment: ${validated.sentiment}`);
}
}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.
plugins array - Load local plugin pathsAll 12 Hook Events:
| Hook | When Fired | Use Case |
|---|---|---|
PreToolUse | Before tool execution | Validate, modify, or block tool calls |
PostToolUse | After tool execution | Log results, trigger side effects |
Notification | Agent notifications | Display status updates |
UserPromptSubmit | User prompt received | Pre-process or validate input |
SubagentStart | Subagent spawned | Track delegation, log context |
SubagentStop | Subagent completed | Aggregate results, cleanup |
PreCompact | Before context compaction | Save state before truncation |
PermissionRequest | Permission needed | Custom approval workflows |
Stop | Agent stopping | Cleanup, final logging |
SessionStart | Session begins | Initialize state |
SessionEnd | Session ends | Persist state, cleanup |
Error | Error occurred | Custom error handling |
Hook Configuration:
const response = query({
prompt: "...",
options: {
hooks: {
PreToolUse: async (input) => {
console.log(`Tool: ${input.toolName}`);
return { allow: true }; // or { allow: false, message: "..." }
},
PostToolUse: async (input) => {
await logToolUsage(input.toolName, input.result);
}
}
}
});fallbackModel - Automatic model fallback on failuresmaxThinkingTokens - Control extended thinking budgetstrictMcpConfig - Strict MCP configuration validationcontinue - Resume with new prompt (differs from resume)permissionMode: 'plan' - New permission mode for planning workflows📚 Docs: https://platform.claude.com/docs/en/agent-sdk/structured-outputs
Key signature:
query(prompt: string | AsyncIterable<SDKUserMessage>, options?: Options)
-> AsyncGenerator<SDKMessage>Critical Options:
outputFormat - Structured JSON schema validation (v0.1.45+)settingSources - Filesystem settings loading ('user'|'project'|'local')canUseTool - Custom permission logic callbackagents - Programmatic subagent definitionsmcpServers - MCP server configurationpermissionMode - 'default'|'acceptEdits'|'bypassPermissions'|'plan'betas - Enable beta features (e.g., 1M context window)sandbox - Sandbox settings for secure executionenableFileCheckpointing - Enable file state snapshotssystemPrompt - System prompt (string or preset object)Enable 1 million token context window:
const response = query({
prompt: "Analyze this large codebase",
options: {
betas: ['context-1m-2025-08-07'], // Enable 1M context
model: "claude-sonnet-4-5"
}
});Two forms of systemPrompt:
// 1. Simple string
systemPrompt: "You are a helpful coding assistant."
// 2. Preset with optional append (preserves Claude Code defaults)
systemPrompt: {
type: 'preset',
preset: 'claude_code',
append: "\n\nAdditional context: Focus on security."
}Use preset form when you want Claude Code's default behaviors plus custom additions.
Tool Control:
allowedTools - Whitelist (takes precedence)disallowedTools - BlacklistcanUseTool - Custom permission callback (see Permission Control section)Built-in Tools: Read, Write, Edit, Bash, Grep, Glob, WebSearch, WebFetch, Task, NotebookEdit, BashOutput, KillBash, ListMcpResources, ReadMcpResource, AskUserQuestion
Enable user interaction during agent execution:
const response = query({
prompt: "Review and refactor the codebase",
options: {
allowedTools: ["Read", "Write", "Edit", "AskUserQuestion"]
}
});
// Agent can now ask clarifying questions
// Questions appear in message stream as tool_call with name "AskUserQuestion"Use cases:
Three forms of tool configuration:
// 1. Exact allowlist (string array)
tools: ["Read", "Write", "Grep"]
// 2. Disable all tools (empty array)
tools: []
// 3. Preset with defaults (object form)
tools: { type: 'preset', preset: 'claude_code' }Note: allowedTools and disallowedTools still work but tools provides more flexibility.
Server Types:
createSdkMcpServer() with tool() definitionsTool Definition:
tool(name: string, description: string, zodSchema, handler)Handler Return:
{ content: [{ type: "text", text: "..." }], isError?: boolean }const response = query({
prompt: "List files and analyze Git history",
options: {
mcpServers: {
// Filesystem server
"filesystem": {
command: "npx",
args: ["@modelcontextprotocol/server-filesystem"],
env: {
ALLOWED_PATHS: "/Users/developer/projects:/tmp"
}
},
// Git operations server
"git": {
command: "npx",
args: ["@modelcontextprotocol/server-git"],
env: {
GIT_REPO_PATH: "/Users/developer/projects/my-repo"
}
}
},
allowedTools: [
"mcp__filesystem__list_files",
"mcp__filesystem__read_file",
"mcp__git__log",
"mcp__git__diff"
]
}
});const response = query({
prompt: "Analyze data from remote service",
options: {
mcpServers: {
"remote-service": {
url: "https://api.example.com/mcp",
headers: {
"Authorization": "Bearer your-token-here",
"Content-Type": "application/json"
}
}
},
allowedTools: ["mcp__remote-service__analyze"]
}
});Format: mcp__<server-name>__<tool-name>
CRITICAL:
__) as separatorsallowedTools arrayExamples: mcp__weather-service__get_weather, mcp__filesystem__read_file
type AgentDefinition = {
description: string; // When to use this agent
prompt: string; // System prompt for agent
tools?: string[]; // Allowed tools (optional)
model?: 'sonnet' | 'opus' | 'haiku' | 'inherit'; // Model (optional)
skills?: string[]; // Skills to load (v0.2.10+)
maxTurns?: number; // Maximum turns before stopping (v0.2.10+)
}Field Details:
haiku/sonnet/opus/inherit)Usage:
agents: {
"security-checker": {
description: "Security audits and vulnerability scanning",
prompt: "You check security. Scan for secrets, verify OWASP compliance.",
tools: ["Read", "Grep", "Bash"],
model: "sonnet",
skills: ["security-best-practices"], // Load specific skills
maxTurns: 10 // Limit to 10 turns
}
}Known Issue: Subagents don't stop when parent agent stops (Issue #132)
When a parent agent is stopped (via cancellation or error), spawned subagents continue running as orphaned processes. This can lead to:
Workaround: Implement cleanup in Stop hooks:
const response = query({
prompt: "Deploy to production",
options: {
agents: {
"deployer": {
description: "Handle deployments",
prompt: "Deploy the application",
tools: ["Bash"]
}
},
hooks: {
Stop: async (input) => {
// Manual cleanup of spawned processes
console.log("Parent stopped - cleaning up subagents");
// Implement process tracking and termination
}
}
}
});Enhancement Tracking: Issue #142 proposes auto-termination
Options:
resume: sessionId - Continue previous sessionforkSession: true - Create new branch from sessioncontinue: prompt - Resume with new prompt (differs from resume)Session Forking Pattern (Unique Capability):
// Explore alternative without modifying original
const forked = query({
prompt: "Try GraphQL instead of REST",
options: {
resume: sessionId,
forkSession: true // Creates new branch, original session unchanged
}
});Capture Session ID:
for await (const message of response) {
if (message.type === 'system' && message.subtype === 'init') {
sessionId = message.session_id; // Save for later resume/fork
}
}Simpler multi-turn conversation pattern:
import {
unstable_v2_createSession,
unstable_v2_resumeSession,
unstable_v2_prompt
} from "@anthropic-ai/claude-agent-sdk";
// Create a new session
const session = await unstable_v2_createSession({
model: "claude-sonnet-4-5",
workingDirectory: process.cwd(),
allowedTools: ["Read", "Grep", "Glob"]
});
// Send prompts and stream responses
const stream = unstable_v2_prompt(session, "Analyze the codebase structure");
for await (const message of stream) {
console.log(message);
}
// Continue conversation in same session
const stream2 = unstable_v2_prompt(session, "Now suggest improvements");
for await (const message of stream2) {
console.log(message);
}
// Resume a previous session
const resumedSession = await unstable_v2_resumeSession(session.sessionId);Note: V2 APIs are in preview (unstable_ prefix). The .receive() method was renamed to .stream() in v0.1.72.
Permission Modes:
type PermissionMode = "default" | "acceptEdits" | "bypassPermissions" | "plan";default - Standard permission checksacceptEdits - Auto-approve file editsbypassPermissions - Skip ALL checks (use in CI/CD only)plan - Planning mode (v0.1.45+)const response = query({
prompt: "Deploy application to production",
options: {
permissionMode: "default",
canUseTool: async (toolName, input) => {
// Allow read-only operations
if (['Read', 'Grep', 'Glob'].includes(toolName)) {
return { behavior: "allow" };
}
// Deny destructive bash commands
if (toolName === 'Bash') {
const dangerous = ['rm -rf', 'dd if=', 'mkfs', '> /dev/'];
if (dangerous.some(pattern => input.command.includes(pattern))) {
return {
behavior: "deny",
message: "Destructive command blocked for safety"
};
}
}
// Require confirmation for deployments
if (input.command?.includes('deploy') || input.command?.includes('kubectl apply')) {
return {
behavior: "ask",
message: "Confirm deployment to production?"
};
}
// Allow by default
return { behavior: "allow" };
}
}
});type CanUseToolCallback = (
toolName: string,
input: any
) => Promise<PermissionDecision>;
type PermissionDecision =
| { behavior: "allow" }
| { behavior: "deny"; message?: string }
| { behavior: "ask"; message?: string };Examples:
// Block all file writes
canUseTool: async (toolName, input) => {
if (toolName === 'Write' || toolName === 'Edit') {
return { behavior: "deny", message: "No file modifications allowed" };
}
return { behavior: "allow" };
}
// Require confirmation for specific files
canUseTool: async (toolName, input) => {
const sensitivePaths = ['/etc/', '/root/', '.env', 'credentials.json'];
if ((toolName === 'Write' || toolName === 'Edit') &&
sensitivePaths.some(path => input.file_path?.includes(path))) {
return {
behavior: "ask",
message: `Modify sensitive file ${input.file_path}?`
};
}
return { behavior: "allow" };
}
// Log all tool usage
canUseTool: async (toolName, input) => {
console.log(`Tool requested: ${toolName}`, input);
await logToDatabase(toolName, input);
return { behavior: "allow" };
}Enable sandboxed execution for Bash commands:
const response = query({
prompt: "Run system diagnostics",
options: {
sandbox: {
enabled: true,
autoAllowBashIfSandboxed: true, // Auto-approve bash in sandbox
excludedCommands: ["rm", "dd", "mkfs"], // Never auto-approve these
allowUnsandboxedCommands: false // Deny unsandboxable commands
}
}
});type SandboxSettings = {
enabled: boolean;
autoAllowBashIfSandboxed?: boolean; // Default: false
excludedCommands?: string[];
allowUnsandboxedCommands?: boolean; // Default: false
network?: NetworkSandboxSettings;
ignoreViolations?: SandboxIgnoreViolations;
};
type NetworkSandboxSettings = {
enabled: boolean;
proxyUrl?: string; // HTTP proxy for network requests
};Key Options:
enabled - Activate sandbox isolationautoAllowBashIfSandboxed - Skip permission prompts for safe bash commandsexcludedCommands - Commands that always require permissionallowUnsandboxedCommands - Allow commands that can't be sandboxed (risky)network.proxyUrl - Route network through proxy for monitoringBest Practice: Always use sandbox in production agents handling untrusted input.
Enable file state snapshots for rollback capability:
const response = query({
prompt: "Refactor the authentication module",
options: {
enableFileCheckpointing: true // Enable file snapshots
}
});
// Later: rewind file changes to a specific point
for await (const message of response) {
if (message.type === 'user' && message.uuid) {
// Can rewind to this point later
const userMessageUuid = message.uuid;
// To rewind (call on Query object)
await response.rewindFiles(userMessageUuid);
}
}Use cases:
Setting Sources:
type SettingSource = 'user' | 'project' | 'local';user - ~/.claude/settings.json (global)project - .claude/settings.json (team-shared)local - .claude/settings.local.json (gitignored overrides)Default: NO settings loaded (settingSources: [])
When multiple sources loaded, settings merge in this order (highest priority first):
query()) - Always win.claude/settings.local.json).claude/settings.json)~/.claude/settings.json)Example:
// .claude/settings.json
{
"allowedTools": ["Read", "Write", "Edit"]
}
// .claude/settings.local.json
{
"allowedTools": ["Read"] // Overrides project settings
}
// Programmatic
const response = query({
options: {
settingSources: ["project", "local"],
allowedTools: ["Read", "Grep"] // ← This wins
}
});
// Actual allowedTools: ["Read", "Grep"]Best Practice: Use settingSources: ["project"] in CI/CD for consistent behavior.
The query() function returns a Query object with these methods:
const q = query({ prompt: "..." });
// Async iteration (primary usage)
for await (const message of q) { ... }
// Runtime model control
await q.setModel("claude-opus-4-5"); // Change model mid-session
await q.setMaxThinkingTokens(4096); // Set thinking budget
// Introspection
const models = await q.supportedModels(); // List available models
const commands = await q.supportedCommands(); // List available commands
const account = await q.accountInfo(); // Get account details
// MCP status
const status = await q.mcpServerStatus(); // Check MCP server status
// Returns: { [serverName]: { status: 'connected' | 'failed', error?: string } }
// File operations (requires enableFileCheckpointing)
await q.rewindFiles(userMessageUuid); // Rewind to checkpointUse cases:
Message Types:
system - Session init/completion (includes session_id)assistant - Agent responsestool_call - Tool execution requeststool_result - Tool execution resultserror - Error messagesresult - Final result (includes structured_output for v0.1.45+)Streaming Pattern:
for await (const message of response) {
if (message.type === 'system' && message.subtype === 'init') {
sessionId = message.session_id; // Capture for resume/fork
}
if (message.type === 'result' && message.structured_output) {
// Structured output available (v0.1.45+)
const validated = schema.parse(message.structured_output);
}
}Error Codes:
| Error Code | Cause | Solution |
|---|---|---|
CLI_NOT_FOUND | Claude Code not installed | Install: npm install -g @anthropic-ai/claude-code |
AUTHENTICATION_FAILED | Invalid API key | Check ANTHROPIC_API_KEY env var |
RATE_LIMIT_EXCEEDED | Too many requests | Implement retry with backoff |
CONTEXT_LENGTH_EXCEEDED | Prompt too long | Use session compaction, reduce context |
PERMISSION_DENIED | Tool blocked | Check permissionMode, canUseTool |
TOOL_EXECUTION_FAILED | Tool error | Check tool implementation |
SESSION_NOT_FOUND | Invalid session ID | Verify session ID |
MCP_SERVER_FAILED | Server error | Check server configuration |
This skill prevents 14 documented issues:
Error: "Claude Code CLI not installed"
Source: SDK requires Claude Code CLI
Why It Happens: CLI not installed globally
Prevention: Install before using SDK: npm install -g @anthropic-ai/claude-code
Error: "Invalid API key"
Source: Missing or incorrect ANTHROPIC_API_KEY
Why It Happens: Environment variable not set
Prevention: Always set export ANTHROPIC_API_KEY="sk-ant-..."
Error: Tool execution blocked
Source: permissionMode restrictions
Why It Happens: Tool not allowed by permissions
Prevention: Use allowedTools or custom canUseTool callback
Error: "Prompt too long"
Source: Input exceeds model context window (Issue #138)
Why It Happens: Large codebase, long conversations
⚠️ Critical Behavior: Once a session hits context limit:
/compact command fails with same errorPrevention Strategies:
// 1. Proactive session forking (create checkpoints before hitting limit)
const checkpoint = query({
prompt: "Checkpoint current state",
options: {
resume: sessionId,
forkSession: true // Create branch before hitting limit
}
});
// 2. Monitor time and rotate sessions proactively
const MAX_SESSION_TIME = 80 * 60 * 1000; // 80 minutes (before 90-min crash)
let sessionStartTime = Date.now();
function shouldRotateSession() {
return Date.now() - sessionStartTime > MAX_SESSION_TIME;
}
// 3. Start new sessions before hitting context limits
if (shouldRotateSession()) {
const summary = await getSummary(currentSession);
const newSession = query({
prompt: `Continue with context: ${summary}`
});
sessionStartTime = Date.now();
}Note: SDK auto-compacts, but if limit is reached, session becomes unrecoverable
Error: Tool doesn't respond Source: Long-running tool execution Why It Happens: Tool takes too long (>5 minutes default) Prevention: Implement timeout handling in tool implementations
Error: "Invalid session ID"
Source: Session expired or invalid
Why It Happens: Session ID incorrect or too old
Prevention: Capture session_id from system init message
Error: Server not responding Source: Server not running or misconfigured Why It Happens: Command/URL incorrect, server crashed Prevention: Test MCP server independently, verify command/URL
Error: Invalid AgentDefinition
Source: Missing required fields
Why It Happens: description or prompt missing
Prevention: Always include description and prompt fields
Error: "Cannot read settings"
Source: Settings file doesn't exist
Why It Happens: settingSources includes non-existent file
Prevention: Check file exists before including in sources
Error: Duplicate tool name Source: Multiple tools with same name Why It Happens: Two MCP servers define same tool name Prevention: Use unique tool names, prefix with server name
Error: Invalid tool input
Source: Input doesn't match Zod schema
Why It Happens: Agent provided wrong data type
Prevention: Use descriptive Zod schemas with .describe()
Error: Cannot access path
Source: Restricted filesystem access
Why It Happens: Path outside workingDirectory or no permissions
Prevention: Set correct workingDirectory, check file permissions
type FieldError: "Claude Code process exited with code 1" (cryptic, no context)
Source: GitHub Issue #131
Why It Happens: URL-based MCP servers require explicit type: "http" or type: "sse" field
Prevention: Always specify transport type for URL-based MCP servers
// ❌ Wrong - missing type field (causes cryptic exit code 1)
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp"
}
}
// ✅ Correct - type field required for URL-based servers
mcpServers: {
"my-server": {
url: "https://api.example.com/mcp",
type: "http" // or "sse" for Server-Sent Events
}
}Diagnostic Clue: If you see "process exited with code 1" with no other context, check your MCP server configuration for missing type fields.
Error: JSON parse error, agent hangs Source: GitHub Issue #137 Why It Happens: Unicode U+2028 (line separator) and U+2029 (paragraph separator) are valid in JSON but break JavaScript parsing Prevention: Escape these characters in MCP tool results
// MCP tool handler - sanitize external data
tool("fetch_content", "Fetch text content", {}, async (args) => {
const content = await fetchExternalData();
// ✅ Sanitize Unicode line/paragraph separators
const sanitized = content
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029');
return {
content: [{ type: "text", text: sanitized }]
};
});When This Matters: External data sources (APIs, web scraping, user input) that may contain these characters
Related: MCP Python SDK Issue #1356
Token Efficiency:
Errors prevented: 14 documented issues with exact solutions (including 2 community-sourced gotchas) 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
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
© LeoYeAI, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file
SKILL.md and 22 other files (scripts, references) in skills/claude-agent-sdk of LeoYeAI/openclaw-master-skills.
Open the folder on GitHubat commit e5199b5
Claude Agent SDK next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.
| Skill | Stars | Used in | Tokens | Auto-check | Licence | Repo updated |
|---|---|---|---|---|---|---|
| Claude Agent SDK this skillLeoYeAI/openclaw-master-skills | 2.2k | — | ~7.3k | Automated safety check: Notes | MIT | |
| MCP Server Patternsaffaan-m/ECC | 276k | 5 repos | ~1k | Automated safety check: Pass | MIT | |
| MCP Server Patternsaffaan-m/ECC | 276k | 1 repos | ~551 | Automated safety check: Pass | MIT | |
| Tool Designagentailor/fullstack-langgraph-nextjs-agent | 132 | — | ~3.2k | Automated safety check: Pass | MIT | |
| Pi AgentK-Dense-AI/scientific-agent-skills | 48k | 1 repos | ~2.1k | Automated safety check: Pass | MIT | |
| Agent Tool Builderomer-metin/skills-for-antigravity | 162 | — | ~705 | Automated safety check: Pass | Apache-2.0 |
affaan-m/ECC
Build MCP servers with Node/TypeScript SDK — tools, resources, prompts, Zod validation, stdio vs Streamable HTTP.
affaan-m/ECC
使用Node/TypeScript SDK构建MCP服务器——工具、资源、提示、Zod验证、stdio与可流式HTTP对比。使用Context7或官方MCP文档获取最新API信息。
agentailor/fullstack-langgraph-nextjs-agent
Design and verify tools that AI agents can actually use — for any framework or language (MCP servers, LangChain/LangGraph, function-calling, raw JSON schema; TypeScript, Python, or otherwise).
K-Dense-AI/scientific-agent-skills
Builds with and operates Pi, the minimal terminal coding harness.
omer-metin/skills-for-antigravity
Tools are how AI agents interact with the world. An agent skill from omer-metin/skills-for-antigravity.
langchain-ai/langchain-skills
INVOKE THIS SKILL when you need human-in-the-loop approval, custom middleware, or structured output.
LeoYeAI/openclaw-master-skills
Manages pipelines on a DevOps quality and efficiency platform through its OpenAPI: list workspaces and templates, create, update, run and cancel pipelines, and read run records.
LeoYeAI/openclaw-master-skills
Patches OpenClaw's Feishu extension so an edited document triggers an isolated agent session that reads the doc and replies inline, turning it into a live chat space.
LeoYeAI/openclaw-master-skills
Multi-context memory management system for OpenClaw agents with group-isolated storage, global shared memory, workspace organization, and group-specific skills isolation.
LeoYeAI/openclaw-master-skills
Runs a brand's AI-search visibility work end to end: diagnosing how AI platforms represent it, repositioning it, producing AI-optimized content and monitoring ongoing mentions.
LeoYeAI/openclaw-master-skills
Installs and authenticates the gws CLI, then automates Gmail, Drive, Sheets, Calendar, Docs, Chat and Tasks with ready-made recipes, persona bundles and security audits.
LeoYeAI/openclaw-master-skills
Runs four advisor roles, a fitness coach, nutritionist, data analyst and TCM practitioner, to build a health profile and track workouts, diet and wellness over time.
Categories
Build autonomous AI agents with Claude Agent SDK. An agent skill from LeoYeAI/openclaw-master-skills. Claude Agent SDK is an agent skill from LeoYeAI/openclaw-master-skills. Build autonomous AI agents with Claude Agent SDK.
Claude Agent SDK fits situations like: : building coding agents; security auditors; troubleshooting CLI not found; structured output validation.
Run `npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a claude-code`. Or copy the skill folder (skills/claude-agent-sdk in LeoYeAI/openclaw-master-skills) into .claude/skills/claude-agent-sdk in your project. Claude Code loads it when a task matches its description.
Run `npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a codex`. Or copy the skill folder (skills/claude-agent-sdk in LeoYeAI/openclaw-master-skills) into .agents/skills/claude-agent-sdk in your project. Codex loads it when a task matches its description.
Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add LeoYeAI/openclaw-master-skills --skill claude-agent-sdk -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/claude-agent-sdk, .gemini/skills/claude-agent-sdk, .github/skills/claude-agent-sdk and .opencode/skills/claude-agent-sdk in your project.
Going by SKILL.md and its folder, Claude Agent SDK needs TypeScript and a shell for the scripts in its folder, the command-line tools its instructions call (npm) and credentials named ANTHROPIC_API_KEY. Our summary lists: Node.js; A Bash shell.
SKILL.md names 2 domains. As links in the text: github.com and platform.claude.com. This is read from the text; nothing was executed.
Our automated static check of SKILL.md found notes only (mentions a .env file), nothing it rates as a warning. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.
Claude Agent SDK is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.
About 7.3k tokens (SKILL.md is roughly 29k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 13k tokens, read only when the agent opens those files.
Skills that share tags, products or a category with Claude Agent SDK: MCP Server Patterns (affaan-m/ECC, 276k stars), MCP Server Patterns (affaan-m/ECC, 276k stars), Tool Design (agentailor/fullstack-langgraph-nextjs-agent, 132 stars) and Pi Agent (K-Dense-AI/scientific-agent-skills, 48k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.
LeoYeAI (a GitHub user) maintains it in LeoYeAI/openclaw-master-skills, which has 2,160 GitHub stars. The repository holds 1,235 skills in this directory. The repository was last updated on July 20, 2026.
Source: LeoYeAI/openclaw-master-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.