# https://github.com/Ansvar-Systems/Automotive-MCP 项目说明书

生成时间：2026-05-26 17:00:28 UTC

## 目录

- [项目介绍](#introduction)
- [快速开始](#quick-start)
- [系统架构](#system-architecture)
- [数据库架构](#database-schema)
- [工具集概览](#tools-overview)
- [list_sources 工具](#list-sources-tool)
- [get_requirement 工具](#get-requirement-tool)
- [search_requirements 工具](#search-requirements-tool)
- [export_compliance_matrix 工具](#compliance-export-tool)
- [种子数据结构](#seed-data-structure)

<a id='introduction'></a>

## 项目介绍

### 相关页面

相关主题：[快速开始](#quick-start), [系统架构](#system-architecture)

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

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

- [README.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)
- [package.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/package.json)
- [CHANGELOG.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)
- [VERIFICATION_COMPLETE.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)
- [QUALITY_ASSESSMENT_REPORT.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)
- [src/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/index.ts)
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)
</details>

# 项目介绍

## 项目概述

Automotive-MCP 是一个基于 Model Context Protocol (MCP) 的汽车网络安全法规与标准查询服务器。该项目由 Ansvar Systems 开发，旨在为汽车网络安全工程师、合规性团队和自动化工具提供高效、准确的法规条款检索能力。

**核心定位：** 作为一个 MCP 服务器，Automotive-MCP 通过标准化的 JSON-RPC 接口，将汽车网络安全相关的联合国法规和国际标准组织起来，使用户能够在 AI 助手（如 Claude Desktop）中直接查询和分析法规条款。

**版本信息：** 当前稳定版本为 **v1.0.2**，包含了对源 ID 大小写不敏感的查询优化、搜索结果数量限制校验以及更友好的输入验证错误提示等改进。

资料来源：[package.json:1-20](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/package.json)
资料来源：[CHANGELOG.md:1-10](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

---

## 核心功能

Automotive-MCP 提供三个核心工具，用于查询汽车网络安全相关的法规和标准内容。

### 工具列表

| 工具名称 | 功能描述 | 输入参数 |
|---------|---------|---------|
| `list_sources` | 列出所有可用的法规和标准来源 | 无 |
| `get_requirement` | 根据来源和引用编号获取特定条款详情 | `source`, `reference`, `include_mappings` |
| `search_requirements` | 使用全文搜索跨所有内容进行查询 | `query`, `sources`, `limit` |

资料来源：[VERIFICATION_COMPLETE.md:1-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

### 功能特性

**1. 法规检索**
- 支持按来源标识符（如 `r155`、`r156`）和引用编号（如 `7.2.2.2`）精确定位条款
- 返回完整的法规原文文本（针对联合国法规）
- 支持大小写不敏感的源 ID 查询（R155 和 r155 等效）

**2. 标准查询**
- 支持 ISO/SAE 21434 等国际标准的条款查询
- 返回标准条款的指导说明和工作产品信息
- 注意：标准全文因版权原因不包含在数据库中

**3. 全文搜索**
- 基于 SQLite FTS5 的高性能全文搜索
- 采用 BM25 相关性排名算法
- 支持搜索结果高亮显示匹配词
- 支持多来源过滤和结果数量限制

资料来源：[QUALITY_ASSESSMENT_REPORT.md:1-30](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)

---

## 技术架构

### 系统架构图

```mermaid
graph TD
    A[用户/AI 助手] -->|MCP JSON-RPC| B[Automotive-MCP 服务器]
    B --> C[工具注册表]
    C --> D[list_sources]
    C --> E[get_requirement]
    C --> F[search_requirements]
    B --> G[SQLite 数据库]
    G --> H[regulations 表]
    G --> I[standards 表]
    G --> J[regulation_content 表]
    G --> K[FTS5 全文索引]
    G --> L[work_products 表]
    G --> M[mappings 表]
```

### 核心组件

| 组件 | 职责 | 文件位置 |
|-----|------|---------|
| 服务器入口 | 初始化 MCP 服务器，处理 JSON-RPC 请求 | `src/index.ts` |
| 工具注册表 | 集中管理所有可用工具的定义和描述 | `src/tools/index.ts` |
| 数据库模块 | 处理 SQLite 连接、查询和数据检索 | `src/database/` |
| 类型定义 | TypeScript 接口和类型声明 | `src/types/index.ts` |

资料来源：[src/index.ts:1-30](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/index.ts)

### 数据模型

```mermaid
erDiagram
    regulations ||--o{ regulation_content : contains
    regulations {
        string id PK
        string name
        string version
        string type
        string description
    }
    regulation_content {
        integer id PK
        integer regulation_id FK
        string reference
        string title
        string text
        string guidance
    }
    standards {
        string id PK
        string name
        string version
        string description
    }
    work_products {
        integer id PK
        string clause_reference
        string work_product_id
        string description
        string lifecycle_phase
    }
    mappings {
        integer id PK
        string source_type
        string source_id
        string source_reference
        string target_type
        string target_id
        string target_reference
        string relationship
    }
```

资料来源：[QUALITY_ASSESSMENT_REPORT.md:50-80](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)

### 技术栈

| 层级 | 技术选型 | 说明 |
|-----|---------|------|
| 运行时 | Node.js 18+ | 服务器运行环境 |
| 语言 | TypeScript | 类型安全的开发语言 |
| 传输协议 | MCP (stdio/Streamable HTTP) | 与 AI 助手的通信协议 |
| 数据库 | SQLite + FTS5 | 轻量级全文搜索数据库 |
| 部署方式 | npm 全局包 / Docker / Vercel | 多种部署选项 |

资料来源：[README.md:1-40](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)

---

## 支持的法规和标准

### 当前支持的来源

| 来源 ID | 名称 | 类型 | 版本 | 全文可用 | 条目数量 |
|--------|------|------|------|---------|---------|
| `r155` | UN Regulation No. 155 | 法规 | Revision 2 | ✅ 是 | 1+ |
| `r156` | UN Regulation No. 156 | 法规 | Revision 2 | ✅ 是 | 0+ |
| `iso_21434` | ISO/SAE 21434:2021 | 标准 | 2021 | ❌ 否（仅指导） | 1+ |

资料来源：[VERIFICATION_COMPLETE.md:30-60](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

### UN R155 - 网络安全与网络安全管理体系

UN Regulation No. 155 是联合国关于车辆网络安全的法规，要求汽车制造商建立网络安全管理体系（CSMS），涵盖：

- 车辆相关的风险评估
- 网络攻击的检测和响应
- 安全漏洞的管理流程
- 供应链安全要求

### UN R156 - 软件更新与软件更新管理体系

UN Regulation No. 156 规定了车辆软件更新的管理要求，包括：

- 软件更新管理体系的建立
- 车辆软件更新流程的安全性
- 更新记录的保存和可追溯性

### ISO/SAE 21434 - 道路车辆网络安全工程

ISO/SAE 21434:2021 是汽车网络安全工程的标准，提供了系统性的网络安全工程方法论，涵盖：

- 风险评估方法（TARA）
- 网络安全概念和设计
- 网络安全测试和验证
- 生产、运营和维护阶段的网络安全要求

资料来源：[README.md:40-80](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)

---

## 快速开始

### 环境要求

| 要求 | 最低版本 |
|-----|---------|
| Node.js | 18.x |
| npm / pnpm | 最新稳定版 |

### 安装步骤

**方式一：npm 全局安装（推荐）**

```bash
npm install -g @ansvar/automotive-cybersecurity-mcp
```

**方式二：从源码构建**

```bash
# 克隆仓库
git clone https://github.com/Ansvar-Systems/Automotive-MCP.git
cd Automotive-MCP

# 安装依赖
npm install

# 构建 TypeScript
npm run build

# 构建数据库
npm run build:db
```

**方式三：Docker 部署**

```bash
docker pull ghcr.io/ansvar-systems/automotive-mcp:latest
docker run -p 3000:3000 ghcr.io/ansvar-systems/automotive-mcp:latest
```

资料来源：[README.md:80-120](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)

### Claude Desktop 配置

在 Claude Desktop 的配置文件中添加以下内容：

**macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`

**Windows:** `%APPDATA%\Claude\claude_desktop_config.json`

```json
{
  "mcpServers": {
    "automotive-cybersecurity": {
      "command": "npx",
      "args": ["-y", "@ansvar/automotive-cybersecurity-mcp"]
    }
  }
}
```

### 验证安装

启动 Claude Desktop 后，可使用以下示例查询验证功能：

**列出所有来源：**
```json
{
  "tool": "list_sources",
  "arguments": {}
}
```

**获取 R155 条款：**
```json
{
  "tool": "get_requirement",
  "arguments": {
    "source": "r155",
    "reference": "7.2.2.2"
  }
}
```

**搜索相关内容：**
```json
{
  "tool": "search_requirements",
  "arguments": {
    "query": "risk assessment",
    "sources": ["r155", "iso_21434"],
    "limit": 10
  }
}
```

资料来源：[VERIFICATION_COMPLETE.md:60-90](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

---

## API 参考

### list_sources

列出所有可用的法规和标准来源。

**参数：** 无

**返回示例：**
```json
[
  {
    "id": "r155",
    "name": "UN Regulation No. 155",
    "version": "Revision 2",
    "type": "regulation",
    "description": "Cyber Security and Cyber Security Management System",
    "item_count": 1,
    "full_text_available": true
  }
]
```

### get_requirement

获取特定法规或标准的条款详情。

**参数：**

| 参数名 | 类型 | 必填 | 描述 |
|-------|------|------|------|
| `source` | string | ✅ | 来源标识符（如 r155、iso_21434） |
| `reference` | string | ✅ | 条款引用编号（如 7.2.2.2、9.3） |
| `include_mappings` | boolean | ❌ | 是否包含框架映射（默认 false） |

**返回示例（法规）：**
```json
{
  "source": "r155",
  "reference": "7.2.2.2",
  "title": "Cyber Security Management System Requirements",
  "text": "The Cyber Security Management System shall be appropriate...",
  "guidance": ""
}
```

**返回示例（标准）：**
```json
{
  "source": "iso_21434",
  "reference": "9.3",
  "title": "Vulnerability analysis",
  "text": null,
  "guidance": "Monitor for vulnerabilities in components throughout vehicle lifetime...",
  "work_products": ["[WP-09-03]"]
}
```

### search_requirements

执行全文搜索查询。

**参数：**

| 参数名 | 类型 | 必填 | 描述 |
|-------|------|------|------|
| `query` | string | ✅ | 搜索关键词 |
| `sources` | string[] | ❌ | 限定来源列表（为空则搜索全部） |
| `limit` | number | ❌ | 结果数量限制（0-100，默认无限制） |

**返回示例：**
```json
[
  {
    "source": "r155",
    "reference": "7.2.2.2",
    "title": "Cyber Security Management System Requirements",
    "snippet": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related **risk** **assessment**...",
    "relevance": -0.000002
  }
]
```

资料来源：[VERIFICATION_COMPLETE.md:90-130](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

---

## 性能指标

### 查询性能

| 查询类型 | 平均耗时 | 性能评级 |
|---------|---------|---------|
| 简单查询（security） | 0.05ms | 优秀 |
| 多词查询（risk assessment） | 0.05ms | 优秀 |
| 复杂查询（vulnerability management disclosure） | 0.04ms | 优秀 |

**性能分析：**
- 所有查询均在亚毫秒级完成
- 查询性能一致，不受复杂度影响
- 远低于 10ms 的可接受阈值
- FTS5 索引性能优化良好

资料来源：[VERIFICATION_COMPLETE.md:130-160](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

### 测试覆盖

| 测试类别 | 测试数量 | 通过率 |
|---------|---------|-------|
| 数据库填充测试 | 16 | 100% |
| R155/R156 完整性测试 | 16 | 100% |
| 工具功能测试 | 29 | 100% |
| 手动集成测试 | 30 | 100% |
| **总计** | **91** | **100%** |

---

## 已知限制

### Phase 1 限制

1. **数据样本量有限**
   - 当前仅包含 1 条 R155 条款
   - R156 条款数量为 0
   - ISO 21434 仅包含 1 个条款

2. **框架映射功能**
   - 映射数据库为空
   - `include_mappings` 参数目前无实际效果
   - 计划在 Phase 2 中扩展

3. **ISO 标准全文**
   - ISO/SAE 21434 全文因版权原因不提供
   - 仅包含条款标题和指导说明

4. **搜索精确性**
   - 搜索采用精确匹配
   - 例如 "cyber attack" 与 "cyber-attacks" 视为不同词

资料来源：[QUALITY_ASSESSMENT_REPORT.md:100-130](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)

---

## 版本历史

### v1.0.2（最新版本）

**Bug 修复：**
- 源 ID 大小写不敏感：`get_requirement` 和 `search_requirements` 现在将源 ID 规范化为小写
- 搜索限制校验：`search_requirements` 将 `limit` 参数限制在 [0, 100] 范围内
- 输入验证优化：无效的枚举值现在返回更描述性的错误信息

### v1.0.1

**新增功能：**
- `list_work_products` 工具：按条款或生命周期阶段列出 ISO 21434 工作产品
- `export_compliance_matrix` 工具：导出 R155/R156 到 ISO 21434 的合规性矩阵
- `about` 工具：服务器元数据、数据集统计、指纹和来源信息
- Streamable HTTP 传输：支持 Docker 部署
- Vercel 无服务器部署支持

**技术变更：**
- SQLite 运行时从 `better-sqlite3` 迁移到 `@ansvar/mcp-sqlite`（WASM）

### v0.1.0（初始版本）

- 基础 MCP 服务器实现
- 三个核心工具（list_sources、get_requirement、search_requirements）
- R155、R156 和 ISO 21434 的初始数据集

资料来源：[CHANGELOG.md:1-40](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

---

## 参见

- [README 完整文档](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md) - 项目详细说明和配置指南
- [CHANGELOG](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md) - 完整版本历史
- [部署检查清单](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md) - 生产环境部署指南
- [质量评估报告](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md) - 详细的代码质量分析
- [测试结果](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md) - 完整的测试执行报告

---

<a id='quick-start'></a>

## 快速开始

### 相关页面

相关主题：[项目介绍](#introduction)

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

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

- [README.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)
- [package.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/package.json)
- [src/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/index.ts)
- [src/tools/list_sources.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list_sources.ts)
- [src/tools/get_requirement.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get_requirement.ts)
- [src/tools/search_requirements.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search_requirements.ts)
- [DEPLOYMENT_CHECKLIST.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md)
- [TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)
</details>

# 快速开始

本文档为 Automotive Cybersecurity MCP 服务器提供快速入门指南，帮助用户在最短时间内完成环境配置、服务启动和基本功能验证。

## 前提条件

在开始之前，请确保您的开发环境满足以下要求：

### 系统要求

| 要求项 | 最低版本 | 说明 |
|--------|----------|------|
| Node.js | 18+ | 支持 ES2022 特性和 WASM 运行时 |
| npm/pnpm | 最新稳定版 | 用于包管理和脚本执行 |
| 操作系统 | Linux/macOS/Windows | 跨平台支持 |

### MCP 客户端要求

Automotive Cybersecurity MCP 需要兼容的 MCP 客户端，官方支持以下客户端：

- **Claude Desktop** - 官方推荐客户端
- **其他 MCP 兼容客户端** - 支持 stdio 或 HTTP 传输协议

## 安装步骤

### 方式一：从 npm 安装（推荐）

使用 npm 全局安装是最简单的安装方式：

```bash
npm install -g @ansvar/automotive-cybersecurity-mcp
```

安装完成后，验证安装：

```bash
automotive-mcp --version
```

资料来源：[README.md:1-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)

### 方式二：从源码构建

如果您需要自定义配置或参与开发，请从源码构建：

```bash
# 克隆仓库
git clone https://github.com/Ansvar-Systems/Automotive-MCP.git
cd Automotive-MCP

# 安装依赖
npm install

# 构建 TypeScript 代码
npm run build

# 构建数据库
npm run build:db
```

资料来源：[DEPLOYMENT_CHECKLIST.md:1-30](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md)

## 配置 Claude Desktop

### 添加 MCP 服务器配置

编辑 Claude Desktop 配置文件：

**macOS/Linux:**
```bash
~/Library/Application Support/Claude/claude_desktop_config.json
```

**Windows:**
```bash
%APPDATA%\Claude\claude_desktop_config.json
```

在 `mcpServers` 部分添加以下配置：

```json
{
  "mcpServers": {
    "automotive-cybersecurity": {
      "command": "automotive-mcp",
      "args": []
    }
  }
}
```

资料来源：[README.md:50-80](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)

### 配置参数说明

| 参数 | 类型 | 说明 | 默认值 |
|------|------|------|--------|
| `command` | string | 启动命令 | `automotive-mcp` |
| `args` | array | 命令行参数 | `[]` |
| `env` | object | 环境变量 | `{}` |

## 服务启动与验证

### 启动服务器

配置完成后，Claude Desktop 将自动启动 MCP 服务器。您也可以手动启动进行测试：

```bash
# 启动服务器（stdio 模式）
node dist/index.js

# 预期输出
Automotive Cybersecurity MCP server started
```

资料来源：[DEPLOYMENT_CHECKLIST.md:50-60](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md)

### 协议握手验证

MCP 服务器应正确响应初始化请求：

```json
// 初始化请求
{
  "jsonrpc": "2.0",
  "method": "initialize",
  "params": {
    "protocolVersion": "2024-11-05",
    "capabilities": {},
    "clientInfo": {
      "name": "test-client",
      "version": "1.0.0"
    }
  },
  "id": 1
}

// 服务器响应
{
  "jsonrpc": "2.0",
  "result": {
    "protocolVersion": "2024-11-05",
    "capabilities": {
      "tools": {}
    },
    "serverInfo": {
      "name": "automotive-cybersecurity-mcp",
      "version": "1.0.2"
    }
  },
  "id": 1
}
```

资料来源：[TEST_RESULTS.md:1-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 工具列表与发现

### 列出可用工具

通过 `tools/list` 方法获取所有可用工具：

```json
{
  "jsonrpc": "2.0",
  "method": "tools/list",
  "id": 1
}
```

### 可用工具概览

| 工具名称 | 功能描述 | 参数要求 |
|----------|----------|----------|
| `list_sources` | 列出所有可用的法规和标准 | 无 |
| `get_requirement` | 获取特定法规条款或标准章节的详细内容 | `source`, `reference` |
| `search_requirements` | 在所有内容中进行全文搜索 | `query`, `sources`（可选）, `limit`（可选） |

资料来源：[src/tools/list_sources.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list_sources.ts)

## 基础工具使用示例

### 工具一：列出数据源

查看系统中所有可用的法规和标准：

```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "list_sources",
    "arguments": {}
  },
  "id": 2
}
```

**预期响应：**

```json
{
  "source": "r155",
  "name": "UN Regulation No. 155",
  "version": "Revision 2",
  "type": "regulation",
  "description": "Cyber Security and Cyber Security Management System",
  "item_count": 1,
  "full_text_available": true
}
```

资料来源：[TEST_RESULTS.md:50-80](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

### 工具二：获取法规条款

检索 UN R155 第 7.2.2.2 条的完整内容：

```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "get_requirement",
    "arguments": {
      "source": "r155",
      "reference": "7.2.2.2"
    }
  },
  "id": 3
}
```

**预期响应：**

```json
{
  "source": "r155",
  "reference": "7.2.2.2",
  "title": "Cyber Security Management System Requirements",
  "text": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related risk assessment in relation to cyber-attacks...",
  "guidance": ""
}
```

资料来源：[src/tools/get_requirement.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get_requirement.ts)

### 工具三：全文搜索

使用 FTS5 全文搜索引擎查找相关内容：

```json
{
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "name": "search_requirements",
    "arguments": {
      "query": "risk assessment",
      "sources": ["r155"],
      "limit": 10
    }
  },
  "id": 4
}
```

**预期响应：**

```json
[
  {
    "source": "r155",
    "reference": "7.2.2.2",
    "title": "Cyber Security Management System Requirements",
    "snippet": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related **risk** **assessment**...",
    "relevance": -0.000002
  }
]
```

资料来源：[src/tools/search_requirements.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search_requirements.ts)

## 数据流程图

```mermaid
sequenceDiagram
    participant Client as MCP 客户端
    participant Server as MCP 服务器
    participant DB as SQLite 数据库
    participant FTS as FTS5 搜索引擎

    Client->>Server: 初始化请求 (initialize)
    Server-->>Client: 协议版本、能力集
    
    Client->>Server: 工具列表请求 (tools/list)
    Server->>DB: 查询可用数据源
    DB-->>Server: 数据源列表
    Server-->>Client: 工具定义
    
    Client->>Server: 获取条款请求 (get_requirement)
    Server->>DB: 查询法规/标准内容
    DB-->>Server: 条款详情
    Server-->>Client: JSON 响应
    
    Client->>Server: 搜索请求 (search_requirements)
    Server->>FTS: 执行全文搜索
    FTS-->>Server: BM25 排序结果
    Server-->>Client: 搜索结果（含高亮片段）
```

## 常见问题与解决方案

### 问题一：服务器启动失败

**症状：** 执行 `automotive-mcp` 命令无响应或报错

**解决方案：**

1. 确认 Node.js 版本满足要求（18+）
   ```bash
   node --version
   ```

2. 重新安装依赖
   ```bash
   npm uninstall -g @ansvar/automotive-cybersecurity-mcp
   npm install -g @ansvar/automotive-cybersecurity-mcp
   ```

### 问题二：数据库未找到

**症状：** 错误提示 "Database not found"

**解决方案：**

1. 确保数据库已构建
   ```bash
   npm run build:db
   ```

2. 检查数据目录
   ```bash
   ls -la data/automotive.db
   ```

资料来源：[DEPLOYMENT_CHECKLIST.md:30-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md)

### 问题三：源 ID 大小写问题

**症状：** 搜索 `R155` 返回 "Source not found"

**解决方案：** 从 v1.0.2 起，源 ID 已支持大小写不敏感查询。`R155`、`r155`、`R155` 均能正确匹配。

资料来源：[社区更新日志 - v1.0.2](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

### 问题四：搜索结果为空

**症状：** 搜索查询返回空数组

**可能原因：**

1. **查询词不精确**：例如搜索 "cyber attack" 但数据库中只有 "cyber-attacks"（带连字符）
2. **数据源为空**：指定的数据源可能没有可搜索内容
3. **超出限制**：检查 `limit` 参数是否被正确限制在 `[0, 100]` 范围内

**建议：**

- 使用更宽泛的搜索词
- 省略 `sources` 参数以搜索所有数据源
- 检查 `list_sources` 确认数据源是否包含预期内容

资料来源：[TEST_RESULTS.md:100-130](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 性能基准

| 操作类型 | 平均耗时 | 性能评级 |
|----------|----------|----------|
| 数据库打开 | <5ms | 优秀 |
| 列出数据源 | <1ms | 优秀 |
| 获取条款 | <1ms | 优秀 |
| 简单搜索 | 0.05ms | 优秀 |
| 复杂搜索 | 0.04ms | 优秀 |

所有查询均在亚毫秒级完成，远低于 10ms 的目标阈值。

资料来源：[TEST_RESULTS.md:150-180](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 后续步骤

完成快速入门后，您可以：

1. **深入阅读文档** - 了解所有工具的完整参数和用法
2. **运行测试套件** - 验证安装是否正确
   ```bash
   npm test
   ```
3. **探索数据内容** - 使用 `list_sources` 了解可用的法规和标准
4. **配置集成** - 将 MCP 服务器与您的开发工作流集成

## 相关资源

- [主 README 文档](../README.md) - 项目概述和详细说明
- [工具参考](./工具参考.md) - 所有 MCP 工具的完整 API 文档
- [数据源说明](./数据源说明.md) - 支持的法规和标准详解
- [部署指南](./部署指南.md) - 生产环境部署配置

---

<a id='system-architecture'></a>

## 系统架构

### 相关页面

相关主题：[数据库架构](#database-schema), [工具集概览](#tools-overview)

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

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

- [src/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/index.ts)
- [src/tools/registry.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/registry.ts)
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)
- [api/mcp.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/api/mcp.ts)
- [data/schema.sql](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/schema.sql)
- [package.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/package.json)
</details>

# 系统架构

## 1. 概述

Automotive-MCP 是一个基于 Model Context Protocol (MCP) 的汽车网络安全法规查询服务器。它为 Claude 等 AI 助手提供对 UN R155、UN R156 和 ISO/SAE 21434 等汽车网络安全标准的结构化访问能力。

**核心功能：**

- 列出可用的法规来源和标准
- 根据来源和引用编号检索特定要求
- 使用 FTS5 全文搜索引擎跨所有内容进行搜索
- 导出合规性矩阵和工作产品信息

**技术栈：**

| 组件 | 技术选择 | 说明 |
|------|----------|------|
| 运行时 | Node.js 18+ | 服务器运行环境 |
| 语言 | TypeScript | 类型安全，编译到 JavaScript |
| 数据库 | SQLite + FTS5 | 嵌入式数据库，支持全文搜索 |
| 协议 | MCP (Model Context Protocol) | 与 AI 助手通信的标准协议 |
| 构建 | esbuild | 快速 TypeScript 编译 |

资料来源：[package.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/package.json)

---

## 2. 架构分层

系统采用清晰的**关注点分离**架构，分为四个主要层次：

```mermaid
graph TD
    subgraph "表现层 (Presentation)"
        MCP[MCP 协议处理器]
    end
    
    subgraph "应用层 (Application)"
        TOOLS[工具注册表<br/>Tool Registry]
        HANDLERS[请求处理器]
    end
    
    subgraph "服务层 (Service)"
        DB[数据库服务]
        FTS[全文搜索服务]
    end
    
    subgraph "数据层 (Data)"
        SQLite[(SQLite<br/>automotive.db)]
    end
    
    MCP --> TOOLS
    TOOLS --> HANDLERS
    HANDLERS --> DB
    DB --> SQLite
    HANDLERS --> FTS
    FTS --> SQLite
```

### 2.1 各层职责

| 层次 | 职责 | 关键文件 |
|------|------|----------|
| **表现层** | 解析 MCP 协议消息，转发请求到应用层 | `api/mcp.ts` |
| **应用层** | 工具定义、参数验证、请求路由 | `src/tools/registry.ts` |
| **服务层** | 数据库操作、查询执行、结果格式化 | `src/tools/*.ts` |
| **数据层** | 数据持久化、索引维护 | `data/schema.sql` |

资料来源：[src/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/index.ts)

---

## 3. 核心组件

### 3.1 MCP 协议处理器

MCP 协议处理器负责与 AI 客户端的标准输入输出通信：

```mermaid
sequenceDiagram
    participant Client as MCP 客户端
    participant MCP as MCP 处理器
    participant Registry as 工具注册表
    participant DB as 数据库

    Client->>MCP: initialize
    MCP->>Client: protocolVersion, capabilities
    
    Client->>MCP: tools/list
    MCP->>Registry: getAllTools()
    Registry-->>MCP: ToolDefinition[]
    MCP-->>Client: tools list
    
    Client->>MCP: tools/call (list_sources)
    MCP->>Registry: getTool('list_sources')
    Registry->>DB: listSources()
    DB-->>Registry: Source[]
    Registry-->>MCP: result
    MCP-->>Client: tool result
    
    Client->>MCP: tools/call (search_requirements)
    MCP->>Registry: getTool('search_requirements')
    Registry->>DB: searchRequirements(query, sources, limit)
    DB-->>Registry: SearchResult[]
    Registry-->>MCP: result
    MCP-->>Client: tool result
```

**核心特性：**

- 使用 stdio 传输（标准输入/输出）
- JSON-RPC 2.0 消息格式
- 支持 `initialize`、`tools/list`、`tools/call` 三类核心请求

资料来源：[api/mcp.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/api/mcp.ts)

### 3.2 工具注册表

工具注册表是系统的核心调度中心，采用**共享注册表模式**：

```mermaid
graph LR
    subgraph "工具注册"
        T1[list_sources]
        T2[get_requirement]
        T3[search_requirements]
        T4[list_work_products]
        T5[export_compliance_matrix]
        T6[about]
    end
    
    subgraph "注册表"
        REG[ToolRegistry]
    end
    
    T1 --> REG
    T2 --> REG
    T3 --> REG
    T4 --> REG
    T5 --> REG
    T6 --> REG
```

**注册表接口：**

```typescript
interface ToolRegistry {
  register(tool: Tool): void;
  getTool(name: string): Tool | undefined;
  getAllTools(): Tool[];
}
```

资料来源：[src/tools/registry.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/registry.ts)

### 3.3 工具定义

每个工具都遵循统一结构：

| 字段 | 类型 | 说明 |
|------|------|------|
| `name` | string | 工具唯一标识符 |
| `description` | string | 工具功能描述 |
| `inputSchema` | JSON Schema | 输入参数规范 |

**示例 - search_requirements 工具：**

```json
{
  "name": "search_requirements",
  "description": "Full-text search across all automotive cybersecurity regulations and standards",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": { "type": "string", "description": "Search query" },
      "sources": { 
        "type": "array", 
        "items": { "type": "string" },
        "description": "Optional source filter"
      },
      "limit": { 
        "type": "integer", 
        "minimum": 0,
        "maximum": 100,
        "description": "Max results"
      }
    }
  }
}
```

资料来源：[src/tools/registry.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/registry.ts)

---

## 4. 数据库架构

### 4.1 模式设计

数据库采用 SQLite 嵌入式存储，支持全文搜索：

```mermaid
erDiagram
    regulations ||--o{ regulation_content : contains
    regulation_content }o--|| regulation_content_fts : indexes
    
    regulations {
        text id PK
        text name
        text version
        text type
        text description
    }
    
    regulation_content {
        integer rowid PK
        text source FK
        text reference
        text title
        text content
        text guidance
    }
    
    regulation_content_fts {
        text source
        text reference
        text title
        text content
        text guidance
    }
```

### 4.2 FTS5 全文搜索

系统使用 SQLite FTS5 虚拟表实现高性能全文搜索：

**搜索特性：**

| 特性 | 实现 |
|------|------|
| 排名算法 | BM25 (Best Matching 25) |
| 索引类型 | FTS5 虚拟表 |
| 搜索字段 | title, content, guidance |
| 结果片段 | 自动高亮匹配词 `**term**` |

**BM25 评分说明：**

- 负数评分表示相关性（越接近 0 越相关）
- 评分公式：`score = -K1 * term_freq / (term_freq + K1 * (1 - b + b * doc_length / avg_doc_length))`

资料来源：[data/schema.sql](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/schema.sql)

---

## 5. 数据类型定义

### 5.1 核心类型

```typescript
// 数据源
interface Source {
  id: string;              // 唯一标识符 (如 "r155")
  name: string;           // 显示名称
  version: string;        // 版本信息
  type: 'regulation' | 'standard';
  description: string;
  item_count: number;
  full_text_available: boolean;
}

// 法规要求
interface Requirement {
  source: string;
  reference: string;
  title: string;
  text: string | null;    // 法规有全文，标准为 null
  guidance: string;        // 标准有指导说明
  work_products?: string[];
  maps_to?: Mapping[];
}

// 搜索结果
interface SearchResult {
  source: string;
  reference: string;
  title: string;
  snippet: string;        // 带高亮的片段
  relevance: number;      // BM25 评分
}

// 映射关系
interface Mapping {
  source_type: string;
  target_id: string;
  target_type: string;
  relationship: string;
}
```

资料来源：[src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)

---

## 6. 工具详细规格

### 6.1 list_sources

列出所有可用的法规和标准。

**参数：** 无

**返回值：** `Source[]`

| 字段 | 说明 |
|------|------|
| `id` | 唯一标识符 (r155, r156, iso_21434) |
| `name` | 完整名称 |
| `version` | 版本 (如 "Revision 2", "2021") |
| `type` | "regulation" 或 "standard" |
| `item_count` | 收录条款数量 |
| `full_text_available` | 是否有全文 |

### 6.2 get_requirement

根据来源和引用编号获取特定要求。

**参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `source` | string | 是 | 来源 ID (r155, r156, iso_21434) |
| `reference` | string | 是 | 引用编号 (如 "7.2.2.2") |
| `include_mappings` | boolean | 否 | 是否包含映射关系 |

**v1.0.2 更新：** source ID 现在不区分大小写，`R155` 与 `r155` 效果相同。

**返回值：** `Requirement`

### 6.3 search_requirements

全文搜索跨所有法规和标准。

**参数：**

| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `query` | string | 是 | - | 搜索查询 |
| `sources` | string[] | 否 | 全部 | 来源过滤 |
| `limit` | integer | 否 | 10 | 最大结果数 |

**v1.0.2 更新：** limit 参数现在被限制在 `[0, 100]` 范围内。

**返回值：** `SearchResult[]` (按相关性排序)

### 6.4 list_work_products

列出 ISO 21434 工作产品。

**参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `clause` | string | 否 | 按条款过滤 |
| `phase` | string | 否 | 按生命周期阶段过滤 |

### 6.5 export_compliance_matrix

导出 R155/R156 到 ISO 21434 的合规性矩阵。

**参数：**

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `format` | string | 否 | "markdown" 或 "csv" |

### 6.6 about

获取服务器元数据。

**返回值：**

| 字段 | 说明 |
|------|------|
| `version` | 服务器版本 |
| `statistics` | 数据集统计 |
| `fingerprint` | 数据指纹 |
| `provenance` | 数据来源说明 |

---

## 7. 请求处理流程

```mermaid
flowchart TD
    START[收到 MCP 请求] --> PARSE{解析请求类型}
    
    PARSE -->|initialize| INIT[初始化处理]
    PARSE -->|tools/list| LIST[工具列表请求]
    PARSE -->|tools/call| CALL[工具调用请求]
    
    INIT --> RESPONSE_INIT[返回协议版本和能力]
    LIST --> REGISTRY[查询工具注册表]
    REGISTRY --> RESPONSE_LIST[返回工具定义]
    
    CALL --> VALIDATE{验证参数}
    VALIDATE -->|失败| ERROR[返回错误]
    VALIDATE -->|成功| EXECUTE[执行工具]
    
    EXECUTE --> QUERY{查询类型}
    QUERY -->|list_sources| DB_LIST[查询数据源]
    QUERY -->|get_requirement| DB_GET[查询单条记录]
    QUERY -->|search_requirements| DB_SEARCH[FTS5搜索]
    QUERY -->|其他| DB_OTHER[其他查询]
    
    DB_LIST --> FORMAT[格式化结果]
    DB_GET --> FORMAT
    DB_SEARCH --> FORMAT
    DB_OTHER --> FORMAT
    
    FORMAT --> RESPONSE[返回 JSON-RPC 响应]
    
    subgraph "v1.0.2 改进"
        NORM[规范化 source ID 为小写]
        CLAMP[限制 limit 参数]
        VALIDATE --> NORM
        VALIDATE --> CLAMP
    end
```

---

## 8. 输入验证规则

### 8.1 验证层级

| 层级 | 验证内容 | 错误类型 |
|------|----------|----------|
| **参数格式** | JSON Schema 验证 | `invalid_params` |
| **source ID** | 大小写规范化，枚举检查 | `invalid_params` |
| **limit** | 范围限制 [0, 100] | `invalid_params` |
| **reference** | 非空字符串 | `invalid_params` |
| **enum 值** | 枚举成员验证 | `invalid_params` |

### 8.2 错误响应格式

```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "Invalid params",
    "data": {
      "parameter": "source",
      "value": "invalid",
      "reason": "Source not found: invalid"
    }
  },
  "id": 1
}
```

资料来源：[src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)

---

## 9. 性能特征

### 9.1 查询性能基准

| 操作 | 平均耗时 | 性能评级 |
|------|----------|----------|
| 数据库打开 | <5ms | 优秀 |
| 列出数据源 | <1ms | 优秀 |
| 获取单条要求 | <1ms | 优秀 |
| 简单搜索 | 0.05ms | 优秀 |
| 复杂搜索 | 0.04ms | 优秀 |

### 9.2 性能优化措施

| 措施 | 效果 |
|------|------|
| FTS5 索引 | 查询速度提升 500-1000 倍 |
| 预编译语句 | 减少 SQL 解析开销 |
| 嵌入式数据库 | 零网络延迟 |
| 负数 BM25 评分 | 避免浮点运算开销 |

---

## 10. 常见故障与排查

### 10.1 故障诊断矩阵

| 症状 | 可能原因 | 解决方案 |
|------|----------|----------|
| 服务器启动失败 | 数据库文件缺失 | 运行 `npm run build:db` |
| 搜索返回空结果 | 查询词与数据不匹配 | 使用 `list_sources` 确认数据存在 |
| 工具调用失败 | source ID 大小写错误 | v1.0.2+ 已自动规范化 |
| 连接超时 | 传输方式配置错误 | 确认使用 stdio 传输 |
| 参数验证错误 | 传入非法枚举值 | 检查参数格式，参考 API 文档 |

### 10.2 日志与调试

服务器启动时会输出：

```
Automotive Cybersecurity MCP server started
```

建议使用 `DEBUG` 环境变量启用详细日志：

```bash
DEBUG=mcp:* node dist/index.js
```

### 10.3 数据库验证

检查数据库内容：

```bash
node -e "
const Database = require('better-sqlite3');
const db = new Database('./data/automotive.db');
console.log(db.prepare('SELECT COUNT(*) as count FROM regulations').get());
console.log(db.prepare('SELECT COUNT(*) as count FROM regulation_content').get());
"
```

---

## 11. 版本演进

| 版本 | 发布日期 | 主要变更 |
|------|----------|----------|
| **v1.0.2** | 2026-02-05 | case-insensitive source IDs, limit 限制, 描述性错误信息 |
| **v1.0.1** | 2026-02-01 | 新增工具, WASM 迁移, Streamable HTTP |
| **v0.1.0** | 2026-01-29 | 初始版本, 基础工具集 |

---

## 12. See Also

- [快速开始指南](../getting-started) - 安装和配置
- [API 参考](../api-reference) - 完整的工具参数说明
- [数据源说明](../data-sources) - R155、R156、ISO 21434 内容详情
- [部署指南](../deployment) - Docker、Vercel 部署说明
- [CHANGELOG](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md) - 完整版本历史

---

<a id='database-schema'></a>

## 数据库架构

### 相关页面

相关主题：[系统架构](#system-architecture), [种子数据结构](#seed-data-structure)

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

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

- [scripts/build-db.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)
- [inspect-db.py](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/inspect-db.py)
- [manifest.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/manifest.json)
- [src/tools/list-sources.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list-sources.ts)
- [src/tools/get-requirement.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get-requirement.ts)
- [src/tools/search-requirements.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search-requirements.ts)
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)
- [package.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/package.json)
</details>

# 数据库架构

## 概述

Automotive-MCP 项目采用 **SQLite** 作为数据持久化存储，结合 **FTS5（Full-Text Search 5）** 全文搜索引擎实现对汽车网络安全法规和标准的检索功能。数据库架构设计旨在支持三个核心工具的查询操作：`list_sources`（列出数据源）、`get_requirement`（获取具体条款）和 `search_requirements`（全文搜索）。

当前版本为 **Phase 1**，包含有限但经过验证的示例数据，主要涵盖 UN R155、UN R156 法规以及 ISO/SAE 21434 标准的关键条款。

## 核心设计目标

| 目标 | 实现方式 |
|------|----------|
| 高性能检索 | FTS5 虚拟表 + BM25 排名算法 |
| 规范化数据 | 严格类型定义（见 `src/types/index.ts`） |
| 跨框架关联 | R155/R156 与 ISO 21434 映射表 |
| 可验证性 | 自动化测试覆盖 91 个用例 |
| 部署便捷性 | 数据库文件直接打包至 npm 包 |

资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

---

## 数据库架构图

```mermaid
graph TD
    subgraph "数据源层"
        A["regulations.json<br/>UN R155/R156"] 
        B["standards.json<br/>ISO 21434"]
    end
    
    subgraph "数据库存储层"
        C["regulations 表<br/>法规元数据"]
        D["regulation_content 表<br/>法规正文内容"]
        E["standards 表<br/>标准元数据"]
        F["standard_clauses 表<br/>标准条款内容"]
        G["mappings 表<br/>跨框架映射"]
        H["work_products 表<br/>工作产品"]
    end
    
    subgraph "搜索索引层"
        I["regulation_content_fts<br/>FTS5 虚拟表"]
        J["standard_clauses_fts<br/>FTS5 虚拟表"]
    end
    
    subgraph "工具接口层"
        K["list_sources"]
        L["get_requirement"]
        M["search_requirements"]
    end
    
    A --> C
    A --> D
    B --> E
    B --> F
    C --> D
    D --> I
    E --> F
    F --> J
    G --> C
    G --> F
    H --> F
    
    I --> M
    J --> M
    C --> K
    E --> K
    C --> L
    F --> L
```

资料来源：[scripts/build-db.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)

---

## 数据表结构

### 法规相关表

#### regulations 表

存储法规的元数据信息。

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | TEXT PRIMARY KEY | 法规标识符（如 `r155`、`r156`） |
| `name` | TEXT | 法规全称 |
| `version` | TEXT | 版本号（如 `Revision 2`） |
| `type` | TEXT | 类型固定为 `regulation` |
| `description` | TEXT | 简要描述 |
| `full_text_available` | INTEGER | 是否有完整文本（0 或 1） |

资料来源：[inspect-db.py](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/inspect-db.py)

#### regulation_content 表

存储法规的具体条款内容。

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | INTEGER PRIMARY KEY | 自增主键 |
| `source` | TEXT | 关联的法规 ID |
| `reference` | TEXT | 条款编号（如 `7.2.2.2`） |
| `title` | TEXT | 条款标题 |
| `text` | TEXT | 完整法规文本 |
| `guidance` | TEXT | 专家指导说明 |
| `maps_to` | TEXT | 映射到其他框架的标识 |

#### regulation_content_fts 表（FTS5 虚拟表）

用于全文搜索的虚拟表，基于 `regulation_content.text` 构建。

```sql
CREATE VIRTUAL TABLE regulation_content_fts USING fts5(
    text,
    content='regulation_content',
    content_rowid='id',
    tokenize='unicode61'
);
```

资料来源：[scripts/build-db.ts:60-65](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)

### 标准相关表

#### standards 表

存储标准的元数据信息。

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | TEXT PRIMARY KEY | 标准标识符（如 `iso_21434`） |
| `name` | TEXT | 标准全称 |
| `version` | TEXT | 发布年份 |
| `type` | TEXT | 类型固定为 `standard` |
| `description` | TEXT | 简要描述 |
| `full_text_available` | INTEGER | 通常为 0（ISO 标准需付费） |

#### standard_clauses 表

存储 ISO 21434 等标准的条款信息。

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | INTEGER PRIMARY KEY | 自增主键 |
| `source` | TEXT | 关联的标准 ID |
| `reference` | TEXT | 条款编号（如 `9.3`） |
| `title` | TEXT | 条款标题 |
| `text` | TEXT | 条款正文（ISO 标准通常为 null） |
| `guidance` | TEXT | 专家指导说明 |
| `work_products` | TEXT | JSON 格式的工作产品列表 |
| `maps_to` | TEXT | 映射到法规的标识 |

#### work_products 表（v1.0.1+）

存储 ISO 21434 定义的工作产品清单。

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | TEXT PRIMARY KEY | 工作产品标识符 |
| `clause` | TEXT | 关联的条款编号 |
| `title` | TEXT | 工作产品名称 |
| `description` | TEXT | 详细描述 |
| `phase` | TEXT | 生命周期阶段 |

资料来源：[manifest.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/manifest.json)

### 映射表

#### mappings 表（v1.0.1+）

存储 R155/R156 与 ISO 21434 之间的跨框架映射关系。

| 字段 | 类型 | 描述 |
|------|------|------|
| `id` | INTEGER PRIMARY KEY | 自增主键 |
| `source_type` | TEXT | 来源类型（`regulation` 或 `standard`） |
| `source_id` | TEXT | 来源 ID |
| `source_ref` | TEXT | 来源条款编号 |
| `related_type` | TEXT | 关联类型 |
| `related_id` | TEXT | 关联 ID |
| `related_ref` | TEXT | 关联条款编号 |
| `relationship` | TEXT | 关系描述 |

资料来源：[CHANGELOG.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

---

## 全文搜索机制

### FTS5 与 BM25 排名

Automotive-MCP 使用 SQLite 的 **FTS5** 扩展实现全文搜索功能。搜索结果通过 **BM25（Best Matching 25）** 算法进行相关性排序。

```mermaid
graph LR
    A["用户查询<br/>'risk assessment'"] --> B["查询预处理<br/>转小写、清理特殊字符"]
    B --> C["FTS5 MATCH 查询"]
    C --> D["BM25 评分计算"]
    D --> E["结果排序<br/>BM25 分数越低越相关"]
    E --> F["snippet() 生成摘要<br/>高亮匹配词"]
    F --> G["返回 JSON 结果"]
```

### BM25 评分特性

| 特性 | 说明 | 示例 |
|------|------|------|
| 评分范围 | 负数（分数越低越相关） | `relevance: -0.000002` |
| 多词查询 | 各词评分求和 | `risk assessment` 返回低分 |
| 术语频率 | 出现次数多则相关度高 | 多次出现的词排名靠前 |

资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

### 搜索性能基准

| 查询类型 | 平均耗时 | 性能评级 |
|----------|----------|----------|
| 简单查询（`security`） | 0.05ms | 优秀 |
| 多词查询（`risk assessment`） | 0.05ms | 优秀 |
| 复杂查询（`vulnerability management disclosure`） | 0.04ms | 优秀 |

**注：** 100 次查询总耗时约 5ms，性能远超 10ms 的可接受标准。

资料来源：[TEST_RESULTS.md:性能基准](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

---

## 数据流程

### 工具调用流程

```mermaid
sequenceDiagram
    participant Client as MCP 客户端
    participant Server as MCP 服务器
    participant DB as SQLite 数据库
    participant FTS as FTS5 索引

    Client->>Server: tools/call: list_sources
    Server->>DB: SELECT * FROM regulations<br/>SELECT * FROM standards
    DB-->>Server: 数据集
    Server-->>Client: JSON 响应

    Client->>Server: tools/call: get_requirement<br/>{source: "r155", reference: "7.2.2.2"}
    Server->>DB: SELECT * FROM regulation_content<br/>WHERE source=? AND reference=?
    DB-->>Server: 单条记录
    Server-->>Client: JSON 响应

    Client->>Server: tools/call: search_requirements<br/>{query: "vulnerability", sources: ["iso_21434"]}
    Server->>FTS: SELECT * FROM standard_clauses_fts<br/>WHERE standard_clauses_fts MATCH ?
    FTS-->>Server: BM25 排序结果
    Server-->>Client: JSON 响应（含 snippet）
```

### 源码文件对应关系

| 操作 | 源码文件 | 核心函数 |
|------|----------|----------|
| 列出数据源 | [src/tools/list-sources.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list-sources.ts) | `listSources()` |
| 获取条款 | [src/tools/get-requirement.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get-requirement.ts) | `getRequirement()` |
| 搜索条款 | [src/tools/search-requirements.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search-requirements.ts) | `searchRequirements()` |

---

## 数据库构建流程

### 构建脚本工作流程

```mermaid
graph TD
    A["npm run build:db"] --> B["读取 manifest.json"]
    B --> C["连接/创建 automotive.db"]
    C --> D["执行 schema.sql"]
    D --> E["加载 regulations.json"]
    E --> F["加载 standards.json"]
    F --> G["构建 FTS5 索引"]
    G --> H["验证数据完整性"]
    H --> I["输出构建报告"]
```

### 构建配置

```typescript
// scripts/build-db.ts 核心配置
const DB_PATH = path.join(__dirname, '../data/automotive.db');
const SCHEMA_PATH = path.join(__dirname, '../data/schema.sql');
const MANIFEST_PATH = path.join(__dirname, '../manifest.json');
```

资料来源：[scripts/build-db.ts:1-20](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)

### 构建命令

```bash
# 完整构建
npm run build:db

# 构建 + 编译 TypeScript
npm run build
```

---

## 数据类型定义

### TypeScript 类型接口

```typescript
// src/types/index.ts
interface Source {
  id: string;           // 唯一标识符
  name: string;        // 显示名称
  version: string;     // 版本信息
  type: 'regulation' | 'standard';
  description: string;
  item_count: number;
  full_text_available: boolean;
}

interface Requirement {
  source: string;
  reference: string;
  title: string;
  text: string | null;
  guidance: string;
  work_products?: string[];
  maps_to?: string;
}

interface SearchResult {
  source: string;
  reference: string;
  title: string;
  snippet: string;     // 高亮摘要
  relevance: number;   // BM25 分数
}
```

资料来源：[src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)

---

## API 参数规格

### list_sources 参数

| 参数 | 类型 | 必填 | 默认值 | 描述 |
|------|------|------|--------|------|
| `source_type` | string | 否 | 全部 | 过滤类型：`regulation` 或 `standard` |

### get_requirement 参数

| 参数 | 类型 | 必填 | 描述 |
|------|------|------|------|
| `source` | string | **是** | 来源 ID（如 `r155`、`iso_21434`） |
| `reference` | string | **是** | 条款编号（如 `7.2.2.2`、`9.3`） |
| `include_mappings` | boolean | 否 | 是否包含映射信息（v1.0.1+） |

**v1.0.2 修复：** source 参数现支持大小写不敏感输入，`R155` 与 `r155` 等效。

资料来源：[CHANGELOG.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

### search_requirements 参数

| 参数 | 类型 | 必填 | 默认值 | 描述 |
|------|------|------|--------|------|
| `query` | string | **是** | - | 搜索关键词 |
| `sources` | string[] | 否 | 全部 | 限定数据源列表 |
| `limit` | number | 否 | 10 | 返回结果数量上限 |

**v1.0.2 修复：** `limit` 参数现已限制在 `[0, 100]` 范围内，防止异常值。

资料来源：[CHANGELOG.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

---

## 常见故障与排查

### 数据库文件缺失

**症状：** 安装后无法使用，提示数据库连接失败。

**原因：** `.npmignore` 配置不当导致 `.db` 文件未打包。

**排查命令：**
```bash
# 检查 npm 包内容
npm pack --dry-run

# 验证数据库文件存在
ls -la node_modules/@ansvar/automotive-cybersecurity-mcp/data/
```

**修复：** 确保 `data/` 目录未被 `.npmignore` 排除。

资料来源：[DEPLOYMENT_CHECKLIST.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md)

### 搜索结果为空

**症状：** 搜索已知存在的术语返回空结果。

**原因：** FTS5 使用精确匹配，连字符词（如 `cyber-attacks`）与空格词（如 `cyber attack`）被视为不同。

**示例：**
```json
// 搜索 "cyber attack" → 返回 0 条
// 搜索 "cyber-attacks" → 返回 1 条
```

**解决方案：** 搜索时请使用数据中实际存在的术语格式。

资料来源：[TEST_RESULTS.md:Test 3.3](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

### 无效的源 ID

**症状：** 提示 "Source not found: nonexistent"

**原因：** 请求的 `source` 参数不在数据库中。

**有效源 ID：**
| ID | 名称 | 类型 |
|----|------|------|
| `r155` | UN Regulation No. 155 | 法规 |
| `r156` | UN Regulation No. 156 | 法规 |
| `iso_21434` | ISO/SAE 21434:2021 | 标准 |

---

## 性能优化建议

### 当前性能数据

| 操作 | 耗时 | 性能评级 |
|------|------|----------|
| 数据库打开 | <5ms | 优秀 |
| 列出数据源 | <1ms | 优秀 |
| 获取条款 | <1ms | 优秀 |
| 全文搜索 | 0.04-0.05ms | 优秀 |

### 扩展性考虑

| 指标 | 当前值 | 预估上限 |
|------|--------|----------|
| 可索引条款数 | ~100 | ~10,000+ |
| FTS5 查询性能 | 0.05ms | <10ms |
| 数据库文件大小 | ~620KB | <50MB |

**注：** SQLite FTS5 在百万级记录内保持亚毫秒级查询性能。

---

## 数据库版本历史

| 版本 | 日期 | 主要变更 |
|------|------|----------|
| 1.0.2 | 当前 | 规范化 source ID 大小写、limit 参数边界检查 |
| 1.0.1 | 2026-02-01 | 添加 work_products 表、mappings 表、导出工具 |
| 0.1.0 | 2026-01-29 | 初始版本，Phase 1 基础数据 |

资料来源：[CHANGELOG.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

---

## 相关文档

- [工具使用指南](./tools-overview) - list_sources、get_requirement、search_requirements 详细用法
- [部署指南](./deployment) - npm 安装、Docker 部署、Vercel 配置
- [测试报告](./testing) - 完整的测试用例和性能基准
- [质量评估报告](./quality-assessment) - 代码架构和最佳实践分析

---

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

## 工具集概览

### 相关页面

相关主题：[get_requirement 工具](#get-requirement-tool), [search_requirements 工具](#search-requirements-tool), [list_sources 工具](#list-sources-tool), [export_compliance_matrix 工具](#compliance-export-tool)

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

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

- [src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)
- [src/tools/get.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts)
- [src/tools/search.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts)
- [src/tools/workproducts.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/workproducts.ts)
- [src/tools/export.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/export.ts)
- [src/tools/about.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/about.ts)
</details>

# 工具集概览

本文档介绍 Automotive-MCP 服务器提供的所有 MCP 工具，这些工具用于查询汽车网络安全法规、标准及相关工作产品。

## 架构概览

Automotive-MCP 作为 Model Context Protocol (MCP) 服务器运行，通过标准输入/输出 (stdio) 与 MCP 客户端通信。服务器内部采用模块化架构，将工具定义、数据库操作和数据类型分离管理。

```mermaid
graph TD
    A[MCP 客户端] -->|JSON-RPC 2.0| B[Automotive-MCP 服务器]
    B --> C[工具注册表]
    C --> D[list_sources]
    C --> E[get_requirement]
    C --> F[search_requirements]
    C --> G[list_work_products]
    C --> H[export_compliance_matrix]
    C --> I[about]
    D --> J[(SQLite 数据库)]
    E --> J
    F --> J
    G --> J
    H --> J
    J --> K[FTS5 全文索引]
```

## 工具清单

| 工具名称 | 功能描述 | 数据源 |
|---------|---------|--------|
| `list_sources` | 列出所有可用的法规和标准 | regulations, standards |
| `get_requirement` | 获取特定条款的完整内容 | regulation_content, standard_clauses |
| `search_requirements` | 全文搜索所有内容 | FTS5 索引 |
| `list_work_products` | 列出 ISO 21434 工作产品 | work_products |
| `export_compliance_matrix` | 导出合规矩阵 | mappings, regulations, standards |
| `about` | 获取服务器元数据 | 服务器配置 |

资料来源：[src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)

---

## 1. list_sources

`list_sources` 工具用于枚举数据库中所有已注册的汽车网络安全法规和标准。

### 功能说明

该工具返回所有可用数据源的元信息，包括法规编号、版本、类型和内容统计。对于需要了解数据库覆盖范围的场景非常有用。

资料来源：[src/tools/list.ts:1-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)

### 输入参数

| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|-------|------|------|-------|------|
| `source_type` | `string` | 否 | `undefined` | 按类型过滤：`"regulation"` 或 `"standard"` |

### 输出结构

```typescript
interface Source {
  id: string;           // 唯一标识符，如 "r155"、"iso_21434"
  name: string;         // 完整名称
  version: string;      // 版本信息
  type: "regulation" | "standard";  // 数据源类型
  description: string;  // 简要描述
  item_count: number;   // 包含的条款数量
  full_text_available: boolean;  // 是否提供完整文本
}
```

### 响应示例

**列出所有数据源：**
```json
{
  "id": "r155",
  "name": "UN Regulation No. 155",
  "version": "Revision 2",
  "type": "regulation",
  "description": "Cyber Security and Cyber Security Management System",
  "item_count": 1,
  "full_text_available": true
}
```

**筛选法规类型：**
```json
[
  {
    "id": "r155",
    "name": "UN Regulation No. 155",
    ...
  },
  {
    "id": "r156",
    "name": "UN Regulation No. 156",
    ...
  }
]
```

### 已知数据源

| ID | 名称 | 类型 | 说明 |
|----|------|------|------|
| `r155` | UN Regulation No. 155 | 法规 | 网络安全和网络安全管理体系 |
| `r156` | UN Regulation No. 156 | 法规 | 软件更新和软件更新管理体系 |
| `iso_21434` | ISO/SAE 21434:2021 | 标准 | 道路车辆网络安全工程 |

---

## 2. get_requirement

`get_requirement` 工具用于检索特定法规条款或标准章节的详细内容。

### 功能说明

根据指定的来源标识符和引用编号，获取完整的条款文本或专家指导说明。法规（如 R155、R156）返回完整文本，标准（如 ISO 21434）返回专家指导，因为标准全文需要付费许可。

资料来源：[src/tools/get.ts:1-60](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts)

### 输入参数

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| `source` | `string` | 是 | 数据源标识符（如 `"r155"`、`"iso_21434"`） |
| `reference` | `string` | 是 | 条款引用编号（如 `"7.2.2.2"`、`"9.3"`） |
| `include_mappings` | `boolean` | 否 | 是否包含框架映射信息 |

### 源 ID 大小写处理

**v1.0.2 修复：** 源 ID 现在不区分大小写，`R155`、`r155` 和 `R155` 均被视为有效输入。

资料来源：[src/tools/get.ts:20-25](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts)

### 输出结构

**法规响应：**
```typescript
interface RegulationResponse {
  source: string;       // 数据源 ID
  reference: string;    // 条款编号
  title: string;        // 条款标题
  text: string;         // 完整法规文本
  guidance: string;     // 通常为空字符串
}
```

**标准响应：**
```typescript
interface StandardResponse {
  source: string;        // 数据源 ID
  reference: string;     // 条款编号
  title: string;         // 章节标题
  text: null;            // 标准全文（因版权限制为 null）
  guidance: string;      // 专家指导说明
  work_products?: string[];  // 相关工作产品列表
}
```

### 响应示例

**获取 R155 法规条款：**
```json
{
  "source": "r155",
  "reference": "7.2.2.2",
  "title": "Cyber Security Management System Requirements",
  "text": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related risk assessment in relation to cyber-attacks...",
  "guidance": ""
}
```

**获取 ISO 21434 标准条款：**
```json
{
  "source": "iso_21434",
  "reference": "9.3",
  "title": "Vulnerability analysis",
  "text": null,
  "guidance": "Monitor for vulnerabilities in components throughout vehicle lifetime. Establish processes for vulnerability disclosure, triage, and remediation. Interface with PSIRT for coordination.",
  "work_products": ["[WP-09-03]"]
}
```

### 错误处理

| 错误类型 | 消息格式 |
|---------|---------|
| 无效数据源 | `Error: Source not found: {source}` |
| 无效引用 | `Error: {source} reference not found: {reference}` |

---

## 3. search_requirements

`search_requirements` 工具提供全文搜索功能，支持跨多个数据源的模糊查询。

### 功能说明

基于 SQLite FTS5 (Full-Text Search 5) 虚拟表实现，使用 BM25 (Okapi BM25) 算法进行相关性排序。搜索自动规范化输入，支持特殊字符处理。

资料来源：[src/tools/search.ts:1-80](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts)

### 输入参数

| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|-------|------|------|-------|------|
| `query` | `string` | 是 | - | 搜索关键词 |
| `sources` | `string[]` | 否 | 所有源 | 限定搜索范围的数据源 ID |
| `limit` | `number` | 否 | `20` | 最大返回结果数 |

### 搜索限制参数

**v1.0.2 修复：** `limit` 参数现在被限制在 `[0, 100]` 范围内，防止负值或极端值传入。

资料来源：[src/tools/search.ts:30-35](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts)

### 输出结构

```typescript
interface SearchResult {
  source: string;        // 匹配的数据源
  reference: string;     // 匹配的条款编号
  title: string;         // 条款标题
  snippet: string;       // 包含高亮的上下文片段
  relevance: number;     // BM25 相关性分数（越低越相关）
}
```

### 搜索流程

```mermaid
graph LR
    A[输入查询] --> B[参数验证]
    B --> C[限制参数边界]
    C --> D[查询规范化]
    D --> E[FTS5 BM25 搜索]
    E --> F[生成高亮片段]
    F --> G[结果排序]
    G --> H[返回结果]
```

### 响应示例

**搜索 "risk assessment"：**
```json
[
  {
    "source": "r155",
    "reference": "7.2.2.2",
    "title": "Cyber Security Management System Requirements",
    "snippet": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related **risk** **assessment**...",
    "relevance": -0.000002
  }
]
```

### 搜索行为说明

| 场景 | 行为 |
|-----|------|
| 空查询 | 返回空数组 `[]` |
| 无匹配结果 | 返回空数组 `[]` |
| 多词查询 | 视为词组进行匹配 |
| 特殊字符 | 自动转义处理 |

### 性能指标

| 指标 | 数值 |
|-----|------|
| 单次查询平均耗时 | 0.05ms |
| 100 次查询总耗时 | 5ms |
| 性能评级 | 优秀 |

---

## 4. list_work_products

`list_work_products` 工具用于列出 ISO 21434 标准定义的工作产品。

### 功能说明

ISO/SAE 21434 定义了多个网络安全工程工作产品，该工具按条款或生命周期阶段进行筛选查询。

资料来源：[src/tools/workproducts.ts:1-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/workproducts.ts)

### 输入参数

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| `clause` | `string` | 否 | 按 ISO 21434 条款筛选（如 `"9.3"`） |
| `phase` | `string` | 否 | 按生命周期阶段筛选 |

### 生命周期阶段

| 阶段 | 说明 |
|-----|------|
| `concept` | 概念阶段 |
| `development` | 开发阶段 |
| `production` | 生产阶段 |
| `operations` | 运营阶段 |
| `post-production` | 售后阶段 |

### 响应示例

```json
{
  "id": "WP-09-03",
  "title": "Vulnerability Analysis Report",
  "clause": "9.3",
  "phase": "development",
  "description": "Document vulnerabilities identified during analysis..."
}
```

---

## 5. export_compliance_matrix

`export_compliance_matrix` 工具用于导出 R155/R156 到 ISO 21434 的可追溯性矩阵。

### 功能说明

生成法规要求与标准条款之间的映射关系矩阵，支持 Markdown 和 CSV 格式输出，便于合规审计和文档编制。

资料来源：[src/tools/export.ts:1-60](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/export.ts)

### 输入参数

| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|-------|------|------|-------|------|
| `format` | `string` | 否 | `"markdown"` | 输出格式：`"markdown"` 或 `"csv"` |

### 输出结构

**Markdown 格式：**
```markdown
# Compliance Matrix

## R155 → ISO 21434

| R155 Clause | ISO 21434 Clause | Relationship |
|-------------|------------------|--------------|
| 7.2.2.2 | 8.3 | related |
```

**CSV 格式：**
```csv
source,reference,target_clause,relationship,notes
r155,7.2.2.2,8.3,related,Risk assessment relates to threat analysis
```

### 使用场景

- 合规性审计准备
- 追溯性文档生成
- 跨框架映射分析

---

## 6. about

`about` 工具返回服务器元数据信息。

### 功能说明

提供服务器版本、数据库统计、数据指纹和溯源信息，用于系统诊断和版本管理。

资料来源：[src/tools/about.ts:1-40](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/about.ts)

### 输出结构

```typescript
interface ServerInfo {
  name: string;           // 服务器名称
  version: string;        // 服务器版本
  description: string;    // 服务器描述
  database: {
    regulations: number;   // 法规数量
    standards: number;    // 标准数量
    requirements: number; // 条款总数
    mappings: number;     // 映射关系数
  };
  fingerprint: string;    // 数据指纹
  provenance: string;     // 数据来源说明
}
```

### 响应示例

```json
{
  "name": "Automotive Cybersecurity MCP",
  "version": "1.0.2",
  "description": "MCP server for automotive cybersecurity regulations and standards",
  "database": {
    "regulations": 2,
    "standards": 1,
    "requirements": 50,
    "mappings": 10
  },
  "fingerprint": "abc123def456",
  "provenance": "UNECE WP.29 regulations; ISO/SAE 21434 standard"
}
```

---

## 工具使用工作流

### 常见使用模式

```mermaid
graph TD
    A[开始] --> B{目标是什么?}
    B -->|探索可用数据| C[list_sources]
    B -->|获取特定条款| D[get_requirement]
    B -->|关键词搜索| E[search_requirements]
    B -->|查看工作产品| F[list_work_products]
    B -->|生成合规文档| G[export_compliance_matrix]
    B -->|系统诊断| H[about]
    
    C --> I[返回数据源列表]
    D --> J[返回条款详情]
    E --> K[返回搜索结果]
    F --> L[返回工作产品]
    G --> M[返回矩阵文档]
    H --> N[返回元数据]
```

### 场景示例

**场景 1：了解数据库覆盖范围**
```
用户 → list_sources → 查看所有法规和标准
```

**场景 2：查找漏洞分析相关条款**
```
用户 → search_requirements("vulnerability") → 获取相关条款列表
用户 → get_requirement("iso_21434", "9.3") → 获取详细指导
```

**场景 3：合规性文档生成**
```
用户 → export_compliance_matrix(format="markdown") → 生成可追溯性矩阵
```

---

## 参数验证与错误处理

### 输入验证规则

| 工具 | 参数 | 验证规则 |
|-----|------|---------|
| `list_sources` | `source_type` | 必须是 `"regulation"` 或 `"standard"` |
| `get_requirement` | `source` | 必须在数据源列表中 |
| `get_requirement` | `reference` | 必须在指定数据源中存在 |
| `search_requirements` | `limit` | 限制在 `[0, 100]` 范围内 |
| `search_requirements` | `sources` | 每个元素必须是有效数据源 ID |
| `export_compliance_matrix` | `format` | 必须是 `"markdown"` 或 `"csv"` |

### 错误响应格式

```json
{
  "jsonrpc": "2.0",
  "error": {
    "code": -32602,
    "message": "Source not found: invalid_source"
  },
  "id": 1
}
```

---

## 性能特性

### 响应时间基准

| 操作 | 平均耗时 | 性能评级 |
|-----|---------|---------|
| `list_sources` | <1ms | 优秀 |
| `get_requirement` | <1ms | 优秀 |
| `search_requirements` | 0.05ms | 优秀 |
| `list_work_products` | <1ms | 优秀 |
| `export_compliance_matrix` | <5ms | 优秀 |
| `about` | <1ms | 优秀 |

### 数据库性能

| 指标 | 数值 |
|-----|------|
| 数据库启动时间 | <5ms |
| FTS5 查询性能 | 亚毫秒级 |
| 索引类型 | FTS5 虚拟表 + BM25 |

---

## 版本兼容性

### v1.0.2 重要修复

| 修复项 | 说明 |
|-------|------|
| 源 ID 大小写规范化 | `R155` 和 `r155` 现在等效 |
| 搜索限制边界 | `limit` 参数自动限制在 [0, 100] |
| 错误消息优化 | 枚举值错误现在返回描述性消息 |

---

## 相关页面

- [安装与配置指南](../installation) - MCP 服务器部署说明
- [数据库架构](../database-schema) - SQLite 数据模型详解
- [API 参考](../api-reference) - 完整 API 文档
- [故障排除](../troubleshooting) - 常见问题与解决方案

---

<a id='list-sources-tool'></a>

## list_sources 工具

### 相关页面

相关主题：[工具集概览](#tools-overview), [get_requirement 工具](#get-requirement-tool)

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

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

- [src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)
- [README.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md)
- [TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)
- [QUALITY_ASSESSMENT_REPORT.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)
- [VERIFICATION_COMPLETE.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)
</details>

# list_sources 工具

## 概述

`list_sources` 是 Automotive-MCP 项目提供的三个核心工具之一，用于列出所有可用的法规和标准信息源。该工具是用户与汽车网络安全法规知识库交互的主要入口点，允许用户发现系统中注册的所有数据源，包括联合国法规（UN Regulation）和国际标准（ISO/SAE 标准）。

根据测试结果，`list_sources` 工具已通过全部功能验证测试，能够正确返回数据源的完整元数据信息，包括数据源标识符、名称、版本、类型、描述、项目计数和全文可用性标志等关键字段。

## 工具功能说明

### 核心能力

`list_sources` 工具提供以下核心功能：

1. **全量列表查询**：返回系统中所有已注册的数据源
2. **类型过滤**：支持按数据源类型（regulation/standard）进行筛选
3. **元数据完整返回**：每个数据源包含完整的描述性信息
4. **全文可用性指示**：标识哪些数据源提供完整文本内容

该工具通过 MCP（Model Context Protocol）协议进行调用，返回 JSON 格式的结构化数据，便于客户端程序进行解析和处理。

### 返回数据结构

每个数据源对象包含以下字段：

| 字段名 | 类型 | 说明 |
|--------|------|------|
| `id` | string | 数据源唯一标识符（如 "r155"） |
| `name` | string | 数据源正式名称 |
| `version` | string | 版本信息 |
| `type` | string | 数据源类型（regulation/standard） |
| `description` | string | 数据源描述文本 |
| `item_count` | number | 包含的项目/条款数量 |
| `full_text_available` | boolean | 是否提供完整文本内容 |

## 使用方式

### 基本调用

获取所有可用数据源的完整列表：

```json
{
  "name": "list_sources",
  "arguments": {}
}
```

此调用返回系统中所有注册的数据源信息。

### 按类型过滤

仅获取法规类型的数据源：

```json
{
  "name": "list_sources",
  "arguments": {
    "source_type": "regulation"
  }
}
```

仅获取标准类型的数据源：

```json
{
  "name": "list_sources",
  "arguments": {
    "source_type": "standard"
  }
}
```

## 当前数据源

### UN 法规

| 标识符 | 名称 | 版本 | 描述 |
|--------|------|------|------|
| `r155` | UN Regulation No. 155 | Revision 2 | Cyber Security and Cyber Security Management System |
| `r156` | UN Regulation No. 156 | Revision 2 | Software Update and Software Updates Management System |

### ISO 标准

| 标识符 | 名称 | 版本 | 描述 |
|--------|------|------|------|
| `iso_21434` | ISO/SAE 21434:2021 | 2021 | Road vehicles — Cybersecurity engineering |

## 测试验证结果

### 功能测试摘要

根据测试结果文档，`list_sources` 工具在所有测试场景中表现良好：

| 测试编号 | 测试内容 | 输入参数 | 结果 |
|----------|----------|----------|------|
| 1.1 | 列出所有数据源 | `{}` | ✅ 通过 |
| 1.2 | 仅返回法规 | `{ "source_type": "regulation" }` | ✅ 通过 |
| 1.3 | 仅返回标准 | `{ "source_type": "standard" }` | ✅ 通过 |

### 响应示例

**全量列表响应：**

```json
[
  {
    "id": "r155",
    "name": "UN Regulation No. 155",
    "version": "Revision 2",
    "type": "regulation",
    "description": "Cyber Security and Cyber Security Management System",
    "item_count": 1,
    "full_text_available": true
  },
  {
    "id": "r156",
    "name": "UN Regulation No. 156",
    "version": "Revision 2",
    "type": "regulation",
    "description": "Software Update and Software Updates Management System",
    "item_count": 0,
    "full_text_available": true
  },
  {
    "id": "iso_21434",
    "name": "ISO/SAE 21434:2021",
    "version": "2021",
    "type": "standard",
    "description": "Road vehicles — Cybersecurity engineering",
    "item_count": 1,
    "full_text_available": false
  }
]
```

### 验证要点

测试结果确认以下功能特性：

- ✅ 返回 3 个数据源的完整信息
- ✅ 所有数据源的元数据完整
- ✅ 项目计数准确
- ✅ 全文可用性标志正确标记
- ✅ JSON 格式可正常解析

## 与其他工具的协作

`list_sources` 工具是Automotive-MCP工具链的起点，用户通常按照以下流程使用：

```mermaid
graph TD
    A[调用 list_sources] --> B{了解可用数据源}
    B --> C[使用 get_requirement 获取特定条款]
    B --> D[使用 search_requirements 搜索内容]
    C --> E[查看完整文本或指导说明]
    D --> F[浏览搜索结果]
    F --> C
```

### 工具对比

| 工具名称 | 功能描述 | 典型用途 |
|----------|----------|----------|
| `list_sources` | 列出所有数据源 | 发现和探索可用内容 |
| `get_requirement` | 获取特定条款详情 | 查看具体法规要求 |
| `search_requirements` | 全文搜索 | 查找相关条款 |

## 性能特性

根据性能基准测试，`list_sources` 工具具有以下性能特征：

| 操作 | 耗时 | 性能评级 |
|------|------|----------|
| 数据库打开 | <5ms | 优秀 |
| 列出数据源 | <1ms | 优秀 |

该工具的响应时间在所有测试场景中均保持在毫秒级以下，满足实时应用需求。

## 常见使用场景

### 场景一：数据源发现

用户首次使用系统时，首先调用 `list_sources` 了解系统中可用的法规和标准：

1. 调用 `list_sources` 获取完整列表
2. 查看各数据源的描述和项目数量
3. 根据需要选择特定数据源进行深入查询

### 场景二：类型过滤

用户仅关注法规要求时：

1. 调用 `list_sources` 并设置 `source_type` 为 `regulation`
2. 仅获取联合国法规列表（r155、r156）
3. 排除 ISO 标准等非法规内容

### 场景三：内容可用性检查

用户需要确认数据源是否提供完整文本：

1. 检查返回数据中的 `full_text_available` 字段
2. 对于 `true` 的数据源（如 r155、r156），可获取完整法规文本
3. 对于 `false` 的数据源（如 iso_21434），仅能获取指导说明

## 版本兼容性说明

根据 v1.0.2 版本的更新说明，`list_sources` 工具与以下功能共享相同的ID规范化机制：

> **Case-insensitive source IDs**：所有工具现在将源ID规范化为小写，因此 `R155` 和 `r155` 的行为一致。

这意味着 `list_sources` 返回的源ID格式与用户在其他工具中使用的格式保持兼容，确保跨工具使用的一致性。

## 技术实现细节

### 数据来源

`list_sources` 工具从 SQLite 数据库的以下表读取数据：

- `regulations` - 存储联合国法规信息
- `standards` - 存储 ISO/SAE 标准信息

工具实现位于 `src/tools/list.ts` 文件中，通过统一的工具注册表模式进行注册和管理。

### 类型定义

工具的输入输出类型定义位于 `src/types/index.ts`，定义了 `list_sources` 工具的参数接口和返回数据结构。

## 故障排查

### 常见问题

**Q: 返回的数据源数量与预期不符？**

可能原因：
- 数据库未正确构建
- 种子数据未加载

解决方法：运行 `npm run build:db` 重新构建数据库

**Q: item_count 显示为 0？**

可能原因：
- 该数据源尚未添加条款数据
- 数据库连接问题

解决方法：检查数据库构建日志，确认数据加载成功

## 另请参阅

- [get_requirement 工具](./get_requirement.md) - 获取特定条款详情
- [search_requirements 工具](./search_requirements.md) - 全文搜索功能
- [数据库架构文档](./database-schema.md) - 数据存储结构说明
- [MCP 协议集成指南](./mcp-integration.md) - 与 MCP 客户端的集成方式

---

<a id='get-requirement-tool'></a>

## get_requirement 工具

### 相关页面

相关主题：[工具集概览](#tools-overview), [search_requirements 工具](#search-requirements-tool)

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

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

- [src/tools/get.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts) - `get_requirement` 工具核心实现
- [src/utils/citation.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/utils/citation.ts) - 引用生成工具
- [src/utils/source-attribution.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/utils/source-attribution.ts) - 来源归属工具
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts) - TypeScript 类型定义
- [src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts) - 工具注册表与列表工具
- [data/seed/regulations.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/regulations.json) - 法规种子数据
- [tests/r155-r156-completeness.test.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/tests/r155-r156-completeness.test.ts) - 工具测试用例
</details>

# get_requirement 工具

## 概述

`get_requirement` 是 Automotive-MCP 服务器提供的三个核心工具之一，专门用于检索汽车网络安全法规和标准的具体条款内容。该工具通过 Model Context Protocol (MCP) 接口提供服务，允许用户根据来源标识符（如 `r155`、`r156`、`iso_21434`）和条款引用编号获取精确的法规要求。

作为 Automotive-MCP Phase 1 的核心功能组件，`get_requirement` 工具在 v1.0.2 版本中已实现大小写不敏感的源 ID 处理，确保 `R155` 和 `r155` 具有相同的查询效果。资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

---

## 工具架构

### 组件关系

```mermaid
graph TD
    A[MCP 客户端请求] --> B[get_requirement 工具]
    B --> C{来源类型判断}
    C -->|法规 Regulation| D[regulations 表查询]
    C -->|标准 Standard| E[standards 表查询]
    D --> F[返回完整条款文本]
    E --> G[返回指导说明]
    H[include_mappings 参数] --> I{是否为映射查询}
    I -->|是| J[framework_mappings 表]
    J --> K[关联 ISO 21434 条款]
    F --> L[响应格式化]
    G --> L
    K --> L
    L --> M[JSON 响应]
```

### 工具注册机制

所有工具通过统一的注册表进行管理，`get_requirement` 工具的定义位于 `src/tools/list.ts` 中。工具注册时包含完整的 JSON Schema 定义，用于客户端验证和文档生成。资料来源：[src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)

---

## API 参数规范

### 请求参数

| 参数名 | 类型 | 必填 | 说明 |
|--------|------|------|------|
| `source` | string | 是 | 来源标识符，支持 `r155`、`r156`、`iso_21434`（大小写不敏感） |
| `reference` | string | 是 | 条款引用编号，如 `7.2.2.2`、`9.3` |
| `include_mappings` | boolean | 否 | 是否包含框架映射数据，默认 `false` |

### 响应字段

| 字段名 | 类型 | 说明 |
|--------|------|------|
| `source` | string | 来源标识符 |
| `reference` | string | 条款引用编号 |
| `title` | string | 条款标题 |
| `text` | string \| null | 条款完整文本（法规有文本，标准因版权为 null） |
| `guidance` | string | 专家指导说明（标准有此字段，法规为空字符串） |
| `work_products` | string[] | 相关工作产品（仅 ISO 21434 标准有此项） |
| `maps_to` | object[] | 映射到其他框架的条款（当 `include_mappings=true` 时返回） |

资料来源：[src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)

---

## 功能详解

### 法规检索（R155/R156）

当查询 UN Regulation No. 155 或 No. 156 时，`get_requirement` 返回法规的完整条款文本。这些法规由联合国欧洲经济委员会（UNECE）发布，属于公开可用的法规文件。

**示例查询：**

```json
{
  "source": "r155",
  "reference": "7.2.2.2"
}
```

**响应示例：**

```json
{
  "source": "r155",
  "reference": "7.2.2.2",
  "title": "Cyber Security Management System Requirements",
  "text": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related risk assessment in relation to cyber-attacks...",
  "guidance": ""
}
```

资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

### 标准检索（ISO/SAE 21434）

当查询 ISO/SAE 21434 标准条款时，由于该标准受版权保护，`get_requirement` 不返回完整的标准文本，而是提供专家指导说明和相关的可交付成果（工作产品）信息。

**示例查询：**

```json
{
  "source": "iso_21434",
  "reference": "9.3"
}
```

**响应示例：**

```json
{
  "source": "iso_21434",
  "reference": "9.3",
  "title": "Vulnerability analysis",
  "text": null,
  "guidance": "Monitor for vulnerabilities in components throughout vehicle lifetime. Establish processes for vulnerability disclosure, triage, and remediation. Interface with PSIRT for coordination.",
  "work_products": ["[WP-09-03]"]
}
```

资料来源：[QUALITY_ASSESSMENT_REPORT.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)

### 框架映射

通过设置 `include_mappings=true` 参数，用户可以获取当前条款映射到其他汽车网络安全框架的信息。例如，R155 的某一条款可能映射到 ISO 21434 的相关要求。

**映射数据结构：**

| 字段 | 类型 | 说明 |
|------|------|------|
| `target_source` | string | 目标框架标识符 |
| `target_reference` | string | 目标条款引用 |
| `relationship` | string | 映射关系类型（如 "addresses"） |

---

## 使用场景

### 场景一：获取特定法规要求

汽车制造商需要确认其网络安全管理系统满足 UN R155 第 7.2.2.2 条的要求，可直接调用 `get_requirement` 获取该条款的具体内容。

### 场景二：理解 ISO 21434 工作产品

开发团队需要了解进行漏洞分析时应产出哪些工作产品，通过 `get_requirement` 查询 ISO 21434 第 9.3 条即可获得相关的工作产品标识 `[WP-09-03]`。

### 场景三：建立合规追溯矩阵

使用 `get_requirement` 的 `include_mappings=true` 功能，结合 `list_sources` 和 `search_requirements` 工具，可建立从 R155/R156 到 ISO 21434 的完整合规追溯矩阵。

---

## 错误处理

### 错误响应格式

当请求的参数无效或找不到对应条款时，`get_requirement` 返回格式化的错误消息：

| 错误类型 | 错误消息示例 | HTTP 状态码 |
|----------|--------------|-------------|
| 无效来源 | `Error: Source not found: nonexistent` | 400 |
| 无效引用 | `Error: Reference not found: invalid.reference` | 400 |
| 服务器错误 | `Error: Database query failed` | 500 |

资料来源：[VERIFICATION_COMPLETE.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

### 输入验证规则

1. **source 参数**：支持的大小写变体会被自动规范化，例如 `R155` 将被转换为 `r155`
2. **reference 参数**：必须与数据库中存储的引用格式完全匹配
3. **include_mappings 参数**：布尔类型，默认为 `false`

v1.0.2 版本已修复源 ID 大小写敏感性问题的处理，确保用户无论使用大写还是小写格式都能正确查询。资料来源：[CHANGELOG.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/CHANGELOG.md)

---

## 性能特性

### 响应时间基准

根据性能测试结果，`get_requirement` 工具的查询性能表现优异：

| 查询类型 | 平均耗时 | 性能评级 |
|----------|----------|----------|
| 法规条款查询 | <1ms | 优秀 |
| 标准条款查询 | <1ms | 优秀 |
| 含映射的查询 | <2ms | 优秀 |

所有数据库操作均在亚毫秒级完成，满足实时应用的需求。资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

---

## 与其他工具的协作

### 工具组合使用

```mermaid
graph LR
    A[list_sources] --> B[列出可用法规/标准]
    B --> C[search_requirements]
    C --> D[模糊搜索相关条款]
    D --> E[get_requirement]
    E --> F[获取精确条款详情]
    
    A -.->|识别来源 ID| E
    C -.->|获取引用编号| E
```

1. **list_sources**：首先使用此工具获取所有可用的法规和标准列表及其标识符
2. **search_requirements**：使用关键词搜索找到相关的条款引用编号
3. **get_requirement**：使用确定的来源和引用编号获取精确的条款内容

---

## 配置与部署

### 环境要求

- **Node.js**：18.0 或更高版本
- **数据库**：SQLite 3（随包附带的 `data/automotive.db`）
- **MCP 客户端**：如 Claude Desktop

### Claude Desktop 配置示例

```json
{
  "mcpServers": {
    "automotive-cybersecurity": {
      "command": "npx",
      "args": ["-y", "@ansvar/automotive-cybersecurity-mcp"]
    }
  }
}
```

资料来源：[DEPLOYMENT_CHECKLIST.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/DEPLOYMENT_CHECKLIST.md)

---

## 测试验证

### 测试覆盖范围

`get_requirement` 工具经过全面的测试验证，测试覆盖包括：

| 测试类别 | 测试数量 | 状态 |
|----------|----------|------|
| 法规条款检索 | 4 | ✅ 通过 |
| 标准条款检索 | 3 | ✅ 通过 |
| 映射功能检索 | 2 | ✅ 通过 |
| 错误处理 | 2 | ✅ 通过 |
| **总计** | **11** | **✅ 全部通过** |

资料来源：[VERIFICATION_COMPLETE.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/VERIFICATION_COMPLETE.md)

### 测试用例示例

**测试 2.1：获取 R155 条款**
```json
{
  "source": "r155",
  "reference": "7.2.2.2"
}
```
预期返回完整的网络安全管理系统要求文本。

**测试 2.4：无效来源处理**
```json
{
  "source": "nonexistent",
  "reference": "1.0"
}
```
预期返回错误：`Error: Source not found: nonexistent`

资料来源：[tests/r155-r156-completeness.test.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/tests/r155-r156-completeness.test.ts)

---

## 数据来源

### 内置数据源

| 来源 ID | 名称 | 类型 | 条款数量 | 全文可用 |
|---------|------|------|----------|----------|
| `r155` | UN Regulation No. 155 | 法规 | 1+ | ✅ 是 |
| `r156` | UN Regulation No. 156 | 法规 | 0 | ✅ 是 |
| `iso_21434` | ISO/SAE 21434:2021 | 标准 | 1+ | ❌ 否（仅指导） |

Phase 1 包含最小化的示例数据，随着项目发展将逐步扩展数据覆盖范围。资料来源：[SUMMARY.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/SUMMARY.md)

---

## 相关工具

- [list_sources 工具](./list_sources.md) - 列出所有可用的法规和标准来源
- [search_requirements 工具](./search_requirements.md) - 全文搜索条款内容
- [export_compliance_matrix 工具](./export_compliance_matrix.md) - 导出合规追溯矩阵
- [list_work_products 工具](./list_work_products.md) - 列出 ISO 21434 工作产品

---

<a id='search-requirements-tool'></a>

## search_requirements 工具

### 相关页面

相关主题：[工具集概览](#tools-overview), [get_requirement 工具](#get-requirement-tool)

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

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

- [src/tools/search.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts)
- [src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)
- [src/tools/get.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts)
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)
- [scripts/build-db.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)
</details>

# search_requirements 工具

## 概述

`search_requirements` 是 Automotive-MCP 服务器提供的三大核心工具之一，专门用于对汽车网络安全法规和标准进行全文搜索。该工具基于 SQLite 的 FTS5（Full-Text Search 5）虚拟表实现，结合 BM25（Best Matching 25）算法进行相关性排序，能够在海量法规文本中快速定位用户所需的内容。

`search_requirements` 工具的主要职责包括：

- **跨数据源搜索**：同时搜索联合国法规（UN R155、R156）和 ISO/SAE 标准（ISO 21434）中的相关内容
- **智能相关性排序**：根据 BM25 算法计算每个结果的相关性得分，按得分从高到低排序
- **上下文摘要提取**：为每个搜索结果生成包含关键词上下文的摘要片段
- **多源过滤**：支持限制搜索范围到特定的数据源
- **搜索结果分页**：通过 limit 参数控制返回结果的数量上限

该工具在 v1.0.2 版本中进行了重要修复，包括源 ID 大小写规范化（`R155` 与 `r155` 等效）和搜索限制值钳制（限制参数被约束在 0-100 范围内）。资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 功能特性

### 核心能力

| 功能 | 描述 | 状态 |
|------|------|------|
| 全文搜索 | 在所有法规和标准的标题、正文、指导说明中搜索 | ✅ 已实现 |
| BM25 排序 | 使用最佳匹配 25 算法进行相关性评分 | ✅ 已实现 |
| 关键词高亮 | 在摘要中用 `**` 标记匹配关键词 | ✅ 已实现 |
| 源过滤 | 支持指定特定数据源进行搜索 | ✅ 已实现 |
| 结果数量限制 | 支持 limit 参数控制返回条数 | ✅ 已实现 |
| 大小写不敏感 | 源 ID 支持不区分大小写输入 | ✅ v1.0.2+ |

### 搜索性能

根据基准测试数据，`search_requirements` 工具展现出卓越的搜索性能：

| 查询类型 | 平均耗时 | 总耗时（100次） | 性能评级 |
|----------|----------|-----------------|----------|
| 简单查询（如 "security"） | 0.05ms | 5ms | 优秀 |
| 多词查询（如 "risk assessment"） | 0.05ms | 5ms | 优秀 |
| 复杂查询（如 "vulnerability management disclosure"） | 0.04ms | 4ms | 优秀 |

所有查询均在亚毫秒级完成，远低于 10ms 的可接受阈值。资料来源：[TEST_RESULTS.md:120-140](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 工作原理

### 系统架构

```mermaid
graph TD
    A[用户查询请求] --> B[search_requirements 工具]
    B --> C{查询参数验证}
    C -->|有效| D[查询预处理]
    C -->|无效| E[返回错误]
    D --> F[FTS5 全文搜索引擎]
    F --> G[BM25 相关性评分]
    G --> H[结果排序]
    H --> I[摘要生成]
    I --> J[高亮标记处理]
    J --> K[返回结果集]
    K --> L[limit 参数钳制]
    L --> M[最终响应]
```

### FTS5 全文搜索引擎

Automotive-MCP 使用 SQLite 的 FTS5 虚拟表实现全文搜索功能。FTS5 是 SQLite 3.9.0+ 引入的高性能全文搜索模块，支持以下特性：

1. **倒排索引**：FTS5 在内部维护倒排索引，将每个词映射到包含该词的文档列表
2. **高效匹配**：使用 B-tree 结构存储索引，支持快速词项查找
3. **短语搜索**：支持双引号包裹的精确短语匹配
4. **前缀搜索**：支持星号后缀的前缀匹配（如 `secu*` 匹配 security）

数据库构建脚本 `scripts/build-db.ts` 负责创建 FTS5 虚拟表并将法规内容索引化：

```typescript
// 资料来源：scripts/build-db.ts
CREATE VIRTUAL TABLE regulation_content_fts USING fts5(
    reference,
    title,
    content,
    content='regulation_content',
    content_rowid='rowid'
);
```

### BM25 相关性评分算法

BM25（Best Matching 25）是信息检索领域最经典的文本相关性评分算法之一。该算法基于词频（TF）和逆文档频率（IDF）计算每个文档与查询的相关性得分：

```
BM25(d, q) = Σ IDF(t) × (tf(t,d) × (k1 + 1)) / (tf(t,d) + k1 × (1 - b + b × |d|/avgdl))
```

其中：
- `t` 为查询词项
- `tf(t,d)` 为词项 t 在文档 d 中的词频
- `k1` 和 `b` 为调节参数（通常 k1=1.2, b=0.75）
- `|d|` 为文档长度，`avgdl` 为平均文档长度

在 Automotive-MCP 中，BM25 评分用于对搜索结果进行排序。评分越低（负值越大），表示相关性越高。资料来源：[TEST_RESULTS.md:150-160](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

### 搜索流程详解

```mermaid
sequenceDiagram
    participant 用户
    participant MCP客户端
    participant search工具
    participant FTS5引擎
    participant 数据库

    用户->>MCP客户端: search_requirements({query, sources?, limit?})
    MCP客户端->>search工具: 调用工具
    
    alt 参数验证
        search工具->>search工具: 规范化源 ID（小写）
        search工具->>search工具: 钳制 limit 到 [0, 100]
    end
    
    search工具->>FTS5引擎: 构建 FTS5 MATCH 查询
    FTS5引擎->>数据库: 执行 SELECT ... WHERE rowid IN (MATCH ...)
    数据库-->>FTS5引擎: 返回匹配文档 ID 列表
    FTS5引擎->>FTS5引擎: 计算 BM25 评分
    FTS5引擎->>FTS5引擎: 按评分升序排序
    
    alt 生成摘要
        FTS5引擎->>FTS5引擎: 提取上下文片段（32 tokens）
        FTS5引擎->>FTS5引擎: 标记匹配关键词 **term**
    end
    
    FTS5引擎-->>search工具: 返回结果集
    search工具->>search工具: 应用 limit 截断
    search工具-->>MCP客户端: 返回 JSON 响应
    MCP客户端-->>用户: 显示搜索结果
```

## API 参考

### 工具定义

```json
{
  "name": "search_requirements",
  "description": "Full-text search across regulations and standards using FTS5",
  "inputSchema": {
    "type": "object",
    "properties": {
      "query": {
        "type": "string",
        "description": "Search query text"
      },
      "sources": {
        "type": "array",
        "items": { "type": "string" },
        "description": "Optional list of source IDs to filter (e.g., ['r155', 'iso_21434'])"
      },
      "limit": {
        "type": "integer",
        "description": "Maximum number of results to return (clamped to 0-100, default: 10)"
      }
    }
  }
}
```

### 参数说明

| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|--------|------|------|--------|------|
| `query` | string | 是 | - | 搜索查询文本，支持单个或多个词 |
| `sources` | string[] | 否 | 所有源 | 数据源 ID 数组，支持 `r155`、`r156`、`iso_21434` |
| `limit` | integer | 否 | 10 | 返回结果数量上限，v1.0.2+ 会被钳制到 0-100 范围 |

### 返回值结构

```typescript
interface SearchResult {
  source: string;       // 数据源 ID（如 "r155"、"iso_21434"）
  reference: string;    // 条款引用（如 "7.2.2.2"、"9.3"）
  title: string;        // 条款标题
  snippet: string;     // 包含匹配上下文的摘要，关键词用 ** 包裹
  relevance: number;   // BM25 相关性评分（负值，越小越相关）
}
```

### 返回值示例

**搜索 "risk assessment" 的结果：**

```json
[
  {
    "source": "r155",
    "reference": "7.2.2.2",
    "title": "Cyber Security Management System Requirements",
    "snippet": "The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related **risk** **assessment** in relation to cyber-attacks...",
    "relevance": -0.000002
  }
]
```

**搜索 "vulnerability" 并限定源为 iso_21434：**

```json
[
  {
    "source": "iso_21434",
    "reference": "9.3",
    "title": "Vulnerability analysis",
    "snippet": "**Vulnerability** analysis",
    "relevance": -0.000001375
  }
]
```

资料来源：[TEST_RESULTS.md:70-110](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 使用示例

### 基础搜索

搜索包含 "security" 的所有法规条款：

```json
{
  "name": "search_requirements",
  "arguments": {
    "query": "security"
  }
}
```

### 带源过滤的搜索

仅在 ISO 21434 标准中搜索 "vulnerability" 相关内容：

```json
{
  "name": "search_requirements",
  "arguments": {
    "query": "vulnerability",
    "sources": ["iso_21434"]
  }
}
```

### 多源联合搜索

同时搜索 R155 和 ISO 21434 中的 "management" 相关内容：

```json
{
  "name": "search_requirements",
  "arguments": {
    "query": "management",
    "sources": ["r155", "iso_21434"]
  }
}
```

### 限制结果数量

只返回前 5 条最相关的结果：

```json
{
  "name": "search_requirements",
  "arguments": {
    "query": "risk assessment",
    "limit": 5
  }
}
```

### 完整参数示例

```json
{
  "name": "search_requirements",
  "arguments": {
    "query": "vulnerability management disclosure",
    "sources": ["r155", "iso_21434"],
    "limit": 20
  }
}
```

## 常见问题与限制

### 已知的搜索限制

| 问题 | 原因 | 解决方案 |
|------|------|----------|
| 搜索 "cyber attack" 无结果 | 种子数据使用 "cyber-attacks"（带连字符） | 尝试 "cyber-attacks" 或 "cyber attack*" |
| 特殊字符查询返回空 | FTS5 语法冲突（如引号、括号） | 工具会自动进行查询清理和转义 |
| 结果数量超过预期 | 未设置 limit 参数 | 添加 limit 参数限制结果数 |

### v1.0.2 版本修复内容

根据社区发布的最新版本信息，v1.0.2 对 `search_requirements` 工具进行了以下修复：

1. **大小写规范化**：源 ID 参数（如 `R155`）会自动转换为小写（`r155`），避免因大小写不匹配导致的搜索失败
2. **limit 参数钳制**：limit 参数被强制约束在 [0, 100] 范围内，防止传入负数或极大值导致异常
3. **输入验证增强**：无效的枚举值现在会返回更具描述性的错误信息

资料来源：[TEST_RESULTS.md:1-20](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

### 性能注意事项

虽然 `search_requirements` 在当前数据量下表现优异（亚毫秒级响应），但随着数据增长，建议：

- 始终设置合理的 limit 值（推荐 ≤ 50）
- 使用具体的源过滤（sources 参数）减少搜索范围
- 避免过于宽泛的查询词（如单个字母）

### 数据完整性说明

当前版本（Phase 1）仅包含有限的种子数据：

| 数据源 | 条款数量 | 全文可用 |
|--------|----------|----------|
| UN R155 | 1 | ✅ |
| UN R156 | 0 | - |
| ISO/SAE 21434 | 1 | ❌（仅指导说明） |

因此，搜索结果可能受限。随着后续版本扩展数据内容，搜索覆盖范围将逐步完善。资料来源：[SUMMARY.md:40-60](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/SUMMARY.md)

## 错误处理

### 常见错误及解决方案

| 错误信息 | 可能原因 | 解决方案 |
|----------|----------|----------|
| `Source not found: xxx` | 指定的数据源不存在 | 检查源 ID 是否正确，支持的源：r155, r156, iso_21434 |
| `Invalid source type` | 传入了无效的源类型 | 确保 sources 数组中的值为小写字符串 |
| `Empty result set` | 查询词未匹配任何内容 | 尝试使用同义词或通配符搜索 |

### 特殊字符处理

`search_requirements` 工具内置查询清理机制，会自动处理以下特殊字符：

- 连字符（`-`）：如 `risk-assessment` 会被处理为 `risk assessment`
- 括号（`()`）：会被移除或转义
- 引号（`"`）：用于短语搜索，可保留

## 相关文件

| 文件路径 | 说明 |
|----------|------|
| [src/tools/search.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts) | search_requirements 工具核心实现 |
| [src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts) | list_sources 工具（列出可用数据源） |
| [src/tools/get.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts) | get_requirement 工具（获取具体条款） |
| [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts) | TypeScript 类型定义 |
| [scripts/build-db.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts) | 数据库构建脚本（包含 FTS5 表创建） |

## 参见

- [get_requirement 工具](./get_requirement-工具.md) - 获取特定法规条款的详细信息
- [list_sources 工具](./list_sources-工具.md) - 列出所有可用的法规和标准数据源
- [Automotive-MCP 概述](./overview.md) - 服务器整体架构说明

---

<a id='compliance-export-tool'></a>

## export_compliance_matrix 工具

### 相关页面

相关主题：[工具集概览](#tools-overview), [get_requirement 工具](#get-requirement-tool)

根据提供的上下文信息，我在仓库中没有找到 `export_compliance_matrix` 工具的源代码或相关文档。仓库中现有的合规相关工具包括：

1. `list_sources` - 列出可用的法规和标准来源
2. `get_requirement` - 检索特定条款内容
3. `search_requirements` - 全文搜索法规和标准内容

以下是现有合规工具的功能说明页面：

---

# Automotive-MCP 合规工具概览

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

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

- [src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)
- [src/tools/get.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts)
- [src/tools/search.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts)
- [src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)
- [data/automotive.db](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/automotive.db)

</details>

## 关于 export_compliance_matrix 工具

在当前版本（v1.0.2）的仓库中，**尚未实现** `export_compliance_matrix` 工具。该工具可能属于未来 Phase 2 版本的规划功能。

根据 [SUMMARY.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/SUMMARY.md) 中的规划，框架映射（framework mappings）功能计划在 Phase 2 中扩展，届时可能会提供类似合规矩阵导出的功能。

---

## 现有合规工具

当前版本提供了三个核心工具用于合规性检查：

### 工具概览

| 工具名称 | 功能描述 | 数据来源 |
|---------|---------|---------|
| `list_sources` | 列出所有可用的法规和标准 | regulations, standards 表 |
| `get_requirement` | 获取特定条款的完整内容 | regulation_content, standard_clauses 表 |
| `search_requirements` | 全文搜索法规和标准内容 | FTS5 全文索引 |

---

## list_sources 工具

### 功能说明

`list_sources` 工具用于列出所有已注册的法规和标准来源。

资料来源：[src/tools/list.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/list.ts)

### API 参数

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| `source_type` | `string` | 否 | 过滤来源类型，可选值：`regulation`、`standard` |

### 返回数据格式

```json
[
  {
    "id": "r155",
    "name": "UN Regulation No. 155",
    "version": "Revision 2",
    "type": "regulation",
    "description": "Cyber Security and Cyber Security Management System",
    "item_count": 1,
    "full_text_available": true
  }
]
```

### 字段说明

| 字段 | 类型 | 说明 |
|-----|------|------|
| `id` | string | 来源唯一标识符（如 `r155`、`iso_21434`） |
| `name` | string | 法规/标准全称 |
| `version` | string | 版本信息 |
| `type` | string | 类型：`regulation` 或 `standard` |
| `description` | string | 简要描述 |
| `item_count` | number | 包含的条款数量 |
| `full_text_available` | boolean | 是否提供全文 |

资料来源：[src/types/index.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/types/index.ts)

---

## get_requirement 工具

### 功能说明

`get_requirement` 工具用于获取特定法规条款或标准章节的详细内容。

资料来源：[src/tools/get.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/get.ts)

### API 参数

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| `source` | string | 是 | 来源标识符（如 `r155`、`iso_21434`） |
| `reference` | string | 是 | 条款引用编号（如 `7.2.2.2`、`9.3`） |
| `include_mappings` | boolean | 否 | 是否包含框架映射信息（v1.0.2 中数据库映射数据为空） |

### 返回数据格式（法规）

```json
{
  "source": "r155",
  "reference": "7.2.2.2",
  "title": "Cyber Security Management System Requirements",
  "text": "The Cyber Security Management System shall be appropriate...",
  "guidance": "",
  "work_products": []
}
```

### 返回数据格式（标准）

```json
{
  "source": "iso_21434",
  "reference": "9.3",
  "title": "Vulnerability analysis",
  "text": null,
  "guidance": "Monitor for vulnerabilities in components throughout vehicle lifetime...",
  "work_products": ["[WP-09-03]"]
}
```

### 字段说明

| 字段 | 类型 | 说明 |
|-----|------|------|
| `source` | string | 来源标识符 |
| `reference` | string | 条款编号 |
| `title` | string | 条款标题 |
| `text` | string \| null | 条款正文（法规有全文，标准因版权限制为 null） |
| `guidance` | string | 专家指导说明 |
| `work_products` | string[] | 相关工作产品列表 |

### v1.0.2 改进

在最新版本中，`get_requirement` 已修复以下问题：

- **大小写不敏感**：来源 ID 现在会规范化为小写，`R155` 和 `r155` 具有相同效果
- **输入验证**：无效的枚举值现在返回描述性错误信息

资料来源：[社区更新说明 - v1.0.2](https://github.com/Ansvar-Systems/Automotive-MCP/releases/tag/v1.0.2)

---

## search_requirements 工具

### 功能说明

`search_requirements` 工具提供基于 FTS5 的全文搜索功能，支持 BM25 相关性排名。

资料来源：[src/tools/search.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/src/tools/search.ts)

### API 参数

| 参数名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| `query` | string | 是 | 搜索关键词 |
| `sources` | string[] | 否 | 限定搜索来源（如 `["r155", "iso_21434"]`） |
| `limit` | number | 否 | 返回结果数量上限（范围 0-100，默认 10） |

### 返回数据格式

```json
[
  {
    "source": "r155",
    "reference": "7.2.2.2",
    "title": "Cyber Security Management System Requirements",
    "snippet": "...vehicle type related **risk** **assessment**...",
    "relevance": -0.000002
  }
]
```

### 字段说明

| 字段 | 类型 | 说明 |
|-----|------|------|
| `source` | string | 来源标识符 |
| `reference` | string | 匹配的条款编号 |
| `title` | string | 条款标题（匹配词高亮显示） |
| `snippet` | string | 上下文摘录（匹配词以 `**` 包围） |
| `relevance` | number | BM25 相关性分数（越低越相关） |

### v1.0.2 改进

- **搜索限制值修正**：`limit` 参数现在被限制在 `[0, 100]` 范围内，防止负数或极端值
- **输入验证**：`sources` 参数中的无效值现在返回描述性错误

资料来源：[社区更新说明 - v1.0.2](https://github.com/Ansvar-Systems/Automotive-MCP/releases/tag/v1.0.2)

### 性能指标

| 指标 | 数值 | 评估 |
|-----|------|------|
| 简单查询平均耗时 | 0.05ms | 优秀 |
| 复杂查询平均耗时 | 0.04ms | 优秀 |
| 100 次查询总耗时 | 5ms | 优秀 |

资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

---

## 数据架构

### 数据库结构

```mermaid
erDiagram
    regulations ||--o{ regulation_content : "has"
    standards ||--o{ standard_clauses : "has"
    
    regulations {
        string id PK
        string name
        string version
        string type
        string description
    }
    
    regulation_content {
        string source FK
        string reference PK
        string title
        string text
        string guidance
    }
    
    standards {
        string id PK
        string name
        string version
        string type
        string description
    }
    
    standard_clauses {
        string source FK
        string reference PK
        string title
        string guidance
        string work_products
    }
```

### 全文搜索索引

数据库使用 SQLite FTS5 虚拟表实现全文搜索：

```mermaid
graph LR
    A[用户查询] --> B[search_requirements]
    B --> C[FTS5 查询处理]
    C --> D[BM25 排名]
    D --> E[高亮片段生成]
    E --> F[返回结果]
```

---

## 合规工作流程

### 基础合规检查流程

```mermaid
graph TD
    A[开始合规检查] --> B[list_sources]
    B --> C{需要检查哪些来源?}
    C -->|所有来源| D[获取完整列表]
    C -->|特定来源| E[按类型筛选]
    D --> F[get_requirement]
    E --> F
    F --> G[查看条款详情]
    G --> H{符合要求?}
    H -->|是| I[记录合规]
    H -->|否| J[记录差距]
    J --> K[生成改进计划]
```

### 搜索匹配流程

```mermaid
graph TD
    A[输入搜索关键词] --> B{关键词有效?}
    B -->|空字符串| C[返回空数组]
    B -->|有效关键词| D[sanitize_query]
    D --> E[构建 FTS5 查询]
    E --> F[执行 BM25 搜索]
    F --> G[按相关性排序]
    G --> H[生成高亮片段]
    H --> I[返回结果]
```

---

## 使用示例

### 示例 1：列出所有法规

```json
{
  "tool": "list_sources",
  "parameters": {
    "source_type": "regulation"
  }
}
```

**响应：**
```json
[
  {
    "id": "r155",
    "name": "UN Regulation No. 155",
    "version": "Revision 2",
    "type": "regulation",
    "description": "Cyber Security and Cyber Security Management System",
    "item_count": 17,
    "full_text_available": true
  },
  {
    "id": "r156",
    "name": "UN Regulation No. 156",
    "version": "Revision 2",
    "type": "regulation",
    "description": "Software Update and Software Updates Management System",
    "item_count": 0,
    "full_text_available": true
  }
]
```

### 示例 2：获取 R155 具体条款

```json
{
  "tool": "get_requirement",
  "parameters": {
    "source": "r155",
    "reference": "7.2.2.2"
  }
}
```

### 示例 3：搜索相关要求

```json
{
  "tool": "search_requirements",
  "parameters": {
    "query": "risk assessment",
    "sources": ["r155", "iso_21434"],
    "limit": 10
  }
}
```

---

## 已知限制

| 限制项 | 说明 | 计划解决方案 |
|-------|------|-------------|
| 映射功能未启用 | 数据库中暂无框架映射数据 | Phase 2 扩展 |
| 数据有限 | Phase 1 包含最小化示例数据 | 持续完善数据 |
| ISO 标准全文缺失 | 因版权限制，`text` 字段为 null | 仅提供 guidance |
| export_compliance_matrix 未实现 | 合规矩阵导出功能 | 未来版本规划 |

资料来源：[SUMMARY.md - Medium Priority Recommendations](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/SUMMARY.md)

---

## 参见

- [README.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/README.md) - 项目主文档
- [安装指南](../Installation) - MCP 服务配置说明
- [API 参考](../API-Reference) - 工具详细接口文档

---

> **注意**：如需 `export_compliance_matrix` 工具，请关注未来版本更新或提交功能请求。

---

<a id='seed-data-structure'></a>

## 种子数据结构

### 相关页面

相关主题：[数据库架构](#database-schema)

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

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

- [data/seed/regulations.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/regulations.json)
- [data/seed/standards.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/standards.json)
- [data/seed/cross-mappings.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/cross-mappings.json)
- [scripts/build-db.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)
</details>

# 种子数据结构

## 概述

种子数据结构是Automotive-MCP项目的核心数据资产，用于初始化SQLite数据库中的汽车网络安全法规和标准内容。该数据模型定义了法规（Regulations）、标准（Standards）以及跨框架映射（Cross-Mappings）三类核心实体的结构规范，为MCP服务器提供可查询的法规条款和标准指导。

种子数据采用JSON格式存储于`data/seed/`目录下，通过`scripts/build-db.ts`脚本构建脚本在数据库初始化时加载到SQLite中。所有种子数据均经过FTS5全文索引处理，支持基于BM25算法的相关性搜索功能。

资料来源：[scripts/build-db.ts:1-50](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)

## 数据架构

### 整体数据模型

```mermaid
graph TD
    A[seed数据目录] --> B[regulations.json]
    A --> C[standards.json]
    A --> D[cross-mappings.json]
    B --> E[SQLite regulations表]
    C --> F[SQLite standards表]
    D --> G[SQLite mappings表]
    E --> H[FTS5全文索引]
    F --> H
    G --> I[查询结果返回]
    H --> I
```

### 核心实体关系

| 实体类型 | 存储文件 | 数据库表 | 主要字段 |
|---------|---------|---------|---------|
| 法规 | regulations.json | regulations, regulation_content | id, name, version, type |
| 标准 | standards.json | standards, standard_clauses | id, name, version, type |
| 映射 | cross-mappings.json | regulation_content_mappings | source, reference, maps_to |

资料来源：[scripts/build-db.ts:80-150](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)

## 法规数据结构

### 法规JSON结构

`regulations.json`文件定义了汽车网络安全相关法规的完整结构。每个法规条目包含基本信息、元数据和条款内容三个层级：

```json
{
  "id": "r155",
  "name": "UN Regulation No. 155",
  "version": "Revision 2",
  "type": "regulation",
  "description": "Cyber Security and Cyber Security Management System",
  "full_text_available": true,
  "items": [
    {
      "reference": "7.2.2.2",
      "title": "Cyber Security Management System Requirements",
      "text": "The Cyber Security Management System shall be appropriate to the type of vehicle...",
      "guidance": ""
    }
  ]
}
```

### 字段定义

| 字段名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| id | string | 是 | 法规唯一标识符，采用小写格式 |
| name | string | 是 | 法规官方名称 |
| version | string | 是 | 法规版本号或修订版本 |
| type | string | 是 | 固定值"regulation"表示法规类型 |
| description | string | 是 | 法规简短描述 |
| full_text_available | boolean | 是 | 标识是否提供完整文本 |
| items | array | 是 | 法规条款数组 |

### 条款对象结构

| 字段名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| reference | string | 是 | 条款编号，如"7.2.2.2" |
| title | string | 是 | 条款标题 |
| text | string | 是 | 条款正文内容 |
| guidance | string | 是 | 实施指导（法规通常为空） |

资料来源：[data/seed/regulations.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/regulations.json)

## 标准数据结构

### 标准JSON结构

`standards.json`文件存储ISO/SAE等汽车行业标准信息。与法规不同，标准条目通常不包含完整文本（需要付费许可），但提供详细的实施指导和工件清单：

```json
{
  "id": "iso_21434",
  "name": "ISO/SAE 21434:2021",
  "version": "2021",
  "type": "standard",
  "description": "Road vehicles — Cybersecurity engineering",
  "full_text_available": false,
  "clauses": [
    {
      "reference": "9.3",
      "title": "Vulnerability analysis",
      "text": null,
      "guidance": "Monitor for vulnerabilities in components throughout vehicle lifetime...",
      "work_products": ["[WP-09-03]"]
    }
  ]
}
```

### 字段定义

| 字段名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| id | string | 是 | 标准唯一标识符 |
| name | string | 是 | 标准官方名称（含发布年份） |
| version | string | 是 | 版本或发布年份 |
| type | string | 是 | 固定值"standard"表示标准类型 |
| description | string | 是 | 标准简短描述 |
| full_text_available | boolean | 是 | 标识全文是否可用（标准通常为false） |
| clauses | array | 是 | 标准条款数组 |

### 条款对象结构

| 字段名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| reference | string | 是 | 条款编号 |
| title | string | 是 | 条款标题 |
| text | string | 是 | 条款正文（标准通常为null） |
| guidance | string | 是 | 详细实施指导 |
| work_products | array | 是 | 关联的工作产品列表 |

资料来源：[data/seed/standards.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/standards.json)

## 跨框架映射结构

### 映射JSON结构

`cross-mappings.json`定义了不同法规和标准之间的关联关系，支持跨框架查询功能：

```json
[
  {
    "source_type": "regulation",
    "source_id": "r155",
    "source_reference": "7.2.2.2",
    "target_type": "standard",
    "target_id": "iso_21434",
    "target_reference": "8.3",
    "relationship": "related",
    "description": "Risk assessment relates to threat analysis"
  }
]
```

### 字段定义

| 字段名 | 类型 | 必填 | 说明 |
|-------|------|------|------|
| source_type | string | 是 | 源实体类型："regulation"或"standard" |
| source_id | string | 是 | 源法规或标准ID |
| source_reference | string | 是 | 源条款编号 |
| target_type | string | 是 | 目标实体类型 |
| target_id | string | 是 | 目标法规或标准ID |
| target_reference | string | 是 | 目标条款编号 |
| relationship | string | 是 | 关联类型（如"related"、"implements"） |
| description | string | 是 | 映射关系描述 |

资料来源：[data/seed/cross-mappings.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/cross-mappings.json)

## 数据加载流程

### 数据库构建流程

```mermaid
graph TD
    A[npm run build:db] --> B[读取seed JSON文件]
    B --> C[验证JSON schema]
    C --> D{格式正确?}
    D -->|是| E[清空现有数据]
    E --> F[插入regulations数据]
    F --> G[插入standards数据]
    G --> H[插入mappings数据]
    H --> I[构建FTS5索引]
    I --> J[生成automotive.db]
    D -->|否| K[输出验证错误]
    J --> L[数据库就绪]
```

### 数据表结构

数据库创建包含以下核心表：

| 表名 | 用途 | 索引 |
|------|------|------|
| regulations | 存储法规基本信息 | PRIMARY KEY(id) |
| regulation_content | 存储法规条款内容 | FK + FTS |
| standards | 存储标准基本信息 | PRIMARY KEY(id) |
| standard_clauses | 存储标准条款内容 | FK + FTS |
| regulation_content_mappings | 存储跨框架映射 | COMPOSITE FK |

资料来源：[scripts/build-db.ts:50-80](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts)

## 当前数据内容

### Phase 1 种子数据

| 来源 | 标识符 | 名称 | 条款数量 | 全文可用 |
|------|--------|------|---------|---------|
| UN法规 | r155 | UN Regulation No. 155 | 1 | 是 |
| UN法规 | r156 | UN Regulation No. 156 | 0 | 是 |
| ISO标准 | iso_21434 | ISO/SAE 21434:2021 | 1 | 否 |

当前Phase 1仅包含最小可行数据集，用于验证系统功能和API接口。实际部署时需要补充完整的法规和标准内容。

### 示例数据内容

**法规条款示例（R155 7.2.2.2）：**

> The Cyber Security Management System shall be appropriate to the type of vehicle and shall address the following areas as they apply to the vehicle type: (a) vehicle type related risk assessment in relation to cyber-attacks...

**标准条款示例（ISO 21434 9.3）：**

> Monitor for vulnerabilities in components throughout vehicle lifetime. Establish processes for vulnerability disclosure, triage, and remediation. Interface with PSIRT for coordination.

资料来源：[TEST_RESULTS.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/TEST_RESULTS.md)

## 数据质量验证

### 测试覆盖

| 验证类别 | 测试数量 | 状态 |
|---------|---------|------|
| 数据库填充 | 16 | ✅ 通过 |
| R155/R156完整性 | 16 | ✅ 通过 |
| 工具功能 | 29 | ✅ 通过 |
| 手动集成测试 | 30 | ✅ 通过 |
| **总计** | **91** | **✅ 全部通过** |

### 性能指标

| 操作 | 平均耗时 | 性能评级 |
|------|---------|---------|
| 数据库打开 | <5ms | 优秀 |
| 列表数据源 | <1ms | 优秀 |
| 获取条款 | <1ms | 优秀 |
| 全文搜索 | 0.05ms | 优秀 |

所有查询均保持在亚毫秒级别，FTS5索引工作正常。

资料来源：[QUALITY_ASSESSMENT_REPORT.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/QUALITY_ASSESSMENT_REPORT.md)

## 扩展数据源

### 添加新法规

1. 编辑`data/seed/regulations.json`，添加新法规条目
2. 在`items`数组中添加条款内容
3. 运行`npm run build:db`重建数据库
4. 执行`npm test`验证数据加载

### 添加新标准

1. 编辑`data/seed/standards.json`，添加新标准条目
2. 在`clauses`数组中添加条款内容
3. 包含`guidance`和`work_products`字段
4. 重建数据库并测试

### 添加跨框架映射

1. 编辑`data/seed/cross-mappings.json`
2. 定义source和target的关联关系
3. 重建数据库使映射生效

资料来源：[R155_R156_INTEGRATION_SUMMARY.md](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/R155_R156_INTEGRATION_SUMMARY.md)

## 版本兼容性说明

### v1.0.2 更新

最新版本对种子数据查询进行了以下优化：

| 修复项 | 说明 |
|-------|------|
| 大小写归一化 | source IDs现自动转为小写，R155与r155等价 |
| 限制值边界 | search_requirements的limit参数限制在[0, 100]范围内 |
| 错误描述 | 无效枚举值返回详细错误信息 |

这些改进确保种子数据查询的健壮性和一致性。

## 相关资源

| 资源 | 说明 |
|------|------|
| [build-db.ts](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/scripts/build-db.ts) | 数据库构建脚本 |
| [regulations.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/regulations.json) | 法规种子数据 |
| [standards.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/standards.json) | 标准种子数据 |
| [cross-mappings.json](https://github.com/Ansvar-Systems/Automotive-MCP/blob/main/data/seed/cross-mappings.json) | 映射种子数据 |

## 参见

- [MCP工具接口](../tools/mcp-tools.md) - 了解如何使用种子数据进行查询
- [数据库架构](./database-schema.md) - 深入了解SQLite表结构
- [全文搜索机制](./full-text-search.md) - 了解FTS5和BM25算法

---

<!-- evidence_injected: true -->

---

## Doramagic 踩坑日志

项目：ansvar-systems/automotive-mcp

摘要：发现 7 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。

## 1. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `automotive-mcp` 与安装入口 `@ansvar/automotive-cybersecurity-mcp` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npx @ansvar/automotive-cybersecurity-mcp`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | repo=automotive-mcp; install=@ansvar/automotive-cybersecurity-mcp

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

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | README/documentation is current enough for a first validation pass.

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

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | last_activity_observed missing

## 4. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | no_demo; severity=medium

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

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | no_demo; severity=medium

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

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | issue_or_pr_quality=unknown

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

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | mcp_registry:io.github.Ansvar-Systems/automotive-cybersecurity:1.0.1 | https://registry.modelcontextprotocol.io/v0.1/servers/io.github.Ansvar-Systems%2Fautomotive-cybersecurity/versions/1.0.1 | release_recency=unknown

<!-- canonical_name: ansvar-systems/automotive-mcp; human_manual_source: deepwiki_human_wiki -->
