examples/mcp-server-example.md
# MCP Server Example
A minimal TypeScript MCP server that Cursor can invoke, with the corresponding `mcp.json` entry.
## Server code (`scripts/my-mcp-server.ts`)
```typescript
#!/usr/bin/env node
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import { readFileSync } from "fs";
const server = new Server(
{ name: "project-tools", version: "1.0.0" },
{ capabilities: { tools: {} } }
);
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [
{
name: "read-env-summary",
description: "Returns a summary of the project's environment variables from .env.example.",
inputSchema: {
type: "object",
properties: {},
required: [],
},
},
{
name: "check-dependency",
description: "Checks if a npm package is listed in package.json.",
inputSchema: {
type: "object",
properties: {
packageName: {
type: "string",
description: "The npm package name to check.",
},
},
required: ["packageName"],
},
},
],
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
const { name, arguments: args } = request.params;
if (name === "read-env-summary") {
try {
const content = readFileSync(".env.example", "utf-8");
const keys = content
.split("\n")
.filter((l) => l.trim() && !l.startsWith("#"))
.map((l) => l.split("=")[0].trim());
return {
content: [
{
type: "text",
text: `Found ${keys.length} env vars: ${keys.join(", ")}`,
},
],
};
} catch {
return { content: [{ type: "text", text: ".env.example not found." }] };
}
}
if (name === "check-dependency") {
const { packageName } = args as { packageName: string };
try {
const pkg = JSON.parse(readFileSync("package.json", "utf-8"));
const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
const found = packageName in allDeps;
return {
content: [
{
type: "text",
text: found
? `${packageName} is installed (${allDeps[packageName]}).`
: `${packageName} is NOT in package.json.`,
},
],
};
} catch {
return { content: [{ type: "text", text: "Could not read package.json." }] };
}
}
return {
content: [{ type: "text", text: `Unknown tool: ${name}` }],
isError: true,
};
});
const transport = new StdioServerTransport();
await server.connect(transport);
```
## `.cursor/mcp.json` entry
```json
{
"mcpServers": {
"project-tools": {
"command": "npx",
"args": ["tsx", "${workspaceFolder}/scripts/my-mcp-server.ts"],
"env": {}
}
}
}
```
Or if compiled to JS:
```json
{
"mcpServers": {
"project-tools": {
"command": "node",
"args": ["${workspaceFolder}/scripts/my-mcp-server.js"]
}
}
}
```
## Install dependencies
```bash
pnpm add -D @modelcontextprotocol/sdk tsx
```
## Testing
After saving `mcp.json`, restart Cursor. In the agent panel, ask: "Use the `read-env-summary` tool." Cursor will call the tool and display the result.
Check Output > "Cursor MCP" for server logs and errors.
examples/rule-file-examples.md
# Rule File Examples
Worked `.mdc` examples for common scenarios.
## 1. Always-apply: coding standards
```mdc
---
alwaysApply: true
---
# Coding Standards
- No em dashes (`—`) or en dashes (`–`) in any prose. Use hyphens, colons, parentheses, or periods instead.
- All exported functions must have JSDoc with `@param` and `@returns`.
- Maximum file length: 400 lines. Split if exceeded.
```
**When to use:** organisation-wide conventions that apply to every file in every context. Keep this under 150 tokens; it burns budget on every invocation.
## 2. Glob-scoped: React component conventions
```mdc
---
description: React component best practices for this project.
globs: "**/*.tsx, **/*.jsx"
alwaysApply: false
---
# React Component Rules
- Use function components only. No class components.
- Name components with PascalCase. Files match the component name.
- One component per file. Exceptions: small co-located helpers under 20 lines.
- Use `shadcn/ui` primitives before reaching for raw HTML elements.
- Props interfaces: always explicitly typed with TypeScript. No implicit `any`.
```
**When to use:** language or framework-specific rules. Fires only when a `.tsx` or `.jsx` file is in context.
## 3. Apply intelligently: database query reviewer
```mdc
---
description: Apply when writing or reviewing database queries, ORM calls, Prisma schema, or SQL migrations.
alwaysApply: false
---
# Database Query Rules
- Always use parameterised queries. Never string-concatenate user input into SQL.
- Prisma: prefer `select` to limit returned fields; never return the full model when only one field is needed.
- Migrations: expand-backfill-contract. Never drop columns in the same migration that removes the code reading them.
- Add an index for every foreign key and every column used in a `WHERE` clause on large tables.
```
**When to use:** context-dependent concerns where the AI can reliably decide relevance from the `description`.
## 4. Apply manually: security audit checklist
```mdc
---
description: Security audit checklist. Mention this rule when conducting a security review.
alwaysApply: false
---
# Security Audit Checklist
1. Input validation: all user inputs validated with Zod or equivalent before use.
2. Authentication: all routes behind authentication middleware. No unauthenticated endpoints except explicit public ones.
3. Secrets: no secrets in source code or git history. All credentials in env vars.
4. SQL injection: parameterised queries everywhere.
5. XSS: user-supplied content escaped before rendering. `dangerouslySetInnerHTML` forbidden.
6. CSRF: state-changing endpoints protected by CSRF token or SameSite cookie.
```
**When to use:** reference material that is only relevant during specific workflows. `@security-audit-checklist` in chat to load it on demand.
## 5. Migration: from `.cursorrules`
**Before (`.cursorrules`):**
```
Always use TypeScript strict mode.
Never use `any` type.
Prefer functional patterns over imperative.
Use pnpm, never npm or yarn.
```
**After (`.cursor/rules/typescript-standards.mdc`):**
```mdc
---
description: TypeScript project standards.
globs: "**/*.ts, **/*.tsx"
alwaysApply: false
---
# TypeScript Standards
- Strict mode enabled in `tsconfig.json`. No exceptions.
- Never use `any`. Use `unknown` + type guard, or a specific type.
- Prefer functional patterns: `map`/`filter`/`reduce` over imperative loops for transformations.
- Package manager: `pnpm` only. Never `npm install` or `yarn add`.
```
**After (`.cursor/rules/tooling.mdc`):**
```mdc
---
alwaysApply: true
---
# Tooling
Always use `pnpm` for all package operations. Never `npm` or `yarn`.
```
The `.cursorrules` content is split into two files: a glob-scoped TypeScript file for code conventions, and a tiny always-apply file for the critical tooling directive.
examples/sdk-agent-example.md
# SDK Agent Example
Complete `@cursor/sdk` pattern: create, stream, error-handle, dispose.
## Installation
```bash
npm install @cursor/sdk
# or
pnpm add @cursor/sdk
```
## Full example (`scripts/run-review.ts`)
```typescript
import {
Agent,
CursorAgentError,
AgentBusyError,
RateLimitError,
} from "@cursor/sdk";
import * as path from "path";
const PROJECT_ROOT = path.resolve(__dirname, "..");
const REVIEW_PROMPT = `
Review the staged changes in this repository for:
1. Security issues (OWASP Top 10)
2. Performance anti-patterns
3. Missing error handling
Output a markdown report with findings grouped by severity: Critical, High, Medium, Low.
`;
async function runReview(): Promise<void> {
let agent: Awaited<ReturnType<typeof Agent.create>> | null = null;
try {
agent = await Agent.create({
local: {
cwd: PROJECT_ROOT,
model: "claude-sonnet-4-5",
settingSources: ["user", "project"],
},
});
console.log("Agent created. Starting review...\n");
const run = agent.send(REVIEW_PROMPT);
// Stream output in real time
let reportBuffer = "";
for await (const msg of run.stream()) {
switch (msg.type) {
case "assistant":
process.stdout.write(msg.text ?? "");
reportBuffer += msg.text ?? "";
break;
case "tool_call":
if (msg.status === "running") {
process.stderr.write(`\n[tool: ${msg.name} running...]\n`);
} else {
process.stderr.write(`[tool: ${msg.name} done]\n`);
}
break;
case "status":
process.stderr.write(`\n[status: ${msg.text}]\n`);
break;
}
}
const result = await run.wait();
console.log(`\n\nReview complete. Status: ${result.status}`);
// Write report to disk
const { writeFileSync } = await import("fs");
writeFileSync("review-report.md", reportBuffer, "utf-8");
console.log("Report written to review-report.md");
} catch (err) {
if (err instanceof AgentBusyError) {
// Cloud agent: one run at a time
console.error("Agent is busy. Wait for the current run to finish.");
} else if (err instanceof RateLimitError) {
// Transient — back off and retry
console.error("Rate limited. Retry after 60 seconds.");
} else if (err instanceof CursorAgentError) {
console.error(`Cursor error [${err.code}]: ${err.message}`);
console.error(`Retryable: ${err.isRetryable}`);
} else {
throw err; // unexpected — rethrow
}
} finally {
if (agent) {
await agent.dispose();
}
}
}
runReview().catch(console.error);
```
## Run it
```bash
npx tsx scripts/run-review.ts
```
## Variant: one-shot with `Agent.prompt`
For simple fire-and-forget automations:
```typescript
import { Agent, CursorAgentError } from "@cursor/sdk";
try {
const result = await Agent.prompt(
"Add JSDoc comments to all exported functions in src/utils.ts",
{
local: {
cwd: process.cwd(),
model: "claude-sonnet-4-5",
},
}
);
console.log("Done:", result.status);
} catch (err) {
if (err instanceof CursorAgentError) {
console.error(`[${err.code}] ${err.message}`);
}
}
```
## Variant: resume across processes
```typescript
import { Agent } from "@cursor/sdk";
import { writeFileSync, readFileSync } from "fs";
// First process: create and save agentId
const agent = await Agent.create({ local: { cwd: process.cwd(), model: "..." } });
writeFileSync(".agent-id", agent.id);
const run = agent.send("Start the migration...");
await run.wait();
// process exits
// Second process: resume
const agentId = readFileSync(".agent-id", "utf-8").trim();
const resumedAgent = await Agent.resume(agentId, {
local: { cwd: process.cwd(), model: "..." },
});
const run2 = resumedAgent.send("Continue from where you left off.");
for await (const msg of run2.stream()) {
if (msg.type === "assistant") process.stdout.write(msg.text ?? "");
}
await run2.wait();
await resumedAgent.dispose();
```
guides/01-principles.md
# Guide 01: Principles
Core philosophy for `cursor-ide-guardian` — read this before any rule authoring, MCP work, or SDK task.
## The MDC-first imperative
`.cursorrules` was Cursor's original rules format: a single file at the project root, always included in every chat/composer/agent context. It still works in Chat mode, but **it is silently ignored in Agent mode**. Because virtually all modern Cursor workflows involve the agent — inline completions aside — any team using `.cursorrules` exclusively loses all their rules the moment they adopt agentic workflows. There is no error, no warning, no indication.
**Rule 1: any project using agentic workflows must use `.cursor/rules/*.mdc`.**
When both formats coexist, MDC wins on conflicting instructions. The override is silent. This means `.cursorrules` content may seem to work (in Chat) while being completely absent (in Agent), leading to inconsistent behaviour across contexts. The safe state is: migrate fully, then archive `.cursorrules`.
## Context budget awareness
Every `alwaysApply: true` rule is prepended to every chat, composer, and agent context window — before any code, before the user's message, before tool calls. This is powerful but expensive.
**Rule 2: keep total `alwaysApply: true` content under ~2,000 tokens across all rule files.**
At 2,000 tokens you have roughly 1,500 words of rule content always burning context budget. Beyond this threshold:
- Agents see less of the actual code they are working on.
- Token costs increase on metered plans.
- Response quality degrades on long-context models that struggle with early instructions being "forgotten".
Prefer `alwaysApply: false` with narrow globs. A rule scoped to `**/*.tsx` that fires only when a TSX file is in context is just as effective as `alwaysApply: true` for TSX files — and costs nothing when the agent is working on Python.
## The four activation modes
Every `.mdc` file with frontmatter picks exactly one of these modes based on the three frontmatter fields:
| Mode name | `alwaysApply` | `globs` | `description` | When it fires |
|---|---|---|---|---|
| Always Apply | `true` | any | any | Every chat, composer, and agent context |
| Apply to Specific Files | `false` | set | any | When a file matching the glob is in context |
| Apply Intelligently | `false` | unset | set | AI reads `description` and decides if relevant |
| Apply Manually | `false` | unset | unset | Only when `@`-mentioned in chat |
**Rule 3: use the most specific activation mode that satisfies the rule's purpose.**
Guidelines:
- Global coding standards that apply everywhere: "Always Apply" (but watch the token budget).
- Language-specific patterns: "Apply to Specific Files" with a glob like `**/*.ts`.
- Domain context (e.g., "This project uses our auth module"): "Apply Intelligently" with a descriptive `description`.
- Reference material users look up on demand: "Apply Manually".
## Rule file size and composability
Cursor recommends keeping individual rule files under 500 lines. This is not a hard limit but a composability signal: if a rule file is growing beyond 500 lines, it probably conflates multiple concerns and should be split.
**Rule 4: one rule file per logical concern. Name files descriptively.**
Good names: `no-em-dashes.mdc`, `react-component-conventions.mdc`, `api-security-rules.mdc`.
Bad names: `rules.mdc`, `all-rules.mdc`, `misc.mdc`.
Use `@filename` references inside rule bodies to point to example files rather than copying them inline. This keeps rules short and prevents them from going stale when the referenced file changes.
## Rule precedence hierarchy
When multiple rules apply to the same context, Cursor applies them in this order (highest priority first):
1. Team Rules (Enterprise/Business admin-enforced, all repos)
2. Project-level `.cursor/rules/*.mdc` files
3. User-level rules (Cursor Settings > Rules)
4. `.cursorrules` (legacy, Chat mode only)
This means project rules can be overridden by Team Rules. Inform users on Enterprise/Business plans that Team Rules may suppress or override their project rules.
## When to defer to other Guardians
`cursor-ide-guardian` owns the configuration layer. When the conversation shifts to what the agent produces, hand off:
- Code quality of agent output → relevant language guardian (`react-guardian`, `python-guardian`, etc.)
- Prompts sent to external LLMs → `mind-guardian`
- CI/CD pipelines that invoke SDK agents → `devops-guardian` (after providing the SDK code)
- Canvas React components → `react-guardian`
- Security of MCP credential handling → `security-guardian`
guides/02-rule-file-authoring.md
# Guide 02: Rule File Authoring
How to write, migrate, and maintain `.cursor/rules/*.mdc` files correctly.
## Anatomy of a rule file
```mdc
---
description: <One sentence: what this rule is about. Used by AI to decide relevance when globs unset.>
globs: **/*.tsx, **/*.ts
alwaysApply: false
---
# Rule Title
Your rule content here. Use markdown. Be specific. Use examples.
```
All three frontmatter fields are optional, but their presence or absence determines the activation mode (see `guides/01-principles.md`). Omit a field entirely rather than setting it to an empty string — empty strings behave differently from unset across Cursor versions.
## Frontmatter field reference
| Field | Type | Required | Notes |
|---|---|---|---|
| `description` | string | Recommended | Used by AI for intelligent activation. 1-2 sentences max. |
| `globs` | string or list | Optional | Comma-separated patterns or YAML list. Standard glob syntax. |
| `alwaysApply` | boolean | Optional | Defaults to `false` if omitted. |
### Glob pattern syntax
| Pattern | Matches |
|---|---|
| `**/*.ts` | All TypeScript files anywhere |
| `src/**/*.tsx` | TSX files under `src/` |
| `**/*.{ts,tsx}` | TS and TSX files anywhere |
| `*.md` | Markdown files in project root only |
| `**/tests/**` | Any file inside a `tests/` folder |
Comma-separate multiple patterns on the same line: `**/*.ts, **/*.tsx`. Or use a YAML list:
```yaml
globs:
- "**/*.ts"
- "**/*.tsx"
```
## How to create a rule file
Three methods, all equivalent:
1. **Slash command (fastest):** type `/create-rule` in the agent panel. Cursor prompts for name and creates the file at `.cursor/rules/<name>.mdc`.
2. **Settings UI:** Cursor Settings > Rules, Commands > "+ Add Rule".
3. **Direct file creation:** create `.cursor/rules/<descriptive-name>.mdc` manually with the Write tool. Cursor picks it up on the next agent invocation.
## Anti-patterns
| Anti-pattern | Why it's bad | Fix |
|---|---|---|
| `alwaysApply: true` on every rule | Exhausts the 2,000-token context budget | Scope with globs or switch to intelligent activation |
| Rule file > 500 lines | Hard to maintain; slow to load | Split into multiple focused files |
| Vague descriptions like "coding standards" | AI cannot decide when to apply intelligently | Write: "Apply when writing or reviewing TypeScript API routes with Zod validation" |
| Copying file content inline | Rules go stale when files change | Use `@filename` references |
| Both `.cursorrules` and `.cursor/rules/` present | Silent precedence conflicts | Migrate fully; archive `.cursorrules` |
## Migrating from `.cursorrules`
Follow this checklist:
1. **Inventory** — read the existing `.cursorrules` file and list every distinct instruction.
2. **Categorise** — for each instruction, decide which activation mode fits:
- Global always: `alwaysApply: true`
- File-specific: `globs` scope
- Context-dependent: intelligent activation with `description`
- On-demand: no globs, no description (manual)
3. **Create `.mdc` files** — one file per logical group. Name them descriptively.
4. **Set frontmatter** — according to the chosen activation mode.
5. **Test** — open a file matching each glob and verify the rule appears in the agent's context (check via "What rules are active?" prompt).
6. **Archive** — rename `.cursorrules` to `.cursorrules.bak` and confirm no regressions.
7. **Delete** — once stable, remove `.cursorrules.bak`.
## Team Rules (Enterprise / Business)
Team Rules are managed in the Cursor dashboard and pushed to all team members' installations. They:
- Override project rules on conflict.
- Support glob patterns for file scoping.
- Are enforced by team admins; individual developers cannot disable them.
If a user reports "my project rules aren't applying", check whether a Team Rule is overriding them.
## Keeping rules current
Rule bodies should reference files via `@filename` rather than duplicating content. When the referenced file changes, the rule stays accurate automatically. Reserve inline content for short, stable directives that will not drift.
Audit rule files when the codebase undergoes major refactors: glob patterns that matched the old file structure silently stop matching after a rename.
guides/03-mcp-integration.md
# Guide 03: MCP Integration
How to register, configure, and build MCP (Model Context Protocol) servers for Cursor.
## What is MCP in Cursor?
MCP is the protocol Cursor uses to let agents call external tools — think of it as a plugin system for the agent's action space. An MCP server exposes `tools` (functions the agent can call), `resources` (read-only data sources), and `prompts` (reusable prompt templates). Cursor ships with several built-in MCP servers and lets you add your own.
## Config file hierarchy
Cursor reads MCP config from two places:
| File | Scope | Priority |
|---|---|---|
| `.cursor/mcp.json` | Project-specific; commit to git for team sharing | Higher (project wins on name conflict) |
| `~/.cursor/mcp.json` | Global; applies to all projects | Lower |
Both files are merged at startup. Restart Cursor after editing either file (unlike Claude Code, Cursor does not hot-reload MCP configs).
## `mcp.json` schema
### STDIO server (process spawned by Cursor)
```json
{
"mcpServers": {
"my-tool": {
"command": "node",
"args": ["${workspaceFolder}/scripts/my-mcp-server.js"],
"env": {
"API_KEY": "${env:MY_API_KEY}"
}
}
}
}
```
Required fields: `command`. Optional: `args`, `env`, `envFile` (path to a `.env` file).
### Remote server (HTTP/SSE)
```json
{
"mcpServers": {
"remote-tool": {
"url": "https://my-mcp.example.com/sse",
"headers": {
"Authorization": "Bearer ${env:REMOTE_TOKEN}"
}
}
}
}
```
### Remote server with OAuth (2026 addition)
```json
{
"mcpServers": {
"oauth-tool": {
"url": "https://my-oauth-mcp.example.com/sse",
"auth": {
"clientId": "${env:MCP_CLIENT_ID}",
"clientSecret": "${env:MCP_CLIENT_SECRET}",
"scopes": ["read", "write"]
}
}
}
}
```
### Config interpolation variables
These variables are resolved in `command`, `args`, `env`, `url`, and `headers`:
| Variable | Value |
|---|---|
| `${env:NAME}` | Environment variable `NAME` |
| `${userHome}` | User home directory |
| `${workspaceFolder}` | Project root (where `.cursor/mcp.json` lives) |
| `${workspaceFolderBasename}` | Project folder name only |
| `${pathSeparator}` or `${/}` | OS path separator |
**Never hardcode secrets in `mcp.json`.** Always use `${env:NAME}` and store the value in your shell environment or a `.env` file (referenced via `envFile`).
## Authoring an MCP tool (TypeScript)
A minimal MCP server using the `@modelcontextprotocol/sdk` package:
```typescript
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
const server = new Server({ name: "my-tool", version: "1.0.0" });
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{
name: "run_security_scan",
description: "Runs a security scan on the specified file and returns findings.",
inputSchema: {
type: "object",
properties: {
filePath: { type: "string", description: "Absolute path to the file to scan." }
},
required: ["filePath"]
}
}]
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "run_security_scan") {
const { filePath } = request.params.arguments as { filePath: string };
// ... your logic here
return { content: [{ type: "text", text: `Scan complete for ${filePath}` }] };
}
throw new Error(`Unknown tool: ${request.params.name}`);
});
const transport = new StdioServerTransport();
await server.connect(transport);
```
### Tool schema requirements
Cursor validates tool schemas strictly. Common failure patterns (silently rejected, no UI error):
| Problem | Fix |
|---|---|
| Missing `inputSchema` | Add `inputSchema: { type: "object", properties: {}, required: [] }` even for zero-param tools |
| `properties` is an array instead of an object | Use `{ "paramName": { "type": "string" } }` format |
| Tool name contains spaces or special chars | Use kebab-case: `run-scan`, `fetch-data` |
| Tool name > ~60 characters | Keep names short and namespaced: `secuity.run-scan` |
### Auto-approval
By default, Cursor asks the user before calling any MCP tool. To enable auto-approval (agent calls tools without prompting):
Settings > Cursor Settings > MCP > "Allow Agent to run tools without asking" > enable per-tool or globally.
## Programmatic registration (Extension API)
For enterprise plugins or automated setup workflows, use the `vscode.cursor.mcp` Extension API to register servers without editing `mcp.json`:
```typescript
import * as vscode from "vscode";
// In your extension's activate() function:
const mcpApi = vscode.extensions.getExtension("cursor.cursor")?.exports?.mcp;
if (mcpApi) {
mcpApi.registerServer("my-enterprise-tool", {
command: "node",
args: ["/path/to/server.js"]
});
}
```
Unregister with `mcpApi.unregisterServer("my-enterprise-tool")`. Useful for:
- Enterprise onboarding tools that add team-standard MCP servers automatically.
- Cursor plugins/extensions that bundle their own MCP server.
## Troubleshooting checklist
- **Tool not appearing in agent:** check `mcp.json` JSON syntax (a single trailing comma breaks the file); restart Cursor; verify the server process starts without errors.
- **Tool call silently fails:** validate `inputSchema` against the JSON Schema spec; check server logs in Output panel > "Cursor MCP".
- **Auth errors on remote server:** confirm env vars are set in your shell before launching Cursor; try `echo ${MY_API_KEY}` in a terminal first.
- **Server spawned multiple times:** Cursor spawns one process per project. If the server is also registered globally, you may get two processes — prefix the name differently to avoid conflicts.
guides/04-sdk-api.md
# Guide 04: Cursor SDK API
Reference guide for `@cursor/sdk` — programmatic agent automation built on the same runtime powering Cursor's IDE.
**Package:** `@cursor/sdk` (public beta since April 29, 2026, npm first published April 26, 2026).
**Install:** `npm install @cursor/sdk`
## Agent lifecycle
```typescript
import { Agent } from "@cursor/sdk";
// Create
const agent = await Agent.create({
local: {
cwd: "/path/to/project",
model: "claude-sonnet-4-5", // required for local runtime
settingSources: ["user"], // optional: which Cursor settings to inherit
}
});
// Send and stream
const run = agent.send("Refactor the auth module to use JWT");
for await (const msg of run.stream()) {
switch (msg.type) {
case "assistant": process.stdout.write(msg.text ?? ""); break;
case "tool_call": console.log(`Tool: ${msg.name} [${msg.status}]`); break;
case "status": console.log(`Status: ${msg.text}`); break;
}
}
const result = await run.wait(); // RunResult
// Dispose
await agent.dispose();
```
## `Agent.create(options)` — option reference
### Local runtime
```typescript
{
local: {
cwd: string, // project root (required)
model: string, // model identifier (required for local)
settingSources?: string[] // e.g. ["user", "project"]
}
}
```
Note: `settingSources` is nested under `local`, NOT at the top level. This is a subtle API gotcha.
### Cloud runtime
```typescript
{
cloud: {
repos?: string[], // GitHub repos to give the agent access to
autoCreatePR?: boolean, // auto-open PR on task completion
skipReviewerRequest?: boolean
}
}
```
Cloud agents: one active run at a time per agent. Watch for `AgentBusyError`.
## Convenience methods
```typescript
// One-shot: create, send, wait, dispose
const result = await Agent.prompt("Fix the failing tests", {
local: { cwd: "/project", model: "claude-sonnet-4-5" }
});
// Resume across process boundaries
const agent = await Agent.resume(agentId, {
local: { cwd: "/project", model: "claude-sonnet-4-5" }
});
```
## `run.stream()` — event types
`run.stream()` is an async generator yielding `SDKMessage` events discriminated on `type`:
| Type | Key fields | Description |
|---|---|---|
| `system` | `text` | System-level messages |
| `user` | `text` | User messages echoed back |
| `assistant` | `text` | Agent prose output |
| `thinking` | `text` | Chain-of-thought (models that support it) |
| `tool_call` | `callId`, `name`, `status`, `args`, `result` | Tool invocations; `status` is `running` or `completed` |
| `status` | `text` | Progress updates |
| `task` | `text` | Sub-task tracking |
| `request` | - | Awaiting user input (rarely seen in SDK flows) |
`tool_call` events ARE streamed incrementally — partial tool-call results are available before the tool completes. This resolves the Command Brief's open question.
### Lower-level callbacks
For per-token streaming and step boundaries, pass callbacks to `agent.send()`:
```typescript
const run = agent.send("do X", {
onDelta: (delta) => process.stdout.write(delta.text ?? ""),
onStep: (step) => console.log("Step:", step.type),
});
```
`onDelta` fires on every token; `onStep` fires at tool/thought/response boundaries. Use these when you need lower latency than batch `SDKMessage` events.
## Error handling
All SDK errors extend `CursorAgentError`:
```typescript
try {
const result = await run.wait();
} catch (err) {
if (err instanceof CursorAgentError) {
console.error(`Code: ${err.code}, Retryable: ${err.isRetryable}`);
if (err.isRetryable) {
// back off and retry
}
}
}
```
### Error subclass catalog
| Class | HTTP | Code | Retryable | Notes |
|---|---|---|---|---|
| `AuthenticationError` | 401 | `authentication_error` | false | Check `CURSOR_API_KEY` / login state |
| `RateLimitError` | 429 | `rate_limit_error` | true | Exponential back-off |
| `ConfigurationError` | 400 | `configuration_error` | false | Bad options in `Agent.create` |
| `AgentBusyError` | 409 | `agent_busy` | false | Cloud only; one run at a time |
| `IntegrationNotConnectedError` | 4xx | `integration_not_connected` | false | MCP or GitHub integration missing |
| `NetworkError` | - | `network_error` | true | Transient connectivity |
| `UnknownAgentError` | 404 | `unknown_agent` | false | `agentId` not found for `Agent.resume` |
**AgentBusyError recovery pattern (cloud agents):**
```typescript
} catch (err) {
if (err instanceof AgentBusyError) {
// Cloud agents allow only one active run; wait and poll
await new Promise(r => setTimeout(r, 5000));
const activeRun = (await Agent.listRuns(agentId)).find(r => r.status === "running");
// handle or cancel activeRun before retrying
}
}
```
For local agents, `agent_busy` never fires. Use `send({ local: { force: true } })` to override any local lock.
## Listing and inspection
```typescript
const agents = await Agent.list();
const runs = await Agent.listRuns(agentId);
const run = await Agent.getRun(runId);
const messages = await Agent.messages.list(runId);
```
## Capability guards
```typescript
if (run.supports("stream")) {
for await (const msg of run.stream()) { ... }
} else {
console.log(run.unsupportedReason("stream"));
}
```
## Open question: plan tier detection
There is no documented public API for detecting the active Cursor plan tier (Free / Pro / Business / Enterprise) from within an SDK run. Guard features by testing them with `run.supports()` or catching `ConfigurationError` rather than inspecting the plan tier directly.
## CI/CD usage (handoff note)
Providing the SDK code that runs agents is `cursor-ide-guardian`'s job. Wiring it into GitHub Actions or Docker containers is `devops-guardian`'s job. After writing the SDK script, hand off to `devops-guardian` for pipeline integration.
guides/05-modes-and-productivity.md
# Guide 05: Modes and Productivity
Custom modes, the Agents Window, slash commands, and keybindings — the Cursor productivity layer.
## Custom modes
Custom modes let you configure a dedicated agent persona: a system prompt, a tool allowlist, and a display name. Use cases: a "Migration Reviewer" mode that only has read tools and always starts with your migration checklist; a "Security Auditor" mode that runs `security-guardian`-aligned rules by default.
### Creating a custom mode
Currently UI-only (as of May 2026; a `.cursor/modes.json` file was under consideration but not yet shipped):
1. Open Cursor Settings > Features > Chat > Custom Modes.
2. Click "Add custom mode".
3. Fill in: **Name** (shown in mode selector), **System prompt** (the mode's persona and directives), **Enabled tools** (subset of standard Cursor tools: codebase search, file operations, terminal, web search, etc.).
4. Save. The mode appears in the agent panel's mode dropdown.
### System prompt design
Effective mode system prompts:
- State the persona in the first sentence: "You are a security auditor reviewing this PR for OWASP Top 10 vulnerabilities."
- List the tools explicitly: "You have access to codebase search and file read. Do not write to disk."
- State what NOT to do: "Do not suggest refactors outside the security scope."
- Reference a rule file: "Treat the directives in `.cursor/rules/security-rules.mdc` as mandatory."
Keep system prompts under 300 tokens; they burn context budget on every invocation.
## The Agents Window (Cursor 3, April 2026)
The Agents Window is the primary agent interface introduced in Cursor 3. It replaces "Background Agents" (now called Cloud Agents) as the canonical multi-agent surface.
### What it shows
A unified sidebar listing all agents regardless of origin:
- Local agents (running in the IDE)
- Cloud Agents (isolated Ubuntu VMs)
- Mobile-initiated agents
- Agents started from Slack, GitHub, or Linear integrations
### When to use each surface
| Surface | Best for |
|---|---|
| Classic editor agent panel | Focused, single-feature work; flexible screen splitting; viewing many files |
| Agent Tabs (tiled layout) | Comparing two approaches side-by-side |
| Agents Window | Long-running cloud agents; multi-repo orchestration; managing many parallel agents |
| `/multitask` | Single task that decomposes naturally (cross-file refactors, parallel test fixes) |
### Cloud Agents setup
1. Cursor Settings > Beta > Background Agent (now "Cloud Agent") > enable.
2. Connect your GitHub account (Settings > Integrations > GitHub).
3. Set a spend limit at cursor.com/dashboard (Cloud Agents consume credits).
4. Trigger: from the Agents Window, click "New Cloud Agent" or use the `@cloud` prefix.
Cloud Agents run in isolated Ubuntu VMs, work on a dedicated `agent/` branch, and auto-open a PR on completion. Email, desktop, and Slack notifications available. Privacy Mode must be disabled.
### Local-to-cloud handoff
Mid-task, you can move an agent from local to cloud: in the Agents Window, select the local agent and choose "Continue in Cloud". The conversation history and context transfer.
## Slash commands
| Command | What it does |
|---|---|
| `/multitask` | Spawns async parallel subagents within the current task. Best for work that decomposes into independent subtasks. |
| `/worktree` | Creates an isolated git worktree for the agent's work, leaving your main checkout untouched. |
| `/best-of-n` | Runs N parallel attempts and lets you pick the best result. |
| `/create-rule` | Creates a new `.cursor/rules/*.mdc` file interactively. |
## Essential keybindings
Default shortcuts (macOS / Windows):
| Action | macOS | Windows |
|---|---|---|
| Open/close agent panel | `Cmd+L` | `Ctrl+L` |
| Open inline chat | `Cmd+K` | `Ctrl+K` |
| Accept inline suggestion | `Tab` | `Tab` |
| Reject inline suggestion | `Esc` | `Esc` |
| Open file search | `Cmd+P` | `Ctrl+P` |
| Open command palette | `Cmd+Shift+P` | `Ctrl+Shift+P` |
| New agent tab | `Cmd+Shift+L` | `Ctrl+Shift+L` |
| Toggle Agents Window | (via sidebar icon) | (via sidebar icon) |
Cursor's keybindings are VS Code-compatible. All standard VS Code shortcuts work; check Preferences > Keyboard Shortcuts for the full list and to rebind.
## Inline chat vs agent panel vs Agents Window vs SDK
Decision tree for choosing the right interaction surface:
```
Do you need the agent to take actions (write files, run commands)?
└── Yes → Are you comfortable with it working autonomously for minutes?
└── Yes → Agent panel or Agents Window (Cloud Agent for long-running)
└── No → Inline chat (Cmd+K) for tight, fast feedback loops
└── No → Inline chat or Chat panel (information only, no side-effects)
Do you want to automate this workflow in a script or CI?
└── Yes → @cursor/sdk (see guides/04-sdk-api.md)
Do you want to run the same task many ways in parallel?
└── Yes → /multitask or /best-of-n
```
## Productivity patterns
- **Rule-first development:** before starting a new feature, create a scoped rule file for the feature's conventions. This primes every agent invocation with the right context automatically.
- **Worktree-per-task:** use `/worktree` for each significant change so your main branch stays clean and agents work in isolation.
- **SDK for repeatables:** any task you do more than twice is a candidate for the SDK. A 20-line TypeScript script with `Agent.prompt` can run the same audit, refactor, or review on every PR.
- **Mode-per-role:** maintain separate custom modes for common roles (reviewer, migrator, security auditor) so you don't have to re-prompt context every time.
guides/06-extension-development.md
# Guide 06: Extension Development
Building Cursor plugins and extensions — manifest structure, MCP server bundling, and marketplace readiness.
> **Source gap note (from research):** The full Cursor plugin manifest schema and marketplace submission checklist were not fully confirmed in the May 2026 research window. The Extension API (`vscode.cursor.mcp.registerServer`, `vscode.cursor.plugins.registerPath`) was found. For the authoritative manifest spec, fetch `https://cursor.com/docs/plugins` directly. This guide documents what is confirmed and flags gaps.
## What is a Cursor extension?
Cursor extensions are VS Code-compatible extensions that additionally register into the `cursor.*` Extension API namespace. They are distributed through the Cursor marketplace (or installed via VSIX). They can:
- Bundle an MCP server and register it programmatically at extension activation.
- Register plugin paths that Cursor's agent loading machinery discovers.
- Contribute skills (`.cursor/skills/`) packaged inside the extension.
- Add commands, panels, and settings via standard VS Code contribution points.
## Extension manifest (`package.json`) — confirmed fields
Standard VS Code fields apply. Cursor-specific additions:
```json
{
"name": "my-cursor-plugin",
"displayName": "My Cursor Plugin",
"version": "1.0.0",
"engines": { "vscode": "^1.85.0" },
"contributes": {
"commands": [ ... ],
"configuration": { ... }
},
"activationEvents": ["onStartupFinished"]
}
```
The Cursor marketplace layer reads standard VS Code manifest fields. No confirmed additional top-level Cursor-specific manifest keys as of May 2026 — verify at `cursor.com/docs/plugins`.
## Registering an MCP server from an extension
In `extension.ts` / `activate()`:
```typescript
import * as vscode from "vscode";
export function activate(context: vscode.ExtensionContext) {
const cursorExt = vscode.extensions.getExtension("cursor.cursor");
const mcpApi = cursorExt?.exports?.mcp;
if (mcpApi?.registerServer) {
const serverPath = context.asAbsolutePath("out/mcp-server.js");
mcpApi.registerServer("my-plugin-tools", {
command: "node",
args: [serverPath],
env: {}
});
context.subscriptions.push({
dispose: () => mcpApi.unregisterServer("my-plugin-tools")
});
}
}
```
Push to `context.subscriptions` so the server is unregistered when the extension deactivates.
## Registering a plugin path
```typescript
const pluginApi = cursorExt?.exports?.plugins;
if (pluginApi?.registerPath) {
pluginApi.registerPath(context.extensionPath);
}
```
Cursor then discovers skills and rules in the extension's directory structure.
## Marketplace readiness checklist
Items confirmed or inferred from VS Code + Cursor publishing norms. Flag any item that requires verification at `cursor.com/docs/plugins`:
- [ ] `package.json` has `name`, `displayName`, `version`, `description`, `publisher`
- [ ] `engines.vscode` set to a realistic minimum version
- [ ] `activationEvents` are as narrow as possible (avoid `*`)
- [ ] Extension compiles cleanly with `vsce package`
- [ ] All `vscode.cursor.*` API calls are guarded with optional chaining (graceful degradation if API not present)
- [ ] Bundled MCP server exits cleanly on deactivation (no zombie processes)
- [ ] Secrets are not hardcoded — use VS Code `secrets` storage or `${env:NAME}` interpolation
- [ ] `README.md` explains what the extension does, how to install, and how to configure
- [ ] `CHANGELOG.md` present with version history
- [ ] Extension icon provided (128x128px PNG)
## Plugin quality gates rule
The `plugin-quality-gates.mdc` rule file at `.cursor/plugins/cache/cursor-public/create-plugin/.../rules/plugin-quality-gates.mdc` enforces manifest, path, and component metadata validity during plugin authoring. Load it when writing extension code.
## Handoff boundary
`cursor-ide-guardian` owns extension scaffolding and the `vscode.cursor.*` API surface. For the React components inside the extension's webview panels, hand off to `react-guardian`. For publishing and CI for the extension, hand off to `devops-guardian`.
reports/README.md
# Reports
Past-run summaries for `cursor-ide-weapon` invocations accumulate here over time.
Each successful significant invocation of `cursor-ide-guardian` MAY produce a dated summary file in this folder:
```
reports/YYYY-MM-DD-<short-slug>.md
```
The folder starts empty. No reports have been filed yet.
## What goes in a report
A report is optional context that helps future invocations understand prior work. Include:
- What was audited or built.
- Key findings or decisions.
- Files modified.
- Open items for follow-up.
Reports are informational only; they do not affect the weapon's behaviour.
research/external/2026-02-06-cursor-rules-design-dev-guide.md
---
source_type: blog
authority: medium
relevance: high
topic: rule-file-authoring
url: https://design.dev/guides/cursor-rules/
fetched: 2026-05-20
---
# Cursor Rules Guide - AI Configuration | design.dev
## Summary
Published February 6, 2026. Comprehensive practitioner guide covering the complete rule priority hierarchy and the modern `.cursor/rules/` system. Unique value: documents the full 5-level priority stack, which the official docs do not present as clearly.
**Full priority hierarchy (highest to lowest):**
1. Team Rules (highest - Enterprise/Business plans, admin-managed)
2. Project Rules (`.cursor/rules/*.mdc` - version-controlled)
3. User Rules (Cursor Settings > Rules - global preferences)
4. Legacy Rules (`.cursorrules` file - deprecated, still supported)
5. AGENTS.md (simple markdown alternative in project root)
**AGENTS.md alternative:** Simple always-on plain markdown instructions in the project root. No frontmatter, no activation modes. Use when you want simple, always-on instructions without the MDC complexity. The `.mdc` system is better when fine-grained control is needed.
**Conflict resolution:** Rules applied later override earlier ones at the same tier. Team Rules can be enforced (cannot be disabled by users) or advisory (users can disable).
**Common patterns from guide:**
- Database rules scoped to `**/*.sql, **/migrations/**`
- Component rules scoped to `**/*.tsx, **/*.jsx`
- Test rules scoped to `**/*.test.*, **/*.spec.*`
- API rules scoped to `**/api/**`
- Global style rules with `alwaysApply: true`
## Key quotations
- "5-layer priority: Team Rules > Project Rules > User Rules > Legacy Rules > AGENTS.md"
- "Tip: Use `.cursor/rules/` with `.mdc` files when you need fine-grained control over when rules activate. Use `AGENTS.md` when you want simple, always-on instructions in plain markdown."
- "Team Rules can be enforced by team admins, preventing users from disabling them."
## Annotations for weapon-forge
- The 5-level priority hierarchy should be a table in `guides/01-principles.md` - it is clearer than anything in the official docs.
- The AGENTS.md alternative is worth documenting in guide 02 as the "no frontmatter, no complexity" option for simple projects.
- The enforced vs. advisory Team Rules distinction is important for Enterprise users - include in guide 02.
- The common scoping patterns (SQL files, TSX components, test files, API routes) are excellent worked examples for guide 02.
research/external/2026-04-02-cursor-3-agents-window.md
---
source_type: blog
authority: high
relevance: high
topic: modes-and-agents
url: https://www.digitalapplied.com/blog/cursor-3-agents-window-design-mode-complete-guide
fetched: 2026-05-20
---
# Cursor 3: Agents Window, Cloud Agents, and What Changed
## Summary
Published April 2, 2026. Cursor 3 is the biggest architectural change since the editor launched. The Agents Window is a new standalone, agent-first interface for running many agents in parallel across local repos, cloud, remote SSH, and mobile. Background Agents from Cursor 2.0 are now officially "Cloud Agents." Composer 2 (Cursor's own frontier coding model) shipped with this release.
**Agents Window capabilities:**
- Unified sidebar showing all agents (local, cloud, mobile, Slack, GitHub, Linear)
- Multi-workspace: one agent session can target several repositories at once
- Local-to-cloud handoff: move agent between local and cloud mid-task
- Agent Tabs (tiled layout added April 13): multiple agents in panes side-by-side
- `/multitask` command: async subagents in parallel rather than queued
- Multi-root workspaces (v3.2): one agent targets multiple folders
**Mode decision table (from post):**
- Single agent tab: focused work on one feature
- Agent Tabs (grid): comparing two approaches side-by-side
- Agents Window: long-running cloud agents, multi-repo orchestration
- `/multitask`: single task that decomposes naturally (cross-file refactors, parallel tests)
**Cloud Agents:** spin up isolated Ubuntu VMs, clone repo, work on dedicated `agent/` branch, open PR on completion. Notifications via email, Cursor desktop, Slack. Privacy Mode must be disabled. Spend limit configurable at cursor.com/dashboard.
**Backward compatibility:** existing rules, models, and project configuration carry over from Cursor 2.0. The main change is the Agents Window becoming the primary agent interface.
## Key quotations
- "The Agents Window is now the primary surface for agent interaction, with the classic editor available as a complement."
- "All your agents appear in one sidebar -- local agents, cloud agents, and the ones you kicked off from mobile, web, the desktop app, Slack, GitHub, and Linear."
- "Background Agents have been renamed to Cloud Agents."
- "Cursor's guidance: the Agents Window works best when you want to run and manage many agents in parallel, while the classic editor remains the better choice for flexible screen splitting, VS Code extensions, and viewing many files at once."
## Annotations for weapon-forge
- The Agents Window is the correct term in 2026 (not "Background Agents" - that is deprecated). Update guide 05 terminology.
- The local-to-cloud handoff capability should be in `guides/05-modes-and-productivity.md` as a workflow pattern.
- The `/multitask` command is a high-value slash command to document in the keybindings/productivity guide.
- The "when to use which surface" table (single tab vs Agent Tabs vs Agents Window vs /multitask) is a useful decision framework.
- Cloud Agent setup steps (Settings > Beta > Background Agent, GitHub repo access, spend limit) should be in guide 05.
research/external/2026-04-10-cursorrules-vs-mdc-migration.md
---
source_type: blog
authority: high
relevance: high
topic: rule-file-authoring
url: https://thepromptshelf.dev/blog/cursorrules-vs-mdc-format-guide-2026
fetched: 2026-05-20
---
# .cursorrules vs .cursor/rules (MDC): Which Format to Use in 2026
## Summary
Published April 10, 2026. This guide provides the definitive comparison between `.cursorrules` (legacy, single-file, always-on) and `.cursor/rules/*.mdc` (modern, multi-file, four activation modes). The key finding: `.cursorrules` is silently ignored in Cursor's Agent mode. Any team using agentic workflows must migrate to MDC format or their rules will not apply.
The MDC format uses YAML frontmatter with three fields (`description`, `alwaysApply`, `globs`) to create four activation modes. Critical performance note: total `alwaysApply: true` rule content should stay under approximately 2,000 tokens combined - these consume context budget before any code is analyzed.
When both formats coexist, `.mdc` rules win over `.cursorrules` on conflicting instructions, but the override is silent and may cause unexpected behavior.
The comparison table shows MDC wins on every modern dimension: Agent mode support, subdirectory rules, file scoping via globs, team rules (Enterprise), conflict resolution, and multiple rule files. The only case for keeping `.cursorrules` is very small, non-agentic projects where no migration is planned.
Migration path: (1) inventory all rules in `.cursorrules`, (2) categorize each by activation mode needed, (3) create one `.mdc` file per logical rule group, (4) set appropriate frontmatter, (5) test by mentioning matching files, (6) archive or delete `.cursorrules`.
## Key quotations
- "`.cursorrules` is silently ignored in Cursor's Agent mode."
- "Important constraint: Keep total `alwaysApply` rule content under approximately 2,000 tokens combined."
- "There is also a precedence issue when both formats coexist: `.mdc` rules win over `.cursorrules` on conflicting instructions."
- "The moment you enable Agent mode, you need MDC — your existing rules are invisible to it. Migration takes under an hour for most projects."
## Annotations for weapon-forge
- The "`.cursorrules` silently ignored in Agent mode" finding is the single most important migration motivator - put it at the top of the migration section in `guides/02-rule-file-authoring.md`.
- The 2,000-token budget for `alwaysApply: true` rules is a critical constraint that should appear in `guides/01-principles.md`.
- The MDC vs `.cursorrules` comparison table is worth reproducing verbatim in the guide.
- The activation mode descriptions (Loaded in every Chat/Composer/Agent, Activates on glob match, AI-decided, Manual mention) should be the four-mode framework for the authoring guide.
research/external/2026-04-29-cursor-sdk-launch-blog.md
---
source_type: blog
authority: high
relevance: high
topic: sdk-api
url: https://cursor.com/blog/typescript-sdk
fetched: 2026-05-20
---
# Build programmatic agents with the Cursor SDK (Official Launch Blog)
## Summary
Official Cursor blog post announcing the TypeScript SDK public beta (April 29, 2026, by Roshan Sadanani). Provides launch context, positioning, and key architectural facts for `weapon-forge` to use as narrative framing in `guides/04-sdk-api.md`.
The SDK is available to all users, billed at standard token-based consumption pricing. It targets three runtime modes: local (runs on caller's machine against cwd), cloud Cursor-hosted (dedicated VM, persistent sessions, autoCreatePR), and self-hosted workers (data residency use cases).
The post confirms integration with the Agents Window in Cursor 3: SDK-launched cloud runs appear in the Agents Window and web app at cursor.com/agents - you can start a task programmatically and jump into Cursor to inspect progress or take over.
Key capabilities beyond basic prompting: `.cursor/hooks.json` file for observing/controlling runs, subagents (delegate subtasks to named subagents with own prompts and models), codebase indexing automatically included.
Reference use cases from the post:
- **Quickstart**: minimal Node.js example, local agent, one prompt, streamed response
- **Prototyping tool**: web app for spinning up sandbox cloud agents
- **Kanban board**: engineer drags a card, agent picks up work, opens PR, posts result back
- **Coding agent CLI**: lightweight terminal interface spawning Cursor agents
## Key quotations
- "The same agent that runs in the Cursor desktop app, CLI, and web app is now accessible with a few lines of TypeScript."
- "SDK cloud runs show up in Cursor's Agents Window and web app. You can start a task programmatically and then jump into Cursor to inspect progress or take over."
- "Hooks: Observe, control with a `.cursor/hooks.json` file."
- "Subagents: Delegate subtasks to named subagents with their own prompts and models, which the main agent spawns via the `Agent` tool."
## Annotations for weapon-forge
- Use the kanban board and coding-agent CLI examples as inspiration for real-world examples in guide 04.
- The `.cursor/hooks.json` mention is a separate feature from the SDK proper - note it as a related but distinct surface in guide 04 and point to Cursor's Hooks docs.
- The "start programmatically, inspect in Cursor Agents Window" workflow is the primary selling point for cloud agents - emphasize in guide 04.
- The three runtime modes (local / Cursor-hosted cloud / self-hosted) should be the organizing framework for the runtime selection section.
research/external/2026-05-14-cursor-agent-modes-deep-dive.md
---
source_type: blog
authority: high
relevance: high
topic: modes-and-agents
url: https://developertoolkit.ai/en/cursor-ide/advanced-techniques/agent-modes-deep-dive/
fetched: 2026-05-20
---
# Agent Modes Deep Dive | Developer Toolkit
## Summary
Published May 18, 2026. Comprehensive guide to Cursor's four primary modes (Agent, Ask, Plan, Debug) plus Custom Modes, with Cursor 3.0 context. Since Cursor 3.0 (April 2, 2026), modes run inside the Agents Window. Each agent tab can hold its own mode, model, and worktree - enabling parallel workflows like Opus 4.7 in Plan mode + Composer 2 in Agent mode simultaneously.
**Mode decision framework:**
- **Agent mode**: Default, most powerful. Read, edit, run terminal commands, search codebase, iterate until done. Enable auto-run for terminal commands so agent can run its own tests. Key insight: "Agent mode becomes dramatically more useful when it can run your test suite after making changes."
- **Ask mode**: Read-only codebase exploration. "Plan with Ask mode and implement with Agent mode" is the recommended pattern from official docs.
- **Plan mode**: Creates detailed implementation plans before writing any code. Agent researches codebase, asks clarifying questions, generates reviewable plan (editable Markdown). Click "Build" to execute in Agent mode. Best for complex features, multi-file changes, unclear requirements.
- **Debug mode**: Systematic bug investigation with runtime evidence.
- **Custom modes**: User-defined modes with specific instruction set and tool permissions (e.g., dedicated code-review mode).
**Power user workflow:**
1. Ask mode to understand architecture and constraints
2. Plan mode to create detailed, reviewable implementation plan
3. Agent mode to execute the plan with auto-run enabled
**Agents Window navigation shortcuts:**
- Open: `Cmd+Shift+P -> Agents Window`
- Tiled layout (v3.1): split view into panes, persistent across sessions
- `/worktree`: spin agent into isolated git worktree
- `/best-of-n`: run same prompt across N models in separate worktrees and compare
- `/multitask`: async parallel subagents
## Key quotations
- "Since Cursor 3.0, modes run inside the Agents Window — `Cmd+Shift+P → Agents Window`."
- "Each agent tab can hold its own mode, model, and worktree."
- "The most effective Cursor users do not stay in one mode. They switch modes as the nature of their work changes within a single task."
- "Agent mode edits too many files. This happens when the prompt is too broad."
## Annotations for weapon-forge
- The three-step workflow (Ask -> Plan -> Agent) should be the recommended pattern in `guides/05-modes-and-productivity.md`.
- `/worktree`, `/best-of-n`, `/multitask` are important slash commands to document in guide 05.
- The "one model per mode" pattern (e.g., Opus 4.7 for Plan, Composer 2 for Agent) is a power-user tip worth including.
- "Agent mode edits too many files" is a common failure mode - include the remedy (narrow prompts + file-scoped context) in guide 05.
- The Agents Window keyboard shortcut (`Cmd+Shift+P -> Agents Window`) should be in the shortcuts table.
research/external/2026-05-18-cursor-mcp-complete-setup-guide.md
---
source_type: blog
authority: medium
relevance: high
topic: mcp-integration
url: https://claudefa.st/blog/tools/mcp-extensions/cursor-mcp-setup
fetched: 2026-05-20
---
# Cursor MCP Servers: Complete Setup Guide for 2026
## Summary
Published May 18, 2026. Practitioner guide covering Cursor MCP server setup from scratch with troubleshooting and comparison against Claude Code. Key value: the Cursor vs. Claude Code MCP comparison table and the troubleshooting section.
**Configuration locations:**
- Project-level: `.cursor/mcp.json`
- Global: `~/.cursor/mcp.json`
**Cursor vs Claude Code MCP comparison:**
| Feature | Cursor | Claude Code |
|---------|--------|-------------|
| Config location | `.cursor/mcp.json` | `~/.claude.json` or `.mcp.json` |
| Transport types | stdio, SSE, HTTP | stdio (HTTP/SSE in some preview builds) |
| OAuth support | Built-in OAuth flow | Manual token paste in `env` block |
| Tool search | Not available (all tools loaded at session start) | Tool Search (lazy loading on demand) |
| Resources | Not yet supported | Supported |
| Hot reload | Restart Cursor required | Reloads on `.mcp.json` edit in some builds |
| Per-project scope | `.cursor/mcp.json` works | `.mcp.json` works the same way |
**Troubleshooting steps:**
1. Open Cursor Settings, search "MCP", confirm "Enable MCP Servers" is checked
2. Run `MCP: View Server Status` from Command Palette to confirm servers loaded
3. Verify JSON syntax is valid
4. Check server logs via Help > Toggle Developer Tools > Console
**Key fact:** MCP server packages are interchangeable between Cursor and Claude Code - both speak the same protocol. The same `mcp.json` config block copies between tools with no modification.
## Key quotations
- "Cursor and Claude Code both speak the same Model Context Protocol, so server packages are interchangeable."
- "Tool search: Not available — all tools loaded at session start" (unlike Claude Code's lazy loading)
- "Resources: Not yet supported" in Cursor (unlike Claude Code)
- "Hot reload: Restart Cursor required for config changes" (unlike Claude Code's auto-reload)
## Annotations for weapon-forge
- The "all tools loaded at session start" limitation is important: large numbers of MCP tools can bloat the context window. Mention in guide 03 as a reason to scope MCP servers per-project.
- Resources (MCP spec feature) not supported in Cursor - note this as a known gap in guide 03.
- The Cursor vs Claude Code comparison table is useful for teams choosing between tools - include a condensed version in guide 03.
- The troubleshooting steps (MCP: View Server Status command) are practical and should be in a troubleshooting section of guide 03.
- Config interpolation (`${env:VAR}`) is the safe way to inject API keys; this guide's reliance on hardcoded env values is an antipattern to note.
research/external/2026-05-20-cursor-keyboard-shortcuts-docs.md
---
source_type: official-docs
authority: high
relevance: high
topic: keybindings
url: https://cursor.com/help/customization/keyboard-shortcuts
fetched: 2026-05-20
---
# Keyboard Shortcuts - Cursor Official Documentation
## Summary
The official keyboard shortcuts reference. Cursor uses the same defaults as VS Code plus its own AI-specific shortcuts. Customization via `Cmd+R then Cmd+S` (Mac) or `Ctrl+R then Ctrl+S` (Windows/Linux), or search in the keyboard shortcuts editor.
**AI-specific shortcuts:**
| Action | Mac | Windows/Linux |
|--------|-----|---------------|
| Toggle Sidepanel | Cmd+I or Cmd+L | Ctrl+I or Ctrl+L |
| Inline edit | Cmd+K | Ctrl+K |
| Mode Menu | Cmd+. | Ctrl+. |
| Rotate between Agent modes | Shift+Tab | Shift+Tab |
| Loop between AI models | Cmd+/ | Ctrl+/ |
| Accept Tab suggestion | Tab | Tab |
**Additional AI shortcuts from community sources (authoritative):**
- Cmd+Shift+L / Ctrl+Shift+L: Add selected code as context to current chat
- Cmd+Enter / Ctrl+Enter: Accept all AI-suggested changes
- Cmd+Backspace / Ctrl+Backspace: Reject all AI-suggested changes
- Cmd+Right / Ctrl+Right: Accept next word of suggestion (partial accept)
- Cmd+N / Ctrl+N: Start new chat (fresh context)
- Cmd+Shift+P / Ctrl+Shift+P: Command palette
- Cmd+P / Ctrl+P: Quick file open
- Cmd+J / Ctrl+J: Toggle terminal
- Cmd+K in terminal: Generate terminal command with natural language
- Cmd+Shift+J / Ctrl+Shift+J: Cursor Settings
**Customization location:** `~/.cursor/User/keybindings.json` (same path as VS Code).
## Key quotations
- "Cursor uses the same default shortcuts as VS Code, plus shortcuts for AI features."
- "Rotate between Agent modes: Shift+Tab (all platforms)"
- "Loop between AI models: Cmd+/ / Ctrl+/"
## Annotations for weapon-forge
- This is the PRIMARY source for the shortcuts reference table in `guides/05-modes-and-productivity.md`.
- The `Cmd+.` / `Ctrl+.` Mode Menu shortcut is the least-known but most useful for switching between Agent/Ask/Plan/Debug - emphasize it.
- `Shift+Tab` for rotating modes and `Cmd+/` for model switching are the two shortcuts most power users are unaware of.
- The terminal `Cmd+K` shortcut (natural language terminal commands) is a high-value productivity tip to feature prominently.
- Keybindings file path `~/.cursor/User/keybindings.json` should be in the guide for users who want to customize.
research/external/2026-05-20-cursor-mcp-official-docs.md
---
source_type: official-docs
authority: high
relevance: high
topic: mcp-integration
url: https://cursor.com/docs/mcp
fetched: 2026-05-20
---
# Model Context Protocol (MCP) - Cursor Official Documentation
## Summary
The official Cursor MCP documentation covers the complete `mcp.json` configuration schema, both stdio and remote server types, OAuth support, config interpolation variables, and the programmatic Extension API for runtime registration. This is the authoritative source for `guides/03-mcp-integration.md`.
**Configuration locations:**
- Project-specific: `.cursor/mcp.json` (commit to git for team sharing; takes priority over global)
- Global: `~/.cursor/mcp.json` (personal, all projects)
- Both files are merged; project-level wins on name conflicts
**STDIO server config fields:**
- `type`: `"stdio"` (required but inferred from presence of `command`)
- `command`: executable (required)
- `args`: array of arguments (optional)
- `env`: environment variables (optional)
- `envFile`: path to .env file (optional)
**Remote server config:**
- `url`: HTTP/SSE endpoint
- `headers`: auth headers (optional)
- `auth`: static OAuth credentials (`CLIENT_ID`, `CLIENT_SECRET`, `scopes`) for OAuth 2.0 servers
**Config interpolation variables** (resolved in `command`, `args`, `env`, `url`, `headers`):
- `${env:NAME}` - environment variables
- `${userHome}` - home folder path
- `${workspaceFolder}` - project root (where `.cursor/mcp.json` lives)
- `${workspaceFolderBasename}` - project folder name
- `${pathSeparator}` / `${/}` - OS path separator
**Extension API** (`vscode.cursor.mcp`):
- `registerServer(config: StdioServerConfig | RemoteServerConfig): void` - programmatic registration without editing mcp.json
- `unregisterServer(serverName: string): void`
- Useful for enterprise onboarding tools and automated setup workflows
## Key quotations
- "Both files are merged. If the same server name appears in both, the project-level config takes priority."
- "By default, Agent asks for your approval before using an MCP tool. Enable auto-run in settings if you prefer Agent to use tools without asking."
- "For MCP servers that use OAuth, you can provide static OAuth client credentials in `mcp.json` instead of dynamic client registration."
- "Use variables in `mcp.json` values. Cursor resolves variables in these fields: `command`, `args`, `env`, `url`, and `headers`."
## Annotations for weapon-forge
- This is the PRIMARY source for `guides/03-mcp-integration.md`. All `mcp.json` field specs should cite this doc.
- The config interpolation variable table is highly useful for teams - reproduce it in full in guide 03.
- The static OAuth `auth` object is a 2026 addition - note it explicitly as a new capability.
- The Extension API (`vscode.cursor.mcp.registerServer`) enables enterprise plugin patterns - cover in `guides/06-extension-development.md`.
- The "project-level wins on name conflicts" merge behavior should be called out in the guide's project vs. global config section.
- Hot-reload: docs say "Restart Cursor" after config changes - note this as a friction point vs. Claude Code's hot-reload.
research/external/2026-05-20-cursor-rules-official-docs.md
---
source_type: official-docs
authority: high
relevance: high
topic: rule-file-authoring
url: https://cursor.com/docs/rules
fetched: 2026-05-20
---
# Cursor Rules Official Documentation
## Summary
The official Cursor rules documentation defines the complete `.cursor/rules/` system. Rules are markdown files (`.md` or `.mdc` extension) stored in `.cursor/rules/`, version-controlled, and scoped using path patterns, manual invocation, or relevance-based inclusion. The MDC format with YAML frontmatter provides four activation modes: Always Apply, Apply Intelligently, Apply to Specific Files, and Apply Manually.
The three frontmatter fields are `alwaysApply` (boolean), `description` (string), and `globs` (pattern or comma-separated patterns). Their interaction determines the activation mode:
- `alwaysApply: true` + anything = always included, ignores globs and description
- `alwaysApply: false` + globs provided = auto-attached when a matching file is in context
- `alwaysApply: false` + description + no globs = AI reads description and decides relevance
- `alwaysApply: false` + no description + no globs = only when `@`-mentioned in chat
Glob patterns support standard wildcards: `*` (single segment), `**` (any directories), and comma-separation for multiple patterns.
Rules can be created via `/create-rule` command in the Agent panel, or from `Cursor Settings > Rules, Commands > + Add Rule`. Best practices: keep rules under 500 lines, split large rules into composable smaller ones, provide concrete examples, avoid vague guidance, reference files instead of copying content.
Team Rules (Enterprise/Business plans) apply across all repositories, support glob patterns, and can be enforced by team admins.
## Key quotations
- "Each rule is a markdown file that you can name anything you want. Cursor supports `.md` and `.mdc` extensions."
- "Use `.mdc` files with frontmatter to specify `description` and `globs` for more control over when rules are applied."
- "Keep rules under 500 lines. Split large rules into multiple, composable rules."
- "Reference files instead of copying their contents - this keeps rules short and prevents them from becoming stale."
## Annotations for weapon-forge
- This is the primary source for `guides/02-rule-file-authoring.md`. All frontmatter field specs should cite this doc.
- The four-mode table (Always Apply / Apply Intelligently / Apply to Specific Files / Apply Manually) is the canonical taxonomy - use it verbatim in the guide.
- The glob pattern table should be reproduced in the authoring guide with examples.
- The `/create-rule` slash command should be mentioned in the "how to create a rule" workflow in guide 02.
- Contrast with `.cursorrules` (legacy): docs mention it as still supported but not the preferred path.
research/external/2026-05-20-cursor-sdk-official-docs.md
---
source_type: official-docs
authority: high
relevance: high
topic: sdk-api
url: https://cursor.com/docs/sdk/typescript.md
fetched: 2026-05-20
---
# Cursor SDK Official TypeScript Documentation
## Summary
The official SDK docs define the complete `@cursor/sdk` public API surface. The SDK entered public beta on April 29, 2026 (npm: `1.0.7` first published April 26, 2026). It exposes the same agent runtime that powers Cursor's desktop, CLI, and web app as a programmable TypeScript library.
**Core API:**
- `Agent.create(options: AgentOptions): Promise<SDKAgent>` - validates options, returns handle; pass `local` or `cloud` to pick runtime
- `Agent.prompt(message, options?)` - one-shot convenience: create, send, wait, dispose
- `Agent.resume(agentId, options?)` - resume across process boundaries
- `agent.send(message)` - returns a `Run`; agent retains conversation context across runs
- `run.stream()` - async generator of `SDKMessage` events (discriminated on `type`)
- `run.wait()` - resolves to terminal `RunResult`
- `run.cancel()`, `run.conversation()`, `run.supports(op)`, `run.unsupportedReason(op)`
- `Agent.list()`, `Agent.listRuns()`, `Agent.getRun()`, `Agent.messages.list()`
**Event types from `run.stream()`:** `system`, `user`, `assistant`, `thinking`, `tool_call`, `status`, `task`, `request` - plus `onDelta` and `onStep` callbacks for lower-level token/step events.
**Error hierarchy:** All extend `CursorAgentError { isRetryable, code, cause, protoErrorCode }`. Subtypes: `AuthenticationError`, `RateLimitError`, `ConfigurationError`, `AgentBusyError` (HTTP 409, code `agent_busy`, `isRetryable: false`), `IntegrationNotConnectedError`, `NetworkError`, `UnknownAgentError`.
**AgentBusyError note:** Cloud agents allow only one active run at a time. Local agents do not return `agent_busy`; use `send({ local: { force: true } })` as recovery.
**Runtime options:** `local: { cwd, settingSources }` vs `cloud: { repos, autoCreatePR, skipReviewerRequest }`. Model is required for local, optional for cloud.
## Key quotations
- "`Agent.create()` validates options and returns a handle immediately. Pass either `local` or `cloud` to pick a runtime."
- "All SDK errors extend `CursorAgentError`. Use `isRetryable` to drive retry logic."
- "Local agents do not return `agent_busy`. Use `send({ local: { force: true } })`"
- "`run.stream()` yields normalized `SDKMessage` events. For lower-level updates (per-token text, tool-call args streaming in, thinking deltas, step boundaries), pass `onDelta` and `onStep` callbacks to `send()`"
## Annotations for weapon-forge
- This is the primary source for `guides/04-sdk-api.md`. All API signatures should be derived from here.
- The `AgentBusyError` / cloud-one-run-at-a-time constraint is a critical gotcha for multi-run scripts - include a dedicated subsection.
- The `onDelta` + `onStep` callbacks for lower-level streaming are not widely documented - include them in guide 04.
- Confirm: streaming DOES include partial tool-call results via `tool_call` type events (answers the open question from the Command Brief).
- The `settingSources` field under `local` (not top-level) is a subtle API gotcha - mention in guide 04.
research/external/2026-05-20-cursor-subagents-docs.md
---
source_type: official-docs
authority: high
relevance: high
topic: modes-and-agents
url: https://cursor.com/docs/agent/subagents
fetched: 2026-05-20
---
# Subagents - Cursor Official Documentation
## Summary
Official documentation for Cursor subagents. Subagents run in foreground (blocks, returns result) or background (returns immediately, works independently) mode. Three built-in subagents: `explore` (codebase search), `bash` (shell commands), `browser` (browser automation). Since Cursor 2.5, subagents can launch child subagents (nested tree of coordinated work).
**Custom subagent file format** (`.cursor/agents/<name>.md`):
YAML frontmatter fields:
- `name` (string, optional, default from filename): display name and identifier; use lowercase + hyphens
- `description` (string, optional): short description shown in Task tool hints; agent reads this to decide delegation
- `model` (string, optional, default `inherit`): `inherit` or specific model ID
- `readonly` (boolean, optional, default `false`): restricted write permissions if true
- `is_background` (boolean, optional, default `false`): run in background without blocking parent
**Scope locations:**
- Project: `.cursor/agents/` (also `.claude/agents/` and `.codex/agents/` for compatibility)
- User: `~/.cursor/agents/` (all projects)
- Project takes precedence over user; `.cursor/` takes precedence over `.claude/` and `.codex/`
**Background behavior:** Background subagents write state to `~/.cursor/subagents/`. Parent agent can read these files to check progress. Can resume after completion with preserved context.
**Parallel execution:** Multiple background subagents run simultaneously; parent agent can coordinate results.
## Key quotations
- "Create a subagent file at .cursor/agents/verifier.md with YAML frontmatter (name, description) followed by the prompt."
- "Since Cursor 2.5, subagents can launch child subagents to create a tree of coordinated work."
- "Project subagents take precedence when names conflict. When multiple locations contain subagents with the same name, `.cursor/` takes precedence over `.claude/` or `.codex/`."
- "Background subagents write output to `~/.cursor/subagents/`. The parent agent can read these files to check progress."
## Annotations for weapon-forge
- The subagent file format (`.cursor/agents/*.md`) is the same format used to create Guild Guardians - this is a key connection to document in guide 05.
- The `is_background` frontmatter field enables fire-and-forget subagent delegation - important for the background agent workflow in guide 05.
- The `.claude/agents/` and `.codex/agents/` compatibility locations mean subagents defined for Claude Code also work in Cursor - note this for teams migrating.
- The `readonly` flag is important for safe delegation of research/audit tasks that should not modify files.
- Built-in `explore`, `bash`, `browser` subagents should be mentioned in guide 05 as zero-config capabilities.
research/index.md
# Research Index: cursor-ide-weapon
Generated by loremaster on 2026-05-20. Updated after every file write.
## Internal Sources (4 files)
| File | Source type | Authority | Relevance | Topic |
|------|-------------|-----------|-----------|-------|
| `internal/2026-05-20-command-brief-analysis.md` | internal-artifact | high | high | weapon-scope |
| `internal/2026-05-20-live-mcp-config.md` | internal-artifact | high | high | mcp-integration |
| `internal/2026-05-20-live-rule-file.md` | internal-artifact | high | high | rule-file-authoring |
| `internal/2026-05-20-cursor-sdk-skill.md` | internal-artifact | high | high | sdk-api |
## External Sources (9 files)
| File | Source type | Authority | Relevance | Topic |
|------|-------------|-----------|-----------|-------|
| `external/2026-05-20-cursor-rules-official-docs.md` | official-docs | high | high | rule-file-authoring |
| `external/2026-04-10-cursorrules-vs-mdc-migration.md` | blog | high | high | rule-file-authoring |
| `external/2026-02-06-cursor-rules-design-dev-guide.md` | blog | medium | high | rule-file-authoring |
| `external/2026-05-20-cursor-sdk-official-docs.md` | official-docs | high | high | sdk-api |
| `external/2026-04-29-cursor-sdk-launch-blog.md` | blog | high | high | sdk-api |
| `external/2026-05-20-cursor-mcp-official-docs.md` | official-docs | high | high | mcp-integration |
| `external/2026-05-18-cursor-mcp-complete-setup-guide.md` | blog | medium | high | mcp-integration |
| `external/2026-04-02-cursor-3-agents-window.md` | blog | high | high | modes-and-agents |
| `external/2026-05-20-cursor-subagents-docs.md` | official-docs | high | high | modes-and-agents |
| `external/2026-05-20-cursor-keyboard-shortcuts-docs.md` | official-docs | high | high | keybindings |
| `external/2026-05-14-cursor-agent-modes-deep-dive.md` | blog | high | high | modes-and-agents |
| `external/2026-05-18-cursor-mcp-complete-setup-guide.md` | blog | medium | high | mcp-integration |
## Coverage by topic
| Topic | Files | Guides covered |
|-------|-------|---------------|
| rule-file-authoring | 4 | guides/01, guides/02 |
| sdk-api | 3 | guides/04 |
| mcp-integration | 3 | guides/03 |
| modes-and-agents | 3 | guides/05 |
| keybindings | 1 | guides/05 |
| weapon-scope | 1 | all |
research/internal/2026-05-20-command-brief-analysis.md
---
source_type: internal-artifact
authority: high
relevance: high
topic: weapon-scope
url: ai-tools/command-briefs/cursor-ide-guardian-command-brief.md
fetched: 2026-05-20
---
# cursor-ide-guardian Command Brief Analysis
## Summary
The Command Brief establishes `cursor-ide-guardian` as the Guild Guild's resident expert on Cursor IDE itself (not on the code Cursor produces). The Guardian owns six surface areas: project rules (`.cursorrules` legacy + `.cursor/rules/*.mdc` modern), custom modes, MCP server registration, agent-panel and background-agent workflows, keybindings and productivity patterns, and the `@cursor/sdk` API. The paired Weapon `cursor-ide-weapon` encodes all six areas as a knowledge repository the Guardian reads before acting.
The brief calls for six guide files:
1. `guides/01-principles.md` - rule file philosophy, alwaysApply vs glob-scoped, context window cost
2. `guides/02-rule-file-authoring.md` - full frontmatter spec, glob patterns, migration from `.cursorrules`
3. `guides/03-mcp-integration.md` - mcp.json schema, tool JSON Schema authoring, stdio vs SSE, gotchas
4. `guides/04-sdk-api.md` - Agent lifecycle, run.stream, CursorAgentError, local vs cloud runtime
5. `guides/05-modes-and-productivity.md` - custom mode JSON, keybindings, inline chat vs agent panel decision tree
6. `guides/06-extension-development.md` - manifest structure, plugin quality gates, marketplace submission
## Key quotations
- "Never write `.cursorrules` for a project that already uses `.cursor/rules/`.": the two formats are not additive; the modern format takes precedence and having both causes confusing precedence behaviour."
- "Prefer `alwaysApply: false` with narrow globs over `alwaysApply: true` for all new rules. Why: `alwaysApply: true` rules inflate every agent context window."
- "When scaffolding MCP servers, always include a `tools` array with explicit JSON Schema for every parameter. Why: Cursor will silently reject tools with malformed schemas, and the error is not surfaced in the UI."
## Annotations for weapon-forge
- The five critical directives (lines 50-55) should become a numbered checklist in `guides/01-principles.md`.
- Open question: "Does Cursor SDK support streaming partial tool-call results, or only final assistant messages?" - research confirms: yes, `run.stream()` yields `SDKMessage` events including `assistant`, `thinking`, `tool_call`, `status`, `task`, `request` types - partial tool-call results ARE streamed.
- Open question: "Is there a stable way to detect which Cursor plan tier is active from within an SDK agent run?" - NOT answered by research; should be flagged as open question for weapon-forge.
- The suggested worked example of an MCP server exposing `run_security_scan` bridging `security-guardian` via SDK should be included in `guides/03-mcp-integration.md` as a capstone example.
research/internal/2026-05-20-cursor-sdk-skill.md
---
source_type: internal-artifact
authority: high
relevance: high
topic: sdk-api
url: C:/Users/mario/.cursor/plugins/cache/cursor-public/cursor-sdk/d1cdb88a9eb33cf392395c87e3fd76419fc1010e/skills/cursor-sdk/SKILL.md
fetched: 2026-05-20
---
# Installed cursor-sdk Skill (Cursor Plugin)
## Summary
The workspace has the official Cursor SDK plugin installed, which includes a `cursor-sdk` SKILL.md. This is the authoritative in-IDE reference for `@cursor/sdk` and defines the three invocation patterns, top five traps, local vs cloud runtime distinction, auth setup, model selection, and production best practices. `cursor-ide-weapon`'s `guides/04-sdk-api.md` should align with and extend this skill - not duplicate it.
## Key quotations
- "Three Invocation Patterns: (1) `Agent.prompt()` - one-shot, (2) `Agent.create()` + `agent.send()` - durable with follow-ups, (3) `Agent.resume()` - pick up an existing agent later."
- "Top Five Traps: (1) Missing `cloud: { repos }` silently defaults to local, (2) Two different kinds of failure (CursorAgentError vs result.status === 'error'), (3) Forgetting `await agent[Symbol.asyncDispose]()` leaks resources, (4) Streaming is optional but `wait()` is (almost) required, (5) Not every run operation is supported on every runtime."
- "Inline `mcpServers` are not persisted across resume - pass them again on the resume call."
- "The SDK holds handles to local executors, persisted run stores, and cloud API clients."
## Key SDK API surface
- `Agent.create(options)` - returns `SDKAgent` immediately
- `agent.send(message)` - returns a `Run`
- `run.stream()` - async generator of `SDKMessage` events
- `run.wait()` - resolves to terminal `RunResult`
- `run.cancel()` - cancels if supported
- `run.supports("cancel"|"stream"|"wait"|"conversation")` - capability check
- `Agent.prompt(message, options)` - one-shot convenience
- `Agent.resume(agentId, options)` - resume across process boundaries
- `Agent.list()`, `Agent.listRuns()`, `Agent.getRun()`, `Agent.messages.list()` - inspection
## Annotations for weapon-forge
- `guides/04-sdk-api.md` should explicitly cross-reference the cursor-sdk skill rather than re-authoring the same content.
- The skill's "What This Skill Doesn't Cover" section (Cloud Agents REST API, `.cursor/hooks.json`, private workers, non-TS SDKs) should be mirrored as a "handoff boundaries" section in guide 04.
- The `run.supports()` guard pattern is critical for `weapon-forge` to include in examples - runtime capabilities differ.
- The `CursorAgentError` subclass taxonomy (AuthenticationError, RateLimitError, ConfigurationError, AgentBusyError, IntegrationNotConnectedError, NetworkError, UnknownAgentError) from the official docs should be the authoritative list in guide 04.
research/internal/2026-05-20-live-mcp-config.md
---
source_type: internal-artifact
authority: high
relevance: high
topic: mcp-integration
url: C:/Users/mario/.cursor/mcp.json
fetched: 2026-05-20
---
# Live mcp.json Configuration (User-Global)
## Summary
The user's global `~/.cursor/mcp.json` demonstrates real-world MCP server registration patterns across four transport types. This is a production example that `weapon-forge` can use to derive concrete examples and gotchas for `guides/03-mcp-integration.md`.
Seven servers are registered:
1. **GitKraken** (stdio, absolute path to `.exe`): Shows the Windows path pattern and `--host=cursor` arg for IDE-aware servers.
2. **Chrome DevTools** (stdio, `npx` with `@latest`): Shows the `npx -y` shorthand for zero-install servers.
3. **perplexity** (stdio, `npx`, env var `PERPLEXITY_API_KEY`): Shows env-based secret injection.
4. **Supabase** (remote HTTP, `url` field only, empty `headers`): Shows the minimal remote server config; demonstrates that `headers` can be an empty object when auth is handled differently.
5. **replicate** (remote HTTP via `mcp-remote@latest` wrapper): Shows the pattern of wrapping SSE endpoints with `mcp-remote` for clients that only support stdio.
6. **cloudflare-api** (remote HTTP, URL only): Another minimal remote server, Cloudflare-hosted.
7. **userback** (remote HTTP, trailing slash in URL): Real example that path-including URLs are valid.
8. **dbhub-bayleebooks** (stdio, `@bytebase/dbhub`, long arg list including DSN): Shows how database connection strings are passed as args rather than env vars.
9. **beeper** (remote HTTP, localhost URL): Shows localhost HTTP servers for locally-running daemons.
## Key observations
- No `type: "stdio"` field is needed for stdio servers; it is the default and Cursor infers it from presence of `command`.
- Sensitive credentials appear in both `env` (perplexity key) and `args` (database DSN). The `args` approach is less secure; `env` is preferred.
- Remote servers with `url` field do NOT need `command` or `args`.
- The `headers` field on remote servers is optional; an empty object `{}` is valid.
- No `disabled` flags are present; all servers are active.
## Annotations for weapon-forge
- Use GitKraken and perplexity entries as stdio examples in `guides/03-mcp-integration.md`.
- Use Supabase and cloudflare-api entries as minimal remote server examples.
- Use replicate (`mcp-remote` wrapper) as the SSE-via-stdio pattern example.
- Note the DSN-in-args antipattern from dbhub; flag it in the security section of guide 03.
- The `beeper` localhost entry is a good example of local daemon registration.
research/internal/2026-05-20-live-rule-file.md
---
source_type: internal-artifact
authority: high
relevance: high
topic: rule-file-authoring
url: c:/Users/mario/GitHub/guild-code/.cursor/rules/no-em-dashes.mdc
fetched: 2026-05-20
---
# Live .mdc Rule File: no-em-dashes
## Summary
The `no-em-dashes.mdc` file in this repository is a canonical example of an `alwaysApply: true` rule. It demonstrates the complete MDC format in practice: YAML frontmatter with two fields (`description` and `alwaysApply`), a clear natural-language rule title, and rich body content with BAD/GOOD examples, a substitution table, and exception cases. This rule is replicated across all three workspace repos (`guild-code`, `guild-website`, `vibe-code-training`), demonstrating the pattern of shared rules maintained in parallel.
## Key observations
- **Frontmatter fields used:** `description` (one sentence) and `alwaysApply: true`. No `globs` field because this rule applies regardless of file type.
- **Description content:** "Never use em dashes (or en dashes) in prose written for the user" - concise, action-oriented, directly tells the agent what NOT to do.
- **Body structure:** H1 title, problem statement, substitution table with BAD/GOOD examples per scenario, exceptions section, self-check instruction. This structure is a model template for other rules.
- **Token cost:** The file is ~430 words / ~600 tokens. As an `alwaysApply: true` rule, it occupies context budget in every session.
- **Cross-repo duplication:** Same file in `.cursor/rules/` across 3 repos. This is acceptable for universal prose rules but would be better served by a Team Rule (Enterprise) if the organization grows.
## Annotations for weapon-forge
- Use this as the worked example in `guides/02-rule-file-authoring.md` showing a complete, production-quality `alwaysApply: true` rule.
- The token budget concern (600 tokens always consumed) is worth noting in `guides/01-principles.md` under the "cost of alwaysApply" section.
- The BAD/GOOD example pattern in the rule body is the recommended style for writing rule content - mention this in guide 02.
- The cross-repo duplication pattern (vs. Team Rules) should be called out as a migration path consideration.
research/research-plan.md
# Research Plan: cursor-ide-weapon
- **Depth tier:** normal
- **Time window:** 2025-11-01 back to 2026-05-20 (6 months); timeless official docs included regardless of date
- **Page budget target:** 8-12 source notes total (internal + external)
- **Source breadth target:** official docs, SDK npm page, community blog posts, MCP spec, internal Guild rule files and MCP configs
## Initial queries (from backlog / command brief)
1. "Cursor IDE rules system .cursorrules project rules 2026 best practices"
2. "Cursor SDK extension API developer documentation 2026"
3. "Cursor MCP server registration custom tools 2026"
4. "Cursor IDE custom modes agent panels background agents 2026"
5. "Cursor IDE keybindings productivity power user shortcuts 2026"
## Canonical reference URLs (from Command Brief)
- https://docs.cursor.com (rules, MCP, modes, SDK)
- https://www.npmjs.com/package/@cursor/sdk
- https://docs.cursor.com/context/model-context-protocol
- https://docs.cursor.com/context/rules-for-ai
- https://docs.cursor.com/agent
- https://modelcontextprotocol.io/docs
## Expansion queries (authored by loremaster)
### Branch from "Cursor IDE rules system .cursorrules project rules 2026 best practices"
- "cursor .cursor/rules mdc frontmatter alwaysApply globs 2026"
- "migrate .cursorrules to cursor rules folder 2026"
### Branch from "Cursor SDK extension API developer documentation 2026"
- "@cursor/sdk Agent.create run.stream CursorAgentError 2026"
- "cursor sdk local vs cloud runtime MCP per-run config 2026"
### Branch from "Cursor MCP server registration custom tools 2026"
- "cursor mcp.json tool schema JSON Schema stdio SSE 2026"
- "cursor MCP server authentication tool name limits 2026"
### Branch from "Cursor IDE custom modes agent panels background agents 2026"
- "cursor custom mode JSON system prompt tool allowlist 2026"
- "cursor background agent workflow best practices 2026"
### Branch from "Cursor IDE keybindings productivity power user shortcuts 2026"
- "cursor inline chat vs agent panel vs background agent decision 2026"
- "cursor IDE power user tips 2026"
## Internal artifacts to capture
1. Representative `.cursor/rules/*.mdc` files in this repo
2. Any `mcp.json` configs present in the workspace
3. The cursor-sdk SKILL.md already installed in this workspace
4. The dms-hand-weapon structure (referenced in Command Brief as cross-reference)
research/research-summary.md
# Research Summary: cursor-ide-weapon
Generated by loremaster on 2026-05-20.
## Depth consumed
- **Tier:** normal
- **Time window:** 2025-11-01 to 2026-05-20 (6 months + timeless official docs)
- **Files written:** 13 total (4 internal, 9 external across `internal/` and `external/`)
## Files written by subfolder
| Subfolder | Count | Topics |
|-----------|-------|--------|
| `internal/` | 4 | weapon-scope, mcp-integration, rule-file-authoring, sdk-api |
| `external/` | 9 | rule-file-authoring (3), sdk-api (2), mcp-integration (2), modes-and-agents (3), keybindings (1) |
| Root | 3 | research-plan.md, index.md, research-summary.md |
## Five most influential sources
### 1. Cursor Rules Official Docs (`external/2026-05-20-cursor-rules-official-docs.md`)
**Why it matters:** The single authoritative definition of the `.cursor/rules/` system - the four activation modes (Always Apply / Apply Intelligently / Apply to Specific Files / Apply Manually), the three frontmatter fields (`alwaysApply`, `description`, `globs`), and the interaction table. Every frontmatter spec in `guides/02-rule-file-authoring.md` derives from this source.
### 2. Cursor SDK Official TypeScript Docs (`external/2026-05-20-cursor-sdk-official-docs.md`)
**Why it matters:** The complete `@cursor/sdk` API surface including `CursorAgentError` subclass taxonomy, `AgentBusyError` cloud constraint, `onDelta`/`onStep` low-level streaming callbacks, `run.supports()` guard pattern, and `settingSources` under `local` (not top-level). This is the authoritative API reference for `guides/04-sdk-api.md`.
### 3. `.cursorrules` vs MDC Migration Guide (`external/2026-04-10-cursorrules-vs-mdc-migration.md`)
**Why it matters:** Contains the single most critical warning for the weapon's audience: `.cursorrules` is silently ignored in Agent mode. Any practitioner still using `.cursorrules` loses all their rules the moment they use agentic workflows. The 2,000-token budget warning for `alwaysApply: true` rules is also here.
### 4. Cursor MCP Official Documentation (`external/2026-05-20-cursor-mcp-official-docs.md`)
**Why it matters:** Authoritative `mcp.json` field specs for both stdio and remote server types, config interpolation variable syntax (`${env:NAME}`, `${workspaceFolder}`, etc.), static OAuth `auth` object (new in 2026), and the programmatic Extension API (`vscode.cursor.mcp.registerServer`). The primary source for `guides/03-mcp-integration.md`.
### 5. Cursor 3 Agents Window Guide (`external/2026-04-02-cursor-3-agents-window.md`)
**Why it matters:** Documents the Cursor 3.0 (April 2, 2026) architectural shift: Background Agents renamed to Cloud Agents, Agents Window as the new primary interface, `/multitask`/`/worktree`/`/best-of-n` slash commands, and the local-to-cloud agent handoff workflow. Without this source, `guides/05-modes-and-productivity.md` would use outdated Cursor 2.0 terminology.
## Five open questions for weapon-forge to address
1. **Plan tier detection from SDK:** Is there a stable way to detect which Cursor plan tier (Free / Pro / Business / Enterprise) is active from within an SDK agent run? The Command Brief asked; research did not find a documented API for this. The `@cursor/sdk` docs make no mention of tier introspection. This may require confirming with Cursor's engineering docs or flagging as "not publicly documented."
2. **Tool name length limits and name conflict resolution for MCP:** The Command Brief mentions "tool name length limits" as a Cursor-specific MCP gotcha. Research found no specific documented limit. The general recommendation from the MCP ecosystem is to keep tool names under 64 characters and namespace them (e.g., `server-name.tool-name`). weapon-forge should either confirm this limit or note it as unverified.
3. **Custom modes JSON file format:** Cursor's official docs mention `We're considering adding a .cursor/modes.json file` but this was not confirmed as shipped. The current method is UI-only (Settings > Features > Chat > Custom Modes > Add custom mode). weapon-forge should verify whether `.cursor/modes.json` exists as of May 2026 before documenting it in guide 05.
4. **Extension development guide (guide 06) source gap:** The research found the `vscode.cursor.mcp.registerServer` Extension API and the plugin path registration API (`vscode.cursor.plugins.registerPath`), but did not find a comprehensive guide to the full Cursor extension/plugin manifest format and marketplace submission checklist. The Command Brief's `guides/06-extension-development.md` will need additional sources; weapon-forge should consult `https://cursor.com/docs/plugins` directly.
5. **SDK streaming partial tool-call results (RESOLVED):** The Command Brief asked "Does Cursor SDK support streaming partial tool-call results?" - Research confirms YES: `run.stream()` yields `tool_call` type events with `callId`, `name`, `status` (`running`|`completed`), `args`, and `result`. The Cloud Agents API SSE stream also confirms this with a detailed `ToolCallEventData` interface.
## Sources weapon-forge should re-fetch with deeper context
- `https://cursor.com/docs/plugins` - full plugin manifest schema for `guides/06-extension-development.md`
- `https://cursor.com/docs/agent/cloud` or equivalent - Cloud Agent setup steps for `guides/05-modes-and-productivity.md`
- `https://cursor.com/docs/context/rules-for-ai` - the legacy rules-for-ai doc to understand the transition from `.cursorrules` and any additional nuances
SKILL.md
---
name: cursor-ide-weapon
description: Equips cursor-ide-guardian to master Cursor IDE as a development platform — project rules (.cursorrules migration, .cursor/rules/*.mdc authoring), custom modes, MCP server integration, Cloud Agents and the Agents Window, keybindings and productivity patterns, and the @cursor/sdk API for programmatic agent automation. Use when the user asks about configuring Cursor, extending it with MCP tools, building automations with the SDK, or maximising their IDE workflow. Do NOT use for code quality of what agents produce (language guardians), prompt engineering for external LLMs (mind-guardian), or CI/CD pipelines that happen to run SDK jobs (devops-guardian).
license: MIT
---
# cursor-ide Weapon
The knowledge repository for `cursor-ide-guardian`. Covers every platform surface of Cursor IDE: rule files, MCP integration, SDK authoring, Agents Window workflows, and productivity patterns.
## When this weapon applies
Load whenever `cursor-ide-guardian` is invoked. Typical triggers (any of these phrases, even without naming Cursor explicitly):
- "review my `.cursorrules`" / "migrate my rules to MDC"
- "add an MCP server" / "register a custom tool in Cursor"
- "build an automation with the Cursor SDK" / "`Agent.create`" / "`@cursor/sdk`"
- "create a custom mode" / "design a Cursor mode for X"
- "background agents" / "cloud agents" / "Agents Window" / `/multitask`
- "Cursor keybindings" / "Cursor shortcuts" / "power user Cursor"
- "Cursor plugin" / "Cursor extension"
Do NOT load for:
- Code quality produced by Cursor agents (language-specific guardians).
- Prompt engineering for OpenAI / Anthropic / etc. (mind-guardian).
- CI/CD pipelines that orchestrate Cursor SDK (devops-guardian owns the pipeline; this weapon authors the SDK code itself).
## First action when loaded
Read in order before acting:
1. **`guides/01-principles.md`** — rule file philosophy, context budget constraints, the MDC vs `.cursorrules` decision, activation mode taxonomy. This is the mental model foundation.
2. **`guides/02-rule-file-authoring.md`** — full frontmatter spec, glob patterns, migration checklist from legacy `.cursorrules`, anti-patterns.
3. Then pull the task-specific guide: `03` for MCP, `04` for SDK, `05` for modes/productivity, `06` for extensions.
## Folder layout
```text
cursor-ide-weapon/
+- SKILL.md (this file — master index)
+- guides/
| +- 01-principles.md (philosophy: rule activation, context budget, MDC vs legacy)
| +- 02-rule-file-authoring.md (frontmatter spec, glob patterns, migration)
| +- 03-mcp-integration.md (mcp.json schema, tool authoring, OAuth, Extension API)
| +- 04-sdk-api.md (Agent lifecycle, run.stream, errors, local vs cloud)
| +- 05-modes-and-productivity.md (custom modes, Agents Window, keybindings, slash commands)
| +- 06-extension-development.md (plugin manifests, quality gates, marketplace checklist)
+- examples/
| +- rule-file-examples.md (worked .mdc examples for common scenarios)
| +- mcp-server-example.md (minimal TypeScript MCP server + mcp.json entry)
| +- sdk-agent-example.md (create, stream, error-handle pattern)
+- templates/
| +- rule-file-template.mdc (canonical .mdc frontmatter template)
| +- mcp-json-template.json (mcp.json with both stdio and remote stubs)
| +- sdk-script-template.ts (Agent.create + run.stream + error handling)
+- reports/
| +- README.md
+- research/ (populated by loremaster, 18 files)
+- research-plan.md
+- research-summary.md
+- index.md
+- internal/ (4 files)
+- external/ (11 files)
```
## Critical directives (lifted from the Command Brief)
These are weapon-level non-negotiables that `cursor-ide-guardian` must enforce on every invocation:
- **Check Cursor version before referencing features.** Why: Cursor ships weekly; Cloud Agents, Agents Window, and SDK capabilities are version-gated. Use Cursor 3 (April 2026+) as the modern baseline.
- **Never write `.cursorrules` for a project already using `.cursor/rules/`.** Why: `.cursorrules` is silently ignored in Agent mode and the two formats produce silent precedence conflicts.
- **MCP tools must have explicit JSON Schema for every parameter.** Why: Cursor silently rejects tools with malformed schemas with no UI feedback.
- **Prefer `alwaysApply: false` with narrow globs over `alwaysApply: true`.** Why: `alwaysApply: true` rules consume the shared context budget (2,000-token cap across all `alwaysApply` rules).
- **Always show `CursorAgentError` handling in SDK examples.** Why: SDK runs fail silently without it.
## Key facts by domain (quick reference)
### Rules
| Format | Agent mode? | Multi-file? | Glob scoping? |
|---|---|---|---|
| `.cursorrules` | No (silently ignored) | No | No |
| `.cursor/rules/*.mdc` | Yes | Yes | Yes |
Four MDC activation modes (frontmatter drives which one applies):
| Mode | `alwaysApply` | `globs` | `description` |
|---|---|---|---|
| Always Apply | `true` | any | any |
| Apply to Specific Files | `false` | set | any |
| Apply Intelligently | `false` | unset | set |
| Apply Manually | `false` | unset | unset |
**Budget:** keep total `alwaysApply: true` content under ~2,000 tokens across all rule files.
### MCP
Config hierarchy: project `.cursor/mcp.json` > global `~/.cursor/mcp.json` (same-name project wins). Restart Cursor after editing either file. Tool auto-approval is off by default (Settings > MCP > allow tool auto-run). Interpolation variables: `${env:NAME}`, `${userHome}`, `${workspaceFolder}`, `${workspaceFolderBasename}`, `${pathSeparator}`.
### SDK (`@cursor/sdk` >= 1.0.7, public beta April 29, 2026)
```typescript
const agent = await Agent.create({ local: { cwd, model: "claude-sonnet-4-5" } });
const run = agent.send("do X");
for await (const msg of run.stream()) {
if (msg.type === "assistant") process.stdout.write(msg.text ?? "");
}
await run.wait(); // resolves RunResult
await agent.dispose();
```
Error handling: all errors extend `CursorAgentError { isRetryable, code }`. Cloud agents: one active run at a time — watch for `AgentBusyError` (code: `agent_busy`, `isRetryable: false`).
### Agents Window (Cursor 3, April 2026)
- Background Agents renamed to **Cloud Agents** in Cursor 3.
- **Agents Window**: unified sidebar for all agents (local, cloud, mobile, Slack, GitHub, Linear).
- **Agent Tabs**: tiled multi-pane layout (added April 13, 2026).
- **`/multitask`**: async parallel subagents within a single task.
- Cloud Agents: isolated Ubuntu VMs, dedicated `agent/` branch, auto-PR on completion.
## Open questions (from research)
1. **Plan tier detection from SDK:** No documented public API for detecting Free / Pro / Business / Enterprise from within an SDK run. Flag as "not publicly documented" in guide 04.
2. **MCP tool name length:** No specific Cursor-documented limit found; best practice is <64 chars, namespace with `server-name.tool-name`.
3. **Custom modes file format:** `.cursor/modes.json` was "under consideration" as of May 2026; current method is UI-only (Settings > Features > Chat > Custom Modes). Do not document the file path until confirmed.
4. **Extension guide source gap:** `vscode.cursor.plugins.registerPath` Extension API found; full manifest schema needs direct fetch from `cursor.com/docs/plugins`.
## Refresh cadence
- Guides `01`-`05`: refresh every 3 months or on any Cursor major version.
- Guide `06`: refresh when extension/plugin manifest format changes.
- Research folder: re-run `loremaster` at `shallow` tier on any Cursor major release.
## Pairing
| Role | Artifact |
|---|---|
| This weapon | `ai-tools/skills/cursor-ide-weapon/` |
| Paired Guardian | `ai-tools/agents/cursor-ide-guardian.md` |
| Command Brief | `ai-tools/command-briefs/cursor-ide-guardian-command-brief.md` |
| Cursor SDK skill (installed) | `.cursor/skills-cursor/sdk/SKILL.md` |
| create-rule skill | `.cursor/skills-cursor/create-rule/SKILL.md` |
---
*Forged by `weapon-forge` from `cursor-ide-guardian-command-brief.md` and `research/`. Part of the Guild AI Tools Factory by [Mario Aldayuz a.k.a @thenotoriousllama](https://github.com/thenotoriousllama).*
templates/mcp-json-template.json
{
"mcpServers": {
"stdio-example": {
"command": "node",
"args": ["${workspaceFolder}/scripts/mcp-server.js"],
"env": {
"API_KEY": "${env:MY_API_KEY}",
"PROJECT_ROOT": "${workspaceFolder}"
}
},
"remote-example": {
"url": "https://my-mcp.example.com/sse",
"headers": {
"Authorization": "Bearer ${env:REMOTE_TOKEN}"
}
},
"oauth-example": {
"url": "https://my-oauth-mcp.example.com/sse",
"auth": {
"clientId": "${env:MCP_CLIENT_ID}",
"clientSecret": "${env:MCP_CLIENT_SECRET}",
"scopes": ["read", "write"]
}
}
}
}
templates/rule-file-template.mdc
---
description: Canonical .mdc frontmatter template for cursor-ide-guardian. Copy and fill in.
globs: "**/*.mdc"
alwaysApply: false
---
# Rule: [Rule Name]
<!--
FRONTMATTER GUIDE:
alwaysApply: true → Always included in every context (budget: ~2,000 tokens total across all alwaysApply rules)
alwaysApply: false + globs set → Apply to Specific Files (fires when a matching file is in context)
alwaysApply: false + description set (no globs) → Apply Intelligently (AI reads description and decides)
alwaysApply: false + no description + no globs → Apply Manually (@mention in chat to load)
GLOB EXAMPLES:
"**/*.ts, **/*.tsx" → all TypeScript files
"src/**" → everything under src/
"**/*.{ts,tsx,js}" → TS and JS files
"*.md" → markdown in project root only
Keep this rule under 500 lines.
Reference files with @filename instead of copying content inline.
-->
[Your rule content here. Be specific. Use concrete examples. Avoid vague directives like "write good code".]
templates/sdk-script-template.ts
import { Agent, CursorAgentError, AgentBusyError, RateLimitError } from "@cursor/sdk";
import * as path from "path";
// --- Configuration ---
const PROJECT_ROOT = path.resolve(__dirname, "..");
const MODEL = "claude-sonnet-4-5"; // Required for local runtime
async function main(): Promise<void> {
let agent: Awaited<ReturnType<typeof Agent.create>> | null = null;
try {
// Create agent with local runtime
agent = await Agent.create({
local: {
cwd: PROJECT_ROOT,
model: MODEL,
// settingSources inherits project + user Cursor settings
settingSources: ["user", "project"],
},
});
// Send a task and stream output
const run = agent.send("Your task description here");
for await (const msg of run.stream()) {
if (msg.type === "assistant") process.stdout.write(msg.text ?? "");
if (msg.type === "tool_call") {
process.stderr.write(`[${msg.name}: ${msg.status}]\n`);
}
}
const result = await run.wait();
console.log(`\nDone. Status: ${result.status}`);
} catch (err) {
if (err instanceof AgentBusyError) {
// Cloud only: one active run at a time
console.error("Agent busy (cloud). Wait for current run to finish.");
} else if (err instanceof RateLimitError && err.isRetryable) {
console.error("Rate limited. Retry after back-off.");
} else if (err instanceof CursorAgentError) {
console.error(`[${err.code}] ${err.message} (retryable: ${err.isRetryable})`);
} else {
throw err;
}
} finally {
if (agent) await agent.dispose();
}
}
main().catch(console.error);