KRIT.JUNSREE PERSONAL WEBSITE
MEDIUM

Definitive Guide: Claude Agent SDK 14 Part — สร้าง AI Agent Generation ถัดไป

คู่มือครบ Claude Agent SDK จาก Burak Kaya — architecture (query/ClaudeSDKClient), tool 18+ ตัว, security model 4 permission mode + hook 12 event, MCP + Skill (agentskills.io), multi-agent, Opus 4.6 + 16-agent C compiler experiment ($20K), memory (30h+ session), production case: Spotify 650 PR/เดือน, Apple Xcode 26.3, BGL 200+ employee. รวม GitHub Actions template

By krit.junsree@gmail.com ◆ Jul 10, 2026 ◆ 27 MIN READ Beginner

☰ ON THIS PAGE

Burak Kaya คู่มือครบสำหรับ Claude Agent SDK 14 ส่วน — จาก conversation → execution, architecture, tool 18+ ตัว, security model, MCP + Skill, multi-agent, Opus 4.6, memory, production, case study (Spotify, Apple, BGL)

Part 1: จาก Conversation สู่ Execution

เดิมทุกคนเน้น conversational chatbot → ตอนนี้เน้น autonomous agent ที่ทำงานซับซ้อน interact ระบบดิจิทัลได้ ให้ผลลัพธ์วัดได้

Claude Agent SDK = open-source production-grade framework เปิด infrastructure ของ Claude Code เป็น library ให้ Python + TypeScript. announce 22 พ.ค. 2025 พร้อม Opus 4/Sonnet 4 · 29 ก.ย. 2025 rebrand เป็น “Claude Agent SDK” ตอน Sonnet 4.5

1.1 Migration v0.1.0

  • SDK ไม่ใช้ system prompt ของ Claude Code เป็น default อีกต่อไป (ต้อง opt-in)
  • อ่าน filesystem setting ปิด default (ต้อง configure settingSources)
  • ClaudeCodeOptions เปลี่ยนเป็น ClaudeAgentOptions

1.2 ทำไมไม่ใช่แค่ API wrapper

Standard SDK (anthropic) = stateless message completion เฉย ๆ · Agent SDK = complete agent runtime: tool + auto context mgmt + session persistence + granular permission + subagent + MCP

text
Your Application (Python / TypeScript)
        ↓
Claude Agent SDK (The Agent Harness)
        ↓
Claude Code CLI (The Runtime Engine, bundled with the SDK)
        ↓
Claude API (The Model)

1.3 Install + Setup

bash
pip install claude-agent-sdk
bash
npm install @anthropic-ai/claude-agent-sdk

Prerequisites: Python 3.10+ (ถึง 3.13), Node.js 18+, macOS/Linux/WSL. Auth: export ANTHROPIC_API_KEY=your-key. Enterprise: Bedrock, Vertex AI, Azure AI Foundry

Part 2: Core Architecture — ให้ Agent มี Computer

2.1 Agentic Loop 5 step

  1. Gather Context — อ่านไฟล์, search web, ตรวจ env
  2. Think & Plan — reason + วางแผน
  3. Take Action — เรียก tool, shell, edit file
  4. Observe Result — วิเคราะห์ output
  5. Verify & Repeat — เช็คงาน ตัดสินใจ step ถัดไป

Loop เป็น strongly-typed message sequence: ToolUseBlock, ThinkingBlock, ResultMessage

2.2 Interface 2 ตัว: query() vs ClaudeSDKClient

  • query() — stateless one-shot, ephemeral session, return AsyncIterator. เหมาะ single task, CLI, CI/CD. Startup overhead ~12 วินาที — ไม่เหมาะ interactive low-latency
  • ClaudeSDKClient — persistent stateful, multi-turn, interrupt, custom tool/hook. TS ใช้ Query object + interrupt() + rewindFiles()
python
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions

async def main():
    options = ClaudeAgentOptions(
        system_prompt="You are an expert Python developer",
        permission_mode="acceptEdits",
        cwd="/home/user/project",
    )
    async for message in query(
        prompt="Create a Python web server with health checks",
        options=options,
    ):
        print(message)

asyncio.run(main())

2.4 Message Stream

  • SDKAssistantMessage — TextBlock, ThinkingBlock, ToolUseBlock, ToolResultBlock
  • SDKResultMessage — subtype, total_cost_usd, modelUsage, duration_ms, num_turns
  • SDKCompactBoundaryMessage — โผล่เมื่อ context ใกล้ limit

Part 3: Tool 18+ ตัวในตัว

Filesystem: Read · Write · Edit · MultiEdit · Glob · Grep

Code exec: Bash · BashOutput · KillBash

Web: WebSearch · WebFetch

Orchestration: Task · AskUserQuestion · TodoWrite · ExitPlanMode

Notebook: NotebookEdit

MCP: ListMcpResources · ReadMcpResource

Part 4: Security Model

4.1 Threat Model

  • Prompt Injection → strict tool permission + input-sanitizing hook
  • Data Exfiltration → network sandbox
  • Destructive Ops → permission prompt + declarative rule + OS sandbox
  • Runaway Execution & Costmax_turns + max_budget_usd circuit breaker

4.2 Multi-Layered Evaluation Order

  1. PreToolUse Hook — powerful ที่สุด
  2. Declarative Deny — disallowed_tools, deny rule ใน settings.json
  3. Declarative Allow
  4. Declarative Ask
  5. Permission Mode
  6. canUseTool Callback — runtime decision สุดท้าย
  7. PostToolUse Hook — post-exec audit

4.3 Permission Mode 4 แบบ

  • default — ปลอดภัยสุด ถาม user เรื่อง sensitive op
  • acceptEdits — auto-approve file mod + common fs command
  • plan — read-only ไม่แก้ environment
  • bypassPermissions — อันตรายสุด ข้ามทุก check ต้อง explicit opt-in

4.4 canUseTool

typescript
const result = query({
  prompt: "Clean up the temp directory and save the logs.",
  options: {
    permissionMode: "default",
    canUseTool: async (toolName, input) => {
      if (toolName === "Bash" && typeof input.command === 'string' && input.command.includes("rm -rf")) {
        return { behavior: 'deny', message: 'Destructive commands permanently blocked.' };
      }
      if (toolName === "Write" && typeof input.file_path === 'string' && !input.file_path.startsWith("output/")) {
        const newPath = `output/${input.file_path.split('/').pop()}`;
        return { behavior: 'allow', updatedInput: { ...input, file_path: newPath } };
      }
      return { behavior: 'allow', updatedInput: input };
    }
  }
});

4.5 Declarative Guardrail

yaml
# Allow the agent to check status and diffs, but not commit or push.
--allowedTools "Bash(git status),Bash(git diff *),Read(*),Glob(*)"

4.6 OS Sandbox

Bubblewrap (Linux) + Seatbelt (macOS) — filesystem + network isolation. Anthropic รายงาน ลด manual permission prompt 84%

4.8 Hook System — 12 lifecycle event

json
{
  "hooks": {
    "PreToolUse": [
      { "matcher": "Bash", "type": "command",
        "command": "python3 /scripts/validate_bash_command.py \"$TOOL_INPUT\"" }
    ],
    "PostToolUse": [
      { "matcher": "Write", "type": "prompt",
        "prompt": "Review this file write. Does it contain sensitive data like API keys? If yes, DENY. Otherwise ALLOW." }
    ]
  }
}

Part 5: Extensibility

5.1 MCP

4 transport: stdio, http/sse, sdk (in-process, ประหยัดสุด). Tool namespace: mcp____

5.2 Custom Tool ผ่าน In-Process MCP

python
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, query
import database

@tool("query_database", "Query the company's user database", {"sql_query": str})
async def query_database(args):
    try:
        results = await database.run_query(args["sql_query"])
        return {"content": [{"type": "text", "text": f"Query Result: {results}"}]}
    except Exception as e:
        return {"content": [{"type": "text", "text": f"Error: {str(e)}"}]}

db_server = create_sdk_mcp_server(name="database", version="1.0.0", tools=[query_database])
options = ClaudeAgentOptions(mcp_servers={"db": db_server}, allowed_tools=["mcp__db__query_database"])

เมื่อ tool definition เกิน 10% ของ context window SDK activate Tool Search Tool — agent search tool (regex / BM25) โหลดเฉพาะที่ต้องการ

5.4 Agent Skill — Reusable Knowledge Layer

Skill = instruction/script/reference package. Publish เป็น open standard ที่ agentskills.io ธ.ค. 2025. โครงเป็น directory มี SKILL.md. ใช้ progressive disclosure — โหลดแค่ name+description ตอน startup

yaml
---
name: pdf-processing
description: Extract and analyze content from PDF documents
---

# PDF Processing Workflow
## Instructions
1. Use `pdftotext` via the `Bash` tool to convert the PDF to text.
2. Read the resulting text file.
3. Analyze the extracted text for the requested data points.
4. Generate a structured Markdown summary.

5.5 Plugin + Slash Command

Plugin bundle: skill + slash command + hook + MCP server. Slash command (เช่น /review) merge กับ Agent Skill ใน SDK ล่าสุด

Part 6: Multi-Agent

6.1 Subagent Pattern

  • Context isolation
  • Parallel execution
  • Distilled summary — subagent return แค่ concise summary

6.2 Define + Invoke Subagent

python
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition

async for message in query(
    prompt="Review the new authentication module for security flaws and then run the test suite.",
    options=ClaudeAgentOptions(
        agents={
            "code-reviewer": AgentDefinition(
                description="Expert code reviewer for security vulnerabilities. Use proactively after code changes.",
                prompt="You are a senior code reviewer focused on security and code quality.",
                tools=["Read", "Grep", "Glob"],
                model="claude-sonnet-4-5"
            ),
            "debugger": AgentDefinition(
                description="Debugging specialist for errors and test failures.",
                prompt="You are an expert debugger. Analyze error logs, identify root causes, suggest fixes.",
                model="claude-haiku-4-5"
            )
        },
        allowed_tools=["Read", "Edit", "Bash", "Task"]  # Parent agents need 'Task'
    )
):
    print(message)

6.3 Rule of Hierarchy

  1. No Infinite Nesting — subagent spawn subagent ต่อไม่ได้
  2. Permission Inheritance — subagent inherit bypassPermissions จาก parent (override ไม่ได้)
  3. Model Flexibility — model ต่างกันได้ (Opus orchestrator + Haiku subtask)

6.4 Filesystem + Built-in Subagent

Subagent = MD file + YAML frontmatter ใน .claude/agents/. Built-in: Explore (read-only) + Plan (research)

Part 7: Engine — Opus 4.6

Release 5 ก.พ. 2026. ทำ 76% บน MRCR v2 (1M-token long-context retrieval). เก่ง tool use, complex instruction, multi-step coherence

7.2 Agent Teams: C Compiler Experiment

ทีม 16 Claude agent orchestrate ผ่าน Agent SDK build C compiler จากศูนย์ ทำงานหลายสัปดาห์ autonomous — ค่า API ~$20,000

Part 8: Memory

8.1 Automatic Compaction

Server-side summarize บทสนทนาเก่าเมื่อ context ใกล้ limit — enable 30+ hours sustained operation กับ Sonnet 4.5. Beta ผ่าน compact-2026-01-12 flag · fire PreCompact hook

8.2 Context Editing

clear_tool_uses_20250919 ลบ verbose tool output เก่าที่ process แล้ว

8.3 Session Management

  • Resumption — resume ด้วย session ID
  • Forking — branch conversation แยก experiment
  • Point-in-Time Recovery — resumeSessionAt: 'message-uuid', rewindFiles()

8.4 Beyond Context Window

  • Memory Tool — read/write dir /memories
  • CLAUDE.md — persistent instruction

8.5 Initializer + Coder Pattern

  1. Initializer — รันครั้งเดียว: setup env + analyze + เขียน TODO.md
  2. Coder — รันซ้ำ ๆ: อ่าน TODO.md, ทำ step ถัดไป, update TODO.md

Part 9: Production

9.1 Hosting + Sizing

Agent ต้องรันใน sandboxed container (Docker, gVisor, Firecracker). ทั่วไป: ~1 GiB RAM, ~5 GiB disk, 1 vCPU

9.2 Observability

Native: LangSmith, MLflow (mlflow.anthropic.autolog()), OpenTelemetry (Grafana, Arize, Datadog, Honeycomb, Sentry, Logfire)

9.4 Known Limitation

  • query() Overhead — ~12 วินาที startup — community #1 request คือ “hot process reuse”
  • allowedTools Bypass Bug — workaround: set disallowedTools + canUseTool ด้วย
  • Context Limit Failure — session ที่ hit context limit ครั้งเดียว = request ถัด ๆ ไป fail ตลอด — fork ก่อน limit
  • Real-World Messiness — practitioner คนหนึ่ง accuracy ตกจาก 10/10 ตอน test → ~60% ใน production

Part 10: Case Study

  • Spotify — background coding agent fleet trigger ผ่าน Slack merge 650+ PR/เดือน · 90% dev time savings ตอน migration
  • BGL Group — natural-language BI agent บน Bedrock AgentCore 200+ employees ตอบทันทีจาก 400+ analytics table
  • Apple — Xcode 26.3 มี native Claude Agent SDK integration (multi-file refactor + SwiftUI gen)
  • Startup — Ad Agent, SOC 2 Compliance, research agent วิเคราะห์ 200+ doc ใน 12 นาที

Part 12: CI/CD — GitHub Actions

text
name: Claude Code Review
on:
  pull_request:
    types: [opened, synchronize]
jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: anthropics/claude-code-action@v1
        with:
          anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
          prompt: |
            Review this pull request for:
            1. Security vulnerabilities
            2. Performance issues
            3. Code style violations
            4. Missing test coverage
          model: claude-sonnet-4-5
          max_budget_usd: "0.50"
          allowed_tools: "Read,Grep,Glob,Bash(npm test *)"

Part 14: New Stack for AI Engineering

Claude Agent SDK = production-grade framework: battle-tested agent loop + rich tool + multi-layered security + extensibility. เมื่อ build agent ง่ายขึ้น challenge ต่อไปคือสร้าง trustworthy agent — อนาคตของ software engineering “not just code-writing but intelligence orchestration”


แหล่งที่มา: “The Definitive Guide to the Claude Agent SDK: Building the Next Generation of AI” โดย Burak Kaya ตีพิมพ์ 10 ก.พ. 2026 บน Medium · อ่านต้นฉบับ

Leave a Reply

Your email address will not be published. Required fields are marked *