The Agent Skills Directory
npx skills add https://smithery.ai/skills/NangoHQ/creating-cursor-rules你是一位擅长创建高效 .cursor/rules 文件的专家,这些文件能帮助 AI 助手理解项目约定并生成更好的代码。
在以下情况使用:
.cursor/rules不适用于:
规则应提供具体指导,而非模糊建议。
❌ 不好 - 模糊:
Write clean code with good practices.
Use proper TypeScript types.
✅ 好 - 具体:
Use functional components with TypeScript.
Define prop types with interfaces, not inline types.
Extract custom hooks when logic exceeds 10 lines.
不要记录代码检查工具能处理的内容。记录架构决策。
❌ 不好 - 代码检查范畴:
Use semicolons in JavaScript.
Indent with 2 spaces.
Add trailing commas.
✅ 好 - 决策指导:
Choose Zustand for global state, React Context for component trees.
Use Zod for runtime validation at API boundaries only.
Prefer server components except for: forms, client-only APIs, animations.
将相关规则分组到清晰的章节中:
## Tech Stack
- Next.js 14 with App Router
- TypeScript strict mode
- Tailwind CSS for styling
## Code Style
- Functional components only
- Named exports (no default exports)
- Co-locate tests with source files
## Patterns
- Use React Server Components by default
- Client components: mark with "use client" directive
- Error handling: try/catch + toast notification
## Project Conventions
- API routes in app/api/
- Components in components/ (flat structure)
- Types in types/ (shared), components/*/types.ts (local)
Cursor 规则采用 MDC (.mdc) 格式编写,该格式支持 YAML 前置元数据和 Markdown 内容。元数据控制规则的应用方式和时机。
每个 Cursor 规则必须以 --- 标记之间的 YAML 前置元数据开头:
---
description: Brief description of when and how to use this rule
globs: ["**/*.ts", "**/*.tsx"]
alwaysApply: false
---
| 属性 | 类型 | 必需 | 描述 |
|---|---|---|---|
description | 字符串 | 是 | 规则用途的简要描述。AI 用于判断相关性。切勿使用 --- 或空字符串等占位符。 |
globs | 数组 | 否 | 触发自动附加的文件模式(例如 ["**/*.ts"])。如果不使用“自动附加”类型,请留空或省略。 |
alwaysApply | 布尔值 | 否 | 如果为 true,规则始终包含在上下文中。如果为 或省略,行为取决于规则类型。 |
使用 Cursor 中的类型下拉菜单控制规则的应用方式:
| 规则类型 | 描述 | 何时使用 |
|---|---|---|
| 始终 | 始终包含在模型上下文中 | 核心项目约定、技术栈、适用于所有地方的通用模式 |
| 自动附加 | 当引用与 globs 模式匹配的文件时包含 | 特定文件类型的规则(例如 React 组件、API 路由、测试文件) |
| 代理请求 | 对 AI 可用,AI 根据 description 决定是否包含 | 上下文相关模式、专门化工作流、可选约定 |
| 手动 | 仅在使用 @ruleName 明确提及时包含 | 很少使用的模式、实验性约定、遗留文档 |
始终规则(核心约定):
---
description: TypeScript and code style conventions for the entire project
alwaysApply: true
---
自动附加规则(文件模式特定):
---
description: React component patterns and conventions
globs: ["**/components/**/*.tsx", "**/app/**/*.tsx"]
alwaysApply: false
---
代理请求规则(上下文相关):
---
description: RPC service boilerplate and patterns for creating new RPC endpoints
globs: []
alwaysApply: false
---
手动规则(显式调用):
---
description: Legacy API migration patterns (deprecated, use for reference only)
globs: []
alwaysApply: false
---
描述是必需的 - AI 用它来确定相关性。要具体:
Backend codeFastify API route patterns, error handling, and validation using Zod策略性地使用 globs - 自动附加到相关文件类型:
["**/*.tsx", "**/*.jsx"]["**/api/**/*.ts", "**/routes/**/*.ts"]["**/*.test.ts", "**/*.spec.ts"]避免始终应用所有内容 - 谨慎使用 alwaysApply: true:
- 编写描述以帮助 AI 理解何时使用:
每个 Cursor 规则文件都应包含以下章节:
## Tech Stack
- Framework: Next.js 14
- Language: TypeScript 5.x (strict mode)
- Styling: Tailwind CSS 3.x
- State: Zustand
- Database: PostgreSQL + Prisma
- Testing: Vitest + Playwright
原因: 防止 AI 建议错误的工具/模式。
## Code Style
- **Components**: Functional with TypeScript
- **Props**: Interface definitions, destructure in params
- **Hooks**: Extract when logic > 10 lines
- **Exports**: Named exports only (no default)
- **File naming**: kebab-case.tsx
始终包含代码示例,而不仅仅是描述:
## Patterns
### Error Handling
```typescript
try {
const result = await operation();
toast.success('Operation completed');
return result;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
toast.error(message);
throw error; // Re-throw for caller to handle
}
// app/api/users/route.ts
export async function GET(request: Request) {
try {
// 1. Parse/validate input
// 2. Check auth/permissions
// 3. Perform operation
// 4. Return Response
} catch (error) {
return new Response(JSON.stringify({ error: 'Message' }), {
status: 500
});
}
}
避免这些常见错误:
❌ 过于明显:
- Write readable code
- Use meaningful variable names
- Add comments when necessary
- Follow best practices
❌ 过于严格:
- Never use any third-party libraries
- Always write everything from scratch
- Every function must be under 5 lines
❌ 与语言无关的建议:
- Use design patterns
- Think before you code
- Test your code
- Keep it simple
为新 Cursor 规则使用此模板:
# Project Name - Cursor Rules
## Tech Stack
[List all major technologies with versions]
## Code Style
[Specific style decisions]
## Project Structure
[Directory organization]
## Patterns
[Common patterns with code examples]
### Pattern Name
[Description + code example]
## Conventions
[Project-specific conventions]
## Common Tasks
[Frequent operations with step-by-step snippets]
### Task Name
1. Step one
2. Step two
[Code example]
## Anti-Patterns
[What to avoid and why]
## Testing
[Testing approach and patterns with examples]
## Tech Stack
**Framework:** Next.js 14 (App Router)
**Language:** TypeScript 5.x (strict mode enabled)
**Styling:** Tailwind CSS 3.x with custom design system
**State:** Zustand for global, React Context for component trees
**Forms:** React Hook Form + Zod validation
**Database:** PostgreSQL with Prisma ORM
**Testing:** Vitest (unit), Playwright (E2E)
**Deployment:** Vercel
**Key Dependencies:**
- `@tanstack/react-query` for server state
- `date-fns` for date manipulation (not moment.js)
- `clsx` + `tailwind-merge` for conditional classes
## Anti-Patterns
### ❌ Don't: Default Exports
```typescript
// ❌ BAD
export default function Button() { }
// ✅ GOOD
export function Button() { }
原因: 命名导出更易于重构,并支持更好的 Tree Shaking。
// ❌ BAD
function UserCard({ user }: { user: { name: string; email: string } }) { }
// ✅ GOOD
interface User {
name: string;
email: string;
}
function UserCard({ user }: { user: User }) { }
原因: 可重用性和可发现性。
包含常用操作的快捷方式:
## Common Tasks
### Adding a New API Route
1. Create `app/api/[route]/route.ts`
2. Define HTTP method exports (GET, POST, etc.)
3. Validate input with Zod schema
4. Use try/catch for error handling
5. Return `Response` object
```typescript
import { z } from 'zod';
const schema = z.object({
name: z.string().min(1)
});
export async function POST(request: Request) {
try {
const body = await request.json();
const data = schema.parse(body);
// Process...
return Response.json({ success: true });
} catch (error) {
if (error instanceof z.ZodError) {
return Response.json(
{ error: error.errors },
{ status: 400 }
);
}
return Response.json(
{ error: 'Internal error' },
{ status: 500 }
);
}
}
backend-api.mdc”)按关注点分解,而不是创建一个单一的大文件:
.cursor/rules/ ├── tech-stack.mdc # 核心技术 ├── typescript-patterns.mdc # 语言特定模式 ├── api-conventions.mdc # API 路由标准 ├── component-patterns.mdc # React/UI 模式 └── testing-standards.mdc # 测试方法
原因: 更易于维护、更新和在类似项目中重用。
始终包含以下内容,而不是模糊的指导:
有关示例,请参阅 components/auth/LoginForm.tsx❌ 不好 - 模糊:
Use proper error handling in API routes.
✅ 好 - 具体:
API routes must use try/catch with typed errors. Example:
```typescript
// app/api/users/route.ts (lines 10-25)
export async function POST(request: Request) {
try {
const data = await request.json();
return Response.json({ success: true });
} catch (error) {
return handleApiError(error); // See lib/errors.ts
}
}
有关完整实现,请参阅 app/api/products/route.ts。
规则应像技术文档一样阅读,而不是随意的建议:
思考: “新工程师能否在不提问的情况下理解这一点?”
如果你发现自己在聊天中反复给出相同的指令:
.cursor/rules/ 中记录该模式需要捕获的常见场景:
创建规则后,测试它们:
验证 AI 是否正确遵循规则。根据发现的差距更新规则。
PRPM 注册表的 .cursor/rules 展示了:
项目上下文:
代码风格:
模式:
组织:
测试:
在帮助用户创建 Cursor 规则时:
发现:
细化:
验证:
目标: 帮助 AI 生成符合项目约定的代码,而无需不断纠正。
每周安装次数
–
来源
首次出现
–
You are an expert at creating effective .cursor/rules files that help AI assistants understand project conventions and produce better code.
Use when:
.cursor/rules setupDon't use for:
Rules should provide concrete guidance, not vague advice.
❌ BAD - Vague:
Write clean code with good practices.
Use proper TypeScript types.
✅ GOOD - Specific:
Use functional components with TypeScript.
Define prop types with interfaces, not inline types.
Extract custom hooks when logic exceeds 10 lines.
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
falseDon't document what linters handle. Document architectural decisions.
❌ BAD - Linter territory:
Use semicolons in JavaScript.
Indent with 2 spaces.
Add trailing commas.
✅ GOOD - Decision guidance:
Choose Zustand for global state, React Context for component trees.
Use Zod for runtime validation at API boundaries only.
Prefer server components except for: forms, client-only APIs, animations.
Group related rules into clear sections:
## Tech Stack
- Next.js 14 with App Router
- TypeScript strict mode
- Tailwind CSS for styling
## Code Style
- Functional components only
- Named exports (no default exports)
- Co-locate tests with source files
## Patterns
- Use React Server Components by default
- Client components: mark with "use client" directive
- Error handling: try/catch + toast notification
## Project Conventions
- API routes in app/api/
- Components in components/ (flat structure)
- Types in types/ (shared), components/*/types.ts (local)
Cursor rules are written in MDC (.mdc) format, which supports YAML frontmatter metadata and markdown content. The metadata controls how and when rules are applied.
Every Cursor rule MUST start with YAML frontmatter between --- markers:
---
description: Brief description of when and how to use this rule
globs: ["**/*.ts", "**/*.tsx"]
alwaysApply: false
---
| Property | Type | Required | Description |
|---|---|---|---|
description | string | Yes | Brief description of the rule's purpose. Used by AI to decide relevance. Never use placeholders like --- or empty strings. |
globs | array | No | File patterns that trigger auto-attachment (e.g., ["**/*.ts"]). Leave empty or omit if not using Auto Attached type. |
alwaysApply | boolean | No | If true, rule is always included in context. If false or omitted, behavior depends on Rule Type. |
Control how rules are applied using the type dropdown in Cursor:
| Rule Type | Description | When to Use |
|---|---|---|
| Always | Always included in model context | Core project conventions, tech stack, universal patterns that apply everywhere |
| Auto Attached | Included when files matching globs pattern are referenced | File-type specific rules (e.g., React components, API routes, test files) |
| Agent Requested | Available to AI, which decides whether to include it based on description | Contextual patterns, specialized workflows, optional conventions |
| Manual | Only included when explicitly mentioned using @ruleName | Rarely-used patterns, experimental conventions, legacy documentation |
Always Rule (Core conventions):
---
description: TypeScript and code style conventions for the entire project
alwaysApply: true
---
Auto Attached Rule (File pattern-specific):
---
description: React component patterns and conventions
globs: ["**/components/**/*.tsx", "**/app/**/*.tsx"]
alwaysApply: false
---
Agent Requested Rule (Contextual):
---
description: RPC service boilerplate and patterns for creating new RPC endpoints
globs: []
alwaysApply: false
---
Manual Rule (Explicit invocation):
---
description: Legacy API migration patterns (deprecated, use for reference only)
globs: []
alwaysApply: false
---
Description is mandatory - AI uses this to determine relevance. Be specific:
Backend codeFastify API route patterns, error handling, and validation using ZodUse globs strategically - Auto-attach to relevant file types:
["**/*.tsx", "**/*.jsx"]["**/api/**/*.ts", "**/routes/**/*.ts"]["**/*.test.ts", "**/*.spec.ts"]Avoid always applying everything - Use alwaysApply: true sparingly:
Make Agent Requested rules discoverable - Write descriptions that help AI understand when to use:
Every Cursor rule file should include these sections:
## Tech Stack
- Framework: Next.js 14
- Language: TypeScript 5.x (strict mode)
- Styling: Tailwind CSS 3.x
- State: Zustand
- Database: PostgreSQL + Prisma
- Testing: Vitest + Playwright
Why: Prevents AI from suggesting wrong tools/patterns.
## Code Style
- **Components**: Functional with TypeScript
- **Props**: Interface definitions, destructure in params
- **Hooks**: Extract when logic > 10 lines
- **Exports**: Named exports only (no default)
- **File naming**: kebab-case.tsx
Always include code examples, not just descriptions:
## Patterns
### Error Handling
```typescript
try {
const result = await operation();
toast.success('Operation completed');
return result;
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error';
toast.error(message);
throw error; // Re-throw for caller to handle
}
// app/api/users/route.ts
export async function GET(request: Request) {
try {
// 1. Parse/validate input
// 2. Check auth/permissions
// 3. Perform operation
// 4. Return Response
} catch (error) {
return new Response(JSON.stringify({ error: 'Message' }), {
status: 500
});
}
}
## What NOT to Include
Avoid these common mistakes:
**❌ Too obvious:**
```markdown
- Write readable code
- Use meaningful variable names
- Add comments when necessary
- Follow best practices
❌ Too restrictive:
- Never use any third-party libraries
- Always write everything from scratch
- Every function must be under 5 lines
❌ Language-agnostic advice:
- Use design patterns
- Think before you code
- Test your code
- Keep it simple
Use this template for new Cursor rules:
# Project Name - Cursor Rules
## Tech Stack
[List all major technologies with versions]
## Code Style
[Specific style decisions]
## Project Structure
[Directory organization]
## Patterns
[Common patterns with code examples]
### Pattern Name
[Description + code example]
## Conventions
[Project-specific conventions]
## Common Tasks
[Frequent operations with step-by-step snippets]
### Task Name
1. Step one
2. Step two
[Code example]
## Anti-Patterns
[What to avoid and why]
## Testing
[Testing approach and patterns with examples]
## Tech Stack
**Framework:** Next.js 14 (App Router)
**Language:** TypeScript 5.x (strict mode enabled)
**Styling:** Tailwind CSS 3.x with custom design system
**State:** Zustand for global, React Context for component trees
**Forms:** React Hook Form + Zod validation
**Database:** PostgreSQL with Prisma ORM
**Testing:** Vitest (unit), Playwright (E2E)
**Deployment:** Vercel
**Key Dependencies:**
- `@tanstack/react-query` for server state
- `date-fns` for date manipulation (not moment.js)
- `clsx` + `tailwind-merge` for conditional classes
## Anti-Patterns
### ❌ Don't: Default Exports
```typescript
// ❌ BAD
export default function Button() { }
// ✅ GOOD
export function Button() { }
Why: Named exports are more refactor-friendly and enable better tree-shaking.
// ❌ BAD
function UserCard({ user }: { user: { name: string; email: string } }) { }
// ✅ GOOD
interface User {
name: string;
email: string;
}
function UserCard({ user }: { user: User }) { }
Why: Reusability and discoverability.
## Common Tasks
Include shortcuts for frequent operations:
```markdown
## Common Tasks
### Adding a New API Route
1. Create `app/api/[route]/route.ts`
2. Define HTTP method exports (GET, POST, etc.)
3. Validate input with Zod schema
4. Use try/catch for error handling
5. Return `Response` object
```typescript
import { z } from 'zod';
const schema = z.object({
name: z.string().min(1)
});
export async function POST(request: Request) {
try {
const body = await request.json();
const data = schema.parse(body);
// Process...
return Response.json({ success: true });
} catch (error) {
if (error instanceof z.ZodError) {
return Response.json(
{ error: error.errors },
{ status: 400 }
);
}
return Response.json(
{ error: 'Internal error' },
{ status: 500 }
);
}
}
## Best Practices
### Keep Rules Under 500 Lines
- Split large rules into multiple, composable files
- Each rule file should focus on one domain or concern
- Reference other rule files when needed (e.g., "See `backend-api.mdc` for API patterns")
- **Why:** Large files become unmanageable and harder for AI to process effectively
### Split Into Composable Rules
Break down by concern rather than creating one monolithic file:
.cursor/rules/ ├── tech-stack.mdc # Core technologies ├── typescript-patterns.mdc # Language-specific patterns ├── api-conventions.mdc # API route standards ├── component-patterns.mdc # React/UI patterns └── testing-standards.mdc # Testing approaches
**Why:** Easier to maintain, update, and reuse across similar projects.
### Provide Concrete Examples or Referenced Files
Instead of vague guidance, always include:
- Complete, runnable code examples
- References to actual project files: `See components/auth/LoginForm.tsx for example`
- Links to internal docs or design system
- Specific file paths and line numbers when relevant
**❌ BAD - Vague:**
```markdown
Use proper error handling in API routes.
✅ GOOD - Concrete:
API routes must use try/catch with typed errors. Example:
```typescript
// app/api/users/route.ts (lines 10-25)
export async function POST(request: Request) {
try {
const data = await request.json();
return Response.json({ success: true });
} catch (error) {
return handleApiError(error); // See lib/errors.ts
}
}
See app/api/products/route.ts for complete implementation.
### Write Rules Like Clear Internal Docs
Rules should read like technical documentation, not casual advice:
- Be precise and unambiguous
- Include the "why" behind decisions
- Document exceptions to rules
- Reference architecture decisions
- Link to related rules or documentation
**Think:** "Could a new engineer understand this without asking questions?"
### Reuse Rules When Repeating Prompts
If you find yourself giving the same instructions repeatedly in chat:
1. Document that pattern in `.cursor/rules/`
2. Include the specific guidance you keep repeating
3. Add examples of correct implementation
4. Update existing rule files rather than creating new ones
**Common scenarios to capture:**
- "Always use X pattern for Y"
- "Don't forget to Z when doing W"
- Corrections you make frequently
- Patterns specific to your team/codebase
### Keep It Scannable
- Use clear section headers
- Bold important terms
- Include code examples (not just prose)
- Use tables for comparisons
- Add table of contents for files over 200 lines
### Update Regularly
- Review monthly or after major changes
- Remove outdated patterns
- Add new patterns as they emerge
- Keep examples current with latest framework versions
- Archive deprecated rules rather than deleting (for reference)
### Test with AI
After creating rules, test them:
1. Ask AI: "Create a new API route following our conventions"
2. Ask AI: "Add error handling to this component"
3. Ask AI: "Refactor this to match our patterns"
Verify AI follows rules correctly. Update rules based on gaps found.
## Real-World Example
The PRPM registry `.cursor/rules` demonstrates:
- Clear tech stack declaration (Fastify, TypeScript, PostgreSQL)
- Specific TypeScript patterns
- Fastify-specific conventions
- Error handling standards
- API route patterns
- Database query patterns
## Checklist for New Cursor Rules
**Project Context:**
- [ ] Tech stack clearly defined with versions
- [ ] Key dependencies listed
- [ ] Deployment platform specified
**Code Style:**
- [ ] Component style specified (functional/class)
- [ ] Export style (named/default)
- [ ] File naming convention
- [ ] Specific to project (not generic advice)
**Patterns:**
- [ ] At least 3-5 code examples
- [ ] Cover most common tasks
- [ ] Include error handling pattern
- [ ] Show project-specific conventions
**Organization:**
- [ ] Logical section headers
- [ ] Scannable (not wall of text)
- [ ] Examples are complete and runnable
- [ ] Anti-patterns included with rationale
**Testing:**
- [ ] Tested with AI assistant
- [ ] AI follows conventions correctly
- [ ] Updated after catching mistakes
## Helpful Prompts for Users
When helping users create Cursor rules:
**Discovery:**
- "What's your tech stack?"
- "What patterns do you want AI to follow?"
- "What mistakes does AI currently make?"
**Refinement:**
- "Are there anti-patterns you want documented?"
- "What are your most common coding tasks?"
- "Do you have naming conventions?"
**Validation:**
- "Let me test these rules by asking you to generate code..."
- "Does this match your team's style?"
## Remember
- Cursor rules are **living documents** - update as project evolves
- Focus on **decisions**, not basics
- Include **runnable code examples**, not descriptions
- Test rules with AI to verify effectiveness
- Keep it **scannable** - use headers, bold, lists
**Goal:** Help AI produce code that matches project conventions without constant correction.
Weekly Installs
–
Source
First Seen
–
React 组合模式指南:Vercel 组件架构最佳实践,提升代码可维护性
109,600 周安装