javalens-mcp
JavaLens MCP server provides 63 semantic analysis tools for Java codebases, built on Eclipse JDT for compiler-accurate code understanding, navigation, refactoring, and metrics.
Project Management: Load Maven, Gradle, Bazel, or plain Java projects; check server health; inspect project structure, classpath, and type members.
Navigation & Search: Search symbols by glob pattern; go to definitions; find references, implementations, and type hierarchies; list file symbols; get symbol/type/method/field info at a position; find super methods.
Fine-Grained Reference Search (JDT-unique, beyond standard LSP):
Annotation usages, type instantiations (
new Type()), casts ((Type) expr),instanceofchecksthrowsdeclarations,catchblocks, method references (Type::method), generic type arguments (List<Type>), and Java reflection usage
Code Analysis: Get diagnostics (errors/warnings); validate syntax; trace incoming/outgoing call hierarchies; find field writes; discover JUnit/TestNG tests; detect unused private members and potential bugs (null risks, resource leaks, empty catches); get hover info, Javadoc, signature help, and enclosing element; analyze change impact (blast radius), data flow, and control flow; find Spring DI registrations.
Compound Analysis (reduces round-trips): analyze_file, analyze_type, analyze_method, get_type_usage_summary — each aggregates multiple analyses in a single call.
Refactoring (returns text edits, does not modify files directly): Rename symbols project-wide; organize imports; extract variable/method/constant/interface; inline variable/method; change method signature; convert anonymous class to lambda.
Quick Fixes: Suggest imports for unresolved types; list available quick fixes at a position; apply fixes (add/remove import, add throws, surround with try-catch).
Metrics & Code Quality: Cyclomatic/cognitive complexity; package/type dependency graphs; circular dependency detection (Tarjan's SCC); find large classes; check Java naming convention violations.
Provides compiler-accurate Java code analysis using Eclipse JDT Core, enabling semantic understanding of Java codebases including type resolution, method overloading, inheritance hierarchies, and fine-grained reference analysis.
Enables detection of Spring Dependency Injection registrations and annotations (@Component, @Bean, @Autowired, @Inject) for analyzing Spring-based Java applications.
JavaLens: AI-First Code Analysis for Java
An MCP server providing 75 semantic analysis tools for Java, built directly on Eclipse JDT for compiler-accurate code understanding.
Built for AI Agents
JavaLens exists because AI systems need compiler-accurate insights that reading source files cannot provide. When an AI uses grep or Read to find usages of a method, it cannot distinguish:
A method call from a method with the same name in an unrelated class
A field read from a field write
An interface implementation from an unrelated class
A cast to a type from other references to that type
This leads to incorrect refactorings, missed usages, and incomplete understanding of code behavior.
Related MCP server: easy-code-reader
Compiler-Accurate Analysis
JavaLens provides compiler-accurate code analysis through Eclipse JDT—the same engine that powers Eclipse IDE. Unlike text search, JDT understands:
Type resolution across inheritance hierarchies
Method overloading and overriding
Generic type arguments
Import resolution and classpath dependencies
Java source from version 1.1 through Java 25 (markdown Javadoc, module imports, compact source files, flexible constructor bodies)
Lombok-generated members — a bundled agent makes
@Dataaccessors and the like resolve, so code using them is not flagged as undefined
Example: Finding all places where UserService.save() is called:
Approach | Result |
| Returns 47 matches including |
| Returns exactly 12 calls to |
AI Training Bias Warning
⚠️ Important for AI developers and users
AI models may exhibit trained bias toward native tools (Grep, Read, LSP) over MCP server tools, even when semantic analysis provides better results. This happens because:
Training data contains extensive grep/text-search patterns
Native tools are "always available" in the model's experience
The model may not recognize when semantic analysis is superior
To get the best results:
Add guidance to your project instructions or system prompt (e.g., CLAUDE.md for Claude Code):
## Code Analysis Preferences
For Java code analysis, prefer JavaLens MCP tools over text search:
- Use `find_references` instead of grep for finding usages
- Use `find_implementations` instead of text search for implementations
- Use `analyze_type` to understand a class before modifying it
- Use refactoring tools (rename_symbol, extract_method) for safe changes
Semantic analysis from JDT is more accurate than text-based search,
especially for overloaded methods, inheritance, and generic types.What is JavaLens?
JavaLens is an MCP server that gives AI assistants deep understanding of Java codebases. It provides semantic analysis, navigation, refactoring, and code intelligence tools that go beyond simple text search.
Why Not LSP?
Language Server Protocol was designed for IDE autocomplete and basic navigation—not for AI agent workflows that require deep semantic analysis.
Capability | Native LSP | JavaLens |
Find all | ❌ | ✅ |
Find all | ❌ | ✅ |
Find all casts to a type | ❌ | ✅ |
Distinguish field reads from writes | ❌ | ✅ |
Detect circular package dependencies | ❌ | ✅ |
Calculate cyclomatic complexity | ❌ | ✅ |
Find unused private methods | ❌ | ✅ |
Detect possible null pointer bugs | ❌ | ✅ |
Project-wide dead-code reachability from entry points | ❌ | ✅ |
Find the tests that exercise a symbol, transitively | ❌ | ✅ |
JavaLens wraps Eclipse JDT Core directly via OSGi, providing:
Fine-grained reference types: Find specifically casts, annotations, throws clauses, catch blocks, instanceof checks, method references, type arguments
Read vs write access distinction: Track where fields are mutated vs just read
Indexed search: JDT pre-builds an index at load time, so symbol/reference queries do not walk source files
Full AST access: Direct manipulation for complex refactorings
Installation
Prerequisites
Java 21 or later (must be on PATH or set
JAVA_HOME) — required for both install paths.Node.js 18+ — required only if you use the npm/
npxinstall path below. Skip if you use the direct-download path.
JavaLens is an analytical server, not a compiler. It uses Eclipse JDT 2025-12 to parse and understand Java source code from version 1.1 through 25. Java 21 is required only as the server runtime.
Install from GitHub Releases (recommended — Java only)
This is the simplest path if you already have Java 21 and don't have Node.js. Download from Releases:
Platform | File |
All platforms |
|
Extract to a location of your choice (e.g., /opt/javalens or C:\javalens). Then point your MCP client at the bundled jar — see Configure MCP Client below.
Install via npm (requires Node.js 18+)
If you already have Node.js, npx will download and cache the JavaLens distribution (~23 MB) on first run:
{
"mcpServers": {
"javalens": {
"command": "npx",
"args": ["-y", "javalens-mcp"],
"env": {
"JAVA_PROJECT_PATH": "/path/to/your/java/project"
}
}
}
}Configure MCP Client
Add to your MCP configuration (e.g., .mcp.json for Claude Code):
{
"mcpServers": {
"javalens": {
"command": "java",
"args": ["-jar", "/path/to/javalens/javalens.jar", "-data", "/path/to/javalens-workspaces"]
}
}
}The -data argument specifies where JavaLens stores its workspace metadata. See How Workspaces Work below.
Auto-Load a Project
Set JAVA_PROJECT_PATH to auto-load a project when the server starts:
{
"mcpServers": {
"javalens": {
"command": "java",
"args": ["-jar", "/path/to/javalens/javalens.jar", "-data", "/path/to/javalens-workspaces"],
"env": {
"JAVA_PROJECT_PATH": "/path/to/your/java/project"
}
}
}
}Note: Project loading happens asynchronously in the background. The MCP server responds immediately while the project loads. Use
health_checkto monitor loading status—it will show"project.status": "loading"until complete, then"loaded"when ready.
How Workspaces Work
Unlike in-memory code models, Eclipse JDT requires a workspace directory to store:
Search indexes for fast symbol lookup
Compilation state and caches
Project metadata
Workspaces Are Outside Your Source
JavaLens creates its workspace outside your source project to keep your codebase clean:
Your Java Project (unchanged)
├── src/main/java/
├── pom.xml
└── (no Eclipse files added)
JavaLens Workspace (specified by -data)
└── {session-uuid}/
├── .metadata/ <- JDT indexes and state
└── javalens-project/ <- Links to your source (not copies)Why this matters:
No pollution: Your source tree stays clean—no
.projector.classpathfilesNo conflicts: Works alongside any build system without interference
Session isolation: Each MCP session gets its own workspace, enabling concurrent analysis
Session Lifecycle
JavaLens starts and creates a unique workspace:
{base}/{uuid}/load_projectcreates linked folders pointing to your sourceJDT builds indexes in the workspace (not in your project)
When the session ends, the workspace is cleaned up
Tools
Navigation (10 tools)
Tool | Description |
| Search types, methods, fields by glob pattern |
| Navigate to symbol definition |
| Find all usages of a symbol |
| Find interface/class implementations |
| Get inheritance chain |
| Get all symbols in a file |
| Get detailed symbol information at position |
| Get type details at cursor |
| Get method details at cursor |
| Get field details at cursor |
Fine-Grained Reference Search (9 tools)
These use JDT's unique reference type constants—not available through LSP:
Tool | Description |
| Find all |
| Find all |
| Find all |
| Find all |
| Find all |
| Find all |
| Find all |
| Find all |
| Find |
Analysis (20 tools)
Tool | Description |
| Get compilation errors and warnings |
| Fast syntax-only validation |
| Find all callers of a method |
| Find all methods called by a method |
| Find where fields are mutated |
| Discover JUnit/TestNG test methods |
| Find unused private members |
| Project-wide dead code — members unreachable from any main method or test, over the whole-program call graph |
| The tests that exercise a symbol, directly or transitively — the set to run after changing it |
| Detect null risks, empty catches, resource leaks |
| Get documentation/signature for symbol |
| Get parsed Javadoc |
| Get method signature at call site |
| Get containing method/class at position |
| Blast radius — direct call sites by depth, or the full transitive closure over the project graph ( |
| Variable read/write/declaration tracking within a method; opt-in |
| Branching, loops, return/throw points, nesting depth |
| Find Spring DI registrations (@Component, @Bean, @Autowired, @Inject) |
| Assembled JPA entity model — tables, id fields, relationships with resolved targets and mappedBy sides |
| Assembled HTTP route table — Spring and JAX-RS paths composed from class prefixes, mapped to handler methods |
Compound Analysis (4 tools)
Combine multiple queries to reduce round-trips:
Tool | Description |
| Get imports, types, diagnostics in one call |
| Get members, hierarchy, usages, diagnostics |
| Get signature, callers, callees, overrides |
| Get instantiations, casts, instanceof counts |
Refactoring (16 tools)
All refactoring tools return text edits (and new-file content where a refactoring creates one) rather than applying changes directly:
Tool | Description |
| Rename across entire project |
| Sort and clean imports |
| Extract expression to local variable |
| Extract code block to new method |
| Extract to |
| Create interface from class methods |
| Move a member into a newly created superclass |
| Replace variable with its initializer |
| Replace call with method body |
| Modify params/return, update all callers |
| Convert anonymous class to lambda |
| Generate accessors and rewrite all direct field accesses |
| Move a member into the superclass |
| Move a member into the subclasses |
| Bundle a method's parameters into a new class, updating callers |
| Move a nested type into its own top-level file |
Quick Fixes (5 tools)
Tool | Description |
| Find import candidates for unresolved type |
| List available fixes for problem at position |
| Apply fix by ID (add import, remove import, add throws, try-catch) |
| Apply one of 10 JDT clean-ups (convert loops, pattern matching, switch expressions, text blocks, ...) and return rewritten source |
| Diagnose a file and return each problem's top quick-fix edits in one call |
Metrics (5 tools)
Tool | Description |
| Cyclomatic/cognitive complexity, LOC per method |
| Package/type dependencies as nodes and edges |
| Detect package cycles using Tarjan's SCC algorithm |
| Find types exceeding method/field/line count thresholds |
| Check against Java naming conventions |
Project & Infrastructure (6 tools)
Tool | Description |
| Server status and capabilities |
| Load Maven/Gradle/Bazel/plain Java project |
| Get package hierarchy |
| Get classpath entries |
| Get members by type name |
| Find overridden method in superclass |
Usage
Basic Workflow
1. load_project(projectPath="/path/to/java/project")
2. search_symbols(query="*Service", kind="Class")
3. find_references(filePath="...", line=10, column=15)
4. analyze_type(typeName="com.example.UserService")Coordinate System
All line/column parameters are zero-based:
Line 0, Column 0 = first character of file
Path Handling
Response paths are relative by default
All paths use forward slashes for cross-platform consistency
Input paths can be relative or absolute
Important Notes
Disk Synchronization
Every answer is verified against the files on disk at query time. Before any tool logic runs, JavaLens content-hashes the known source files, detects edits, additions, and deletions (the agent reports nothing — the server discovers changes itself), repairs exactly what changed, waits for the search index to absorb the repair, and only then answers. There is no file watcher and no background thread — verification is synchronous inside the query the agent issued, so there are no race conditions.
The agent's loop is just: edit → query.
1. Use JavaLens tools to analyze
2. Write changes to files
3. Use JavaLens tools to verify — answers already reflect the changesload_project is needed only on first use, when a response reports RELOAD_REQUIRED (a build file like pom.xml changed, so the classpath must be rebuilt), or to rebuild everything from scratch. If verification itself fails, the query returns VERIFICATION_FAILED rather than an unverified answer.
Cost: verification is hash-based and parallel — measured per query at ~2 ms for a 72-file project, ~25 ms at 1,000 files, ~180 ms at 10,000 files. Repairs cost only what changed (one edited file reconciles in well under a second), never a full reindex.
Manual mode: set JAVALENS_DISK_SYNC=manual to restore the pre-1.5.0 contract — answers reflect the last load and the agent calls load_project after editing files. Tool descriptions and the MCP instructions field always state the active contract, and health_check reports it as diskSync.
Refactoring Returns Edits
Refactoring tools return text edits but don't modify files. This gives visibility into what would change before applying.
Session Isolation
Each MCP session is independent with its own workspace UUID. Multiple sessions can analyze the same project concurrently.
Build System Support
JavaLens loads three real build systems plus plain Java directories. Each is exercised end-to-end in CI against synthetic real-shaped fixtures (multi-module reactors with cross-module deps, real external libraries, annotation processors).
System | Detection | Single-module | Multi-module / multi-project | Compiler compliance from build files | Generated sources | Annotation processors |
Maven |
| ✅ | ✅ (reactor classpath aggregation, cross-module navigation) | ✅ ( | ✅ ( | ✅ ( |
Gradle |
| ✅ | ✅ ( | ✅ ( | ✅ ( | ✅ ( |
Bazel |
| ✅ | ✅ (every | ✅ ( | n/a (Bazel actions write into | ✅ (any classpath jar with |
Plain Java |
| ✅ | n/a | ✅ (falls back to | n/a | n/a |
Subprocess invocations of mvn / gradle happen during project load. If a tool is missing or fails, JavaLens surfaces a structured LoadWarning (e.g. MAVEN_SUBPROCESS_FAILED, GRADLE_SUBPROCESS_FAILED, COMPLIANCE_LEVEL_UNKNOWN) in the load_project response so callers know analysis quality is degraded rather than silently getting an empty classpath.
Configuration
Environment Variable | Description | Default |
| Auto-load project on startup | (none) |
| Operation timeout | 30 |
|
| strict |
| TRACE/DEBUG/INFO/WARN/ERROR | INFO |
| JVM options, e.g. | (default: 512m via eclipse.ini) |
| Path to the Lombok agent jar attached at launch; overrides the bundled one | (bundled) |
Building from Source
git clone https://github.com/pzalutski-pixel/javalens-mcp.git
cd javalens-mcp
./mvnw clean verifyDistributions are output to org.javalens.product/target/products/.
Build Requirements
Java 21+ (server runtime)
Maven 3.9+ (wrapper included as
./mvnw)
To run the full test suite (which includes end-to-end tests against real Maven, Gradle, and Bazel builds), the corresponding tools must also be on PATH:
Maven (provided by the wrapper)
Gradle 8+
Bazel 9+ (or
bazelisk)
Tests gracefully skip when a tool is missing on a developer machine. Set JAVALENS_TESTS_REQUIRE_TOOLS=true to flip the gate: missing tools cause a hard failure instead of a skip. CI runs with this flag set so any provisioning gap surfaces as a real failure rather than weakening the suite silently.
Testing
# Full suite, gentle (missing tools skip)
./mvnw verify
# Full suite, strict (missing tools fail; what CI does)
JAVALENS_TESTS_REQUIRE_TOOLS=true ./mvnw verifyBuild-system coverage is structured as focused per-bug tests plus realistic end-to-end tests. The end-to-end tests load a single representative project per build system that exercises every fix in one pass — multi-module Maven with Lombok APT and cross-module references; multi-project Gradle with annotation processors; multi-target Bazel with cross-target deps. CI runs them on Linux, macOS, and Windows.
Architecture
flowchart TD
Client["<b>MCP Client</b>"]
MCP["<b>org.javalens.mcp</b><br/>McpProtocolHandler → ToolRegistry → 75 Tools"]
Core["<b>org.javalens.core</b><br/>JdtServiceImpl → WorkspaceManager, SearchService"]
JDT["<b>Eclipse JDT Core</b> (via OSGi / Equinox)<br/>IWorkspace, IJavaProject, SearchEngine, ASTParser"]
Client -->|"JSON-RPC over stdio"| MCP
MCP --> Core
Core --> JDTLicense
MIT License - see LICENSE for details.
Maintenance
Latest Blog Posts
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/pzalutski-pixel/javalens-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server