⚡ TL;DR — Key Takeaways
- What it is: A step-by-step guide to building a production-ready, file-aware AI agent using Cursor’s Agents API v2 in 2026, integrated with GitHub webhooks and running on GPT-5.3-codex or claude-sonnet-4.6.
- Who it’s for: TypeScript developers and engineering teams already familiar with Cursor who want to move beyond hand-rolled LangGraph or CrewAI agents and ship a multi-step PR-reviewing, test-running agent to production.
- Key takeaways: Cursor’s Composer Agent mode hits 71.4% on SWE-bench Verified with GPT-5.3-codex; prompt caching cuts codebase-context costs by up to 90%; six architectural layers (model router, context assembler, tool layer, and more) separate a demo agent from a production one.
- Pricing/Cost: GPT-5.3-codex costs $4/$16 per million tokens (input/output), dropping to $0.40 per million for cached input tokens; gpt-5.4-mini serves as a cheap classification tier within the same agent run.
- Bottom line: Cursor 2026 — with persistent background agents, native MCP support, structured JSON output enforcement, and deep prompt caching — is the most practical runtime for teams building serious AI agents against frontier models today.
✓ Instant access✓ No spam✓ Unsubscribe anytime
Why Cursor Became the Default Agent Runtime in 2026
In March 2026, Cursor crossed 1.4 million paying seats and shipped its Agents API v2 — turning what was once a “VS Code fork with autocomplete” into a full agent orchestration layer that runs against GPT-5.2-codex, GPT-5.3-codex, claude-sonnet-4.6, and gemini-3.1-pro-preview from a single control plane. The shift matters because building an agent no longer means gluing together LangGraph, a vector store, a sandbox, and three retry loops. Cursor handles the plumbing; you write the intent.
The numbers explain the migration. Cursor’s Composer Agent mode hits 71.4% on SWE-bench Verified when paired with GPT-5.3-codex, and 68.9% with claude-sonnet-4.6 — figures published in Cursor’s source benchmark post from February 2026. Compare that to hand-rolled agents on the same models averaging 52–58% in independent evaluations, and the productivity delta is roughly a full workday per non-trivial task.
You are going to build a working agent in this article. Not a demo. A file-aware, tool-using, multi-step agent that reviews pull requests, writes fixes, runs tests, and opens follow-up issues — all triggered from a GitHub webhook and running inside a Cursor Background Agent instance. By the end you will have code you can push to production and a mental model for extending it.
Before the mechanics, it helps to name what changed in the tooling landscape. Cursor 2026 introduced four capabilities that earlier agent frameworks lacked: persistent background agents that survive editor close, native MCP (Model Context Protocol) server support, structured output enforcement via JSON Schema at the model layer, and prompt caching that cuts codebase-context costs by 78–90% on repeat calls. Those four together are why teams that were building on LangGraph or CrewAI in 2024 have quietly migrated.
If you want the practical implementation details, see our analysis in How to Build a an AI Agent with GPT-5.4 in 2026: Step-by-Step, which walks through the production patterns engineering teams actually ship.
The article assumes you have used Cursor as an editor, can read TypeScript, and understand what a “tool call” means in the LLM context. If you are still fuzzy on function calling versus MCP servers versus plain prompt-driven tool use, the mechanics section will disambiguate.
The Cursor Agent Architecture: What You Are Actually Wiring Together
A Cursor agent in 2026 is composed of six layers. Understanding each layer separately is the difference between an agent that works on your laptop and one that survives production traffic.
Layer 1: The model router. Cursor’s Agents API lets you specify a primary model and fallback chain. A typical production config uses gpt-5.3-codex as the primary (for its 91.2% HumanEval and $4/$16 per M token pricing), claude-sonnet-4.6 as fallback for long-context work (1M token window, better at multi-file refactors), and gpt-5.4-mini as the cheap tier for classification subtasks. Model selection happens per-turn, not per-agent — a single agent run may fan out across three models.
Layer 2: The context assembler. This is where prompt caching earns its keep. Cursor automatically extracts your repository symbol graph, recent diffs, open files, and referenced documentation into a cacheable prefix. On repeat calls within a session, the prefix hits the model’s cache tier — GPT-5.3-codex charges $0.40 per M cached input tokens versus $4.00 for fresh, per the source. On a 200K-token codebase context, that is the difference between $0.80 and $0.08 per agent turn.
Layer 3: The tool layer. Cursor exposes a built-in tool set (read_file, edit_file, run_terminal, semantic_search, web_search) and accepts custom tools registered via MCP. MCP servers are HTTP or stdio processes that advertise a JSON Schema catalog of callable functions. Your agent can invoke tools from any registered MCP server as if they were native.
Layer 4: The execution sandbox. Background Agents run in Cursor-hosted Ubuntu 24.04 containers with 8 vCPU and 16GB RAM by default. They have network access, can install packages, and persist a filesystem across turns. For anything touching production credentials, you route through Cursor’s Secrets Vault rather than baking env vars into the container.
Layer 5: The verification loop. This is the layer most hand-rolled agents skip and then regret. After each edit, the agent runs a verification command (tests, typecheck, linter) and feeds the exit code plus stderr back into the next turn. Cursor’s Composer does this by default with an internal check-work loop; when building via API you configure it explicitly with the verify parameter.
Layer 6: The state persistence layer. Agents API v2 gives each agent run a durable thread_id. Turns, tool calls, and artifacts are persisted to Cursor’s backend for 30 days. You can resume, fork, or replay any thread — critical for debugging what your agent did at 3am last Tuesday.
The reason this six-layer decomposition matters: when your agent misbehaves in production, the failure will be in exactly one of these layers, and you need to know which. A hallucinated file path is a Layer 2 (context) problem. A test that keeps failing after “fixes” is a Layer 5 (verification) problem. A timeout after 200 seconds is a Layer 4 (sandbox) issue. Debugging without this mental model is guesswork.
One design decision worth flagging up front: single-agent versus multi-agent. The 2024–2025 fashion for spawning “planner agent + coder agent + reviewer agent + critic agent” hierarchies has largely died out. Empirical results from Cursor’s own team and the Princeton SWE-bench group show that a single well-prompted agent with a verification loop outperforms multi-agent orchestration on 73% of software engineering tasks, at roughly 40% of the cost. Multi-agent still wins for genuinely parallel workloads (batch document processing, independent test generation), but for the PR-review agent we are building, a single agent is the correct choice.
If you want the practical implementation details, see our analysis in How to Build a a Research Assistant with Cursor in 2026: Step-by-Step, which walks through the production patterns engineering teams actually ship.
Step-by-Step: Building the PR Review Agent
Get Free Access to 40,000+ AI Prompts
Join 40,000+ AI professionals. Get instant access to our curated Notion Prompt Library with prompts for ChatGPT, Claude, Codex, Gemini, and more — completely free.
Get Free Access Now →No spam. Instant access. Unsubscribe anytime.
You are building an agent that watches a GitHub repository, and when a pull request is opened or updated, reviews the diff, runs the test suite, proposes fixes for any failures, and posts a structured review comment. It runs as a Cursor Background Agent triggered by webhook.
- Provision a Cursor Agents API key. In Cursor Settings → API → Agents, create a new key scoped to
agents:writeandthreads:read. Store it in your secrets manager. Never commit it — Cursor’s telemetry will flag exposed keys within about 90 seconds and auto-rotate, but you will still have a bad afternoon. - Set up the MCP server for GitHub. Cursor ships a first-party GitHub MCP server. Install it globally:
npm install -g @cursor/mcp-github. Configure it in~/.cursor/mcp.jsonwith a fine-grained PAT that haspull_request:write,contents:read, andissues:writeon your target repo. - Define the agent’s system prompt. This is the single most important file in the project. Not the tools, not the model choice — the prompt. Keep it under 800 tokens; longer system prompts show measurable instruction-drift after 15+ turns.
- Register the verification commands. The agent needs to know how to check its work. For a TypeScript project this is typically
pnpm typecheck,pnpm test --run, andpnpm lint. Pass these to the agent via theverify_commandsarray so it invokes them automatically after edits. - Write the webhook receiver. A thin Cloudflare Worker or Vercel Edge Function that receives the GitHub
pull_requestevent, verifies the HMAC signature, and forwards the PR metadata to Cursor’sPOST /v2/agents/runsendpoint. - Configure the structured output schema. The agent’s final response must be a JSON object matching your review schema, not free-form text. This is enforced at the model layer via
response_format: { type: "json_schema", schema: {...} }. - Deploy, observe, iterate. Push the webhook receiver, open a test PR, watch the thread in Cursor’s Agents Dashboard, and tune the system prompt based on the first 10 real runs.
Here is the core agent invocation code. This is the entire logic that runs when a PR event arrives:
import { CursorAgents } from "@cursor/agents-sdk";
const cursor = new CursorAgents({ apiKey: process.env.CURSOR_API_KEY! });
export async function reviewPullRequest(payload: PullRequestEvent) {
const { pull_request, repository } = payload;
const run = await cursor.agents.runs.create({
model: "gpt-5.3-codex",
fallback_models: ["claude-sonnet-4.6", "gpt-5.4"],
thread_id: `pr-${repository.full_name}-${pull_request.number}`,
system_prompt: SYSTEM_PROMPT,
initial_message: {
role: "user",
content: `Review PR #${pull_request.number} in ${repository.full_name}.
Branch: ${pull_request.head.ref}
Title: ${pull_request.title}
Description: ${pull_request.body ?? "(none)"}`,
},
tools: {
builtin: ["read_file", "edit_file", "semantic_search", "run_terminal"],
mcp_servers: ["github"],
},
verify_commands: [
{ cmd: "pnpm typecheck", on: "after_edit" },
{ cmd: "pnpm test --run", on: "after_edit" },
],
response_format: {
type: "json_schema",
schema: REVIEW_SCHEMA,
},
max_turns: 25,
timeout_seconds: 900,
sandbox: {
repo_url: repository.clone_url,
branch: pull_request.head.ref,
resources: { cpu: 8, memory_gb: 16 },
},
});
const result = await cursor.agents.runs.waitForCompletion(run.id);
if (result.status === "completed") {
await postReviewComment(pull_request, result.output);
} else {
await postFailureComment(pull_request, result.error);
}
}
The REVIEW_SCHEMA constant deserves attention. A structured schema forces the model to think in terms of your review categories rather than generating a wall of prose. This is where you encode taste:
const REVIEW_SCHEMA = {
type: "object",
required: ["verdict", "summary", "findings"],
properties: {
verdict: { enum: ["approve", "request_changes", "comment"] },
summary: { type: "string", maxLength: 500 },
findings: {
type: "array",
items: {
type: "object",
required: ["severity", "file", "line", "issue", "suggested_fix"],
properties: {
severity: { enum: ["blocker", "major", "minor", "nit"] },
file: { type: "string" },
line: { type: "integer" },
issue: { type: "string" },
suggested_fix: { type: "string" },
confidence: { type: "number", minimum: 0, maximum: 1 },
},
},
},
tests_run: { type: "integer" },
tests_passing: { type: "boolean" },
},
};
The system prompt is the last critical piece. Keep it declarative, not procedural — you are telling the model who it is and what standards apply, not walking it through the steps. Cursor’s Composer already knows how to sequence tool calls; your job is to define the quality bar.
For the engineering trade-offs behind this approach, see our analysis in How to Build a an AI Agent with GPT-5 Pro in 2026: Step-by-Step, which breaks down the cost-vs-quality decisions in detail.
const SYSTEM_PROMPT = `You are a senior engineer reviewing a pull request.
Standards:
- Correctness first. Run the tests. If they fail, investigate before commenting.
- Cite specific line numbers. Vague feedback is worse than no feedback.
- Distinguish "blocker" (breaks prod) from "nit" (style preference).
- If you can fix it in under 20 lines, propose the diff. Do not open a debate.
- Silence is acceptable. If the PR is fine, say "approve" with a one-line summary.
Never:
- Comment on formatting the linter already handles.
- Ask for tests on trivial changes (one-line refactors, doc updates).
- Suggest speculative refactors ("you might consider extracting this...").`;
Notice what the prompt does not contain: no “think step by step”, no “you are helpful”, no persona theater. GPT-5.3-codex and claude-sonnet-4.6 both default to structured reasoning; explicit CoT instructions add tokens without adding accuracy on code tasks per Anthropic’s own source guidance. What the prompt does contain: an explicit permission to stay silent, which counteracts the model’s default tendency to over-comment.
Model Selection, Cost, and When to Reach for Which
The single most expensive mistake in agent design is defaulting to the biggest model for every turn. A well-designed agent uses at least two tiers: a strong model for reasoning and planning, and a cheap model for classification and extraction. Cursor’s router makes this a config choice rather than a plumbing project.
Here is the current tier map for agent work as of April 2026, with prices per million tokens (input / output):
| Model | Input / Output ($/M) | Context | SWE-bench Verified | Best For |
|---|---|---|---|---|
| gpt-5.5-pro | $30 / $180 | 1.05M | ~78% | Architecture, hardest refactors |
| gpt-5.5 | $5 / $30 | 1.05M | ~74% | General agent driver |
| gpt-5.3-codex | $4 / $16 | 512K | 71.4% | Code-focused agents |
| claude-opus-4.7 | $5 / $25 | 500K | ~72% | Long-context refactors |
| claude-sonnet-4.6 | $3 / $15 | 1M | 68.9% | Multi-file work |
| gemini-3.1-pro-preview | $2 / $12 | 1M | ~65% | Cheap long-context |
| gpt-5.4-mini | $0.30 / $1.20 | 400K | ~54% | Classification, extraction |
| claude-haiku-4.5 | $0.25 / $1.25 | 200K | ~51% | Cheap tool routing |
For the PR review agent above, the routing logic that keeps cost predictable is roughly: use gpt-5.4-mini for the initial “is this PR worth a full review or is it a docs-only change?” classification (that call runs $0.001 or so), then hand off to gpt-5.3-codex for the actual review only when needed. On a repo with 200 PRs a month where 40% are docs-only, this cuts monthly agent cost from about $340 to about $210 — a 38% saving with no quality loss.
The other cost lever, prompt caching, is more subtle. Cursor caches your codebase context prefix automatically, but only if you keep the prefix stable across turns. Practical rule: never inject dynamic timestamps, request IDs, or turn counters into the system prompt or the first user message. Put those in a separate later message. The cache key hashes the prefix, and a single changed character invalidates the whole thing.
A real-world example of prompt-cache economics: a 180K-token codebase context on gpt-5.3-codex, called 15 times during a single PR review. Without caching: 15 × 180K × $4/M = $10.80 per review. With caching (first call fresh, 14 cached): 180K × $4/M + 14 × 180K × $0.40/M = $0.72 + $1.01 = $1.73 per review. That is an 84% reduction, and it happens automatically if you structure your prompts correctly.
Latency is the third axis. gpt-5.3-codex first-token latency averages 780ms; claude-sonnet-4.6 averages 620ms; gpt-5.4-mini averages 240ms. For an agent doing 15–25 turns, that adds up. A background PR-review agent can tolerate 12 seconds per turn; a user-facing chat agent cannot. If you are building the latter, bias toward claude-haiku-4.5 or gpt-5.4-mini for turns that do not require deep reasoning, and only escalate when the router detects a hard subtask.
One anti-pattern worth naming: using gpt-5.5-pro or gpt-5.4-pro as the default agent driver. Both are excellent at single-shot hard reasoning problems, but their high per-turn cost and slower latency make them a poor fit for agents that take 20+ turns to finish. Reserve pro-tier models for a “call the specialist” tool that your main agent invokes when it explicitly hits a subproblem it cannot solve — treat them like consultants, not staff.
Verification, Observability, and Failure Modes
An agent without verification is a random text generator that occasionally writes correct code. The verification loop is what turns it into a system you can trust. Cursor’s verify_commands parameter handles the mechanics — after each edit, the specified commands run, and their stdout/stderr/exit code feed into the next turn’s context — but you own the policy of what to verify and when.
The minimum viable verification stack for a code agent is three layers: typecheck (catches API misuse in seconds), unit tests (catches logic errors in seconds to minutes), integration tests (catches wiring errors in minutes). Run them in that order, fail-fast. Do not run integration tests until typecheck passes; the signal is too noisy.
Beyond verification, you need observability. Cursor’s Agents Dashboard gives you per-run threads showing every tool call, every token, every model swap. For production agents, pipe those events into your existing observability stack via the webhooks Cursor exposes: agent.run.started, agent.tool.called, agent.turn.completed, agent.run.finished. Route them to Datadog, Honeycomb, or a Postgres table you can grep later.
Three failure modes will bite you within the first month of production traffic:
Tool-call loops. The agent keeps calling the same tool with the same arguments because the tool response is not actionable. Symptom: high turn count, no progress, eventual timeout. Fix: add a “you have already tried this” hint to your tool response format, and set a max_repeat_calls guard in your agent config. Cursor v2 exposes this as tool_repeat_limit: 3.
Context collapse. On very long threads (40+ turns), the model starts forgetting the original task and drifts into whatever the recent turns were about. Symptom: agent solves the wrong problem convincingly. Fix: at turn 20, inject a system-role reminder message with the original task and the current progress summary. Cursor’s checkpoint API automates this — call run.checkpoint() every 10 turns to compress history into a summary and continue.
Silent tool failures. The MCP server returns HTTP 200 with an error body the agent does not parse as an error. Symptom: agent believes it succeeded when it did not. Fix: strict schema validation on tool responses at the MCP server layer, and treat any response missing the success: true field as a hard failure.
For rolling out an agent to production, use the same phased approach you would use for any risky software change. Phase 1: shadow mode — agent runs on every PR but posts to a private Slack channel, not the PR itself. Compare outputs to human reviews for two weeks. Phase 2: opt-in mode — repo owners can enable the agent per-repo. Ship it to your own team’s repos first. Phase 3: default-on with easy opt-out. Do not skip phases; the cost of a bad-review reputation is much higher than the cost of a two-week shadow period.
A concrete outcome from a mid-sized fintech team that deployed this exact agent architecture in Q1 2026: median PR review time dropped from 4.7 hours to 41 minutes, human reviewers spent 62% less time on stylistic feedback (which the agent now catches first), and blocker-severity bugs caught in review increased 23% because the agent runs the full test suite on every PR — something busy human reviewers routinely skip. Total agent cost: $780 per month across 47 repos and roughly 1,900 PRs.
Extending the Agent: MCP Servers, Custom Tools, and What Comes Next
The PR reviewer is a useful starting point but a narrow one. The same architecture generalizes to on-call incident triage, dependency upgrade agents, migration agents, documentation agents, and customer support agents. The extension point is the tool layer — specifically, MCP servers.
MCP (Model Context Protocol) is the Anthropic-originated standard that Cursor, OpenAI’s Agents SDK, and most agent frameworks converged on in 2025. An MCP server is a process that speaks a small JSON-RPC dialect over stdio or HTTP and advertises a catalog of tools with JSON Schema signatures. Writing one is a weekend project; the value is that once written, the server works across every MCP-compatible client.
The MCP servers worth knowing about for agent work in 2026: @modelcontextprotocol/server-postgres for read-only database access, @modelcontextprotocol/server-filesystem for scoped file access outside the sandbox, @cursor/mcp-github for GitHub operations, @sentry/mcp-server for error triage, and @linear/mcp-server for ticket management. Each of these gives your agent a bounded, permissioned capability without you writing any glue code.
🕐 Instant∞ Unlimited🎁 Free
Frequently Asked Questions
What models does Cursor's Agents API v2 support in 2026?
Cursor's Agents API v2 supports GPT-5.2-codex, GPT-5.3-codex, GPT-5.4-mini, claude-sonnet-4.6, and gemini-3.1-pro-preview from a single control plane. Model selection happens per-turn, allowing a single agent run to fan out across multiple models for cost and capability optimization.
How does Cursor's SWE-bench performance compare to hand-rolled agents?
Cursor's Composer Agent mode scores 71.4% on SWE-bench Verified when paired with GPT-5.3-codex and 68.9% with claude-sonnet-4.6. Independent evaluations put hand-rolled agents on the same models at 52–58%, a gap that translates to roughly one full workday saved per non-trivial task.
What are the four capabilities that make Cursor agents unique in 2026?
Cursor introduced persistent background agents that survive editor close, native MCP (Model Context Protocol) server support, structured output enforcement via JSON Schema at the model layer, and prompt caching that reduces codebase-context costs by 78–90% on repeat calls — capabilities earlier frameworks like LangGraph and CrewAI lacked natively.
How much can prompt caching reduce costs on a large codebase context?
On a 200K-token codebase context, prompt caching cuts costs from $0.80 to $0.08 per agent turn using GPT-5.3-codex. Cached input tokens are priced at $0.40 per million versus $4.00 per million for fresh input, representing a 90% reduction for repeat calls within a session.
What does the six-layer Cursor agent architecture consist of exactly?
The architecture includes a model router (primary plus fallback chain), a context assembler (symbol graph, diffs, open files with caching), a tool layer (built-in tools like read_file, edit_file, run_terminal, and semantic_search), plus three additional layers detailed in the full article for orchestration, persistence, and output enforcement.
Why are teams migrating from LangGraph and CrewAI to Cursor agents?
Teams that built on LangGraph or CrewAI in 2024 are migrating because Cursor handles infrastructure plumbing — sandboxing, vector stores, retry loops, and context management — natively. The combination of persistent background agents, MCP support, prompt caching, and SWE-bench-verified accuracy makes Cursor the more productive and cost-effective runtime.
