Skip to content

AIExplore

How to Use Cursor Agent to Build and Refactor Code

Use Cursor Agent for features, refactors, and bug fixes by stating outcomes, scoping files with @ references, reviewing diffs as edits land, and verifying with tests before you merge.

Cursor Agent is the mode that edits your repository. You describe what should exist, Agent searches the codebase, changes files, runs terminal commands when your settings allow, and shows each edit in the diff view as it works. Most disappointing Agent sessions are not model failures. They are brief failures: vague goals, no file scope, no definition of done, and diffs accepted without reading.

This guide walks through a practical Agent workflow for new features, refactors, and targeted fixes. For choosing Ask, Plan, or Debug instead, see /blog/cursor-ask-vs-agent-vs-plan-which-mode-should-you-use. For the full Explore summary, see /explore/cursor.

When Agent is the right mode

Use Agent when you want files changed, tests run, or shell commands executed in the project you have open. Use Ask when you only need explanation. Use Plan when the change is large and you want a written plan before code lands. Use Debug when you have a reproduction but need runtime evidence. Agent is the default for shipping work.

The Agent workflow

A reliable session follows six steps. First, state the outcome and how you will verify it. Second, attach @ references when you already know which files matter. Third, let Agent explore and edit while you watch the diff view. Fourth, reject hunks you do not understand before Agent builds on them. Fifth, ask Agent to run the test or lint command you named. Sixth, review scope before you commit. Skipping the review step is how drive by refactors reach production.

Open Agent and write a ticket style prompt

Press Cmd+I on Mac or Ctrl+I on Windows or Linux. Lead with behavior, not library guesses. Say what the user should see, what the API should return, or which test must pass when the work is complete.

Weak prompt

Add dark mode to the app.

Strong Agent prompt

Goal: Add a dark mode toggle on the settings page.
Stack: Next.js App Router, TypeScript, existing Switch component.
Done when: toggle persists in localStorage and settings.test.tsx passes.
Scope: src/app/settings/ and src/components/ui/switch.tsx only.
Do not: change global CSS variables outside settings.

The strong version gives Agent a finish line. Agent can stop when the test passes instead of guessing when you are satisfied.

Scope with @ references

Agent searches automatically, but @ attachments save time when you know the locus. Attach the file under change, one reference file that shows the pattern to copy, and any doc that defines conventions.

@src/features/reports/ReportsTable.tsx @src/features/billing/BillingTable.tsx
Add CSV export to BillingTable using the same export action pattern as ReportsTable.
Done when: billing table test covers export and only src/features/billing/* changes.

More detail on @ mentions and rules lives in /blog/how-to-give-cursor-better-context-with-mentions-and-rules.

Example: fix a bug with evidence

@src/components/ContactForm.tsx
Goal: Stop double submit on mobile Safari.
Reproduce: open /contact, fill fields, tap submit once.
Expected: one POST to /api/contact.
Actual: two POSTs and duplicate rows.
Done when: npm test -- --testPathPattern=ContactForm passes.
Do not add dependencies.

Example: refactor with explicit non goals

Refactors go wrong when Agent cleans up adjacent code you never asked to touch. Name the extraction target and what must stay identical.

Refactor: extract shared validation from
src/components/checkout-form.tsx and src/app/api/checkout/route.ts
into src/lib/checkout-validation.ts.

Keep: public function signatures and HTTP response shapes unchanged.
Verify: npm test -- --testPathPattern=checkout
First: list files you will touch. Then implement.

Example: small API change with a reference route

@src/app/api/products/route.ts @src/app/api/orders/route.ts
Add GET /api/invoices with cursor pagination matching the orders route pattern.
Response: { items, nextCursor } with 20 items per page.
Only modify src/app/api/invoices/ and its test.
Run npm test -- --testPathPattern=invoices after edits.

Review diffs and checkpoints while Agent works

Agent applies edits continuously. Treat the diff view like a live code review. Reject hunks that change formatting, rename symbols broadly, or touch files outside scope. Hover an earlier message and choose Restore Checkpoint to roll back everything after that point. You can queue the next instruction while Agent is busy; it runs when the current task finishes.

Click Stop when Agent drifts into unrelated refactors or starts editing files you did not list. Stopping early is cheaper than untangling a messy branch. After Stop, restate scope in a shorter prompt or switch to Ask if you still need orientation.

Example: explain first, implement second

For billing, auth, or migration code, ask Agent to explain the existing path before it edits. You can do this in Ask mode first, or instruct Agent to plan in bullets without writing code until you confirm.

@src/lib/billing/retry.ts
Phase 1: explain triggers, retry count, and failure side effects in bullets.
Phase 2: after I confirm, add idempotency keyed by invoiceId with minimal diff.
Do not edit until Phase 1 is approved.

Example: scaffold a module with tests

Stack: Node 20, TypeScript, Express.
Goal: create src/notifications/ module with sendEmail wrapper.
Constraints: no new dependencies; follow src/lib/logger.ts patterns.
Done when: npm test -- --testPathPattern=notifications passes.
Files allowed: src/notifications/* only.

Subagents and parallel exploration

Agent can delegate research or shell work to subagents defined in .cursor/agents/ or use built in subagent behavior for parallel exploration. You still review the combined diff. For very large repos, narrow scope with @ folders so subagents do not wander.

Working in large monorepos

Name the package or app directory first. Attach @packages/billing/ instead of the whole tree. State which shared libraries may change and which are read only reference. Monorepo prompts fail when Agent assumes the wrong app owns a route or config file.

@packages/web/app/settings/page.tsx @packages/shared/ui/Switch.tsx
Implement settings dark mode toggle for the web app only.
Do not edit packages/mobile/ or packages/admin/.
Done when: pnpm --filter web test -- settings passes.

Terminal commands and verification

Agent can run tests and lint when your approval settings allow. Put the command in the same prompt as the implementation. See /blog/how-to-test-and-verify-changes-made-by-cursor for a full verification workflow.

Implement the null guard in src/lib/parseConfig.ts.
Then run npm test -- --testPathPattern=parseConfig.
If tests fail, paste output and fix only what is required.
Do not commit.

When to switch out of Agent

  • You need a map of the codebase before editing: switch to Ask
  • The feature spans many systems and requirements are unclear: switch to Plan
  • You can reproduce the bug but static reading fails: switch to Debug
  • You only need inline completion while typing: use Tab, not Agent

Common mistakes

  • Asking Agent to improve the whole app with no acceptance criteria
  • Accepting large diffs because the main feature mostly works
  • Mixing unrelated tasks in one Agent chat so context gets noisy
  • Naming libraries instead of describing behavior you need
  • Skipping test commands when the repo already has coverage

Safety checks before merge

  • Every changed file was in scope or you can justify the expansion
  • You can explain each hunk to a teammate
  • Tests and lint you trust are green
  • No secrets, tokens, or debug logging left in the patch

Usage limits and long sessions

Usage limits and long sessions

Individual plans include usage pools for Cursor Models and third party models that reset monthly per Cursor docs. Long Agent sessions with large context can consume included usage faster. Check cursor.com/dashboard/usage before you kick off many parallel tasks. Hobby tier includes limited Agent requests compared with Pro and higher tiers.

Images and assets from Agent

Agent can generate images for mockups or diagrams when you ask. Review generated assets like code diffs before commit. Prefer referencing existing design files with @ when brand assets already live in the repo.

Related: /blog/how-to-test-and-verify-changes-made-by-cursor, /blog/how-to-debug-code-with-cursor, and /blog/cursor-ask-vs-agent-vs-plan-which-mode-should-you-use.

Related articles