Skip to main content
Glama
handsomestWei

Java Class Analyzer MCP Server

decompile_class

Decompile Java class files to retrieve source code for analyzing dependencies and preventing AI hallucinations in generated code.

Instructions

反编译指定的Java类文件,返回Java源码

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
classNameYes要反编译的Java类全名,如:com.example.QueryBizOrderDO
projectPathYesMaven项目根目录路径
useCacheNo是否使用缓存,默认true
cfrPathNoCFR反编译工具的jar包路径,可选

Implementation Reference

  • The MCP tool handler for 'decompile_class'. Extracts input args, ensures dependency index exists, delegates to DecompilerService.decompileClass, handles empty results and errors, returns formatted text response with decompiled Java source code.
    private async handleDecompileClass(args: any) {
        const { className, projectPath, useCache = true, cfrPath } = args;
    
        try {
            console.error(`开始反编译类: ${className}, 项目路径: ${projectPath}, 使用缓存: ${useCache}, CFR路径: ${cfrPath || '自动查找'}`);
    
            // 检查索引是否存在,如果不存在则先创建
            await this.ensureIndexExists(projectPath);
    
            const sourceCode = await this.decompiler.decompileClass(className, projectPath, useCache, cfrPath);
    
            if (!sourceCode || sourceCode.trim() === '') {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `警告: 类 ${className} 的反编译结果为空,可能是CFR工具问题或类文件损坏`,
                        },
                    ],
                };
            }
    
            return {
                content: [
                    {
                        type: 'text',
                        text: `类 ${className} 的反编译源码:\n\n\`\`\`java\n${sourceCode}\n\`\`\``,
                    },
                ],
            };
        } catch (error) {
            console.error(`反编译类 ${className} 失败:`, error);
            return {
                content: [
                    {
                        type: 'text',
                        text: `反编译失败: ${error instanceof Error ? error.message : String(error)}\n\n建议:\n1. 确保已运行 scan_dependencies 建立类索引\n2. 检查CFR工具是否正确安装\n3. 验证类名是否正确`,
                    },
                ],
            };
        }
    }
  • Input schema for the 'decompile_class' tool as returned by ListToolsRequestHandler, defining parameters: className (required), projectPath (required), useCache (boolean, default true), cfrPath (optional string).
    {
        name: 'decompile_class',
        description: '反编译指定的Java类文件,返回Java源码',
        inputSchema: {
            type: 'object',
            properties: {
                className: {
                    type: 'string',
                    description: '要反编译的Java类全名,如:com.example.QueryBizOrderDO',
                },
                projectPath: {
                    type: 'string',
                    description: 'Maven项目根目录路径',
                },
                useCache: {
                    type: 'boolean',
                    description: '是否使用缓存,默认true',
                    default: true,
                },
                cfrPath: {
                    type: 'string',
                    description: 'CFR反编译工具的jar包路径,可选',
                },
            },
            required: ['className', 'projectPath'],
        },
    },
  • src/index.ts:29-31 (registration)
    Registration of the 'decompile_class' tool in the MCP server capabilities declaration.
    decompile_class: {
        description: '反编译指定的Java类文件,返回Java源码',
    },
  • Core helper method implementing the decompilation logic: handles CFR initialization, caching, JAR lookup via DependencyScanner, class file extraction from JAR using yauzl, CFR execution via child_process, and cleanup.
    async decompileClass(className: string, projectPath: string, useCache: boolean = true, cfrPath?: string): Promise<string> {
        try {
            // 如果外部指定了CFR路径,则使用外部路径
            if (cfrPath) {
                this.cfrPath = cfrPath;
                console.error(`使用外部指定的CFR工具路径: ${this.cfrPath}`);
            } else {
                await this.initializeCfrPath();
            }
    
            // 1. 检查缓存
            const cachePath = this.getCachePath(className, projectPath);
            if (useCache && await fs.pathExists(cachePath)) {
                console.error(`使用缓存的反编译结果: ${cachePath}`);
                return await readFile(cachePath, 'utf-8');
            }
    
            // 2. 查找类对应的JAR包
            console.error(`查找类 ${className} 对应的JAR包...`);
    
            // 添加超时处理
            const jarPath = await Promise.race([
                this.scanner.findJarForClass(className, projectPath),
                new Promise<null>((_, reject) =>
                    setTimeout(() => reject(new Error('查找JAR包超时')), 10000)
                )
            ]);
    
            if (!jarPath) {
                throw new Error(`未找到类 ${className} 对应的JAR包,请先运行 scan_dependencies 建立类索引`);
            }
            console.error(`找到JAR包: ${jarPath}`);
    
            // 3. 从JAR包中提取.class文件
            const classFilePath = await this.extractClassFile(jarPath, className);
    
            // 4. 使用CFR反编译
            const sourceCode = await this.decompileWithCfr(classFilePath);
    
            // 5. 保存到缓存
            if (useCache) {
                await fs.ensureDir(path.dirname(cachePath));
                await fs.outputFile(cachePath, sourceCode, 'utf-8');
                console.error(`反编译结果已缓存: ${cachePath}`);
            }
    
            // 6. 清理临时文件(只有在不使用缓存时才清理)
            if (!useCache) {
                try {
                    await fs.remove(classFilePath);
                    console.error(`清理临时文件: ${classFilePath}`);
                } catch (cleanupError) {
                    console.warn(`清理临时文件失败: ${cleanupError}`);
                }
            }
    
            return sourceCode;
        } catch (error) {
            console.error(`反编译类 ${className} 失败:`, error);
            throw error; // 重新抛出错误,让上层处理
        }
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions the output (Java source code) but doesn't cover important aspects like whether this is a read-only operation, potential performance impacts, error handling, or that it uses CFR tooling (only hinted in the schema). The description is minimal and lacks behavioral context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise - a single sentence that directly states the tool's purpose and output. Every word earns its place with no wasted text. It's appropriately sized for a straightforward decompilation tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given no annotations, no output schema, and a 4-parameter tool with mutation implications (decompilation typically involves processing/transformation), the description is insufficient. It doesn't explain what the tool actually does beyond the basic purpose, doesn't mention the CFR tool dependency, and provides no information about return format or error conditions.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so all parameters are documented in the schema. The description adds no additional parameter information beyond what's in the schema. The baseline score of 3 reflects adequate parameter documentation through the schema alone, with no value added by the description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('反编译' - decompile) and resource ('指定的Java类文件' - specified Java class file), and specifies the output ('返回Java源码' - returns Java source code). It doesn't explicitly differentiate from sibling tools like analyze_class or scan_dependencies, but the decompilation purpose is distinct enough to avoid confusion.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus the sibling tools (analyze_class, scan_dependencies). There's no mention of prerequisites, alternatives, or specific contexts where decompilation is preferred over analysis or dependency scanning.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

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/handsomestWei/java-class-analyzer-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server