claude-sdk-agent.ts
File: claude-sdk-agent.ts. Copy it with the button on the code block, or download it with the agent templates: agents-templates.zip.
/** * Claude Agent SDK template: summarise a PR diff into summary.md. * * Setup: npm init -y && npm pkg set type=module (top-level await needs an ES module) * npm install -D tsx && npm install @anthropic-ai/claude-agent-sdk * Auth: ANTHROPIC_API_KEY (or the Bedrock / Vertex AI / Foundry environment variables) * Run: git fetch origin main && npx tsx claude-sdk-agent.ts * (in CI, fetch the base branch first or the diff has nothing to compare against) * * Exit codes: 0 = success, 1 = max turns reached, 2 = budget exceeded, * 3 = error during the run, 4 = timed out, 5 = no result. * Check option names against the current SDK docs; the surface evolves. */import { query } from "@anthropic-ai/claude-agent-sdk";
const PROMPT = `Summarise the changes in \`git diff origin/main...HEAD\`.Write the result to summary.md using exactly these headings:## What changed## Why it matters## RisksKeep it under 200 words. Do not modify any other file.`;
const TIMEOUT_MS = 10 * 60_000;
const EXIT_CODES: Record<string, number> = { success: 0, error_max_turns: 1, error_max_budget_usd: 2, error_during_execution: 3,};
async function main(): Promise<number> { const abortController = new AbortController(); const timer = setTimeout(() => abortController.abort(), TIMEOUT_MS); let exitCode = 5;
try { for await (const message of query({ prompt: PROMPT, options: { systemPrompt: "You are a release engineer. Be concise and factual.", tools: ["Read", "Grep", "Glob", "Bash", "Write"], // the only tools the agent has allowedTools: ["Read", "Grep", "Glob", "Bash(git diff *)", "Write"], // run without asking permissionMode: "dontAsk", // deny anything not in allowedTools settingSources: [], // ignore ambient config, for reproducible CI maxTurns: 20, maxBudgetUsd: 1, abortController, // MCP example: GitHub's official server (github/github-mcp-server). Allow its tools too, // e.g. add "mcp__github__*" to allowedTools. // mcpServers: { // github: { // command: "docker", // args: ["run", "-i", "--rm", "-e", "GITHUB_PERSONAL_ACCESS_TOKEN", "ghcr.io/github/github-mcp-server"], // env: { GITHUB_PERSONAL_ACCESS_TOKEN: process.env.GITHUB_TOKEN! }, // }, // }, // agents: { "diff-reader": { description: "...", prompt: "...", tools: ["Read", "Bash"] } }, }, })) { if (message.type === "result") { console.error(`result=${message.subtype} turns=${message.num_turns} cost=$${message.total_cost_usd}`); exitCode = EXIT_CODES[message.subtype] ?? 3; } } } catch (err) { if (abortController.signal.aborted) { console.error(`timed out after ${TIMEOUT_MS / 1000}s`); return 4; } throw err; } finally { clearTimeout(timer); }
return exitCode;}
process.exit(await main());