Skip to content

zksite/java-class-view-mcp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

6 Commits
 
 
 
 
 
 
 
 

Repository files navigation

Java JAR Explorer MCP

A Model Context Protocol (MCP) server that provides comprehensive Java class analysis and exploration capabilities. This tool allows AI assistants to inspect Java classes, analyze dependencies, search for classes, and retrieve source code from JAR files and classpaths. Features include method-level source code extraction, smart decompilation, and precise code boundary detection.

Implementation Principles

Architecture Overview

The Java JAR Explorer MCP is built on the following core principles:

  1. MCP Protocol Integration: Implements the Model Context Protocol to expose Java analysis capabilities as standardized tools that AI assistants can use.

  2. Asynchronous Processing: Uses Python's asyncio for non-blocking operations, especially when executing external Java tools like javap.

  3. Classpath-Aware Analysis: Automatically detects and uses the system classpath, including support for custom JAVA_CLASSPATH environment variables.

  4. Multi-Source Class Discovery: Supports class analysis from multiple sources:

    • JAR files (including nested JARs)
    • Directory-based class files
    • JRT filesystem (Java 9+ module system)
    • System classpath
  5. Robust Error Handling: Implements comprehensive error handling with graceful degradation when tools or classes are unavailable.

Core Components

JavaClassViewer Class

The main engine that handles:

  • Classpath parsing and validation
  • Class structure analysis using javap
  • Source code extraction and decompilation
  • Method-level source code extraction with precise boundary detection
  • Dependency analysis
  • Class search across multiple sources

Data Models

  • ClassInfo: Represents complete class structure including fields, methods, constructors
  • ClassMember: Represents individual class members (fields, methods) with detailed signatures

Tool Integration

  • javap: Primary tool for class analysis and bytecode inspection
  • jar: For extracting source files from JAR archives
  • java: For classpath detection and validation

Advanced Features

  • Method-Level Analysis: Extract and analyze individual method source code
  • Smart Source Detection: Automatically detects original vs decompiled source
  • Line-Accurate Extraction: Precise method boundary detection for clean code extraction
  • Signature Analysis: Optional method signature inclusion for better context

Quick Start

1. Clone and Setup

First, clone this repository and install the required dependencies:

# Clone the repository
git clone https://github.com/zksite/java-class-view-mcp
cd java-class-view-mcp

# Install Python dependencies
pip install -r requirements.txt

2. MCP Configuration

To use this MCP server, add the following configuration to your MCP client:

{
  "java-jar-explorer": {
    "command": "python",
    "args": ["java-class-viewer.py"],
    "env": {
      "MAVEN_HOME": "",
      "JAVA_HOME": "",
      "JAVA_CLASSPATH": ""
    }
  }
}

Environment Variables Configuration

  • MAVEN_HOME: Path to your Maven installation (optional)
  • JAVA_HOME: Path to your Java installation (required)
  • JAVA_CLASSPATH: Custom classpath for analysis (optional, will use system classpath if not specified)

Example Configuration

{
  "java-jar-explorer": {
    "command": "python",
    "args": ["java-class-viewer.py"],
    "env": {
      "MAVEN_HOME": "C:\\Program Files\\Apache\\maven",
      "JAVA_HOME": "C:\\Program Files\\Java\\jdk-17",
      "JAVA_CLASSPATH": "C:\\myproject\\target\\classes;C:\\myproject\\lib\\*.jar"
    }
  }
}

Available Tools

The MCP server exposes the following tools for AI assistants:

1. view_class_structure

Purpose: Get complete structural information about a Java class

Parameters:

  • class_name (string): Fully qualified class name (e.g., 'java.lang.String')

Returns: Detailed class structure including:

  • Class metadata (name, package, modifiers, type)
  • Fields with types and modifiers
  • Methods with signatures and parameters
  • Constructors
  • Inheritance relationships
  • Inner classes

2. search_classes

Purpose: Search for Java classes matching specific patterns

Parameters:

  • pattern (string): Search pattern (supports wildcards and regex)
  • search_type (string): Type of search - "name", "package", "method", "field"
  • limit (integer): Maximum number of results (default: 20)

Returns: List of matching classes with location information

3. analyze_class_dependencies

Purpose: Analyze dependency relationships of a class

Parameters:

  • class_name (string): Fully qualified class name
  • depth (integer): Analysis depth (1=direct dependencies, 2=second-level, etc.)

Returns: Dependency tree showing class relationships

4. find_class_usages

Purpose: Find where a class is used throughout the codebase

Parameters:

  • class_name (string): Fully qualified class name
  • search_scope (string): Search scope - "classpath", "jar", "directory"

Returns: List of locations where the class is referenced

5. get_class_hierarchy

Purpose: Get inheritance hierarchy information for a class

Parameters:

  • class_name (string): Fully qualified class name

Returns: Inheritance tree showing:

  • Parent classes
  • Implemented interfaces
  • Class type (class, interface, enum, annotation)

6. find_class_location

Purpose: Locate the physical location of a class file

Parameters:

  • class_name (string): Fully qualified class name

Returns: Path to JAR file or directory containing the class

7. get_class_source

Purpose: Retrieve source code for a class

Parameters:

  • class_name (string): Fully qualified class name
  • decompile (boolean): Whether to decompile if source not available (default: true)

Returns: Source code with metadata:

  • Original source (if available in JAR)
  • Decompiled source (using javap)
  • Source type and location information

8. get_class_bytecode

Purpose: Get detailed bytecode information for a class

Parameters:

  • class_name (string): Fully qualified class name

Returns: Verbose bytecode output from javap including:

  • Constant pool
  • Method bytecode
  • Field information
  • Class metadata

9. get_method_source

Purpose: Extract source code for a specific method from a Java class

Parameters:

  • class_name (string): Fully qualified class name
  • method_name (string): Name of the method to extract
  • include_signature (boolean): Whether to include method signature (default: false)

Returns: Method source code information including:

  • Method source code
  • Method signature (if requested)
  • Line numbers and location information
  • Source type (original or decompiled)

10. get_classpath_info

Purpose: Get current classpath configuration and statistics

Parameters: None

Returns: Comprehensive classpath information:

  • Environment variables (JAVA_CLASSPATH, JAVA_HOME)
  • Current effective classpath
  • Statistics (JAR count, directory count, invalid paths)
  • Detailed path breakdown

Usage Examples

Basic Class Analysis

# Get structure of a specific class
result = await view_class_structure("java.util.ArrayList")

# Search for classes by name pattern
results = await search_classes("*List*", "name", 10)

Dependency Analysis

# Analyze direct dependencies
deps = await analyze_class_dependencies("com.example.MyClass", 1)

# Find where a class is used
usages = await find_class_usages("java.util.List", "classpath")

Source Code Retrieval

# Get complete class source code (with decompilation fallback)
source = await get_class_source("com.example.MyClass", True)

# Get specific method source code
method_source = await get_method_source("com.example.MyClass", "methodName", True)

# Get bytecode for detailed analysis
bytecode = await get_class_bytecode("com.example.MyClass")

Configuration

Environment Variables

  • JAVA_HOME: Path to Java installation
  • JAVA_CLASSPATH: Custom classpath (optional, overrides system classpath)

Requirements

  • Java 8 or higher
  • Python 3.7+
  • javap tool available in PATH
  • Access to target JAR files and classpaths

Error Handling

The tool implements robust error handling:

  • Graceful degradation when Java tools are unavailable
  • Clear error messages for missing classes or invalid classpaths
  • Fallback mechanisms for source code retrieval
  • Validation of input parameters and classpath entries

Performance Considerations

  • Asynchronous operations prevent blocking during long-running analysis
  • Classpath caching reduces repeated filesystem operations
  • Configurable search limits prevent overwhelming results
  • Efficient JAR scanning using zipfile operations

This MCP server enables AI assistants to perform sophisticated Java codebase analysis, making it easier to understand complex Java applications, analyze dependencies, and explore class relationships programmatically.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages