@mustafagoksever/java-inspector 3.0.0 → 3.1.1

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