中文译本。原文见同目录 README.md

第 15 课:AGENTS.md —— 为 Agent 提供项目上下文

引言

新工程师加入团队时,你不会只把代码库扔给他然后说「祝你好运」。你会给入职文档、解释构建系统、指出测试放在哪里,并提醒哪些代码别动。

AI 编程 Agent 也需要同样的东西。没有项目上下文,Agent 会猜测你的约定、用错测试运行器、忽略分支策略,写出和项目格格不入的代码。AGENTS.md 通过一份结构化的入职文档解决这个问题——Agent 开工前可以先读它。

ELI5:把 AGENTS.md 想成欢迎礼包

想象公司在新人第一天发一张一页纸速查表:WiFi 密码、怎么跑构建、风格指南在哪、什么永远别碰。AGENTS.md 就是那张速查表——不过是给在你代码库上工作的 AI Agent 用的。

核心要点: AGENTS.md 是放在仓库里的简单 Markdown 文件,用来告诉 AI Agent 如何在你的项目上工作。多数主流 AI 编程工具会自动读取它。

Interactive AGENTS.md Template Builder

Toggle sections on/off to build your AGENTS.md. Click to expand and see sample content.

📄 AGENTS.md Preview

        

什么是 AGENTS.md

AGENTS.md 是开放格式的 Markdown 文件,放在仓库中。它为 AI 编程 Agent(如 Claude Code、Cursor、GitHub Copilot、Gemini 等)提供说明与上下文。

没有特殊 schema,不要求 YAML frontmatter,不依赖特定工具链。就是普通 Markdown。写法就像给人类写说明——本质上也确实是:给会像人一样读文档的 AI 用的说明。

它解决什么问题

没有 AGENTS.md 时,每次用 AI 编程 Agent 你都在重复自己:

  • 「我们用 pytest,不用 unittest」
  • 「提交前先跑 make lint」
  • 「API 代码在 src/api/,前端在 web/」
  • 「永远不要改 vendor/ 里的文件」

AGENTS.md 把这些写一次、放一处,这样每个接触代码的 Agent 都带着正确上下文起步。

它如何工作

  1. 在仓库根目录放一份 AGENTS.md
  2. AI 编程 Agent 开始处理项目时会自动发现并读取
  3. 这些说明影响 Agent 如何写代码、跑测试、做决策
  4. 也可以在子目录再放 AGENTS.md,做区域级指引

就这样。无需配置、无需构建步骤、无需集成工作。


简史

AGENTS.md 于 2025 年 8 月由 OpenAI(Codex)、Amp、Google(Jules)、Cursor 与 Factory 协作提出。各家没有各自搞专有格式,而是约定了一套共享、开放的标准。

2025 年 12 月,AGENTS.md 贡献给 Linux Foundation 旗下的 Agentic AI Foundation (AAIF),与 Anthropic 的 Model Context Protocol(MCP)以及 Block 的 Goose 并列。它现已成为由基金会托管的开放标准。

截至 2026 年初,已有超过 60,000 个开源仓库包含 AGENTS.md 文件。


AGENTS.md 里写什么

对成千上万真实仓库的分析表明,六个核心区域影响最大:

1. Commands(命令)

构建、lint、测试、运行项目的确切命令。要具体——写上 flag 和选项,别只写工具名。

## Commands

- Build: `npm run build`
- Lint: `npm run lint -- --fix`
- Test all: `npm test`
- Test single file: `npm test -- --testPathPattern=<filename>`
- Dev server: `npm run dev` (runs on port 3000)
- Type check: `npx tsc --noEmit`

为什么重要:知道确切命令的 Agent 可以在提交结果前自己跑测试和 lint,验证工作。

2. Testing(测试)

测试如何组织、用什么框架,以及写新测试时应遵循的约定。

## Testing

- Framework: pytest with pytest-asyncio for async tests
- Test location: tests mirror src structure (src/api/users.py -> tests/api/test_users.py)
- Naming: test files start with `test_`, test functions start with `test_`
- Fixtures: shared fixtures live in tests/conftest.py
- Run a single test: `pytest tests/api/test_users.py::test_create_user -v`

3. Project structure(项目结构)

东西放在哪的地图。Agent 知道该看哪些目录时会工作得更好。

## Project Structure

- `src/api/` - REST API endpoints (FastAPI)
- `src/core/` - Business logic, domain models
- `src/db/` - Database models and migrations (SQLAlchemy + Alembic)
- `src/workers/` - Background task processors
- `web/` - React frontend (Vite + TypeScript)
- `infra/` - Terraform infrastructure definitions
- `scripts/` - Developer utility scripts

4. Code style(代码风格)

命名约定、格式规则、偏好模式。一小段展示风格的代码示例,比大段文字描述更有用。

## Code Style

- Python: Black formatting, isort for imports, Google-style docstrings
- TypeScript: Prettier + ESLint, functional components with hooks
- Naming: snake_case for Python, camelCase for TypeScript
- Prefer explicit over implicit - no magic imports or star exports
- Error handling: use custom exception classes from src/core/exceptions.py

5. Git workflow(Git 工作流)

分支策略、提交信息约定、PR 要求。

## Git Workflow

- Branch from `main`, prefix with `feat/`, `fix/`, or `chore/`
- Commit messages: conventional commits format (e.g., "feat: add user search endpoint")
- Squash merge PRs
- All PRs require passing CI and one approval

6. Boundaries(边界)

Agent 永远不该碰什么。这是最重要的章节之一。

## Do Not Modify

- `vendor/` - third-party code, managed externally
- `.env` files - contain secrets, never commit
- `infra/production/` - production infrastructure, requires manual review
- `src/db/migrations/` - generate migrations with Alembic, do not write by hand
- `package-lock.json` - only modify via npm install

Monorepo 中的分层 AGENTS.md

你可以在目录树多层放置 AGENTS.md。Agent 会读取当前目录或其父级中最近的那份。这对不同区域有不同约定的 monorepo 很有用。

my-monorepo/
  AGENTS.md              # Shared conventions (git workflow, CI, etc.)
  services/
    api/
      AGENTS.md          # Python-specific: pytest, Black, FastAPI patterns
    frontend/
      AGENTS.md          # TypeScript-specific: Vitest, Prettier, React patterns
    ml-pipeline/
      AGENTS.md          # Python + notebooks: data conventions, model testing

每个子项目的 AGENTS.md 可专注该区域独有内容。根级文件覆盖共享实践。


AGENTS.md 与其他 Agent 配置文件

多种 AI 工具有各自的说明文件格式。内容大量重叠——构建命令、编码标准、项目结构。差异在于工具特有功能。

文件 工具 特殊能力
AGENTS.md 跨工具标准 通用、无特殊语法、多数 Agent 可读
CLAUDE.md Claude Code 支持 @path 导入做模块化说明
.cursor/rules/*.mdc Cursor 带激活模式的 YAML frontmatter(Always、Auto、Agent Requested)。注意:旧版 .cursorrules 已弃用。
.github/copilot-instructions.md GitHub Copilot 带 glob 的 scoped .instructions.md
GEMINI.md Gemini Gemini 专用说明

实务做法

共享说明放进 AGENTS.md。多数工具会读它。只有需要某工具独有功能时,再用工具专用文件。

若已有 CLAUDE.md 或 .cursor/rules/,不必把一切再抄进 AGENTS.md。但若希望说明跨多种工具生效,AGENTS.md 是公约数。


最佳实践

保持简洁

目标 150 行以内。文件太长会淹没重要信息,并浪费 Agent 上下文窗口的 token。若 AGENTS.md 比 README 还长,多半太长了。

具体且可执行

差:「我们用现代 JavaScript 技术栈」 好:「React 18 + TypeScript 5.3、Vite 5、Tailwind CSS 3.4」

差:「遵循标准测试实践」 好:「跑 npm test -- --coverage,新代码保持 >80% 行覆盖率」

展示,而不是空讲

代码示例传达风格,比一段描述更有效。

## API Endpoint Pattern

New endpoints should follow this structure:

\```python
@router.post("/users", response_model=UserResponse, status_code=201)
async def create_user(
    request: CreateUserRequest,
    db: AsyncSession = Depends(get_db),
    current_user: User = Depends(get_current_user),
) -> UserResponse:
    """Create a new user account."""
    user = await user_service.create(db, request)
    return UserResponse.from_orm(user)
\```

根据 Agent 行为迭代

从最小 AGENTS.md 起步。发现 Agent 反复犯同一错误时,加一条说明纠正。最好的 AGENTS.md 靠迭代生长,而不是一次性规划写完。

当代码一样对待

构建流程、测试约定或项目结构变更时,在同一 PR 里更新 AGENTS.md。过时说明比没有说明更糟——它们会主动误导 Agent。

必要时写上「为什么」

对不显而易见的规则,简短解释有助于 Agent 在边界情况下正确应用。

- Do not use `datetime.now()` directly. Use `src/core/clock.py` instead.
  This allows tests to control time without monkeypatching.

完整示例

下面是一份面向 Python Web 应用的真实感 AGENTS.md:

# AGENTS.md

## Project

Order management API built with FastAPI and PostgreSQL.
Python 3.12, managed with Poetry.

## Commands

- Install dependencies: `poetry install`
- Run dev server: `poetry run uvicorn src.main:app --reload --port 8000`
- Run all tests: `poetry run pytest`
- Run single test: `poetry run pytest tests/path/to/test.py -v`
- Lint: `poetry run ruff check src tests`
- Format: `poetry run ruff format src tests`
- Type check: `poetry run mypy src`
- Generate migration: `poetry run alembic revision --autogenerate -m "description"`
- Apply migrations: `poetry run alembic upgrade head`

## Project Structure

- `src/api/` - API route handlers
- `src/core/` - Business logic and domain models
- `src/db/` - SQLAlchemy models and Alembic migrations
- `src/services/` - External service integrations
- `tests/` - Mirrors src structure

## Code Style

- Ruff for linting and formatting (config in pyproject.toml)
- Google-style docstrings on public functions
- Type hints on all function signatures
- Prefer `async def` for all route handlers
- Use dependency injection via FastAPI's `Depends()`

## Testing

- pytest with pytest-asyncio
- Use factories from `tests/factories.py` to create test data
- Tests run against a real PostgreSQL database (not mocks)
- Each test function gets a fresh transaction that rolls back

## Git

- Branch naming: `feat/`, `fix/`, `chore/` prefixes
- Conventional commits
- Squash merge to main

## Do Not Modify

- `alembic/versions/` - Do not edit migration files by hand
- `.env` and `.env.local` - Contains secrets
- `src/core/legacy_adapter.py` - Scheduled for removal, do not add new code here

当 AGENTS.md 不够用时

AGENTS.md 很适合项目级上下文。但有些场景需要更多:

  • 动态工具访问 —— 若 Agent 需要查库、调 API 或与外部服务交互,你需要 MCP server 或 tools,而不只是说明文字。
  • 可复用工作流 —— 若要把多步流程打包成 Agent 可调用的能力,见 Agent Skills。
  • 跨 Agent 协作 —— 若多个 Agent 需要一起工作,需要 编排层(orchestration)。

AGENTS.md 是基础。可以把它想成让其他一切更好用的第一层上下文。


自己动手试

  1. 在某个项目里创建 AGENTS.md
  2. 先只写 Commands 和 Project Structure
  3. 用 AI 编程 Agent 在该项目上工作,看它是否遵循说明
  4. 发现 Agent 出错时,补充说明来纠正
  5. 持续打磨,直到 Agent 稳定产出贴合项目的代码

关键要点

  • AGENTS.md 是普通 Markdown 文件,告诉 AI Agent 如何在你的项目上工作
  • 它是开放标准,获多数主流 AI 编程工具支持
  • 聚焦六个区域:commands、testing、project structure、code style、git workflow、boundaries
  • 保持简洁(150 行以内)、具体,并及时更新
  • 从简单开始,根据 Agent 做错的地方迭代
  • Monorepo 用分层文件做区域指引
  • 共享说明放 AGENTS.md,工具特有功能放各自配置文件

延伸阅读


上一课:Agent Protocols - MCP and A2A | 下一课:MCP Deep Dive ->