Skip to main content
Glama
mcp-rule-engine

mcp-rule-engine

by sole03

GovernFlow

AI-native code governance pipeline. Assemble, don't build.

GovernFlow 将 AI Agent 的代码治理从"自研轮子"重构为"组装业界工具链"的四层流水线。不建新平台,嵌入现有工作流。


环境依赖

依赖

版本要求

说明

Node.js

≥ 22

运行时

npm

≥ 10

包管理

SQLite

3 (内置)

本地数据库 (零配置)

Node.js 22 是硬性要求(使用了 --experimental 特性的 tree-sitter wasm 绑定)。SQLite 通过 better-sqlite3 内嵌,无需单独安装。


Related MCP server: mcp-code-context

快速部署运行

方式一:npm 安装(推荐)

npm install governflow
# 或指定版本
npm install governflow@1.0.0-alpha.9

方式二:源码构建

# 1. 拉取仓库
git clone https://github.com/sole03/governflow.git
cd governflow

# 2. 安装依赖 (自动编译 TypeScript → dist/ + 生成 Prisma Client)
npm install

# 3. 配置环境变量 (可选,默认使用 SQLite)
#    set DATABASE_URL=file:./custom.db   (Windows)

# 4. 运行测试 (验证环境正确)
npm test                    # 291 tests, 37 files

# 5. 启动
governflow                  # MCP stdio 模式 (供 Cursor/Claude Desktop 等客户端使用)
# 或
npm run start:http          # HTTP REST API 模式

配置说明

环境变量

默认值

说明

DATABASE_URL

file:./mcp-cognition.db

SQLite 数据库路径

LOG_LEVEL

info

日志级别 (trace/debug/info/warn/error)

无需 .env 文件即可运行。所有配置均有合理默认值。


项目目录结构

governflow/
├── packages/
│   ├── core/                    # governflow-core — 协议无关内核
│   │   └── src/
│   │       ├── perception/      # 感知层: MerlionBridge + ShapleyAttributor
│   │       ├── proposal/        # 提案层: RegoCompiler + StructuredGenerator + PromptPipeline
│   │       ├── verification/    # 验证层: PropertyTests + ShadowVerifier
│   │       ├── delivery/        # 决策层: GitOpsEngine + CanaryController
│   │       ├── constraints/     # 约束 DSL 编译器 + 模板库 + 运行时
│   │       ├── sandbox/         # COW 沙箱 + 自愈循环 + 安全阀 + 健康门控
│   │       ├── dashboard/       # 指标收集器 + DashboardSnapshot 类型
│   │       ├── cognition/       # 认知图引擎核心
│   │       ├── events/          # 事件总线 + 领域事件
│   │       ├── audit/           # 满意度追踪 (开发者体验兜底)
│   │       ├── cli/             # CLI 入口
│   │       └── di/              # 依赖注入容器
│   └── dashboard/               # governflow-dashboard — 可视化仪表盘
├── src/                         # MCP Server 传输层 (stdio + HTTP)
│   ├── transport/               # MCP 工具处理器 + HTTP 服务
│   ├── governance/              # 策略引擎 + 规则免疫 + 审批工作流 + 影子服务
│   ├── core/                    # AST 约束求解器 + 认知图遍历器 + 意图识别
│   ├── data/                    # Prisma Repository + 向量存储 + LRU 缓存
│   └── adapters/                # Zod Schema 校验 + Embedding 适配器
├── tests/                       # 测试 (37 files, 291 tests)
├── prisma/                      # 数据库 Schema + 迁移
├── scripts/                     # License 检查 + 影子回放 CLI + Pack 脚本
├── benchmarks/                  # 性能基准
└── .github/workflows/           # CI 配置 (Rule Verification + License Check)

功能说明

四层流水线

层

核心模块

功能

感知层

perception/

Z-score 动态基线异常检测 + EMA 自适应 + 季节性分解 + Shapley 多维根因归因

提案层

proposal/

JSON DSL → OPA Rego 编译 + Zod 约束 LLM 结构化输出 + Few-shot 自动编译

验证层

verification/

属性测试自动证伪 + 影子日志回放 + CI 自动验证 PR

决策层

delivery/

DashboardSnapshot → PR Markdown (GitOps) + 5%→100% 金丝雀渐进交付

数据模型

模型

用途

Rule

规则定义 (含 hitCount/falsePositiveCount/adoptedCount 效能追踪)

PolicyVariant

A/B 策略变体对比

ShadowLog

影子模式运行日志 (新规则 7 天前置观察)

CognitionNode / CognitionEdge

认知图拓扑

AstTemplate

AST 级约束模板

Proposal / ApprovalRequest

注入审批工作流

MCP 工具 (20 tools)

分类

工具

用途

Diff

analyze_workspace

Git diff 分析 + 意图识别 + 语言检测 (19 种语言)

Diff

capture_diff

单文件差异捕获 → AST/Regex 差异归一化

Rule

list_rules

分页查询全量规则 + 按语言/置信度过滤

Rule

query_rules

按文件路径 + 语言匹配适用规则

Rule

confirm_rule

审批(adopt)/拒绝(reject)/跳过(skip) 规则

Rule

resolve_conflict

解决规则冲突 (keep/skip/merge 三种策略)

Cognition

cognition_query

认知图上下文查询 (最大深度 3 层 BFS)

Cognition

cognition_validate

代码 vs 约束节点一致性校验

Cognition

cognition_feedback

提交 ACCEPTED/REJECTED 反馈回流

Cognition

cognition_update_config

认知引擎配置热更新 (需 expertMode)

Cognition

cognition_approve_injection

审批/拒绝注入提案

Governance

governance_pause_arbitrator

暂停自动仲裁 (1-1440 分钟)

Governance

governance_rollback_arbitration

回滚指定时间后的仲裁结果

Workflow

workflow_submit

提交多评审人审批工作流

Workflow

workflow_vote

审批投票 (APPROVE/REJECT)

Workflow

workflow_status

查询审批状态

Workflow

workflow_escalate

审批超时升级

Immune

immune_cycle

规则免疫周期执行

Immune

immune_stats

免疫统计 (抑制/恢复/反馈)

传输协议: stdio 和 HTTP 均覆盖,HTTP 额外包含 Workflow + Immune 工具。


技术栈

类别

技术

语言

TypeScript 5.6

运行时

Node.js 22

数据库

SQLite (better-sqlite3)

ORM

Prisma 5.22

测试

Vitest 2.1

AST

tree-sitter (JS/Python/TS)

Embedding

@xenova/transformers (ONNX 本地推理)

Schema 校验

Zod 4

日志

Pino

协议

MCP (Model Context Protocol)

内核包

governflow-core 零 MCP 依赖,可独立发布为 npm 包:

npm install governflow-core
import { MerlionBridge, RegoCompiler, CanaryController } from "governflow-core";

文档

完整架构设计与开发文档见 GitHub Wiki.


常见问题

npm install 报错 better-sqlite3 编译失败

需要系统安装 C++ 编译工具链:

  • Windows: npm install --global windows-build-tools 或安装 Visual Studio Build Tools

  • Mac: xcode-select --install

  • Linux: sudo apt install build-essential python3

prisma db push 报错 Environment variable not found: DATABASE_URL

设置环境变量或使用默认值:

export DATABASE_URL="file:./mcp-cognition.db"   # Linux/Mac
set DATABASE_URL=file:./mcp-cognition.db        # Windows cmd
$env:DATABASE_URL="file:./mcp-cognition.db"     # PowerShell

测试报错 database is locked

SQLite 并发文件锁的已知限制。重跑即可:

npm test

如果频繁出现,尝试 npx vitest run --no-cache --pool=forks。

Node.js 版本过低

MCP SDK 和 tree-sitter wasm 绑定需要 Node.js ≥ 22。检查版本:

node -v

如果低于 22,使用 nvm/fnm 升级。


心法

不要构建系统,要构建流水线。

让异常检测成为监控平台的插件,而非独立服务。 让规则生成成为 CI 的一个 Step,而非后台黑盒。 让人机协同成为 Code Review 的自然延伸,而非额外负担。


Changelog

v1.0.0-alpha.9 (2026-06-21)

  • 🔴 认知图写入修复: capture_diff / analyze_workspace 所有 upsertCognitionClosure / createNodeWithEdges 加 await,解决 fire-and-forget 导致节点丢失

  • 🔴 认知图错误可见: 写入错误不再静默吞掉,改为写入 warnings 字段

  • 🔴 认知图查询扩展: cognition_query 支持 5 种检索模式(nodeType / filePath / language / contextHash / semanticHash),不再死锁在单一 hash

  • 🟡 CognitionRepository: 新增 findOrCreateNode(P2002 时返回已有节点)+ findNodesByPayloadField / findNodesByType 多维检索

  • 🟡 Schema 放宽: CognitionQuerySchema 放宽 required 约束,支持多种可选检索条件

  • 🟡 空 pattern 防御: rule-matcher / rule-generator / capture-diff / rule-repo 四层拦截空 pattern 规则

  • 📄 文档: 新增 Agent 工作流指南(knowledge injection → rule coding → code audit)

  • 📄 文档: 新增架构设计文档(enhancement-plan / gaps)

v1.0.0-alpha.8 (2026-06-21)

  • 🧠 Prisma Client 重新生成: 同步 ApprovalRequest.version 字段

  • 🧠 build 修复: approval-workflow.ts version 类型错误修复

v1.0.0-alpha.7 (2026-06-18)

  • 🛡 冲突全景图修复①: Rule 模型新增 @@unique([type, language, pattern, suggestion]) — 数据库级拦截完全重复规则

  • 🛡 冲突全景图修复②: rule-repo.ts create() 前置 findFirst 存在检查(belt-and-suspenders)

  • 🛡 冲突全景图修复③: ApprovalRequest 新增 version 字段 + castVote 乐观锁 P2025 重试(最多 3 次),防止并发投票丢失

  • 🛡 冲突全景图修复④: capture-diff PATTERN 节点 TOCTOU 硬化(re-fetch on duplicate key)

  • 🛠 CognitionRepository: 新增 createEdge() 单边创建方法

  • 🛠 Schema 错误消息: Zod enum 校验失败时显式列出合法值

  • 🛠 Schema 别名: cognition_query 新增 semanticHash 参数

  • 🛠 validateInput: Zod Required 错误翻译为 field-aware 消息

  • 🧹 清理: prisma/ 下 59 个历史脏数据库文件

v1.0.0-alpha.6 (2026-06-18)

  • 🧠 认知图谱闭环: capture_diff 自动创建 INTENT 节点(intent-recognizer 分类 REFACTOR/BUGFIX/BOILERPLATE)+ CAUSES 边连接 PATTERN

  • 🧠 认知图谱完善: analyze_workspace 为每个文件 diff 持久化 PATTERN 节点

  • 🧠 认知图谱完善: confirm_rule accept 自动创建 CONSTRAINT 节点(架构约束)

  • 🛠 CognitionRepository: 新增 createEdge() 单边创建方法

  • 🛠 Schema 错误消息: Zod enum 校验失败时显式列出合法值(accept/reject/edit/skip)

  • 🛠 Schema 别名: cognition_query 新增 semanticHash 参数(contextHash 别名)

  • 🛠 validateInput: Zod Required 错误翻译为 field-aware 消息(如 filePath is required)

  • 🧹 清理: prisma/ 下 59 个历史脏数据库文件(dev-1.db ~ dev-37.db)

v1.0.0-alpha.5 (2026-06-18)

  • 🐛 CI 修复: bench workflow DATABASE_URL 路径偏差(prisma/prisma/ -> prisma/)+ Node 22

  • 🐛 pack 修复: VM EOF bug — 新增 pack-from-subdir.mjs 绕过 npm tar 路径问题

  • 🐛 License: 修复 sentinel 注释导致 CI license:check 失败

  • 📄 文档: README 精简安装步骤(auto prepare + Prisma generate)

v1.0.0-alpha.4 (2026-06-18)

  • 🛠 工程: 新增 .env.example 配置模板,覆盖 DATABASE_URL / LOG_LEVEL

  • 🛠 工程: 清理 prisma/ 下 37 个 CI/测试残留 .db 文件,加入 .gitignore 全局匹配

  • 🛠 测试: 修复 cognition-repository 性能测试偶发超时(timeout 5s → 15s + semanticHash 去重)

  • 🛠 文档: 修正 README 全文 DATABASE_URL 默认值与代码实际值不一致(dev.db → mcp-cognition.db)

  • 🛠 文档: 快速开始新增 .env.example 引导,替换硬编码路径示例

v1.0.0-alpha.3 (2026-06-18)

  • 🔴 修复: HTTP transport 每次请求重新创建 transport 导致崩溃 — 改为启动时连接一次

  • 🔴 修复: detectLang 缺失 Java/Vue/XML/YML/YAML 等 5 种语言覆盖率

  • 🔴 修复: CaptureDiffSchema.originalContent 从 .min(1) 放宽为 .optional().default(""),新文件不再被拒绝

  • 🟡 修复: HTTP transport 补齐 governance_pause_arbitrator / governance_rollback_arbitration 工具注册

  • 🟡 修复: cognition_update_config TOOLS schema 补齐 expertMode 字段

  • 📦 首次发布 npm 包: npm install governflow@1.0.0-alpha.7

v1.0.0-alpha.2 (2026-06-17)

  • 20 MCP 工具完整实现 (Diff/Rule/Cognition/Governance/Workflow/Immune 六分类)

  • 认知图引擎 (CognitionNode + CognitionEdge + BFS 遍历)

  • AST 约束求解器 + 意图识别器

  • 策略引擎 + 规则免疫 + 审批工作流 + 影子服务

  • Streamable HTTP + stdio 双传输协议

  • Prisma + SQLite 数据持久层

License

Apache-2.0 © 2026 熊高锐

Available Tools

28 tools
analyze_projectC

Scan a project directory to extract file stats, detect coding conventions, and batch-create cognition nodes for governance initialization

Inputs: projectPath (required), deepScan, maxFiles, projectId, +3 more.

analyze_workspaceC

Analyze a git workspace diff for rule violations

Inputs: baseCommit (required), paths, taskId, headCommit.

capture_diffC

Capture and analyze a code diff for rule violations

Inputs: filePath (required), language (required), modifiedContent (required), originalContent (required), +1 more.

cognition_approve_injectionC

Approve, reject, or override a pending injection proposal

Inputs: decision (required), proposalId (required).

cognition_feedbackC

Submit feedback to adjust edge weights

Inputs: nodeId (required), outcome (required), edgeId, comment.

cognition_queryC

Query the cognition graph from a context hash

Inputs: contextHash (required), maxDepth, intentHint.

cognition_update_configC

Update server configuration

Inputs: data, mode.

cognition_validateC

Validate code content against an AST template

Inputs: nodeId (required), targetFileContent (required).

confirm_ruleC

Accept, reject, edit, or skip a suggested rule

Inputs: action (required), ruleId (required), editedPattern, editedSuggestion.

generate_rules_from_cognitionC

Explicitly learn a governance rule from a (language, pattern, suggestion) triple, building the cognition closure (PATTERN→INTENT→CONSTRAINT) and a pending shadow Rule

Inputs: pattern (required), language (required), suggestion (required), intent, +4 more.

governance_pause_arbitratorC

Pause the automatic constraint arbitrator for N minutes

Inputs: minutes (required).

governance_rollback_arbitrationC

Rollback auto-resolved conflicts since an ISO datetime

Inputs: since (required).

list_rulesC

List rules with optional filters

Inputs: limit, scope, offset, status, +2 more.

plugin_listA

List all loaded plugins with status and registered extensions

Inputs: no named parameters.

plugin_loadA

Load a GovernFlow plugin from an NPM package name or local file path

Inputs: source (required), config.

plugin_unloadB

Unload a loaded plugin by plugin name or instance ID

Inputs: pluginName (required).

query_rulesC

Query rules by language and file path

Inputs: filePath (required), language (required), tags, maxRules, +3 more.

resolve_conflictD

Resolve a rule conflict

Inputs: conflictId (required), resolution (required), batchAllSession.

session_contextC

Set or get a shared context value within a session

Inputs: key (required), action (required), sessionId (required), value.

session_createC

Create a new collaborative session for multi-turn governance workflows

Inputs: name (required), creatorName (required), ttlMs, projectId, +1 more.

session_joinC

Join an existing collaborative session

Inputs: sessionId (required), participantName (required), role.

session_leaveC

Leave a collaborative session

Inputs: sessionId (required), participantName (required).

session_listA

List all active sessions, optionally filtered by project

Inputs: projectId.

session_statusC

Get session details, participants, context, and optionally tool call history

Inputs: sessionId (required), historyLimit, includeHistory.

webhook_listA

List all registered webhooks and delivery statistics

Inputs: no named parameters.

webhook_registerB

Register a webhook URL to receive governance events (rule created, conflict resolved, etc.)

Inputs: url (required), events (required), secret, projectId.

webhook_testB

Send a test ping to a registered webhook to verify connectivity

Inputs: webhookId (required).

webhook_unregisterA

Remove a registered webhook by ID

Inputs: webhookId (required).

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    C2.8/5.0

    Scored across 28 tools

    Disambiguation4/5

    Most tools have distinct purposes (e.g., session, webhook, plugin groups), but 'capture_diff' and 'analyze_workspace' both analyze diffs for rule violations, and 'query_rules' vs 'list_rules' overlap in listing rules. This causes minor ambiguity.

    Naming Consistency5/5

    All tools follow a consistent verb_noun pattern using snake_case, with domain prefixes (cognition_, governance_) applied uniformly. No mixed conventions or irregularities.

    Tool Count3/5

    28 tools is slightly above the typical well-scoped range (3-15). The broad domain (rule management, cognition, sessions, webhooks, plugins) justifies the count, but it feels heavy for a single server.

    Completeness3/5

    Core rule lifecycle (create via generate, confirm/edit, list, query, resolve conflicts) is covered, but a 'delete_rule' tool is missing. Session, webhook, and plugin management appear complete, leaving minor gaps.

    Maintenance

    ActivityInactive
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      Provides AI agents with queryable, version-controlled project rules and coding standards. Enables validation, rule-based guidance, and task summaries to keep AI work aligned with your project's conventions without repeating context.
      2
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      Enables LLMs to efficiently read, write, and refactor code using precise AST-based operations, reducing token usage and context window waste.
      25
      238 npm
      3
      MIT