Skip to main content
Glama
lean-lsp-mcp

lean-lsp-mcp

by r-irbe

lean4-lsp-mcp

Give AI coding agents instant Lean 4 proof goals, sub-5ms symbol navigation, and automatic counterexample checks without waiting on full project rebuilds.

lean4-lsp-mcp (published on npm as lean4-lsp-mcp / lean-lsp-mcp) is a standalone Model Context Protocol (MCP)mcp server that connects AI coding agents (Claude Code, Cursor, Windsurf, Zed, and Antigravity) directly to your Lean 4 proof environment and C FFI headers.

lean4-lsp-mcp Architecture and Customer Journeys


Why Use lean4-lsp-mcp? (What Problem Does It Solve?)

When AI coding agents try to write or fix Lean 4 proofs using standard shell commands, they get stuck in a slow, expensive loop:

  1. Running lake build after every edit takes minutes: Standard agents edit a .lean file, insert trace_state, and recompile the whole module just to see the current proof goal. lean4-lsp-mcp keeps a shared lake serve session warm and returns the exact tactic goal at any line and column in milliseconds (lean_goal).

  2. Agents waste hours trying to prove false lemmas: If a helper lemma has a subtle boundary bug (like a natural number subtraction underflow), an agent will burn hundreds of tactic attempts trying to prove the impossible. lean_counterexample_search tests candidate theorems with Plausibleplausible first so false claims are caught in seconds.

  3. Searching large Mathlib or multi-file projects is slow: Starting a full language server just to find where a theorem is defined or used eats RAM and time. lean4-lsp-mcp reads compiled .ilean index files directly from disk in under 5 milliseconds (lean_lookup_symbol, lean_decl_references, lean_module_hierarchy).


Related MCP server: lsp-mcp-server

Start in 2 Minutes

1. Run via npx (Zero Manual Build Required)

Add lean-lsp to your coding agent's MCP configuration (.mcp.json, ~/.claude/claude_desktop_config.json, or .cursor/mcp.json):

{
  "mcpServers": {
    "lean-lsp": {
      "command": "npx",
      "args": ["-y", "lean4-lsp-mcp"],
      "env": {
        "PATH": "${HOME}/.elan/bin:/usr/bin:/bin"
      }
    }
  }
}
# Global npm install
npm install -g lean4-lsp-mcp

# Or build from a local clone
git clone https://github.com/r-irbe/lean4-lsp-mcp.git
cd lean4-lsp-mcp && npm install && npm run build

If your IDE launches MCP servers from outside your Lean repository, set "LEAN_PROJECT_ROOT": "/path/to/your/lake/project" in the env block.


Adapt to Your Use Case (Customer Journeys)

How lean4-lsp-mcp Replaces Slow lake build Loops With Instant Proof Feedback

  • Who this is for: Researchers, engineers, and AI agents actively closing sorry placeholders in Lean 4.

  • How to use it:

    • Call lean_goal with {"filePath": "MyProj/Basic.lean", "line": 42, "col": 4, "target": "tactic"} to see the exact proof state at the cursor, or "target": "altproof" for ranked tactic suggestions.

    • Call lean_diagnostics with {"filePath": "MyProj/Basic.lean"} to get live compiler errors plus automatic warnings for natural-number truncation (a - b without b <= a) and division by zero.

  • Who this is for: Teams writing new formal specifications where edge cases (0, empty lists, off-by-one bounds) are easy to miss.

  • How to use it: Call lean_counterexample_search with {"filePath": "MyProj/Spec.lean", "theoremName": "my_lemma", "strategy": "dense"}. It runs an isolated property check in a scratch directory and returns a concrete counterexample if the lemma is false.

  • Who this is for: Maintainers of large Lean 4 repositories, teams porting proofs from Rocq/Coq or Isabelle, and systems engineers binding Lean 4 @[extern] functions to C.

  • How to use it:

    • Sub-5ms Offline Navigation: lean_lookup_symbol, lean_decl_references, and lean_module_hierarchy query .lake/build/lib/**/*.ilean directly without booting lake serve.

    • Multi-Source Search: lean_search, lean_book_index_lookup (65+ math/CS textbooks), and lean_cross_itp_concordance (Coq/Isabelle/HOL Light -> Lean 4 tactic equivalents).

    • Trust & FFI Verification: lean_axiom_closure verifies a theorem depends only on standard axioms (propext, Classical.choice, Quot.sound), and lean_ffi checks @[extern] C symbols against your C headers.


Complete 21-Tool Reference

See instructions.md for copy-paste JSON payloads and agent prompting guidelines.

Tool Name

Required Parameters

What It Does

lean_goal

filePath, line

Returns tactic goal, term goal, filtered goal, or altproof tactic advice at (line, col).

lean_diagnostics

filePath

Live elaboration errors, unsolved goals, and static Nat truncation/div-by-zero checks.

lean_counterexample_search

filePath, theoremName

Runs Plausible property testing in an isolated scratch dir to falsify broken theorems.

lean_lookup_symbol

symbol

Instant offline .ilean jump-to-definition and type signature lookup (<5ms).

lean_decl_references

symbol

Finds declarations that uses or are usedBy the target symbol (<5ms).

lean_module_hierarchy

moduleName

Returns module imports or importedBy dependency trees.

lean_dependency_subgraph

moduleName

Exports bounded module dependency subgraphs (mermaid, dot, or json).

lean_search

query

Unified search across local code, Loogle, LeanSearch, Reservoir, arXiv, books, and graph.

lean_book_index_lookup

term

Looks up concepts across 65+ curated theorem-proving and math textbook indexes.

lean_cross_itp_concordance

concept

Maps tactics and concepts across Coq/Rocq, Isabelle, HOL Light, Agda, and Lean 4.

lean_axiom_closure

symbol

Runs #print axioms to verify a theorem uses no sorryAx or custom axioms.

lean_navigate

operation (+ filePath, line, col / query)

Live LSP navigation (hover, definition, typeDefinition, declaration, implementation, references, documentSymbol, workspaceSymbol/findSymbol, call hierarchy, advertise-only codeAction) plus offline moduleImports/moduleImportedBy, behind the admitted-context gate. With an admitted Lean context it runs in exact mode (no ambient fallback); a Lake project without admission runs ambient (contextCertified:false); anything else is refused. Refusals read environment_unavailable: <code>: <operation>: <detail>. LEAN_NAV_REQUIRE_EXACT=1 (or the requireExactNavigation constructor option) refuses everything but exact. Mutations (rename, executeCommand, codeAction apply) are not exposed.

lean_metrics / lean_module_census

target

Computes declaration counts, complexity metrics, and corpus censuses.

lean_blueprint / lean_blueprint_scaffold

(optional)

Scaffolds and inspects Lean Blueprint LaTeX/dependency nodes and Zettelkasten links.

lean_proof_skeleton

filePath or symbol

Extracts the high-level have/suffices skeleton of a proof.

lean_ffi

(optional)

Inspects Lean C FFI sysroot headers and verifies @[extern] C symbol bindings.

lean_exec / lean_run_code

code

Executes a standalone Lean 4 snippet (#check, #eval) via lake env lean.

lean_resync / lean_server_status

filePath / (none)

Refreshes a file worker or reports the resolved Lake project root and server health.

Optional knowledge graph

Set PROVER_KNOWLEDGE_KZ to the proof-skills release archive to enable concept and tactic concordance lookup. For a private graph, set KUZU_ARCHIVE_PATH to its archive, or set LEAN_KUZU_CONFIG_PATH to an explicit federation config that lists its enabled databases. The server opens graphs only after explicit configuration. Point standalone deployments at the small proof-skills release archive when local collections must stay outside the search service.

See the graph examples and result limits.

  1. Model Context Protocol (MCP): An open standard that lets AI coding assistants call external tools and language servers over stdio JSON-RPC.

    ↩
  2. Plausible: Lean 4's property-based testing library (similar to QuickCheck) that generates test inputs to find counterexamples to a theorem statement.

    ↩

Available Tools

5 tools
lean_c_ffi_inspectA

Cross-language C FFI inspector: Lean @[extern] declarations, C implementations, and Lean sysroot include flags

Inputs: action, externName.

lean_goalA

Queries interactive Lean 4 tactic proof state at cursor position ($/lean/plainGoal)

Inputs: line (required), filePath (required), col, character.

lean_lookup_symbolA

Offline zero-latency symbol lookup and jump-to-definition via pre-compiled .ilean cache

Inputs: symbol (required), preferOfflineIlean.

lean_module_hierarchyB

Forward and reverse module import dependency hierarchy analysis

Inputs: moduleName (required), direction.

lean_term_goalB

Queries expected term type under cursor ($/lean/plainTermGoal)

Inputs: line (required), filePath (required), col, character.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.8/5.0

    Scored across 5 tools

    Disambiguation5/5

    Each tool targets a distinct concern: tactic proof state, term type inspection, symbol lookup, module dependency analysis, and C FFI inspection. There is no overlap or ambiguity between these operations, even the two goal-related tools are clearly differentiated by context.

    Naming Consistency5/5

    All tool names follow a uniform pattern with the 'lean_' prefix and snake_case, using noun-based or verb-noun combinations consistently (e.g., lean_goal, lean_lookup_symbol). The naming is predictable and easy to infer purpose from.

    Tool Count5/5

    With 5 tools, the server is well-scoped for a Lean LSP integration, providing a focused set of capabilities without redundancy or bloat. Each tool serves a clear purpose in the interactive theorem proving workflow.

    Completeness4/5

    The tool set covers essential Lean-specific operations like goal queries and symbol lookup, but lacks common LSP features such as hover, diagnostics, or references. However, for a specialized Lean server, the core proving workflows are well-represented, with only minor gaps.

    Maintenance

    ActivityActive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      B
      maintenance
      Enables LLM agents to interact with the Lean theorem prover through the Language Server Protocol, providing tools for analyzing Lean projects, accessing diagnostics, goal states, documentation, and searching for theorems using both local and external search services.
      22
      148,993 PyPI
      559
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Exposes type-aware code navigation and fast file search to AI agents via language servers, enabling definitions, references, symbols, and file lookup without reading entire codebases.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables agents to perform local hybrid code search and code intelligence across a workspace, including semantic and full-text search, symbol lookup, file outlines, and caller analysis.
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      Enables AI-driven formal proof search in Lean 4 by submitting theorems with sorry placeholders and running parallel LLM agents whose proposed edits are verified by the Lean compiler until a machine-checked proof is produced. Also provides Mathlib theorem search and job/attempt management tools.
      3
      MIT