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; // 重新抛出错误,让上层处理
        }
    }

Tool Definition Quality

Score is being calculated. Check back soon.

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