Skip to main content
Glama

World Model MCP

编码代理的事件时钟。一个为你的代码库构建时序知识图谱的 MCP 服务器——它能从 Claude Code 会话中捕获决策轨迹,将其与测试结果关联,学习轨迹,并在编辑边界强制执行约束。

状态:Alpha (v0.6.0) -- 编码代理的事件时钟。包含 22 个 MCP 工具、186 个测试、PreToolUse 强制执行、决策轨迹和预测层。欢迎贡献。

PyPI Downloads License: MIT Python 3.11+


功能概述

World Model MCP 为你的代码库创建一个时序知识图谱,通过学习每一次 Claude Code 会话来实现:

  • 防止幻觉 - 在使用前根据已知实体验证 API/函数引用

  • 杜绝重复错误 - 从修正中学习约束,并在未来的会话中应用它们

  • 减少回归 - 跟踪 Bug 修复,并在变更触及关键区域时发出警告

可以将其视为赋予 Claude 项目的长期记忆


快速开始

安装

# 1. Install the package
pip install world-model-mcp

# 2. Setup in your project (auto-seeds the knowledge graph from existing code)
cd /path/to/your/project
python -m world_model_server.cli setup

# 3. Restart Claude Code
# Done! The world model is pre-populated and active

你也可以随时重新播种或手动播种:

# Seed from existing codebase
world-model seed

# Re-seed with force (re-processes already seeded files)
world-model seed --force

安装内容

your-project/
├── .mcp.json                    # MCP server configuration
├── .claude/
│   ├── settings.json           # Hook configuration
│   ├── hooks/                  # Compiled TypeScript hooks
│   └── world-model/            # SQLite databases (~155 KB)

特性

1. 防止幻觉

之前:

// Claude invents an API that doesn't exist
const user = await User.findByEmail(email); // This method doesn't exist

之后:

// Claude checks the world model first
const user = await User.findOne({ email }); // Verified to exist

目标:通过针对知识图谱进行验证,减少不存在的 API 引用

2. 从修正中学习

会话 1:用户修正 Claude

// Claude writes:
console.log('debug info');

// User corrects to:
logger.debug('debug info');

// World model learns: "Use logger.debug() not console.log()"

会话 2:Claude 使用已学习的模式

// Claude automatically writes:
logger.debug('debug info'); // No correction needed

目标:已学习的模式在会话间持久存在,并防止重复违规

3. 防止回归

// Week 1: Bug fixed (null check added)
if (user && user.email) { ... }

// Week 2: Refactoring
// World model warns: "This line preserves a critical bug fix"
// Claude preserves the null check

// Result: Bug not re-introduced

目标:在代码执行前检测潜在的回归


工作原理

架构

┌──────────────────────────────────────────────────────────┐
│ Claude Code + Hooks                                      │
│ Captures: file edits, tool calls, user corrections       │
└──────────────────────────────────────────────────────────┘
                         |
                         v
┌──────────────────────────────────────────────────────────┐
│ MCP Server (Python)                                      │
│ - 22 MCP tools for querying/recording/predicting          │
│ - LLM-powered entity extraction (Claude Haiku)           │
│ - External linter integration (ESLint, Pylint, Ruff)     │
└──────────────────────────────────────────────────────────┘
                         |
                         v
┌──────────────────────────────────────────────────────────┐
│ Knowledge Graph (SQLite + FTS5)                          │
│ - entities.db: APIs, functions, classes                  │
│ - facts.db: Temporal assertions with evidence            │
│ - relationships.db: Entity dependency graph              │
│ - constraints.db: Learned rules from corrections         │
│ - sessions.db: Session history and outcomes              │
│ - events.db: Activity log with reasoning chains          │
└──────────────────────────────────────────────────────────┘

核心概念

  1. 时序事实:每个事实都有 validAtinvalidAt 时间戳

    • “函数 X 在 2024-01-15 到 2024-03-20 期间存在”

    • 查询:“3 月 1 日时哪些是真实的?”

  2. 证据链:每个断言都可以追溯到源头

    • 事实 -> 会话 -> 事件 -> 源代码位置

  3. 约束学习:从用户修正中进行模式识别

    • 自动规则类型推断(Linting、架构、测试)

    • 严重性检测(错误、警告、信息)

    • 为未来参考生成示例

  4. 双重验证:结合两种验证源

    • 世界模型约束(从用户处学习)

    • 外部 Linter(ESLint、Pylint、Ruff)


MCP 工具

提供给 Claude Code 的 22 个 MCP 工具:

1. query_fact

在使用前检查 API/函数是否存在

result = query_fact(
    query="Does User.findByEmail exist?",
    entity_type="function"
)
# Returns: {exists: bool, confidence: float, facts: [...]}

2. record_event

捕获带有推理链的开发活动

record_event(
    event_type="file_edit",
    file_path="src/api/auth.ts",
    reasoning="Added JWT authentication middleware"
)

3. validate_change

针对约束和 Linter 进行执行前验证

result = validate_change(
    file_path="src/api/auth.ts",
    proposed_content="..."
)
# Returns: {safe: bool, violations: [...], suggestions: [...]}

4. get_constraints

检索文件的项目特定规则

constraints = get_constraints(
    file_path="src/**/*.ts",
    constraint_types=["linting", "architecture"]
)

5. record_correction

从用户编辑中学习(高优先级)

record_correction(
    claude_action={...},
    user_correction={...},
    reasoning="Use logger.debug instead of console.log"
)

6. get_related_bugs

回归风险评估

result = get_related_bugs(
    file_path="src/api/auth.ts",
    change_description="refactoring authentication logic"
)
# Returns: {bugs: [...], risk_score: float, critical_regions: [...]}

7. seed_project

扫描代码库并使用实体和关系填充知识图谱

result = seed_project(
    project_dir=".",
    force=False
)
# Returns: {files_seeded: int, entities_created: int, relationships_created: int}

8. ingest_pr_reviews

拉取 GitHub PR 审查评论并将团队反馈转换为约束

result = ingest_pr_reviews(
    repo="owner/repo",  # Auto-detected from git remote if omitted
    count=10
)
# Returns: {prs_scanned: int, constraints_created: int, constraints_updated: int}

文档


测试

# Run tests
pytest

# With coverage
pytest --cov=world_model_server --cov-report=html

186 个测试,涵盖知识图谱 CRUD、FTS5 搜索、约束管理、Bug 跟踪、自动播种、PR 审查摄取、决策轨迹、结果关联、轨迹学习、预测层、内存健康、矛盾检测、转录指针、项目标识和 PreToolUse 强制执行。详情请参阅 tests/


配置

环境变量

# Database location (default: ./.claude/world-model/)
export WORLD_MODEL_DB_PATH="/custom/path"

# Anthropic API key (optional - enables LLM extraction)
# IMPORTANT: Never commit this! Use .env file (see .env.example)
export ANTHROPIC_API_KEY="your-api-key-here"

# Model selection
export WORLD_MODEL_EXTRACTION_MODEL="claude-3-haiku-20240307"  # Fast
export WORLD_MODEL_REASONING_MODEL="claude-3-5-sonnet-20241022"  # Accurate

# Debug mode
export WORLD_MODEL_DEBUG=1

注意:在项目根目录创建一个 .env 文件(参见 .env.example)——它会被 git 自动忽略。

自定义钩子

编辑 .claude/settings.json 以自定义哪些工具触发世界模型钩子:

{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write|Bash",
      "hooks": [...]
    }]
  }
}

语言支持

当前支持

  • TypeScript / JavaScript

  • Python

即将推出

  • Go, Rust, Java, C++

可扩展架构:易于添加新的语言解析器(参见 CONTRIBUTING.md


隐私与安全

  • 本地优先:所有数据保留在你的机器上

  • 无遥测:零跟踪或外部数据传输

  • 可选 LLM:无需 API 密钥即可工作(使用正则表达式作为回退)

  • 加密存储:SQLite 数据库是本地文件(加密你的磁盘以确保安全)

API 密钥使用(仅在你提供 ANTHROPIC_API_KEY 时):

  • 从代码变更中提取实体

  • 从修正中推断约束

  • 绝不发送:凭据、密钥、PII

安全最佳实践

  • 永远不要提交 .env 文件

  • 使用 .env.example 作为模板

  • 仅在环境变量或 .env 文件中存储 API 密钥

  • .gitignore 会自动排除敏感文件


路线图

v0.2.x

  • [x] 自动播种:设置时从现有代码库填充知识图谱

  • [x] PR 审查智能:将 GitHub 审查评论摄取为约束

  • [x] 关系跟踪:实体间的导入和依赖图

  • [x] 多语言支持:Python, TypeScript/JavaScript, Solidity, Go, Rust

  • [x] 用于知识图谱查找的 CLI 查询命令

  • [x] 40 个测试,8 个 MCP 工具

v0.3.0

  • [x] 模块级匹配:按模块名称查询可找到文件及其内容

  • [x] 增量重新播种:仅重新处理自上次播种以来更改的文件

  • [x] 模糊实体匹配:针对拼写错误和缩写的近似名称搜索

  • [x] 查询缓存:带有 TTL 的内存缓存,用于重复查找

  • [x] Java 支持:完整的多语言覆盖

  • [x] 真实项目上的 MCP 服务器管道验证

v0.4.0

  • [x] 结果关联:将测试失败与带有事实的代码变更关联

  • [x] 轨迹学习:跨会话跟踪协同编辑模式

  • [x] 决策轨迹捕获:代理建议和人工修正的结构化日志

  • [x] 带有项目注册表的跨项目实体搜索

  • [x] 5 个新 MCP 工具(总计 13 个),104 个测试

v0.5.0

  • [x] 回归预测、“假设”模拟、测试失败预测

  • [x] 多项目知识迁移、内存健康、事实 TTL/衰减

  • [x] get_context_for_action 编辑前捆绑、约束违规跟踪、find_contradictions

  • [x] 20 个 MCP 工具,151 个测试

v0.6.0 (当前) — 强制执行、来源、标识

  • [x] PreToolUse 约束强制执行钩子:在编辑边界拒绝严重违规

  • [x] 索引转录指针:将任何事实还原回源对话

  • [x] 项目标识解耦:跨目录重命名的稳定 UUID

  • [x] 事实和约束的内容哈希去重

  • [x] 从知识图谱自动生成 CLAUDE.md

  • [x] 用于 Anthropic SDK 集成的 BetaAbstractMemoryTool 子类

  • [x] 用于 Claude Desktop 的桌面扩展 (.mcpb) 打包

  • [x] 22 个 MCP 工具,13 个 CLI 子命令,186 个测试

v0.7.0 (下一步)

  • [ ] 通过 tree-sitter 进行基于 AST 的提取

  • [ ] 后台事实衰减调度程序(可选)

  • [ ] 带有自动解决功能的置信度加权矛盾检测

  • [ ] 组织范围的约束联合


贡献

欢迎贡献。请参阅 CONTRIBUTING.md 了解:

  • 开发设置

  • 编码标准

  • 添加语言支持

  • 编写测试

  • 提交 PR

需要帮助的领域

  • 语言解析器 (Go, Rust, Java, C++)

  • 性能优化

  • 文档改进

  • 真实世界测试反馈


统计

项目规模

  • ~4,800 行代码

  • 13 个 Python 模块

  • 3 个 TypeScript 钩子实现

存储效率

  • 空数据库:~155 KB

  • 每个实体:~500 字节

  • 每个事实:~800 字节


许可证

MIT 许可证 - 可免费用于商业和个人用途


支持

A
license - permissive license
-
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
8wRelease cycle
3Releases (12mo)

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/SaravananJaichandar/world-model-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server