Lean LSP

by ooo0ooo

Not rated
GitHub

About

Interact with the Lean theorem prover via the Language Server Protocol (LSP), enabling LLM agents to understand, analyze, and modify Lean projects.

Details

Author
ooo0ooo
Categories
Developer Tools, AI

4. Install ripgrep (optional but recommended)

For the local search toollean_local_search, installripgrep(rg) and make sure it is available in your PATH.

5. Install the Lean 4 skill (optional but recommended)

With any agentic coding platform such as Claude Code or Codex, you can install theAgentic Coding Skill: Lean 4 Theorem Proving. This skill provides additional prompts and templates for interacting with Lean 4 projects, including guidance on usinglean-lsp-mcp.

SeeTools documentationfor the full list of available tools.

Many clients allow the user to disable specific tools manually (e.g. lean_build).

VSCode: Click on the Wrench/Screwdriver icon in the chat.

Cursor: In "Cursor Settings" > "MCP" click on the name of a tool to disable it (strikethrough).

You can also disable tools at server startup:

- LEAN_MCP_DISABLED_TOOLS: Comma-separated tool names (for examplelean_run_code,lean_build).
- LEAN_MCP_INSTRUCTIONS: Replacement server instructions string.
- LEAN_MCP_TOOL_DESCRIPTIONS: JSON object to override tool descriptions.

export LEAN_MCP_DISABLED_TOOLS="lean_run_code,lean_build" export LEAN_MCP_INSTRUCTIONS="Prefer lean_local_search before remote search tools." export LEAN_MCP_TOOL_DESCRIPTIONS='{"lean_goal":"Primary proof-state inspection tool."}'

This MCP server works out-of-the-box without any configuration. However, a few optional settings are available.

- LEAN_LOG_LEVEL: Log level for the server. Options are "INFO", "WARNING", "ERROR", "NONE". Defaults to "INFO".
- LEAN_LOG_FILE_CONFIG: Config file path for logging, with priority overLEAN_LOG_LEVEL. If not set, logs are printed to stdout.
- LEAN_PROJECT_PATH: Path to your Lean project root. A valid Lean project root must containlean-toolchainand eitherlakefile.leanorlakefile.toml. Relativefile_patharguments resolve against this root. This variable is required forstreamable-httpandsse.
- LEAN_MCP_DISABLED_TOOLS: Comma-separated list of tool names to remove from MCP tool listing.
- LEAN_MCP_INSTRUCTIONS: Replacement server instructions string.
- LEAN_MCP_TOOL_DESCRIPTIONS: JSON object mapping tool names to replacement descriptions.
- LEAN_MCP_SCRATCH_SLOTS: Number of parallel scratch documents used for snippet trials. Defaults to1; increase it only when parallel attempts are worth the additional Lean process memory.
- LEAN_REPL: Set totrue,1, oryesto enable fast REPL-basedlean_run_codeand line-basedlean_multi_attempt(see
REPL Setup).
- LEAN_REPL_PATH: Path to thereplbinary. Auto-detected from.lake/packages/repl/or.lake/packages/REPL/if not set.
- LEAN_REPL_TIMEOUT: Per-command timeout in seconds (default: 60).
- LEAN_REPL_MEM_MB: Max memory per REPL in MB (default: 16384). Only enforced on Linux/macOS.
- LEAN_LSP_MCP_TOKEN: Secret token for bearer authentication when usingstreamable-httporssetransport. If set, bearer auth is required for every request.
- LEAN_BUILD_CONCURRENCY: Build concurrency mode forlean_build. Options:allow(default),cancel,share.
- LEAN_STATE_SEARCH_URL: URL for a self-hosted
premise-search.cominstance. Rate limits are skipped when set to a custom backend.
- LEAN_HAMMER_URL: URL for a self-hosted
Lean Hammer Premise Searchinstance. Rate limits are skipped when set to a custom backend.
- LEAN_LOOGLE_LOCAL: Set totrue,1, oryesto enable local loogle (see
Local Looglesection).
- LEAN_LOOGLE_CACHE_DIR: Override the cache directory for local loogle (default:~/.cache/lean-lsp-mcp/loogle).
- LOOGLE_URL: URL for a self-hosted Loogle instance (default:https://loogle.lean-lang.org). Rate limits are skipped when set to a custom backend.
- LOOGLE_HEADERS: JSON object of extra HTTP headers for Loogle requests (e.g.'{"X-API-Key": "..."}').

You can also often set these environment variables in your MCP client configuration:

{ "servers": { "lean-lsp": { "type": "stdio", "command": "uvx", "args": [ "lean-lsp-mcp" ], "env": { "LEAN_PROJECT_PATH": "/path/to/your/lean/project", "LEAN_LOG_LEVEL": "NONE" } } } }

The Lean LSP MCP server supports the following transport methods:

- stdio: Standard input/output (default)
- streamable-http: HTTP streaming
- sse: Server-sent events (MCP legacy, usestreamable-httpif possible)

stdiosupports project inference and switching as you move between Lean projects.streamable-httpandsseare single-project deployments: they requireLEAN_PROJECT_PATHat startup and reject tool-driven project switching.

You can specify the transport method using the--transportargument when running the server. Forsseandstreamable-httpyou can also optionally specify the host and port:

uvx lean-lsp-mcp --transport stdio # Default transport uvx lean-lsp-mcp --transport streamable-http # Available at http://127.0.0.1:8000/mcp uvx lean-lsp-mcp --transport sse --host localhost --port 12345 # Available at http://localhost:12345/sse uvx lean-lsp-mcp --version # Print the installed version

For ChatGPT, Codex, Responses API, or other OpenAI surfaces, useOpenAI Secure MCP Tunnelinstead of exposinglean-lsp-mcpto the public internet. Create a tunnel inPlatform tunnel settings, then runtunnel-clienton a host that can reach your Lean project:

export CONTROL_PLANE_API_KEY="sk-..." tunnel-client init \ --sample sample_mcp_stdio_local \ --profile lean-lsp-local \ --tunnel-id tunnel_0123456789abcdef0123456789abcdef \ --mcp-command "uvx lean-lsp-mcp --transport stdio --lean-project-path /path/to/lean/project" tunnel-client doctor --profile lean-lsp-local --explain tunnel-client run --profile lean-lsp-local

Use--lean-project-pathso relativefile_patharguments resolve inside the intended Lean project. For HTTP, bindlean-lsp-mcpto loopback and use--mcp-server-url http://127.0.0.1:8000/mcpin the tunnel profile:

export LEAN_PROJECT_PATH="/path/to/lean/project" uvx lean-lsp-mcp --transport streamable-http --host 127.0.0.1 --port 8000

Keeptunnel-client runhealthy while testing connector discovery or tool calls. In ChatGPT connector settings, chooseTunnelas the connection type.

Transport viastreamable-httpandssesupports bearer token authentication. For private OpenAI access, prefer OpenAI Secure MCP Tunnel; bearer auth remains available for HTTP/SSE deployments that clients reach directly.

Set theLEAN_LSP_MCP_TOKENenvironment variable (or see section 3 for setting env variables in MCP config) to a secret token before starting the server. If this variable is set, requests without a matchingAuthorization: Bearer ...header are rejected before tool dispatch.

export LEAN_LSP_MCP_TOKEN="your_secret_token" uvx lean-lsp-mcp --transport streamable-http

Clients should then include the token in theAuthorizationheader.

Enable fast REPL-basedlean_run_codeand line-basedlean_multi_attempt. Usesleanprover-community/repltactic mode. Exactcolumn-based attempts still use the LSP path.

1. Add REPL to your Lean project'slakefile.toml:

[[require]] name = "repl" git = "https://github.com/leanprover-community/repl" rev = "v4.25.0" # Match your Lean version

3. Enable via CLI or environment variable:

uvx lean-lsp-mcp --repl # Or via environment variable export LEAN_REPL=true

The REPL binary is auto-detected from.lake/packages/repl/or.lake/packages/REPL/. Falls back to LSP if not found.

File-based tools only operate on files inside the active Lean project, resolved.lake/packages/*dependencies, and the Lean stdlib source tree. Returned file paths are sanitized to avoid leaking host absolute paths:

- Project files are returned relative to the project root, for examplesrc/MyFile.lean.
- Dependency files are returned under.lake/packages/<package>/....
- Stdlib files are returned under.lean-stdlib/....

Symlink escapes outside those roots are rejected.

Run Loogle locally to avoid the remote API's rate limit (3 req/30s). The binary is built once for the project's Lean toolchain. The first Mathlib index takes a few minutes; subsequent starts load it in seconds.

# Enable via CLI uvx lean-lsp-mcp --loogle-local # Or via environment variable export LEAN_LOOGLE_LOCAL=true

Requirements:git,lake(elan), a built Mathlib project, and substantial memory for indexing. In measurements on current Mathlib, the initial index used ~13 GiB peak RSS and a warm load used ~7 GiB.

Note:Local loogle is currently only supported on Unix systems (Linux/macOS). Windows users should use WSL or the remote API.

Mathlib comes from your project:--lean-project-pathmust point at a built project that depends on Mathlib. The local binary is compiled for that project's Lean toolchain and runs throughlake env, so Lake supplies the project's own dependency environment. Loogle's native dependency hash detects changed.oleanfiles and rebuilds a stale index automatically.

Falls back to remote API if local loogle fails.

There are many valid security concerns with the Model Context Protocol (MCP) in general!

This MCP server is meant as a research tool and is currently in beta. While it does not handle any sensitive data such as passwords or API keys, it still includes various security risks:

- Access to your local file system.
- Powerful local build and analysis capabilities.
- External network access for remote search tools unless disabled by the operator.

Please be aware of these risks. Feel free to audit the code and report security issues!

Containerized setup (recommended for stricter isolation)

docker build -t lean-lsp-mcp:containerized .

Run with a mounted project root (read-only source + writable Lake cache):

docker run --rm -i \ -v "$PWD":/workspace:ro \ -v lean-lsp-mcp-lake-cache:/workspace/.lake \ lean-lsp-mcp:containerized

- LEAN_PROJECT_PATH=/workspace
- LEAN_MCP_DISABLED_TOOLS=lean_run_code

- LEAN_MCP_DISABLED_TOOLSis a startup default and can be overridden bydocker run -e.
- Using--network nonecan break tools that require network access (leansearch,loogle,leanfinder,state_search,hammer_premise) and dependency downloads.
- The entrypoint exits immediately ifLEAN_PROJECT_PATHdoes not exist.

For more information, you can useAwesome MCP Securityas a starting point.

MCP server that allows agentic interaction with theLean theorem provervia theLanguage Server Protocolusingleanclient. This server provides a range of tools for LLM agents to understand, analyze and interact with Lean projects.

- Rich Lean Interaction: Access diagnostics, goal states, term information, hover documentation and more.
- External Search Tools: UseLeanSearch,Loogle,Lean Finder,Lean HammerandLean State Searchto find relevant theorems and definitions.
- Easy Setup: Simple configuration for various clients, including VSCode, Cursor and Claude Code.
- Install
uv, a Python package manager.
- Make sure your Lean project builds quickly by runninglake buildmanually.
- Configure your IDE/Setup
- (Optional, highly recommended) Install
ripgrep(rg) for local search and source scanning (lean_verifywarnings).

Install uvfor your system. On Linux/MacOS:curl -LsSf https://astral.sh/uv/install.sh | sh

If you use Nix, you can install the package directly from GitHub:

nix profile install github:oOo0oOo/lean-lsp-mcp

Or run it without installing:nix run github:oOo0oOo/lean-lsp-mcp.

This provides the MCP server only. You still need a Lean toolchain (elan/lake) for your project, same as theuvsetup below.

lean-lsp-mcpwill runlake servein the project root to use the language server (for most tools). Some clients (e.g. Cursor) might timeout during this process. Therefore, it is recommended to runlake buildmanually before starting the MCP. This ensures a faster build time and avoids timeouts.

Ctrl+Shift+P > "MCP: Add Server..." > "Command (stdio)" > "uvx lean-lsp-mcp" > "lean-lsp" (or any name you like) > Global or Workspace

OR manually adding config by openingmcp.jsonwith:

Ctrl+Shift+P > "MCP: Open User Configuration"

{ "servers": { "lean-lsp": { "type": "stdio", "command": "uvx", "args": [ "lean-lsp-mcp" ] } } }

If you installed VSCode on Windows and are using WSL2 as your development environment, you may need to use this config instead:

{ "servers": { "lean-lsp": { "type": "stdio", "command": "wsl.exe", "args": [ "uvx", "lean-lsp-mcp" ] } } }

If that doesn't work, you can try cloning this repository and replace"lean-lsp-mcp"with"/path/to/cloned/lean-lsp-mcp".
-

"+ Add a new global MCP Server" > ("Create File")

Paste the server config intomcp.jsonfile:

{ "mcpServers": { "lean-lsp": { "command": "uvx", "args": ["lean-lsp-mcp"] } } }
# Local-scoped MCP server claude mcp add lean-lsp uvx lean-lsp-mcp # OR project-scoped MCP server # (creates or updates a .mcp.json file in the current directory) claude mcp add lean-lsp -s project uvx lean-lsp-mcp

You can find more details about MCP server configuration for Claude Codehere.

Paste the following into the file (e.g. at the end):

[[mcp_servers]] name = "lean-lsp" transport = "stdio" command = "uvx" args = ["lean-lsp-mcp"] tool_timeout_sec = 600

If there are no existing MCP servers, you may have to removemcp_servers = [].

4. Install ripgrep (optional but recommended)

For the local search toollean_local_search, installripgrep(rg) and make sure it is available in your PATH.

5. Install the Lean 4 skill (optional but recommended)

With any agentic coding platform such as Claude Code or Codex, you can install theAgentic Coding Skill: Lean 4 Theorem Proving. This skill provides additional prompts and templates for interacting with Lean 4 projects, including guidance on usinglean-lsp-mcp.

SeeTools documentationfor the full list of available tools.

Many clients allow the user to disable specific tools manually (e.g. lean_build).

VSCode: Click on the Wrench/Screwdriver icon in the chat.

Cursor: In "Cursor Settings" > "MCP" click on the name of a tool to disable it (strikethrough).

You can also disable tools at server startup:

- LEAN_MCP_DISABLED_TOOLS: Comma-separated tool names (for examplelean_run_code,lean_build).
- LEAN_MCP_INSTRUCTIONS: Replacement server instructions string.
- LEAN_MCP_TOOL_DESCRIPTIONS: JSON object to override tool descriptions.

export LEAN_MCP_DISABLED_TOOLS="lean_run_code,lean_build" export LEAN_MCP_INSTRUCTIONS="Prefer lean_local_search before remote search tools." export LEAN_MCP_TOOL_DESCRIPTIONS='{"lean_goal":"Primary proof-state inspection tool."}'

This MCP server works out-of-the-box without any configuration. However, a few optional settings are available.

- LEAN_LOG_LEVEL: Log level for the server. Options are "INFO", "WARNING", "ERROR", "NONE". Defaults to "INFO".
- LEAN_LOG_FILE_CONFIG: Config file path for logging, with priority overLEAN_LOG_LEVEL. If not set, logs are printed to stdout.
- LEAN_PROJECT_PATH: Path to your Lean project root. A valid Lean project root must containlean-toolchainand eitherlakefile.leanorlakefile.toml. Relativefile_patharguments resolve against this root. This variable is required forstreamable-httpandsse.
- LEAN_MCP_DISABLED_TOOLS: Comma-separated list of tool names to remove from MCP tool listing.
- LEAN_MCP_INSTRUCTIONS: Replacement server instructions string.
- LEAN_MCP_TOOL_DESCRIPTIONS: JSON object mapping tool names to replacement descriptions.
- LEAN_MCP_SCRATCH_SLOTS: Number of parallel scratch documents used for snippet trials. Defaults to1; increase it only when parallel attempts are worth the additional Lean process memory.
- LEAN_REPL: Set totrue,1, oryesto enable fast REPL-basedlean_run_codeand line-basedlean_multi_attempt(see
REPL Setup).
- LEAN_REPL_PATH: Path to thereplbinary. Auto-detected from.lake/packages/repl/or.lake/packages/REPL/if not set.
- LEAN_REPL_TIMEOUT: Per-command timeout in seconds (default: 60).
- LEAN_REPL_MEM_MB: Max memory per REPL in MB (default: 16384). Only enforced on Linux/macOS.
- LEAN_LSP_MCP_TOKEN: Secret token for bearer authentication when usingstreamable-httporssetransport. If set, bearer auth is required for every request.
- LEAN_BUILD_CONCURRENCY: Build concurrency mode forlean_build. Options:allow(default),cancel,share.
- LEAN_STATE_SEARCH_URL: URL for a self-hosted
premise-search.cominstance. Rate limits are skipped when set to a custom backend.
- LEAN_HAMMER_URL: URL for a self-hosted
Lean Hammer Premise Searchinstance. Rate limits are skipped when set to a custom backend.
- LEAN_LOOGLE_LOCAL: Set totrue,1, oryesto enable local loogle (see
Local Looglesection).
- LEAN_LOOGLE_CACHE_DIR: Override the cache directory for local loogle (default:~/.cache/lean-lsp-mcp/loogle).
- LOOGLE_URL: URL for a self-hosted Loogle instance (default:https://loogle.lean-lang.org). Rate limits are skipped when set to a custom backend.
- LOOGLE_HEADERS: JSON object of extra HTTP headers for Loogle requests (e.g.'{"X-API-Key": "..."}').

You can also often set these environment variables in your MCP client configuration:

{ "servers": { "lean-lsp": { "type": "stdio", "command": "uvx", "args": [ "lean-lsp-mcp" ], "env": { "LEAN_PROJECT_PATH": "/path/to/your/lean/project", "LEAN_LOG_LEVEL": "NONE" } } } }

The Lean LSP MCP server supports the following transport methods:

- stdio: Standard input/output (default)
- streamable-http: HTTP streaming
- sse: Server-sent events (MCP legacy, usestreamable-httpif possible)

stdiosupports project inference and switching as you move between Lean projects.streamable-httpandsseare single-project deployments: they requireLEAN_PROJECT_PATHat startup and reject tool-driven project switching.

You can specify the transport method using the--transportargument when running the server. Forsseandstreamable-httpyou can also optionally specify the host and port:

uvx lean-lsp-mcp --transport stdio # Default transport uvx lean-lsp-mcp --transport streamable-http # Available at http://127.0.0.1:8000/mcp uvx lean-lsp-mcp --transport sse --host localhost --port 12345 # Available at http://localhost:12345/sse uvx lean-lsp-mcp --version # Print the installed version

For ChatGPT, Codex, Responses API, or other OpenAI surfaces, useOpenAI Secure MCP Tunnelinstead of exposinglean-lsp-mcpto the public internet. Create a tunnel inPlatform tunnel settings, then runtunnel-clienton a host that can reach your Lean project:

export CONTROL_PLANE_API_KEY="sk-..." tunnel-client init \ --sample sample_mcp_stdio_local \ --profile lean-lsp-local \ --tunnel-id tunnel_0123456789abcdef0123456789abcdef \ --mcp-command "uvx lean-lsp-mcp --transport stdio --lean-project-path /path/to/lean/project" tunnel-client doctor --profile lean-lsp-local --explain tunnel-client run --profile lean-lsp-local

Use--lean-project-pathso relativefile_patharguments resolve inside the intended Lean project. For HTTP, bindlean-lsp-mcpto loopback and use--mcp-server-url http://127.0.0.1:8000/mcpin the tunnel profile:

export LEAN_PROJECT_PATH="/path/to/lean/project" uvx lean-lsp-mcp --transport streamable-http --host 127.0.0.1 --port 8000

Keeptunnel-client runhealthy while testing connector discovery or tool calls. In ChatGPT connector settings, chooseTunnelas the connection type.

Transport viastreamable-httpandssesupports bearer token authentication. For private OpenAI access, prefer OpenAI Secure MCP Tunnel; bearer auth remains available for HTTP/SSE deployments that clients reach directly.

Set theLEAN_LSP_MCP_TOKENenvironment variable (or see section 3 for setting env variables in MCP config) to a secret token before starting the server. If this variable is set, requests without a matchingAuthorization: Bearer ...header are rejected before tool dispatch.

export LEAN_LSP_MCP_TOKEN="your_secret_token" uvx lean-lsp-mcp --transport streamable-http

Clients should then include the token in theAuthorizationheader.

Enable fast REPL-basedlean_run_codeand line-basedlean_multi_attempt. Usesleanprover-community/repltactic mode. Exactcolumn-based attempts still use the LSP path.

1. Add REPL to your Lean project'slakefile.toml:

[[require]] name = "repl" git = "https://github.com/leanprover-community/repl" rev = "v4.25.0" # Match your Lean version

3. Enable via CLI or environment variable:

uvx lean-lsp-mcp --repl # Or via environment variable export LEAN_REPL=true

The REPL binary is auto-detected from.lake/packages/repl/or.lake/packages/REPL/. Falls back to LSP if not found.

File-based tools only operate on files inside the active Lean project, resolved.lake/packages/*dependencies, and the Lean stdlib source tree. Returned file paths are sanitized to avoid leaking host absolute paths:

- Project files are returned relative to the project root, for examplesrc/MyFile.lean.
- Dependency files are returned under.lake/packages/<package>/....
- Stdlib files are returned under.lean-stdlib/....

Symlink escapes outside those roots are rejected.

Run Loogle locally to avoid the remote API's rate limit (3 req/30s). The binary is built once for the project's Lean toolchain. The first Mathlib index takes a few minutes; subsequent starts load it in seconds.

# Enable via CLI uvx lean-lsp-mcp --loogle-local # Or via environment variable export LEAN_LOOGLE_LOCAL=true

Requirements:git,lake(elan), a built Mathlib project, and substantial memory for indexing. In measurements on current Mathlib, the initial index used ~13 GiB peak RSS and a warm load used ~7 GiB.

Note:Local loogle is currently only supported on Unix systems (Linux/macOS). Windows users should use WSL or the remote API.

Mathlib comes from your project:--lean-project-pathmust point at a built project that depends on Mathlib. The local binary is compiled for that project's Lean toolchain and runs throughlake env, so Lake supplies the project's own dependency environment. Loogle's native dependency hash detects changed.oleanfiles and rebuilds a stale index automatically.

Falls back to remote API if local loogle fails.

There are many valid security concerns with the Model Context Protocol (MCP) in general!

This MCP server is meant as a research tool and is currently in beta. While it does not handle any sensitive data such as passwords or API keys, it still includes various security risks:

- Access to your local file system.
- Powerful local build and analysis capabilities.
- External network access for remote search tools unless disabled by the operator.

Please be aware of these risks. Feel free to audit the code and report security issues!

Containerized setup (recommended for stricter isolation)

docker build -t lean-lsp-mcp:containerized .

Run with a mounted project root (read-only source + writable Lake cache):

docker run --rm -i \ -v "$PWD":/workspace:ro \ -v lean-lsp-mcp-lake-cache:/workspace/.lake \ lean-lsp-mcp:containerized

- LEAN_PROJECT_PATH=/workspace
- LEAN_MCP_DISABLED_TOOLS=lean_run_code

- LEAN_MCP_DISABLED_TOOLSis a startup default and can be overridden bydocker run -e.
- Using--network nonecan break tools that require network access (leansearch,loogle,leanfinder,state_search,hammer_premise) and dependency downloads.
- The entrypoint exits immediately ifLEAN_PROJECT_PATHdoes not exist.

For more information, you can useAwesome MCP Securityas a starting point.

No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.