mcpField
C
cursor-rules-config

cursor-rules-config

github.com/jeremylongshoreAgent 工作流2.9k42 次安装2 天前更新
代码仓库

关于 cursor-rules-config

为 Cursor 项目规则提供编写、组织和审核指导,适合维护团队工程规范的开发者。重点是按路径限定规则、测试行为并通过版本控制跟踪变更。

主要功能

  1. 01创建带作用范围的 .mdc 规则
  2. 02按文件路径自动应用规则
  3. 03维护共享规则与本地约定
  4. 04测试规则并审查变更
  5. 05排查冲突与敏感信息

适用场景

  1. 01为 API 路由添加验证规范
  2. 02将旧 .cursorrules 拆分为规则文件
  3. 03确认规则不会影响无关文件

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/jeremylongshore/tons-of-skills-marketplace --skill cursor-rules-config

安装后在 Claude Code 中输入/cursor-rules-config确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

references/
advanced-configuration.md
basic-configuration.md
errors.md
examples.md
framework-specific-templates.md
tips-for-effective-rules.md

详细介绍

Cursor 规则配置

概述

将 Cursor 规则作为版本化的工程政策进行管理,以塑造 AI 上下文和行为;规则必须具体、范围明确、经过审查,并与仓库的事实来源保持一致。

前置条件

  • 仓库所有者批准、现有工程/安全标准,以及一个测试工作区。
  • 经过审查的忽略策略,用于排除机密、生成文件和敏感数据。

说明

  1. 每项关注点编写一条明确的规则,说明其范围、优先级和具体的验收行为。
  2. 将共享规则纳入源代码管理,并使用按路径限定的规则来规范本地约定。
  3. 在非敏感的测试样例上测试新规则,检查结果行为,并通过常规审查流程合并。
  4. 定期移除过时或相互冲突的规则,并记录任何有意保留的例外。

输出

  • 一套经过审查和版本控制的规则集,范围明确,并附有经过测试的行为示例。

错误处理

情况安全响应
规则冲突确定唯一的权威规则,并在部署前测试修订后的规则。
规则泄露敏感内容移除该规则,修复忽略控制,并评估泄露情况。
规则范围过宽按路径/任务限定范围,而不是禁用所有共享治理规则。

示例

添加一条按路径限定的 API 规则,要求使用现有验证和测试,然后在经过脱敏的测试样例上进行测试。为该规则创建 PR,并在合并前确认它不会应用于无关的前端文件。

通过 Cursor 的规则系统配置项目专属的 AI 行为。现代方法使用 .cursor/rules/*.mdc 文件;旧版 .cursorrules 文件仍受支持,但已弃用。

规则系统架构

现代项目规则(.cursor/rules/*.mdc)

每个 .mdc 文件都包含 YAML frontmatter,后接 Markdown 内容:

---
description: "Enforce TypeScript strict mode and functional patterns"
globs: "src/**/*.ts,src/**/*.tsx"
alwaysApply: false
---
# TypeScript Standards

- Use `const` over `let`, never `var`
- Prefer pure functions over classes
- All functions must have explicit return types
- Use discriminated unions over enums

Frontmatter 字段:

字段类型用途
descriptionstring简洁说明规则用途(显示在 Cursor 界面中)
globsstring用于自动附加的 Gitignore 风格模式
alwaysApplybooleantrue = 始终启用;false = 仅在上下文引用匹配文件时启用
按 alwaysApply + globs 组合划分的规则类型
alwaysApplyglobs行为
true空注入到每个提示词中
false已设置上下文中包含匹配文件时自动附加
false空仅手动使用——在聊天中通过 @Cursor Rules 引用
文件命名约定

使用 kebab-case,并以 .mdc 为扩展名。名称应描述规则的适用范围:

.cursor/rules/
  typescript-standards.mdc
  react-component-patterns.mdc
  api-error-handling.mdc
  testing-conventions.mdc
  database-migrations.mdc
  security-requirements.mdc

通过以下方式创建新规则:Cmd+Shift+P > New Cursor Rule

完整的项目规则示例

.cursor/rules/project-context.mdc(始终启用):

---
description: "Core project context and conventions"
globs: ""
alwaysApply: true
---
# Project: E-Commerce Platform

Tech stack: Next.js 15, TypeScript 5.7, Prisma ORM, PostgreSQL, Tailwind CSS 4.
Package manager: pnpm. Monorepo with turborepo.

## Conventions
- API routes in `app/api/` using Route Handlers
- Server Components by default, `"use client"` only when needed
- Error boundaries at layout level
- All monetary values stored as integers (cents)
- Dates stored as UTC, displayed in user timezone

.cursor/rules/react-patterns.mdc(按 glob 限定范围):

---
description: "React component standards for TSX files"
globs: "src/**/*.tsx,app/**/*.tsx"
alwaysApply: false
---
# React Component Rules

- Export components as named exports, not default
- Props interface named `{Component}Props`
- Use `forwardRef` for components accepting `ref`
- Colocate styles in `.module.css` files
- Server Components: no `useState`, `useEffect`, or event handlers

```tsx
// Correct pattern
export interface ButtonProps {
  variant: 'primary' | 'secondary';
  children: React.ReactNode;
  onClick?: () => void;
}

export function Button({ variant, children, onClick }: ButtonProps) {
  return (
    <button className={styles[variant]} onClick={onClick}>
      {children}
    </button>
  );
}

**`.cursor/rules/api-routes.mdc`** (glob-scoped):
```yaml
---
description: "API route handler patterns"
globs: "app/api/**/*.ts"
alwaysApply: false
---
# API Route Standards

- Always validate request body with Zod
- Return typed `NextResponse.json()` responses
- Use consistent error response shape: `{ error: string, code: string }`
- Wrap handlers in try/catch with structured logging

```ts
import { NextRequest, NextResponse } from 'next/server';
import { z } from 'zod';

const CreateOrderSchema = z.object({
  items: z.array(z.object({
    productId: z.string().uuid(),
    quantity: z.number().int().positive(),
  })),
});

export async function POST(req: NextRequest) {
  try {
    const body = await req.json();
    const parsed = CreateOrderSchema.parse(body);
    const order = await createOrder(parsed);
    return NextResponse.json(order, { status: 201 });
  } catch (err) {
    if (err instanceof z.ZodError) {
      return NextResponse.json(
        { error: 'Validation failed', code: 'INVALID_INPUT', details: err.issues },
        { status: 400 }
      );
    }
    return NextResponse.json(
      { error: 'Internal server error', code: 'INTERNAL_ERROR' },
      { status: 500 }
    );
  }
}

## Legacy .cursorrules Format

Place a `.cursorrules` file in project root. Plain markdown, no frontmatter:

```markdown
# Project Rules

You are working on a Django REST Framework API.

## Stack
- Python 3.12, Django 5.1, DRF 3.15
- PostgreSQL 16 with pgvector extension
- Redis for caching and Celery broker
- pytest for testing

## Conventions
- ViewSets over function-based views
- Always use serializer validation
- Custom exceptions inherit from `APIException`
- All endpoints require authentication unless explicitly marked
- Use `select_related` and `prefetch_related` to avoid N+1 queries

## Code Style
- Type hints on all function signatures
- Docstrings on all public methods (Google style)
- Max function length: 30 lines

迁移:从 .cursorrules 迁移到 .cursor/rules/

将单体 .cursorrules 拆分为按范围限定的 .mdc 文件:

  1. 创建 .cursor/rules/ 目录
  2. 将全局上下文提取到 alwaysApply: true 规则中
  3. 将语言/框架规则提取到按 glob 限定范围的规则中
  4. 确认所有规则均已加载后,删除 .cursorrules

在规则中引用文件

应用规则时,使用 @file 语法引入其他上下文文件:

---
description: "Database schema context for migration files"
globs: "prisma/**/*.prisma,drizzle/**/*.ts"
alwaysApply: false
---
Reference these files for schema context:
@prisma/schema.prisma
@docs/data-model.md

调试规则

  1. 打开聊天并输入 @Cursor Rules,查看当前启用的规则
  2. 检查 glob 模式是否与文件匹配:打开一个文件,然后确认该规则出现在上下文提示框中
  3. alwaysApply: true 规则始终显示;glob 规则仅在上下文中包含匹配文件时显示

企业注意事项

  • 版本控制:将 .cursor/rules/ 提交到 git——规则属于项目文档
  • 团队一致性:团队范围的标准使用 alwaysApply: true
  • 敏感数据:切勿在规则文件中放入 API 密钥、机密或凭证
  • 规则大小:单条规则应聚焦且不超过 200 行;大型规则应拆分为多个文件
  • 审计跟踪:规则变更会记录在 git 历史中,以供合规审查

资源

评论

支持 Markdown