Claude Code: Agent SDK

最終更新:2026-08-31

Agent SDK により、Claude Code の能力がプログラマブルな API になります — アプリケーションに AI コーディング能力を組み込み、カスタム AI ワークフローを構築できます。

💡 ヒント: Agent SDK は Claude Code を API サーバーにするのではなく、コード内で Claude Code の Agent 能力を呼び出す SDK を提供します — ファイルの読み書き、コード生成、テスト実行等。

📋 前提条件: 第23章 - Git ワークフローと GitHub Actions

1. 学ぶ内容


2. Agent SDK アーキテクチャ

(1) SDK と CLI

次元 CLI SDK
使用方法 ターミナルコマンド コードからの呼び出し
インタラクション 人間との会話 プログラミングインターフェース
カスタマイズ性 限定 完全にカスタマイズ可能
統合 パイプライン/スクリプト 深い組み込み
ユースケース 日常開発 AI アプリケーションの構築

▶ 例1:SDK の基本使用

TYPESCRIPT
import { Agent } from "@anthropic-ai/claude-code-sdk";

const agent = new Agent({
  apiKey: process.env.ANTHROPIC_API_KEY,
  model: "claude-sonnet-4-20250514",
  workingDir: "./my-project",
});

const result = await agent.run("Add user login with JWT authentication");

console.log(result.summary);
console.log(`Files modified: ${result.files.length}`);
console.log(`Tests passed: ${result.testsPassed}`);

3. コア API

(1) Agent の作成と設定

TYPESCRIPT
const agent = new Agent({
  apiKey: "sk-ant-api03-xxxxx",
  model: "claude-sonnet-4-20250514",
  workingDir: "/path/to/project",
  tools: ["Read", "Write", "Bash"],
  maxTurns: 30,
  style: "concise",
});

(2) タスクの実行

TYPESCRIPT
// 基本実行
const result = await agent.run("Fix all TypeScript errors");

// ストリーミング実行
const stream = agent.runStream("Refactor auth module");
for await (const event of stream) {
  console.log(event.type, event.data);
}

// コンテキスト付き実行
const result = await agent.run("Modify this function", {
  files: ["src/auth/jwt.ts"],
  context: "Use RS256 instead of HS256",
});

(3) 結果の処理

TYPESCRIPT
interface AgentResult {
  summary: string;
  files: FileChange[];
  commands: CommandResult[];
  testsPassed: number;
  testsFailed: number;
  tokensUsed: number;
  cost: number;
}

▶ 例2:カスタムワークフロー

TYPESCRIPT
async function reviewAndFix(projectDir: string) {
  const agent = new Agent({
    apiKey: process.env.ANTHROPIC_API_KEY!,
    workingDir: projectDir,
    tools: ["Read", "Write", "Bash"],
  });

  // Step 1: コードレビュー
  const review = await agent.run(
    "Review project code quality, list all issues to fix"
  );

  // Step 2: 自動修正
  if (review.summary.includes("issue")) {
    const fix = await agent.run("Fix all listed quality issues, run tests");
    console.log(`Tests: ${fix.testsPassed} passed, ${fix.testsFailed} failed`);
  }
}

4. カスタム Agent

(1) カスタムツール

TYPESCRIPT
const databaseQueryTool: Tool = {
  name: "database_query",
  description: "Execute a read-only SQL query",
  parameters: {
    sql: { type: "string", description: "SQL query (SELECT only)" },
  },
  execute: async ({ sql }) => {
    if (!sql.trim().toUpperCase().startsWith("SELECT")) {
      throw new Error("Only SELECT queries allowed");
    }
    const result = await db.query(sql);
    return { rows: result.rows, count: result.rowCount };
  },
};

const agent = new Agent({
  apiKey: process.env.ANTHROPIC_API_KEY!,
  tools: ["Read", "Write", databaseQueryTool],
});

(2) イベントリスニング

TYPESCRIPT
agent.on("file:write", (data) => {
  console.log(`Modified: ${data.filePath}`);
  auditLog.record(data);
});

agent.on("bash:execute", (data) => {
  if (data.command.includes("DROP")) {
    throw new Error("Dangerous command blocked");
  }
});

▶ 例3:コードレビュー Bot

TYPESCRIPT
class CodeReviewBot {
  private agent: Agent;

  constructor(apiKey: string) {
    this.agent = new Agent({
      apiKey,
      model: "claude-sonnet-4-20250514",
      tools: ["Read", "Bash"],
    });
  }

  async reviewPR(repoDir: string, prDiff: string) {
    this.agent.setWorkingDir(repoDir);
    const result = await this.agent.run(
      `Review PR changes:\n${prDiff}\n\nCheck security, performance, style, test coverage`
    );
    return { review: result.summary, score: this.calculateScore(result.summary) };
  }

  private calculateScore(text: string): number {
    let score = 100;
    if (text.includes("critical")) score -= 30;
    if (text.includes("warning")) score -= 10;
    return Math.max(0, score);
  }
}

5. SDK と CLI の連携

シナリオ CLI SDK
日常開発
CI/CD ✅(headless)
カスタムツール
Web アプリ統合
バッチ自動化 ⚠️(スクリプト)

❓ よくある質問

Q SDK には別途 CLI のインストールが必要ですか?
A いいえ。SDK は独立した npm パッケージです。両者は同じ API Key を共有します。
Q SDK API は安定していますか?
A コア API は安定していますが、詳細はバージョンで変更される可能性があります。バージョン番号を固定し、changelog を確認してください。
Q SDK はブラウザで動作しますか?
A いいえ。Node.js 環境が必要です。ファイルシステムと Shell 操作が含まれます。
Q CLI と同じ料金ですか?
A はい。両者とも同じ課金で Anthropic API を呼び出します。

📖 まとめ


📝 練習問題

  1. 基本 (⭐): SDK で Agent を作成し、シンプルなタスクを実行して結果を出力してください。
  2. 応用 (⭐⭐): 構造化出力の自動コードレビュースクリプトを構築してください。
  3. 高度 (⭐⭐⭐): GitHub Webhook と統合したコードレビュー Bot を構築し、自動 PR レビューを実装してください。
Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%