mcp-rule-engine

mcp-rule-engine

Captures code modifications via AST analysis, generates reusable rules, and injects them into AI agent context with version audit and token-budgeted rule retrieval.

Category
访问服务器

README

MCP Rule Engine — Cognition Engine & Trust Governance Layer

build coverage MCP License Trademark Policy

A production-grade MCP server that combines a cognition graph engine with a trusted governance layer. Provides intelligent code pattern matching, AST-level constraint validation, and auditable injection approval for AI agents.

<!-- TEMP_BANNER_REMOVE_AFTER_2W -->

📢 Protocol Update: We have adopted Apache 2.0 licensing with a formal trademark policy. Read the announcement → <!-- /TEMP_BANNER -->


The Problem It Solves

AI Agents are powerful but chaotic. They generate code confidently, yet they lack a persistent cognition layer to remember project-specific patterns across sessions, and they lack a governance layer to enforce security boundaries on their own output. Without these, every agent session starts from zero — repeating the same mistakes, ignoring your team's conventions, and producing code that looks plausible but violates project invariants.

This engine fixes that. It gives agents a long-term graph memory of project patterns (what works, what's forbidden, what's idiomatic in this codebase) and a trusted approval workflow so every injection is reviewed, audited, and accountable.


Core Features

  • Cognition Graph Engine — Intent recognition, weighted graph traversal, and AST constraint solving for intelligent code analysis
  • Trust Governance — Three-tier knowledge base with injection approval workflow, TTL-based proposals, and audit logging
  • Universal Connectivity — Stdio (local) and Streamable HTTP (remote) transports with full MCP lifecycle support
  • Agent Hard Constraints — Output schema enforcement with `validationRequired` auto-validation; non-compliant agent responses intercepted
  • Hot Config Updates — Dynamic threshold tuning with expert mode authorization and version chain tracking

Architecture

```mermaid flowchart LR Agent["AI Agent (Cursor / Claude / Cline)"] MCP["MCP Server (stdio / HTTP)"] CV["Constraint Validator"] GT["Graph Traverser"] IA["Injection Approval"] FL["Feedback Loop"] DB[("SQLite / Prisma")]

Agent -->|tools/list → tools/call| MCP
MCP -->|cognition_validate| CV
MCP -->|cognition_query| GT
MCP -->|cognition_approve_injection| IA
MCP -->|cognition_feedback| FL
CV -->|parse + validate| GT
GT -->|weighted BFS| DB
IA -->|TTL proposal| DB
FL -->|update weights| DB
DB -->|graph data| GT

```


Quick Start

Prerequisites

  • Node.js >= 18
  • npm >= 9

Setup

```bash git clone <repo-url> && cd mcp-rule-engine npm install npx prisma db push npm run build ```

Start Server

```bash

Stdio mode (default)

node dist/index.js

HTTP mode

TRANSPORT=http PORT=3000 node dist/index.js ```


MCP Integration

Cursor

Add to `.cursor/mcp.json`:

```json { "mcpServers": { "cognition-engine": { "command": "node", "args": ["dist/index.js"], "env": { "DATABASE_URL": "file:./dev.db" } } } } ```

Claude Desktop

Add to `claude_desktop_config.json`:

```json { "mcpServers": { "cognition-engine": { "command": "node", "args": ["path/to/mcp-rule-engine/dist/index.js"], "env": { "DATABASE_URL": "file:./dev.db" } } } } ```

VS Code (GitHub Copilot Chat / VS Code MCP Extension)

Add to your VS Code settings (User `settings.json` or workspace `.vscode/mcp.json`):

```json { "mcp": { "servers": { "cognition-engine": { "type": "stdio", "command": "node", "args": ["dist/index.js"], "env": { "DATABASE_URL": "file:./dev.db" } } } } } ```

Cline / Roo Code (HTTP)

```json { "mcpServers": { "cognition-engine": { "url": "http://localhost:3000", "transport": "streamable-http" } } } ```


Trust Governance Protocol

Three-Tier Knowledge

Tier Scope Node Type Validation
Global Universal patterns NegativeConstraint = REJECT Hard block
Project Project conventions PositiveConstraint = WARN Soft warning
Reuse Cross-project patterns Intent + Heuristic Weight-based

Injection Proposal State Machine

```mermaid stateDiagram-v2 [] --> PENDING: cognition_query triggers implicit proposal PENDING --> APPROVED: cognition_approve_injection(proposalId, APPROVE) PENDING --> REJECTED: cognition_approve_injection(proposalId, REJECT) PENDING --> OVERRIDDEN: cognition_approve_injection(proposalId, OVERRIDE) PENDING --> EXPIRED: TTL = 5 min elapsed APPROVED --> []: Rules injected into graph REJECTED --> []: Proposal discarded OVERRIDDEN --> []: Force-injected (audit logged) EXPIRED --> [*]: -32602 Proposal Expired + retryable:true ```

Proposals are in-memory with a 5-minute TTL. Concurrent proposals for the same context hash return the existing proposal to prevent conflicts. Expired proposals return `-32602 Proposal Expired` with `retryable: true`.

Constraint Validation Dual-Mode

  • REJECT (Hard Block) — Returned as `-32602` + `ruleId`. Agent must stop.
  • WARN (Soft Warning) — Returned as violation. Agent may continue with user confirmation.

Config Hot Update

Dynamic thresholds (similarity 0.7 / 0.9) are stored as `CognitionNode(type=HEURISTIC)`. Each update creates a new version node with the old node marked `supersededBy`. Requires `expertMode: true`.

Audit & Compliance

All injection decisions, config changes, and validation events are recorded via `MetricEvent` with async non-blocking writes. On database write failure, events fall back to `logs/fallback.log`.


MCP Resources

URI Type Content
`cognition://schema` application/json Cognition graph data model
`cognition://stats` application/json Node/edge counts + approvalRate7d
`cognition://docs` text/markdown Full tool documentation
`cognition://rules-changelog` application/json Versioned rule change log

MCP Tools

Tool Description readOnlyHint
`cognition_query` Query graph by context hash
`cognition_validate` Validate code against AST templates
`cognition_feedback` Provide feedback to refine traversal
`cognition_approve_injection` Approve/reject proposals with TTL
`cognition_update_config` Hot-update thresholds (expert mode)

Testing

```bash

Run all tests (118/118 passing)

npm test

Run specific suite

npx vitest run tests/protocol/ ```


Protocol Compliance

This server conforms to MCP Specification v1.29.0 and supports:

  • [x] initialize / initialized / ping / shutdown lifecycle
  • [x] tools/list + tools/call with JSON Schema input/output
  • [x] resources/list + resources/read with `cognition://` URI scheme
  • [x] StdioServerTransport and StreamableHTTPServerTransport
  • [x] Error codes: -32602 (invalid params), -32603 (internal), -32001 (timeout)
  • [x] Annotations: readOnlyHint, destructiveHint, openWorldHint

Contributing

We welcome contributions from the community! Here's how you can get involved:

  • Report a bug: Open an issue with reproduction steps.
  • Suggest a feature: Start a discussion to gather feedback before implementation.
  • Submit a PR: Follow the guidelines in CONTRIBUTING.md.

For major changes, please open an issue first to discuss what you would like to change.

🟢 New to the project?

Looking for a place to start? Check out our Good First Issues — they're specifically scoped for first-time contributors and include detailed context, acceptance criteria, and file references.


License

Copyright (c) 2026 熊高锐

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Full license text: LICENSE.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选