Step-by-step: build an SDK agent (Claude Agent SDK & Cursor SDK)
Use this guide when an agent must run from code: a CI job, a bot, a scheduled task, or inside a product. Each step has a Goal, what to Do, and how to Verify it.
Running example: a pr-summary agent that runs in CI, reads the diff, and writes a summary to summary.md.
To skip copying a template, use the SDK agent builder. It asks for the job, trigger, tools and budget this guide requires and writes a TypeScript file (or two, if you pick both SDKs) you can copy or download. Put keys in the environment, then come back to these steps for setup, testing, and deploy.
SDK APIs change faster than the file formats. The snippets here show the shape of each SDK. Always check them against the current docs in the official sources before you rely on them.
Step 1: Define the job, trigger, and output
Section titled “Step 1: Define the job, trigger, and output”- Goal: Know what starts the agent, what it does, and where its result goes.
- Do: Write down:
- Trigger: a PR is opened (CI), a cron schedule, a webhook, or a user action in your app
- Inputs: the repo checkout, the PR number, and environment variables
- Output: a file, a PR comment, a JSON result, or an exit code
- Budget: maximum turns, maximum cost, and a timeout
- Verify: You could implement it as a shell script if the “thinking” part were done by a human.
Step 2: Choose the SDK
Section titled “Step 2: Choose the SDK”-
Goal: The right harness.
-
Do:
Choose If Claude Agent SDK You want to run on your own infrastructure with Anthropic models (directly, or via Amazon Bedrock, Google Vertex AI, or Microsoft Foundry), and need fine-grained tool, permission, and hook control Cursor SDK You want the Cursor agent (any model Cursor offers), your existing .cursor/config, and optionally Cursor Cloud Agents to run it remotelyHeadless CLI ( claude -p/agent -p)A one-off in a shell script or CI step is enough. It’s the simplest option -
Verify: The choice and the reason are written in
DECISIONS.md.
Step 3: Set up the project and credentials
Section titled “Step 3: Set up the project and credentials”-
Goal: A runnable skeleton that authenticates.
-
Do:
Terminal window npm init -ynpm pkg set type=module # the snippets use top-level await, which needs an ES modulenpm install -D tsx# Claude Agent SDK (TypeScript, Node >= 18)npm install @anthropic-ai/claude-agent-sdk# Python (3.10+): pip install claude-agent-sdk# Auth: set ANTHROPIC_API_KEY, or the Bedrock / Vertex AI / Foundry environment variables# Cursor SDK (TypeScript, Node >= 22.13)npm install @cursor/sdk# Python: pip install cursor-sdk# Auth: set CURSOR_API_KEY (create one under Cursor Dashboard → API Keys)The snippets and both SDK templates use top-level
await. In a default CommonJS project (whatnpm init -ycreates),npx tsxfails on it. Runnpm pkg set type=moduleas shown, or give the file an.mtsextension.Keep keys in environment variables or CI secrets. Never commit them.
-
Verify: A “hello” prompt runs and returns text.
Step 4: Write the minimal agent
Section titled “Step 4: Write the minimal agent”-
Goal: The smallest agent that does the job.
-
Do (Claude Agent SDK, TypeScript): see
templates/claude-sdk-agent.ts, or fill in the SDK agent builder and download a.tsfile. Save this aspr-summary.tsand runnpx tsx pr-summary.ts:import { query } from "@anthropic-ai/claude-agent-sdk";for await (const message of query({prompt: "Summarise the changes in `git diff origin/main...HEAD` into summary.md",options: {systemPrompt: "You are a release engineer. Be concise and factual.",tools: ["Read", "Grep", "Glob", "Bash", "Write"], // the only tools the agent hasallowedTools: ["Read", "Grep", "Glob", "Bash(git diff *)", "Write"], // run without askingpermissionMode: "dontAsk", // deny anything not in allowedToolssettingSources: [], // ignore ambient config, for reproducible CImaxTurns: 20,},})) {if (message.type === "result") console.log(message.subtype, message.total_cost_usd);}Why
dontAskand notacceptEdits: there’s no human to answer a permission prompt, sodontAskdenies anything that isn’t pre-approved.acceptEditsauto-approves edits to any file, plusrm,mv,cp, andsed, which is far more than a summary job needs.In CI, fetch the base branch first (for example
git fetch origin main), orgit diff origin/main...HEADhas nothing to compare against. -
Do (Cursor SDK, TypeScript): see
templates/cursor-sdk-agent.ts, or the Cursor file from the SDK agent builder. The flow is: create an agent, send a prompt, then stream or wait for the run. -
Verify: It runs locally against a real repo and produces the output.
Step 5: Restrict tools and permissions
Section titled “Step 5: Restrict tools and permissions”- Goal: Least privilege for unattended runs.
- Do:
-
Restrict the tool set. In the Claude Agent SDK,
allowedToolson its own only auto-approves the listed tools: every other tool stays available. A real restriction comes from:- the
toolsoption (the agent has only these tools); disallowedTools(these tools are removed);- or
allowedToolscombined withpermissionMode: "dontAsk"(anything not listed is denied).
Scope shell access to the commands the job needs, for example
Bash(git diff *). - the
-
Pick the least permissive permission mode that still works:
dontAskfor locked-down headless agents. AvoidacceptEditsfor unattended runs, and never bypass permissions except in a disposable sandbox. -
Run in a container or ephemeral CI runner with a scoped token (for example, a PR-comment-only GitHub token).
-
Add hooks to block dangerous commands if it has shell access.
-
- Verify: Try to make it do something outside its job (for example “delete the README”). It refuses or is blocked.
Step 6: Add tools and knowledge (optional)
Section titled “Step 6: Add tools and knowledge (optional)”- Goal: Give it the capabilities and procedures it needs.
- Do:
- MCP servers: pass them in the options (
mcpServers), and allow their tools, for exampleallowedTools: ["mcp__notes__*"]. Without that, the agent sees the tools but can’t call them. - Project config (Claude Agent SDK): when
settingSourcesis omitted, the SDK loads user, project, and local settings, the same as the CLI. That includes.claude/skills, agents,CLAUDE.md, and.mcp.json. PasssettingSources: []for reproducible CI, or["project"]to load only the repo’s config. Cursor local runtime: uselocal.settingSources. - Custom in-process tools (Claude Agent SDK): define them with
tool()+createSdkMcpServer(). This is useful for calling your app’s own functions. - Skills and subagents: load them from the project through setting sources, or define subagents inline with the
agentsoption (Claude Agent SDK).
- MCP servers: pass them in the options (
- Verify: The agent lists and uses the new tools on a test task.
Step 7: Handle output, errors, and budget
Section titled “Step 7: Handle output, errors, and budget”- Goal: Predictable behaviour in automation.
- Do:
-
Ask for structured output (JSON matching a schema, or a fixed Markdown template) and validate it in code.
-
Set
maxTurns, a cost ceiling, and a timeout, and log the cost per run. In the Claude Agent SDK, the cost ceiling ismaxBudgetUsdand the timeout is anabortControlleryou abort after a deadline:const abortController = new AbortController();const timer = setTimeout(() => abortController.abort(), 10 * 60_000); // 10 minutes// options: { ..., maxBudgetUsd: 1, abortController }// after the loop: clearTimeout(timer); -
Handle errors: an auth failure, a rate limit (retry with backoff), a max-turns or budget stop, or malformed output (retry once, then fail loudly). In the Cursor SDK, treat any run status other than
finished(includingcancelled) as a failure. -
Return a non-zero exit code when it fails, so CI notices. Use distinct codes for startup failures and run failures.
-
- Verify: Force each failure mode (a bad key,
maxTurns: 1, and malformed output) and confirm it’s handled cleanly.
Step 8: Test with golden tasks
Section titled “Step 8: Test with golden tasks”- Goal: Regression protection.
- Do: Build 5–10 fixed tasks with known good outcomes (for example, sample diffs with expected summary points). Run them on every change to the prompt, tools, or model, and assert on the results. See Testing & evaluation.
- Verify: The golden suite passes and is wired into CI.
Step 9: Deploy
Section titled “Step 9: Deploy”- Goal: It runs on its trigger without you.
- Do:
- CI: add a job that installs the SDK, sets the secret, and runs the script. Use
--output-format jsonfor CLI variants. - Scheduled: a cron job or scheduled workflow.
- Cursor Cloud Agents: run it on Cursor’s infrastructure with the SDK’s cloud runtime or the REST API.
- Add logging: the prompt version, model, turns, cost, and outcome.
- CI: add a job that installs the SDK, sets the secret, and runs the script. Use
- Verify: Trigger it for real (open a test PR). The output appears, and the logs are complete.
Step 10: Operate
Section titled “Step 10: Operate”- Goal: It stays healthy.
- Do: Monitor the failure rate and cost, re-run the golden tasks when models update, version the system prompt, and log changes in
DECISIONS.md. - Verify: There’s an owner, a dashboard or log query, and an alert on repeated failures.
Next: Design patterns · Checklist