jvinhit//lab

Search posts

Type to search across journal entries.

navigate open esc close

Config Files cho Coding Agent — Từ CLAUDE.md đến .mdc, MCP và Commands

Hệ thống config files điều khiển coding agent (Claude Code + Cursor): CLAUDE.md, settings.json, .mdc rules, MCP servers, commands, sub-agents — ý nghĩa, cách dùng, và setup thực tế.

Bạn mở Cursor, gõ prompt “tạo component UserTable”, agent tạo ra code dùng class component + default export + inline styles. Trong khi project của bạn dùng functional component + named export + Tailwind.

Không phải agent “ngu” — nó không biết conventions của project bạn. Và đó chính xác là vấn đề mà config files giải quyết.

Config files cho coding agent giống như onboarding package cho nhân viên mới: tech stack là gì, naming conventions thế nào, cái gì được làm và cái gì cấm. Chỉ khác là “nhân viên” này đọc file trong vài millisecond thay vì vài ngày.

Dưới đây là interactive reference cho toàn bộ hệ thống config files — bấm vào từng tab để xem chi tiết.

Hệ thống file config — ý nghĩa & ví dụ thực hành
Claude Code · Cursor · React + TypeScript + Zustand + Ant Design
Mỗi file có một vai trò riêng biệt. Hiểu đúng vai trò → không bị nhầm lẫn khi setup.
Nhóm 1 — Claude Code (terminal agent)
CLAUDE.md commit
Memory file. Claude đọc mỗi khi start session. Chứa context project + conventions + rules hành vi. Tương đương "briefing document" cho nhân viên mới.
CLAUDE.local.md gitignore
Memory cá nhân. Override CLAUDE.md cho máy của bạn. Preferences cá nhân, local env info.
.claude/settings.json commit
Permissions + hooks. Quyết định Claude được làm gì (allow/deny), tự động chạy lệnh gì sau mỗi action. Tương đương "hợp đồng lao động".
.claude/settings.local.json gitignore
Override settings cá nhân. Ví dụ: cho phép git commit trên máy mình.
.claude/commands/ commit
Custom slash commands (skills). Mỗi file .md = một lệnh /tên-file. Đóng gói quy trình lặp lại.
.claude/agents/ commit
Sub-agent definitions. Mỗi file .md = một specialist agent. Claude tự route task đến đúng agent.
Nhóm 2 — Cursor (editor)
.cursor/rules/*.mdc commit
Rules files cho Cursor. Format .mdc (2026) thay thế .cursorrules (deprecated với Agent mode). Mỗi file có frontmatter YAML điều khiển khi nào rule được inject.
.cursorrules deprecated
Legacy format — vẫn chạy với Chat/Inline nhưng KHÔNG load với Agent mode. Nên migrate sang .mdc.
Nhóm 3 — MCP (extensions)
.mcp.json commit
Project-level MCP servers. Giao thức cho phép agent dùng tools ngoài file system — GitHub, database, memory...
~/.claude.json không commit
User-level MCP config, OAuth tokens, per-project state. Nằm ở home directory.
Nhóm 4 — Docs (context cho agent)
docs/ARCHITECTURE.md commit
Context về hệ thống — giải thích tại sao dùng stack này, data flow, boundary rules.
docs/COMPONENT_GUIDE.md commit
Pattern library — component templates, naming, folder structure.
CLAUDE.md = "Briefing document". Claude đọc khi start. Trả lời: project này là gì, làm gì, theo rules nào?
Anatomy — 5 phần cần có
Phần 1 — Stack & context ai cũng cần
Liệt kê tech stack + version. Agent cần biết đang làm việc với gì.
## Stack
- React 18 + TypeScript 5 (strict mode)
- UI: Ant Design 5.x
- State: Zustand v5 (UI state only)
- Server state: React Query v5
- Build: Vite · Testing: Vitest + RTL
- Package manager: pnpm
Phần 2 — Naming conventions ai cũng cần
Quy tắc đặt tên file, component, function.
## Naming
- Components: PascalCase → UserTable.tsx
- Stores: camelCase + suffix → userStore.ts
- Hooks: prefix use → useUserData.ts
- Types: PascalCase + suffix → UserDto, ApiResponse
- Files: kebab-case → user-service.ts
Phần 3 — Architecture rules ai cũng cần
Boundary rules cứng — ngăn agent phá vỡ kiến trúc.
## Architecture rules
- KHÔNG lưu server data vào Zustand — dùng React Query
- Pages chỉ compose components, không fetch trực tiếp
- Components không biết về store structure
- API calls CHỈ trong src/services/
- Business logic CHỈ trong custom hooks
Phần 4 — Agent behavior quan trọng
Hành vi mong muốn: khi nào hỏi, khi nào tự làm.
## Agent behavior
- Đọc docs/ARCHITECTURE.md trước khi tạo file mới
- Viết test song song với code
- Hỏi trước khi thêm dependency mới
- Khi xong: liệt kê files đã tạo/sửa + lý do
- Khi thấy bug ngoài scope: comment TODO, không tự fix
Phần 5 — Prohibitions không được bỏ qua
Danh sách tuyệt đối không làm.
## KHÔNG được
- Dùng `any` hoặc `@ts-ignore`
- Import toàn bộ antd: import * as antd
- Lưu API response vào Zustand
- Tạo inline styles
- Commit .env files
Giữ CLAUDE.md dưới 400 tokens (~300 dòng). Quá dài sẽ tốn context window.
Đừng nhét everything vào CLAUDE.md. Extract chi tiết ra docs/ rồi dùng @filename khi cần.
settings.json = "Hợp đồng lao động". Quyết định Claude được làm gì và không được làm gì.
Permissions (allow / deny)
Allow — những gì Claude được tự động làm
"permissions": {
  "allow": [
    "Bash(pnpm run *)",
    "Bash(npx tsc --noEmit)",
    "Bash(npx vitest run *)",
    "Bash(git status)",
    "Bash(git diff *)",
    "Read(./src/**)",
    "Read(./docs/**)"
  ]
}
Wildcard * cho phép mọi argument sau lệnh đó.
Deny — tuyệt đối KHÔNG được làm
"permissions": {
  "deny": [
    "Bash(git push *)",
    "Bash(git commit *)",
    "Bash(rm -rf *)",
    "Bash(curl *)",
    "Read(./.env)",
    "Read(./.env.*)",
    "Write(./prisma/migrations/**)"
  ]
}
Deny có priority cao hơn allow. Nếu cùng match, deny thắng.
Hooks (tự động chạy sau actions)
PostToolUse hook — TypeScript check tự động
Mỗi khi Claude sửa file .tsx/.ts, tự chạy TypeScript check.
"hooks": {
  "PostToolUse": [
    {
      "matcher": "Write(./src/**/*.tsx)",
      "hooks": [{
        "type": "command",
        "command": "npx tsc --noEmit 2>&1 | head -30"
      }]
    }
  ]
}
PreToolUse hook — cảnh báo trước action
"hooks": {
  "PreToolUse": [
    {
      "matcher": "Write(./src/stores/**)",
      "hooks": [{
        "type": "command",
        "command": "echo 'Reminder: Zustand stores chỉ cho UI state'"
      }]
    }
  ]
}
settings.json vs settings.local.json
settings.json commit
Rules cho cả team. An toàn cho mọi người.
settings.local.json gitignore
Override cho máy bạn.
Cursor .mdc = "System prompt theo từng file type". Nhiều file rules, mỗi cái chỉ load khi cần.
Anatomy của file .mdc
---
description: "Mô tả để AI biết khi nào dùng rule này"
globs: "src/components/**/*.tsx"
alwaysApply: false
---

# Nội dung rule (markdown bình thường)
- Rule 1...
- Rule 2...
3 trường frontmatter: description, globs, alwaysApply.
4 activation modes
Mode 1 Always Apply
Load vào mọi request. Dùng cho rules core nhất.
---
alwaysApply: true
description: "Core project conventions"
---
Tech: React 18, TypeScript strict, pnpm, Vitest.
Never: `any` type, class components, default exports.
Giới hạn dưới 200 từ. Mỗi token tốn context của mọi request.
Mode 2 Auto Attached (glob) — hiệu quả nhất
Chỉ load khi file khớp glob. Mở store → Zustand rules load. File khác không ảnh hưởng.
---
description: "Zustand store patterns"
globs: "src/stores/**/*.ts"
alwaysApply: false
---
- Tách State và Actions interface rõ ràng
- Dùng devtools middleware
- KHÔNG lưu server data
- Luôn có reset() action
Mode 3 Agent Requested
Không có globs. AI tự đọc description và quyết định load.
---
description: "Dùng khi tạo form với Ant Design validation"
alwaysApply: false
---
- Dùng Form.useForm() không dùng ref
- Rules array cho mỗi Form.Item
- onFinish thay vì onSubmit
Mode 4 Manual
Chỉ load khi gõ @tên-file trong chat. Dùng cho rules ít dùng.
Setup chuẩn
.cursor/rules/
├── base.mdc              # alwaysApply: true  (~150 từ)
├── react-components.mdc  # globs: src/components/**/*.tsx
├── zustand-stores.mdc    # globs: src/stores/**/*.ts
├── antd-usage.mdc        # globs: src/**/*.tsx
├── testing.mdc           # globs: **/*.test.tsx,**/*.test.ts
└── personal.mdc          # alwaysApply: true (gitignore)
Mỗi file rules một domain. Không nhét tất cả vào một file.
MCP (Model Context Protocol) = "Plugin system". Thêm tools: GitHub, database, memory, search...
.mcp.json — project level
Cấu trúc cơ bản
{
  "mcpServers": {
    "tên-server": {
      "command": "npx",
      "args": ["-y", "@package/server-name"],
      "env": {
        "API_KEY": "${ENV_VAR_NAME}"
      }
    }
  }
}
Mỗi server = một set of tools mới. env truyền credentials qua env variables.
MCP servers hữu ích nhất
GitHub MCP
Create PRs, view issues, review code trực tiếp từ chat.
"github": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-github"],
  "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}" }
}
Memory MCP
Persistent knowledge graph giữa sessions. Agent nhớ decisions dù bắt đầu session mới.
"memory": {
  "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-memory"]
}
Context7 MCP
Tra cứu docs thư viện theo version chính xác.
"context7": {
  "command": "npx",
  "args": ["-y", "@upstash/context7-mcp@latest"]
}
Rất hữu ích với AntD v5 — Agent tra docs đúng version.
Commands = "SOP được đóng gói". Viết một lần, dùng mãi bằng /tên-command.
5 commands thiết yếu
/new-component — tạo component mới
Tạo React component: $ARGUMENTS

Steps:
1. Tạo folder src/components/$ARGUMENTS/
2. $ARGUMENTS.types.ts — props interface
3. $ARGUMENTS.tsx — implementation với AntD
4. index.tsx — barrel export
5. $ARGUMENTS.test.tsx — tests RTL

Rules:
- Named export, không default export
- Props interface: ${ARGUMENTS}Props
- Không dùng any
Dùng: /new-component ProductTable
/new-store — tạo Zustand store
Tạo Zustand store cho domain: $ARGUMENTS

Steps:
1. Tạo src/stores/$ARGUMENTS.store.ts
2. Định nghĩa State + Actions interfaces
3. Implement với devtools middleware
4. Tạo test file

Rules:
- KHÔNG lưu API data
- Tách State và Actions interface
- Luôn có reset() action
/review — review code
Review code: $ARGUMENTS

Checklist:
1. TypeScript: no any, proper generics?
2. React: hooks rules, deps array đúng?
3. Zustand: server state không?
4. Performance: unnecessary re-renders?
5. Tests: behavior tested không?

Output: 🔴 Critical · 🟡 Warning · 🟢 Suggestion
/handoff — tóm tắt session
Tạo HANDOFF.md: tasks done, tasks remaining, decisions + lý do, files changed, next steps.
Sub-agents = "Nhân viên chuyên môn". Mỗi cái được "train" sâu về một domain.
3 agents hữu ích nhất
component-builder.md
---
name: component-builder
description: Tạo React components với AntD và TypeScript strict.
tools: Read, Write, Bash
---
Trước khi tạo component:
1. Đọc rules liên quan
2. Xem component tương tự để follow pattern
3. Types file trước, component sau, test cùng lúc
test-writer.md
---
name: test-writer
description: Viết tests cho React components và hooks.
tools: Read, Write, Bash
---
- Test behavior, KHÔNG test implementation
- Query priority: getByRole > getByLabelText > getByText
- userEvent thay vì fireEvent
- AAA pattern: Arrange → Act → Assert
code-reviewer.md
---
name: code-reviewer
description: Review code theo project standards.
tools: Read, Bash
---
Checklist: TypeScript · React · Zustand · AntD · Security · Performance
Output: 🔴 Critical / 🟡 Warning / 🟢 Suggestion
Mỗi item: vấn đề + file:line + cách fix
Cách invoke
Tự động (AI route)
"Write tests for UserTable" → Claude route sang test-writer tự động
Tường minh
"Use the test-writer agent to create tests for UserTable"
Docs files không phải rules — là context. Agent đọc khi cần hiểu "tại sao".
Rules vs Context
Rules (CLAUDE.md, .mdc)
Prescriptive — "làm gì / không làm gì"

"Không dùng any"
"Named exports only"
Context (docs/)
Descriptive — "tại sao / như thế nào"

"Dùng Zustand vì state đơn giản..."
"Data flow từ API → React Query → Component vì..."
ARCHITECTURE.md — nội dung cần có
## 1. Overview (3-5 câu)
Project là gì, phục vụ ai, scale thế nào.

## 2. Tech decisions + lý do
Zustand thay vì Redux: state đơn giản.
React Query thay vì axios thuần: cần cache, refetch.

## 3. Folder structure
src/
├── components/   # shared components
├── pages/        # route-level
├── stores/       # Zustand (UI state only)
├── services/     # API calls
└── hooks/        # shared custom hooks

## 4. Data flow
API → React Query (cache) → Component
UI events → Hook → Zustand → Component

## 5. Boundary rules
- Pages không gọi API trực tiếp
- Components không biết store internals
- Services không import từ components
Giới hạn 100-150 dòng. Quá dài sẽ bị agent bỏ qua.

Tổng kết

  • Config files biến agent từ “generic AI” thành “team member biết conventions”. Không config = output ngẫu nhiên, có config = output nhất quán.
  • CLAUDE.md là briefing document — giữ ngắn (dưới 400 tokens), chỉ chứa rules core nhất.
  • settings.json kiểm soát quyền (allow/deny) và tự động hóa (hooks). Deny luôn thắng allow.
  • Cursor .mdc rules cho phép conditional loading — chỉ load rule khi file phù hợp đang trong context. Mode “Auto Attached” (glob) hiệu quả nhất.
  • MCP mở rộng khả năng agent: GitHub, memory, docs lookup. Đừng hardcode secrets — dùng env variables.
  • Commands đóng gói quy trình lặp lại. Sub-agents tạo specialist cho từng domain.
  • Tách rules và context: rules (làm gì) vào CLAUDE.md/.mdc, context (tại sao) vào docs/.
  • Setup tốt là quá trình iterate — thêm rule mỗi khi agent làm sai, không phải viết 50 rules cùng lúc.

Đọc thêm