LeanUI Docs
← Open LeanUI Studio GitHub

07 · Code Generation, CLI, Full-IDE MCP (54 Tools), GenUI (16 Widgets) & ACP v2#

LeanUI compiles every verified graph & multi-project Solution specification to deterministic targets and exposes the entire IDE over:

  1. Command-Line Interface (@leanui/cli)
  2. Full-IDE Model Context Protocol Server (@leanui/mcp-server) — 54 MCP tools (41 core IDE tools + 13 high-velocity macro & GenUI tools), 7 resources, 4 URI templates, 6 guided prompts
  3. Full 16-Widget Reusable GenUI System — renders rich, interactive previews, solution maps, proof matrices, WCAG palettes, FSM simulators, data explorers, trace debuggers, and live generated apps directly inline in Studio Agent chat
  4. Agentic Coding Harness & Official ACP Latest (v2) Protocol (@leanui/agent-harness) — Token/API-key LLMs (Gemini, OpenAI / Codex, Claude), Subscription Coding CLIs (Claude Code, Codex CLI, Gemini CLI), and Local (STDIO) & Remote (HTTP + Bearer + SSE) ACP v2 server & client!

1. Multi-Target Code Generation (@leanui/codegen)#

From Studio's Export ▾ menu (or live code panels λ Lean 4, ◇ HTML, ⚛ React) you can copy or download:

TargetExtensionDescription
Lean 4 Formal Spec.leanComplete machine-checkable Lean 4 module (ViewModel, initState, Action, update, Invariant, rootView, WCAG styleSheet, i18n resourceBundle, built-in theorems, and user proof_rule theorems).
Standalone HTML/JS.htmlZero-dependency, self-contained reactive HTML/CSS/JS application with <script> escaping and live state reducer.
Connected Prototype HTML.htmlSelf-contained multi-screen interactive Prototype bundling all Solution modules, cross-screen routes, Back/Forward history, transitions, and Desktop/Tablet/Mobile viewports.
React + TypeScript.tsxTyped React functional component (ViewModel interface, Action discriminated union, pure reducer, and typed JSX).
Trace Regression Tests.test.mjs / .spec.tsRunnable Node.js or Playwright regression test suites synthesized directly from recorded Debugger traces (generateTraceTestSuite).
Solution Lakefilelakefile.leanMulti-project Lean 4 Lake manifest linking all projects & modules in the active LeanUISolution.
Module / Solution Spec.leanui.json / .leanui-sln.jsonLossless JSON graph/solution serialization for version control and CI pipelines.

2. CLI Reference (@leanui/cli)#

bash
# Verify all 13 built-in presets and regenerate Lean 4, HTML, and React TSX outputs
npm run generate:examples

# Run static check across all 13 presets with machine-readable JSON CI output
node packages/cli/dist/index.js --all --check --format json

# Compile a single preset (all 13 presets supported, including verified_templates & custom_logic)
node packages/cli/dist/index.js --preset custom_logic --lean-dir lean/Examples --html-dir examples --tsx-dir examples/react

# Compile & live-watch a custom exported Studio spec JSON
node packages/cli/dist/index.js --input ./MyApp.leanui.json --lean-dir ./out/lean --html-dir ./out/html --tsx-dir ./out/tsx --watch

# Scaffold a brand-new verified Solution from any of the 6 Solution Templates
node packages/cli/dist/index.js --new-solution mvvm_app --name AcmeSuite --out ./AcmeSuite.leanui-sln.json --format json

# Verify & batch-compile a multi-project Solution (.leanui-sln.json) + emit Connected Prototype HTML
node packages/cli/dist/index.js --solution ./Enterprise.leanui-sln.json --lean-dir ./out/lean --html-dir ./out/html --prototype ./out/prototype.html --format json

# Verify the built-in Enterprise Suite Solution & export a standalone multi-screen Prototype
node packages/cli/dist/index.js --default-solution --prototype ./out/enterprise-prototype.html --format json

# Run real native Lean 4 formal verification (`lake build` inside ./lean)
npm run verify:lean

# Build Lean project AND emit standalone HTML directly from the Lean 4 native compiler (lean/Main.lean)
npm run codegen:lean

3. Full-IDE MCP Server (@leanui/mcp-server — 54 Tools)#

LeanUI ships a full MCP (2025-03-26) server with full IDE parity enabling external and embedded AI coding agents to create, structure, edit, batch-wire, style, template, debug, formally prove in real Lean 4, render interactive GenUI cards, and build every part of a multi-project Solution.

Transports#

  1. STDIO Transport (recommended for local AI agent clients):
    bash
    npm run mcp:stdio
    # Runs: node packages/mcp-server/dist/stdio.js --lean-project lean
  2. Standalone Streamable HTTP Transport (POST /mcp, GET /mcp/info, GET /mcp/health):
    bash
    npm run mcp:http
    # Runs on http://127.0.0.1:4178/mcp
  3. Live Shared Studio Dev Endpoint:
    • Running npm run dev mounts ONE shared LeanUIMcpServer instance across /mcp, /acp, and /agent (http://localhost:5173/mcp), synced live with Studio's 🤖 Agent & MCP panel (↑ Push Sln / ↓ Pull Sln / Auto-Sync).

Client Configuration Example (STDIO)#

json
{
  "mcpServers": {
    "leanui": {
      "command": "node",
      "args": ["/absolute/path/to/LeanUI/packages/mcp-server/dist/stdio.js", "--lean-project", "/absolute/path/to/LeanUI/lean"]
    }
  }
}

All 54 MCP Tools (41 Core IDE + 13 High-Velocity Macro & GenUI)#

CategoryTool NameDescription
Solution Management & Buildget_solution_overviewReturn full active LeanUISolution tree (projects, nested folders, modules, node/edge counts, verification errors, workflows, and architecture metrics).
get_active_solutionExport the complete active LeanUISolution JSON and activeModuleId for full Studio synchronization.
set_active_solutionReplace the active LeanUISolution on the live server (used by Studio ↑ Push Sln and Agent Auto-Sync).
select_moduleSwitch the active working graph to any module inside the active Solution by module ID or name.
scaffold_solutionList all 26 Solution/Project/Item templates, create a new Solution from any template, add structured Projects or any of the 14 Item types, create nested folders, and serialize/load full .leanui-sln.json workspaces.
manage_solution_itemsFull Solution CRUD: rename_solution, rename_project, delete_project, rename_folder, delete_folder, rename_module, duplicate_module, move_module, delete_module, and set_entry_module.
build_solution_targetsBuild and verify an entire Solution, a single Project, or a single Module to lean, html, tsx, prototype, and lakefile targets.
Presets & Active Graphlist_presetsList all 13 verified LeanUI preset keys, titles, and node/edge counts.
load_presetLoad any of the 13 built-in presets into the active workspace.
get_workspace_graphRead the current workspace SpecGraph JSON.
set_workspace_graphReplace the workspace graph (used by Studio ↑ Push Graph sync).
create_spec_graphCreate a fresh empty SpecGraph with a given namespace title.
list_ide_capabilitiesInspect full IDE capabilities (41 MCP tools, 67 node kinds, 13 presets, 26 solution/project/item templates).
Graph Construction & Refactoringadd_nodeAdd any of the 67 typed node kinds with custom properties & coordinates.
update_nodePatch properties of an existing node by ID.
delete_nodeDelete a node and its incident edges.
connect_portsConnect two typed ports with compatibility validation.
disconnect_edgeRemove a wire by edge ID.
edit_graph_batchAtomic multi-node graph authoring: add multiple nodes with tempId aliases, patch/delete nodes, wire ports using tempIds, and run auto-layout in one verified call.
manage_subprogram_or_groupHigh-level IDE canvas ops: group, extract_subprogram, list_templates, insert_template, align, distribute, splice_reroute, and split_portals.
Design System & ControlTemplatesmanage_design_systemCreate/update WCAG-verified style tokens (upsert_style), multi-locale i18n/token resource bundles (upsert_resource), or audit contrast/i18n diagnostics.
manage_control_templateCreate or edit first-class control_template nodes (create, update, add_prop, add_part, add_trigger) with instant TPL001–TPL005 verification.
inspect_control_templateInspect control_template nodes (rootContainer, props, parts, triggers, custom events, nested templateSpecGraph controls, and static diagnostics).
set_template_root_containerReconfigure a template's rootContainer (border|stack|row|grid|scroll|card|panel|button), columns, gap, alignment, and custom events.
Runtime, Debugger & FSMrun_debugger_sessionFull interactive debugger session: dispatch actions, evaluate Watch expressions, test conditional breakpoints, check breakOnViolation, and export Node or Playwright regression tests (generateTraceTestSuite).
run_runtime_traceDispatch an ordered sequence of Action names (with optional initial state overrides) and verify every invariant at every step.
step_state_machineAdvance a named state_machine (FSM) node across events, evaluating transition guards and terminal states.
Data Sources & Querieslist_data_providersList all 9 supported Data Source providers (Online, Firebase Realtime, MS Access / SQL, Local Files) and their capabilities.
query_data_sourceExecute/inspect datasource & data_query nodes (including MS Access JOINs, WHERE filters, FK validation, and optional live HTTP fetch).
Layout, Diff & App Flow Architectureapply_layoutRun one of the 5 automatic layout algorithms (layered, hierarchical, grouped, tree, grid).
trace_wiringCompute upstream & downstream causal wiring cone for specified node IDs.
diff_workspace_graphCompute structural & proof-level diffs (added/modified/removed nodes, wires, and invariant/theorem regressions).
manage_solution_workflowList, add (with optional guardExpr & transition), or remove cross-module WorkflowLinks (navigate|event|state_sync|dependency) on the active Solution, or export a Connected Prototype HTML.
analyze_solution_architectureAnalyze macro View & ViewModel reachability, orphan/dead-end screens, shared ViewModel hubs, and WF002 port contracts; compute layered/swimlanes/clusters layouts or Bird's-Eye clusters; or simulate live cross-module workflow hops.
Verification & Formal Lean 4 Proofsverify_graphRun the instant @leanui/verifier static & bounded invariant checker.
verify_solutionRun incremental multi-project Solution verification across all modules & contracts.
prove_leanRun the real Lean 4 compiler (lake env lean) to mechanically prove all generated theorems.
add_proof_ruleAdd a user-defined proof_rule (Hoare triple, View constraint, or Reachability theorem).
manage_lean_proof_nodesAuthor full Lean 4 proof language nodes (lean_type, lean_def, lean_theorem, lean_tactic) with custom imports & optional real Lean 4 check.
check_wcag_contrastCompute exact WCAG contrast ratio (x10) and AA/AAA pass status for any foreground/background hex pair.
Code Generationgenerate_codeGenerate lean, lean_standalone, html, or tsx targets from the active workspace graph.
High-Velocity Macro & GenUI Tools (13)get_architecture_guidelinesReturn structured LeanUI architectural rules, canonical folder layouts, anti-patterns, and recommended tools by topic.
describe_node_kindsInspect exact typed input/output port schemas and defaults for any of the 69 node kinds before wiring.
search_solutionCross-project search across all modules, nodes, diagnostics, templates, and workflow links.
manage_project_referencesManage acyclic project dependency DAG references (add, remove, validate) across multi-project Solutions.
organize_solutionAuto-organize modules into canonical folders, prune empty folders, validate reference DAGs, and clean broken links.
build_viewmodelAtomically scaffold states, collections, computeds, predicates, actions, FSMs, and invariants wired and laid out in one call.
build_view_uiAtomically construct a full nested View hierarchy bound to ViewModel outputs & action triggers with auto-layout.
build_proof_suiteAuthor lean_type, lean_def, lean_theorem, lean_tactic, and proof_rule suites with optional real Lean 4 verification.
manage_data_nodesCreate, configure, and wire datasource (all 9 providers) & data_query pipelines in one call.
manage_state_machineCreate/update state_machine FSM states, guarded transitions, and terminal states.
manage_module_contractsWire cross-module module_ref nodes and typed WorkflowLink contracts (state_sync, navigate, event, dependency).
auto_fix_diagnosticsAutomatically repair common verification issues (WCAG contrast, missing accessible labels, broken links/edges).
render_genui_cardEmit any of the 16 interactive GenUI widgets directly into Studio Agent chat.

MCP Resources (7), URI Templates (4) & Guided Prompts (6)#

  • 7 Static Resources:
    • leanui://guidelines — LeanUI Architecture, Graph & Agentic Engineering Guidelines
    • leanui://presets — LeanUI Verified Presets Catalog (all 13 presets)
    • leanui://node-kinds — All 69 Node Kinds & Typed Port Schemas
    • leanui://workspace/active — Active LeanUI Workspace Graph JSON
    • leanui://workspace/lean — Active Workspace Lean 4 Formal Spec
    • leanui://solution/active — Complete Active LeanUISolution JSON
    • leanui://solution/architecture — Live Macro App Flow Architecture & Reachability Analysis
  • 4 Resource URI Templates:
    • leanui://preset/{key}, leanui://preset/{key}/lean, leanui://preset/{key}/html, leanui://preset/{key}/tsx
  • 6 Guided Prompts:
    • design_verified_ui, prove_view_constraints, refactor_large_graph, build_full_solution_app, organize_and_audit_solution, build_mvvm_feature

4. Full 16-Widget Reusable GenUI System#

LeanUI's Agent Chat renders 16 rich, interactive GenUI widget kinds (render_genui_card + automatic harness emissions), reusing Studio's live module renderer, proof visualizer, WCAG contrast calculator, FSM engine, and code highlighters:

Widget KindInteractive Capabilities
live_previewLive interactive module UI rendered inline with real action dispatch & state sync back to Studio.
solution_mapClickable multi-project tree with module counts, error badges, workflow edges, and 1-click tab opening.
kpi_dashboardMetric KPI tiles (ok / warn / err / neutral) for verification, coverage, and architecture health.
proof_matrixTheorem & invariant status table with 1-click jump to node or Lean 4 proof check.
wcag_paletteInteractive color swatch cards displaying live WCAG AA/AAA contrast ratios and pass/fail badges.
action_checklistClickable follow-up prompt chips and direct Studio actions (prove, layout, explode, orbit3d).
diff_summaryStructural graph diff + proof regression summary with direct link to Visual Graph Diff dialog.
interactive_formStructured agent form (text, select, boolean, number, color, slider, chips) submitting directly back to the agent.
guidelines_browserSearchable interactive browser for LeanUI architectural guidelines, rules, and anti-patterns.
viewmodel_workbenchLive ViewModel state inspector, computed evaluator, and interactive action trigger buttons inline in chat.
fsm_simulatorInteractive finite state machine transition stepper highlighting active/terminal states and guard status.
control_template_showcaseLive rendered control_template gallery with Light/Dark preview and slot inspection.
data_explorerInteractive table & query inspector for datasource and data_query records.
code_inspectorTabbed syntax-highlighted Lean 4 / Standalone HTML / React TSX viewer with copy & download buttons.
trace_debuggerInline runtime execution trace scrubber with per-step state diffs and invariant indicators.
genui_spec_appFull self-contained live SpecGraph mini-app synthesized on the fly with 1-click Import into Solution.

5. Agentic Coding Harness & ACP Latest (v2) Protocol (@leanui/agent-harness)#

@leanui/agent-harness delivers a state-of-the-art coding agent harness and full Agent Client Protocol (ACP v2 Latest, backward-compatible with v1) server & client support across all 9 provider modes:

Supported Coding Agent Providers#

CategoryProvider IDAuth / TransportDescription
Built-In (Offline)leanui_builtinZero-key localDeterministic offline LeanUI Architect driving all 41 MCP tools with automatic verification.
Token / API KeygeminiGEMINI_API_KEY (or UI input)Native Gemini :generateContent multi-turn functionCall / functionResponse loop over all 41 MCP tools.
openai_codexOPENAI_API_KEY (or UI input)OpenAI / Codex /chat/completions multi-turn tool_calls loop over all 41 MCP tools (supports custom OpenAI-compatible baseUrl).
claudeANTHROPIC_API_KEY (or UI input)Anthropic /v1/messages multi-turn tool_use / tool_result loop over all 41 MCP tools.
Subscription Local CLIclaude_code_subLocal claude OAuth loginSpawns your local signed-in Claude Code CLI with LeanUI's 41-tool MCP server automatically attached.
codex_subLocal codex OAuth loginSpawns your local signed-in OpenAI Codex CLI with LeanUI's 41-tool MCP server automatically attached.
gemini_cli_subLocal gemini OAuth loginSpawns your local signed-in Gemini CLI with LeanUI's 41-tool MCP server automatically attached.
ACP v1 (Local & Remote)acp_localSTDIO Subprocess (AcpStdioClient)Speaks strict line-delimited JSON-RPC 2.0 ACP v1 over stdin/stdout to any local ACP coding agent (leanui, gemini, opencode acp, goose acp, claude-code-acp).
acp_remoteHTTP + Bearer (AcpRemoteHttpClient)Connects over ACP v1 JSON-RPC HTTP with optional Authorization: Bearer <token> to any remote ACP coding agent harness.

Harness Architecture, Reasoning & Safety Controls#

  • Plan → Tool Loop → Auto-Verify → Optional Real Lean 4 Prove: Streams live SSE events (run_started, plan, thought, tool_call, tool_result, permission_request, message_delta, workspace_synced, completed) to Studio's 🤖 Agent & MCP panel.
  • Live Model Discovery Across All Modes (POST /agent/models):
    • Dynamically fetches the current model list from Gemini (/v1beta/models), OpenAI / Codex / Ollama / OpenRouter (/v1/models), Anthropic Claude (/v1/models), Subscription CLIs (claude, codex, gemini version & model detection), and Live ACP v1 (initialize + session/new over Local STDIO or Remote HTTP) with graceful catalog fallback and live source badges (● Live API, ● Live ACP, ● CLI).
    • Studio's bottom composer features zero-clunk inline pickers (top-layer searchable Model & Provider popover + inline Mode, Reasoning & Approval selectors) and persists preferences in localStorage.
  • Full Model Catalog & Reasoning Effort (off | minimal | low | medium | high | max):
    • Dynamically selects any model across Gemini (gemini-2.5-pro, gemini-2.5-flash, gemini-3-pro-preview), OpenAI/Codex (gpt-5-codex, gpt-5, o3, o4-mini, gpt-4.1), Claude (claude-opus-4-1, claude-sonnet-4-5, claude-3-7-sonnet-latest), Subscription CLIs, Built-In, and ACP session/set_model.
    • Wires reasoning effort directly to each provider: Gemini thinkingConfig.thinkingBudget, OpenAI/Codex reasoning_effort, Claude Extended thinking.budget_tokens, Codex CLI model_reasoning_effort, and ACP session/set_config_option("reasoning_effort", ...).
  • All 7 Agent Modes (session/set_mode): full (Full Autonomous), builder, architect, plan (Plan Only), verifier, debug, and read_only.
  • All 6 Approval Policies (approval_policy): full_auto (Unrestricted), auto (Safe Edits), ask_destructive (Confirm Deletes/Overwrites), ask (Confirm Every Write with Allow Once / Allow Session / Deny), plan_only, and read_only.
  • Full ACP Latest (v2) Session Lifecycle & Streaming:
    • Negotiates protocolVersion: 2 (with automatic v1 fallback) across Local STDIO (AcpStdioClient) and Remote Streamable HTTP + SSE (AcpRemoteHttpClient / /agent/acp-session).
    • Full session management: session/new, session/list, session/load (with history replay), session/fork, session/resume, session/close, session/set_mode, session/set_model, and session/set_config_option (including boolean toggles like auto_prove_lean).
    • Bidirectional session/request_permission approval handshake (Allow Once / Allow Session / Deny) plus real-time token usage & cursor updates.
  • Live Auto-Sync: Automatically pushes Studio's active Solution before a run and pulls mutated Solutions straight back into Studio's Solution Explorer & Canvas.

Running LeanUI as an ACP v2 Agent Server (Local STDIO or Remote HTTP)#

bash
# 1. Local ACP v2 STDIO Server (for Zed, JetBrains, or any ACP v1/v2 client)
npm run acp:stdio
# Runs: node packages/agent-harness/dist/acp-stdio.js --lean-project lean

# 2. Standalone Remote ACP v2 + Agent Harness HTTP Server (:4179)
#    Optional: export LEANUI_ACP_TOKEN=your-secret-bearer-token
npm run acp:http
# Exposes: POST /acp, GET /acp/info, GET /agent/info, POST /agent/run (SSE), POST /agent/acp-session, POST /agent/permission, POST /agent/cancel, POST /agent/acp-handshake

Zed / JetBrains ACP STDIO Client Config#

json
{
  "agent_servers": {
    "leanui": {
      "command": "node",
      "args": ["/absolute/path/to/LeanUI/packages/agent-harness/dist/acp-stdio.js", "--lean-project", "/absolute/path/to/LeanUI/lean"],
      "protocol": "acp/v2"
    }
  }
}
Diagram Preview
Enlarged diagram