Content
# Java Class Analyzer MCP Server
> Current project address: [yudongf/java-class-analyzer-mcp-server](https://github.com/yudongf/java-class-analyzer-mcp-server) (Based on [handsomestWei/java-class-analyzer-mcp-server](https://github.com/handsomestWei/java-class-analyzer-mcp-server)).
> While retaining the original MCP tool capabilities, this project focuses on enhancing **Windows / macOS cross-platform support** and **CFR decompiler tool search and loading logic**, allowing it to run stably in macOS / Linux environments.
A Java class analysis service based on Model Context Protocol (MCP) that can scan Maven project dependencies, decompile Java class files, retrieve class method lists, and provide detailed information to LLM for code analysis.
## Applicable Scenarios
Cursor and other AI tools directly generate code that calls second-party (internal calls) and third-party package (external calls) interfaces. However, because AI cannot read the source code of dependencies not opened in the current project, the generated code often contains errors and may exhibit hallucinations.
To solve this problem, it is common to directly copy source code content to feed LLM or place source files in the current project and reference them in conversations.
Using a local decompilation MCP solution is the most effective, as it accurately analyzes classes and methods in jar packages, significantly improving the accuracy and usability of generated code.
## Features
- **🚀 Easy to Use**: The mcp service is implemented in TypeScript, packaged with npm, and has weak environment dependencies, making it easy to distribute and install.
- 🔍 **Dependency Scanning**: Automatically scans all dependency JAR packages of a Maven project.
- 📦 **Class Indexing**: Establishes a mapping index from full class names to JAR package paths.
- 🧭 **Intelligent Class Name Matching**: When an exact full qualified class name is not found, it performs fuzzy matching by simpleName and provides friendly prompts for candidate matches.
- 🔄 **Decompilation**: Uses the CFR tool (already built-in) to decompile .class files into Java source code in real-time.
- 📊 **Class Analysis**: Analyzes the structure, methods, fields, and inheritance relationships of Java classes.
- 💾 **Intelligent Caching**: Caches decompilation results by package name structure and supports cache control.
- 🚀 **Automatic Indexing**: Automatically checks and creates indexes before analysis.
- ⚙️ **Flexible Configuration**: Supports external specification of CFR tool paths and prioritizes loading through the `CFR_PATH` environment variable.
- 🖥️ **Cross-Platform Compatibility**: Fixes `javap` call issues on macOS / Linux and automatically selects executable files by platform.
- 🤖 **LLM Integration**: Provides Java code analysis capabilities to LLM through the MCP protocol.
## Update Content (v1.0.1)
> Modifications relative to the original [handsomestWei/java-class-analyzer-mcp-server](https://github.com/handsomestWei/java-class-analyzer-mcp-server).
### 1. Cross-Platform Support for Windows and macOS
The original version had hardcoded Windows paths and executable file names in multiple places, causing it to fail on macOS / Linux. This update achieves true cross-platform compatibility:
- **`javap` Call Platform Selection**: [`JavaClassAnalyzer.getJavapCommand()`](src/analyzer/JavaClassAnalyzer.ts:332) no longer hardcodes `javap.exe` but instead automatically selects based on `process.platform`:
- Windows: `${JAVA_HOME}/bin/javap.exe`
- macOS / Linux: `${JAVA_HOME}/bin/javap`
- If `JAVA_HOME` is not set, it falls back to `javap` in `PATH`.
- **Temporary Directory Uses System tmp**: [`DecompilerService.extractClassFile()`](src/decompiler/DecompilerService.ts:121) changes from fixed writing to `process.cwd()/.mcp-class-temp` to using `os.tmpdir()/mcp-class-temp` to avoid polluting the working directory across platforms. If the MCP process returns an abnormal path or empty string for `os.tmpdir()`, it falls back to the user's home directory (`HOME` / `USERPROFILE`) under `.mcp-class-temp/`.
- **Cross-Platform Example Configuration**: [`mcp-server-config.json`](mcp-server-config.json) changes from Windows absolute paths (`D:/ws-git/...`) + `node` startup to the recommended global command `java-class-analyzer-mcp start`, with environment variables using placeholders (`${HOME}/.m2/repository`, `${JAVA_HOME}`, and added `CFR_PATH`), making it universal for Windows / macOS.
| System | `JAVA_HOME` Example | `MAVEN_REPO` Example | Actual `javap` Call |
| --- | --- | --- | --- |
| Windows | `C:/Program Files/Java/jdk-11` | `D:/maven/repository` | `${JAVA_HOME}/bin/javap.exe` |
| macOS | `/Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home` | `${HOME}/.m2/repository` | `${JAVA_HOME}/bin/javap` |
| Linux | `/usr/lib/jvm/java-11-openjdk` | `${HOME}/.m2/repository` | `${JAVA_HOME}/bin/javap` |
### 2. Enhanced CFR Decompiler Tool Handling Logic
The original version only searched for CFR from the project directory or `CLASSPATH`, with inflexible configuration and unfriendly error messages. This update enhances the CFR search and failure prompt logic:
- **Four-Level Priority Search** ([`DecompilerService.findCfrJar()`](src/decompiler/DecompilerService.ts:231), each step prints clear logs for troubleshooting):
1. `CFR_PATH` environment variable (highest priority, recommended method)
2. Files matching the `cfr-*.jar` regular expression in the user's home directory (`HOME` / `USERPROFILE`, cross-platform)
3. Common paths like the project's `lib/` directory and current working directory
4. Entries containing `cfr` in the `CLASSPATH` environment variable
- **Friendly Errors When CFR is Missing**: [`DecompilerService.decompileWithCfr()`](src/decompiler/DecompilerService.ts:189) no longer throws a general error when CFR is not found. Instead, it lists three available configuration methods to guide the user to quickly fix the issue:
```text
CFR decompiler tool not found. Please configure using one of the following methods:
1. Set the CFR_PATH environment variable to point to the cfr jar file path
2. Place the cfr jar in the ~/cfr-*.jar (user's home directory)
3. Place the cfr jar in the project's lib/ directory
```
- **Runtime Still Supports `cfrPath` Parameter Override**: When calling the `decompile_class` tool and explicitly passing `cfrPath`, you can temporarily specify the CFR jar path, which has a higher priority than the above automatic search.
**Recommended Configuration Methods**:
- Windows: Download `cfr-0.152.jar` and set the environment variable `CFR_PATH=D:\tools\cfr-0.152.jar`, or place it in `%USERPROFILE%\cfr-0.152.jar`.
- macOS / Linux: `export CFR_PATH=$HOME/cfr-0.152.jar`, or directly place the jar in `~/cfr-0.152.jar` without any additional configuration.
**CFR Download Address**
The CFR download address is as follows, choose the latest version:
[leibnitz27/cfr](https://github.com/leibnitz27/cfr/releases)
The latest version is currently 0.152. Download it to your local disk (remember the path for subsequent configuration).
### 3. Other Modifications
- **Class Name Search Supports Fuzzy Matching**: [`DependencyScanner.findJarForClass()`](src/scanner/DependencyScanner.ts:254) after exact matching fails, it falls back to unique matching by simpleName, reports multiple candidates, and includes matches in three levels.
- **Version Unification**: [`src/cli.ts`](src/cli.ts:11) and [`src/index.ts`](src/index.ts:23) are updated from `1.0.0` to `1.0.1` to align with `package.json`.
## Usage Examples
### Registering the MCP Service in the IDE

### Using MCP in Intelligent Body Conversations

## Instructions
#### Installation from Source
```bash
git clone https://github.com/yudongf/java-class-analyzer-mcp-server.git
cd java-class-analyzer-mcp-server
npm install
npm run build
npm install -g .
```
### MCP Service Configuration
#### Method 1: Using the Generated Configuration (Recommended)
Run the following command to generate a configuration template:
```bash
java-class-analyzer-mcp config -o mcp-client-config.json
```
Then add the generated configuration content to your MCP client configuration file.
#### Method 2: Manual Configuration
Refer to the following configuration example and add it to your MCP client configuration file:
**Windows Global Installation Configuration:**
```json
{
"mcpServers": {
"java-class-analyzer": {
"command": "java-class-analyzer-mcp",
"args": ["start"],
"env": {
"NODE_ENV": "production",
"MAVEN_REPO": "D:/maven/repository",
"JAVA_HOME": "C:/Program Files/Java/jdk-11",
"CFR_PATH": "D:/tools/cfr-0.152.jar"
}
}
}
}
```
**MAC Global Installation Configuration (Add Auto-Authorization):**
``` json
{
"mcpServers": {
"java-class-analyzer": {
"autoApprove": [
"scan_dependencies",
"analyze_class",
"decompile_class"
],
"disabled": false,
"timeout": 180,
"command": "java-class-analyzer-mcp",
"type": "stdio",
"transportType": "stdio",
"args": [
"start"
],
"env": {
"NODE_ENV": "production",
"MAVEN_REPO": "/tools/maven/repo",
"CFR_PATH": "/tools/cfr-0.152.jar"
}
}
}
}
```
**Local Installation Configuration:**
```json
{
"mcpServers": {
"java-class-analyzer": {
"command": "node",
"args": [
"node_modules/java-class-analyzer-mcp-server/dist/index.js"
],
"env": {
"NODE_ENV": "production",
"MAVEN_REPO": "D:/maven/repository",
"JAVA_HOME": "C:/Program Files/Java/jdk-11",
"CFR_PATH": "D:/tools/cfr-0.152.jar"
}
}
}
}
```
#### Parameter Description
- `command`: The command to run the MCP server, here using `node`.
- `args`: Parameters passed to Node.js, pointing to the file in the `dist` folder compiled by `npm run build`.
- `env`: Environment variable settings.
#### Environment Variable Description
- `NODE_ENV`: Runtime environment identifier
- `production`: Production environment, reducing log output and enabling performance optimization
- `development`: Development environment, outputting detailed debugging information
- `test`: Test environment
- `MAVEN_REPO`: Maven local repository path (optional)
- If set, the program uses the specified repository path to scan JAR packages
- If not set, the program uses the default `~/.m2/repository` path
- `JAVA_HOME`: Java installation path (optional)
- If set, the program uses `${JAVA_HOME}/bin/java` to execute Java commands (used for CFR decompilation)
- If not set, the program uses the `java` command in PATH
- `CFR_PATH`: Path to the CFR decompiler tool (optional, automatically searched by the program)
- Search order: `CFR_PATH` → User's home directory `cfr-*.jar` → Project `lib/` directory → `CLASSPATH`
### Available Tools
#### 1. scan_dependencies
Scans all dependencies of a Maven project and establishes a mapping index from class names to JAR package paths.
**Parameters:**
- `projectPath` (string): Maven project root directory path
- `forceRefresh` (boolean, optional): Whether to force refresh the index, default is false
**Example:**
```json
{
"name": "scan_dependencies",
"arguments": {
"projectPath": "/path/to/your/maven/project",
"forceRefresh": false
}
}
```
#### 2. decompile_class
Decompiles the specified Java class file and returns the Java source code.
**Parameters:**
- `className` (string): Full name of the Java class to decompile, e.g., com.example.QueryBizOrderDO
- `projectPath` (string): Maven project root directory path
- `useCache` (boolean, optional): Whether to use cache, default is true. Avoid regenerating every time.
- `cfrPath` (string, optional): Path to the CFR decompiler tool jar package. Built-in available, can specify additional versions.
**Example:**
```json
{
"name": "decompile_class",
"arguments": {
"className": "com.example.QueryBizOrderDO",
"projectPath": "/path/to/your/maven/project",
"useCache": true,
"cfrPath": "/path/to/cfr-0.152.jar"
}
}
```
#### 3. analyze_class
Analyzes the structure, methods, fields, and other information of a Java class.
**Parameters:**
- `className` (string): Full name of the Java class to analyze
- `projectPath` (string): Maven project root directory path
**Example:**
```json
{
"name": "analyze_class",
"arguments": {
"className": "com.example.QueryBizOrderDO",
"projectPath": "/path/to/your/maven/project",
}
}
```
### Cache Files
In the current project, the following cache directories and files are generated.
- `.mcp-class-index.json`: Class index cache file
- `.mcp-decompile-cache/`: Decompilation result cache directory (by package name structure)
> Explanation: From v1.0.1, the temporary class extraction directory has been moved to the system temporary directory (`os.tmpdir()/mcp-class-temp`), no longer polluting the project root directory's `.mcp-class-temp/`. Only when the system temporary directory is unavailable does it fall back to the user's home directory under `.mcp-class-temp/`.
## Workflow
1. **Automatic Indexing**: Automatically checks and creates indexes when `analyze_class` or `decompile_class` is called for the first time.
2. **Intelligent Caching**: Decompilation results are cached by package name structure, supporting cache control.
3. **Class Analysis**: Use `analyze_class` or `decompile_class` to obtain detailed class information.
4. **LLM Analysis**: Provide decompiled source code to LLM for code analysis.
## Technical Architecture
### Core Components
- **DependencyScanner**: Responsible for scanning Maven dependencies and establishing class indexes.
- **DecompilerService**: Responsible for decompiling .class files.
- **JavaClassAnalyzer**: Responsible for analyzing Java class structures.
- **MCP Server**: Provides standardized MCP interfaces.
### Dependency Scanning Process
1. Execute `mvn dependency:tree` to obtain the dependency tree.
2. Parse each JAR package and extract all .class files.
3. Establish a mapping index from "full class name -> JAR package path".
4. Cache the index to the `.mcp-class-index.json` file.
### Decompilation Process
1. Find the corresponding JAR package path based on the class name.
2. Check the cache; if it exists and cache is enabled, return directly.
3. Extract the .class file from the JAR package to the `.mcp-class-temp` directory (by package name structure).
4. Use the CFR tool to decompile the .class file.
5. Save the decompilation result to the cache `.mcp-decompile-cache` directory (by package name structure).
6. Return the Java source code.
## Troubleshooting
### Common Issues
1. **Maven Command Failure**
- Ensure Maven is installed and in PATH.
- Check if the project has a valid pom.xml file.
2. **CFR Decompilation Failure**
- Ensure the CFR jar package is downloaded (supports any version).
- Check if the Java environment is correctly configured.
- Specify the CFR path through the `cfrPath` parameter.
- Also, load automatically by setting the `CFR_PATH` environment variable or placing `cfr-*.jar` in the user's home directory / project `lib/` directory.
3. **Class Not Found**
- The program automatically checks and creates indexes.
- Check if the class name is correct (from v1.0.1, inputting simpleName can also try to match; if there are multiple classes with the same name, all full qualified candidates are listed).
- Ensure project dependencies are correctly resolved.
4. **macOS / Linux `javap` Call Failure**
- This issue is fixed in v1.0.1 (no longer hardcodes `javap.exe`).
- Confirm that `JAVA_HOME` is correctly set, or add `javap` to `PATH`.
## Test Instructions
### Build the Project
```bash
npm install
npm run build
```
### Test Tool Usage
The project provides an independent test tool that can directly test various functions of the MCP service without going through the MCP client.
```bash
# Test all tools
node test-tools.js
# Test a specific tool
node test-tools.js --tool decompile_class --class com.alibaba.excel.EasyExcelFactory --project /path/to/project
# Without cache
node test-tools.js --tool decompile_class --no-cache
# Specify CFR path
node test-tools.js --tool decompile_class --cfr-path /path/to/cfr.jar
```
### Test Tool Parameters
- `-t, --tool <tool name>`: Specify the tool to test (scan|decompile|analyze|all)
- `-p, --project <path>`: Project path
- `-c, --class <class name>`: Class name to analyze
- `--no-refresh`: Do not force refresh dependency index
- `--no-cache`: Do not use decompilation cache
- `--cfr-path <path>`: Specify the path to the CFR decompiler tool jar package
- `-h, --help`: Display help information
### Log Level Control
Control log output through the `NODE_ENV` environment variable:
- `development`: Output detailed debugging information
- `production`: Only output key information
MCP Config
Below is the configuration for this MCP Server. You can copy it directly to Cursor or other MCP clients.
mcp.json
Connection Info
You Might Also Like
No recommendations available