Skip to main content
Glama
rajendarmuddasani

graph-mcp-java-gen

graph-mcp-java-gen

CI Python Evidence License MCP Neo4j

基于图(Graph)的 MCP 服务器,可将自然语言请求转换为经过验证、可编译的 Java 测试方法——无幻觉导入、无无根据符号、无静默失败。

自然语言或结构化请求进入官方 Model Context Protocol (MCP) stdio 服务器。版本化图目录(Neo4j 或 JSON fixture)提供生成器唯一可引用的符号。多层验证器在返回任何源代码之前检查语法、框架契约、接地性和禁用 API 规则。两个可选的 LLM 代理——意图规范化器和生成后审查器——将流水线扩展到自由格式输入,同时不损害确定性安全边界。


架构

%%{init: {"theme": "base", "themeVariables": {"primaryColor": "#1e3a5f", "primaryTextColor": "#ffffff", "primaryBorderColor": "#0d2137", "lineColor": "#4a9eca", "secondaryColor": "#2d6a4f", "tertiaryColor": "#7b2d8b"}}}%%
flowchart TD
    classDef input    fill:#7b2d8b,stroke:#4a1a54,color:#fff,font-size:13px
    classDef mcp      fill:#e07b00,stroke:#9a5700,color:#fff,font-size:13px
    classDef agent    fill:#1a6b8a,stroke:#0d3f52,color:#fff,font-size:13px
    classDef core     fill:#2d6a4f,stroke:#1b4332,color:#fff,font-size:13px
    classDef graph    fill:#1e3a5f,stroke:#0d1f3c,color:#fff,font-size:13px
    classDef validate fill:#4a6741,stroke:#2d4026,color:#fff,font-size:13px
    classDef ok       fill:#155724,stroke:#0a3015,color:#fff,font-size:13px
    classDef reject   fill:#721c24,stroke:#3d0a0e,color:#fff,font-size:13px

    NL["🌎 Free-form NL\n(generate_java_test_nlp)"]:::input
    SF["📄 Structured fields\n(generate_java_test)"]:::input
    TX["💬 Intent text\n(generate_java_test_from_intent)"]:::input

    MCP["🔌 FastMCP stdio Server\n7 tools · zero raw Cypher"]:::mcp

    A1["🤖 LLMIntentParser\nAgent 1 · gpt-4o-mini\nfield extraction"]:::agent
    INT["✅ GenerationIntent\nclass · package · module\nconfig · version"]:::core
    GDB["📊 Graph Catalog\nNeo4j 5.26 / JSON fixture\n8 symbols · 12 methods"]:::graph
    GEN["⚙️ Template Generator\ndeterministic render"]:::core
    VAL["🛡️ JavaValidator\nTree-sitter AST\ncontract · grounding\nsource-safety"]:::validate
    A2["🤖 ReviewAgent\nAgent 2 · gpt-4o-mini\n6-item checklist"]:::agent

    OK["✅ Accepted Java\nsource + citations\n+ review verdict"]:::ok
    REJ["❌ Typed Rejection\nerror code + message\nno source returned"]:::reject

    NL --> MCP
    SF --> MCP
    TX --> MCP
    MCP -->|"NLP path"| A1
    MCP -->|"direct path"| INT
    A1 -->|"extracted fields"| INT
    INT -->|"invalid"| REJ
    INT -->|"valid"| GDB
    GDB -->|"cited symbols"| GEN
    GEN --> VAL
    VAL -->|"any gate fails"| REJ
    VAL -->|"all gates pass"| A2
    A2 -->|"issues found"| REJ
    A2 -->|"approved"| OK

多代理流水线

%%{init: {"theme": "base", "themeVariables": {"actorBkg": "#1e3a5f", "actorTextColor": "#ffffff", "actorBorderColor": "#4a9eca", "activationBkgColor": "#2d6a4f", "activationBorderColor": "#155724", "noteBkgColor": "#fff8e1", "noteTextColor": "#333", "signalColor": "#4a9eca", "signalTextColor": "#1e3a5f"}}}%%
sequenceDiagram
    autonumber
    actor User
    participant MCP as FastMCP Server
    participant A1  as LLMIntentParser<br/>(Agent 1)
    participant GDB as Graph Catalog<br/>(Neo4j / Fixture)
    participant GEN as Generator +<br/>JavaValidator
    participant A2  as ReviewAgent<br/>(Agent 2)

    User->>MCP: generate_java_test_nlp(free-form NL)
    MCP->>A1: extract intent fields
    Note over A1: gpt-4o-mini · temp=0<br/>strict JSON schema
    A1-->>MCP: {class, package, module, config, version}
    MCP->>GDB: get versioned symbols
    GDB-->>MCP: 7 cited GraphSymbol objects
    MCP->>GEN: render Java + validate
    Note over GEN: Tree-sitter AST<br/>contract · grounding · safety
    GEN-->>MCP: validated Java source
    MCP->>A2: review(source, class, package)
    Note over A2: gpt-4o-mini · temp=0<br/>6-item checklist
    A2-->>MCP: {approved, checklist, issues}
    MCP-->>User: {status, source, citations, review}

证据仪表板

所有测量均使用独立生成的 CC0 许可合成 fixture。 结果来自在保留的确认分割上接受的 strict_graph_v2 策略。

表面

结果

工件

基准规模

96 个 CC0 意图 — 32 开发 / 32 验证 / 32 确认

task_evaluation.json

确认任务成功率

32 / 32 有界任务

evaluation_trace.json

生成源代码验证

24 / 24 受支持意图 — 语法 + 契约 + 接地性 + 安全性

task_evaluation.json

安全对抗性拒绝

8 / 8 — 零误接受

task_evaluation.json

引用精确度

100% — 仅导入图引用的符号

task_evaluation.json

必需符号召回率

100% — 每个必需符号均存在

task_evaluation.json

实时 Neo4j 集成

Neo4j 5.26.29 — 8 个符号,12 个方法已物化

neo4j_integration.json

官方 MCP 基准

120 / 120 预期结果 — 零协议错误

mcp_benchmark.json

MCP 热延迟(p50 / p95 / p99)

29.13 / 48.61 / 54.23 ms 并发 1

mcp_benchmark.json

Java 编译

8 / 8 类文件 通过 Eclipse ECJ 3.21

java_compile.json

外部模型调用(确定性路径)

0 次调用 · $0.00

mcp_benchmark.json

延迟数据为单进程本地 Windows 测量值,并非生产 SLO。


策略选择

评估了四种生成策略。选择目标在打开确认分割之前已声明:在通过所有安全门的候选中最大化验证任务成功率。确认仅对所选候选打开一次。

%%{init: {"theme": "base", "themeVariables": {"quadrant1Fill": "#155724", "quadrant2Fill": "#856404", "quadrant3Fill": "#721c24", "quadrant4Fill": "#856404"}}}%%
xychart-beta
    title "Validation: task success vs safe-rejection recall (%)"
    x-axis ["no_graph_v0", "lenient_repair_v1", "strict_graph_v2 ✓", "wide_context_v3"]
    y-axis "Task success (%)" 0 --> 105
    bar  [21.9, 75.0, 100.0, 96.9]
    line [87.5,  0.0, 100.0, 87.5]

候选

任务成功率

生成有效

安全拒绝

引用精确度

决策

no_graph_v0

21.9%

0%

87.5%

0%

拒绝 — 无接地性

lenient_repair_v1

75.0%

100%

0%

100%

拒绝 — 8 个误接受

strict_graph_v2

100%

100%

100%

100%

已选择

wide_context_v3

96.9%

100%

87.5%

87.5%

拒绝 — 无关上下文 + 1 个误接受


MCP 工具

工具

类型

行为

get_fixture_metadata

读取

返回 fixture 身份、来源、许可证、后端、符号数量

search_graph

读取

参数化名称/方法搜索;最多 20 个结果

generate_java_test

生成

类型化字段 → 图查找 → Java → 所有验证门

generate_java_test_from_intent

生成

有界 3 形式语法 → 相同严格策略

validate_java_source

验证

检查最多 20 000 个字符;从不写入或执行源代码

generate_java_test_nlp

多代理

LLM 意图解析器 → 生成器 → LLM 审查器;需要 OPENAI_API_KEY

Neo4j 适配器使用固定参数化 Cypher,拒绝 URI 中的凭据,并拒绝 fixture 身份冲突。


快速开始

python -m venv .venv
# Windows
.\.venv\Scripts\Activate.ps1
# Linux / macOS
source .venv/bin/activate

pip install -r requirements-dev.txt
pip install --no-deps -e .

# Run the offline smoke test (no database needed)
python scripts/container_smoke.py python -m graph_mcp.server

MCP 客户端配置(VS Code / Claude Desktop)

{
  "mcpServers": {
    "graph-java-gen": {
      "command": "/absolute/path/to/.venv/bin/python",
      "args": ["-m", "graph_mcp.server"],
      "cwd": "/absolute/path/to/repo"
    }
  }
}

启用多代理 NLP 工具

# Add to your environment or .env file
OPENAI_API_KEY=sk-...
GRAPH_BACKEND=neo4j   # optional; defaults to local JSON fixture

复现证据

# Build the CC0 benchmark fixture
python scripts/build_evaluation_fixture.py

# Run all four candidate policies and select strict_graph_v2
python scripts/evaluate_workflow.py

# Validate the claims ledger and evidence privacy rules
python scripts/validate_evidence.py

# Full test suite
pytest --cov=src --cov-report=term-missing --cov-fail-under=75

# Lint and security
ruff check src tests scripts
bandit -r src scripts -q -ll
pip-audit -r requirements.txt --progress-spinner off

实时 Neo4j 路径

# Start a local Neo4j Community instance (Docker)
docker compose up -d neo4j
python scripts/wait_for_neo4j.py

# Seed the synthetic graph fixture and verify retrieval
python scripts/seed_graph.py
python scripts/verify_neo4j.py   # writes evidence/neo4j_integration.json

# Full MCP benchmark over stdio with live graph
python scripts/benchmark_mcp.py  # writes evidence/mcp_benchmark.json

Java 编译

# Requires JDK 21 on PATH
python scripts/compile_generated.py --require-compiler
# Writes evidence/java_compile.json

安全设计

  • MCP 表面无原始 Cypher — 所有图查询均为参数化。

  • 严格字段允许列表 — 类名、包名、模块名、版本和配置路径在每次图查找之前均根据编译后的正则表达式模式进行检查。

  • 源代码安全扫描器 — 如果生成的 Java 引用了 Runtime.getRuntime、ProcessBuilder、System.exit、java.io、java.nio.file 或 java.net,则拒绝。

  • 路径遍历防护 — 配置路径字段中拒绝绝对路径和 .. 段。

  • 接地性强制 — 生成源代码中的每个导入必须对应于从图中为该确切版本检索到的符号。

  • LLM 输出重新验证 — 由 LLM 意图解析器提取的字段通过与直接 API 调用相同的 GenerationIntent.from_mapping() 验证。

  • Neo4j 凭据 — 仅从环境变量加载;从不记录或返回在证据工件中。

  • XML 预检 — defusedxml 防止项目结构扫描中的实体扩展攻击。

  • 容器 — 固定 Chainguard Linux 镜像,非 root UID/GID 65532;CI 执行 MCP-over-container stdio 冒烟测试。

完整威胁边界见 SECURITY.md。


仓库结构

src/graph_mcp/
  workflow.py            intent parsing · graph lookup · Java generation · validation
  graph_store.py         Neo4j catalog adapter (parameterised Cypher)
  llm_intent_parser.py   Agent 1 — LLM free-form NL → GenerationIntent
  review_agent.py        Agent 2 — LLM post-generation checklist reviewer
  server.py              FastMCP stdio server (7 tools)
  evaluation.py          candidate scoring and selection harness

fixtures/
  synthetic_graph.json   CC0 versioned framework symbol catalog (SHA-256 bound)
  evaluation_cases.json  96 CC0 natural-language intents (32/32/32 split)
  java_framework/        7 independently generated Java stub classes

evidence/
  claims.json            machine-readable claims ledger (14 public claims)
  evaluation_protocol.json  pre-declared selection rules and safety gates
  task_evaluation.json   per-candidate, per-split, per-case results
  evaluation_trace.json  confirmation case-level trace
  neo4j_integration.json live Neo4j integration result
  mcp_benchmark.json     MCP protocol benchmark (120 calls)
  java_compile.json      ECJ compilation result

scripts/
  build_evaluation_fixture.py   generate benchmark from seed
  evaluate_workflow.py          run and score all four candidates
  validate_evidence.py          verify claims ledger and privacy rules
  benchmark_mcp.py              official MCP stdio latency benchmark
  verify_neo4j.py               live graph integration check
  compile_generated.py          ECJ compile gate
  seed_graph.py                 materialise fixture into Neo4j

tests/
  test_generation_loop.py       generation + validation unit tests
  test_graph_store.py           Neo4j adapter unit tests
  test_mcp_protocol.py          official MCP protocol conformance
  test_evaluation.py            evaluation harness tests
  test_evidence.py              claims ledger integrity tests
  test_neo4j_live.py            opt-in live graph tests (NEO4J_* env required)

docs/
  ARCHITECTURE.md        component design and data flow
  POLICY_CARD.md         candidate selection details
  DATA_CARD.md           fixture provenance and license
  MCP_INTEGRATION.md     client configuration guide
  DEPLOYMENT.md          Docker and container notes

templates/               MCP prompt templates for VS Code Copilot
examples/                sample project preflight scanner

边界

本仓库不声明以下内容:

  • 独立于模型版本的自由格式意图解析质量 — LLM 流水线为可选,其结果不包含在冻结的评估工件中。

  • 与任何专有或机密 Java 测试框架的兼容性。

  • 生产延迟 SLO — 所有测量均为单进程本地顺序基准。

  • 并发、分布式或高可用性操作。

  • 对硬件或测试仪器自动执行生成的 Java。

  • 任何生产力、成本、产量或测试时间节省 — 本仓库仅包含生成和验证证据。

完整机器可读边界见 evidence/claims.json。


许可证

仓库代码:MIT。 图 fixture、意图用例和 Java 存根:CC0-1.0(在 fixture 元数据中标记)。

Related MCP Connectors