@mustafagoksever/java-inspector 2.4.0 → 3.0.0
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 +138 -263
- package/dist/analyzer/JavaClassAnalyzer.d.ts +6 -0
- package/dist/analyzer/JavaClassAnalyzer.d.ts.map +1 -1
- package/dist/analyzer/JavaClassAnalyzer.js +27 -0
- 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 +5 -0
- package/dist/cache/ProjectCache.d.ts.map +1 -1
- package/dist/cache/ProjectCache.js +50 -8
- package/dist/cache/ProjectCache.js.map +1 -1
- package/dist/decompiler/DecompilerService.d.ts +4 -2
- package/dist/decompiler/DecompilerService.d.ts.map +1 -1
- package/dist/decompiler/DecompilerService.js +35 -12
- package/dist/decompiler/DecompilerService.js.map +1 -1
- package/dist/index.d.ts +25 -14
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +513 -595
- package/dist/index.js.map +1 -1
- package/dist/scanner/ArtifactService.d.ts +104 -0
- package/dist/scanner/ArtifactService.d.ts.map +1 -0
- package/dist/scanner/ArtifactService.js +569 -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 +4 -0
- package/dist/scanner/DependencyScanner.d.ts.map +1 -1
- package/dist/scanner/DependencyScanner.js +37 -1
- 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/ProjectDiscovery.d.ts +6 -0
- package/dist/scanner/ProjectDiscovery.d.ts.map +1 -0
- package/dist/scanner/ProjectDiscovery.js +49 -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/package.json +4 -2
package/dist/index.js
CHANGED
|
@@ -1,682 +1,600 @@
|
|
|
1
1
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
2
2
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
3
|
-
import { CallToolRequestSchema, ListToolsRequestSchema
|
|
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 { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
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 { DependencyScanner } from './scanner/DependencyScanner.js';
|
|
13
|
+
import { DecompilerService } from './decompiler/DecompilerService.js';
|
|
14
|
+
import { artifactService } from './scanner/ArtifactService.js';
|
|
15
|
+
import { jarIndexer } from './scanner/JarIndexer.js';
|
|
16
|
+
import { projectDiscovery } from './scanner/ProjectDiscovery.js';
|
|
17
|
+
import { ClassFileMetadataReader } from './scanner/ClassFileMetadataReader.js';
|
|
18
|
+
import { getResultCacheDir } from './utils/cachePaths.js';
|
|
19
|
+
import { extractMethod } from './utils/methodExtractor.js';
|
|
13
20
|
import { Logger } from './utils/Logger.js';
|
|
14
21
|
const __filename = fileURLToPath(import.meta.url);
|
|
15
22
|
const __dirname = path.dirname(__filename);
|
|
16
23
|
const { version } = JSON.parse(readFileSync(path.resolve(__dirname, '../package.json'), 'utf-8'));
|
|
24
|
+
const FORMAT_PROPERTY = { type: 'string', enum: ['text', 'json', 'toon'], default: 'text', description: 'Output format.' };
|
|
25
|
+
const SELECTOR_PROPERTIES = {
|
|
26
|
+
workspacePath: { type: 'string', description: 'Absolute Java workspace path. Maven is optional.' },
|
|
27
|
+
jarPath: { type: 'string', description: 'Absolute path to an exact JAR. Fastest selector.' },
|
|
28
|
+
jarDirectory: { type: 'string', description: 'Absolute directory to search for a JAR on demand.' },
|
|
29
|
+
jarNamePrefix: { type: 'string', description: 'JAR basename prefix.' },
|
|
30
|
+
coordinates: { type: 'string', description: 'groupId:artifactId[:version[:classifier]].' },
|
|
31
|
+
};
|
|
17
32
|
export class JavaClassAnalyzerMCPServer {
|
|
18
33
|
server;
|
|
19
|
-
analyzer;
|
|
20
|
-
scanner;
|
|
21
|
-
decompiler;
|
|
34
|
+
analyzer = new JavaClassAnalyzer();
|
|
35
|
+
scanner = new DependencyScanner();
|
|
36
|
+
decompiler = new DecompilerService();
|
|
22
37
|
constructor() {
|
|
23
|
-
this.server = new Server({
|
|
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();
|
|
38
|
+
this.server = new Server({ name: 'java-inspector', version }, { capabilities: { tools: {}, logging: {} } });
|
|
35
39
|
this.setupHandlers();
|
|
36
40
|
}
|
|
37
41
|
setupHandlers() {
|
|
38
|
-
this.server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
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
|
-
});
|
|
42
|
+
this.server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: [
|
|
43
|
+
{
|
|
44
|
+
name: 'scan_project',
|
|
45
|
+
description: 'Start, refresh, or poll the non-blocking Maven dependency scan. Startup automatically calls this for the highest-level pom.xml files.',
|
|
46
|
+
inputSchema: { type: 'object', properties: { workspacePath: { type: 'string' }, forceRefresh: { type: 'boolean', default: false }, format: FORMAT_PROPERTY }, required: ['workspacePath'] },
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
name: 'find_jar',
|
|
50
|
+
description: 'Find JAR paths by exact path, filename, prefix, substring, or Maven coordinates without opening the JAR.',
|
|
51
|
+
inputSchema: { type: 'object', properties: { ...SELECTOR_PROPERTIES, match: { type: 'string', enum: ['exact', 'prefix', 'contains'], default: 'prefix' }, limit: { type: 'number', default: 20 }, format: FORMAT_PROPERTY } },
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
name: 'inspect_jar',
|
|
55
|
+
description: 'Inspect one JAR: manifest, Maven coordinates, layout, packages, classes, resources, and nested JAR metadata.',
|
|
56
|
+
inputSchema: { type: 'object', properties: { ...SELECTOR_PROPERTIES, query: { type: 'string' }, offset: { type: 'number', default: 1 }, limit: { type: 'number', default: 100 }, format: FORMAT_PROPERTY } },
|
|
57
|
+
},
|
|
58
|
+
{
|
|
59
|
+
name: 'search_class',
|
|
60
|
+
description: 'Search the live partial index, then foreground-scan only relevant JARs without waiting for background scan completion.',
|
|
61
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' }, ...SELECTOR_PROPERTIES, includeJdk: { type: 'boolean', default: false }, mode: { type: 'string', enum: ['fast', 'balanced'], default: 'balanced' }, limit: { type: 'number', default: 20 }, format: FORMAT_PROPERTY }, required: ['query'] },
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
name: 'search_code',
|
|
65
|
+
description: 'Find method/field declarations, annotations, references, and real string constants from lazy class-file metadata.',
|
|
66
|
+
inputSchema: { type: 'object', properties: { query: { type: 'string' }, kind: { type: 'string', enum: ['method', 'field', 'annotation', 'reference', 'string'] }, ...SELECTOR_PROPERTIES, mode: { type: 'string', enum: ['fast', 'balanced'], default: 'balanced' }, limit: { type: 'number', default: 20 }, format: FORMAT_PROPERTY }, required: ['query', 'kind'] },
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
name: 'find_implementations',
|
|
70
|
+
description: 'Find direct or transitive implementations/subtypes using lazy deep class metadata.',
|
|
71
|
+
inputSchema: { type: 'object', properties: { className: { type: 'string' }, ...SELECTOR_PROPERTIES, transitive: { type: 'boolean', default: true }, mode: { type: 'string', enum: ['fast', 'balanced'], default: 'balanced' }, limit: { type: 'number', default: 50 }, format: FORMAT_PROPERTY }, required: ['className'] },
|
|
72
|
+
},
|
|
73
|
+
{
|
|
74
|
+
name: 'inspect_class',
|
|
75
|
+
description: 'Resolve and inspect a class from Maven, a local JAR, or the JDK. Views: source, API, hierarchy, bytecode, or all.',
|
|
76
|
+
inputSchema: { type: 'object', properties: { className: { type: 'string' }, ...SELECTOR_PROPERTIES, view: { type: 'string', enum: ['source', 'api', 'hierarchy', 'bytecode', 'all'], default: 'source' }, methodName: { type: 'string' }, paramTypes: { type: 'array', items: { type: 'string' } }, offset: { type: 'number', default: 1 }, limit: { type: 'number', default: 0 }, useCache: { type: 'boolean', default: true }, format: FORMAT_PROPERTY }, required: ['className'] },
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
name: 'explain_dependency',
|
|
80
|
+
description: 'Run a filtered Maven dependency tree and explain why an artifact is present.',
|
|
81
|
+
inputSchema: { type: 'object', properties: { workspacePath: { type: 'string' }, coordinates: { type: 'string' }, jarPath: { type: 'string' }, format: FORMAT_PROPERTY }, required: ['workspacePath'] },
|
|
82
|
+
},
|
|
83
|
+
{
|
|
84
|
+
name: 'search_resources',
|
|
85
|
+
description: 'Search resource paths or bounded text resource content in selected JARs.',
|
|
86
|
+
inputSchema: { type: 'object', properties: { ...SELECTOR_PROPERTIES, pathQuery: { type: 'string', default: '' }, contentQuery: { type: 'string' }, limit: { type: 'number', default: 20 }, format: FORMAT_PROPERTY } },
|
|
87
|
+
},
|
|
88
|
+
{
|
|
89
|
+
name: 'read_resource',
|
|
90
|
+
description: 'Read an exact text resource with safe line pagination. Binary resources are rejected.',
|
|
91
|
+
inputSchema: { type: 'object', properties: { ...SELECTOR_PROPERTIES, resourcePath: { type: 'string' }, offset: { type: 'number', default: 1 }, limit: { type: 'number', default: 200 }, format: FORMAT_PROPERTY }, required: ['resourcePath'] },
|
|
92
|
+
},
|
|
93
|
+
] }));
|
|
204
94
|
this.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
205
|
-
const { name, arguments: args } = request.params;
|
|
95
|
+
const { name, arguments: args = {} } = request.params;
|
|
206
96
|
const sendProgress = async (message, progress, total) => {
|
|
207
97
|
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
|
-
});
|
|
98
|
+
await extra.sendNotification({ method: 'notifications/progress', params: { progressToken: extra._meta.progressToken, message, progress, total } });
|
|
217
99
|
}
|
|
218
|
-
console.error(`[${name}] ${message}`);
|
|
219
100
|
};
|
|
220
101
|
try {
|
|
221
|
-
await sendProgress(`Starting tool: ${name}`);
|
|
222
102
|
switch (name) {
|
|
223
|
-
case '
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
case '
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
case '
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
case '
|
|
233
|
-
|
|
234
|
-
return await this.handleSearchClass(args, sendProgress);
|
|
235
|
-
case 'get_inheritance_tree':
|
|
236
|
-
await this.validateProjectPath(args.projectPath);
|
|
237
|
-
return await this.handleGetInheritanceTree(args, sendProgress);
|
|
238
|
-
default:
|
|
239
|
-
throw new Error(`Unknown tool: ${name}`);
|
|
103
|
+
case 'scan_project': return this.handleScanProject(args, sendProgress);
|
|
104
|
+
case 'find_jar': return this.handleFindJar(args);
|
|
105
|
+
case 'inspect_jar': return this.handleInspectJar(args);
|
|
106
|
+
case 'search_class': return this.handleSearchClass(args, sendProgress);
|
|
107
|
+
case 'search_code': return this.handleSearchCode(args, sendProgress);
|
|
108
|
+
case 'find_implementations': return this.handleFindImplementations(args, sendProgress);
|
|
109
|
+
case 'inspect_class': return this.handleInspectClass(args, sendProgress);
|
|
110
|
+
case 'explain_dependency': return this.handleExplainDependency(args, sendProgress);
|
|
111
|
+
case 'search_resources': return this.handleSearchResources(args);
|
|
112
|
+
case 'read_resource': return this.handleReadResource(args);
|
|
113
|
+
default: throw new Error(`Unknown tool: ${name}`);
|
|
240
114
|
}
|
|
241
115
|
}
|
|
242
116
|
catch (error) {
|
|
243
|
-
const
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
return {
|
|
247
|
-
content: [
|
|
248
|
-
{
|
|
249
|
-
type: 'text',
|
|
250
|
-
text: `Tool call failed: ${errorMessage}`,
|
|
251
|
-
},
|
|
252
|
-
],
|
|
253
|
-
isError: true,
|
|
254
|
-
};
|
|
117
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
118
|
+
await sendProgress(`Failed: ${message}`);
|
|
119
|
+
return { content: [{ type: 'text', text: `Tool call failed: ${message}` }], isError: true };
|
|
255
120
|
}
|
|
256
121
|
});
|
|
257
122
|
}
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
123
|
+
async handleScanProject(args, sendProgress) {
|
|
124
|
+
const workspacePath = await this.validateWorkspacePath(args.workspacePath);
|
|
125
|
+
const pomRoots = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
126
|
+
if (pomRoots.length === 0) {
|
|
127
|
+
const structured = { workspacePath, status: 'no_maven_project', pomRoots: [], message: 'Direct/local JAR tools remain available.' };
|
|
128
|
+
return this.formatResponse('No Maven project found. Direct and local JAR inspection is available.', structured, args.format);
|
|
261
129
|
}
|
|
262
|
-
|
|
130
|
+
await sendProgress?.(`Starting/polling ${pomRoots.length} Maven context(s)`, 0, pomRoots.length);
|
|
131
|
+
const projects = [];
|
|
132
|
+
for (let i = 0; i < pomRoots.length; i++) {
|
|
133
|
+
const result = await this.scanner.scanProject(pomRoots[i], Boolean(args.forceRefresh), async (message) => sendProgress?.(`[${path.basename(pomRoots[i])}] ${message}`, i, pomRoots.length));
|
|
134
|
+
projects.push({ projectPath: pomRoots[i], ...result });
|
|
135
|
+
}
|
|
136
|
+
const complete = projects.every(project => project.status === 'complete');
|
|
137
|
+
const structured = { workspacePath, status: complete ? 'complete' : 'in_progress', pomRoots, projects };
|
|
138
|
+
const text = complete ? `Maven scan complete for ${pomRoots.length} top-level project(s).` : `Maven auto-scan is running for ${pomRoots.length} top-level project(s). Tools can be used immediately.`;
|
|
139
|
+
return this.formatResponse(text, structured, args.format);
|
|
140
|
+
}
|
|
141
|
+
async handleFindJar(args) {
|
|
142
|
+
const selector = await this.selectorFromArgs(args);
|
|
143
|
+
const result = await artifactService.findJars(selector, args.match ?? 'prefix', this.clamp(args.limit, 1, 100, 20));
|
|
144
|
+
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.';
|
|
145
|
+
if (!result.complete)
|
|
146
|
+
text += '\n\nJAR search is partial.';
|
|
147
|
+
if (result.errors.length)
|
|
148
|
+
text += `\n${result.errors.map(error => `- ${error.contextPath ?? error.jarPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
149
|
+
return this.formatResponse(text, result, args.format);
|
|
150
|
+
}
|
|
151
|
+
async handleInspectJar(args) {
|
|
152
|
+
const inspected = await artifactService.inspectJar(await this.selectorFromArgs(args));
|
|
153
|
+
if (!inspected.index)
|
|
154
|
+
return this.ambiguityResponse('JAR selector', inspected.candidates ?? [], args.format);
|
|
155
|
+
const index = inspected.index;
|
|
156
|
+
const query = String(args.query ?? '').toLowerCase();
|
|
157
|
+
const offset = this.clamp(args.offset, 1, Number.MAX_SAFE_INTEGER, 1);
|
|
158
|
+
const limit = this.clamp(args.limit, 1, 1000, 100);
|
|
159
|
+
const classes = index.classes.filter(item => !item.isInner && (!query || item.className.toLowerCase().includes(query)));
|
|
160
|
+
const resources = index.resources.filter(item => !query || item.path.toLowerCase().includes(query));
|
|
161
|
+
const entries = [
|
|
162
|
+
...classes.map(item => ({ type: item.isSource ? 'source' : 'class', path: item.entryPath, className: item.className })),
|
|
163
|
+
...resources.map(item => ({ type: 'resource', path: item.path, size: item.size })),
|
|
164
|
+
].slice(offset - 1, offset - 1 + limit);
|
|
165
|
+
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 };
|
|
166
|
+
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')}`;
|
|
167
|
+
return this.formatResponse(text, structured, args.format);
|
|
168
|
+
}
|
|
169
|
+
async handleSearchClass(args, sendProgress) {
|
|
170
|
+
if (!args.query || typeof args.query !== 'string')
|
|
171
|
+
throw new Error('query is required');
|
|
172
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
173
|
+
await sendProgress?.(`Searching for class: ${args.query}`, 0, 100);
|
|
174
|
+
const result = await artifactService.searchClasses(args.query, selector, this.clamp(args.limit, 1, 100, 20), args.mode === 'fast' ? 5 : 20);
|
|
175
|
+
const jdkResults = args.includeJdk ? await jdkSourceService.searchClasses(args.query, this.clamp(args.limit, 1, 100, 20)) : [];
|
|
176
|
+
const structured = { ...result, jdkResults, backgroundScanProgress: await this.aggregateScanProgress(selector.workspacePath) };
|
|
177
|
+
const totalResults = result.results.length + jdkResults.length;
|
|
178
|
+
let text = totalResults ? `Found ${totalResults} class candidate(s):\n${[
|
|
179
|
+
...result.results.map(item => `- ${item.className} -> ${item.jarPath}`),
|
|
180
|
+
...jdkResults.map(item => `- ${item.className} -> jdk:${item.module ?? 'unknown-module'}`),
|
|
181
|
+
].join('\n')}` : `No class found matching "${args.query}".`;
|
|
182
|
+
if (!result.complete)
|
|
183
|
+
text += `\n\nSearch is partial; ${result.remainingJarCount} candidate JAR(s) remain.`;
|
|
184
|
+
if (result.errors.length)
|
|
185
|
+
text += `\n\nScan errors:\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
186
|
+
return this.formatResponse(text, structured, args.format);
|
|
187
|
+
}
|
|
188
|
+
async handleSearchCode(args, sendProgress) {
|
|
189
|
+
if (!args.query || !args.kind)
|
|
190
|
+
throw new Error('query and kind are required');
|
|
191
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
192
|
+
await sendProgress?.(`Searching deep metadata for ${args.kind}: ${args.query}`, 0, 100);
|
|
193
|
+
const result = await artifactService.searchCode(args.query, args.kind, selector, this.clamp(args.limit, 1, 100, 20), args.mode === 'fast' ? 2 : 5);
|
|
194
|
+
let text = result.matches.length ? `Found ${result.matches.length} match(es):\n${result.matches.map(item => `- ${item.className}${item.member ? `#${item.member}` : ''} -> ${item.jarPath}`).join('\n')}` : `No ${args.kind} match found for "${args.query}".`;
|
|
195
|
+
if (!result.complete)
|
|
196
|
+
text += `\n\nSearch is partial; ${result.remainingJarCount} JAR(s) remain.`;
|
|
197
|
+
if (result.errors.length)
|
|
198
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
199
|
+
return this.formatResponse(text, result, args.format);
|
|
200
|
+
}
|
|
201
|
+
async handleFindImplementations(args, sendProgress) {
|
|
202
|
+
this.validateClassName(args.className);
|
|
203
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
204
|
+
await sendProgress?.(`Finding implementations of ${args.className}`, 0, 100);
|
|
205
|
+
const result = await artifactService.findImplementations(args.className, selector, args.transitive !== false, this.clamp(args.limit, 1, 200, 50), args.mode === 'fast' ? 2 : 5);
|
|
206
|
+
let text = result.implementations.length ? `Found ${result.implementations.length} implementation(s):\n${result.implementations.map(item => `- ${item.className} -> ${item.jarPath}`).join('\n')}` : `No implementations found for ${args.className}${result.complete ? '.' : ' in the currently deep-indexed JARs.'}`;
|
|
207
|
+
if (result.errors.length)
|
|
208
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
209
|
+
return this.formatResponse(text, result, args.format);
|
|
210
|
+
}
|
|
211
|
+
async handleInspectClass(args, sendProgress) {
|
|
212
|
+
this.validateClassName(args.className);
|
|
213
|
+
const selector = await this.selectorFromArgs(args, true);
|
|
214
|
+
const contextPath = selector.workspacePath || (selector.jarPath ? path.dirname(selector.jarPath) : process.cwd());
|
|
215
|
+
const view = args.view ?? 'source';
|
|
216
|
+
await sendProgress?.(`Resolving ${args.className}`, 0, 100);
|
|
217
|
+
if (jdkSourceService.isLikelyJdkClass(args.className) && !selector.jarPath && !selector.jarNamePrefix && !selector.jarDirectory && !selector.coordinates) {
|
|
218
|
+
const result = await this.inspectJdkClass(args.className, contextPath, view, args);
|
|
219
|
+
return this.formatResponse(this.classInspectionText(args.className, result), result, args.format);
|
|
220
|
+
}
|
|
221
|
+
const resolved = await artifactService.resolveClass(args.className, selector);
|
|
222
|
+
const exact = resolved.results.filter(item => item.className.toLowerCase() === String(args.className).toLowerCase() || item.simpleName.toLowerCase() === String(args.className).toLowerCase());
|
|
223
|
+
const unique = this.uniqueClassCandidates(exact.length ? exact : resolved.results);
|
|
224
|
+
if (!unique.length)
|
|
225
|
+
throw new Error(`Class not found: ${args.className}`);
|
|
226
|
+
if (unique.length > 1)
|
|
227
|
+
return this.ambiguityResponse('Class', unique, args.format);
|
|
228
|
+
let candidate = unique[0];
|
|
229
|
+
let inspection = await artifactService.inspectJar({ jarPath: candidate.jarPath, workspacePath: selector.workspacePath });
|
|
230
|
+
let classEntry = inspection.index.classes.find(item => item.className === candidate.className && !item.isSource) ?? inspection.index.classes.find(item => item.className === candidate.className);
|
|
231
|
+
if (!classEntry)
|
|
232
|
+
throw new Error(`Class entry not found after indexing: ${candidate.className}`);
|
|
233
|
+
if (classEntry.isSource && view !== 'source') {
|
|
234
|
+
const binaryJar = candidate.jarPath.replace(/-sources\.jar$/i, '.jar');
|
|
235
|
+
if (!(await fs.pathExists(binaryJar)))
|
|
236
|
+
throw new Error(`API/bytecode view requires a binary JAR; only source JAR is available: ${candidate.jarPath}`);
|
|
237
|
+
candidate = { ...candidate, jarPath: binaryJar };
|
|
238
|
+
inspection = await artifactService.inspectJar({ jarPath: binaryJar, workspacePath: selector.workspacePath });
|
|
239
|
+
classEntry = inspection.index.classes.find(item => item.className === candidate.className && !item.isSource);
|
|
240
|
+
if (!classEntry)
|
|
241
|
+
throw new Error(`Binary class not found for source: ${candidate.className}`);
|
|
242
|
+
}
|
|
243
|
+
const result = { className: candidate.className, jarPath: candidate.jarPath, entryPath: classEntry.entryPath, origin: candidate.origin, backgroundSearchComplete: resolved.complete };
|
|
244
|
+
if (view === 'source' || view === 'all') {
|
|
245
|
+
await sendProgress?.('Loading source/decompiling class', 35, 100);
|
|
246
|
+
result.source = await this.loadClassSource(candidate, classEntry.entryPath, contextPath, args);
|
|
247
|
+
}
|
|
248
|
+
const normalEntryPath = `${candidate.className.replace(/\./g, '/')}.class`;
|
|
249
|
+
const needsExtractedClass = classEntry.entryPath !== normalEntryPath;
|
|
250
|
+
let inspectionClassFile;
|
|
251
|
+
if (view === 'api' || view === 'all') {
|
|
252
|
+
const bytes = await jarIndexer.readEntry(candidate.jarPath, classEntry.entryPath, 20 * 1024 * 1024);
|
|
253
|
+
const classFileMetadata = ClassFileMetadataReader.read(bytes);
|
|
254
|
+
if (needsExtractedClass)
|
|
255
|
+
inspectionClassFile = await this.getInspectionClassFile(candidate, classEntry.entryPath, contextPath, bytes);
|
|
256
|
+
const summary = inspectionClassFile
|
|
257
|
+
? await this.analyzer.analyzeClassFile(candidate.className, inspectionClassFile, contextPath)
|
|
258
|
+
: await this.analyzer.analyzeClassFromJar(candidate.className, candidate.jarPath, contextPath, true);
|
|
259
|
+
result.api = { summary, classFileMetadata };
|
|
260
|
+
}
|
|
261
|
+
if (view === 'hierarchy' || view === 'all')
|
|
262
|
+
result.hierarchy = await this.resolveHierarchy(candidate, selector, contextPath, classEntry.entryPath);
|
|
263
|
+
if (view === 'bytecode' || view === 'all') {
|
|
264
|
+
if (needsExtractedClass && !inspectionClassFile)
|
|
265
|
+
inspectionClassFile = await this.getInspectionClassFile(candidate, classEntry.entryPath, contextPath);
|
|
266
|
+
result.bytecode = inspectionClassFile
|
|
267
|
+
? await this.analyzer.getBytecodeFromClassFile(inspectionClassFile, contextPath)
|
|
268
|
+
: await this.analyzer.getBytecode(candidate.className, contextPath, candidate.jarPath);
|
|
269
|
+
}
|
|
270
|
+
await sendProgress?.('Class inspection complete', 100, 100);
|
|
271
|
+
return this.formatResponse(this.classInspectionText(candidate.className, result), result, args.format);
|
|
272
|
+
}
|
|
273
|
+
async handleExplainDependency(args, sendProgress) {
|
|
274
|
+
const workspacePath = await this.validateWorkspacePath(args.workspacePath);
|
|
275
|
+
let coordinates = args.coordinates;
|
|
276
|
+
if (!coordinates && args.jarPath) {
|
|
277
|
+
const inspected = await artifactService.inspectJar({ jarPath: args.jarPath, workspacePath });
|
|
278
|
+
const coordinate = inspected.index?.mavenCoordinates[0];
|
|
279
|
+
if (coordinate?.groupId && coordinate.artifactId)
|
|
280
|
+
coordinates = `${coordinate.groupId}:${coordinate.artifactId}`;
|
|
281
|
+
}
|
|
282
|
+
if (!coordinates)
|
|
283
|
+
throw new Error('coordinates or a JAR containing Maven pom.properties is required');
|
|
284
|
+
const contexts = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
285
|
+
const outputs = [];
|
|
286
|
+
for (let i = 0; i < contexts.length; i++) {
|
|
263
287
|
try {
|
|
264
|
-
|
|
265
|
-
return { content: [{ type: 'text', text: toonText }] };
|
|
288
|
+
outputs.push({ projectPath: contexts[i], output: await this.scanner.explainDependency(contexts[i], coordinates) });
|
|
266
289
|
}
|
|
267
|
-
catch {
|
|
268
|
-
|
|
290
|
+
catch (error) {
|
|
291
|
+
outputs.push({ projectPath: contexts[i], error: error instanceof Error ? error.message : String(error) });
|
|
269
292
|
}
|
|
293
|
+
await sendProgress?.(`Checked ${i + 1}/${contexts.length} Maven context(s)`, i + 1, contexts.length);
|
|
270
294
|
}
|
|
271
|
-
|
|
295
|
+
const text = outputs.map(item => `Project: ${item.projectPath}\n${item.output || `Error: ${item.error}`}`).join('\n\n');
|
|
296
|
+
return this.formatResponse(text, { coordinates, outputs }, args.format);
|
|
272
297
|
}
|
|
273
|
-
async
|
|
274
|
-
const
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
if (
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
298
|
+
async handleSearchResources(args) {
|
|
299
|
+
const result = await artifactService.searchResources(await this.selectorFromArgs(args, true), args.pathQuery ?? '', args.contentQuery, this.clamp(args.limit, 1, 100, 20));
|
|
300
|
+
let text = result.results.length ? `Found ${result.results.length} resource(s):\n${result.results.map(item => `- ${item.resourcePath} -> ${item.jarPath}`).join('\n')}` : 'No matching resources found.';
|
|
301
|
+
if (!result.complete)
|
|
302
|
+
text += '\n\nResource search is partial.';
|
|
303
|
+
if (result.errors.length)
|
|
304
|
+
text += `\n${result.errors.map(error => `- ${error.jarPath ?? error.contextPath ?? 'workspace'}: ${error.message}`).join('\n')}`;
|
|
305
|
+
return this.formatResponse(text, result, args.format);
|
|
306
|
+
}
|
|
307
|
+
async handleReadResource(args) {
|
|
308
|
+
if (!args.resourcePath)
|
|
309
|
+
throw new Error('resourcePath is required');
|
|
310
|
+
const result = await artifactService.readResource(await this.selectorFromArgs(args), args.resourcePath, args.offset, args.limit);
|
|
311
|
+
return this.formatResponse(`Resource ${result.resourcePath} (${result.startLine}-${result.endLine}/${result.totalLines}):\n\n${result.text}`, result, args.format);
|
|
312
|
+
}
|
|
313
|
+
async loadClassSource(candidate, entryPath, contextPath, args) {
|
|
314
|
+
const sameJarIndex = await jarIndexer.getLightIndex(candidate.jarPath, contextPath);
|
|
315
|
+
const embeddedSource = sameJarIndex.classes.find(item => item.className === candidate.className && item.isSource);
|
|
316
|
+
if (embeddedSource) {
|
|
317
|
+
return this.sliceSource((await jarIndexer.readEntry(candidate.jarPath, embeddedSource.entryPath, 10 * 1024 * 1024)).toString('utf8'), args);
|
|
292
318
|
}
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
let text = `Background dependency scan is in progress.\n\n`;
|
|
300
|
-
if (result.message) {
|
|
301
|
-
text += `${result.message}\n\n`;
|
|
319
|
+
const sourceJar = candidate.jarPath.replace(/\.jar$/i, '-sources.jar');
|
|
320
|
+
if (await fs.pathExists(sourceJar)) {
|
|
321
|
+
const sourceIndex = await jarIndexer.getLightIndex(sourceJar, contextPath);
|
|
322
|
+
const sourceEntry = sourceIndex.classes.find(item => item.className === candidate.className && item.isSource);
|
|
323
|
+
if (sourceEntry)
|
|
324
|
+
return this.sliceSource((await jarIndexer.readEntry(sourceJar, sourceEntry.entryPath, 10 * 1024 * 1024)).toString('utf8'), args);
|
|
302
325
|
}
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
text += `You can already use \`decompile_class\` and \`analyze_class\` — the server will resolve classes on-demand. `;
|
|
306
|
-
text += `Call \`scan_dependencies\` again later to check progress.`;
|
|
307
|
-
const structured = {
|
|
308
|
-
status: result.status,
|
|
309
|
-
jarCount: result.jarCount,
|
|
310
|
-
progress: result.progress,
|
|
311
|
-
};
|
|
312
|
-
return this.formatResponse(text, structured, format);
|
|
326
|
+
const source = await this.decompiler.decompileClassFromJar(candidate.className, candidate.jarPath, contextPath, entryPath, args.useCache !== false);
|
|
327
|
+
return this.sliceSource(source, args);
|
|
313
328
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
329
|
+
sliceSource(source, args) {
|
|
330
|
+
if (args.methodName) {
|
|
331
|
+
const extracted = extractMethod(source, args.methodName, args.paramTypes);
|
|
332
|
+
if (!extracted)
|
|
333
|
+
throw new Error(`Method not found: ${args.methodName}`);
|
|
334
|
+
return extracted;
|
|
335
|
+
}
|
|
336
|
+
const lines = source.split('\n');
|
|
337
|
+
const offset = this.clamp(args.offset, 1, Number.MAX_SAFE_INTEGER, 1);
|
|
338
|
+
const requestedLimit = Number(args.limit ?? 0);
|
|
339
|
+
if (offset === 1 && requestedLimit <= 0)
|
|
340
|
+
return source;
|
|
341
|
+
const end = requestedLimit > 0 ? Math.min(lines.length, offset - 1 + requestedLimit) : lines.length;
|
|
342
|
+
return lines.slice(offset - 1, end).join('\n');
|
|
343
|
+
}
|
|
344
|
+
async inspectJdkClass(className, contextPath, view, args) {
|
|
345
|
+
const result = { className, origin: 'jdk' };
|
|
346
|
+
if (view === 'source' || view === 'all') {
|
|
347
|
+
const source = await jdkSourceService.getSource(className);
|
|
348
|
+
if (source)
|
|
349
|
+
result.source = this.sliceSource(source, args);
|
|
350
|
+
else
|
|
351
|
+
result.sourceUnavailable = true;
|
|
352
|
+
}
|
|
353
|
+
if (view === 'api' || view === 'all' || view === 'hierarchy')
|
|
354
|
+
result.api = await this.analyzer.analyzeJdkClass(className, contextPath);
|
|
355
|
+
if (view === 'hierarchy' || view === 'all')
|
|
356
|
+
result.hierarchy = await this.resolveJdkHierarchy(className, contextPath);
|
|
357
|
+
if (view === 'bytecode' || view === 'all')
|
|
358
|
+
result.bytecode = await this.analyzer.getBytecode(className, contextPath);
|
|
359
|
+
return result;
|
|
360
|
+
}
|
|
361
|
+
async resolveJdkHierarchy(className, contextPath) {
|
|
362
|
+
const hierarchy = [];
|
|
363
|
+
const visited = new Set();
|
|
364
|
+
let current = className;
|
|
365
|
+
while (current && hierarchy.length < 20 && !visited.has(current)) {
|
|
366
|
+
visited.add(current);
|
|
367
|
+
hierarchy.push({ className: current, level: hierarchy.length, resolved: true });
|
|
368
|
+
try {
|
|
369
|
+
current = (await this.analyzer.analyzeJdkClass(current, contextPath)).superClass;
|
|
333
370
|
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
let finalSourceCode = sourceCode;
|
|
338
|
-
let sliceInfo = '';
|
|
339
|
-
let extractedMethodRange;
|
|
340
|
-
if (methodName) {
|
|
341
|
-
const extracted = extractMethod(sourceCode, methodName, paramTypes);
|
|
342
|
-
if (!extracted) {
|
|
343
|
-
const text = `Method "${methodName}" not found in class ${className}${paramTypes ? ' with paramTypes ' + JSON.stringify(paramTypes) : ''}.`;
|
|
344
|
-
const structured = { className, totalLines, methods, methodName, paramTypes };
|
|
345
|
-
return this.formatResponse(text, structured, format);
|
|
346
|
-
}
|
|
347
|
-
finalSourceCode = extracted;
|
|
348
|
-
sliceInfo = ` (method: ${methodName}${paramTypes ? ' ' + JSON.stringify(paramTypes) : ''})`;
|
|
349
|
-
extractedMethodRange = methods.find(m => {
|
|
350
|
-
if (m.name !== methodName)
|
|
351
|
-
return false;
|
|
352
|
-
if (!paramTypes || paramTypes.length === 0)
|
|
353
|
-
return true;
|
|
354
|
-
const sigParams = extractParamTypes(m.signature);
|
|
355
|
-
return matchParamTypes(sigParams, paramTypes);
|
|
356
|
-
});
|
|
371
|
+
catch {
|
|
372
|
+
hierarchy[hierarchy.length - 1].resolved = false;
|
|
373
|
+
break;
|
|
357
374
|
}
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
375
|
+
}
|
|
376
|
+
return hierarchy.reverse().map((entry, level) => ({ ...entry, level }));
|
|
377
|
+
}
|
|
378
|
+
async resolveHierarchy(candidate, selector, contextPath, firstEntryPath) {
|
|
379
|
+
const chain = [];
|
|
380
|
+
const visited = new Set();
|
|
381
|
+
let current = candidate.className;
|
|
382
|
+
let currentJar = candidate.jarPath;
|
|
383
|
+
let entryPath = firstEntryPath;
|
|
384
|
+
while (current && chain.length < 20 && !visited.has(current)) {
|
|
385
|
+
visited.add(current);
|
|
386
|
+
try {
|
|
387
|
+
let analysis;
|
|
388
|
+
if (jdkSourceService.isLikelyJdkClass(current))
|
|
389
|
+
analysis = await this.analyzer.analyzeJdkClass(current, contextPath);
|
|
390
|
+
else if (currentJar && entryPath) {
|
|
391
|
+
const metadata = ClassFileMetadataReader.read(await jarIndexer.readEntry(currentJar, entryPath, 20 * 1024 * 1024));
|
|
392
|
+
analysis = { className: current, packageName: current.includes('.') ? current.substring(0, current.lastIndexOf('.')) : '', modifiers: [], superClass: metadata.superClass, interfaces: metadata.interfaces, fields: [], methods: [] };
|
|
393
|
+
}
|
|
394
|
+
else if (currentJar)
|
|
395
|
+
analysis = await this.analyzer.analyzeClassFromJar(current, currentJar, contextPath, false);
|
|
396
|
+
else
|
|
397
|
+
throw new Error('unresolved');
|
|
398
|
+
chain.push({ className: current, level: chain.length, resolved: true });
|
|
399
|
+
const analyzedJar = currentJar;
|
|
400
|
+
current = analysis.superClass;
|
|
401
|
+
entryPath = undefined;
|
|
402
|
+
if (current && !jdkSourceService.isLikelyJdkClass(current)) {
|
|
403
|
+
currentJar = undefined;
|
|
404
|
+
if (analyzedJar) {
|
|
405
|
+
const sameJarEntry = (await jarIndexer.getLightIndex(analyzedJar, contextPath)).classes
|
|
406
|
+
.find(item => item.className === current && !item.isSource);
|
|
407
|
+
if (sameJarEntry) {
|
|
408
|
+
currentJar = analyzedJar;
|
|
409
|
+
entryPath = sameJarEntry.entryPath;
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (!currentJar) {
|
|
413
|
+
const next = (await artifactService.resolveClass(current, selector)).results.find(item => item.className === current);
|
|
414
|
+
currentJar = next?.jarPath;
|
|
415
|
+
if (next)
|
|
416
|
+
entryPath = (await jarIndexer.getLightIndex(next.jarPath, contextPath)).classes.find(item => item.className === current && !item.isSource)?.entryPath;
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
else if (current) {
|
|
420
|
+
currentJar = undefined;
|
|
365
421
|
}
|
|
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
422
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
const structured = {
|
|
378
|
-
className,
|
|
379
|
-
totalLines,
|
|
380
|
-
sourceCode: finalSourceCode,
|
|
381
|
-
methods,
|
|
382
|
-
};
|
|
383
|
-
if (extractedMethodRange) {
|
|
384
|
-
structured.extractedMethod = {
|
|
385
|
-
name: extractedMethodRange.name,
|
|
386
|
-
startLine: extractedMethodRange.startLine,
|
|
387
|
-
endLine: extractedMethodRange.endLine,
|
|
388
|
-
};
|
|
423
|
+
catch {
|
|
424
|
+
chain.push({ className: current, level: chain.length, resolved: false });
|
|
425
|
+
break;
|
|
389
426
|
}
|
|
390
|
-
return this.formatResponse(text, structured, format);
|
|
391
|
-
}
|
|
392
|
-
catch (error) {
|
|
393
|
-
const errorMessage = error instanceof Error ? error.message : String(error);
|
|
394
|
-
const duration = ((performance.now() - start) / 1000).toFixed(2);
|
|
395
|
-
logger.error(`[TOOL:decompile_class] Failed after ${duration}s: ${errorMessage}`);
|
|
396
|
-
await sendProgress?.(`Decompilation failed: ${errorMessage}`);
|
|
397
|
-
const text = `Decompilation failed: ${errorMessage}`;
|
|
398
|
-
const structured = { className, error: errorMessage };
|
|
399
|
-
return this.formatResponse(text, structured, format);
|
|
400
427
|
}
|
|
428
|
+
return chain.reverse().map((entry, level) => ({ ...entry, level }));
|
|
401
429
|
}
|
|
402
|
-
async
|
|
403
|
-
const
|
|
404
|
-
|
|
405
|
-
const
|
|
406
|
-
const
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
// Check if index exists, create if not
|
|
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';
|
|
430
|
+
async getInspectionClassFile(candidate, entryPath, contextPath, existingBytes) {
|
|
431
|
+
const fingerprint = await jarIndexer.fingerprint(candidate.jarPath);
|
|
432
|
+
const simpleName = candidate.className.substring(candidate.className.lastIndexOf('.') + 1);
|
|
433
|
+
const classKey = createHash('sha256').update(`${candidate.className}\n${entryPath}`).digest('hex').substring(0, 12);
|
|
434
|
+
const target = path.join(getResultCacheDir(contextPath), fingerprint.key, 'class-files', `${simpleName}-${classKey}.class`);
|
|
435
|
+
if (!(await fs.pathExists(target))) {
|
|
436
|
+
const bytes = existingBytes ?? await jarIndexer.readEntry(candidate.jarPath, entryPath, 20 * 1024 * 1024);
|
|
437
|
+
await fs.outputFile(target, bytes);
|
|
431
438
|
}
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
text +=
|
|
439
|
+
return target;
|
|
440
|
+
}
|
|
441
|
+
classInspectionText(className, result) {
|
|
442
|
+
let text = `Class inspection: ${className}\nOrigin: ${result.origin}${result.jarPath ? `\nJAR: ${result.jarPath}` : ''}`;
|
|
443
|
+
if (result.source)
|
|
444
|
+
text += `\n\nSource:\n\n\`\`\`java\n${result.source}\n\`\`\``;
|
|
445
|
+
if (result.api)
|
|
446
|
+
text += `\n\nAPI:\n${JSON.stringify(result.api, null, 2)}`;
|
|
447
|
+
if (result.hierarchy)
|
|
448
|
+
text += `\n\nHierarchy:\n${result.hierarchy.map((item) => `${' '.repeat(item.level)}${item.className}${item.resolved ? '' : ' (unresolved)'}`).join('\n')}`;
|
|
449
|
+
if (result.bytecode)
|
|
450
|
+
text += `\n\nBytecode:\n\n\`\`\`text\n${result.bytecode}\n\`\`\``;
|
|
451
|
+
return text;
|
|
452
|
+
}
|
|
453
|
+
uniqueClassCandidates(candidates) {
|
|
454
|
+
const map = new Map();
|
|
455
|
+
for (const candidate of candidates)
|
|
456
|
+
map.set(`${candidate.className}::${path.resolve(candidate.jarPath)}`, candidate);
|
|
457
|
+
return [...map.values()];
|
|
458
|
+
}
|
|
459
|
+
async aggregateScanProgress(workspacePath) {
|
|
460
|
+
if (!workspacePath)
|
|
461
|
+
return undefined;
|
|
462
|
+
let processed = 0, total = 0;
|
|
463
|
+
for (const context of await projectDiscovery.findTopLevelPomDirectories(workspacePath)) {
|
|
464
|
+
const progress = await this.scanner.getScanProgress(context);
|
|
465
|
+
processed += progress?.processed ?? 0;
|
|
466
|
+
total += progress?.total ?? 0;
|
|
438
467
|
}
|
|
439
|
-
|
|
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);
|
|
468
|
+
return { processed, total, percent: total ? Math.floor(processed / total * 100) : 0 };
|
|
449
469
|
}
|
|
450
|
-
async
|
|
451
|
-
const {
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
logger.info(`[TOOL:search_class] Request: query="${query}", limit=${limit}`);
|
|
455
|
-
this.logToolDebug(logger, 'search_class', projectPath, { query, limit });
|
|
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
|
+
async selectorFromArgs(args, allowEmpty = false) {
|
|
471
|
+
const selector = { workspacePath: args.workspacePath, jarPath: args.jarPath, jarDirectory: args.jarDirectory, jarNamePrefix: args.jarNamePrefix, coordinates: args.coordinates };
|
|
472
|
+
if (!selector.workspacePath && !selector.jarPath && !selector.jarDirectory && !selector.coordinates) {
|
|
473
|
+
selector.workspacePath = process.cwd();
|
|
470
474
|
}
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
text += `\n\n_Note: Background dependency scan is ${pct}% complete. Results may be partial._`;
|
|
475
|
+
if (selector.workspacePath)
|
|
476
|
+
selector.workspacePath = await this.validateWorkspacePath(selector.workspacePath);
|
|
477
|
+
if (selector.jarDirectory)
|
|
478
|
+
selector.jarDirectory = await this.validateDirectory(selector.jarDirectory, 'jarDirectory');
|
|
479
|
+
if (selector.jarPath) {
|
|
480
|
+
if (!path.isAbsolute(selector.jarPath))
|
|
481
|
+
throw new Error('jarPath must be absolute');
|
|
482
|
+
selector.jarPath = path.resolve(selector.jarPath);
|
|
480
483
|
}
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
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);
|
|
484
|
+
if (!allowEmpty && !selector.workspacePath && !selector.jarPath && !selector.jarDirectory && !selector.coordinates)
|
|
485
|
+
throw new Error('Provide workspacePath, jarPath, jarDirectory, or coordinates');
|
|
486
|
+
return selector;
|
|
494
487
|
}
|
|
495
|
-
|
|
496
|
-
const {
|
|
497
|
-
|
|
498
|
-
const logger = Logger.get(projectPath);
|
|
499
|
-
const start = performance.now();
|
|
500
|
-
logger.info(`[TOOL:get_inheritance_tree] Request: className=${className}`);
|
|
501
|
-
this.logToolDebug(logger, 'get_inheritance_tree', projectPath, { className });
|
|
502
|
-
await sendProgress?.(`Building inheritance tree for: ${className}`, 0, 100);
|
|
503
|
-
await this.ensureScanStarted(projectPath, sendProgress);
|
|
504
|
-
await sendProgress?.('Analyzing class hierarchy...', 50, 100);
|
|
505
|
-
const hierarchy = await this.analyzer.getInheritanceHierarchy(className, projectPath);
|
|
506
|
-
const duration = ((performance.now() - start) / 1000).toFixed(2);
|
|
507
|
-
logger.info(`[TOOL:get_inheritance_tree] Complete in ${duration}s. Hierarchy depth: ${hierarchy.length}`);
|
|
508
|
-
await sendProgress?.('Hierarchy complete', 100, 100);
|
|
509
|
-
let text = `Inheritance hierarchy for \`${className}\`:\n\n`;
|
|
510
|
-
hierarchy.forEach((entry, idx) => {
|
|
511
|
-
const indent = ' '.repeat(idx);
|
|
512
|
-
const arrow = idx === 0 ? '' : '▸ ';
|
|
513
|
-
text += `${indent}${arrow}\`${entry.className}\`${entry.resolved ? '' : ' (not in indexed dependencies)'}\n`;
|
|
514
|
-
});
|
|
515
|
-
if (hierarchy.length === 1) {
|
|
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
|
-
})),
|
|
525
|
-
};
|
|
488
|
+
ambiguityResponse(label, candidates, format = 'text') {
|
|
489
|
+
const structured = { ambiguous: true, candidates };
|
|
490
|
+
const text = `${label} is ambiguous. Provide an exact path/name:\n${candidates.map(candidate => `- ${candidate.jarPath ?? candidate.className}`).join('\n')}`;
|
|
526
491
|
return this.formatResponse(text, structured, format);
|
|
527
492
|
}
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
if (
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
fields = fields.filter(f => f.modifiers.includes(filter));
|
|
539
|
-
methods = methods.filter(m => m.modifiers.includes(filter));
|
|
493
|
+
formatResponse(text, structured, format = 'text') {
|
|
494
|
+
if (format === 'json')
|
|
495
|
+
return { content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }] };
|
|
496
|
+
if (format === 'toon') {
|
|
497
|
+
try {
|
|
498
|
+
return { content: [{ type: 'text', text: toonEncode(structured) }] };
|
|
499
|
+
}
|
|
500
|
+
catch {
|
|
501
|
+
return { content: [{ type: 'text', text }] };
|
|
502
|
+
}
|
|
540
503
|
}
|
|
541
|
-
return {
|
|
504
|
+
return { content: [{ type: 'text', text }] };
|
|
505
|
+
}
|
|
506
|
+
clamp(value, min, max, fallback) {
|
|
507
|
+
const parsed = Number(value);
|
|
508
|
+
return Number.isFinite(parsed) ? Math.max(min, Math.min(max, Math.floor(parsed))) : fallback;
|
|
542
509
|
}
|
|
543
510
|
validateClassName(className) {
|
|
544
|
-
if (!className || typeof className !== 'string')
|
|
545
|
-
throw new Error('className is required and must be a string
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
if (!
|
|
552
|
-
throw new Error(
|
|
553
|
-
|
|
511
|
+
if (!className || typeof className !== 'string')
|
|
512
|
+
throw new Error('className is required and must be a string');
|
|
513
|
+
if (!/^[a-zA-Z_$][a-zA-Z0-9_$]*(\.[a-zA-Z_$][a-zA-Z0-9_$]*)*$/.test(className))
|
|
514
|
+
throw new Error('className must be a valid Java class name');
|
|
515
|
+
}
|
|
516
|
+
async validateWorkspacePath(workspacePath) { return this.validateDirectory(workspacePath, 'workspacePath'); }
|
|
517
|
+
async validateDirectory(value, label) {
|
|
518
|
+
if (!value || typeof value !== 'string')
|
|
519
|
+
throw new Error(`${label} is required and must be a string`);
|
|
520
|
+
if (!path.isAbsolute(value))
|
|
521
|
+
throw new Error(`${label} must be an absolute path`);
|
|
522
|
+
const resolved = path.resolve(value);
|
|
523
|
+
const stat = await fs.stat(resolved).catch(() => null);
|
|
524
|
+
if (!stat)
|
|
525
|
+
throw new Error(`${label} does not exist: ${resolved}`);
|
|
526
|
+
if (!stat.isDirectory())
|
|
527
|
+
throw new Error(`${label} is not a directory: ${resolved}`);
|
|
528
|
+
return resolved;
|
|
554
529
|
}
|
|
555
|
-
/**
|
|
556
|
-
* Validate that projectPath is a valid Maven project root.
|
|
557
|
-
*/
|
|
558
530
|
async validateProjectPath(projectPath) {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
if (!path.isAbsolute(projectPath)) {
|
|
563
|
-
throw new Error(`projectPath must be an absolute path. Received: ${projectPath}`);
|
|
564
|
-
}
|
|
565
|
-
if (!(await fs.pathExists(projectPath))) {
|
|
566
|
-
throw new Error(`projectPath does not exist: ${projectPath}`);
|
|
567
|
-
}
|
|
568
|
-
const stat = await fs.stat(projectPath);
|
|
569
|
-
if (!stat.isDirectory()) {
|
|
570
|
-
throw new Error(`projectPath is not a directory: ${projectPath}`);
|
|
571
|
-
}
|
|
572
|
-
const pomPath = path.join(projectPath, 'pom.xml');
|
|
573
|
-
if (!(await fs.pathExists(pomPath))) {
|
|
574
|
-
throw new Error(`No pom.xml found in ${projectPath}. This is not a Maven project. ` +
|
|
575
|
-
`java-inspector only supports Maven-based Java projects.`);
|
|
576
|
-
}
|
|
531
|
+
const resolved = await this.validateDirectory(projectPath, 'projectPath');
|
|
532
|
+
if (!(await fs.pathExists(path.join(resolved, 'pom.xml'))))
|
|
533
|
+
throw new Error(`No pom.xml found in ${resolved}`);
|
|
577
534
|
}
|
|
578
|
-
/**
|
|
579
|
-
* Ensure classpath is resolved and background scan has started.
|
|
580
|
-
* This is non-blocking — the scan continues in the background.
|
|
581
|
-
*/
|
|
582
535
|
async ensureScanStarted(projectPath, sendProgress) {
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
// Check if classpath cache exists (scan already started)
|
|
588
|
-
if (await this.scanner.getClasspath(projectPath)) {
|
|
589
|
-
return; // Background scan already in progress
|
|
590
|
-
}
|
|
591
|
-
console.error('No index found. Starting background dependency scan...');
|
|
592
|
-
await sendProgress?.('No index found. Starting background dependency scan...');
|
|
536
|
+
if (await this.scanner.isIndexComplete(projectPath))
|
|
537
|
+
return;
|
|
538
|
+
if (await this.scanner.getClasspath(projectPath))
|
|
539
|
+
return;
|
|
593
540
|
try {
|
|
594
541
|
await this.scanner.scanProject(projectPath, false, sendProgress);
|
|
595
|
-
console.error('Background scan started');
|
|
596
|
-
await sendProgress?.('Background scan started');
|
|
597
542
|
}
|
|
598
543
|
catch (error) {
|
|
599
|
-
console.error('Failed to start background scan:', error);
|
|
600
544
|
throw new Error(`Unable to start dependency scan: ${error instanceof Error ? error.message : String(error)}`);
|
|
601
545
|
}
|
|
602
546
|
}
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
}
|
|
613
|
-
logServerStartup(logger) {
|
|
614
|
-
const env = process.env.NODE_ENV || 'development';
|
|
615
|
-
const modeLabel = env === 'development' ? 'DEBUG MODE' : 'production';
|
|
616
|
-
const startupMsg = `java-inspector v${version} MCP Server running on stdio (${modeLabel})`;
|
|
617
|
-
const envMsg = `[SERVER] Environment: ${JSON.stringify(this.getDebugEnv())}`;
|
|
618
|
-
const runtimeMsg = `[SERVER] Runtime: cwd=${process.cwd()}, platform=${process.platform}, arch=${process.arch}, node=${process.version}, pid=${process.pid}`;
|
|
619
|
-
console.error(startupMsg);
|
|
620
|
-
console.error(`[SERVER] ${runtimeMsg}`);
|
|
621
|
-
console.error(envMsg);
|
|
622
|
-
if (logger) {
|
|
623
|
-
logger.info(`[SERVER] ${startupMsg}`);
|
|
624
|
-
logger.info(runtimeMsg);
|
|
625
|
-
logger.info(envMsg);
|
|
547
|
+
applyFilter(analysis, filter) {
|
|
548
|
+
let fields = analysis.fields, methods = analysis.methods;
|
|
549
|
+
if (filter === 'fields')
|
|
550
|
+
methods = [];
|
|
551
|
+
else if (filter === 'methods')
|
|
552
|
+
fields = [];
|
|
553
|
+
else if (filter !== 'all') {
|
|
554
|
+
fields = fields.filter(field => field.modifiers.includes(filter));
|
|
555
|
+
methods = methods.filter(method => method.modifiers.includes(filter));
|
|
626
556
|
}
|
|
557
|
+
return { fields, methods };
|
|
558
|
+
}
|
|
559
|
+
getDebugEnv() {
|
|
560
|
+
return { NODE_ENV: process.env.NODE_ENV, JAVA_HOME: process.env.JAVA_HOME, MAVEN_HOME: process.env.MAVEN_HOME, MAVEN_CMD: process.env.MAVEN_CMD, MAVEN_REPO: process.env.MAVEN_REPO, DECOMPILER_PATH: process.env.DECOMPILER_PATH };
|
|
627
561
|
}
|
|
628
562
|
logToolDebug(logger, toolName, projectPath, extra) {
|
|
629
|
-
|
|
630
|
-
if (!isDebug)
|
|
563
|
+
if (process.env.NODE_ENV !== 'development')
|
|
631
564
|
return;
|
|
632
|
-
logger.debug(`[TOOL:${toolName}] Context: projectPath=${projectPath}, serverVersion=${version}
|
|
633
|
-
if (extra)
|
|
565
|
+
logger.debug(`[TOOL:${toolName}] Context: projectPath=${projectPath}, serverVersion=${version}`);
|
|
566
|
+
if (extra)
|
|
634
567
|
logger.debug(`[TOOL:${toolName}] Params: ${JSON.stringify(extra)}`);
|
|
635
|
-
}
|
|
636
568
|
}
|
|
637
569
|
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...`);
|
|
570
|
+
const workspacePath = process.cwd();
|
|
571
|
+
const logger = Logger.get(workspacePath);
|
|
647
572
|
try {
|
|
648
|
-
await
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
}
|
|
653
|
-
|
|
654
|
-
|
|
573
|
+
const pomRoots = await projectDiscovery.findTopLevelPomDirectories(workspacePath);
|
|
574
|
+
if (!pomRoots.length) {
|
|
575
|
+
logger.info('[AUTO-SCAN] No Maven project found. Waiting for direct/local JAR calls.');
|
|
576
|
+
return;
|
|
577
|
+
}
|
|
578
|
+
logger.info(`[AUTO-SCAN] Found ${pomRoots.length} top-level Maven project(s): ${pomRoots.join(', ')}`);
|
|
579
|
+
for (const pomRoot of pomRoots) {
|
|
580
|
+
this.scanner.scanProject(pomRoot, false, async (message) => logger.info(`[AUTO-SCAN:${path.basename(pomRoot)}] ${message}`))
|
|
581
|
+
.catch(error => logger.error(`[AUTO-SCAN] ${pomRoot}: ${error instanceof Error ? error.message : String(error)}`));
|
|
582
|
+
}
|
|
655
583
|
}
|
|
656
584
|
catch (error) {
|
|
657
|
-
|
|
658
|
-
logger.error(`[AUTO-SCAN] Failed: ${msg}`);
|
|
585
|
+
logger.error(`[AUTO-SCAN] Discovery failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
659
586
|
}
|
|
660
587
|
}
|
|
661
588
|
async run() {
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
this.logServerStartup(startupLogger);
|
|
666
|
-
await this.tryAutoScan();
|
|
589
|
+
await this.server.connect(new StdioServerTransport());
|
|
590
|
+
Logger.get(process.cwd()).info(`[SERVER] java-inspector v${version} running; cwd=${process.cwd()}, node=${process.version}, pid=${process.pid}`);
|
|
591
|
+
void this.tryAutoScan();
|
|
667
592
|
}
|
|
668
593
|
}
|
|
669
594
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
|
670
595
|
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
|
-
});
|
|
596
|
+
process.on('uncaughtException', error => console.error('Uncaught exception:', error));
|
|
597
|
+
process.on('unhandledRejection', reason => console.error('Unhandled Promise rejection:', reason));
|
|
598
|
+
mcpServer.run().catch(error => { console.error('Server startup failed:', error); process.exit(1); });
|
|
681
599
|
}
|
|
682
600
|
//# sourceMappingURL=index.js.map
|