@mustafagoksever/java-inspector 2.4.0 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +147 -261
- package/dist/analyzer/ApiDiff.d.ts +35 -0
- package/dist/analyzer/ApiDiff.d.ts.map +1 -0
- package/dist/analyzer/ApiDiff.js +199 -0
- package/dist/analyzer/ApiDiff.js.map +1 -0
- package/dist/analyzer/JavaClassAnalyzer.d.ts +16 -0
- package/dist/analyzer/JavaClassAnalyzer.d.ts.map +1 -1
- package/dist/analyzer/JavaClassAnalyzer.js +64 -10
- package/dist/analyzer/JavaClassAnalyzer.js.map +1 -1
- package/dist/analyzer/JdkSourceService.d.ts +17 -0
- package/dist/analyzer/JdkSourceService.d.ts.map +1 -0
- package/dist/analyzer/JdkSourceService.js +138 -0
- package/dist/analyzer/JdkSourceService.js.map +1 -0
- package/dist/cache/ProjectCache.d.ts +14 -1
- package/dist/cache/ProjectCache.d.ts.map +1 -1
- package/dist/cache/ProjectCache.js +122 -12
- package/dist/cache/ProjectCache.js.map +1 -1
- package/dist/decompiler/DecompilerService.d.ts +9 -2
- package/dist/decompiler/DecompilerService.d.ts.map +1 -1
- package/dist/decompiler/DecompilerService.js +114 -17
- package/dist/decompiler/DecompilerService.js.map +1 -1
- package/dist/index.d.ts +96 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1146 -606
- package/dist/index.js.map +1 -1
- package/dist/scanner/ArtifactService.d.ts +168 -0
- package/dist/scanner/ArtifactService.d.ts.map +1 -0
- package/dist/scanner/ArtifactService.js +828 -0
- package/dist/scanner/ArtifactService.js.map +1 -0
- package/dist/scanner/BackgroundScanner.d.ts.map +1 -1
- package/dist/scanner/BackgroundScanner.js +38 -26
- package/dist/scanner/BackgroundScanner.js.map +1 -1
- package/dist/scanner/ClassFileMetadataReader.d.ts +31 -0
- package/dist/scanner/ClassFileMetadataReader.d.ts.map +1 -0
- package/dist/scanner/ClassFileMetadataReader.js +215 -0
- package/dist/scanner/ClassFileMetadataReader.js.map +1 -0
- package/dist/scanner/DependencyScanner.d.ts +80 -0
- package/dist/scanner/DependencyScanner.d.ts.map +1 -1
- package/dist/scanner/DependencyScanner.js +401 -41
- package/dist/scanner/DependencyScanner.js.map +1 -1
- package/dist/scanner/JarIndexer.d.ts +73 -0
- package/dist/scanner/JarIndexer.d.ts.map +1 -0
- package/dist/scanner/JarIndexer.js +445 -0
- package/dist/scanner/JarIndexer.js.map +1 -0
- package/dist/scanner/JarScanCoordinator.d.ts +32 -0
- package/dist/scanner/JarScanCoordinator.d.ts.map +1 -0
- package/dist/scanner/JarScanCoordinator.js +124 -0
- package/dist/scanner/JarScanCoordinator.js.map +1 -0
- package/dist/scanner/LazyResolver.js +1 -1
- package/dist/scanner/LazyResolver.js.map +1 -1
- package/dist/scanner/ProjectDiscovery.d.ts +13 -0
- package/dist/scanner/ProjectDiscovery.d.ts.map +1 -0
- package/dist/scanner/ProjectDiscovery.js +84 -0
- package/dist/scanner/ProjectDiscovery.js.map +1 -0
- package/dist/utils/cachePaths.d.ts +3 -0
- package/dist/utils/cachePaths.d.ts.map +1 -1
- package/dist/utils/cachePaths.js +9 -0
- package/dist/utils/cachePaths.js.map +1 -1
- package/dist/utils/javaOutline.d.ts +70 -0
- package/dist/utils/javaOutline.d.ts.map +1 -0
- package/dist/utils/javaOutline.js +444 -0
- package/dist/utils/javaOutline.js.map +1 -0
- package/dist/utils/methodExtractor.d.ts +7 -0
- package/dist/utils/methodExtractor.d.ts.map +1 -1
- package/dist/utils/methodExtractor.js +50 -0
- package/dist/utils/methodExtractor.js.map +1 -1
- package/lib/vineflower-1.12.0.jar +0 -0
- package/package.json +8 -5
- package/lib/vineflower-1.11.2.jar +0 -0
package/dist/index.js
CHANGED
|
@@ -1,682 +1,1222 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
|
|
2
2
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
-
import {
|
|
4
|
-
import { JavaClassAnalyzer } from './analyzer/JavaClassAnalyzer.js';
|
|
5
|
-
import { DependencyScanner } from './scanner/DependencyScanner.js';
|
|
6
|
-
import { DecompilerService } from './decompiler/DecompilerService.js';
|
|
7
|
-
import { extractMethod, extractMethodMap, extractParamTypes, matchParamTypes } from './utils/methodExtractor.js';
|
|
3
|
+
import { z } from 'zod';
|
|
8
4
|
import { encode as toonEncode } from '@toon-format/toon';
|
|
9
5
|
import { fileURLToPath } from 'url';
|
|
10
6
|
import { readFileSync } from 'fs';
|
|
7
|
+
import { createHash } from 'crypto';
|
|
11
8
|
import * as path from 'path';
|
|
12
9
|
import fs from 'fs-extra';
|
|
10
|
+
import { JavaClassAnalyzer } from './analyzer/JavaClassAnalyzer.js';
|
|
11
|
+
import { jdkSourceService } from './analyzer/JdkSourceService.js';
|
|
12
|
+
import { diffApi } from './analyzer/ApiDiff.js';
|
|
13
|
+
import { DependencyScanner } from './scanner/DependencyScanner.js';
|
|
14
|
+
import { DecompilerService } from './decompiler/DecompilerService.js';
|
|
15
|
+
import { artifactService } from './scanner/ArtifactService.js';
|
|
16
|
+
import { jarIndexer } from './scanner/JarIndexer.js';
|
|
17
|
+
import { buildToolOf, projectDiscovery } from './scanner/ProjectDiscovery.js';
|
|
18
|
+
import { ClassFileMetadataReader } from './scanner/ClassFileMetadataReader.js';
|
|
19
|
+
import { getResultCacheDir } from './utils/cachePaths.js';
|
|
20
|
+
import { extractMethod, extractParamTypes, extractTypeDeclaration } from './utils/methodExtractor.js';
|
|
21
|
+
import { buildOutline, cleanDecompilerFailures, extractMembers, formatOutline, javapMemberAtLine, memberAtLine, memberRangeWithDoc, parseJavapMembers, selectJavapMembers } from './utils/javaOutline.js';
|
|
13
22
|
import { Logger } from './utils/Logger.js';
|
|
14
23
|
const __filename = fileURLToPath(import.meta.url);
|
|
15
24
|
const __dirname = path.dirname(__filename);
|
|
16
25
|
const { version } = JSON.parse(readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'));
|
|
26
|
+
/** Source files longer than this are not returned whole by default: outline + first lines instead. */
|
|
27
|
+
const SOURCE_AUTO_LIMIT = 400;
|
|
28
|
+
const SOURCE_AUTO_PREVIEW = 120;
|
|
29
|
+
/** javap -c output longer than this is replaced by the member list unless methodName/line is given. */
|
|
30
|
+
const BYTECODE_AUTO_LIMIT = 400;
|
|
31
|
+
/** Hard cap for any single tool response (~10k tokens). */
|
|
32
|
+
const MAX_RESPONSE_CHARS = 40_000;
|
|
33
|
+
class MemberNotFoundError extends Error {
|
|
34
|
+
memberName;
|
|
35
|
+
outline;
|
|
36
|
+
constructor(memberName, outline, paramTypes) {
|
|
37
|
+
const lower = memberName.toLowerCase();
|
|
38
|
+
const similar = [...new Set(outline.filter(member => (member.kind === 'method' || member.kind === 'constructor') && member.name.toLowerCase().includes(lower.substring(0, Math.max(3, lower.length - 2)))).map(member => member.signature))].slice(0, 15);
|
|
39
|
+
super(`Method not found: ${memberName}${paramTypes?.length ? `(${paramTypes.join(', ')})` : ''}.${similar.length ? `\nSimilar members:\n${similar.map(item => `- ${item}`).join('\n')}` : ' Use view=outline to list the members.'}`);
|
|
40
|
+
this.memberName = memberName;
|
|
41
|
+
this.outline = outline;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Sent to the client in the initialize response. Clients such as Claude Code and
|
|
46
|
+
* Cursor inject this into the model's context, which is what makes the agent pick
|
|
47
|
+
* these tools over shelling out to javap / unzip / jar / find ~/.m2.
|
|
48
|
+
*/
|
|
49
|
+
export const SERVER_INSTRUCTIONS = `java-inspector gives read-only access to compiled Java code: Maven/Gradle dependencies of the workspace, local JAR/WAR/Spring Boot fat JARs, and JDK classes.
|
|
50
|
+
|
|
51
|
+
Prefer these tools over shell commands for anything inside a JAR or the JDK:
|
|
52
|
+
- Instead of \`javap\` / \`javap -c\` / \`javap -p\`: inspect_class with view "api" (signatures) or "bytecode".
|
|
53
|
+
- Instead of decompiling by hand or guessing library behaviour: inspect_class with view "source" (uses -sources.jar when present, otherwise Vineflower). Large class: view "outline" first, then methodName for one method (inherited methods are found too). Stack-trace frame "Foo.java:123": pass line=123. Nested classes: Outer$Inner.
|
|
54
|
+
- For classes from the project's dependencies, pass only className (fully qualified). Do NOT look up the JAR in ~/.m2 / ~/.gradle or pass jarPath first: the server knows the project classpath and finds the JAR itself, waiting for Maven/Gradle if the project is opened for the first time.
|
|
55
|
+
- Instead of \`unzip -l\`, \`jar tf\`, \`find ~/.m2 -name\`, \`grep -r\` over JARs: search_class, find_jar, inspect_jar, search_resources, read_resource.
|
|
56
|
+
- Before upgrading a library, or for NoSuchMethodError/AbstractMethodError: compare_versions (API diff between two versions).
|
|
57
|
+
- Instead of \`mvn dependency:tree\` or reading pom.xml: list_dependencies (real versions, scope, direct/transitive); explain_dependency for why one artifact is there. For version conflicts / the same class in several JARs (NoSuchMethodError, ClassCastException): find_duplicates.
|
|
58
|
+
- To find who implements an interface or calls/declares a member or uses a string: find_implementations / search_code.
|
|
59
|
+
|
|
60
|
+
Workflow: inspect_class with the fully qualified name; if you only know the simple name, search_class first. No scan is required first: the classpath is resolved in the background at startup and tools return partial results with complete=false instead of waiting. When a result is ambiguous, the response lists candidates; repeat the call with jarPath set to one of them. All paths must be absolute.`;
|
|
61
|
+
const FORMAT = z.enum(['text', 'json', 'toon']).default('text').describe('"text": compact; "json": full structured result; "toon": compact structured.');
|
|
62
|
+
const MODE = z.enum(['fast', 'balanced']).default('balanced').describe('"fast" opens fewer unindexed JARs per call (quicker, more often partial).');
|
|
63
|
+
const num = (description) => z.coerce.number().int().optional().describe(description);
|
|
64
|
+
/** Shared by many tools, so kept short: every word here is repeated in tools/list once per tool. */
|
|
65
|
+
const SELECTOR = {
|
|
66
|
+
workspacePath: z.string().optional().describe('Absolute project directory (pom.xml or Gradle build, or a parent of several). Default: server cwd.'),
|
|
67
|
+
jarPath: z.string().optional().describe('Absolute path of one JAR. Not needed for project dependencies; use it for other JARs or to pick a listed candidate.'),
|
|
68
|
+
jarDirectory: z.string().optional().describe('Absolute directory of JARs to search (projects without Maven/Gradle, e.g. lib/).'),
|
|
69
|
+
jarNamePrefix: z.string().optional().describe('Only JARs whose file name starts with this, e.g. "jackson-databind".'),
|
|
70
|
+
coordinates: z.string().optional().describe('groupId:artifactId[:version[:classifier]] from the local Maven repository.'),
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* Shrink a structured result until its serialized size is <= MAX_RESPONSE_CHARS: repeatedly halve the
|
|
74
|
+
* largest array or string, then record what was dropped in `truncated`. The result is always valid JSON.
|
|
75
|
+
*/
|
|
76
|
+
export function shrinkStructured(value, size, max = MAX_RESPONSE_CHARS) {
|
|
77
|
+
const originalChars = size(value);
|
|
78
|
+
if (originalChars <= max)
|
|
79
|
+
return value;
|
|
80
|
+
const copy = JSON.parse(JSON.stringify(value));
|
|
81
|
+
const dropped = [];
|
|
82
|
+
for (let round = 0; round < 60 && size(copy) > max - 400; round++) {
|
|
83
|
+
let best = null;
|
|
84
|
+
const visit = (node, parent, key, nodePath) => {
|
|
85
|
+
if (typeof node === 'string' && node.length > 200) {
|
|
86
|
+
if (!best || node.length > best.weight)
|
|
87
|
+
best = { parent, key, path: nodePath, weight: node.length };
|
|
88
|
+
}
|
|
89
|
+
else if (Array.isArray(node)) {
|
|
90
|
+
if (node.length > 1) {
|
|
91
|
+
const weight = JSON.stringify(node).length;
|
|
92
|
+
if (!best || weight > best.weight)
|
|
93
|
+
best = { parent, key, path: nodePath, weight };
|
|
94
|
+
}
|
|
95
|
+
node.forEach((child, index) => visit(child, node, index, `${nodePath}[${index}]`));
|
|
96
|
+
}
|
|
97
|
+
else if (node && typeof node === 'object') {
|
|
98
|
+
for (const [childKey, child] of Object.entries(node))
|
|
99
|
+
visit(child, node, childKey, nodePath ? `${nodePath}.${childKey}` : childKey);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
visit(copy, null, '', '');
|
|
103
|
+
const target = best;
|
|
104
|
+
if (!target || target.parent === null)
|
|
105
|
+
break;
|
|
106
|
+
const current = target.parent[target.key];
|
|
107
|
+
if (typeof current === 'string') {
|
|
108
|
+
target.parent[target.key] = `${current.substring(0, Math.floor(current.length / 2))}\n[... truncated]`;
|
|
109
|
+
if (!dropped.includes(target.path.replace(/\[\d+\]/g, '[]')))
|
|
110
|
+
dropped.push(target.path.replace(/\[\d+\]/g, '[]'));
|
|
111
|
+
}
|
|
112
|
+
else {
|
|
113
|
+
target.parent[target.key] = current.slice(0, Math.max(1, Math.floor(current.length / 2)));
|
|
114
|
+
const label = `${target.path.replace(/\[\d+\]/g, '[]')}`;
|
|
115
|
+
if (!dropped.includes(label))
|
|
116
|
+
dropped.push(label);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
copy.truncated = { originalChars, maxChars: max, shortened: dropped, note: 'Result shortened to fit the response limit; narrow the request (query, limit, className, methodName) for the rest.' };
|
|
120
|
+
return copy;
|
|
121
|
+
}
|
|
122
|
+
const READ_ONLY = { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false };
|
|
17
123
|
export class JavaClassAnalyzerMCPServer {
|
|
18
|
-
|
|
19
|
-
analyzer;
|
|
20
|
-
scanner;
|
|
21
|
-
|
|
124
|
+
mcp;
|
|
125
|
+
analyzer = new JavaClassAnalyzer();
|
|
126
|
+
scanner = new DependencyScanner();
|
|
127
|
+
sourceDownloads = new Map();
|
|
128
|
+
decompiler = new DecompilerService();
|
|
129
|
+
/** Low-level protocol server (kept for tests and advanced use). */
|
|
130
|
+
get server() { return this.mcp.server; }
|
|
22
131
|
constructor() {
|
|
23
|
-
this.
|
|
24
|
-
name: 'java-inspector',
|
|
25
|
-
version,
|
|
26
|
-
}, {
|
|
27
|
-
capabilities: {
|
|
28
|
-
tools: {},
|
|
29
|
-
logging: {},
|
|
30
|
-
},
|
|
31
|
-
});
|
|
32
|
-
this.analyzer = new JavaClassAnalyzer();
|
|
33
|
-
this.scanner = new DependencyScanner();
|
|
34
|
-
this.decompiler = new DecompilerService();
|
|
132
|
+
this.mcp = new McpServer({ name: 'java-inspector', title: 'Java Inspector', version }, { capabilities: { tools: {}, logging: {} }, instructions: SERVER_INSTRUCTIONS });
|
|
35
133
|
this.setupHandlers();
|
|
36
134
|
}
|
|
37
135
|
setupHandlers() {
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
},
|
|
56
|
-
format: {
|
|
57
|
-
type: 'string',
|
|
58
|
-
enum: ['text', 'json', 'toon'],
|
|
59
|
-
description: 'Output format. Default is text (human-readable). Use json for structured machine-readable data. Use toon for Token-Oriented Object Notation — a compact, LLM-friendly format that reduces tokens by ~40% compared to JSON while preserving structure (https://github.com/toon-format/toon).',
|
|
60
|
-
default: 'text',
|
|
61
|
-
},
|
|
62
|
-
},
|
|
63
|
-
required: ['projectPath'],
|
|
64
|
-
},
|
|
65
|
-
},
|
|
66
|
-
{
|
|
67
|
-
name: 'decompile_class',
|
|
68
|
-
description: 'Decompile a Java class from Maven dependency JARs into readable Java source code using the Vineflower decompiler. IMPORTANT: This tool works ONLY with classes from Maven dependencies (external libraries listed in pom.xml), NOT the project\'s own source files — use your file reading tools for project source code. Use this when you need to understand how a library class works internally, see method implementations, or debug dependency behavior. Supports extracting a single method with methodName/paramTypes, and pagination with offset/limit for large classes.',
|
|
69
|
-
inputSchema: {
|
|
70
|
-
type: 'object',
|
|
71
|
-
properties: {
|
|
72
|
-
className: {
|
|
73
|
-
type: 'string',
|
|
74
|
-
description: 'Fully qualified class name from a Maven dependency JAR (e.g., org.springframework.web.bind.annotation.RequestMapping, io.micrometer.observation.ObservationRegistry). Must be a class from an external dependency, not from the project\'s own source code.',
|
|
75
|
-
},
|
|
76
|
-
projectPath: {
|
|
77
|
-
type: 'string',
|
|
78
|
-
description: 'Absolute path to the Maven project root directory (the directory containing pom.xml)',
|
|
79
|
-
},
|
|
80
|
-
useCache: {
|
|
81
|
-
type: 'boolean',
|
|
82
|
-
description: 'Whether to use cache, default true',
|
|
83
|
-
default: true,
|
|
84
|
-
},
|
|
85
|
-
decompilerPath: {
|
|
86
|
-
type: 'string',
|
|
87
|
-
description: 'JAR package path of Vineflower decompiler, optional',
|
|
88
|
-
},
|
|
89
|
-
methodName: {
|
|
90
|
-
type: 'string',
|
|
91
|
-
description: 'Optional method name to extract instead of the full class. When provided, only the method body is returned.',
|
|
92
|
-
},
|
|
93
|
-
paramTypes: {
|
|
94
|
-
type: 'array',
|
|
95
|
-
items: { type: 'string' },
|
|
96
|
-
description: 'Optional: filter method overloads by parameter types (e.g. ["String", "int"]). Use when multiple methods with the same name exist.',
|
|
97
|
-
},
|
|
98
|
-
offset: {
|
|
99
|
-
type: 'number',
|
|
100
|
-
description: 'Start line number (1-based, default: 1)',
|
|
101
|
-
default: 1,
|
|
102
|
-
},
|
|
103
|
-
limit: {
|
|
104
|
-
type: 'number',
|
|
105
|
-
description: 'Max lines to return (0 = all lines)',
|
|
106
|
-
default: 0,
|
|
107
|
-
},
|
|
108
|
-
format: {
|
|
109
|
-
type: 'string',
|
|
110
|
-
enum: ['text', 'json', 'toon'],
|
|
111
|
-
description: 'Output format. Default is text (human-readable). Use json for structured machine-readable data. Use toon for Token-Oriented Object Notation — a compact, LLM-friendly format that reduces tokens by ~40% compared to JSON while preserving structure (https://github.com/toon-format/toon).',
|
|
112
|
-
default: 'text',
|
|
113
|
-
},
|
|
114
|
-
},
|
|
115
|
-
required: ['className', 'projectPath'],
|
|
116
|
-
},
|
|
117
|
-
},
|
|
118
|
-
{
|
|
119
|
-
name: 'analyze_class',
|
|
120
|
-
description: 'Get the structure (fields, methods, constructors, superclass, interfaces) of a Java class from Maven dependency JARs using javap — signatures only, no method bodies. IMPORTANT: This tool works ONLY with classes from Maven dependencies (external libraries in pom.xml), NOT the project\'s own source files. Use this instead of decompile_class when you only need the API surface (e.g., available methods, field types, class hierarchy) without the full implementation. Much faster than decompilation.',
|
|
121
|
-
inputSchema: {
|
|
122
|
-
type: 'object',
|
|
123
|
-
properties: {
|
|
124
|
-
className: {
|
|
125
|
-
type: 'string',
|
|
126
|
-
description: 'Fully qualified class name from a Maven dependency JAR (e.g., org.springframework.web.bind.annotation.RequestMapping, io.micrometer.observation.ObservationRegistry). Must be a class from an external dependency, not from the project\'s own source code.',
|
|
127
|
-
},
|
|
128
|
-
projectPath: {
|
|
129
|
-
type: 'string',
|
|
130
|
-
description: 'Absolute path to the Maven project root directory (the directory containing pom.xml)',
|
|
131
|
-
},
|
|
132
|
-
filter: {
|
|
133
|
-
type: 'string',
|
|
134
|
-
enum: ['all', 'public', 'private', 'protected', 'fields', 'methods'],
|
|
135
|
-
description: 'Filter members by visibility or type',
|
|
136
|
-
default: 'all'
|
|
137
|
-
},
|
|
138
|
-
format: {
|
|
139
|
-
type: 'string',
|
|
140
|
-
enum: ['text', 'json', 'toon'],
|
|
141
|
-
description: 'Output format. Default is text (human-readable). Use json for structured machine-readable data. Use toon for Token-Oriented Object Notation — a compact, LLM-friendly format that reduces tokens by ~40% compared to JSON while preserving structure (https://github.com/toon-format/toon).',
|
|
142
|
-
default: 'text',
|
|
143
|
-
},
|
|
144
|
-
},
|
|
145
|
-
required: ['className', 'projectPath'],
|
|
146
|
-
},
|
|
147
|
-
},
|
|
148
|
-
{
|
|
149
|
-
name: 'search_class',
|
|
150
|
-
description: 'Search for Java classes by name within the project\'s Maven dependency JARs (fuzzy matching). IMPORTANT: This searches ONLY classes from Maven dependencies (external libraries in pom.xml), NOT the project\'s own source files. Use this to find the fully qualified class name before calling decompile_class or analyze_class. Example queries: \'JpaRepository\', \'HttpClient\', \'ObjectMapper\'. Results may be partial if the background scan is still in progress.',
|
|
151
|
-
inputSchema: {
|
|
152
|
-
type: 'object',
|
|
153
|
-
properties: {
|
|
154
|
-
query: {
|
|
155
|
-
type: 'string',
|
|
156
|
-
description: 'Search query — partial or full class name from Maven dependencies (e.g. "JpaRepository", "HttpClient", "ObjectMapper")',
|
|
157
|
-
},
|
|
158
|
-
projectPath: {
|
|
159
|
-
type: 'string',
|
|
160
|
-
description: 'Absolute path to the Maven project root directory (the directory containing pom.xml)',
|
|
161
|
-
},
|
|
162
|
-
limit: {
|
|
163
|
-
type: 'number',
|
|
164
|
-
description: 'Maximum number of results to return',
|
|
165
|
-
default: 20,
|
|
166
|
-
},
|
|
167
|
-
format: {
|
|
168
|
-
type: 'string',
|
|
169
|
-
enum: ['text', 'json', 'toon'],
|
|
170
|
-
description: 'Output format. Default is text (human-readable). Use json for structured machine-readable data. Use toon for Token-Oriented Object Notation — a compact, LLM-friendly format that reduces tokens by ~40% compared to JSON while preserving structure (https://github.com/toon-format/toon).',
|
|
171
|
-
default: 'text',
|
|
172
|
-
},
|
|
173
|
-
},
|
|
174
|
-
required: ['query', 'projectPath'],
|
|
175
|
-
},
|
|
176
|
-
},
|
|
177
|
-
{
|
|
178
|
-
name: 'get_inheritance_tree',
|
|
179
|
-
description: 'Get the full inheritance chain (superclasses and interfaces) of a Java class from Maven dependency JARs. IMPORTANT: This tool works ONLY with classes from Maven dependencies (external libraries in pom.xml), NOT the project\'s own source files. Use this to understand class hierarchies, find parent classes, and discover which interfaces a dependency class implements. Classes not found in dependencies are marked as unresolved.',
|
|
180
|
-
inputSchema: {
|
|
181
|
-
type: 'object',
|
|
182
|
-
properties: {
|
|
183
|
-
className: {
|
|
184
|
-
type: 'string',
|
|
185
|
-
description: 'Fully qualified class name from a Maven dependency JAR (e.g., org.springframework.web.bind.annotation.RequestMapping, io.micrometer.observation.ObservationRegistry). Must be a class from an external dependency, not from the project\'s own source code.',
|
|
186
|
-
},
|
|
187
|
-
projectPath: {
|
|
188
|
-
type: 'string',
|
|
189
|
-
description: 'Absolute path to the Maven project root directory (the directory containing pom.xml)',
|
|
190
|
-
},
|
|
191
|
-
format: {
|
|
192
|
-
type: 'string',
|
|
193
|
-
enum: ['text', 'json', 'toon'],
|
|
194
|
-
description: 'Output format. Default is text (human-readable). Use json for structured machine-readable data. Use toon for Token-Oriented Object Notation — a compact, LLM-friendly format that reduces tokens by ~40% compared to JSON while preserving structure (https://github.com/toon-format/toon).',
|
|
195
|
-
default: 'text',
|
|
196
|
-
},
|
|
197
|
-
},
|
|
198
|
-
required: ['className', 'projectPath'],
|
|
199
|
-
},
|
|
200
|
-
},
|
|
201
|
-
],
|
|
202
|
-
};
|
|
203
|
-
});
|
|
204
|
-
this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
205
|
-
const { name, arguments: args } = request.params;
|
|
206
|
-
const sendProgress = async (message, progress, total) => {
|
|
207
|
-
if (extra._meta?.progressToken !== undefined) {
|
|
208
|
-
await extra.sendNotification({
|
|
209
|
-
method: 'notifications/progress',
|
|
210
|
-
params: {
|
|
211
|
-
progressToken: extra._meta.progressToken,
|
|
212
|
-
progress,
|
|
213
|
-
total,
|
|
214
|
-
message
|
|
215
|
-
}
|
|
216
|
-
});
|
|
136
|
+
const register = (name, title, description, inputSchema, handler) => {
|
|
137
|
+
this.mcp.registerTool(name, { title, description, inputSchema, annotations: { title, ...READ_ONLY } }, async (args, extra) => {
|
|
138
|
+
const sendProgress = async (message, progress, total) => {
|
|
139
|
+
const progressToken = extra?._meta?.progressToken;
|
|
140
|
+
if (progressToken === undefined)
|
|
141
|
+
return;
|
|
142
|
+
// MCP requires a numeric progress value on every progress notification.
|
|
143
|
+
await extra.sendNotification({ method: 'notifications/progress', params: { progressToken, message, progress: progress ?? 0, total } }).catch(() => { });
|
|
144
|
+
};
|
|
145
|
+
try {
|
|
146
|
+
// Must be awaited: returning the bare promise would let rejections escape this
|
|
147
|
+
// try/catch and surface as JSON-RPC protocol errors instead of tool errors the model can read.
|
|
148
|
+
return await handler(args, sendProgress);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
152
|
+
return { content: [{ type: 'text', text: `Tool call failed: ${message}` }], isError: true };
|
|
217
153
|
}
|
|
218
|
-
|
|
154
|
+
});
|
|
155
|
+
};
|
|
156
|
+
register('scan_project', 'Scan dependencies', 'Start, refresh, or poll the background index of a workspace\'s dependency JARs (Maven or Gradle). Returns immediately. ' +
|
|
157
|
+
'Usually NOT needed: the server auto-scans the top-level Maven/Gradle builds under its cwd at startup and every other tool works on a partial index. ' +
|
|
158
|
+
'Call it to index a different workspace, to check progress, or with forceRefresh=true after build files change.', { workspacePath: z.string().describe('Absolute project directory (pom.xml or Gradle build, or a parent of several).'), forceRefresh: z.boolean().default(false).describe('Drop the cached classpath/index and resolve it again.'), format: FORMAT }, (args, progress) => this.handleScanProject(args, progress));
|
|
159
|
+
register('find_jar', 'Find JAR', 'Locate dependency/local JAR files by file name prefix, substring, exact name, or Maven coordinates, without opening them. ' +
|
|
160
|
+
'Use instead of `find ~/.m2 -name "*.jar"` or `ls lib/`. Returns absolute jarPath values usable as the jarPath selector of other tools.', { ...SELECTOR, match: z.enum(['exact', 'prefix', 'contains']).default('prefix').describe('How jarNamePrefix / the coordinates artifactId is matched against JAR file names.'), limit: num('Max results (1-100, default 20).'), format: FORMAT }, args => this.handleFindJar(args));
|
|
161
|
+
register('inspect_jar', 'Inspect JAR contents', 'List what is inside ONE JAR: manifest, Maven coordinates (pom.properties), layout (plain, Spring Boot, WAR, multi-release), packages, classes, resources and nested JARs. ' +
|
|
162
|
+
'Use instead of `unzip -l` / `jar tf`. If the selector matches several JARs, candidates are returned; repeat with jarPath. Entries are paginated with offset/limit and can be filtered with query.', { ...SELECTOR, query: z.string().optional().describe('Case-insensitive substring filter on class names and resource paths.'), offset: num('1-based index of the first entry to return (default 1).'), limit: num('Max entries to return (1-1000, default 100).'), format: FORMAT }, args => this.handleInspectJar(args));
|
|
163
|
+
register('search_class', 'Search classes', 'Find classes by simple name, fully qualified name, or partial name (e.g. "ObjectMapper", "jackson ObjectMapper", "web.client.RestTemplate") across the workspace\'s dependencies, a JAR directory, or one JAR. ' +
|
|
164
|
+
'First step before inspect_class when the package is unknown. Uses the live (possibly still-building) index and opens unindexed JARs on demand; complete=false means more JARs remain, so call again or narrow with jarNamePrefix. ' +
|
|
165
|
+
'Use instead of `unzip -l *.jar | grep` or `find ~/.m2`.', { query: z.string().describe('Class name or fragment. Space/dot separated parts must all appear in the fully qualified name.'), ...SELECTOR, includeJdk: z.boolean().default(false).describe('Also search JDK classes (java.*, javax.*, jdk.*).'), mode: MODE, limit: num('Max results (1-100, default 20).'), format: FORMAT }, (args, progress) => this.handleSearchClass(args, progress));
|
|
166
|
+
register('search_code', 'Search compiled code', 'Search bytecode metadata without decompiling: method or field declarations by name, annotations, references (calls/field accesses to an owner#member), or string constants (e.g. an exception message or config key). ' +
|
|
167
|
+
'Use to answer "where is this log/error message thrown?", "who calls RestTemplate#exchange?", "which classes are annotated @AutoConfiguration?". Use instead of `grep` over decompiled code or `javap -c | grep`. ' +
|
|
168
|
+
'Deep indexes are built lazily per JAR; complete=false means some JARs were not searched yet. Calling again continues where it stopped; narrowing with jarNamePrefix/jarPath is faster.', { query: z.string().describe('Case-insensitive substring. For kind=reference you may use "Owner#member" or "com.foo.Owner.member".'), kind: z.enum(['method', 'field', 'annotation', 'reference', 'string']).describe('What to search.'), ...SELECTOR, mode: MODE, limit: num('Max matches (1-100, default 20).'), format: FORMAT }, (args, progress) => this.handleSearchCode(args, progress));
|
|
169
|
+
register('find_implementations', 'Find implementations', 'Find classes that implement an interface or extend a class (direct or transitive) across dependency JARs, using lazily built bytecode indexes. ' +
|
|
170
|
+
'Use for "what implementations of HttpMessageConverter exist?", SPI lookups, etc. complete=false means more JARs remain; call again to continue.', { className: z.string().describe('Fully qualified name of the interface or superclass, e.g. "org.springframework.core.convert.converter.Converter".'), ...SELECTOR, transitive: z.boolean().default(true).describe('Include indirect subtypes (subclass of an implementation, sub-interfaces).'), mode: MODE, limit: num('Max results (1-200, default 50).'), format: FORMAT }, (args, progress) => this.handleFindImplementations(args, progress));
|
|
171
|
+
register('find_duplicates', 'Find duplicate classes', 'List classes that exist in more than one JAR of the classpath: the same artifact in two versions, split packages, or shaded/relocated copies (typical causes of NoSuchMethodError, ClassCastException, "works in IDE, fails in prod"). ' +
|
|
172
|
+
'Groups duplicates by the set of JARs that share them, with Maven coordinates, class counts and sample classes. Use instead of comparing `jar tf` listings by hand; then explain_dependency tells why each JAR is on the classpath. ' +
|
|
173
|
+
'complete=false means some JARs were not indexed yet; call again.', {
|
|
174
|
+
...SELECTOR,
|
|
175
|
+
query: z.string().optional().describe('Only report duplicate classes whose fully qualified name contains this (case-insensitive), e.g. "org.slf4j" or "Logger".'),
|
|
176
|
+
limit: num('Max JAR groups (1-200, default 30).'),
|
|
177
|
+
classLimit: num('Sample classes listed per group (1-100, default 10).'),
|
|
178
|
+
mode: MODE,
|
|
179
|
+
format: FORMAT,
|
|
180
|
+
}, (args, progress) => this.handleFindDuplicates(args, progress));
|
|
181
|
+
register('inspect_class', 'Inspect / decompile class', 'Read a Java class from a project dependency, local JAR, or the JDK. Use instead of javap, unzip or a decompiler in the shell. ' +
|
|
182
|
+
'view="source": real source from a -sources.jar if present, otherwise decompiled with Vineflower; files over 400 lines return the first lines plus an outline. view="outline": members with line ranges (cheapest way to see a large class). ' +
|
|
183
|
+
'view="api": compact member signatures (replaces `javap -p`). view="bytecode": `javap -c` (per method with methodName). view="hierarchy": superclass chain and interfaces. view="all": everything. ' +
|
|
184
|
+
'Efficient pattern: outline (or api) first, then methodName for the code you need. For a stack trace, pass line. For project dependencies pass ONLY className: the JAR comes from the classpath (do not locate it in ~/.m2). Use search_class first if you only know part of the name.', {
|
|
185
|
+
className: z.string().describe('Fully qualified class name, e.g. "com.fasterxml.jackson.databind.ObjectMapper". Nested classes: "com.acme.Outer$Inner" (or "com.acme.Outer.Inner"); view=source then returns just the nested declaration.'),
|
|
186
|
+
...SELECTOR,
|
|
187
|
+
view: z.enum(['source', 'outline', 'api', 'hierarchy', 'bytecode', 'all']).default('source').describe('Which view to return.'),
|
|
188
|
+
methodName: z.string().optional().describe('source/bytecode: return just this method or constructor (all overloads unless paramTypes is given). If the class does not declare it, superclasses and interfaces are searched.'),
|
|
189
|
+
paramTypes: z.array(z.string()).optional().describe('Simple or qualified parameter type names to select one overload, e.g. ["String", "int"].'),
|
|
190
|
+
line: num('Source line from a stack trace, e.g. 123 from "at com.acme.Foo.bar(Foo.java:123)": returns the method containing it (also for decompiled code, via the line table).'),
|
|
191
|
+
offset: num('view=source: 1-based first line to return (default 1).'),
|
|
192
|
+
limit: num(`view=source: number of lines to return. Default: whole file up to ${SOURCE_AUTO_LIMIT} lines; larger files return the first ${SOURCE_AUTO_PREVIEW} lines plus an outline.`),
|
|
193
|
+
useCache: z.boolean().default(true).describe('Reuse cached decompiled source.'),
|
|
194
|
+
downloadSources: z.boolean().optional().describe('Maven: download a missing -sources.jar (`mvn dependency:get`, network) instead of decompiling. Default: env JAVA_INSPECTOR_DOWNLOAD_SOURCES.'),
|
|
195
|
+
format: FORMAT,
|
|
196
|
+
}, (args, progress) => this.handleInspectClass(args, progress));
|
|
197
|
+
register('explain_dependency', 'Explain dependency', 'Explain why an artifact is on the classpath: runs a filtered `mvn dependency:tree -Dincludes=<coordinates> -Dverbose` for each Maven project in the workspace (paths from root to the artifact, conflicts, omitted versions). ' +
|
|
198
|
+
'Use instead of running mvn dependency:tree yourself. Slower (runs Maven).', { workspacePath: z.string().optional().describe('Absolute workspace path containing pom.xml. Defaults to the server cwd.'), coordinates: z.string().optional().describe('groupId:artifactId (or groupId only). Optional if jarPath is given.'), jarPath: z.string().optional().describe('Absolute JAR path; coordinates are read from its pom.properties.'), format: FORMAT }, (args, progress) => this.handleExplainDependency(args, progress));
|
|
199
|
+
register('compare_versions', 'Compare API between versions', 'Binary API diff of a library between two versions (or any two JARs): added/removed classes, and per class the public/protected methods and fields that were added, removed or changed (visibility, static, final, abstract, supertypes), with breaking changes flagged. ' +
|
|
200
|
+
'Use before upgrading a dependency, or to explain NoSuchMethodError/AbstractMethodError, instead of decompiling both versions and comparing by hand. ' +
|
|
201
|
+
'Give coordinates + toVersion (fromVersion defaults to the version on the project classpath), or fromJarPath + toJarPath. Then inspect_class with jarPath shows the code of a changed member.', {
|
|
202
|
+
coordinates: z.string().optional().describe('groupId:artifactId, e.g. "com.fasterxml.jackson.core:jackson-databind".'),
|
|
203
|
+
fromVersion: z.string().optional().describe('Old version. Default: the version on the workspace classpath.'),
|
|
204
|
+
toVersion: z.string().optional().describe('New version (required with coordinates).'),
|
|
205
|
+
fromJarPath: z.string().optional().describe('Absolute path of the old JAR (instead of coordinates/fromVersion).'),
|
|
206
|
+
toJarPath: z.string().optional().describe('Absolute path of the new JAR (instead of coordinates/toVersion).'),
|
|
207
|
+
className: z.string().optional().describe('Compare only this class (fully qualified; its nested classes are included).'),
|
|
208
|
+
packagePrefix: z.string().optional().describe('Compare only classes in this package and its subpackages, e.g. "org.apache.commons.lang3.time".'),
|
|
209
|
+
download: z.boolean().default(false).describe('Download a version missing from ~/.m2 with `mvn dependency:get` (network).'),
|
|
210
|
+
workspacePath: z.string().optional().describe('Absolute workspace path used to find the classpath version. Defaults to the server cwd.'),
|
|
211
|
+
limit: num('Max changed classes listed in the text output (1-500, default 40).'),
|
|
212
|
+
format: FORMAT,
|
|
213
|
+
}, (args, progress) => this.handleCompareVersions(args, progress));
|
|
214
|
+
register('list_dependencies', 'List Maven dependencies', 'Resolved dependencies of every Maven module in the workspace with groupId:artifactId:version, scope, and whether each is direct (declared in the pom) or transitive (with the path that pulls it in). ' +
|
|
215
|
+
'Use instead of running `mvn dependency:tree` or reading pom.xml files to find out which version of a library the project really uses. Runs Maven once, then cached until pom.xml changes.', {
|
|
216
|
+
workspacePath: z.string().optional().describe('Absolute workspace path containing pom.xml. Defaults to the server cwd.'),
|
|
217
|
+
query: z.string().optional().describe('Only dependencies whose groupId:artifactId contains this (case-insensitive), e.g. "jackson" or "org.slf4j"; each match is shown with its path from the module.'),
|
|
218
|
+
directOnly: z.boolean().default(false).describe('Only dependencies declared directly in the module poms.'),
|
|
219
|
+
scope: z.string().optional().describe('Only this scope: compile, runtime, test, provided, system or import.'),
|
|
220
|
+
limit: num('Max dependency lines in the text output (1-2000, default 300).'),
|
|
221
|
+
format: FORMAT,
|
|
222
|
+
}, (args, progress) => this.handleListDependencies(args, progress));
|
|
223
|
+
register('search_resources', 'Search JAR resources', 'Find non-class files inside JARs (META-INF/spring/*.imports, META-INF/services/*, *.properties, *.xml, *.json ...) by path substring and optionally by text content. ' +
|
|
224
|
+
'Use instead of `unzip -p x.jar | grep`. Then use read_resource to read a match.', { ...SELECTOR, pathQuery: z.string().default('').describe('Case-insensitive substring of the resource path, e.g. "META-INF/services".'), contentQuery: z.string().optional().describe('Case-insensitive text to look for inside text resources (<= 1 MB).'), limit: num('Max results (1-100, default 20).'), format: FORMAT }, args => this.handleSearchResources(args));
|
|
225
|
+
register('read_resource', 'Read JAR resource', 'Read one text resource from inside a JAR (exact path as returned by search_resources/inspect_jar), paginated by lines. Binary resources are rejected. Use instead of `unzip -p`.', { ...SELECTOR, resourcePath: z.string().describe('Exact entry path inside the JAR, e.g. "META-INF/spring.factories".'), offset: num('1-based first line (default 1).'), limit: num('Number of lines (1-1000, default 200).'), format: FORMAT }, args => this.handleReadResource(args));
|
|
226
|
+
}
|
|
227
|
+
async handleScanProject(args, sendProgress) {
|
|
228
|
+
const workspacePath = await this.validateWorkspacePath(args.workspacePath);
|
|
229
|
+
const pomRoots = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
230
|
+
if (pomRoots.length === 0) {
|
|
231
|
+
const structured = { workspacePath, status: 'no_maven_project', pomRoots: [], message: 'Direct/local JAR tools remain available.' };
|
|
232
|
+
return this.formatResponse('No Maven project found. Direct and local JAR inspection is available.', structured, args.format);
|
|
233
|
+
}
|
|
234
|
+
await sendProgress?.(`Starting/polling ${pomRoots.length} Maven context(s)`, 0, pomRoots.length);
|
|
235
|
+
const projects = [];
|
|
236
|
+
for (let i = 0; i < pomRoots.length; i++) {
|
|
237
|
+
const result = await this.scanner.scanProject(pomRoots[i], Boolean(args.forceRefresh), async (message) => sendProgress?.(`[${path.basename(pomRoots[i])}] ${message}`, i, pomRoots.length));
|
|
238
|
+
projects.push({ projectPath: pomRoots[i], ...result });
|
|
239
|
+
}
|
|
240
|
+
const complete = projects.every(project => project.status === 'complete');
|
|
241
|
+
const structured = { workspacePath, status: complete ? 'complete' : 'in_progress', pomRoots, projects };
|
|
242
|
+
const text = complete ? `Scan complete for ${pomRoots.length} top-level project(s).` : `Auto-scan is running for ${pomRoots.length} top-level project(s). Tools can be used immediately.`;
|
|
243
|
+
return this.formatResponse(text, structured, args.format);
|
|
244
|
+
}
|
|
245
|
+
async handleFindJar(args) {
|
|
246
|
+
const selector = await this.selectorFromArgs(args);
|
|
247
|
+
const result = await artifactService.findJars(selector, args.match ?? 'prefix', this.clamp(args.limit, 1, 100, 20));
|
|
248
|
+
let text = result.results.length ? `Found ${result.results.length} JAR(s):\n${result.results.map(item => `- ${item.jarPath} (${item.origin})`).join('\n')}` : 'No matching JAR found.';
|
|
249
|
+
if (!result.complete)
|
|
250
|
+
text += '\n\nJAR search is partial.';
|
|
251
|
+
if (result.errors.length)
|
|
252
|
+
text += `\n${result.errors.map(error => `- ${error.contextPath ?? error.jarPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
253
|
+
return this.formatResponse(text, result, args.format);
|
|
254
|
+
}
|
|
255
|
+
async handleInspectJar(args) {
|
|
256
|
+
const inspected = await artifactService.inspectJar(await this.selectorFromArgs(args));
|
|
257
|
+
if (!inspected.index)
|
|
258
|
+
return this.ambiguityResponse('JAR selector', inspected.candidates ?? [], args.format);
|
|
259
|
+
const index = inspected.index;
|
|
260
|
+
const query = String(args.query ?? '').toLowerCase();
|
|
261
|
+
const offset = this.clamp(args.offset, 1, Number.MAX_SAFE_INTEGER, 1);
|
|
262
|
+
const limit = this.clamp(args.limit, 1, 1000, 100);
|
|
263
|
+
const classes = index.classes.filter(item => !item.isInner && (!query || item.className.toLowerCase().includes(query)));
|
|
264
|
+
const resources = index.resources.filter(item => !query || item.path.toLowerCase().includes(query));
|
|
265
|
+
const entries = [
|
|
266
|
+
...classes.map(item => ({ type: item.isSource ? 'source' : 'class', path: item.entryPath, className: item.className })),
|
|
267
|
+
...resources.map(item => ({ type: 'resource', path: item.path, size: item.size })),
|
|
268
|
+
].slice(offset - 1, offset - 1 + limit);
|
|
269
|
+
const structured = { jarPath: index.jarPath, jarName: index.jarName, fingerprint: index.fingerprint, layout: index.layout, isMultiRelease: index.isMultiRelease, isSourceJar: index.isSourceJar, manifest: index.manifest, mavenCoordinates: index.mavenCoordinates, counts: { classes: classes.length, packages: index.packages.length, resources: resources.length, nestedJars: index.nestedJars.length }, packages: index.packages, nestedJars: index.nestedJars, entries, totalMatchingEntries: classes.length + resources.length };
|
|
270
|
+
const text = `JAR: ${index.jarPath}\nLayout: ${index.layout}\nClasses: ${classes.length}\nPackages: ${index.packages.length}\nResources: ${resources.length}\nNested JARs: ${index.nestedJars.length}\n\n${entries.map(item => `- [${item.type}] ${item.path}`).join('\n')}`;
|
|
271
|
+
return this.formatResponse(text, structured, args.format);
|
|
272
|
+
}
|
|
273
|
+
async handleSearchClass(args, sendProgress) {
|
|
274
|
+
if (!args.query || typeof args.query !== 'string')
|
|
275
|
+
throw new Error('query is required');
|
|
276
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
277
|
+
await sendProgress?.(`Searching for class: ${args.query}`, 0, 100);
|
|
278
|
+
const result = await artifactService.searchClasses(args.query, { ...selector, classpathWaitMs: args.mode === 'fast' ? 0 : 30_000, onWait: message => sendProgress?.(message, 10, 100) ?? Promise.resolve() }, this.clamp(args.limit, 1, 100, 20), args.mode === 'fast' ? 5 : 20);
|
|
279
|
+
const jdkResults = args.includeJdk ? await jdkSourceService.searchClasses(args.query, this.clamp(args.limit, 1, 100, 20)) : [];
|
|
280
|
+
const structured = { ...result, jdkResults, backgroundScanProgress: await this.aggregateScanProgress(selector.workspacePath) };
|
|
281
|
+
const totalResults = result.results.length + jdkResults.length;
|
|
282
|
+
let text = totalResults ? `Found ${totalResults} class candidate(s):\n${[
|
|
283
|
+
this.groupByJar(result.results, item => item.className),
|
|
284
|
+
...jdkResults.map(item => `jdk:${item.module ?? 'unknown-module'}\n - ${item.className}`),
|
|
285
|
+
].filter(Boolean).join('\n')}` : `No class found matching "${args.query}".`;
|
|
286
|
+
if (!result.complete)
|
|
287
|
+
text += `\n\nSearch is partial; ${result.remainingJarCount} candidate JAR(s) remain.`;
|
|
288
|
+
if (result.errors.length)
|
|
289
|
+
text += `\n\nScan errors:\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
290
|
+
return this.formatResponse(text, structured, args.format);
|
|
291
|
+
}
|
|
292
|
+
async handleSearchCode(args, sendProgress) {
|
|
293
|
+
if (!args.query || !args.kind)
|
|
294
|
+
throw new Error('query and kind are required');
|
|
295
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
296
|
+
await sendProgress?.(`Searching deep metadata for ${args.kind}: ${args.query}`, 0, 100);
|
|
297
|
+
const result = await artifactService.searchCode(args.query, args.kind, selector, this.clamp(args.limit, 1, 100, 20), args.mode === 'fast' ? 3 : 10);
|
|
298
|
+
let text = result.matches.length ? `Found ${result.matches.length} match(es):\n${this.groupByJar(result.matches, item => `${item.className}${item.member ? `#${item.member}${item.descriptor ? ` ${item.descriptor}` : ''}` : ''}${item.owner ? ` -> ${item.owner}` : ''}${item.value !== undefined ? ` "${item.value.length > 120 ? `${item.value.substring(0, 117)}...` : item.value}"` : ''}`)}` : `No ${args.kind} match found for "${args.query}".`;
|
|
299
|
+
if (!result.complete)
|
|
300
|
+
text += `\n\nSearch is partial; ${result.remainingJarCount} JAR(s) remain.`;
|
|
301
|
+
if (result.errors.length)
|
|
302
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
303
|
+
return this.formatResponse(text, result, args.format);
|
|
304
|
+
}
|
|
305
|
+
async handleFindImplementations(args, sendProgress) {
|
|
306
|
+
this.validateClassName(args.className);
|
|
307
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
308
|
+
await sendProgress?.(`Finding implementations of ${args.className}`, 0, 100);
|
|
309
|
+
const result = await artifactService.findImplementations(args.className, selector, args.transitive !== false, this.clamp(args.limit, 1, 200, 50), args.mode === 'fast' ? 3 : 10);
|
|
310
|
+
let text = result.implementations.length ? `Found ${result.implementations.length} implementation(s):\n${this.groupByJar(result.implementations, item => item.className)}` : `No implementations found for ${args.className}${result.complete ? '.' : ' in the currently deep-indexed JARs.'}`;
|
|
311
|
+
if (!result.complete && result.remainingJarCount > 0)
|
|
312
|
+
text += `\n\nSearch is partial; ${result.remainingJarCount} JAR(s) not deep-indexed yet. Call again to continue, or narrow with jarNamePrefix.`;
|
|
313
|
+
if (result.errors.length)
|
|
314
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
315
|
+
return this.formatResponse(text, result, args.format);
|
|
316
|
+
}
|
|
317
|
+
async handleFindDuplicates(args, sendProgress) {
|
|
318
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
319
|
+
await sendProgress?.('Collecting classpath class index', 0, 100);
|
|
320
|
+
const result = await artifactService.findDuplicateClasses({ ...selector, classpathWaitMs: args.mode === 'fast' ? 0 : 60_000, onWait: message => sendProgress?.(message, 10, 100) ?? Promise.resolve() }, {
|
|
321
|
+
query: args.query,
|
|
322
|
+
limit: this.clamp(args.limit, 1, 200, 30),
|
|
323
|
+
classLimit: this.clamp(args.classLimit, 1, 100, 10),
|
|
324
|
+
maxNewJars: args.mode === 'fast' ? 50 : 500,
|
|
325
|
+
deadlineMs: args.mode === 'fast' ? 5_000 : 25_000,
|
|
326
|
+
});
|
|
327
|
+
const describeJar = (jar) => jar.artifactId ? `${jar.groupId ?? '?'}:${jar.artifactId}:${jar.version} (${jar.jarPath})` : jar.jarPath;
|
|
328
|
+
let text = result.groups.length
|
|
329
|
+
? `Found ${result.totalDuplicateClasses} duplicate class(es) in ${result.totalGroups} JAR group(s)${result.groups.length < result.totalGroups ? ` (showing ${result.groups.length})` : ''}:\n\n` +
|
|
330
|
+
result.groups.map((group, index) => [
|
|
331
|
+
`${index + 1}. ${group.kind === 'same-artifact-multiple-versions' ? 'Same artifact, multiple versions' : 'Different artifacts'} - ${group.classCount} class(es)`,
|
|
332
|
+
...group.jars.map(jar => ` - ${describeJar(jar)}`),
|
|
333
|
+
` Packages: ${group.packages.join(', ') || '(default)'}`,
|
|
334
|
+
` Classes: ${group.sampleClasses.join(', ')}${group.classCount > group.sampleClasses.length ? ', ...' : ''}`,
|
|
335
|
+
].join('\n')).join('\n\n')
|
|
336
|
+
: `No duplicate classes found${args.query ? ` matching "${args.query}"` : ''}${result.complete ? '.' : ' in the JARs indexed so far.'}`;
|
|
337
|
+
if (!result.complete)
|
|
338
|
+
text += `\n\nResult is partial${result.remainingJarCount ? `; ${result.remainingJarCount} JAR(s) not indexed yet` : ''}. Call again to continue.`;
|
|
339
|
+
if (result.errors.length)
|
|
340
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
341
|
+
return this.formatResponse(text, result, args.format);
|
|
342
|
+
}
|
|
343
|
+
async handleInspectClass(args, sendProgress) {
|
|
344
|
+
this.validateClassName(args.className);
|
|
345
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
346
|
+
const contextPath = selector.workspacePath || (selector.jarPath ? path.dirname(selector.jarPath) : process.cwd());
|
|
347
|
+
const view = args.view ?? 'source';
|
|
348
|
+
await sendProgress?.(`Resolving ${args.className}`, 0, 100);
|
|
349
|
+
if (jdkSourceService.isLikelyJdkClass(args.className) && !selector.jarPath && !selector.jarNamePrefix && !selector.jarDirectory && !selector.coordinates) {
|
|
350
|
+
const result = await this.inspectJdkClass(args.className, contextPath, view, args);
|
|
351
|
+
return this.formatResponse(this.classInspectionText(args.className, result), result, args.format);
|
|
352
|
+
}
|
|
353
|
+
// Single-class lookups may wait for a cold-start Maven resolution instead of failing immediately;
|
|
354
|
+
// otherwise agents give up and go hunting for JARs in ~/.m2 themselves.
|
|
355
|
+
const resolved = await artifactService.resolveClass(args.className, {
|
|
356
|
+
...selector,
|
|
357
|
+
classpathWaitMs: 90_000,
|
|
358
|
+
onWait: message => sendProgress?.(message, 10, 100) ?? Promise.resolve(),
|
|
359
|
+
});
|
|
360
|
+
let requested = String(args.className);
|
|
361
|
+
const isQualified = requested.includes('.');
|
|
362
|
+
// Never fall back to fuzzy matches here: silently decompiling "FooBar" when "Foo" was asked is worse than an error.
|
|
363
|
+
const exactMatches = (result, name) => this.uniqueClassCandidates(result.results.filter(item => isQualified ? item.className === name : item.simpleName === name));
|
|
364
|
+
let unique = exactMatches(resolved, requested);
|
|
365
|
+
const binaryName = unique.length ? undefined : this.nestedBinaryName(requested);
|
|
366
|
+
if (binaryName) {
|
|
367
|
+
// Source-style nested name (java.util.Map.Entry style): retry as the binary name Outer$Inner.
|
|
368
|
+
const retry = await artifactService.resolveClass(binaryName, { ...selector, classpathWaitMs: 90_000 });
|
|
369
|
+
const retryUnique = exactMatches(retry, binaryName);
|
|
370
|
+
if (retryUnique.length) {
|
|
371
|
+
unique = retryUnique;
|
|
372
|
+
requested = binaryName;
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
if (!unique.length) {
|
|
376
|
+
const suggestions = this.uniqueClassCandidates(resolved.results).slice(0, 10).map(item => `- ${item.className} -> ${item.jarPath}`);
|
|
377
|
+
const buildErrors = resolved.errors.filter(error => error.contextPath && !error.jarPath).map(error => error.message).slice(0, 1);
|
|
378
|
+
const partial = buildErrors.length ? ` ${buildErrors.join('\n')}` : resolved.complete ? '' : (resolved.results.length === 0 && resolved.scannedJarCount === 0
|
|
379
|
+
? ' The Maven classpath is still being resolved (first run for this project); call again in a moment with the same arguments.'
|
|
380
|
+
: ` ${resolved.remainingJarCount} dependency JAR(s) were not searched yet; call again with the same arguments.`);
|
|
381
|
+
throw new Error(`Class not found: ${requested}.${partial}${suggestions.length ? `\nSimilar classes:\n${suggestions.join('\n')}` : ' Use search_class with a partial name.'}`);
|
|
382
|
+
}
|
|
383
|
+
if (unique.length > 1)
|
|
384
|
+
return this.ambiguityResponse('Class', unique, args.format);
|
|
385
|
+
let candidate = unique[0];
|
|
386
|
+
let inspection = await artifactService.inspectJar({ jarPath: candidate.jarPath, workspacePath: selector.workspacePath });
|
|
387
|
+
let classEntry = inspection.index.classes.find(item => item.className === candidate.className && !item.isSource) ?? inspection.index.classes.find(item => item.className === candidate.className);
|
|
388
|
+
if (!classEntry)
|
|
389
|
+
throw new Error(`Class entry not found after indexing: ${candidate.className}`);
|
|
390
|
+
if (classEntry.isSource && view !== 'source') {
|
|
391
|
+
const binaryJar = candidate.jarPath.replace(/-sources\.jar$/i, '.jar');
|
|
392
|
+
if (!(await fs.pathExists(binaryJar)))
|
|
393
|
+
throw new Error(`API/bytecode view requires a binary JAR; only source JAR is available: ${candidate.jarPath}`);
|
|
394
|
+
candidate = { ...candidate, jarPath: binaryJar };
|
|
395
|
+
inspection = await artifactService.inspectJar({ jarPath: binaryJar, workspacePath: selector.workspacePath });
|
|
396
|
+
classEntry = inspection.index.classes.find(item => item.className === candidate.className && !item.isSource);
|
|
397
|
+
if (!classEntry)
|
|
398
|
+
throw new Error(`Binary class not found for source: ${candidate.className}`);
|
|
399
|
+
}
|
|
400
|
+
const result = { className: candidate.className, jarPath: candidate.jarPath, entryPath: classEntry.entryPath, origin: candidate.origin, backgroundSearchComplete: resolved.complete };
|
|
401
|
+
const entryPath = classEntry.entryPath;
|
|
402
|
+
const needsExtractedClass = entryPath !== `${candidate.className.replace(/\./g, '/')}.class`;
|
|
403
|
+
let inspectionClassFile;
|
|
404
|
+
const classFile = async (bytes) => {
|
|
405
|
+
if (needsExtractedClass && !inspectionClassFile)
|
|
406
|
+
inspectionClassFile = await this.getInspectionClassFile(candidate, entryPath, contextPath, bytes);
|
|
407
|
+
return inspectionClassFile;
|
|
408
|
+
};
|
|
409
|
+
let bytecodeOutput;
|
|
410
|
+
const bytecode = () => bytecodeOutput ??= classFile().then(file => file
|
|
411
|
+
? this.analyzer.getBytecodeFromClassFile(file, contextPath)
|
|
412
|
+
: this.analyzer.getBytecode(candidate.className, contextPath, candidate.jarPath));
|
|
413
|
+
const javapMembers = async () => parseJavapMembers(await bytecode(), candidate.className).members;
|
|
414
|
+
if (view === 'source' || view === 'all' || view === 'outline') {
|
|
415
|
+
await sendProgress?.('Loading source/decompiling class', 35, 100);
|
|
416
|
+
if (view === 'outline')
|
|
417
|
+
Object.assign(result, await this.loadClassOutline(candidate, entryPath, contextPath, args));
|
|
418
|
+
else
|
|
419
|
+
Object.assign(result, await this.loadClassSource(candidate, entryPath, contextPath, args, selector, classEntry.isSource ? undefined : javapMembers));
|
|
420
|
+
}
|
|
421
|
+
if (view === 'api' || view === 'all') {
|
|
422
|
+
const bytes = await jarIndexer.readEntry(candidate.jarPath, entryPath, 20 * 1024 * 1024);
|
|
423
|
+
const classFileMetadata = ClassFileMetadataReader.read(bytes);
|
|
424
|
+
const file = await classFile(bytes);
|
|
425
|
+
const signatures = await this.analyzer.getSignatures(candidate.className, contextPath, file ? { classFile: file } : { jarPath: candidate.jarPath });
|
|
426
|
+
result.api = {
|
|
427
|
+
signatures: signatures.trim(),
|
|
428
|
+
superClass: classFileMetadata.superClass,
|
|
429
|
+
interfaces: classFileMetadata.interfaces,
|
|
430
|
+
accessFlags: classFileMetadata.accessFlags,
|
|
219
431
|
};
|
|
432
|
+
}
|
|
433
|
+
if (view === 'hierarchy' || view === 'all')
|
|
434
|
+
result.hierarchy = await this.resolveHierarchy(candidate, selector, contextPath, entryPath);
|
|
435
|
+
if (view === 'bytecode' || view === 'all')
|
|
436
|
+
Object.assign(result, this.bytecodeView(await bytecode(), candidate.className, args));
|
|
437
|
+
await sendProgress?.('Class inspection complete', 100, 100);
|
|
438
|
+
return this.formatResponse(this.classInspectionText(candidate.className, result), result, args.format);
|
|
439
|
+
}
|
|
440
|
+
async handleCompareVersions(args, sendProgress) {
|
|
441
|
+
const workspacePath = args.workspacePath ? await this.validateWorkspacePath(args.workspacePath) : process.cwd();
|
|
442
|
+
const [groupId, artifactId] = typeof args.coordinates === 'string' ? args.coordinates.split(':') : [];
|
|
443
|
+
if (args.coordinates && (!groupId || !artifactId))
|
|
444
|
+
throw new Error('coordinates must be groupId:artifactId');
|
|
445
|
+
const notes = [];
|
|
446
|
+
const resolveJar = async (label, jarPath, version) => {
|
|
447
|
+
if (jarPath) {
|
|
448
|
+
if (!path.isAbsolute(jarPath) || !(await fs.pathExists(jarPath)))
|
|
449
|
+
throw new Error(`${label}JarPath does not exist or is not absolute: ${jarPath}`);
|
|
450
|
+
return { jarPath: path.resolve(jarPath), version: artifactService.coordinatesFromJarPath(jarPath).version };
|
|
451
|
+
}
|
|
452
|
+
if (!groupId)
|
|
453
|
+
throw new Error(`Give coordinates (groupId:artifactId) or ${label}JarPath.`);
|
|
454
|
+
if (!version && label === 'from') {
|
|
455
|
+
const found = await artifactService.findJars({ workspacePath, jarNamePrefix: `${artifactId}-`, classpathWaitMs: 60_000 }, 'prefix', 50);
|
|
456
|
+
const match = found.results.find(item => { const c = artifactService.coordinatesFromJarPath(item.jarPath); return c.groupId === groupId && c.artifactId === artifactId; });
|
|
457
|
+
if (!match)
|
|
458
|
+
throw new Error(`${groupId}:${artifactId} is not on the classpath of ${workspacePath}; pass fromVersion or fromJarPath.`);
|
|
459
|
+
notes.push(`fromVersion taken from the project classpath.`);
|
|
460
|
+
return { jarPath: match.jarPath, version: artifactService.coordinatesFromJarPath(match.jarPath).version };
|
|
461
|
+
}
|
|
462
|
+
if (!version)
|
|
463
|
+
throw new Error(`${label}Version is required with coordinates.`);
|
|
464
|
+
let jar = (await artifactService.findCoordinateJars(`${groupId}:${artifactId}:${version}`))[0];
|
|
465
|
+
if (!jar && args.download) {
|
|
466
|
+
await sendProgress?.(`Downloading ${groupId}:${artifactId}:${version}`, 10, 100);
|
|
467
|
+
const result = await this.scanner.downloadArtifact(workspacePath, { groupId, artifactId, version });
|
|
468
|
+
jar = (await artifactService.findCoordinateJars(`${groupId}:${artifactId}:${version}`))[0];
|
|
469
|
+
if (!jar)
|
|
470
|
+
throw new Error(`Could not download ${groupId}:${artifactId}:${version}${result.message ? `: ${result.message}` : ''}`);
|
|
471
|
+
notes.push(`Downloaded ${groupId}:${artifactId}:${version}.`);
|
|
472
|
+
}
|
|
473
|
+
if (!jar)
|
|
474
|
+
throw new Error(`${groupId}:${artifactId}:${version} is not in the local Maven repository. Pass download: true to fetch it with mvn dependency:get.`);
|
|
475
|
+
return { jarPath: jar, version };
|
|
476
|
+
};
|
|
477
|
+
const from = await resolveJar('from', args.fromJarPath, args.fromVersion);
|
|
478
|
+
const to = await resolveJar('to', args.toJarPath, args.toVersion);
|
|
479
|
+
await sendProgress?.('Reading class files of both versions', 40, 100);
|
|
480
|
+
const select = (classes) => classes.filter(cls => !cls.entryPath.startsWith('META-INF/versions/')
|
|
481
|
+
&& (!args.className || cls.className === args.className || cls.className.startsWith(`${args.className}$`))
|
|
482
|
+
&& (!args.packagePrefix || cls.className.startsWith(`${String(args.packagePrefix).replace(/\.$/, '')}.`)));
|
|
483
|
+
const [fromIndex, toIndex] = await Promise.all([jarIndexer.getDeepIndex(from.jarPath, workspacePath), jarIndexer.getDeepIndex(to.jarPath, workspacePath)]);
|
|
484
|
+
const fromClasses = select(fromIndex.classes);
|
|
485
|
+
const toClasses = select(toIndex.classes);
|
|
486
|
+
if (args.className && !fromClasses.length && !toClasses.length)
|
|
487
|
+
throw new Error(`${args.className} exists in neither JAR.`);
|
|
488
|
+
const diff = diffApi(fromClasses, toClasses);
|
|
489
|
+
const limit = this.clamp(args.limit, 1, 500, 40);
|
|
490
|
+
const label = (side) => side.version && groupId ? side.version : path.basename(side.jarPath);
|
|
491
|
+
const listNames = (names, max = 50) => names.slice(0, max).join(', ') + (names.length > max ? `, ... (${names.length - max} more)` : '');
|
|
492
|
+
const lines = [
|
|
493
|
+
`API diff${groupId ? ` of ${groupId}:${artifactId}` : ''}: ${label(from)} -> ${label(to)}`,
|
|
494
|
+
`From: ${from.jarPath}`,
|
|
495
|
+
`To: ${to.jarPath}`,
|
|
496
|
+
...notes,
|
|
497
|
+
`Public classes: ${diff.addedClasses.length} added, ${diff.removedClasses.length} removed, ${diff.changedClasses.length} changed, ${diff.unchangedClassCount} unchanged. Breaking changes: ${diff.breakingChangeCount}.`,
|
|
498
|
+
];
|
|
499
|
+
if (diff.removedClasses.length)
|
|
500
|
+
lines.push('', `Removed classes (breaking): ${listNames(diff.removedClasses)}`);
|
|
501
|
+
if (diff.addedClasses.length)
|
|
502
|
+
lines.push('', `Added classes: ${listNames(diff.addedClasses)}`);
|
|
503
|
+
if (diff.changedClasses.length) {
|
|
504
|
+
lines.push('', 'Changed classes:');
|
|
505
|
+
for (const cls of diff.changedClasses.slice(0, limit)) {
|
|
506
|
+
lines.push(`${cls.breaking ? '[BREAKING] ' : ''}${cls.className}`);
|
|
507
|
+
for (const change of cls.classChanges)
|
|
508
|
+
lines.push(` * ${change}`);
|
|
509
|
+
for (const member of cls.removed)
|
|
510
|
+
lines.push(` - ${member}`);
|
|
511
|
+
for (const change of cls.changed)
|
|
512
|
+
lines.push(` ~ ${change.member}: ${change.change}${change.breaking ? ' (breaking)' : ''}`);
|
|
513
|
+
for (const member of cls.added)
|
|
514
|
+
lines.push(` + ${member}`);
|
|
515
|
+
}
|
|
516
|
+
if (diff.changedClasses.length > limit)
|
|
517
|
+
lines.push(`... ${diff.changedClasses.length - limit} more changed class(es); narrow with className/packagePrefix or raise limit.`);
|
|
518
|
+
}
|
|
519
|
+
if (!diff.addedClasses.length && !diff.removedClasses.length && !diff.changedClasses.length)
|
|
520
|
+
lines.push('', 'No public/protected API differences.');
|
|
521
|
+
lines.push('', 'Legend: - removed, + added, ~ changed, * class-level change. Only public/protected, non-synthetic members are compared; method bodies are not.');
|
|
522
|
+
return this.formatResponse(lines.join('\n'), { from, to, ...diff }, args.format);
|
|
523
|
+
}
|
|
524
|
+
async handleListDependencies(args, sendProgress) {
|
|
525
|
+
const workspacePath = await this.validateWorkspacePath(args.workspacePath ?? process.cwd());
|
|
526
|
+
const contexts = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
527
|
+
if (!contexts.length)
|
|
528
|
+
throw new Error(`No Maven/Gradle build found under ${workspacePath}; list_dependencies needs a Maven project.`);
|
|
529
|
+
const query = typeof args.query === 'string' ? args.query.toLowerCase() : '';
|
|
530
|
+
const limit = this.clamp(args.limit, 1, 2000, 300);
|
|
531
|
+
const projects = [];
|
|
532
|
+
for (let i = 0; i < contexts.length; i++) {
|
|
533
|
+
await sendProgress?.(`Resolving dependency tree of ${path.basename(contexts[i])}`, i, contexts.length);
|
|
220
534
|
try {
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
await this.validateProjectPath(args.projectPath);
|
|
237
|
-
return await this.handleGetInheritanceTree(args, sendProgress);
|
|
238
|
-
default:
|
|
239
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
240
|
-
}
|
|
535
|
+
const { modules } = await this.scanner.listDependencies(contexts[i]);
|
|
536
|
+
projects.push({
|
|
537
|
+
projectPath: contexts[i],
|
|
538
|
+
modules: modules.map(module => {
|
|
539
|
+
// Filtered results are rendered flat with their parent (via), so the tree shape is not needed.
|
|
540
|
+
const dependencies = module.dependencies.filter(dep => {
|
|
541
|
+
if (args.directOnly && dep.depth > 1)
|
|
542
|
+
return false;
|
|
543
|
+
if (args.scope && dep.scope !== args.scope)
|
|
544
|
+
return false;
|
|
545
|
+
return !query || `${dep.groupId}:${dep.artifactId}`.toLowerCase().includes(query);
|
|
546
|
+
});
|
|
547
|
+
return { module: module.module, dependencies, directCount: module.dependencies.filter(dep => dep.depth === 1).length, transitiveCount: module.dependencies.filter(dep => dep.depth > 1).length };
|
|
548
|
+
}),
|
|
549
|
+
});
|
|
241
550
|
}
|
|
242
551
|
catch (error) {
|
|
243
|
-
|
|
244
|
-
console.error(`Tool call exception [${name}]:`, error);
|
|
245
|
-
await sendProgress(`Failed: ${errorMessage}`);
|
|
246
|
-
return {
|
|
247
|
-
content: [
|
|
248
|
-
{
|
|
249
|
-
type: 'text',
|
|
250
|
-
text: `Tool call failed: ${errorMessage}`,
|
|
251
|
-
},
|
|
252
|
-
],
|
|
253
|
-
isError: true,
|
|
254
|
-
};
|
|
552
|
+
projects.push({ projectPath: contexts[i], error: error instanceof Error ? error.message : String(error) });
|
|
255
553
|
}
|
|
256
|
-
}
|
|
554
|
+
}
|
|
555
|
+
let remaining = limit;
|
|
556
|
+
let truncated = 0;
|
|
557
|
+
const render = (dep) => `${dep.groupId}:${dep.artifactId}:${dep.version}${dep.classifier ? `:${dep.classifier}` : ''}${dep.type !== 'jar' ? ` (${dep.type})` : ''} [${dep.scope ?? '?'}]${dep.optional ? ' optional' : ''}`;
|
|
558
|
+
const text = projects.map(project => {
|
|
559
|
+
if (project.error)
|
|
560
|
+
return `Project: ${project.projectPath}\nError: ${project.error}`;
|
|
561
|
+
const filtered = Boolean(query || args.directOnly || args.scope);
|
|
562
|
+
const shown = project.modules.filter(module => module.dependencies.length || (!filtered && module.directCount));
|
|
563
|
+
if (!shown.length)
|
|
564
|
+
return `Project: ${project.projectPath}\nNo ${filtered ? 'matching ' : ''}dependencies.`;
|
|
565
|
+
return shown.map(module => {
|
|
566
|
+
const header = `Module ${module.module}: ${module.directCount} direct, ${module.transitiveCount} transitive${query || args.directOnly || args.scope ? `; ${module.dependencies.length} shown` : ''}`;
|
|
567
|
+
const rows = module.dependencies.flatMap(dep => {
|
|
568
|
+
if (remaining <= 0) {
|
|
569
|
+
truncated++;
|
|
570
|
+
return [];
|
|
571
|
+
}
|
|
572
|
+
remaining--;
|
|
573
|
+
if (filtered)
|
|
574
|
+
return [`- ${render(dep)}${dep.depth > 1 ? ` (transitive, via ${dep.via})` : ' (direct)'}`];
|
|
575
|
+
return [`${' '.repeat(dep.depth - 1)}${dep.depth === 1 ? '- ' : '\\- '}${render(dep)}`];
|
|
576
|
+
});
|
|
577
|
+
return [header, ...rows].join('\n');
|
|
578
|
+
}).join('\n\n');
|
|
579
|
+
}).join('\n\n') + (truncated ? `\n\n${truncated} more dependency line(s) not shown; narrow with query, directOnly or scope, or raise limit.` : '');
|
|
580
|
+
return this.formatResponse(text, { projects }, args.format);
|
|
257
581
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
582
|
+
async handleExplainDependency(args, sendProgress) {
|
|
583
|
+
const workspacePath = await this.validateWorkspacePath(args.workspacePath ?? process.cwd());
|
|
584
|
+
let coordinates = args.coordinates;
|
|
585
|
+
if (!coordinates && args.jarPath) {
|
|
586
|
+
const inspected = await artifactService.inspectJar({ jarPath: args.jarPath, workspacePath });
|
|
587
|
+
const coordinate = inspected.index?.mavenCoordinates[0];
|
|
588
|
+
if (coordinate?.groupId && coordinate.artifactId)
|
|
589
|
+
coordinates = `${coordinate.groupId}:${coordinate.artifactId}`;
|
|
261
590
|
}
|
|
262
|
-
if (
|
|
591
|
+
if (!coordinates)
|
|
592
|
+
throw new Error('coordinates or a JAR containing Maven pom.properties is required');
|
|
593
|
+
const contexts = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
594
|
+
if (!contexts.length)
|
|
595
|
+
throw new Error(`No Maven/Gradle build found under ${workspacePath}; explain_dependency needs a Maven project.`);
|
|
596
|
+
const outputs = [];
|
|
597
|
+
for (let i = 0; i < contexts.length; i++) {
|
|
263
598
|
try {
|
|
264
|
-
|
|
265
|
-
return { content: [{ type: 'text', text: toonText }] };
|
|
599
|
+
outputs.push({ projectPath: contexts[i], output: await this.scanner.explainDependency(contexts[i], coordinates) });
|
|
266
600
|
}
|
|
267
|
-
catch {
|
|
268
|
-
|
|
601
|
+
catch (error) {
|
|
602
|
+
outputs.push({ projectPath: contexts[i], error: error instanceof Error ? error.message : String(error) });
|
|
269
603
|
}
|
|
604
|
+
await sendProgress?.(`Checked ${i + 1}/${contexts.length} Maven context(s)`, i + 1, contexts.length);
|
|
270
605
|
}
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
const
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
jarCount: result.jarCount,
|
|
310
|
-
progress: result.progress,
|
|
606
|
+
const text = outputs.map(item => `Project: ${item.projectPath}\n${item.output || `Error: ${item.error}`}`).join('\n\n');
|
|
607
|
+
return this.formatResponse(text, { coordinates, outputs }, args.format);
|
|
608
|
+
}
|
|
609
|
+
async handleSearchResources(args) {
|
|
610
|
+
const result = await artifactService.searchResources(await this.selectorFromArgs(args, true), args.pathQuery ?? '', args.contentQuery, this.clamp(args.limit, 1, 100, 20));
|
|
611
|
+
let text = result.results.length ? `Found ${result.results.length} resource(s):\n${result.results.map(item => `- ${item.resourcePath} -> ${item.jarPath}${item.contentMatch ? `\n ...${item.contentMatch.replace(/\s+/g, ' ').trim()}...` : ''}`).join('\n')}` : 'No matching resources found.';
|
|
612
|
+
if (!result.complete)
|
|
613
|
+
text += '\n\nResource search is partial.';
|
|
614
|
+
if (result.errors.length)
|
|
615
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
616
|
+
return this.formatResponse(text, result, args.format);
|
|
617
|
+
}
|
|
618
|
+
async handleReadResource(args) {
|
|
619
|
+
if (!args.resourcePath)
|
|
620
|
+
throw new Error('resourcePath is required');
|
|
621
|
+
const result = await artifactService.readResource(await this.selectorFromArgs(args), args.resourcePath, args.offset, args.limit);
|
|
622
|
+
return this.formatResponse(`Resource ${result.resourcePath} (${result.startLine}-${result.endLine}/${result.totalLines}):\n\n${result.text}`, result, args.format);
|
|
623
|
+
}
|
|
624
|
+
/** Full source of the class (for nested classes: just the nested declaration), plus the outer raw source. */
|
|
625
|
+
async loadFullSource(candidate, entryPath, contextPath, args) {
|
|
626
|
+
const dollar = candidate.className.indexOf('$', candidate.className.lastIndexOf('.') + 1);
|
|
627
|
+
if (dollar < 0) {
|
|
628
|
+
const raw = await this.loadRawSource(candidate, entryPath, contextPath, args);
|
|
629
|
+
return { ...raw, rawSource: raw.source };
|
|
630
|
+
}
|
|
631
|
+
// Nested class: sources and Vineflower output live in the top-level class; cut out the nested declaration.
|
|
632
|
+
const outerClassName = candidate.className.substring(0, dollar);
|
|
633
|
+
const outerEntryPath = entryPath.replace(/\$[^/]*(\.class|\.java)$/i, '$1');
|
|
634
|
+
const raw = await this.loadRawSource({ ...candidate, className: outerClassName }, outerEntryPath, contextPath, args);
|
|
635
|
+
const nested = extractTypeDeclaration(raw.source, candidate.className.substring(dollar + 1).split('$'));
|
|
636
|
+
if (nested)
|
|
637
|
+
return { source: nested, sourceOrigin: raw.sourceOrigin, enclosingClass: outerClassName, rawSource: raw.source, ...(raw.sourceNote ? { sourceNote: raw.sourceNote } : {}) };
|
|
638
|
+
return {
|
|
639
|
+
source: raw.source,
|
|
640
|
+
rawSource: raw.source,
|
|
641
|
+
sourceOrigin: raw.sourceOrigin,
|
|
642
|
+
enclosingClass: outerClassName,
|
|
643
|
+
sourceNote: [`${candidate.className} is an anonymous/local or synthetic class; showing the source of ${outerClassName}. Use view=bytecode for its exact code.`, raw.sourceNote].filter(Boolean).join(' '),
|
|
311
644
|
};
|
|
312
|
-
return this.formatResponse(text, structured, format);
|
|
313
645
|
}
|
|
314
|
-
async
|
|
315
|
-
const
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
logger.info(`[TOOL:decompile_class] Request: className=${className}, useCache=${useCache}, decompilerPath=${decompilerPath || 'auto-detect'}`);
|
|
320
|
-
this.logToolDebug(logger, 'decompile_class', projectPath, { className, useCache, decompilerPath: decompilerPath || 'auto-detect' });
|
|
646
|
+
async loadClassSource(candidate, entryPath, contextPath, args, selector, javapMembers) {
|
|
647
|
+
const full = await this.loadFullSource(candidate, entryPath, contextPath, args);
|
|
648
|
+
const meta = { sourceOrigin: full.sourceOrigin, ...(full.enclosingClass ? { enclosingClass: full.enclosingClass } : {}), ...(full.sourceNote ? { sourceNote: full.sourceNote } : {}) };
|
|
649
|
+
if (args.line)
|
|
650
|
+
return { ...meta, ...await this.sourceAtLine(full.rawSource, full.sourceOrigin, Number(args.line), candidate.className, javapMembers) };
|
|
321
651
|
try {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
await
|
|
329
|
-
if (!
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
652
|
+
const slice = this.sliceSource(full.source, args);
|
|
653
|
+
return { ...meta, ...slice, sourceNote: [meta.sourceNote, slice.sourceNote].filter(Boolean).join(' ') || undefined };
|
|
654
|
+
}
|
|
655
|
+
catch (error) {
|
|
656
|
+
if (!(error instanceof MemberNotFoundError))
|
|
657
|
+
throw error;
|
|
658
|
+
const inherited = await this.inheritedMemberSource(candidate, entryPath, contextPath, args, selector);
|
|
659
|
+
if (!inherited)
|
|
660
|
+
throw error;
|
|
661
|
+
return inherited;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
async loadClassOutline(candidate, entryPath, contextPath, args) {
|
|
665
|
+
const full = await this.loadFullSource(candidate, entryPath, contextPath, args);
|
|
666
|
+
const members = buildOutline(full.source);
|
|
667
|
+
return {
|
|
668
|
+
sourceOrigin: full.sourceOrigin,
|
|
669
|
+
...(full.enclosingClass ? { enclosingClass: full.enclosingClass } : {}),
|
|
670
|
+
...(full.sourceNote ? { sourceNote: full.sourceNote } : {}),
|
|
671
|
+
totalLines: full.source.split('\n').length,
|
|
672
|
+
memberCount: members.length,
|
|
673
|
+
outline: formatOutline(members),
|
|
674
|
+
};
|
|
675
|
+
}
|
|
676
|
+
/**
|
|
677
|
+
* methodName was not declared in the class: walk superclasses and interfaces (breadth-first) and
|
|
678
|
+
* return the first declaration found, so "where does getBean() come from?" needs one call.
|
|
679
|
+
*/
|
|
680
|
+
async inheritedMemberSource(candidate, entryPath, contextPath, args, selector) {
|
|
681
|
+
const parentsOf = async (jarPath, entry, className) => {
|
|
682
|
+
try {
|
|
683
|
+
if (jdkSourceService.isLikelyJdkClass(className)) {
|
|
684
|
+
const analysis = await this.analyzer.analyzeJdkClass(className, contextPath);
|
|
685
|
+
return [analysis.superClass, ...analysis.interfaces].filter(Boolean);
|
|
346
686
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
const sigParams = extractParamTypes(m.signature);
|
|
355
|
-
return matchParamTypes(sigParams, paramTypes);
|
|
356
|
-
});
|
|
687
|
+
if (!jarPath || !entry || entry.endsWith('.java'))
|
|
688
|
+
return [];
|
|
689
|
+
const metadata = ClassFileMetadataReader.read(await jarIndexer.readEntry(jarPath, entry, 20 * 1024 * 1024));
|
|
690
|
+
return [metadata.superClass, ...metadata.interfaces].filter(Boolean);
|
|
691
|
+
}
|
|
692
|
+
catch {
|
|
693
|
+
return [];
|
|
357
694
|
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
695
|
+
};
|
|
696
|
+
const queue = (await parentsOf(candidate.jarPath, entryPath, candidate.className)).filter(name => name !== 'java.lang.Object');
|
|
697
|
+
const visited = new Set([candidate.className]);
|
|
698
|
+
while (queue.length && visited.size < 25) {
|
|
699
|
+
const parent = queue.shift();
|
|
700
|
+
if (visited.has(parent))
|
|
701
|
+
continue;
|
|
702
|
+
visited.add(parent);
|
|
703
|
+
try {
|
|
704
|
+
let source = null;
|
|
705
|
+
let origin = 'jdk-src.zip';
|
|
706
|
+
let parentJar;
|
|
707
|
+
let parentEntry;
|
|
708
|
+
if (jdkSourceService.isLikelyJdkClass(parent)) {
|
|
709
|
+
source = await this.jdkClassSource(parent);
|
|
710
|
+
}
|
|
711
|
+
else {
|
|
712
|
+
const sameJar = (await jarIndexer.getLightIndex(candidate.jarPath, contextPath)).classes.find(item => item.className === parent && !item.isSource);
|
|
713
|
+
const located = sameJar
|
|
714
|
+
? { ...candidate, className: parent, entryPath: sameJar.entryPath }
|
|
715
|
+
: (await artifactService.resolveClass(parent, selector.workspacePath ? { workspacePath: selector.workspacePath } : selector)).results.find(item => item.className === parent);
|
|
716
|
+
if (located) {
|
|
717
|
+
parentJar = located.jarPath;
|
|
718
|
+
parentEntry = located.entryPath ?? (await jarIndexer.getLightIndex(located.jarPath, contextPath)).classes.find(item => item.className === parent && !item.isSource)?.entryPath;
|
|
719
|
+
if (parentEntry) {
|
|
720
|
+
const full = await this.loadFullSource(located, parentEntry, contextPath, args);
|
|
721
|
+
source = full.source;
|
|
722
|
+
origin = full.sourceOrigin;
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
if (source) {
|
|
727
|
+
const members = extractMembers(source, args.methodName, args.paramTypes);
|
|
728
|
+
if (members.length) {
|
|
729
|
+
return {
|
|
730
|
+
source: members.map(member => member.text).join('\n\n// ===== Method Overload =====\n\n'),
|
|
731
|
+
sourceOrigin: origin,
|
|
732
|
+
declaredIn: parent,
|
|
733
|
+
lineInfo: `${args.methodName} is not declared in ${candidate.className}; inherited from ${parent}${parentJar ? ` (${path.basename(parentJar)})` : ''}.`,
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
for (const grandParent of await parentsOf(parentJar, parentEntry, parent)) {
|
|
738
|
+
if (grandParent !== 'java.lang.Object' && !visited.has(grandParent))
|
|
739
|
+
queue.push(grandParent);
|
|
365
740
|
}
|
|
366
|
-
const effectiveLimit = limit < 0 ? 0 : limit;
|
|
367
|
-
const startIndex = effectiveOffset - 1;
|
|
368
|
-
const endIndex = effectiveLimit > 0
|
|
369
|
-
? Math.min(startIndex + effectiveLimit, totalLines)
|
|
370
|
-
: totalLines;
|
|
371
|
-
finalSourceCode = lines.slice(startIndex, endIndex).join('\n');
|
|
372
|
-
sliceInfo = ` (lines ${effectiveOffset}-${endIndex} of ${totalLines})`;
|
|
373
741
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
742
|
+
catch { /* unresolved parent: keep walking the others */ }
|
|
743
|
+
}
|
|
744
|
+
return null;
|
|
745
|
+
}
|
|
746
|
+
/** Stack-trace style lookup: show the member that contains original source line `line`. */
|
|
747
|
+
async sourceAtLine(source, sourceOrigin, line, className, javapMembers) {
|
|
748
|
+
if (!Number.isInteger(line) || line < 1)
|
|
749
|
+
throw new Error('line must be a positive integer (the line number from a stack trace).');
|
|
750
|
+
const lines = source.split('\n');
|
|
751
|
+
const outline = buildOutline(source);
|
|
752
|
+
if (sourceOrigin !== 'decompiled') {
|
|
753
|
+
if (line > lines.length)
|
|
754
|
+
throw new Error(`line ${line} is past the end of the source (${lines.length} lines). Is the dependency version the one from the stack trace?`);
|
|
755
|
+
const member = memberAtLine(outline, line);
|
|
756
|
+
let range = member ? memberRangeWithDoc(lines, member) : { start: Math.max(1, line - 20), end: Math.min(lines.length, line + 20) };
|
|
757
|
+
if (range.end - range.start > 300)
|
|
758
|
+
range = { start: Math.max(range.start, line - 60), end: Math.min(range.end, line + 60) };
|
|
759
|
+
return {
|
|
760
|
+
source: this.numberLines(lines, range.start, range.end, line),
|
|
761
|
+
sourceRange: { startLine: range.start, endLine: range.end, totalLines: lines.length },
|
|
762
|
+
lineInfo: `Line ${line} (marked >>) is in ${member ? member.signature : 'the class body (no enclosing method)'}.`,
|
|
382
763
|
};
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
764
|
+
}
|
|
765
|
+
if (!javapMembers)
|
|
766
|
+
throw new Error('Line lookup in decompiled source needs the class file.');
|
|
767
|
+
const members = await javapMembers();
|
|
768
|
+
const hit = javapMemberAtLine(members, line);
|
|
769
|
+
if (!hit) {
|
|
770
|
+
const all = members.flatMap(member => member.lines);
|
|
771
|
+
throw new Error(all.length
|
|
772
|
+
? `Line ${line} is not in ${className} (its code spans original lines ${Math.min(...all)}-${Math.max(...all)}). Check the class in the stack trace: lambdas/anonymous/inner classes appear as Outer$1, Outer$Inner, and a different dependency version shifts lines.`
|
|
773
|
+
: `${className} was compiled without line numbers (no LineNumberTable); use methodName instead.`);
|
|
774
|
+
}
|
|
775
|
+
let name = hit.name;
|
|
776
|
+
// javap prints com.acme.Outer$Key; the source says Key (or Outer.Key): compare simple names.
|
|
777
|
+
let paramTypes = hit.paramTypes.map(type => type.replace(/<.*>/g, '').replace(/^[\w.$]*[.$](?=[\w]+(\[\]|\.\.\.)*$)/, ''));
|
|
778
|
+
let where = hit.signature.replace(/;$/, '');
|
|
779
|
+
const lambda = name.match(/^lambda\$(.+)\$\d+$/);
|
|
780
|
+
if (lambda) {
|
|
781
|
+
name = lambda[1];
|
|
782
|
+
paramTypes = undefined;
|
|
783
|
+
where = `a lambda inside ${name}()`;
|
|
784
|
+
}
|
|
785
|
+
const simple = className.substring(className.lastIndexOf('.') + 1).split('$').pop();
|
|
786
|
+
const ownMembers = outline.filter(member => member.owner[member.owner.length - 1] === simple);
|
|
787
|
+
const scope = ownMembers.length ? ownMembers : outline;
|
|
788
|
+
let found;
|
|
789
|
+
if (name === '<clinit>') {
|
|
790
|
+
const init = scope.find(member => member.kind === 'initializer');
|
|
791
|
+
if (init) {
|
|
792
|
+
const range = memberRangeWithDoc(lines, init);
|
|
793
|
+
found = { text: lines.slice(range.start - 1, range.end).join('\n') };
|
|
389
794
|
}
|
|
390
|
-
return this.formatResponse(text, structured, format);
|
|
391
795
|
}
|
|
392
|
-
|
|
393
|
-
const
|
|
394
|
-
const
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
await sendProgress?.('Checking class index...', 20, 100);
|
|
412
|
-
await this.ensureScanStarted(projectPath, sendProgress);
|
|
413
|
-
await sendProgress?.('Running javap analysis...', 50, 100);
|
|
414
|
-
const analysis = await this.analyzer.analyzeClass(className, projectPath);
|
|
415
|
-
await sendProgress?.('Analysis complete', 100, 100);
|
|
416
|
-
const duration = ((performance.now() - start) / 1000).toFixed(2);
|
|
417
|
-
logger.info(`[TOOL:analyze_class] Complete in ${duration}s. Fields: ${analysis.fields.length}, Methods: ${analysis.methods.length}`);
|
|
418
|
-
const { fields, methods } = this.applyFilter(analysis, filter);
|
|
419
|
-
let text = `Analysis result for class ${className}:\n\n`;
|
|
420
|
-
text += `Package name: ${analysis.packageName}\n`;
|
|
421
|
-
text += `Class name: ${analysis.className}\n`;
|
|
422
|
-
text += `Modifiers: ${analysis.modifiers.join(' ')}\n`;
|
|
423
|
-
text += `Super class: ${analysis.superClass || 'None'}\n`;
|
|
424
|
-
text += `Implemented interfaces: ${analysis.interfaces.join(', ') || 'None'}\n\n`;
|
|
425
|
-
if (fields.length > 0) {
|
|
426
|
-
text += `Fields (${fields.length}):\n`;
|
|
427
|
-
fields.forEach(field => {
|
|
428
|
-
text += ` - ${field.modifiers.join(' ')} ${field.type} ${field.name}\n`;
|
|
429
|
-
});
|
|
430
|
-
text += '\n';
|
|
796
|
+
else {
|
|
797
|
+
const memberName = name === '<init>' ? simple : name;
|
|
798
|
+
const typed = paramTypes ? extractMembers(source, memberName, paramTypes, scope) : [];
|
|
799
|
+
// Inner-class constructors carry the synthetic outer instance as first javap parameter.
|
|
800
|
+
const withoutOuter = !typed.length && name === '<init>' && paramTypes?.length ? extractMembers(source, memberName, paramTypes.slice(1), scope) : [];
|
|
801
|
+
const exact = typed.length ? typed : withoutOuter;
|
|
802
|
+
if (exact.length) {
|
|
803
|
+
found = exact[0];
|
|
804
|
+
}
|
|
805
|
+
else {
|
|
806
|
+
const byName = extractMembers(source, memberName, undefined, scope);
|
|
807
|
+
const sameArity = paramTypes ? byName.filter(item => extractParamTypes(item.member.signature).length === paramTypes.length) : byName;
|
|
808
|
+
const candidates = sameArity.length ? sameArity : byName;
|
|
809
|
+
if (candidates.length === 1)
|
|
810
|
+
found = candidates[0];
|
|
811
|
+
else if (candidates.length > 1) {
|
|
812
|
+
return { source: hit.text, lineInfo: `Original line ${line} is in ${where}; ${candidates.length} overloads of ${memberName} in the decompiled source could not be told apart, so its bytecode is shown. Use methodName with paramTypes for the source.` };
|
|
813
|
+
}
|
|
814
|
+
}
|
|
431
815
|
}
|
|
432
|
-
if (
|
|
433
|
-
text
|
|
434
|
-
|
|
435
|
-
text += ` - ${method.modifiers.join(' ')} ${method.returnType} ${method.name}(${method.parameters.join(', ')})\n`;
|
|
436
|
-
});
|
|
437
|
-
text += '\n';
|
|
438
|
-
}
|
|
439
|
-
const structured = {
|
|
440
|
-
className: analysis.className,
|
|
441
|
-
packageName: analysis.packageName,
|
|
442
|
-
modifiers: analysis.modifiers,
|
|
443
|
-
superClass: analysis.superClass,
|
|
444
|
-
interfaces: analysis.interfaces,
|
|
445
|
-
fields,
|
|
446
|
-
methods,
|
|
447
|
-
};
|
|
448
|
-
return this.formatResponse(text, structured, format);
|
|
816
|
+
if (!found)
|
|
817
|
+
return { source: hit.text, lineInfo: `Original line ${line} is in ${where}; it could not be located in the decompiled source, showing its bytecode instead.` };
|
|
818
|
+
return { source: found.text, lineInfo: `Original line ${line} is in ${where}. The source is decompiled, so its line numbers differ from the stack trace; the whole member is shown.` };
|
|
449
819
|
}
|
|
450
|
-
|
|
451
|
-
const
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
await sendProgress?.(`Searching for classes matching: "${query}"`, 0, 100);
|
|
457
|
-
await this.ensureScanStarted(projectPath, sendProgress);
|
|
458
|
-
await sendProgress?.('Searching index...', 50, 100);
|
|
459
|
-
const results = await this.scanner.searchClasses(projectPath, query, limit);
|
|
460
|
-
const duration = ((performance.now() - start) / 1000).toFixed(2);
|
|
461
|
-
logger.info(`[TOOL:search_class] Complete in ${duration}s. Found ${results.length} results.`);
|
|
462
|
-
await sendProgress?.(`Found ${results.length} matches`, 100, 100);
|
|
463
|
-
const isComplete = await this.scanner.isIndexComplete(projectPath);
|
|
464
|
-
const scanProgress = isComplete ? undefined : await this.scanner.getScanProgress(projectPath);
|
|
465
|
-
const pct = scanProgress ? Math.floor((scanProgress.processed / scanProgress.total) * 100) : undefined;
|
|
466
|
-
if (results.length === 0) {
|
|
467
|
-
const text = `No classes found matching "${query}".\n\nSuggestions:\n1. Check your spelling\n2. Run scan_dependencies first if you haven't already\n3. Try a broader query (e.g. "Repository" instead of "JpaRepository")`;
|
|
468
|
-
const structured = { query, results: [], isComplete, scanProgressPct: pct };
|
|
469
|
-
return this.formatResponse(text, structured, format);
|
|
470
|
-
}
|
|
471
|
-
let text = `Found ${results.length} class(es) matching "${query}":\n\n`;
|
|
472
|
-
text += '| # | Class Name | Package | JAR | Score |\n';
|
|
473
|
-
text += '|---|------------|---------|-----|-------|\n';
|
|
474
|
-
results.forEach((entry, idx) => {
|
|
475
|
-
text += `| ${idx + 1} | \`${entry.simpleName}\` | ${entry.packageName} | ${path.basename(entry.jarPath)} | ${entry.score} |\n`;
|
|
476
|
-
});
|
|
477
|
-
text += '\nUse the fully qualified class name with `decompile_class` or `analyze_class` to inspect it further.';
|
|
478
|
-
if (!isComplete && pct !== undefined) {
|
|
479
|
-
text += `\n\n_Note: Background dependency scan is ${pct}% complete. Results may be partial._`;
|
|
480
|
-
}
|
|
481
|
-
const structured = {
|
|
482
|
-
query,
|
|
483
|
-
results: results.map((r) => ({
|
|
484
|
-
className: `${r.packageName}.${r.simpleName}`,
|
|
485
|
-
packageName: r.packageName,
|
|
486
|
-
simpleName: r.simpleName,
|
|
487
|
-
jarName: path.basename(r.jarPath),
|
|
488
|
-
score: r.score,
|
|
489
|
-
})),
|
|
490
|
-
isComplete,
|
|
491
|
-
scanProgressPct: pct,
|
|
492
|
-
};
|
|
493
|
-
return this.formatResponse(text, structured, format);
|
|
820
|
+
numberLines(lines, start, end, mark) {
|
|
821
|
+
const width = String(end).length;
|
|
822
|
+
return lines.slice(start - 1, end).map((text, index) => {
|
|
823
|
+
const number = start + index;
|
|
824
|
+
return `${number === mark ? '>>' : ' '} ${String(number).padStart(width)} | ${text}`;
|
|
825
|
+
}).join('\n');
|
|
494
826
|
}
|
|
495
|
-
|
|
496
|
-
const
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
text += '\n(This class has no superclass in the indexed dependencies; it likely extends java.lang.Object or a JDK class not present in the Maven dependencies.)';
|
|
517
|
-
}
|
|
518
|
-
const structured = {
|
|
519
|
-
className,
|
|
520
|
-
hierarchy: hierarchy.map(entry => ({
|
|
521
|
-
className: entry.className,
|
|
522
|
-
level: entry.level,
|
|
523
|
-
resolved: entry.resolved,
|
|
524
|
-
})),
|
|
827
|
+
bytecodeView(output, className, args) {
|
|
828
|
+
const parsed = parseJavapMembers(output, className);
|
|
829
|
+
if (args.methodName) {
|
|
830
|
+
const selected = selectJavapMembers(parsed.members, args.methodName, args.paramTypes, className);
|
|
831
|
+
if (!selected.length) {
|
|
832
|
+
const names = [...new Set(parsed.members.filter(member => member.isMethod).map(member => member.name))];
|
|
833
|
+
throw new Error(`Method not found in bytecode: ${args.methodName}. Methods: ${names.slice(0, 60).join(', ')}${names.length > 60 ? ', ...' : ''}`);
|
|
834
|
+
}
|
|
835
|
+
return { bytecode: selected.map(member => member.text).join('\n\n') };
|
|
836
|
+
}
|
|
837
|
+
if (args.line) {
|
|
838
|
+
const member = javapMemberAtLine(parsed.members, Number(args.line));
|
|
839
|
+
if (member)
|
|
840
|
+
return { bytecode: member.text, bytecodeNote: `Line ${args.line} is in ${member.signature.replace(/;$/, '')}.` };
|
|
841
|
+
}
|
|
842
|
+
const lineCount = output.split('\n').length;
|
|
843
|
+
if (lineCount <= BYTECODE_AUTO_LIMIT)
|
|
844
|
+
return { bytecode: output.trim() };
|
|
845
|
+
return {
|
|
846
|
+
bytecode: `${parsed.header}\n${parsed.members.map(member => ` ${member.signature}`).join('\n')}\n}`,
|
|
847
|
+
bytecodeNote: `Full bytecode is ${lineCount} lines; only member signatures are listed. Pass methodName (and paramTypes) for one method's bytecode, or line for the method at a stack-trace line.`,
|
|
525
848
|
};
|
|
526
|
-
return this.formatResponse(text, structured, format);
|
|
527
849
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
if (
|
|
532
|
-
|
|
850
|
+
async loadRawSource(candidate, entryPath, contextPath, args) {
|
|
851
|
+
const sameJarIndex = await jarIndexer.getLightIndex(candidate.jarPath, contextPath);
|
|
852
|
+
const embeddedSource = sameJarIndex.classes.find(item => item.className === candidate.className && item.isSource);
|
|
853
|
+
if (embeddedSource) {
|
|
854
|
+
return { source: (await jarIndexer.readEntry(candidate.jarPath, embeddedSource.entryPath, 10 * 1024 * 1024)).toString('utf8'), sourceOrigin: 'embedded-source' };
|
|
533
855
|
}
|
|
534
|
-
|
|
535
|
-
|
|
856
|
+
let sourceJar = await artifactService.findSourcesJar(candidate.jarPath);
|
|
857
|
+
if (sourceJar) {
|
|
858
|
+
const sourceIndex = await jarIndexer.getLightIndex(sourceJar, contextPath);
|
|
859
|
+
const sourceEntry = sourceIndex.classes.find(item => item.className === candidate.className && item.isSource);
|
|
860
|
+
if (sourceEntry)
|
|
861
|
+
return { source: (await jarIndexer.readEntry(sourceJar, sourceEntry.entryPath, 10 * 1024 * 1024)).toString('utf8'), sourceOrigin: 'sources-jar' };
|
|
536
862
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
863
|
+
const downloadNote = await this.tryDownloadSources(candidate, contextPath, args);
|
|
864
|
+
if (downloadNote === true)
|
|
865
|
+
sourceJar = await artifactService.findSourcesJar(candidate.jarPath);
|
|
866
|
+
if (downloadNote === true && sourceJar) {
|
|
867
|
+
const sourceIndex = await jarIndexer.getLightIndex(sourceJar, contextPath);
|
|
868
|
+
const sourceEntry = sourceIndex.classes.find(item => item.className === candidate.className && item.isSource);
|
|
869
|
+
if (sourceEntry)
|
|
870
|
+
return { source: (await jarIndexer.readEntry(sourceJar, sourceEntry.entryPath, 10 * 1024 * 1024)).toString('utf8'), sourceOrigin: 'sources-jar', sourceNote: 'Sources JAR downloaded with mvn dependency:get.' };
|
|
540
871
|
}
|
|
541
|
-
|
|
872
|
+
const decompiled = cleanDecompilerFailures(await this.decompiler.decompileClassFromJar(candidate.className, candidate.jarPath, contextPath, entryPath, args.useCache !== false));
|
|
873
|
+
return {
|
|
874
|
+
source: decompiled.source,
|
|
875
|
+
sourceOrigin: 'decompiled',
|
|
876
|
+
...(typeof downloadNote === 'string' || decompiled.failedMethods.length ? { sourceNote: [typeof downloadNote === 'string' ? downloadNote : '', decompiled.failedMethods.length ? `Vineflower could not decompile ${decompiled.failedMethods.length} method(s): ${decompiled.failedMethods.join('; ')}. Their bodies contain a bytecode listing; use view=bytecode with methodName for javap output.` : ''].filter(Boolean).join(' ') } : {}),
|
|
877
|
+
};
|
|
542
878
|
}
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
879
|
+
/** true = a sources JAR was downloaded; string = why not (shown to the agent); undefined = not requested. */
|
|
880
|
+
async tryDownloadSources(candidate, contextPath, args) {
|
|
881
|
+
const requested = args.downloadSources ?? /^(1|true|yes)$/i.test(process.env.JAVA_INSPECTOR_DOWNLOAD_SOURCES ?? '');
|
|
882
|
+
if (!requested)
|
|
883
|
+
return undefined;
|
|
884
|
+
const coordinates = artifactService.coordinatesFromJarPath(candidate.jarPath);
|
|
885
|
+
if (!coordinates.groupId || !coordinates.artifactId || !coordinates.version)
|
|
886
|
+
return 'downloadSources skipped: the JAR is not in a Maven repository layout.';
|
|
887
|
+
if (await buildToolOf(contextPath) === 'gradle')
|
|
888
|
+
return 'downloadSources needs Maven; for Gradle projects add the sources to the Gradle cache (e.g. the IDE "Download Sources" action).';
|
|
889
|
+
const key = `${coordinates.groupId}:${coordinates.artifactId}:${coordinates.version}`;
|
|
890
|
+
let attempt = this.sourceDownloads.get(key);
|
|
891
|
+
if (!attempt) {
|
|
892
|
+
attempt = this.scanner.downloadSources(contextPath, coordinates);
|
|
893
|
+
this.sourceDownloads.set(key, attempt);
|
|
546
894
|
}
|
|
547
|
-
|
|
548
|
-
|
|
895
|
+
const result = await attempt;
|
|
896
|
+
if (result.ok && await artifactService.findSourcesJar(candidate.jarPath))
|
|
897
|
+
return true;
|
|
898
|
+
return `No sources JAR could be downloaded for ${key}${result.message ? ` (${result.message})` : ''}; showing decompiled code.`;
|
|
899
|
+
}
|
|
900
|
+
sliceSource(source, args) {
|
|
901
|
+
const lines = source.split('\n');
|
|
902
|
+
const totalLines = lines.length;
|
|
903
|
+
if (args.methodName) {
|
|
904
|
+
const outline = buildOutline(source);
|
|
905
|
+
const members = extractMembers(source, args.methodName, args.paramTypes, outline);
|
|
906
|
+
if (members.length) {
|
|
907
|
+
return {
|
|
908
|
+
source: members.map(member => member.text).join('\n\n// ===== Method Overload =====\n\n'),
|
|
909
|
+
lineInfo: members.length === 1 ? `Lines ${members[0].start}-${members[0].end} of ${totalLines}.` : `${members.length} overloads.`,
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
const extracted = extractMethod(source, args.methodName, args.paramTypes);
|
|
913
|
+
if (extracted)
|
|
914
|
+
return { source: extracted };
|
|
915
|
+
throw new MemberNotFoundError(args.methodName, outline, args.paramTypes);
|
|
549
916
|
}
|
|
550
|
-
const
|
|
551
|
-
|
|
552
|
-
|
|
917
|
+
const offset = this.clamp(args.offset, 1, Number.MAX_SAFE_INTEGER, 1);
|
|
918
|
+
const requestedLimit = Number(args.limit ?? 0);
|
|
919
|
+
if (offset === 1 && !(requestedLimit > 0)) {
|
|
920
|
+
if (totalLines <= SOURCE_AUTO_LIMIT)
|
|
921
|
+
return { source };
|
|
922
|
+
// Large file: never dump it whole. First lines + member outline; the agent then reads one member.
|
|
923
|
+
return {
|
|
924
|
+
source: lines.slice(0, SOURCE_AUTO_PREVIEW).join('\n'),
|
|
925
|
+
sourceRange: { startLine: 1, endLine: SOURCE_AUTO_PREVIEW, totalLines },
|
|
926
|
+
outline: formatOutline(buildOutline(source)),
|
|
927
|
+
sourceNote: `Large file (${totalLines} lines): showing lines 1-${SOURCE_AUTO_PREVIEW} and the member outline. Read a member with methodName, or a range with offset/limit using the outline's line numbers.`,
|
|
928
|
+
};
|
|
553
929
|
}
|
|
930
|
+
if (offset > totalLines)
|
|
931
|
+
throw new Error(`offset ${offset} is past the end of the source (${totalLines} lines).`);
|
|
932
|
+
const end = requestedLimit > 0 ? Math.min(totalLines, offset - 1 + requestedLimit) : totalLines;
|
|
933
|
+
return { source: lines.slice(offset - 1, end).join('\n'), sourceRange: { startLine: offset, endLine: end, totalLines } };
|
|
554
934
|
}
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
if (!
|
|
560
|
-
|
|
935
|
+
async jdkClassSource(className) {
|
|
936
|
+
const dollar = className.indexOf('$');
|
|
937
|
+
const outerName = dollar > 0 ? className.substring(0, dollar) : className;
|
|
938
|
+
const outerSource = await jdkSourceService.getSource(outerName);
|
|
939
|
+
if (!outerSource || dollar < 0)
|
|
940
|
+
return outerSource;
|
|
941
|
+
return extractTypeDeclaration(outerSource, className.substring(dollar + 1).split('$')) ?? outerSource;
|
|
942
|
+
}
|
|
943
|
+
async inspectJdkClass(className, contextPath, view, args) {
|
|
944
|
+
const result = { className, origin: 'jdk' };
|
|
945
|
+
const dollar = className.indexOf('$');
|
|
946
|
+
let bytecodeOutput;
|
|
947
|
+
const bytecode = () => bytecodeOutput ??= this.analyzer.getBytecode(className, contextPath);
|
|
948
|
+
if (view === 'source' || view === 'all' || view === 'outline') {
|
|
949
|
+
const source = args.line && dollar > 0 ? await jdkSourceService.getSource(className.substring(0, dollar)) : await this.jdkClassSource(className);
|
|
950
|
+
if (!source)
|
|
951
|
+
result.sourceUnavailable = true;
|
|
952
|
+
else if (view === 'outline')
|
|
953
|
+
Object.assign(result, { sourceOrigin: 'jdk-src.zip', outline: formatOutline(buildOutline(source)), totalLines: source.split('\n').length });
|
|
954
|
+
else if (args.line)
|
|
955
|
+
Object.assign(result, await this.sourceAtLine(source, 'jdk-src.zip', Number(args.line), className), { sourceOrigin: 'jdk-src.zip' });
|
|
956
|
+
else
|
|
957
|
+
Object.assign(result, this.sliceSource(source, args), { sourceOrigin: 'jdk-src.zip' });
|
|
958
|
+
if (source && dollar > 0)
|
|
959
|
+
result.enclosingClass = className.substring(0, dollar);
|
|
561
960
|
}
|
|
562
|
-
if (
|
|
563
|
-
|
|
961
|
+
if (view === 'api' || view === 'all')
|
|
962
|
+
result.api = { signatures: (await this.analyzer.getSignatures(className, contextPath)).trim() };
|
|
963
|
+
if (view === 'hierarchy' || view === 'all')
|
|
964
|
+
result.hierarchy = await this.resolveJdkHierarchy(className, contextPath);
|
|
965
|
+
if (view === 'bytecode' || view === 'all')
|
|
966
|
+
Object.assign(result, this.bytecodeView(await bytecode(), className, args));
|
|
967
|
+
return result;
|
|
968
|
+
}
|
|
969
|
+
async resolveJdkHierarchy(className, contextPath) {
|
|
970
|
+
const hierarchy = [];
|
|
971
|
+
const visited = new Set();
|
|
972
|
+
let current = className;
|
|
973
|
+
while (current && hierarchy.length < 20 && !visited.has(current)) {
|
|
974
|
+
visited.add(current);
|
|
975
|
+
hierarchy.push({ className: current, level: hierarchy.length, resolved: true });
|
|
976
|
+
try {
|
|
977
|
+
const analysis = await this.analyzer.analyzeJdkClass(current, contextPath);
|
|
978
|
+
hierarchy[hierarchy.length - 1].interfaces = analysis.interfaces;
|
|
979
|
+
current = analysis.superClass;
|
|
980
|
+
}
|
|
981
|
+
catch {
|
|
982
|
+
hierarchy[hierarchy.length - 1].resolved = false;
|
|
983
|
+
break;
|
|
984
|
+
}
|
|
564
985
|
}
|
|
565
|
-
|
|
566
|
-
|
|
986
|
+
return hierarchy.reverse().map((entry, level) => ({ ...entry, level }));
|
|
987
|
+
}
|
|
988
|
+
async resolveHierarchy(candidate, selector, contextPath, firstEntryPath) {
|
|
989
|
+
const chain = [];
|
|
990
|
+
const visited = new Set();
|
|
991
|
+
let current = candidate.className;
|
|
992
|
+
let currentJar = candidate.jarPath;
|
|
993
|
+
let entryPath = firstEntryPath;
|
|
994
|
+
while (current && chain.length < 20 && !visited.has(current)) {
|
|
995
|
+
visited.add(current);
|
|
996
|
+
try {
|
|
997
|
+
let analysis;
|
|
998
|
+
if (jdkSourceService.isLikelyJdkClass(current))
|
|
999
|
+
analysis = await this.analyzer.analyzeJdkClass(current, contextPath);
|
|
1000
|
+
else if (currentJar && entryPath) {
|
|
1001
|
+
const metadata = ClassFileMetadataReader.read(await jarIndexer.readEntry(currentJar, entryPath, 20 * 1024 * 1024));
|
|
1002
|
+
analysis = { className: current, packageName: current.includes('.') ? current.substring(0, current.lastIndexOf('.')) : '', modifiers: [], superClass: metadata.superClass, interfaces: metadata.interfaces, fields: [], methods: [] };
|
|
1003
|
+
}
|
|
1004
|
+
else if (currentJar)
|
|
1005
|
+
analysis = await this.analyzer.analyzeClassFromJar(current, currentJar, contextPath, false);
|
|
1006
|
+
else
|
|
1007
|
+
throw new Error('unresolved');
|
|
1008
|
+
chain.push({ className: current, level: chain.length, resolved: true, interfaces: analysis.interfaces });
|
|
1009
|
+
const analyzedJar = currentJar;
|
|
1010
|
+
current = analysis.superClass;
|
|
1011
|
+
entryPath = undefined;
|
|
1012
|
+
if (current && !jdkSourceService.isLikelyJdkClass(current)) {
|
|
1013
|
+
currentJar = undefined;
|
|
1014
|
+
if (analyzedJar) {
|
|
1015
|
+
const sameJarEntry = (await jarIndexer.getLightIndex(analyzedJar, contextPath)).classes
|
|
1016
|
+
.find(item => item.className === current && !item.isSource);
|
|
1017
|
+
if (sameJarEntry) {
|
|
1018
|
+
currentJar = analyzedJar;
|
|
1019
|
+
entryPath = sameJarEntry.entryPath;
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
if (!currentJar) {
|
|
1023
|
+
const next = (await artifactService.resolveClass(current, selector)).results.find(item => item.className === current);
|
|
1024
|
+
currentJar = next?.jarPath;
|
|
1025
|
+
if (next)
|
|
1026
|
+
entryPath = (await jarIndexer.getLightIndex(next.jarPath, contextPath)).classes.find(item => item.className === current && !item.isSource)?.entryPath;
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
else if (current) {
|
|
1030
|
+
currentJar = undefined;
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
catch {
|
|
1034
|
+
chain.push({ className: current, level: chain.length, resolved: false });
|
|
1035
|
+
break;
|
|
1036
|
+
}
|
|
567
1037
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
1038
|
+
return chain.reverse().map((entry, level) => ({ ...entry, level }));
|
|
1039
|
+
}
|
|
1040
|
+
async getInspectionClassFile(candidate, entryPath, contextPath, existingBytes) {
|
|
1041
|
+
const fingerprint = await jarIndexer.fingerprint(candidate.jarPath);
|
|
1042
|
+
const simpleName = candidate.className.substring(candidate.className.lastIndexOf('.') + 1);
|
|
1043
|
+
const classKey = createHash('sha256').update(`${candidate.className}\n${entryPath}`).digest('hex').substring(0, 12);
|
|
1044
|
+
const target = path.join(getResultCacheDir(contextPath), fingerprint.key, 'class-files', `${simpleName}-${classKey}.class`);
|
|
1045
|
+
if (!(await fs.pathExists(target))) {
|
|
1046
|
+
const bytes = existingBytes ?? await jarIndexer.readEntry(candidate.jarPath, entryPath, 20 * 1024 * 1024);
|
|
1047
|
+
await fs.outputFile(target, bytes);
|
|
571
1048
|
}
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
1049
|
+
return target;
|
|
1050
|
+
}
|
|
1051
|
+
classInspectionText(className, result) {
|
|
1052
|
+
let text = `Class inspection: ${className}\nOrigin: ${result.origin}${result.jarPath ? `\nJAR: ${result.jarPath}` : ''}`;
|
|
1053
|
+
if (result.sourceOrigin)
|
|
1054
|
+
text += `\nSource origin: ${result.sourceOrigin === 'decompiled' ? 'decompiled with Vineflower (not original source; comments and local names may differ)' : result.sourceOrigin}`;
|
|
1055
|
+
if (result.enclosingClass)
|
|
1056
|
+
text += `\nEnclosing class: ${result.enclosingClass}`;
|
|
1057
|
+
if (result.sourceNote)
|
|
1058
|
+
text += `\nNote: ${result.sourceNote}`;
|
|
1059
|
+
if (result.sourceRange)
|
|
1060
|
+
text += `\nLines: ${result.sourceRange.startLine}-${result.sourceRange.endLine} of ${result.sourceRange.totalLines}${result.sourceRange.endLine < result.sourceRange.totalLines ? ` (call again with offset=${result.sourceRange.endLine + 1} for more)` : ''}`;
|
|
1061
|
+
if (result.lineInfo)
|
|
1062
|
+
text += `\n${result.lineInfo}`;
|
|
1063
|
+
if (result.declaredIn)
|
|
1064
|
+
text += `\nDeclared in: ${result.declaredIn}`;
|
|
1065
|
+
if (result.totalLines && result.outline && !result.source)
|
|
1066
|
+
text += `\nLines: ${result.totalLines}`;
|
|
1067
|
+
if (result.sourceUnavailable)
|
|
1068
|
+
text += '\n\nSource: unavailable - the JDK has no lib/src.zip (install the JDK source package, e.g. openjdk-<version>-source, or a JDK that ships src.zip). view=api and view=bytecode still work.';
|
|
1069
|
+
if (result.source)
|
|
1070
|
+
text += `\n\nSource:\n\n\`\`\`java\n${result.source}\n\`\`\``;
|
|
1071
|
+
if (result.outline)
|
|
1072
|
+
text += `\n\nOutline (line ranges; read a member with methodName or offset/limit):\n\n\`\`\`text\n${result.outline}\n\`\`\``;
|
|
1073
|
+
if (result.api)
|
|
1074
|
+
text += `\n\nAPI (javap -p):\n\n\`\`\`text\n${result.api.signatures}\n\`\`\``;
|
|
1075
|
+
if (result.hierarchy)
|
|
1076
|
+
text += `\n\nHierarchy (root first):\n${result.hierarchy.map((item) => `${' '.repeat(item.level)}${item.className}${item.resolved ? '' : ' (unresolved)'}${item.interfaces?.length ? ` implements ${item.interfaces.join(', ')}` : ''}`).join('\n')}`;
|
|
1077
|
+
if (result.bytecodeNote)
|
|
1078
|
+
text += `\n\n${result.bytecodeNote}`;
|
|
1079
|
+
if (result.bytecode)
|
|
1080
|
+
text += `\n\nBytecode:\n\n\`\`\`text\n${result.bytecode}\n\`\`\``;
|
|
1081
|
+
return text;
|
|
1082
|
+
}
|
|
1083
|
+
/** "com.acme.Outer.Inner" -> "com.acme.Outer$Inner" (first capitalised segment that is not the last starts the nesting). */
|
|
1084
|
+
nestedBinaryName(className) {
|
|
1085
|
+
if (className.includes('$'))
|
|
1086
|
+
return undefined;
|
|
1087
|
+
const segments = className.split('.');
|
|
1088
|
+
const outer = segments.findIndex((segment, index) => index < segments.length - 1 && /^[A-Z]/.test(segment));
|
|
1089
|
+
if (outer < 0)
|
|
1090
|
+
return undefined;
|
|
1091
|
+
return `${segments.slice(0, outer + 1).join('.')}$${segments.slice(outer + 1).join('$')}`;
|
|
1092
|
+
}
|
|
1093
|
+
uniqueClassCandidates(candidates) {
|
|
1094
|
+
const map = new Map();
|
|
1095
|
+
for (const candidate of candidates)
|
|
1096
|
+
map.set(`${candidate.className}::${path.resolve(candidate.jarPath)}`, candidate);
|
|
1097
|
+
return [...map.values()];
|
|
1098
|
+
}
|
|
1099
|
+
async aggregateScanProgress(workspacePath) {
|
|
1100
|
+
if (!workspacePath)
|
|
1101
|
+
return undefined;
|
|
1102
|
+
let processed = 0, total = 0;
|
|
1103
|
+
for (const context of await projectDiscovery.findTopLevelPomDirectories(workspacePath)) {
|
|
1104
|
+
const progress = await this.scanner.getScanProgress(context);
|
|
1105
|
+
processed += progress?.processed ?? 0;
|
|
1106
|
+
total += progress?.total ?? 0;
|
|
576
1107
|
}
|
|
1108
|
+
return { processed, total, percent: total ? Math.floor(processed / total * 100) : 0 };
|
|
577
1109
|
}
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
async ensureScanStarted(projectPath, sendProgress) {
|
|
583
|
-
// Check if we have a complete and valid index
|
|
584
|
-
if (await this.scanner.isIndexComplete(projectPath)) {
|
|
585
|
-
return; // Already have a complete index
|
|
1110
|
+
async selectorFromArgs(args, allowEmpty = false) {
|
|
1111
|
+
const selector = { workspacePath: args.workspacePath, jarPath: args.jarPath, jarDirectory: args.jarDirectory, jarNamePrefix: args.jarNamePrefix, coordinates: args.coordinates };
|
|
1112
|
+
if (!selector.workspacePath && !selector.jarPath && !selector.jarDirectory && !selector.coordinates) {
|
|
1113
|
+
selector.workspacePath = process.cwd();
|
|
586
1114
|
}
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
1115
|
+
if (selector.workspacePath)
|
|
1116
|
+
selector.workspacePath = await this.validateWorkspacePath(selector.workspacePath);
|
|
1117
|
+
if (selector.jarDirectory)
|
|
1118
|
+
selector.jarDirectory = await this.validateDirectory(selector.jarDirectory, 'jarDirectory');
|
|
1119
|
+
if (selector.jarPath) {
|
|
1120
|
+
if (!path.isAbsolute(selector.jarPath))
|
|
1121
|
+
throw new Error('jarPath must be absolute');
|
|
1122
|
+
selector.jarPath = path.resolve(selector.jarPath);
|
|
590
1123
|
}
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
1124
|
+
if (!allowEmpty && !selector.workspacePath && !selector.jarPath && !selector.jarDirectory && !selector.coordinates)
|
|
1125
|
+
throw new Error('Provide workspacePath, jarPath, jarDirectory, or coordinates');
|
|
1126
|
+
return selector;
|
|
1127
|
+
}
|
|
1128
|
+
ambiguityResponse(label, candidates, format = 'text') {
|
|
1129
|
+
const structured = { ambiguous: true, candidates };
|
|
1130
|
+
const text = `${label} is ambiguous. Provide an exact path/name:\n${candidates.map(candidate => `- ${candidate.jarPath ?? candidate.className}`).join('\n')}`;
|
|
1131
|
+
return this.formatResponse(text, structured, format);
|
|
1132
|
+
}
|
|
1133
|
+
formatResponse(text, structured, format = 'text') {
|
|
1134
|
+
const wrap = (value) => ({ content: [{ type: 'text', text: value }] });
|
|
1135
|
+
// Structured output must stay parseable, so it is shrunk (long arrays/strings halved) instead of cut.
|
|
1136
|
+
if (format === 'json')
|
|
1137
|
+
return wrap(JSON.stringify(shrinkStructured(structured, value => JSON.stringify(value, null, 2).length), null, 2));
|
|
1138
|
+
if (format === 'toon') {
|
|
1139
|
+
try {
|
|
1140
|
+
return wrap(toonEncode(shrinkStructured(structured, value => toonEncode(value).length)));
|
|
1141
|
+
}
|
|
1142
|
+
catch {
|
|
1143
|
+
return wrap(this.capResponse(text));
|
|
1144
|
+
}
|
|
597
1145
|
}
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
1146
|
+
return wrap(this.capResponse(text));
|
|
1147
|
+
}
|
|
1148
|
+
/** Text lists grouped under their JAR, so long Maven paths are printed once instead of per line. */
|
|
1149
|
+
groupByJar(items, render) {
|
|
1150
|
+
const groups = new Map();
|
|
1151
|
+
for (const item of items) {
|
|
1152
|
+
if (!groups.has(item.jarPath))
|
|
1153
|
+
groups.set(item.jarPath, []);
|
|
1154
|
+
groups.get(item.jarPath).push(` - ${render(item)}`);
|
|
601
1155
|
}
|
|
1156
|
+
return [...groups].map(([jarPath, lines]) => `${jarPath}\n${lines.join('\n')}`).join('\n');
|
|
602
1157
|
}
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
};
|
|
1158
|
+
/** Last-resort guard: no single response may flood the agent's context. */
|
|
1159
|
+
capResponse(text) {
|
|
1160
|
+
if (text.length <= MAX_RESPONSE_CHARS)
|
|
1161
|
+
return text;
|
|
1162
|
+
const cut = text.lastIndexOf('\n', MAX_RESPONSE_CHARS);
|
|
1163
|
+
const kept = text.substring(0, cut > MAX_RESPONSE_CHARS * 0.8 ? cut : MAX_RESPONSE_CHARS);
|
|
1164
|
+
const fence = (kept.match(/```/g)?.length ?? 0) % 2 === 1 ? '\n```' : '';
|
|
1165
|
+
return `${kept}${fence}\n\n[Response truncated at ${MAX_RESPONSE_CHARS} of ${text.length} characters. Narrow the request: methodName/line/offset+limit for source, methodName for bytecode, a smaller limit or a more specific query for searches.]`;
|
|
612
1166
|
}
|
|
613
|
-
|
|
614
|
-
const
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
const
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
if (
|
|
634
|
-
|
|
635
|
-
|
|
1167
|
+
clamp(value, min, max, fallback) {
|
|
1168
|
+
const parsed = Number(value);
|
|
1169
|
+
return Number.isFinite(parsed) ? Math.max(min, Math.min(max, Math.floor(parsed))) : fallback;
|
|
1170
|
+
}
|
|
1171
|
+
validateClassName(className) {
|
|
1172
|
+
if (!className || typeof className !== 'string')
|
|
1173
|
+
throw new Error('className is required and must be a string');
|
|
1174
|
+
if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test(className))
|
|
1175
|
+
throw new Error('className must be a valid Java class name');
|
|
1176
|
+
}
|
|
1177
|
+
async validateWorkspacePath(workspacePath) { return this.validateDirectory(workspacePath, 'workspacePath'); }
|
|
1178
|
+
async validateDirectory(value, label) {
|
|
1179
|
+
if (!value || typeof value !== 'string')
|
|
1180
|
+
throw new Error(`${label} is required and must be a string`);
|
|
1181
|
+
if (!path.isAbsolute(value))
|
|
1182
|
+
throw new Error(`${label} must be an absolute path`);
|
|
1183
|
+
const resolved = path.resolve(value);
|
|
1184
|
+
const stat = await fs.stat(resolved).catch(() => null);
|
|
1185
|
+
if (!stat)
|
|
1186
|
+
throw new Error(`${label} does not exist: ${resolved}`);
|
|
1187
|
+
if (!stat.isDirectory())
|
|
1188
|
+
throw new Error(`${label} is not a directory: ${resolved}`);
|
|
1189
|
+
return resolved;
|
|
636
1190
|
}
|
|
637
1191
|
async tryAutoScan() {
|
|
638
|
-
const
|
|
639
|
-
const
|
|
640
|
-
if (!(await fs.pathExists(pomPath))) {
|
|
641
|
-
const logger = Logger.get(cwd);
|
|
642
|
-
logger.info('[AUTO-SCAN] No Maven project detected at cwd, skipping auto-scan.');
|
|
643
|
-
return;
|
|
644
|
-
}
|
|
645
|
-
const logger = Logger.get(cwd);
|
|
646
|
-
logger.info(`[AUTO-SCAN] Maven project detected at ${cwd}. Starting dependency scan...`);
|
|
1192
|
+
const workspacePath = process.cwd();
|
|
1193
|
+
const logger = Logger.get(workspacePath);
|
|
647
1194
|
try {
|
|
648
|
-
await
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
|
|
1195
|
+
const pomRoots = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
1196
|
+
if (!pomRoots.length) {
|
|
1197
|
+
logger.info('[AUTO-SCAN] No Maven project found. Waiting for direct/local JAR calls.');
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
logger.info(`[AUTO-SCAN] Found ${pomRoots.length} top-level Maven project(s): ${pomRoots.join(', ')}`);
|
|
1201
|
+
for (const pomRoot of pomRoots) {
|
|
1202
|
+
this.scanner.scanProject(pomRoot, false, async (message) => logger.info(`[AUTO-SCAN:${path.basename(pomRoot)}] ${message}`))
|
|
1203
|
+
.catch(error => logger.error(`[AUTO-SCAN] ${pomRoot}: ${error instanceof Error ? error.message : String(error)}`));
|
|
1204
|
+
}
|
|
655
1205
|
}
|
|
656
1206
|
catch (error) {
|
|
657
|
-
|
|
658
|
-
logger.error(`[AUTO-SCAN] Failed: ${msg}`);
|
|
1207
|
+
logger.error(`[AUTO-SCAN] Discovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
659
1208
|
}
|
|
660
1209
|
}
|
|
661
1210
|
async run() {
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
this.logServerStartup(startupLogger);
|
|
666
|
-
await this.tryAutoScan();
|
|
1211
|
+
await this.mcp.connect(new StdioServerTransport());
|
|
1212
|
+
Logger.get(process.cwd()).info(`[SERVER] java-inspector v${version} running; cwd=${process.cwd()}, node=${process.version}, pid=${process.pid}`);
|
|
1213
|
+
void this.tryAutoScan();
|
|
667
1214
|
}
|
|
668
1215
|
}
|
|
669
1216
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
670
1217
|
const mcpServer = new JavaClassAnalyzerMCPServer();
|
|
671
|
-
process.on('uncaughtException',
|
|
672
|
-
|
|
673
|
-
});
|
|
674
|
-
process.on('unhandledRejection', (reason, promise) => {
|
|
675
|
-
console.error('Unhandled Promise rejection:', reason);
|
|
676
|
-
});
|
|
677
|
-
mcpServer.run().catch((error) => {
|
|
678
|
-
console.error('Server startup failed:', error);
|
|
679
|
-
process.exit(1);
|
|
680
|
-
});
|
|
1218
|
+
process.on('uncaughtException', error => console.error('Uncaught exception:', error));
|
|
1219
|
+
process.on('unhandledRejection', reason => console.error('Unhandled Promise rejection:', reason));
|
|
1220
|
+
mcpServer.run().catch(error => { console.error('Server startup failed:', error); process.exit(1); });
|
|
681
1221
|
}
|
|
682
1222
|
//# sourceMappingURL=index.js.map
|