# https://github.com/promptfoo/promptfoo 项目说明书

生成时间：2026-06-20 16:43:11 UTC

## 目录

- [项目概览](#page-overview)
- [Lib 模块](#page-src-commands-mcp-lib)
- [Lib 模块](#page-src-app-src-lib)
- [Src 模块](#page-code-scan-action-src)

<a id='page-overview'></a>

## 项目概览

### 相关页面

相关主题：[Lib 模块](#page-src-commands-mcp-lib)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [package.json](https://github.com/promptfoo/promptfoo/blob/main/package.json)
- [site/README.md](https://github.com/promptfoo/promptfoo/blob/main/site/README.md)
- [examples/openai-mcp/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/openai-mcp/README.md)
- [examples/claude-agent-sdk/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/claude-agent-sdk/README.md)
- [examples/openai-codex-sdk/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/openai-codex-sdk/README.md)
- [examples/anthropic/structured-outputs/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/anthropic/structured-outputs/README.md)
- [examples/google-vertex/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/google-vertex/README.md)
- [examples/openai-structured-output/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/openai-structured-output/README.md)
- [examples/compare-agentic-sdks/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/compare-agentic-sdks/README.md)
- [src/commands/mcp/lib/toolRegistry.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts)
- [src/commands/mcp/lib/utils.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/utils.ts)
- [src/redteam/providers/README.md](https://github.com/promptfoo/promptfoo/blob/main/src/redteam/providers/README.md)
- [examples/eval-markdown-rendering/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/eval-markdown-rendering/README.md)
- [examples/provider-elevenlabs/tts-advanced/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/provider-elevenlabs/tts-advanced/README.md)
</details>

# 项目概览

## 一、项目定位与目标

promptfoo 是一个面向大语言模型（LLM）应用的**评估与测试工具集（LLM eval & testing toolkit）**。从 [package.json](https://github.com/promptfoo/promptfoo/blob/main/package.json) 的描述可以确认，其核心定位是为开发者提供对 LLM 提示词、Agent 行为以及多模态输出进行系统化、可重复的验证能力。仓库当前版本为 `0.121.17`，遵循 MIT 协议发布，作者为 Ian Webster 资料来源：[package.json:1-15]()。

该项目的设计目标可以归纳为三个层面：

1. **覆盖广泛的模型与协议**——同时支持 OpenAI、Anthropic、Google Vertex、Cerebras、ElevenLabs、AWS Bedrock 等多家厂商，以及 Model Context Protocol（MCP）、A2A、OpenAI Codex SDK、Claude Agent SDK 等新兴的 Agent 通信或开发协议。
2. **提供端到端的工作流**——从本地配置（`promptfooconfig.yaml` / `.ts`）、命令行执行、结果浏览器（`promptfoo view`），到代码扫描 GitHub Action（`code-scan-action`）。
3. **支持红队与安全评估**——仓库内置 `src/redteam/` 目录，提供对抗性测试、Unblocking、Crescendo、GOAT 等多策略攻击链路。

## 二、核心架构与组件划分

promptfoo 的代码组织呈典型的"核心库 + 命令 + 示例"三层结构。运行时通过 Node.js 入口加载，并对外暴露 CLI 二进制命令。

| 模块路径 | 主要职责 | 关键产物 |
| --- | --- | --- |
| `src/` | 核心评估引擎、Provider、断言系统 | `dist/src/index.js`（`main` 字段） |
| `src/commands/mcp/lib/` | MCP 协议服务、工具注册 | `toolRegistry.ts`、`utils.ts` |
| `src/redteam/providers/` | 对抗性测试与红队策略 | Crescendo / GOAT / Unblocking |
| `examples/` | 可直接运行的配置示例 | `openai-mcp`、`claude-agent-sdk` 等 |
| `site/` | 基于 Docusaurus 的官方文档站 | `llms-full.txt`、`llms.txt` |

入口二进制在 [package.json](https://github.com/promptfoo/promptfoo/blob/main/package.json) 的 `bin` 字段中声明为 `promptfoo` 与 `pf` 两个命令别名。`exports` 字段同时提供 ESM 与 CJS 入口，并对外暴露 `./contracts` 类型子路径，使下游项目能够复用 promptfoo 的契约类型。资料来源：[package.json:16-50]()。

### 整体数据流

```mermaid
flowchart LR
    Config[promptfooconfig.yaml] --> Loader[Config Loader]
    Loader --> Provider[Provider Adapter]
    Provider -->|HTTP/RPC| Target[(目标 LLM/Agent)]
    Target -->|原始输出| Assert[Assertion Engine]
    Assert -->|通过/失败 + 评分| Reporter[Reporter / Web UI]
    Reporter --> User((开发者))
    RedTeam[redteam/providers] -. 注入对抗 .-> Provider
    MCP[MCP Server] -. 工具调用 .-> Provider
```

该图概括了从配置加载到结果呈现的完整链路，并标出 MCP 工具调用与红队对抗两条非主流程的注入路径。

## 三、关键能力与典型用法

### 1. 协议与模型适配

`examples/openai-mcp/README.md` 演示了如何通过 `type: mcp` 工具定义接入远程 MCP 服务（如 `https://mcp.deepwiki.com/mcp`），并支持 `require_approval` 的精细控制。资料来源：[examples/openai-mcp/README.md:1-40]()。`examples/openai-codex-sdk/README.md` 则展示了基于 `@openai/codex-sdk` 的 Agent 评估模式，支持线程持久化、Git 感知以及 `codex_path_override` 自定义二进制。资料来源：[examples/openai-codex-sdk/README.md:1-60]()。

### 2. 结构化输出与 Agent 测试

Anthropic、OpenAI、Vertex AI 等示例目录均覆盖了结构化输出（JSON schema / `output_format`）能力。`examples/anthropic/structured-outputs/README.md` 强调"JSON 输出 vs. 严格工具调用"的适用场景；`examples/openai-structured-output/README.md` 区分了 Chat API 与 Responses API 的内联与外联 schema 用法。资料来源：[examples/anthropic/structured-outputs/README.md:1-30]()、[examples/openai-structured-output/README.md:1-25]()。

### 3. MCP 服务端与工具注册

`src/commands/mcp/lib/toolRegistry.ts` 维护了一个"工具元数据单一事实源（single source of truth）"，其中包含 `list_evaluations`、`get_evaluation_details`、`run_evaluation`、`share_evaluation` 等核心工具的定义，并标注了 `readOnlyHint`、`idempotentHint`、`longRunningHint` 等 MCP 注解。资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-25]()。`utils.ts` 提供了统一的 `createToolResponse`、`withTimeout`、`safeStringify` 等辅助函数，默认将长任务超时设为 5 分钟。资料来源：[src/commands/mcp/lib/utils.ts:1-20]()。

### 4. 红队与 Agent 对比

`src/redteam/providers/README.md` 描述了图像红队、Unblocking（自动回答目标模型的澄清性问题）等高级流程。`examples/compare-agentic-sdks/README.md` 通过 OpenAI Codex、Claude Agent、OpenCode、纯 LLM 四种方案的对比，凸显 SDK 工具调用在真实代码审计任务中的优势。资料来源：[examples/compare-agentic-sdks/README.md:1-30]()。

## 四、社区关注与已知问题

仓库近期发版节奏密集，0.121.x 系列涵盖了 `MiniMax provider`（0.121.13）、A2A provider（0.121.14）、多模态断言评分（0.121.15）等多项能力。社区讨论中也有若干反复出现的诉求：

- **Per-test-case `repeat` 选项**（issue #9700）：用户希望在负向断言场景中按测试用例粒度控制重复次数，以排除偶然通过；
- **`--repeat` UI 分组**（issue #992）：在 Web 视图中将重复结果折叠显示，便于阅读；
- **多配置文件独立执行**（issue #1098）：避免 `promptfoo eval -c a.yaml b.yaml` 时被合并到同一运行；
- **按 Prompt 拆分测试**（issue #1092）：支持将不同子集绑定到不同 Prompt；
- **`promptfooconfig.yaml` 的 JSON Schema**（issue #726）：增强 IDE 提示与错误校验。

最新版本 0.121.17 修复了 Docker 镜像中 Python 版本与 Alpine 基础镜像的匹配问题，表明项目在跨平台可复现性方面持续投入。

## 五、版本与运行环境

`package.json` 中的 `engines` 字段要求 Node.js `^20.20.0 || >=22.22.0`，对应到各 SDK 示例的运行前提，例如 Codex SDK 同样要求 Node 20.20+。资料来源：[package.json:60-75]()、[examples/openai-codex-sdk/README.md:1-25]()。官方文档站 `site/` 基于 Docusaurus 2 构建，并在构建过程中自动生成 `llms.txt` 与 `llms-full.txt` 以支持 LLM 驱动的检索工具。资料来源：[site/README.md:1-20]()。

## See Also

- 评估与断言系统：参考 `src/assertions/` 目录与 `examples/*/README.md` 中的断言样例
- Red Team 攻击策略：`src/redteam/providers/README.md`
- MCP 工具注册表：`src/commands/mcp/lib/toolRegistry.ts`
- 官方文档站构建流程：`site/README.md`

---

<a id='page-src-commands-mcp-lib'></a>

## Lib 模块

### 相关页面

相关主题：[项目概览](#page-overview), [Lib 模块](#page-src-app-src-lib)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/commands/mcp/lib/errors.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/errors.ts)
- [src/commands/mcp/lib/performance.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/performance.ts)
- [src/commands/mcp/lib/resultFormatter.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/resultFormatter.ts)
- [src/commands/mcp/lib/security.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/security.ts)
- [src/commands/mcp/lib/toolRegistry.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts)
- [src/commands/mcp/lib/types.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/types.ts)
</details>

# Lib 模块

## 概述

`Lib` 模块位于 [`src/commands/mcp/lib/`](https://github.com/promptfoo/promptfoo/tree/main/src/commands/mcp/lib) 目录，是 promptfoo 项目中 MCP（Model Context Protocol）命令的内部支撑库。它向 [`src/commands/mcp/`](https://github.com/promptfoo/promptfoo/tree/main/src/commands/mcp) 上层命令与 MCP 服务器实现提供可复用的工具注册、错误处理、性能监控、结果格式化、安全控制与类型定义等子模块。该模块体现了单一职责的设计思路：每个文件聚焦一类横切关注点，避免与具体命令逻辑耦合，从而保证上层 MCP 服务能够专注于协议通信与业务编排。

资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-50]()

## 模块组成

`Lib` 模块由六个相互协作的子模块组成，结构如下表所示。

| 文件 | 主要职责 | 关键导出 |
|------|----------|----------|
| `toolRegistry.ts` | 注册与维护 MCP 工具的元数据 | `TOOL_DEFINITIONS`、`ToolMetadata` |
| `errors.ts` | 统一错误类型与错误码映射 | 自定义错误类 |
| `performance.ts` | 调用延迟、并发与超时统计 | 性能计时工具 |
| `resultFormatter.ts` | 评估结果的可读化输出 | 格式化函数 |
| `security.ts` | 鉴权、输入校验与权限策略 | 安全中间件 |
| `types.ts` | 跨子模块共享的类型与接口 | `ToolMetadata`、`Eval*` 接口 |

资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()、[src/commands/mcp/lib/types.ts]()、[src/commands/mcp/lib/security.ts]()

## Tool Registry：单一事实来源

`toolRegistry.ts` 是该模块的"单一事实来源"（single source of truth）。它导出数组 [`TOOL_DEFINITIONS: ToolMetadata[]`](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts)，集中维护所有 MCP 工具的名称、描述、参数签名与注解。注释明确指出该数组"是工具文档的唯一来源"，新增或修改工具必须在此处同步，否则 MCP 客户端无法获得最新的 schema 描述。

资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()

### 已注册工具类别

根据 `toolRegistry.ts` 顶部注释与导出内容，至少包含"evaluation"类别的四个核心工具：

- `list_evaluations` —— 分页列出评估运行，支持 `datasetId`、`page`、`pageSize` 过滤；标记为 `readOnlyHint: true` 与 `idempotentHint: true`。
- `get_evaluation_details` —— 通过 `id` 获取评估详情及指标，幂等且只读。
- `run_evaluation` —— 通过 `configPath` 触发评估执行，支持 `testCaseIndices`、`promptFilter`、`providerFilter`、`maxConcurrency`（1-20）、`timeoutMs`（1 秒至 5 分钟）、`resultLimit`、`resultOffset`；标记为 `longRunningHint: true`，因评估通常耗时较长。
- `share_evaluation` —— 创建可公开分享的评估链接（数组中下一项所示）。

资料来源：[src/commands/mcp/lib/toolRegistry.ts:10-50]()

每个工具条目均包含 `name`、`description`、`parameters`（字符串签名描述）、`annotations`（`readOnlyHint`、`idempotentHint`、`longRunningHint`）与 `category` 字段，便于上层 MCP server 自动生成协议层描述与调用策略。

### 与社区需求的呼应

社区长期关注"按提示分离测试"、"多配置独立评估"以及 `--repeat` 模式下 UI 分组等痛点（参见 issue [#1092](https://github.com/promptfoo/promptfoo/issues/1092)、[#1098](https://github.com/promptfoo/promptfoo/issues/1098) 与 [#992](https://github.com/promptfoo/promptfoo/issues/992)）。`toolRegistry.ts` 中的 `run_evaluation` 工具通过显式暴露 `testCaseIndices`、`promptFilter`、`providerFilter` 参数，使这些场景可通过 MCP 接口直接表达，而无需 CLI 多次调用。

资料来源：[src/commands/mcp/lib/toolRegistry.ts:36-45]()

## 错误、性能与安全协同

错误、性能与安全三个子模块形成横切层。`errors.ts` 定义统一错误类型，使上层 MCP 处理器能够将异常序列化为协议友好的错误响应；`performance.ts` 为 `run_evaluation` 等长任务提供计时与超时信号，与 `toolRegistry.ts` 中 `timeoutMs` 的取值范围（1 秒至 5 分钟）保持一致；`security.ts` 负责输入校验与权限决策，对应 `maxConcurrency` 上限（1-20）以及 `resultLimit`（1-100）的边界检查，防止资源滥用。

`resultFormatter.ts` 则承接 `performance.ts` 的统计数据，把评估结果以适合 LLM 消费的精简结构返回，是"原始评估数据 → MCP 响应"链路中的关键适配层。

资料来源：[src/commands/mcp/lib/performance.ts]()、[src/commands/mcp/lib/security.ts]()、[src/commands/mcp/lib/resultFormatter.ts]()

## 数据流架构

```mermaid
flowchart LR
  A[MCP Client] -->|JSON-RPC 调用| B[MCP Server]
  B --> C{toolRegistry.ts}
  C -->|查找 ToolMetadata| D[Handlers]
  D --> E[evaluation pipeline]
  E --> F[resultFormatter.ts]
  E -.latency.-> G[performance.ts]
  D -.validate.-> H[security.ts]
  D -.raise.-> I[errors.ts]
  F --> B
  I --> B
  G --> B
  B -->|JSON-RPC 响应| A
```

资料来源：[src/commands/mcp/lib/toolRegistry.ts]()、[src/commands/mcp/lib/errors.ts]()、[src/commands/mcp/lib/performance.ts]()、[src/commands/mcp/lib/resultFormatter.ts]()、[src/commands/mcp/lib/security.ts]()

## 常见使用模式

- **新增工具**：在 [`toolRegistry.ts`](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts) 的 `TOOL_DEFINITIONS` 数组中追加条目，并在对应 handler 中实现业务逻辑。
- **调整超时或并发**：通过 `run_evaluation` 工具的 `maxConcurrency` 与 `timeoutMs` 参数控制，校验逻辑由 `security.ts` 与 `performance.ts` 共同保障。
- **统一错误响应**：handler 抛出 `errors.ts` 中定义的错误类型，由协议层负责映射为标准错误码。
- **结果格式化**：所有经 MCP 返回的评估数据都需通过 `resultFormatter.ts` 处理，避免泄露内部敏感字段。

## 另请参阅

- [src/commands/mcp/lib/toolRegistry.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts) —— 工具元数据单一来源
- [src/commands/mcp/README.md](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp) —— MCP 命令顶层文档
- [src/commands/mcp/lib/types.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/types.ts) —— 跨子模块类型定义
- Issue [#1092](https://github.com/promptfoo/promptfoo/issues/1092)、[#1098](https://github.com/promptfoo/promptfoo/issues/1098) —— 与"按提示/按配置分离测试"相关的社区讨论
- Issue [#992](https://github.com/promptfoo/promptfoo/issues/992) —— 关于 `--repeat` 结果分组的 UI 增强诉求

---

<a id='page-src-app-src-lib'></a>

## Lib 模块

### 相关页面

相关主题：[Lib 模块](#page-src-commands-mcp-lib), [Src 模块](#page-code-scan-action-src)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [src/commands/mcp/lib/toolRegistry.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts)
- [package.json](https://github.com/promptfoo/promptfoo/blob/main/package.json)
- [examples/openai-mcp/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/openai-mcp/README.md)
- [examples/claude-agent-sdk/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/claude-agent-sdk/README.md)
- [examples/anthropic/structured-outputs/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/anthropic/structured-outputs/README.md)
- [examples/anthropic/web-tools/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/anthropic/web-tools/README.md)
- [site/README.md](https://github.com/promptfoo/promptfoo/blob/main/site/README.md)
</details>

# Lib 模块

## 概述

Lib 模块是 promptfoo 项目中封装各类底层工具、共享逻辑与领域功能的核心代码集合体。promptfoo 是一个 LLM 评估与测试工具包（"LLM eval & testing toolkit"），其仓库 `package.json` 中将自身定位为可通过 CLI 调用的工具链，并暴露 `promptfoo` 与 `pf` 两个二进制入口 资料来源：[package.json:1-50]()。在源码层面，`src/commands/mcp/lib/` 是其中一个典型的 Lib 子模块，承载了 MCP（Model Context Protocol）相关命令运行时的辅助功能，例如工具注册表（tool registry）的元数据维护。

整个 promptfoo 的 Lib 模块遵循"单一来源真相（single source of truth）"原则，在 MCP 子模块中通过集中化的 `TOOL_DEFINITIONS` 数组描述所有可被外部调用的工具，避免元数据散落在多处。资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()。

## MCP Lib 模块的目录职责

`src/commands/mcp/lib/toolRegistry.ts` 的开头注释明确指出，该文件保存"所有 MCP 工具及其元数据"，是工具文档的"单一来源真相"。资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-5]()。

具体来说，文件导出 `TOOL_DEFINITIONS: ToolMetadata[]`，每一项都包含：

| 字段 | 类型 | 说明 |
|---|---|---|
| `name` | string | 工具名称，例如 `list_evaluations`、`run_evaluation` |
| `description` | string | 工具的语义化描述，用于 LLM/客户端理解用途 |
| `parameters` | string | 参数签名（简化为可读字符串） |
| `annotations` | object | MCP 注解，含 `readOnlyHint`、`idempotentHint`、`longRunningHint` |
| `category` | string | 工具分类，例如 `evaluation`、`sharing`、`generation` |

资料来源：[src/commands/mcp/lib/toolRegistry.ts:6-50]()。

工具分类涵盖：

- **evaluation（评估）**：例如 `list_evaluations`、`get_evaluation_details`、`run_evaluation`，提供评估结果浏览与触发执行的能力；其中 `run_evaluation` 通过 `configPath`、`testCaseIndices`、`promptFilter`、`providerFilter`、`maxConcurrency`、`timeoutMs`、`resultLimit`、`resultOffset` 等参数控制执行范围与分页 资料来源：[src/commands/mcp/lib/toolRegistry.ts:10-45]()。
- **sharing（分享）**：例如 `share_evaluation`，用于生成可公开分享的链接 资料来源：[src/commands/mcp/lib/toolRegistry.ts:50-60]()。

注解（annotations）字段对 MCP 客户端尤其重要，例如 `run_evaluation` 被标记为 `readOnlyHint: false`、`idempotentHint: false`、`longRunningHint: true`，用以提示调用方这是一个长时、非幂等且具有副作用的操作。资料来源：[src/commands/mcp/lib/toolRegistry.ts:35-45]()。

## 与外部 Provider 生态的协作

promptfoo 的 Lib 模块不仅支撑自有 CLI，还通过多个 Provider 适配层与外部 AI 服务协作。MCP 子模块的 Lib 同时服务于类似 `examples/openai-mcp/` 中演示的 MCP 工具接入方式——在该示例中，OpenAI 通过 `type: mcp` 的工具条目连接 DeepWiki MCP Server，并通过 `allowed_tools` 与 `require_approval` 控制可用工具与审批策略。资料来源：[examples/openai-mcp/README.md:1-40]()。

在 Anthropic 生态中，Lib 模块以插件/Provider 形式承载各类结构化输出与工具能力，例如 `examples/anthropic/structured-outputs/` 演示了 `output_format` 的 JSON schema 用法与工具的 `strict: true` 模式，资料来源：[examples/anthropic/structured-outputs/README.md:30-60]()；`examples/anthropic/web-tools/` 则演示了 `web_search_20250305` 与 `web_fetch_20250910` 工具的组合调用，资料来源：[examples/anthropic/web-tools/README.md:1-40]()。

`examples/claude-agent-sdk/` 进一步说明 Claude Agent SDK 的 Lib 能力：包括沙箱隔离、运行时选择（`node`/`bun`/`deno`）、`AskUserQuestion` 工具处理以及 Skills 测试等；其 `append_allowed_tools` 与 `ask_user_question.behavior` 等字段也是由对应 Lib 模块解析的。资料来源：[examples/claude-agent-sdk/README.md:1-60]()。

## 文档与发布支撑

Lib 模块在交付层面也支撑了文档站（`site/`）的自动化生成。`site/README.md` 描述了基于 Docusaurus 2 的文档站点与自定义 LLMs.txt 插件：该插件会在 `npm run build` 时聚合所有 markdown/MDX 内容并输出 `llms-full.txt` 与 `llms.txt`，供 LLM 工具检索使用。资料来源：[site/README.md:1-30]()。

配合 `package.json` 中声明的工作区（`src/app`、`site`）以及 `engines` 字段（`^20.20.0 || >=22.22.0`），Lib 模块在 Node.js 双大版本下可一致地被构建与发布。资料来源：[package.json:30-60]()。

## 常见注意事项

1. **版本敏感性**：`engines` 显式要求 Node.js 20.20+ 或 22.22+，在更早版本下 MCP 长时工具（`longRunningHint: true`）的超时控制可能行为不一致。资料来源：[package.json:48-50]()。
2. **工具幂等性**：`run_evaluation` 标注为非幂等，重复调用会触发新的评估运行，社区已有相关讨论希望"按测试粒度控制重复次数"——见 [#9700](https://github.com/promptfoo/promptfoo/issues/9700)。
3. **MCP 审批策略**：使用 `require_approval` 时支持 `never` / `never.tool_names` 等选择性子键；若选择 `never` 但未指定 `tool_names`，将默认授权所有工具，调用方需自行评估风险。资料来源：[examples/openai-mcp/README.md:30-50]()。

## See Also

- [Promptfoo MCP 文档](https://promptfoo.dev/docs/)
- [Model Context Protocol 规范](https://modelcontextprotocol.io/)
- 相关 Issue：[#9700 Per-test-case repeat option](https://github.com/promptfoo/promptfoo/issues/9700)、[#1395 Compare runs](https://github.com/promptfoo/promptfoo/issues/1395)、[#992 Group --repeat tests](https://github.com/promptfoo/promptfoo/issues/992)

---

<a id='page-code-scan-action-src'></a>

## Src 模块

### 相关页面

相关主题：[Lib 模块](#page-src-app-src-lib)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [package.json](https://github.com/promptfoo/promptfoo/blob/main/package.json)
- [src/commands/mcp/lib/toolRegistry.ts](https://github.com/promptfoo/promptfoo/blob/main/src/commands/mcp/lib/toolRegistry.ts)
- [src/redteam/providers/README.md](https://github.com/promptfoo/promptfoo/blob/main/src/redteam/providers/README.md)
- [examples/openai-mcp/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/openai-mcp/README.md)
- [examples/claude-agent-sdk/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/claude-agent-sdk/README.md)
- [examples/compare-agentic-sdks/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/compare-agentic-sdks/README.md)
- [examples/openai-codex-sdk/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/openai-codex-sdk/README.md)
- [examples/redteam-harmbench/README.md](https://github.com/promptfoo/promptfoo/blob/main/examples/redteam-harmbench/README.md)
- [site/README.md](https://github.com/promptfoo/promptfoo/blob/main/site/README.md)
</details>

# Src 模块

## 概述

`src/` 目录是 promptfoo 的核心代码库，承载了 CLI、Provider、Assertion、Red Team、Server、App、Commands 等全部 TypeScript 源码，是发布到 npm 的 `promptfoo` 与 `pf` 二进制命令的实际实现来源 [资料来源：[package.json:1-50]()]。该模块以 ESM（`"type": "module"`）组织，并通过双重导出（`./dist/src/index.js` 与 `./dist/src/index.cjs`）同时支持 `import` 与 `require` 调用方 [资料来源：[package.json:1-50]()]。运行时要求 Node.js `^20.20.0 || >=22.22.0` [资料来源：[package.json:1-50]()]。

仓库整体是一个 monorepo，使用 npm workspaces 维护两个子项目：`src/app`（本地 Web 评估查看器）与 `site`（Docusaurus 文档站）[资料来源：[package.json:1-50]()]。

## 入口与打包契约

`package.json` 明确定义了产物的暴露方式：

| 字段 | 值 | 说明 |
| --- | --- | --- |
| `main` | `./dist/src/index.js` | CommonJS 兼容入口 |
| `exports.import.default` | `./dist/src/index.js` | ESM 默认入口 |
| `exports.import.types` | `./dist/src/index.d.ts` | ESM 类型声明 |
| `exports.require.default` | `./dist/src/index.cjs` | CJS 默认入口 |
| `types` / `typings` | `./dist/src/index.d.ts` | 顶层类型入口 |
| `bin.promptfoo` | `dist/src/entrypoint.js` | CLI 主二进制 |
| `bin.pf` | 同上 | CLI 简写二进制 |
| `contracts` | `dist/src/contracts.{js,cjs,d.ts}` | 公开契约子路径 |

仅 `dist`、`!dist/test`、`!dist/src/__mocks__`、`!dist/**/*.map` 被打包进 npm，避免泄漏测试夹具与源码映射 [资料来源：[package.json:1-50]()]。

## 核心子系统

### Commands / MCP 命令空间

`src/commands/mcp/` 是 promptfoo 的 MCP（Model Context Protocol）服务实现。`src/commands/mcp/lib/toolRegistry.ts` 导出一个 `TOOL_DEFINITIONS` 常量，作为 MCP 工具文档的唯一可信来源（single source of truth）[资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()]。该注册表按 `category` 分类，至少包含以下评估类工具：

- `list_evaluations`：分页浏览历史评测，支持按 `datasetId` 过滤；标注 `readOnlyHint` 与 `idempotentHint`[资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()]。
- `get_evaluation_details`：通过 `id` 获取某次评测的指标与测试用例详情，幂等只读 [资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()]。
- `run_evaluation`：按配置运行评测，支持 `testCaseIndices`、`promptFilter`、`providerFilter`、`maxConcurrency`、`timeoutMs`、`resultLimit`、`resultOffset` 等参数，标记为 `longRunningHint`[资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()]。
- `share_evaluation`：创建可公开分享的评测链接（条目在文件后半部分定义）[资料来源：[src/commands/mcp/lib/toolRegistry.ts:1-30]()]。

### Providers 与 Red Team

`src/providers/` 承载各模型提供方适配器，包括 Anthropic、OpenAI、Bedrock、Cerebras、Google Vertex、xAI Grok、HuggingFace、Claude Agent SDK、OpenAI Codex SDK 等；其集成示例分别落地在 `examples/anthropic/`、`examples/openai-codex-sdk/`、`examples/amazon-bedrock/`、`examples/provider-cerebras/`、`examples/google-vertex/`、`examples/xai/chat/`、`examples/huggingface/`、`examples/claude-agent-sdk/` 中 [资料来源：[examples/openai-codex-sdk/README.md:1-30]()][资料来源：[examples/compare-agentic-sdks/README.md:1-30]()]。

`src/redteam/providers/` 实现对抗性红队流程，例如基于迭代的图像越狱流水线（生成 → 目标模型 → 视觉模型判定 → 反馈循环，结束条件为 score ≥ 10 或达到最大迭代次数）[资料来源：[src/redteam/providers/README.md:1-40]()]。同一目录下还提供 *Unblocking* 机制，用于在目标模型抛出阻塞性澄清问题时自动作答，使 Crescendo、GOAT、Custom 等多轮攻击得以继续推进 [资料来源：[src/redteam/providers/README.md:1-40]()]。配合 `examples/redteam-harmbench/` 提供的 `llm-rubric` + `latency` 断言模板，可对有害请求的拒绝率与响应时延进行联合评估 [资料来源：[examples/redteam-harmbench/README.md:1-40]()]。

## 工具与契约导出

```mermaid
flowchart LR
  CLI[CLI 入口<br/>dist/src/entrypoint.js] --> Core[src/<br/>core + commands]
  Core --> MCP[commands/mcp<br/>MCP Server]
  MCP --> Registry[lib/toolRegistry.ts<br/>TOOL_DEFINITIONS]
  Core --> Providers[providers/<br/>Anthropic/OpenAI/Bedrock/...]
  Core --> RedTeam[redteam/providers/<br/>迭代式攻击]
  Core --> App[src/app<br/>Web 查看器 workspace]
  Core --> Site[site<br/>Docusaurus docs workspace]
  Registry --> Tools[MCP Tools:<br/>list/get/run/share eval]
```

通过 `./contracts` 子路径，源码层对外暴露稳定的类型契约（`dist/src/contracts.d.ts` / `contracts.d.cts`），`typesVersions` 字段进一步将 `promptfoo/contracts` 解析到对应类型文件，便于外部消费方在不引入完整运行时的前提下引用类型 [资料来源：[package.json:1-50]()]。

## 社区关注的演进点

- **重复执行（repeat）粒度**：用户希望在单个测试用例层面控制 `--repeat`，以验证“模型不应产生 X”这类反向断言的稳定性（[#9700](https://github.com/promptfoo/promptfoo/issues/9700)），同时 0.121.12 已新增 *repeat-aware fetch cache options* 以避免重复触发远程拉取（[#6844](https://github.com/promptfoo/promptfoo/issues/6844)）。
- **多配置文件隔离执行**：社区曾要求 `promptfoo eval -c a.yaml b.yaml` 改为分别运行而非合并（[#1098](https://github.com/promptfoo/promptfoo/issues/1098)），这通常涉及 `src/commands/eval.ts` 的入口逻辑。
- **UI 折叠重复用例**：`--repeat N` 在 Web Viewer 中产生大量重复行，建议按测试用例分组折叠（[#992](https://github.com/promptfoo/promptfoo/issues/992)），与 `src/app` 工作区相关。
- **多 prompt 分流测试**：希望按 prompt 子集运行测试子集（[#1092](https://github.com/promptfoo/promptfoo/issues/1092)），影响 `src/providers/` 与测试调度逻辑。
- **`promptfooconfig.yaml` JSON Schema**：社区呼吁发布官方 schema 以获得 IDE 自动补全与校验（[#726](https://github.com/promptfoo/promptfoo/issues/726)），与 `src/config` 子模块相关。

## See Also

- [Provider 适配概览](/docs/providers)（位于 `src/providers/`）
- [Red Team 插件与策略](/docs/red-team)（位于 `src/redteam/`）
- [MCP 服务与工具注册](/docs/integrations/mcp)（位于 `src/commands/mcp/`）
- [CLI 命令参考](/docs/usage/command-line)（位于 `src/entrypoint.ts`）

---

<!-- evidence_pipeline_checked: true -->
<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：promptfoo/promptfoo

摘要：发现 19 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 失败模式：installation: 0.121.8。

## 1. 安装坑 · 失败模式：installation: 0.121.8

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: 0.121.8
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.8
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.8 | 0.121.8

## 2. 安装坑 · 失败模式：installation: code-scan-action: 0.1.6

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: code-scan-action: 0.1.6
- 对用户的影响：Upgrade or migration may change expected behavior: code-scan-action: 0.1.6
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/code-scan-action-0.1.6 | code-scan-action: 0.1.6

## 3. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 证据：capability.host_targets | https://github.com/promptfoo/promptfoo | host_targets=claude, chatgpt

## 4. 配置坑 · 失败模式：configuration: 0.121.15

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: 0.121.15
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.15
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.15 | 0.121.15

## 5. 配置坑 · 失败模式：configuration: Per-test-case `repeat` option to control how many times individual tests run

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this configuration risk before relying on the project: Per-test-case `repeat` option to control how many times individual tests run
- 对用户的影响：Developers may misconfigure credentials, environment, or host setup: Per-test-case `repeat` option to control how many times individual tests run
- 证据：failure_mode_cluster:github_issue | https://github.com/promptfoo/promptfoo/issues/9700 | Per-test-case `repeat` option to control how many times individual tests run

## 6. 配置坑 · 来源证据：Per-test-case `repeat` option to control how many times individual tests run

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Per-test-case `repeat` option to control how many times individual tests run
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 证据：community_evidence:github | https://github.com/promptfoo/promptfoo/issues/9700 | 来源类型 github_issue 暴露的待验证使用条件。

## 7. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 证据：capability.assumptions | https://github.com/promptfoo/promptfoo | README/documentation is current enough for a first validation pass.

## 8. 运行坑 · 失败模式：runtime: 0.121.12

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this runtime risk before relying on the project: 0.121.12
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.12
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.12 | 0.121.12

## 9. 运行坑 · 失败模式：runtime: 0.121.14

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this runtime risk before relying on the project: 0.121.14
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.14
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.14 | 0.121.14

## 10. 维护坑 · 失败模式：migration: 0.121.13

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this migration risk before relying on the project: 0.121.13
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.13
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.13 | 0.121.13

## 11. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 证据：evidence.maintainer_signals | https://github.com/promptfoo/promptfoo | last_activity_observed missing

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 证据：downstream_validation.risk_items | https://github.com/promptfoo/promptfoo | no_demo; severity=medium

## 13. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 证据：risks.scoring_risks | https://github.com/promptfoo/promptfoo | no_demo; severity=medium

## 14. 运行坑 · 失败模式：performance: 0.121.10

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this performance risk before relying on the project: 0.121.10
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.10
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.10 | 0.121.10

## 15. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 证据：evidence.maintainer_signals | https://github.com/promptfoo/promptfoo | issue_or_pr_quality=unknown

## 16. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 证据：evidence.maintainer_signals | https://github.com/promptfoo/promptfoo | release_recency=unknown

## 17. 维护坑 · 失败模式：maintenance: 0.121.11

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: 0.121.11
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.11
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.11 | 0.121.11

## 18. 维护坑 · 失败模式：maintenance: 0.121.9

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: 0.121.9
- 对用户的影响：Upgrade or migration may change expected behavior: 0.121.9
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/0.121.9 | 0.121.9

## 19. 维护坑 · 失败模式：maintenance: code-scan-action: 0.1.7

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this maintenance risk before relying on the project: code-scan-action: 0.1.7
- 对用户的影响：Upgrade or migration may change expected behavior: code-scan-action: 0.1.7
- 证据：failure_mode_cluster:github_release | https://github.com/promptfoo/promptfoo/releases/tag/code-scan-action-0.1.7 | code-scan-action: 0.1.7

<!-- canonical_name: promptfoo/promptfoo; human_manual_source: deepwiki_human_wiki -->
