cursor-sdk-agent.ts
File: cursor-sdk-agent.ts. Copy it with the button on the code block, or download it with the agent templates: agents-templates.zip.
/** * Cursor SDK agent 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 @cursor/sdk (Node >= 22.13) * Auth: CURSOR_API_KEY (create one under Cursor Dashboard → API Keys, or use a team service account) * Run: git fetch origin main && npx tsx cursor-sdk-agent.ts * (in CI, fetch the base branch first or the diff has nothing to compare against) * * Exit codes: 0 = finished, 1 = agent never started (auth, config or network), * 2 = run did not finish (error or cancelled), 3 = error after the run started. */import { Agent, CursorAgentError } from "@cursor/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.`;
async function main(): Promise<number> { if (!process.env.CURSOR_API_KEY) { console.error("CURSOR_API_KEY is not set"); return 1; }
let started = false; try { await using agent = await Agent.create({ apiKey: process.env.CURSOR_API_KEY, model: { id: "composer-2.5" }, local: { cwd: process.cwd() }, // set explicitly; use `cloud: { repos: [...] }` for Cloud Agents });
const run = await agent.send(PROMPT); started = true; console.error(`agent=${agent.agentId} run=${run.id}`);
for await (const event of run.stream()) { if (event.type === "assistant") { for (const block of event.message.content) { if (block.type === "text") process.stdout.write(block.text); } } }
const result = await run.wait(); if (result.status !== "finished") { console.error(`run ${result.id} ended with status=${result.status}: ${result.error?.message ?? "no details"}`); return 2; } return 0; } catch (err) { if (err instanceof CursorAgentError) { const phase = started ? "run" : "startup"; console.error(`${phase} failed: ${err.message} (retryable=${err.isRetryable})`); return started ? 3 : 1; } throw err; }}
process.exit(await main());