工具Cursor(2)使用案例

发布于:2025-08-02 ⋅ 阅读:(11) ⋅ 点赞:(0)

一、Review MR

准备好一个MR,让Curson帮助我们review代码。需要先把本地Curson环境配置好。

通过 Cursor AI 进行代码审查可以显著提高审查效率和质量。本方案集成了以下功能:

  • GitLab 集成:直接获取 MR 详情和代码变更

  • 智能分析:结合项目架构进行风险评估

  • 规则检查:基于预定义规则进行系统性检查

  • 记忆功能:保存审查进度和发现的问题

1、MCP服务器配置

打开curson--settings

选择Tools and Inte..

 

点击

输入

{
  "mcpServers": {
    "memory": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-memory"],
      "env": {
        "MEMORY_FILE_PATH": ""C:\\Users\\xxx\\.mcp-storage\\memory.json""
      }
    },
    "sequential-thinking": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-sequential-thinking"]
    },
    "playwright": {
      "command": "npx",
      "args": ["-y", "@playwright/mcp@latest", "--browser", "chrome"]
    },
    "gitlab": {
      "command": "npx",
      "args": ["-y", "@zereight/mcp-gitlab"],
      "env": {
        "GITLAB_PERSONAL_ACCESS_TOKEN": "xxxxx",
        "GITLAB_API_URL": "https://git.xxx.us",
        "GITLAB_READ_ONLY_MODE": "false",
        "USE_GITLAB_WIKI": "false",
        "NODE_TLS_REJECT_UNAUTHORIZED": "0"
      }
    }
  }
}

配置说明:

  • memory: 用于保存审查进度和结果,或者在prompt中让AI使用本地文件记录进度也可以

  • sequential-thinking: 用于结构化思考和分析

  • playwright: 用于 Web 界面操作(如需要)

  • 推荐模型:claude-4-sonnet (Thinking)

GitLab Token 配置:

  1. 访问:https://git.xxx.us/-/user_settings/personal_access_tokens

  2. 创建新 Token,scopes 记得选择 api

  3. Copy出来 Token 替换配置中的 xxxxx

注意:确保将路径 /Users/xxxx/.mcp-storage/memory.json 替换为您的实际路径

注意:配置完应该都显示绿灯,如果是red,需要排查下原因

(1)目录是否正确

memory.json文件会自动生成,但是目录不会,需要确保目录可读可写,如果不存在手动创建一个。

(2)本地是否安装了插件
npx -y @modelcontextprotocol/server-memory

这个命令用于临时运行 MCP 的 memory server,而不需要手动全局安装

输出:

 

把这两个开关disable再打开,就可以了

 

2、规则文件设置

在你的项目下新建.cursor/rules目录,并新建两个文件

.cursor/

├── rules/

│ ├── code-review-guide.mdc

│ └── coding-rules.mdc

(1)code-review-guide.mdc内容为
---
description: Code Review Guide
globs: 
alwaysApply: false
---
<goal>
You are an AI reviewer responsible for planning and executing a comprehensive code review process using sequential and checklist-driven methodologies.
Your goal is to ensure code quality, minimize risk, and generate actionable reports.
</goal>

<process_steps>
1. Code Change Analysis
   - Read all code changes, tag and classify them, referencing the project architecture.
   - Use tools (sequentialthinking, gitlab, git) to gather all necessary information.
2. Risk and Impact Assessment
   - Assess risk and potential impact using both project context and change details.
3. Checklist Review
   - Filter the code review checklist based on the specific changes.
   - Check each item individually; for each violation, create a detailed record.
4. Issue Summary and Reporting
   - Compile all findings into a clear, comprehensive report for the team.
</process_steps>

<execution_requirements>
- Always use the sequentialthinking tool to plan and track each review phase.
- Persist the results of each phase to memory or local files for traceability.
- Annotate code directly for each discovered issue, referencing the exact rule.
- Produce a full summary at the end of each review, including risk categorization and recommendations.
</execution_requirements>

<formatting_instructions>
Return the review as a structured markdown document, with headings for each section and sub-lists for each rule violation grouped by risk level and category.
Include explicit references to project documents or code sections where relevant.
</formatting_instructions>
(2) coding-rules.mdc内容为
---
description: Code Review Rules
globs: 
alwaysApply: false
---
<goal>
You are given a set of code review rules designed to identify risks and ensure code quality in a software project.
Your task is to interpret, categorize, and apply these rules to code changes during review.
</goal>

<risk_indicators>
- [LOW-RISK]: Minor code quality issues, do not impact functionality.
- [MEDIUM-RISK]: May affect performance or maintainability.
- [HIGH-RISK]: May cause functional issues or security vulnerabilities.
- [CRITICAL-RISK]: May lead to system failures, regressions, or critical outages.
</risk_indicators>

<note>
This project is still under development, ignore Regression Risk and Backward Compatibility for now
</note>

<categories>
- REACT
- TYPESCRIPT
- NAMING
- CODE_QUALITY
- PLUGIN_ARCHITECTURE
- PERFORMANCE
- RISK
- FEATURE_FLAGS
- SECURITY
- BLUE_GREEN
</categories>

<application_criteria>
For each code change:
- Identify the relevant category and rules based on file type, context, and change details.
- Assess the risk level according to the indicators.
- For each violated rule, record the risk, provide a concise description, and annotate the corresponding code.
- For checklist-based items, verify each item individually. Do not assume items are met without inspection.
- High-risk and critical-risk issues must be prioritized in reports.
</application_criteria>

<reporting_criteria>
- For each code review, generate a summary report including:
  - List of all issues by risk level and category.
  - Specific risk annotation and recommended mitigation.
  - References to relevant guidelines or files when needed (e.g., [coding-rules.mdc]).
  - Comprehensive summary for stakeholders and developers.
</reporting_criteria>

<formatting_instructions>
Output findings as a structured markdown table or bulleted list grouped by risk level and category.
Use clear, actionable language.
</formatting_instructions>

<rules>

## REACT

### [React Component Definition] [LOW-RISK]
- Use function declarations or arrow functions with displayName
- Forbidden: Anonymous components

### [Single Responsibility Principle] [MEDIUM-RISK]
- Each component should only handle one functionality
- Complex logic needs to be split into components

### [Component Return Values] [LOW-RISK]
- Explicitly return JSX.Element type
- Use early returns for conditional rendering

## TYPESCRIPT

### [Strict Mode] [MEDIUM-RISK]
**Tech**: `typescript` `component`
- Must enable TypeScript strict mode
- All props must have type definitions

### [Props Destructuring] [LOW-RISK]
- Must destructure props parameters
- Explicitly define Props interface

## NAMING

### [Component Naming] [LOW-RISK]
- Components: PascalCase (UserProfile, DataTable)
- Hooks: use + PascalCase (useUserData)
- HOC: with + PascalCase (withAuth)

### [Variable Naming] [LOW-RISK]
- Variables: camelCase (userData, isLoading)
- Functions: verb + Noun (handleClick, fetchUser)
- Booleans: is/has/can/should + Adjective

### [Constants and Type Naming] [LOW-RISK]
- Constants: SCREAMING_SNAKE_CASE
- Types: PascalCase
- Interfaces: I + PascalCase
- Enums: PascalCase

### [File and CSS Naming] [LOW-RISK]
- Files: kebab-case (.tsx, .css)
- CSS classes: kebab-case (.user-card)
- CSS modules: camelCase (styles.userCard)

## CODE_QUALITY

### [Maintainability] [MEDIUM-RISK]
- Code clarity takes priority over cleverness
- Complex logic must include comments

### [Function Definition Location] [MEDIUM-RISK]
- Function definitions outside render scope
- Avoid defining helper functions inside components

## PERFORMANCE

### [React Performance - Avoid Re-renders] [MEDIUM-RISK]
- Use useCallback to wrap event handler functions
- Forbidden: Defining anonymous functions in render

### [React Performance - Style Optimization] [MEDIUM-RISK]
- Forbidden: Using style={{}}
- Must use className or styled-components

### [React Performance - Array Rendering] [MEDIUM-RISK]
- Use unique id as key, forbidden to use index

### [React Performance - Complex Calculations] [MEDIUM-RISK]
- Use useMemo for complex calculations
- Use component mapping instead of switch for complex conditions

### [Runtime Performance] [MEDIUM-RISK]
- No unnecessary re-renders
- Correct usage of useCallback/useMemo
- Component splitting implementation
- Memory leak prevention
- Event listener cleanup
- WebSocket connection management

## RISK

### [Regression Risk Priority] [CRITICAL-RISK]
- Regression risk > Feature completeness
- Production stability > Code elegance
- Backward compatibility = Mandatory requirement

### [Backward Compatibility Validation] [CRITICAL-RISK]
- Check for breaking changes without feature flags
- Global state change checks
- Error boundary implementation checks
- Rollback mechanism checks

## FEATURE_FLAGS

### [Feature Flag Implementation Requirements] [HIGH-RISK]
- Feature flags for progressive rollouts
- Kill switches for quick disabling
- Feature detection mode usage
- Fallback behavior implementation
- Flag configuration documentation
- Rollback strategy definition

## SECURITY

### [Input Validation] [HIGH-RISK]
- All user input sanitization
- File upload restrictions in place
- URL validation implementation
- Message content filtering

### [XSS Prevention] [HIGH-RISK]
- No innerHTML usage for user data
- Proper escaping in templates
- CSP header configuration
- Script injection prevention

### [Data Protection] [HIGH-RISK]
- No sensitive data in logs
- Secure local storage usage
- Proper session management
- Third-party data processing compliance

</rules>

3、创建自定义模式

需要先在setting里面把custom model打开,因为这是个beta功能。

 之后可以看到这里多了一个custom mode,点击Add

也是可以点击edit进去修改的:

  • Name: Code Review Assistant

  • Tools: 勾选 "Run"(避免每次确认)

  • Instructions(点击advances options): 使用以下提示词

用gitlab MCP获取MR详情,git MCP获取完整代码上下文,如果本地分支和目标分支不一致,使用git命令查看文件上下文。简单改动可无描述,复杂需求改动需提供设计文档或说明等必要信息,如信息不足无法准确review则终止并要求补充。重点识别缺陷/风险/改进点,内容多时用记忆工具存储进度。审查后发布GitLab评论:具体问题作行内评论,整体总结作通用评论,评论用英语,均标记AI生成。无问题时简洁表达未发现问题。

4、加载rules文件

点击add context把coding-rules加载进来

5、使用

发送一个MR(copy进去后,前面会自动加上@),回车,可以看到在自动分析了。


网站公告

今日签到

点亮在社区的每一天
去签到