@mustafagoksever/java-inspector 2.3.3 → 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.
Files changed (62) hide show
  1. package/README.md +138 -263
  2. package/dist/analyzer/JavaClassAnalyzer.d.ts +7 -4
  3. package/dist/analyzer/JavaClassAnalyzer.d.ts.map +1 -1
  4. package/dist/analyzer/JavaClassAnalyzer.js +47 -28
  5. package/dist/analyzer/JavaClassAnalyzer.js.map +1 -1
  6. package/dist/analyzer/JdkSourceService.d.ts +17 -0
  7. package/dist/analyzer/JdkSourceService.d.ts.map +1 -0
  8. package/dist/analyzer/JdkSourceService.js +138 -0
  9. package/dist/analyzer/JdkSourceService.js.map +1 -0
  10. package/dist/cache/ProjectCache.d.ts +6 -1
  11. package/dist/cache/ProjectCache.d.ts.map +1 -1
  12. package/dist/cache/ProjectCache.js +59 -18
  13. package/dist/cache/ProjectCache.js.map +1 -1
  14. package/dist/cli.js +1 -12
  15. package/dist/cli.js.map +1 -1
  16. package/dist/decompiler/DecompilerService.d.ts +10 -4
  17. package/dist/decompiler/DecompilerService.d.ts.map +1 -1
  18. package/dist/decompiler/DecompilerService.js +86 -30
  19. package/dist/decompiler/DecompilerService.js.map +1 -1
  20. package/dist/index.d.ts +26 -14
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +515 -581
  23. package/dist/index.js.map +1 -1
  24. package/dist/scanner/ArtifactService.d.ts +104 -0
  25. package/dist/scanner/ArtifactService.d.ts.map +1 -0
  26. package/dist/scanner/ArtifactService.js +569 -0
  27. package/dist/scanner/ArtifactService.js.map +1 -0
  28. package/dist/scanner/BackgroundScanner.d.ts.map +1 -1
  29. package/dist/scanner/BackgroundScanner.js +38 -26
  30. package/dist/scanner/BackgroundScanner.js.map +1 -1
  31. package/dist/scanner/ClassFileMetadataReader.d.ts +31 -0
  32. package/dist/scanner/ClassFileMetadataReader.d.ts.map +1 -0
  33. package/dist/scanner/ClassFileMetadataReader.js +215 -0
  34. package/dist/scanner/ClassFileMetadataReader.js.map +1 -0
  35. package/dist/scanner/DependencyScanner.d.ts +5 -0
  36. package/dist/scanner/DependencyScanner.d.ts.map +1 -1
  37. package/dist/scanner/DependencyScanner.js +59 -2
  38. package/dist/scanner/DependencyScanner.js.map +1 -1
  39. package/dist/scanner/JarIndexer.d.ts +73 -0
  40. package/dist/scanner/JarIndexer.d.ts.map +1 -0
  41. package/dist/scanner/JarIndexer.js +445 -0
  42. package/dist/scanner/JarIndexer.js.map +1 -0
  43. package/dist/scanner/JarScanCoordinator.d.ts +32 -0
  44. package/dist/scanner/JarScanCoordinator.d.ts.map +1 -0
  45. package/dist/scanner/JarScanCoordinator.js +124 -0
  46. package/dist/scanner/JarScanCoordinator.js.map +1 -0
  47. package/dist/scanner/LazyResolver.d.ts.map +1 -1
  48. package/dist/scanner/LazyResolver.js +80 -70
  49. package/dist/scanner/LazyResolver.js.map +1 -1
  50. package/dist/scanner/ProjectDiscovery.d.ts +6 -0
  51. package/dist/scanner/ProjectDiscovery.d.ts.map +1 -0
  52. package/dist/scanner/ProjectDiscovery.js +49 -0
  53. package/dist/scanner/ProjectDiscovery.js.map +1 -0
  54. package/dist/utils/Logger.d.ts +3 -0
  55. package/dist/utils/Logger.d.ts.map +1 -1
  56. package/dist/utils/Logger.js +27 -6
  57. package/dist/utils/Logger.js.map +1 -1
  58. package/dist/utils/cachePaths.d.ts +3 -0
  59. package/dist/utils/cachePaths.d.ts.map +1 -1
  60. package/dist/utils/cachePaths.js +9 -0
  61. package/dist/utils/cachePaths.js.map +1 -1
  62. package/package.json +5 -5
package/dist/index.js CHANGED
@@ -1,666 +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, } from '@modelcontextprotocol/sdk/types.js';
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
- return {
40
- tools: [
41
- {
42
- name: 'scan_dependencies',
43
- description: 'Scan and index all Java classes from the project\'s Maven dependencies (pom.xml). This tool ONLY indexes classes from external dependency JARs — it does NOT index the project\'s own source code. The scan runs in the background; call again to check progress. Use forceRefresh=true to rebuild the index after dependency changes. You must call this (or let it auto-run) before using other tools.',
44
- inputSchema: {
45
- type: 'object',
46
- properties: {
47
- projectPath: {
48
- type: 'string',
49
- description: 'Absolute path to the Maven project root directory (the directory containing pom.xml)',
50
- },
51
- forceRefresh: {
52
- type: 'boolean',
53
- description: 'Whether to force refresh index',
54
- default: false,
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
- });
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 'scan_dependencies':
224
- await this.validateProjectPath(args.projectPath);
225
- return await this.handleScanDependencies(args, sendProgress);
226
- case 'decompile_class':
227
- await this.validateProjectPath(args.projectPath);
228
- return await this.handleDecompileClass(args, sendProgress);
229
- case 'analyze_class':
230
- await this.validateProjectPath(args.projectPath);
231
- return await this.handleAnalyzeClass(args, sendProgress);
232
- case 'search_class':
233
- await this.validateProjectPath(args.projectPath);
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 errorMessage = error instanceof Error ? error.message : String(error);
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
- };
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 };
254
120
  }
255
121
  });
256
122
  }
257
- formatResponse(text, structured, format) {
258
- if (format === 'json') {
259
- return { content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }] };
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);
260
129
  }
261
- if (format === 'toon') {
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++) {
262
287
  try {
263
- const toonText = toonEncode(structured);
264
- return { content: [{ type: 'text', text: toonText }] };
288
+ outputs.push({ projectPath: contexts[i], output: await this.scanner.explainDependency(contexts[i], coordinates) });
265
289
  }
266
- catch {
267
- return { content: [{ type: 'text', text }] };
290
+ catch (error) {
291
+ outputs.push({ projectPath: contexts[i], error: error instanceof Error ? error.message : String(error) });
268
292
  }
293
+ await sendProgress?.(`Checked ${i + 1}/${contexts.length} Maven context(s)`, i + 1, contexts.length);
269
294
  }
270
- return { content: [{ type: 'text', text }] };
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);
271
297
  }
272
- async handleScanDependencies(args, sendProgress) {
273
- const { projectPath, forceRefresh = false, format = 'text' } = args;
274
- const logger = Logger.get(projectPath);
275
- const start = performance.now();
276
- logger.info(`[TOOL:scan_dependencies] Request: forceRefresh=${forceRefresh}`);
277
- this.logToolDebug(logger, 'scan_dependencies', projectPath, { forceRefresh });
278
- await sendProgress?.(`Scanning project: ${projectPath}`, 0, 100);
279
- const result = await this.scanner.scanProject(projectPath, forceRefresh, sendProgress);
280
- const duration = ((performance.now() - start) / 1000).toFixed(2);
281
- logger.info(`[TOOL:scan_dependencies] Complete in ${duration}s. Status: ${result.status}, JARs: ${result.jarCount}, Classes: ${result.classCount}`);
282
- if (result.status === 'complete') {
283
- await sendProgress?.(`Scan complete: ${result.jarCount} JARs, ${result.classCount} classes`, 100, 100);
284
- const text = `Dependency scanning complete! Indexed ${result.classCount} classes from ${result.jarCount} JARs.`;
285
- const structured = {
286
- status: result.status,
287
- jarCount: result.jarCount,
288
- classCount: result.classCount,
289
- };
290
- return this.formatResponse(text, structured, format);
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);
291
318
  }
292
- // Background scan in progress
293
- const progressText = result.progress
294
- ? `${result.progress.processed}/${result.progress.total} JARs processed`
295
- : 'starting...';
296
- const progressPct = result.progress ? Math.floor((result.progress.processed / result.progress.total) * 100) : 0;
297
- await sendProgress?.(`Background scan in progress: ${progressText}`, progressPct, 100);
298
- let text = `Background dependency scan is in progress.\n\n`;
299
- if (result.message) {
300
- 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);
301
325
  }
302
- text += `Total JARs: ${result.jarCount}\n`;
303
- text += `Progress: ${progressText}\n\n`;
304
- text += `You can already use \`decompile_class\` and \`analyze_class\` — the server will resolve classes on-demand. `;
305
- text += `Call \`scan_dependencies\` again later to check progress.`;
306
- const structured = {
307
- status: result.status,
308
- jarCount: result.jarCount,
309
- progress: result.progress,
310
- };
311
- 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);
312
328
  }
313
- async handleDecompileClass(args, sendProgress) {
314
- const { className, projectPath, useCache = true, decompilerPath, offset = 1, limit = 0, format = 'text', methodName, paramTypes } = args;
315
- const logger = Logger.get(projectPath);
316
- const start = performance.now();
317
- logger.info(`[TOOL:decompile_class] Request: className=${className}, useCache=${useCache}, decompilerPath=${decompilerPath || 'auto-detect'}`);
318
- this.logToolDebug(logger, 'decompile_class', projectPath, { className, useCache, decompilerPath: decompilerPath || 'auto-detect' });
319
- try {
320
- await sendProgress?.(`Starting decompilation of class: ${className}`, 0, 100);
321
- // Check if index exists, create if not
322
- await sendProgress?.('Checking class index...', 10, 100);
323
- await this.ensureScanStarted(projectPath, sendProgress);
324
- await sendProgress?.('Decompiling class...', 50, 100);
325
- const sourceCode = await this.decompiler.decompileClass(className, projectPath, useCache, decompilerPath);
326
- await sendProgress?.('Decompilation complete', 100, 100);
327
- if (!sourceCode || sourceCode.trim() === '') {
328
- const text = `Warning: Decompilation result for class ${className} is empty, possibly due to Vineflower decompiler issues or corrupted class file`;
329
- const structured = { className, sourceCode: '', totalLines: 0, methods: [] };
330
- return this.formatResponse(text, structured, format);
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;
331
370
  }
332
- const totalLines = sourceCode.split('\n').length;
333
- const methods = (format === 'json' || format === 'toon') ? extractMethodMap(sourceCode) : [];
334
- // Apply method extraction or offset/limit slicing
335
- let finalSourceCode = sourceCode;
336
- let sliceInfo = '';
337
- let extractedMethodRange;
338
- if (methodName) {
339
- const extracted = extractMethod(sourceCode, methodName, paramTypes);
340
- if (!extracted) {
341
- const text = `Method "${methodName}" not found in class ${className}${paramTypes ? ' with paramTypes ' + JSON.stringify(paramTypes) : ''}.`;
342
- const structured = { className, totalLines, methods, methodName, paramTypes };
343
- return this.formatResponse(text, structured, format);
344
- }
345
- finalSourceCode = extracted;
346
- sliceInfo = ` (method: ${methodName}${paramTypes ? ' ' + JSON.stringify(paramTypes) : ''})`;
347
- extractedMethodRange = methods.find(m => {
348
- if (m.name !== methodName)
349
- return false;
350
- if (!paramTypes || paramTypes.length === 0)
351
- return true;
352
- const sigParams = extractParamTypes(m.signature);
353
- return matchParamTypes(sigParams, paramTypes);
354
- });
371
+ catch {
372
+ hierarchy[hierarchy.length - 1].resolved = false;
373
+ break;
355
374
  }
356
- else if (offset > 1 || limit > 0) {
357
- const lines = sourceCode.split('\n');
358
- const effectiveOffset = offset <= 0 ? 1 : offset;
359
- if (effectiveOffset > totalLines) {
360
- const text = `Offset ${effectiveOffset} exceeds total lines ${totalLines} for class ${className}.`;
361
- const structured = { className, totalLines, methods };
362
- return this.formatResponse(text, structured, format);
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;
363
421
  }
364
- const effectiveLimit = limit < 0 ? 0 : limit;
365
- const startIndex = effectiveOffset - 1;
366
- const endIndex = effectiveLimit > 0
367
- ? Math.min(startIndex + effectiveLimit, totalLines)
368
- : totalLines;
369
- finalSourceCode = lines.slice(startIndex, endIndex).join('\n');
370
- sliceInfo = ` (lines ${effectiveOffset}-${endIndex} of ${totalLines})`;
371
422
  }
372
- const duration = ((performance.now() - start) / 1000).toFixed(2);
373
- logger.info(`[TOOL:decompile_class] Complete in ${duration}s. Source length: ${sourceCode.length} chars.`);
374
- const text = `Decompiled source code for class ${className}${sliceInfo}:\n\n\`\`\`java\n${finalSourceCode}\n\`\`\``;
375
- const structured = {
376
- className,
377
- totalLines,
378
- sourceCode: finalSourceCode,
379
- methods,
380
- };
381
- if (extractedMethodRange) {
382
- structured.extractedMethod = {
383
- name: extractedMethodRange.name,
384
- startLine: extractedMethodRange.startLine,
385
- endLine: extractedMethodRange.endLine,
386
- };
423
+ catch {
424
+ chain.push({ className: current, level: chain.length, resolved: false });
425
+ break;
387
426
  }
388
- return this.formatResponse(text, structured, format);
389
- }
390
- catch (error) {
391
- const errorMessage = error instanceof Error ? error.message : String(error);
392
- const duration = ((performance.now() - start) / 1000).toFixed(2);
393
- logger.error(`[TOOL:decompile_class] Failed after ${duration}s: ${errorMessage}`);
394
- await sendProgress?.(`Decompilation failed: ${errorMessage}`);
395
- const text = `Decompilation failed: ${errorMessage}`;
396
- const structured = { className, error: errorMessage };
397
- return this.formatResponse(text, structured, format);
398
427
  }
428
+ return chain.reverse().map((entry, level) => ({ ...entry, level }));
399
429
  }
400
- async handleAnalyzeClass(args, sendProgress) {
401
- const { className, projectPath, filter = 'all', format = 'text' } = args;
402
- const logger = Logger.get(projectPath);
403
- const start = performance.now();
404
- logger.info(`[TOOL:analyze_class] Request: className=${className}, filter=${filter}`);
405
- this.logToolDebug(logger, 'analyze_class', projectPath, { className, filter });
406
- await sendProgress?.(`Analyzing class: ${className}`, 0, 100);
407
- // Check if index exists, create if not
408
- await sendProgress?.('Checking class index...', 20, 100);
409
- await this.ensureScanStarted(projectPath, sendProgress);
410
- await sendProgress?.('Running javap analysis...', 50, 100);
411
- const analysis = await this.analyzer.analyzeClass(className, projectPath);
412
- await sendProgress?.('Analysis complete', 100, 100);
413
- const duration = ((performance.now() - start) / 1000).toFixed(2);
414
- logger.info(`[TOOL:analyze_class] Complete in ${duration}s. Fields: ${analysis.fields.length}, Methods: ${analysis.methods.length}`);
415
- const { fields, methods } = this.applyFilter(analysis, filter);
416
- let text = `Analysis result for class ${className}:\n\n`;
417
- text += `Package name: ${analysis.packageName}\n`;
418
- text += `Class name: ${analysis.className}\n`;
419
- text += `Modifiers: ${analysis.modifiers.join(' ')}\n`;
420
- text += `Super class: ${analysis.superClass || 'None'}\n`;
421
- text += `Implemented interfaces: ${analysis.interfaces.join(', ') || 'None'}\n\n`;
422
- if (fields.length > 0) {
423
- text += `Fields (${fields.length}):\n`;
424
- fields.forEach(field => {
425
- text += ` - ${field.modifiers.join(' ')} ${field.type} ${field.name}\n`;
426
- });
427
- 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);
428
438
  }
429
- if (methods.length > 0) {
430
- text += `Methods (${methods.length}):\n`;
431
- methods.forEach(method => {
432
- text += ` - ${method.modifiers.join(' ')} ${method.returnType} ${method.name}(${method.parameters.join(', ')})\n`;
433
- });
434
- text += '\n';
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;
435
467
  }
436
- const structured = {
437
- className: analysis.className,
438
- packageName: analysis.packageName,
439
- modifiers: analysis.modifiers,
440
- superClass: analysis.superClass,
441
- interfaces: analysis.interfaces,
442
- fields,
443
- methods,
444
- };
445
- return this.formatResponse(text, structured, format);
468
+ return { processed, total, percent: total ? Math.floor(processed / total * 100) : 0 };
446
469
  }
447
- async handleSearchClass(args, sendProgress) {
448
- const { query, projectPath, limit = 20, format = 'text' } = args;
449
- const logger = Logger.get(projectPath);
450
- const start = performance.now();
451
- logger.info(`[TOOL:search_class] Request: query="${query}", limit=${limit}`);
452
- this.logToolDebug(logger, 'search_class', projectPath, { query, limit });
453
- await sendProgress?.(`Searching for classes matching: "${query}"`, 0, 100);
454
- await this.ensureScanStarted(projectPath, sendProgress);
455
- await sendProgress?.('Searching index...', 50, 100);
456
- const results = await this.scanner.searchClasses(projectPath, query, limit);
457
- const duration = ((performance.now() - start) / 1000).toFixed(2);
458
- logger.info(`[TOOL:search_class] Complete in ${duration}s. Found ${results.length} results.`);
459
- await sendProgress?.(`Found ${results.length} matches`, 100, 100);
460
- const isComplete = await this.scanner.isIndexComplete(projectPath);
461
- const scanProgress = isComplete ? undefined : await this.scanner.getScanProgress(projectPath);
462
- const pct = scanProgress ? Math.floor((scanProgress.processed / scanProgress.total) * 100) : undefined;
463
- if (results.length === 0) {
464
- 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")`;
465
- const structured = { query, results: [], isComplete, scanProgressPct: pct };
466
- 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();
467
474
  }
468
- let text = `Found ${results.length} class(es) matching "${query}":\n\n`;
469
- text += '| # | Class Name | Package | JAR | Score |\n';
470
- text += '|---|------------|---------|-----|-------|\n';
471
- results.forEach((entry, idx) => {
472
- text += `| ${idx + 1} | \`${entry.simpleName}\` | ${entry.packageName} | ${path.basename(entry.jarPath)} | ${entry.score} |\n`;
473
- });
474
- text += '\nUse the fully qualified class name with `decompile_class` or `analyze_class` to inspect it further.';
475
- if (!isComplete && pct !== undefined) {
476
- 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);
477
483
  }
478
- const structured = {
479
- query,
480
- results: results.map((r) => ({
481
- className: `${r.packageName}.${r.simpleName}`,
482
- packageName: r.packageName,
483
- simpleName: r.simpleName,
484
- jarName: path.basename(r.jarPath),
485
- score: r.score,
486
- })),
487
- isComplete,
488
- scanProgressPct: pct,
489
- };
490
- 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;
491
487
  }
492
- async handleGetInheritanceTree(args, sendProgress) {
493
- const { className, projectPath, format = 'text' } = args;
494
- const logger = Logger.get(projectPath);
495
- const start = performance.now();
496
- logger.info(`[TOOL:get_inheritance_tree] Request: className=${className}`);
497
- this.logToolDebug(logger, 'get_inheritance_tree', projectPath, { className });
498
- await sendProgress?.(`Building inheritance tree for: ${className}`, 0, 100);
499
- await this.ensureScanStarted(projectPath, sendProgress);
500
- await sendProgress?.('Analyzing class hierarchy...', 50, 100);
501
- const hierarchy = await this.analyzer.getInheritanceHierarchy(className, projectPath);
502
- const duration = ((performance.now() - start) / 1000).toFixed(2);
503
- logger.info(`[TOOL:get_inheritance_tree] Complete in ${duration}s. Hierarchy depth: ${hierarchy.length}`);
504
- await sendProgress?.('Hierarchy complete', 100, 100);
505
- let text = `Inheritance hierarchy for \`${className}\`:\n\n`;
506
- hierarchy.forEach((entry, idx) => {
507
- const indent = ' '.repeat(idx);
508
- const arrow = idx === 0 ? '' : '▸ ';
509
- text += `${indent}${arrow}\`${entry.className}\`${entry.resolved ? '' : ' (not in indexed dependencies)'}\n`;
510
- });
511
- if (hierarchy.length === 1) {
512
- 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.)';
513
- }
514
- const structured = {
515
- className,
516
- hierarchy: hierarchy.map(entry => ({
517
- className: entry.className,
518
- level: entry.level,
519
- resolved: entry.resolved,
520
- })),
521
- };
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')}`;
522
491
  return this.formatResponse(text, structured, format);
523
492
  }
524
- applyFilter(analysis, filter) {
525
- let fields = analysis.fields;
526
- let methods = analysis.methods;
527
- if (filter === 'fields') {
528
- methods = [];
529
- }
530
- else if (filter === 'methods') {
531
- fields = [];
532
- }
533
- else if (filter !== 'all') {
534
- fields = fields.filter(f => f.modifiers.includes(filter));
535
- 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
+ }
536
503
  }
537
- return { fields, methods };
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;
509
+ }
510
+ validateClassName(className) {
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;
538
529
  }
539
- /**
540
- * Validate that projectPath is a valid Maven project root.
541
- */
542
530
  async validateProjectPath(projectPath) {
543
- if (!projectPath || typeof projectPath !== 'string') {
544
- throw new Error('projectPath is required and must be a string.');
545
- }
546
- if (!path.isAbsolute(projectPath)) {
547
- throw new Error(`projectPath must be an absolute path. Received: ${projectPath}`);
548
- }
549
- if (!(await fs.pathExists(projectPath))) {
550
- throw new Error(`projectPath does not exist: ${projectPath}`);
551
- }
552
- const stat = await fs.stat(projectPath);
553
- if (!stat.isDirectory()) {
554
- throw new Error(`projectPath is not a directory: ${projectPath}`);
555
- }
556
- const pomPath = path.join(projectPath, 'pom.xml');
557
- if (!(await fs.pathExists(pomPath))) {
558
- throw new Error(`No pom.xml found in ${projectPath}. This is not a Maven project. ` +
559
- `java-inspector only supports Maven-based Java projects.`);
560
- }
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}`);
561
534
  }
562
- /**
563
- * Ensure classpath is resolved and background scan has started.
564
- * This is non-blocking — the scan continues in the background.
565
- */
566
535
  async ensureScanStarted(projectPath, sendProgress) {
567
- // Check if we have a complete and valid index
568
- if (await this.scanner.isIndexComplete(projectPath)) {
569
- return; // Already have a complete index
570
- }
571
- // Check if classpath cache exists (scan already started)
572
- if (await this.scanner.getClasspath(projectPath)) {
573
- return; // Background scan already in progress
574
- }
575
- console.error('No index found. Starting background dependency scan...');
576
- 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;
577
540
  try {
578
541
  await this.scanner.scanProject(projectPath, false, sendProgress);
579
- console.error('Background scan started');
580
- await sendProgress?.('Background scan started');
581
542
  }
582
543
  catch (error) {
583
- console.error('Failed to start background scan:', error);
584
544
  throw new Error(`Unable to start dependency scan: ${error instanceof Error ? error.message : String(error)}`);
585
545
  }
586
546
  }
587
- getDebugEnv() {
588
- return {
589
- NODE_ENV: process.env.NODE_ENV,
590
- JAVA_HOME: process.env.JAVA_HOME,
591
- MAVEN_HOME: process.env.MAVEN_HOME,
592
- MAVEN_CMD: process.env.MAVEN_CMD,
593
- MAVEN_REPO: process.env.MAVEN_REPO,
594
- DECOMPILER_PATH: process.env.DECOMPILER_PATH,
595
- };
596
- }
597
- logServerStartup(logger) {
598
- const env = process.env.NODE_ENV || 'development';
599
- const modeLabel = env === 'development' ? 'DEBUG MODE' : 'production';
600
- const startupMsg = `java-inspector v${version} MCP Server running on stdio (${modeLabel})`;
601
- const envMsg = `[SERVER] Environment: ${JSON.stringify(this.getDebugEnv())}`;
602
- const runtimeMsg = `[SERVER] Runtime: cwd=${process.cwd()}, platform=${process.platform}, arch=${process.arch}, node=${process.version}, pid=${process.pid}`;
603
- console.error(startupMsg);
604
- console.error(`[SERVER] ${runtimeMsg}`);
605
- console.error(envMsg);
606
- if (logger) {
607
- logger.info(`[SERVER] ${startupMsg}`);
608
- logger.info(runtimeMsg);
609
- 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));
610
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 };
611
561
  }
612
562
  logToolDebug(logger, toolName, projectPath, extra) {
613
- const isDebug = process.env.NODE_ENV === 'development';
614
- if (!isDebug)
563
+ if (process.env.NODE_ENV !== 'development')
615
564
  return;
616
- logger.debug(`[TOOL:${toolName}] Context: projectPath=${projectPath}, serverVersion=${version}, node=${process.version}, platform=${process.platform}`);
617
- if (extra) {
565
+ logger.debug(`[TOOL:${toolName}] Context: projectPath=${projectPath}, serverVersion=${version}`);
566
+ if (extra)
618
567
  logger.debug(`[TOOL:${toolName}] Params: ${JSON.stringify(extra)}`);
619
- }
620
568
  }
621
569
  async tryAutoScan() {
622
- const cwd = process.cwd();
623
- const pomPath = path.join(cwd, 'pom.xml');
624
- if (!(await fs.pathExists(pomPath))) {
625
- const logger = Logger.get(cwd);
626
- logger.info('[AUTO-SCAN] No Maven project detected at cwd, skipping auto-scan.');
627
- return;
628
- }
629
- const logger = Logger.get(cwd);
630
- logger.info(`[AUTO-SCAN] Maven project detected at ${cwd}. Starting dependency scan...`);
570
+ const workspacePath = process.cwd();
571
+ const logger = Logger.get(workspacePath);
631
572
  try {
632
- await this.validateProjectPath(cwd);
633
- const start = performance.now();
634
- await this.scanner.scanProject(cwd, false, async (msg) => {
635
- logger.info(`[AUTO-SCAN] ${msg}`);
636
- });
637
- const duration = ((performance.now() - start) / 1000).toFixed(2);
638
- logger.info(`[AUTO-SCAN] scanProject returned in ${duration}s.`);
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
+ }
639
583
  }
640
584
  catch (error) {
641
- const msg = error instanceof Error ? error.message : String(error);
642
- logger.error(`[AUTO-SCAN] Failed: ${msg}`);
585
+ logger.error(`[AUTO-SCAN] Discovery failed: ${error instanceof Error ? error.message : String(error)}`);
643
586
  }
644
587
  }
645
588
  async run() {
646
- const transport = new StdioServerTransport();
647
- await this.server.connect(transport);
648
- const startupLogger = Logger.get(process.cwd());
649
- this.logServerStartup(startupLogger);
650
- 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();
651
592
  }
652
593
  }
653
594
  if (process.argv[1] === fileURLToPath(import.meta.url)) {
654
595
  const mcpServer = new JavaClassAnalyzerMCPServer();
655
- process.on('uncaughtException', (error) => {
656
- console.error('Uncaught exception:', error);
657
- });
658
- process.on('unhandledRejection', (reason, promise) => {
659
- console.error('Unhandled Promise rejection:', reason);
660
- });
661
- mcpServer.run().catch((error) => {
662
- console.error('Server startup failed:', error);
663
- process.exit(1);
664
- });
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); });
665
599
  }
666
600
  //# sourceMappingURL=index.js.map