Skip to main content
Glama
graph-mcp-java-gen

graph-mcp-java-gen

graph-mcp-java-gen

CI Python Evidence License MCP Neo4j

图锚定的 MCP 服务器:将自然语言请求转换为经过验证、可编译的 Java 测试方法——不产生幻觉式导入,不引入无锚定的符号,也不会静默失败。

自然语言或结构化请求进入官方 Model Context Protocol(MCP)stdio 服务器。带版本的图目录(Neo4j 或 JSON fixture)提供生成器唯一可以引用的符号。多层验证器在返回任何源码之前,会检查语法、框架契约、锚定(grounding)以及禁用 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

Related MCP server: MCP Universal Test Suite Generator

多智能体流水线

%%{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 个 class 文件,通过 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-form 语法 → 同一严格策略

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,则该代码会被拒绝。

  • 路径遍历防护 — 拒绝配置以太网路径中的绝对路径和 .. 段。

  • 锚定强制 — 生成源码中的每个 import 必须与某个从图中按该确切版本检索出的符号对应。

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

  • Neo4j 凭据 — 仅从环境变量加载;从不写入日志或返回给证据文件。

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

  • 容器 — 固定的 Chainguard Linux 镜像,非 root 用户 UID/GID 65532;CI 会对容器内的 MCP 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 元数据中标注)。

Available Tools

6 tools
generate_java_testD

Generate Java only when graph grounding, syntax, contract, and safety pass.

Inputs: class_name (required), config_path (required), module_name (required), package_name (required), +1 more. Returns: object

generate_java_test_from_intentC

Parse a bounded natural-language request, generate Java, and enforce all gates.

Inputs: request (required). Returns: object

generate_java_test_nlpB

Multi-agent pipeline: LLM parses free-form NL, generates Java, LLM reviews it.

Agent 1 (LLMIntentParser) normalises natural language to a structured intent. The deterministic generator produces graph-cited, validated Java source. Agent 2 (ReviewAgent) audits the result against a six-item checklist. Requires OPENAI_API_KEY in the environment.

Inputs: request (required). Returns: object

get_fixture_metadataA

Return provenance and version information for the active graph fixture.

Inputs: no named parameters. Returns: object

search_graphB

Search the bounded synthetic graph by class, qualified name, or method.

Inputs: query (required), limit, version. Returns: object

validate_java_sourceC

Validate bounded Java source against syntax, graph, contract, and safety gates.

Inputs: source (required), class_name (required), config_path (required), module_name (required), +2 more. Returns: object

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3/5.0

    Scored across 6 tools

    Disambiguation4/5

    The tools are mostly distinct: metadata retrieval, graph search, three variations of Java test generation, and validation. The three generate_java_test* tools could be confused, but their descriptions clearly differentiate by input type (structured, bounded NL, free-form NL with review). Minor overlap exists but descriptions resolve ambiguity.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case: get_fixture_metadata, search_graph, generate_java_test, generate_java_test_from_intent, generate_java_test_nlp, validate_java_source. The naming is predictable and uniform throughout the set.

    Tool Count5/5

    With 6 tools, the server is well-scoped for its purpose of generating and validating Java tests from a synthetic graph. Each tool serves a clear role in the workflow, and the count feels appropriate—not too few to be inadequate, not too many to be unwieldy.

    Completeness5/5

    The tool surface covers the full lifecycle: metadata retrieval, graph search for grounding, three generation pathways (including NL-based variants), and validation. There are no obvious missing operations for the stated purpose; the server provides a complete pipeline from context gathering to output validation.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers