Skip to main content
Glama
HCM-LLM MCP Server

HCM-LLM MCP Server

by crosstraffic

一个基于 FastAPI 的模型上下文协议(MCP)服务器,用于公路通行能力手册(HCM)分析和交通工程计算。到目前为止,该服务器提供遵循 HCM 第 15 章方法的全面双车道公路分析。

功能

  • 对 HCM 文档的语义搜索

  • 完整的 HCM 第 15 章(双车道公路)和第 12 章(基本高速公路)分析

  • 完整的 HCM 章节覆盖,第 10 章至第 28 章,通过三个能力工具(hcm_analyze、hcm_describe、hcm_validate)提供 33 个方法,每个方法都接受库自身的示例用例 JSON,并针对其已发布的示例问题进行验证

  • 针对 HCM/AASHTO 约束的输入验证网关(通过 transportations-validator)

  • 全语料验证(涵盖 HCM/AASHTO/MUTCD/HSM/ADA/... 的 300+ 条规则),带引用、地形/上下文门控规则和澄清请求——在进程内运行,无需数据库

  • 知识图谱推理:溯因设计修复(双车道与基本高速公路)、可废止代码协调、逆向设计以及正向/反向链——每个修复候选都会通过经过验证的库重新执行

  • 基于 YAML 的函数注册表,便于扩展

  • 函数调用接口,提供 15+ 个交通分析函数

  • MCP 服务器兼容性,可与 AI 助手集成(支持 Claude)

  • 用于直接访问的 RESTful API 端点

  • 基于注册表的动态端点生成

  • 全面的测试套件和验证工具

Related MCP server: MCP WebAnalyzer

连接到远程 MCP 服务器

此服务器可用作 Claude Desktop 等 AI 代码代理的后端,使其能够执行复杂的交通分析并动态访问 HCM 文档。

要启用此功能,请将服务器作为 MCP 服务器添加到您的 AI 助手配置中。

对于 Claude Desktop 用户

在用户设置中,您可以找到 Connectors 选项卡,然后点击 Add custom connector。

然后将 https://api.hcm-calculator.com/mcp 添加到您的 Claude 配置中。

对于 VSCode 上的 GitHub Copilot 用户

您也可以通过将服务器配置为自定义 MCP 服务器,将其与 GitHub Copilot 一起使用。

为此,请按 Ctrl+p 并选择 MCP: Open User Configuration,然后将以下内容修改到您的 mcp.json 中:

{
	"servers": {
		"hcm-mcp": {
			"url": "https://api.hcm-calculator.com/mcp"
		}
	}
}

连接到本地 MCP 服务器

您也可以出于开发或测试目的在本地运行此服务器。

uv venv

# Windows
.venv\Scripts\activate
# Linux
source .venv/bin/activate

uv pip install .

然后运行服务器。

# Setup the database.
python hcm_mcp_server/scripts/import_hcm_docs.py

# Start the server.
python mcp_server_fastapi.py

对于 Claude Desktop 用户

打开 Claude Desktop,并将服务器添加为自定义 MCP 服务器,URL 为 http://localhost:8000/mcp。

添加到您的 Claude Desktop 配置(claude_desktop_config.json)中:

注意:这些 json 设置最近似乎不起作用(https://github.com/anthropics/claude-code/issues/4188),在我的桌面环境中也不起作用。

{
  "mcpServers": {
    "hcm-mcp-local": {
      "url": "http://127.0.0.1:8000/mcp"
    }
  }
}

对于 VSCode 上的 GitHub Copilot 用户

与上面相同,您可以通过将服务器配置为自定义 MCP 服务器,将其与 GitHub Copilot 一起使用。

为此,请按 Ctrl+p 并选择 MCP: Open User Configuration,然后将以下内容修改到您的 mcp.json 中:

{
	"servers": {
		"hcm-mcp-local": {
			"url": "http://127.0.0.1:8000/mcp"
		}
	}
}

然后您就可以直接在代码编辑器中使用函数调用接口。

项目结构

hcm-mcp-server/
├── mcp_server_fastapi.py        # Main FastAPI application
├── functions_registry.yaml      # Function registry configuration
├── hcm_mcp_server/
│   ├── example_prompts/                  
│   │   ├── *.txt                # Example prompts for function calling
│   │   └── *.json               # Example json files for web validation
│   ├── core/                    # Core application modules
│   │   ├── dependencies.py      # Dependency injection and utilities
│   │   ├── registry.py          # Function registry implementation
│   │   ├── models.py            # Pydantic data models
│   │   └── endpoints.py         # Dynamic endpoint creation
│   ├── functions/                  
│   │   ├── chapter15.py         # Chapter 15: Two-Lane Highways
│   │   └── research.py          # Research and documentation
│   └── scripts/                    
│       ├── import_hcm_docs.py   # Import HCM documentation and setup ChromaDB
│       └── validate_registry.py # Registry validation
├── data/                           
│   └──  hcm_files/               # HCM documentation files
└── chroma_db/                    # ChromaDB storage

配置

环境变量

基于 .env.example 创建一个 .env 文件。复制并粘贴以下内容,或执行 cp .env.example .env:

CHROMA_DB_PATH=./chroma_db
HOST=127.0.0.1
PORT=8000
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
LOG_LEVEL=INFO
DB_MODE=local
PUBLIC_SUPABASE_URL=https://
PUBLIC_SUPABASE_API=your-anon-key / service-role-key

函数注册表

函数在 functions_registry.yaml 中定义:

functions:
  chapter15:
    identify_vertical_class:
      module: "functions.chapter15"
      function: "identify_vertical_class_function"
      description: "Identify vertical alignment class range"
      category: "transportation"
      chapter: 15
      step: 1
      parameters:
        type: "object"
        properties:
          segment_index:
            type: "integer"
          highway_data:
            type: "object"
        required: ["segment_index", "highway_data"]

消融分支(受限的 MCP 表面)

对于表 5 / 图 7 的 2x2 消融,可以启动同一个应用,仅暴露一部分工具,以便在每种条件下单独评估模型:

python mcp_server_fastapi.py     # ct  : full system (all tools), port 8000
python mcp_server_kg_only.py     # kg  : 7 reasoning/validation tools only, port 8001 (no Chroma needed)
python mcp_server_rag_only.py    # rag : query_hcm only, port 8002

两个启动器都是轻量包装器,在导入应用之前设置两个环境变量:

  • HCM_MCP_INCLUDE_OPS — MCP 表面暴露的逗号分隔的操作 ID(未设置 = 全部)。过滤使用 FastApiMCP(include_operations=...)。

  • HCM_ENABLE_RAG — 设置为 false 以跳过加载嵌入模型和向量存储(仅知识图谱分支两者都不需要)。

将每个 VS Code / Claude Desktop MCP 客户端指向被测分支的端口(例如,仅知识图谱分支使用 http://localhost:8001),以便模型只看到该分支的工具。base 分支就是简单地不附加 MCP 服务器。

API 用法

完整公路分析

curl -X POST "http://localhost:8000/analysis/chapter15/complete" \
  -H "Content-Type: application/json" \
  -d '{
    "segments": [{
      "passing_type": 0,
      "length": 2.0,
      "grade": 2.0,
      "spl": 50.0,
      "volume": 760.0,
      "volume_op": 1500.0,
      "phf": 0.95,
      "phv": 5.0
    }],
    "lane_width": 12.0,
    "shoulder_width": 6.0,
    "apd": 5.0
  }'

函数调用接口

curl -X POST "http://localhost:8000/tools/call" \
  -H "Content-Type: application/json" \
  -d '{
    "function": {
      "name": "chapter15_determine_free_flow_speed",
      "arguments": {
        "segment_index": 0,
        "highway_data": {
          "segments": [{"passing_type": 0, "length": 2.0, "grade": 2.0, "spl": 50.0}],
          "lane_width": 12.0,
          "shoulder_width": 6.0
        }
      }
    }
  }'

列出可用函数

# List all functions
curl -X POST "http://localhost:8000/tools/list"

# Filter by category
curl -X POST "http://localhost:8000/tools/list" \
  -H "Content-Type: application/json" \
  -d '{"category": "transportation"}'

# Filter by chapter
curl -X POST "http://localhost:8000/tools/list" \
  -H "Content-Type: application/json" \
  -d '{"chapter": 15}'

查询 HCM 文档

curl -X POST "http://localhost:8000/tools/query-hcm" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "What factors affect free flow speed in two-lane highways?",
    "top_k": 5
  }'

可用函数

第 15 章函数

  • chapter15_identify_vertical_class - 步骤 1:确定纵断面线形类别范围

  • chapter15_determine_demand_flow - 步骤 2:计算需求流率和通行能力

  • chapter15_determine_vertical_alignment - 步骤 3:确定纵断面线形分类

  • chapter15_determine_free_flow_speed - 步骤 4:计算自由流速度

  • chapter15_estimate_average_speed - 步骤 5:估算平均行驶速度

  • chapter15_estimate_percent_followers - 步骤 6:估算跟驰车辆百分比

  • chapter15_determine_follower_density_pl - 步骤 8a:超车车道的跟驰密度

  • chapter15_determine_follower_density_pc_pz - 步骤 8b:PC/PZ 路段的跟驰密度

  • chapter15_determine_segment_los - 步骤 9:计算路段服务水平

  • chapter15_determine_facility_los - 步骤 10:计算设施服务水平

  • chapter15_complete_analysis - 完整的 HCM 第 15 章流程

第 12 章函数(基本高速公路路段)

与第 15 章不同的方程族——lane width -> FFS -> capacity/speed -> density -> LOS 链。需要 transportations-library>=0.1.12。

  • chapter12_determine_free_flow_speed - 步骤 2:估算并调整自由流速度

  • chapter12_estimate_capacity - 步骤 3:基准和调整后的通行能力(pc/h/ln)

  • chapter12_estimate_demand_volume - 步骤 4:每车道流率 v_p

  • chapter12_calculate_speed - 步骤 5a:通过速度-流量曲线计算区间平均速度

  • chapter12_estimate_density - 步骤 5b:密度 D = v_p / S

  • chapter12_determine_segment_los - 步骤 6:路段服务水平

  • chapter12_complete_analysis - 完整的 HCM 第 12 章基本高速公路流程

HCM 分析能力(完整章节覆盖)

计算库实现的每个 HCM 方法,第 10 章至第 28 章,都位于三个能力工具之后。方法是一个参数,而不是一个工具:三十三个几乎相同的模式会消耗每个调用者的上下文并削弱工具选择,而且上面的十个已发布工具已经是能力形态的。

  • hcm_analyze — {method, config}。运行一个方法。工具描述包含方法目录,每个方法一行简洁说明,method 是三十三个 ID 的枚举。

  • hcm_describe — {method?}。提供方法时:返回其输入模式概要、结果字段含义以及用于验证它的示例问题夹具。不提供方法时:返回目录,每个方法 ID 及其章节和一行摘要。请先调用此工具;调用者通过它了解方法的形态,而无需阅读 Rust 绑定。

  • hcm_validate — {method, config}。解析并检查配置,不运行分析,返回库自身的验证错误或 ok。迭代配置只需一次解析,而不是完整分析。三十三个方法中有二十四个在构造函数后面有真正的验证步骤(serde 反序列化、构造函数范围检查,以及第 15 章通过 tl.validate_input 进行的 Exhibit 15-8 参数范围检查);另外九个是库中的单一 JSON 入口点,解析和计算是一次调用,这些方法会在响应中说明这一点,而不是运行分析并将其称为验证。

输入始终是计算库自身的示例用例(fixture)JSON,作为 config 传递——而不是为 MCP 层发明的第二个扁平化模式。来自 transportations-library/tests/ExampleCases/hcm/ 的示例用例可以原样传递。需要 transportations-library>=0.3.7。

章节

method

计算内容

10

analyze_freeway_facility

高速公路设施(第 25 章引擎)

10

analyze_managed_lanes

管理车道高速公路设施

11

analyze_freeway_reliability

高速公路行程时间可靠性

12

analyze_basic_freeway

基本高速公路和多车道路段

13

analyze_weaving

高速公路交织路段(HCM 7 和 7.1)

14

analyze_merge_diverge

高速公路合流和分流路段(HCM 7 和 7.1)

15

analyze_bicycle_los

双车道和多车道公路路段,自行车模式

15

analyze_two_lane_highway

双车道公路设施

16

analyze_urban_facility

城市街道设施

17

analyze_urban_reliability

城市街道行程时间可靠性

18

analyze_bicycle_segment

城市街道路段,自行车模式

18

analyze_pedestrian_segment

城市街道路段,行人模式

18

analyze_transit_segment

城市街道路段,公交模式

18

analyze_urban_segment

城市街道路段,汽车模式

19

analyze_signalized

信号控制交叉口,汽车模式

19

analyze_signalized_bicycle

信号控制交叉口,自行车模式

19

analyze_signalized_pedestrian

信号控制交叉口,行人模式

19

analyze_two_stage_crossing

两阶段行人过街延误

20

analyze_twsc

双向停车控制交叉口,机动车

20

analyze_twsc_pedestrian

TWSC 和路段中间过街,行人模式

21

analyze_awsc

全向停车控制交叉口

22

analyze_roundabout

环形交叉口

23

analyze_alternative_intersection

RCUT 和 MUT 替代交叉口(C 部分)

23

analyze_displaced_left_turn

移位左转交叉口(C 部分)

23

analyze_ramp_terminal

互通式立交匝道端点(B 部分)

24

analyze_offstreet_bicycle

路外路径,自行车模式

24

analyze_pedestrian_walkway

专用人行道或楼梯

24

analyze_shared_use_path_pedestrian

共用路径,行人模式

25

analyze_composite_grade

混合流模型,组合坡度

25

analyze_planning_facility

规划层面的高速公路设施

26

analyze_mixed_flow

混合流模型,单一坡度

27

analyze_weaving_service_volumes

交织路段服务交通量

28

analyze_ramp_service_volumes

合流和分流服务交通量

每个方法都在 hcm_mcp_server/data/examples/<method>.json 下附带其工作示例,tests/test_methods.py 通过 hcm_analyze 驱动每一个示例,对照该示例问题的已发布值,并采用计算库自身测试套件所断言的容差。

每个方法还在 /analysis/hcm/<method-with-hyphens> 处保留一个方法形状的 REST 路由,供直接 API 调用者使用。路由不是 MCP 工具,因此不会消耗调用者的上下文。

领域拒绝携带库自身的消息。未数字化的混合流等级、域外的特定升级 PCE 以及格式错误的配置都会以库的语言返回 {"success": false, "error": "..."},因为这些消息说明了已发布的 HCM 数据所涵盖的内容。

这些工具不在默认的 MCP 表面中。 mcp_server_fastapi.py 是 ct 消融臂,它默认宣传的十个工具是已发布实验所针对的表面(参见 tests/test_frozen_surface.py)。设置 HCM_MCP_FULL_COVERAGE=true 可将三个能力工具附加到 MCP 挂载点。没有它,它们仍然可以通过 REST 和 /tools/call 访问。

验证函数

  • validation_validate_design_full - 根据完整规则语料库(300+ 条规则:HCM、AASHTO、MUTCD、HSM、ADA、OpenDRIVE 等)验证设计,包含引用、地形/管辖区门控规则,以及当输入缺失或上下文不明确时的澄清请求。在捆绑的种子语料库上进程内运行——无需数据库。(第 15/12 章工具使用较轻量的语义防火墙网关;这是完整的引擎。)需要 transportations-validator>=0.2.0 + sqlalchemy。

研究函数

  • query_hcm - 查询 HCM 文档数据库

推理函数

X-KG 推理层在知识图谱和经过验证的可执行基座上推理。修复和逆向设计在返回结果之前通过 transportations-library 重新执行每个候选,因此结果是经过证明合规的,而非仅声明。无需数据库。

  • reasoning_propagate_change - 前向链:受变更输入影响的下游参数

  • reasoning_diagnose_failure - 后向链:失败参数的上游原因

  • reasoning_repair_design - 溯因修复:双车道公路(HCM 第 15 章)的最小合规修复

  • reasoning_repair_freeway - 溯因修复:基本高速公路(HCM 第 12 章)的最小合规修复

  • reasoning_reconcile_codes - 对冲突的规范条款进行可废止裁决,并附有论证轨迹

  • reasoning_inverse_design - 目标导向的综合:达到目标 LOS 的可行几何形状

依赖项: 推理函数需要 transportations-validator>=0.2.0 和 transportations-library>=0.1.12(后者用于 reasoning_repair_freeway 使用的 BasicFreeways 绑定)。两者都在 PyPI 上,因此正常的 pip install(或 uv sync)即可解析。

API 端点

访问 API 端点目录以执行分析或查询 HCM 文档。

注意:/docs 的详细 API 端点描述正在建设中,即将可用。

核心端点

  • POST /tools/call - 执行任何已注册的函数

  • POST /tools/list - 列出可用函数并支持过滤

  • GET /mcp/discovery - MCP 能力发现

按方法的 HCM 分析

POST /analysis/hcm/analyze                # {method, config}
POST /analysis/hcm/describe               # {method?} - catalog, or one method's schema + worked example
POST /analysis/hcm/validate               # {method, config} - parse and check, without running

POST /analysis/hcm/<method-with-hyphens>  # method-shaped convenience route, e.g. /analysis/hcm/analyze-roundabout

按方法的路由采用该方法示例案例模式中的 {"config": { ... }}。完整列表请参阅上面的 HCM 分析能力。

第 15 章分析

  • POST /analysis/chapter15/complete - 完整的 HCM 分析

  • POST /analysis/chapter15/segment - 单段分析

研究

  • POST /tools/query-hcm - 查询 HCM 数据库

  • POST /research/search_hcm_by_chapter - 按特定章节搜索 HCM 内容

  • GET /research/get_hcm_section - 获取特定的 HCM 章节内容

  • POST /research/summarize_hcm_content - 总结某个主题的 HCM 内容

推理与验证

为 X-KG 推理层和完整语料库验证提供专用端点(因此也是一等 MCP 工具)。每个端点都从注册表解析其实现,因此表面与 function_registry.yaml 保持同步。

  • POST /reason/propagate-change - 前向链下游影响

  • POST /reason/diagnose-failure - 后向链上游原因

  • POST /reason/repair-design - 最小合规修复(双车道公路,HCM 第 15 章)

  • POST /reason/repair-freeway - 最小合规修复(基本高速公路,HCM 第 12 章)

  • POST /reason/reconcile-codes - 可废止的多管辖区裁决

  • POST /reason/inverse-design - 目标导向的几何综合

  • POST /validate/design-full - 根据完整规则语料库进行验证,包含引用和澄清

工具

  • GET /health - 健康检查

  • GET /registry/info - 注册表信息

  • POST /registry/reload - 重新加载函数注册表

数据模型

公路路段

{
  "passing_type": 0,      # 0=PC, 1=PZ, 2=PL
  "length": 2.0,          # miles
  "grade": 2.0,           # percent
  "spl": 50.0,            # speed limit (mph)
  "volume": 760.0,        # vehicles/hour
  "volume_op": 1500.0,    # opposing volume
  "phf": 0.95,            # peak hour factor
  "phv": 5.0              # percent heavy vehicles
}

公路设施

{
  "segments": [...],      # list of segments
  "lane_width": 12.0,     # feet
  "shoulder_width": 6.0,  # feet
  "apd": 5.0,             # access points/mile
  "pmhvfl": 0.02,         # percent HV in fast lane
  "l_de": 0.0             # effective passing distance
}

添加新的 HCM 章节

1. 创建函数模块

创建 functions/chapter16.py:

def new_analysis_function(data: Dict[str, Any]) -> Dict[str, Any]:
    """Implementation for new analysis."""
    try:
        # Your implementation here
        return {"success": True, "result": "analysis_result"}
    except Exception as e:
        return {"success": False, "error": str(e)}

2. 更新注册表

添加到 functions_registry.yaml:

functions:
  chapter16:
    new_analysis:
      module: "functions.chapter16"
      function: "new_analysis_function"
      description: "New analysis function"
      category: "transportation"
      chapter: 16
      parameters:
        type: "object"
        properties:
          input_param:
            type: "string"
        required: ["input_param"]

3. 重启服务器

注册表将自动加载新函数。

开发

运行测试

注意:测试即将添加。

pytest tests/

验证注册表

注意:尚未使用。

python scripts/validate_registry.py

设置开发数据库

python scripts/import_hcm_docs.py

自定义

自定义分析模型

扩展 core/models.py 中的模型:

class CustomAnalysisInput(BaseModel):
    parameter1: float = Field(description="Custom parameter")
    parameter2: str = Field(description="Another parameter")

自定义函数

  1. 在适当的模块中实现函数

  2. 添加到 functions_registry.yaml

  3. 重启服务器或调用 /registry/reload

支持

此项目为测试版,目前主要用于研究目的。非常感谢任何贡献或反馈!

对于问题和疑问:

  • 在 GitHub 上打开问题

  • 查看 /docs 处的 API 文档

  • 在 /registry/info 处查看函数注册表

  • 使用实用脚本验证设置

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      A high-performance FastAPI server supporting Model Context Protocol (MCP) for seamless integration with Large Language Models, featuring REST, GraphQL, and WebSocket APIs, along with real-time monitoring and vector search capabilities.
      8
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      An enterprise-grade Model Context Protocol server for high-performance web analysis that discovers subpages, provides AI-based page summaries, and extracts structured content for RAG using FastMCP and FastAPI.
      2
      4
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server implementation built with FastAPI that enables AI agent interactions. Provides a structured foundation for building AI-powered applications with proper data validation and modern Python tooling.
      -
    • F
      license
      Not graded
      quality
      D
      maintenance
      A demonstration MCP server built with FastAPI that provides basic mathematical operations and greeting services. Integrates with Gemini CLI to showcase MCP protocol implementation with simple REST endpoints.
      -