@fabersep/atlas 0.1.0 → 0.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.
@@ -16,6 +16,8 @@ export interface McpServerOptions {
16
16
  out?: string;
17
17
  /** Run incremental scan automatically before each query (default: true). */
18
18
  fresh?: boolean;
19
+ /** Where startup diagnostics go (default: stderr, which MCP clients keep in their logs). */
20
+ log?: (message: string) => void;
19
21
  /** Streams for stdio transport (defaults to process.stdin / process.stdout). */
20
22
  input?: Readable;
21
23
  output?: Writable;
@@ -36,12 +38,101 @@ interface JsonRpcResponse {
36
38
  message: string;
37
39
  };
38
40
  }
41
+ /** Shown by clients in the system prompt even while tool schemas are deferred (02/AC-23). */
42
+ export declare const SERVER_INSTRUCTIONS: string;
39
43
  export declare const MCP_TOOLS: readonly [{
44
+ readonly name: "investigate";
45
+ readonly _meta: {
46
+ readonly 'anthropic/alwaysLoad': true;
47
+ };
48
+ readonly description: "One-call context pack for a code question: combines structural search hits, non-trivial flow/impact chains, line-numbered source excerpts within a token budget, and related test files.";
49
+ readonly inputSchema: {
50
+ readonly type: "object";
51
+ readonly required: readonly ["query"];
52
+ readonly properties: {
53
+ readonly root: {
54
+ readonly type: "string";
55
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
56
+ };
57
+ readonly query: {
58
+ readonly type: "string";
59
+ readonly description: "Question keywords, symbol name, route, event, or job name.";
60
+ };
61
+ readonly budget: {
62
+ readonly type: "integer";
63
+ readonly minimum: 400;
64
+ readonly maximum: 16000;
65
+ readonly description: "Token budget for the pack (default: 3000).";
66
+ };
67
+ readonly folder: {
68
+ readonly type: "string";
69
+ readonly description: "Optional subfolder prefix to restrict search.";
70
+ };
71
+ readonly limit: {
72
+ readonly type: "integer";
73
+ readonly minimum: 1;
74
+ readonly maximum: 20;
75
+ readonly description: "Maximum search hits to consider (default: 8).";
76
+ };
77
+ readonly depth: {
78
+ readonly type: "integer";
79
+ readonly minimum: 1;
80
+ readonly maximum: 5;
81
+ readonly description: "Flow/impact traversal depth (default: 2).";
82
+ };
83
+ readonly includeTests: {
84
+ readonly type: "boolean";
85
+ readonly description: "Include test/spec files in search and chains (default: false).";
86
+ };
87
+ };
88
+ };
89
+ }, {
90
+ readonly name: "search";
91
+ readonly _meta: {
92
+ readonly 'anthropic/alwaysLoad': true;
93
+ };
94
+ readonly description: "Fast structural search across symbols, files, HTTP routes, events, and jobs. Returns file:line, signatures, entrypoints, and call/event/job links in one step. Use before Grep or Glob.";
95
+ readonly inputSchema: {
96
+ readonly type: "object";
97
+ readonly required: readonly ["query"];
98
+ readonly properties: {
99
+ readonly root: {
100
+ readonly type: "string";
101
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
102
+ };
103
+ readonly query: {
104
+ readonly type: "string";
105
+ readonly description: "Keywords, symbol name, route, event, or job name (e.g. \"validateApiKey\", \"storage path\", \"AssetExtractMetadata\").";
106
+ };
107
+ readonly folder: {
108
+ readonly type: "string";
109
+ readonly description: "Optional subfolder prefix to restrict search.";
110
+ };
111
+ readonly limit: {
112
+ readonly type: "integer";
113
+ readonly minimum: 1;
114
+ readonly maximum: 50;
115
+ readonly description: "Maximum hits to return (default: 12).";
116
+ };
117
+ readonly includeTests: {
118
+ readonly type: "boolean";
119
+ readonly description: "Include test/spec files (default: false).";
120
+ };
121
+ };
122
+ };
123
+ }, {
40
124
  readonly name: "map";
125
+ readonly _meta: {
126
+ readonly 'anthropic/alwaysLoad': true;
127
+ };
41
128
  readonly description: "Layered structural map of the codebase. Start with zoom=0 (~200 tokens) to see folders and roles, then zoom=1 on relevant folders (files + top-level symbols, tests excluded) before calling brief, flow, or impact.";
42
129
  readonly inputSchema: {
43
130
  readonly type: "object";
44
131
  readonly properties: {
132
+ readonly root: {
133
+ readonly type: "string";
134
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
135
+ };
45
136
  readonly folder: {
46
137
  readonly type: "string";
47
138
  readonly description: "Optional subfolder or file path relative to repo root.";
@@ -81,6 +172,10 @@ export declare const MCP_TOOLS: readonly [{
81
172
  readonly type: "object";
82
173
  readonly required: readonly ["files"];
83
174
  readonly properties: {
175
+ readonly root: {
176
+ readonly type: "string";
177
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
178
+ };
84
179
  readonly files: {
85
180
  readonly type: "array";
86
181
  readonly items: {
@@ -98,6 +193,10 @@ export declare const MCP_TOOLS: readonly [{
98
193
  readonly type: "object";
99
194
  readonly required: readonly ["files"];
100
195
  readonly properties: {
196
+ readonly root: {
197
+ readonly type: "string";
198
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
199
+ };
101
200
  readonly files: {
102
201
  readonly type: "array";
103
202
  readonly items: {
@@ -119,11 +218,18 @@ export declare const MCP_TOOLS: readonly [{
119
218
  };
120
219
  }, {
121
220
  readonly name: "flow";
221
+ readonly _meta: {
222
+ readonly 'anthropic/alwaysLoad': true;
223
+ };
122
224
  readonly description: "Trace downstream execution flow from a symbol (e.g. \"AuthController.changePassword\", \"OrderService.place\", \"event:OrderPlaced\", \"job:SendReceipt\") across calls, inherited fields, interface implementations, @OnEvent, @OnJob, and C# MediatR handlers.";
123
225
  readonly inputSchema: {
124
226
  readonly type: "object";
125
227
  readonly required: readonly ["symbol"];
126
228
  readonly properties: {
229
+ readonly root: {
230
+ readonly type: "string";
231
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
232
+ };
127
233
  readonly symbol: {
128
234
  readonly type: "string";
129
235
  readonly description: "Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.";
@@ -142,11 +248,18 @@ export declare const MCP_TOOLS: readonly [{
142
248
  };
143
249
  }, {
144
250
  readonly name: "impact";
251
+ readonly _meta: {
252
+ readonly 'anthropic/alwaysLoad': true;
253
+ };
145
254
  readonly description: "Trace upstream callers and entrypoints (HTTP routes, events, jobs) that reach a symbol.";
146
255
  readonly inputSchema: {
147
256
  readonly type: "object";
148
257
  readonly required: readonly ["symbol"];
149
258
  readonly properties: {
259
+ readonly root: {
260
+ readonly type: "string";
261
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
262
+ };
150
263
  readonly symbol: {
151
264
  readonly type: "string";
152
265
  readonly description: "Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.";
@@ -169,6 +282,10 @@ export declare const MCP_TOOLS: readonly [{
169
282
  readonly inputSchema: {
170
283
  readonly type: "object";
171
284
  readonly properties: {
285
+ readonly root: {
286
+ readonly type: "string";
287
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
288
+ };
172
289
  readonly top: {
173
290
  readonly type: "integer";
174
291
  readonly minimum: 1;
@@ -184,6 +301,10 @@ export declare const MCP_TOOLS: readonly [{
184
301
  readonly type: "object";
185
302
  readonly required: readonly ["maxFileLines", "maxFunctionLines", "hardFunctionLines", "maxNestingDepth", "minDuplicateLines"];
186
303
  readonly properties: {
304
+ readonly root: {
305
+ readonly type: "string";
306
+ readonly description: "Absolute project path; pass it when Atlas asks for it.";
307
+ };
187
308
  readonly maxFileLines: {
188
309
  readonly type: "integer";
189
310
  readonly minimum: 1;
@@ -239,6 +360,17 @@ export declare class McpHandler {
239
360
  */
240
361
  get root(): string;
241
362
  get out(): string;
363
+ /**
364
+ * The project a call maps (02/AC-18, 02/AC-20): `--root`; else the call's own `root` argument; else the git root
365
+ * at or above the client's workspace root (the one holding the start folder, or the first), or above the folder
366
+ * the tool started the server in. Never the home folder or `/`.
367
+ */
368
+ resolveRoot(argRoot?: unknown): string;
369
+ private outFor;
370
+ /** Set by serveMcp: sends a new roots/list request (and makes calls wait for it). */
371
+ requestRoots?: () => void;
372
+ /** True when the project can only come from the client: no --root, no root argument, no roots yet, start folder not a project. */
373
+ private needsClientRoots;
242
374
  /** A `roots/list` request is on its way; tool calls wait for its answer (at most `timeoutMs`). */
243
375
  expectRoots(timeoutMs?: number): void;
244
376
  setClientRoots(result: unknown): void;
@@ -9,19 +9,68 @@ import { checkLimits, health } from '../health/health.js';
9
9
  import { recordMcpMetric } from '../metrics/log.js';
10
10
  import { readCodeMap, readTopology } from '../outputs.js';
11
11
  import { flow, impact, renderFlow } from '../queries/flow.js';
12
+ import { investigate, renderInvestigate } from '../queries/investigate.js';
12
13
  import { renderMap } from '../queries/map.js';
13
14
  import { neighborhood } from '../queries/neighborhood.js';
15
+ import { renderSearch, search } from '../queries/search.js';
14
16
  import { scan } from '../scan/scan.js';
15
17
  import { briefsText, neighborhoodList, neighborhoodText } from '../text/briefs.js';
16
18
  import { estimateTokens } from '../tokens.js';
17
19
  import { GENERATOR_VERSION } from '../version.js';
20
+ /** Kept short: it is repeated in all eight tool schemas. */
21
+ const ROOT_DESCRIPTION = 'Absolute project path; pass it when Atlas asks for it.';
22
+ /** Shown by clients in the system prompt even while tool schemas are deferred (02/AC-23). */
23
+ export const SERVER_INSTRUCTIONS = 'FaberSEP Atlas maps the project the tool has open: files, symbols with signatures, calls, events and jobs. ' +
24
+ 'To find code, use these tools before Grep, Glob or reading files: investigate(query) for a one-call context pack ' +
25
+ '(search hits + flow/impact chains + budgeted code excerpts + related tests), search(query) to locate symbols, files, routes, ' +
26
+ 'events and jobs in one step, map (zoom 0, then zoom 1 on a folder) for folder overviews, flow to see what a function ' +
27
+ 'calls, impact to see what calls it and what a change breaks, brief for signatures. Use Grep and Read for exact literal ' +
28
+ 'text or when Atlas has no answer. If a call says the folder is not a project, call again with root set to the absolute project path.';
29
+ /** Claude Code keeps tools marked like this loaded instead of deferring them behind ToolSearch. */
30
+ const ALWAYS_LOAD = { 'anthropic/alwaysLoad': true };
18
31
  export const MCP_TOOLS = [
32
+ {
33
+ name: 'investigate',
34
+ _meta: ALWAYS_LOAD,
35
+ description: 'One-call context pack for a code question: combines structural search hits, non-trivial flow/impact chains, line-numbered source excerpts within a token budget, and related test files.',
36
+ inputSchema: {
37
+ type: 'object',
38
+ required: ['query'],
39
+ properties: {
40
+ root: { type: 'string', description: ROOT_DESCRIPTION },
41
+ query: { type: 'string', description: 'Question keywords, symbol name, route, event, or job name.' },
42
+ budget: { type: 'integer', minimum: 400, maximum: 16000, description: 'Token budget for the pack (default: 3000).' },
43
+ folder: { type: 'string', description: 'Optional subfolder prefix to restrict search.' },
44
+ limit: { type: 'integer', minimum: 1, maximum: 20, description: 'Maximum search hits to consider (default: 8).' },
45
+ depth: { type: 'integer', minimum: 1, maximum: 5, description: 'Flow/impact traversal depth (default: 2).' },
46
+ includeTests: { type: 'boolean', description: 'Include test/spec files in search and chains (default: false).' },
47
+ },
48
+ },
49
+ },
50
+ {
51
+ name: 'search',
52
+ _meta: ALWAYS_LOAD,
53
+ description: 'Fast structural search across symbols, files, HTTP routes, events, and jobs. Returns file:line, signatures, entrypoints, and call/event/job links in one step. Use before Grep or Glob.',
54
+ inputSchema: {
55
+ type: 'object',
56
+ required: ['query'],
57
+ properties: {
58
+ root: { type: 'string', description: ROOT_DESCRIPTION },
59
+ query: { type: 'string', description: 'Keywords, symbol name, route, event, or job name (e.g. "validateApiKey", "storage path", "AssetExtractMetadata").' },
60
+ folder: { type: 'string', description: 'Optional subfolder prefix to restrict search.' },
61
+ limit: { type: 'integer', minimum: 1, maximum: 50, description: 'Maximum hits to return (default: 12).' },
62
+ includeTests: { type: 'boolean', description: 'Include test/spec files (default: false).' },
63
+ },
64
+ },
65
+ },
19
66
  {
20
67
  name: 'map',
68
+ _meta: ALWAYS_LOAD,
21
69
  description: 'Layered structural map of the codebase. Start with zoom=0 (~200 tokens) to see folders and roles, then zoom=1 on relevant folders (files + top-level symbols, tests excluded) before calling brief, flow, or impact.',
22
70
  inputSchema: {
23
71
  type: 'object',
24
72
  properties: {
73
+ root: { type: 'string', description: ROOT_DESCRIPTION },
25
74
  folder: { type: 'string', description: 'Optional subfolder or file path relative to repo root.' },
26
75
  zoom: { type: 'integer', enum: [0, 1, 2], description: '0: folders with counts & roles; 1: files + top-level symbols (default); 2: method-level compact map.' },
27
76
  includeTests: { type: 'boolean', description: 'Include test/spec files in zoom 0/1 maps (default: false).' },
@@ -39,6 +88,7 @@ export const MCP_TOOLS = [
39
88
  type: 'object',
40
89
  required: ['files'],
41
90
  properties: {
91
+ root: { type: 'string', description: ROOT_DESCRIPTION },
42
92
  files: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Project-relative file paths.' },
43
93
  },
44
94
  },
@@ -50,6 +100,7 @@ export const MCP_TOOLS = [
50
100
  type: 'object',
51
101
  required: ['files'],
52
102
  properties: {
103
+ root: { type: 'string', description: ROOT_DESCRIPTION },
53
104
  files: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Project-relative target file paths.' },
54
105
  budget: { type: 'integer', minimum: 1, description: 'Optional token budget to include second-ring dependencies.' },
55
106
  list: { type: 'boolean', description: 'Return only file paths and token counts without briefs.' },
@@ -58,11 +109,13 @@ export const MCP_TOOLS = [
58
109
  },
59
110
  {
60
111
  name: 'flow',
112
+ _meta: ALWAYS_LOAD,
61
113
  description: 'Trace downstream execution flow from a symbol (e.g. "AuthController.changePassword", "OrderService.place", "event:OrderPlaced", "job:SendReceipt") across calls, inherited fields, interface implementations, @OnEvent, @OnJob, and C# MediatR handlers.',
62
114
  inputSchema: {
63
115
  type: 'object',
64
116
  required: ['symbol'],
65
117
  properties: {
118
+ root: { type: 'string', description: ROOT_DESCRIPTION },
66
119
  symbol: { type: 'string', description: 'Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.' },
67
120
  depth: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum traversal depth (default: 4).' },
68
121
  includeTests: { type: 'boolean', description: 'Include test files in traversal (default: false).' },
@@ -71,11 +124,13 @@ export const MCP_TOOLS = [
71
124
  },
72
125
  {
73
126
  name: 'impact',
127
+ _meta: ALWAYS_LOAD,
74
128
  description: 'Trace upstream callers and entrypoints (HTTP routes, events, jobs) that reach a symbol.',
75
129
  inputSchema: {
76
130
  type: 'object',
77
131
  required: ['symbol'],
78
132
  properties: {
133
+ root: { type: 'string', description: ROOT_DESCRIPTION },
79
134
  symbol: { type: 'string', description: 'Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.' },
80
135
  depth: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum traversal depth (default: 4).' },
81
136
  includeTests: { type: 'boolean', description: 'Include test files in traversal (default: false).' },
@@ -88,6 +143,7 @@ export const MCP_TOOLS = [
88
143
  inputSchema: {
89
144
  type: 'object',
90
145
  properties: {
146
+ root: { type: 'string', description: ROOT_DESCRIPTION },
91
147
  top: { type: 'integer', minimum: 1, maximum: 100, description: 'Number of top hubs to return (default: 10).' },
92
148
  },
93
149
  },
@@ -99,6 +155,7 @@ export const MCP_TOOLS = [
99
155
  type: 'object',
100
156
  required: ['maxFileLines', 'maxFunctionLines', 'hardFunctionLines', 'maxNestingDepth', 'minDuplicateLines'],
101
157
  properties: {
158
+ root: { type: 'string', description: ROOT_DESCRIPTION },
102
159
  maxFileLines: { type: 'integer', minimum: 1 },
103
160
  maxFunctionLines: { type: 'integer', minimum: 1 },
104
161
  hardFunctionLines: { type: 'integer', minimum: 1 },
@@ -126,8 +183,9 @@ export function projectRootFrom(start) {
126
183
  /** Atlas refuses to map the whole home folder or the file system root (an AI tool opened outside any project). */
127
184
  export class NoProjectError extends Error {
128
185
  constructor(folder) {
129
- super(`${folder} is not a project folder, so Atlas will not map it. Open your AI tool in a project folder ` +
130
- '(or start the server with --root <folder>).');
186
+ super(`${folder} is not a project folder, so Atlas will not map it. ` +
187
+ 'AI agent: call this tool again with "root" set to the absolute path of the project you are working in. ' +
188
+ '(Or open your AI tool in a project folder, or start the server with --root <folder>.)');
131
189
  }
132
190
  }
133
191
  function assertProject(root, userHome) {
@@ -192,15 +250,49 @@ export class McpHandler {
192
250
  * root (the one holding the start folder, or the first), or above the folder the tool started the server in.
193
251
  */
194
252
  get root() {
253
+ return this.resolveRoot();
254
+ }
255
+ get out() {
256
+ return this.outFor();
257
+ }
258
+ /**
259
+ * The project a call maps (02/AC-18, 02/AC-20): `--root`; else the call's own `root` argument; else the git root
260
+ * at or above the client's workspace root (the one holding the start folder, or the first), or above the folder
261
+ * the tool started the server in. Never the home folder or `/`.
262
+ */
263
+ resolveRoot(argRoot) {
195
264
  if (this.explicitRoot)
196
265
  return this.explicitRoot;
266
+ if (typeof argRoot === 'string' && argRoot.trim()) {
267
+ const given = argRoot.trim();
268
+ if (!path.isAbsolute(given))
269
+ throw new Error(`root must be an absolute path (got "${given}").`);
270
+ if (!fs.existsSync(given) || !fs.statSync(given).isDirectory())
271
+ throw new Error(`root ${given} is not a folder.`);
272
+ return assertProject(projectRootFrom(given), this.userHome);
273
+ }
197
274
  const inside = this.clientRoots.find((r) => this.cwd === r || this.cwd.startsWith(`${r}${path.sep}`));
198
275
  // Claude Code reports the folder it was opened in, which can be a subfolder: go up to its git root too.
199
276
  const picked = projectRootFrom(inside ?? this.clientRoots[0] ?? this.cwd);
200
277
  return assertProject(picked, this.userHome);
201
278
  }
202
- get out() {
203
- return this.explicitOut ?? path.join(this.root, '.faber-atlas');
279
+ outFor(argRoot) {
280
+ const hasArg = typeof argRoot === 'string' && argRoot.trim() !== '';
281
+ return this.explicitOut && (!hasArg || this.explicitRoot) ? this.explicitOut : path.join(this.resolveRoot(argRoot), '.faber-atlas');
282
+ }
283
+ /** Set by serveMcp: sends a new roots/list request (and makes calls wait for it). */
284
+ requestRoots;
285
+ /** True when the project can only come from the client: no --root, no root argument, no roots yet, start folder not a project. */
286
+ needsClientRoots(args) {
287
+ if (this.explicitRoot || (typeof args.root === 'string' && args.root.trim()) || this.clientRoots.length)
288
+ return false;
289
+ try {
290
+ this.resolveRoot();
291
+ return false;
292
+ }
293
+ catch {
294
+ return this.clientHasRoots;
295
+ }
204
296
  }
205
297
  /** A `roots/list` request is on its way; tool calls wait for its answer (at most `timeoutMs`). */
206
298
  expectRoots(timeoutMs = 2000) {
@@ -216,24 +308,27 @@ export class McpHandler {
216
308
  this.clientRoots = rootsToPaths(result).map((p) => path.resolve(p));
217
309
  this.releaseRoots?.();
218
310
  }
219
- async loadIndex() {
311
+ async loadIndex(root, out) {
220
312
  if (this.fresh)
221
- return ensureFreshIndex(this.root, this.out);
222
- return { map: readCodeMap(this.out), topology: readTopology(this.out) };
313
+ return ensureFreshIndex(root, out);
314
+ return { map: readCodeMap(out), topology: readTopology(out) };
223
315
  }
224
316
  /** Tool calls run one at a time, so two scans never write the same index together. */
225
317
  callToolQueued(name, args = {}) {
226
318
  const run = this.queue.then(async () => {
319
+ // Roots that came late, or empty at first: ask again before giving up on the project.
320
+ if (this.needsClientRoots(args))
321
+ this.requestRoots?.();
227
322
  await this.rootsWaiter;
228
323
  return this.callTool(name, args);
229
324
  });
230
325
  this.queue = run.catch(() => undefined);
231
326
  return run;
232
327
  }
233
- record(data) {
328
+ record(argRoot, data) {
234
329
  let out;
235
330
  try {
236
- out = this.out;
331
+ out = this.outFor(argRoot);
237
332
  }
238
333
  catch {
239
334
  return; // No project folder: nothing to log into.
@@ -244,9 +339,34 @@ export class McpHandler {
244
339
  const started = Date.now();
245
340
  const zoom = name === 'map' ? (asNumber(args.zoom) ?? 1) : undefined;
246
341
  try {
247
- const { map, topology } = await this.loadIndex();
342
+ const root = this.resolveRoot(args.root);
343
+ const { map, topology } = await this.loadIndex(root, this.outFor(args.root));
248
344
  let text;
249
345
  switch (name) {
346
+ case 'investigate': {
347
+ if (typeof args.query !== 'string' || !args.query.trim())
348
+ throw new Error('query is required.');
349
+ const result = investigate(map, root, args.query, {
350
+ budget: asNumber(args.budget),
351
+ folder: typeof args.folder === 'string' ? args.folder : undefined,
352
+ limit: asNumber(args.limit),
353
+ depth: asNumber(args.depth),
354
+ includeTests: args.includeTests === true,
355
+ });
356
+ text = renderInvestigate(result);
357
+ break;
358
+ }
359
+ case 'search': {
360
+ if (typeof args.query !== 'string' || !args.query.trim())
361
+ throw new Error('query is required.');
362
+ const result = search(map, args.query, {
363
+ folder: typeof args.folder === 'string' ? args.folder : undefined,
364
+ limit: asNumber(args.limit),
365
+ includeTests: args.includeTests === true,
366
+ });
367
+ text = renderSearch(result);
368
+ break;
369
+ }
250
370
  case 'map': {
251
371
  const z = (asNumber(args.zoom) ?? 1);
252
372
  if (z !== 0 && z !== 1 && z !== 2)
@@ -301,14 +421,14 @@ export class McpHandler {
301
421
  maxNestingDepth: asNumber(args.maxNestingDepth),
302
422
  minDuplicateLines: asNumber(args.minDuplicateLines),
303
423
  });
304
- const report = health(map, topology, this.root, limits, PACKS);
424
+ const report = health(map, topology, root, limits, PACKS);
305
425
  text = JSON.stringify(report, null, 2);
306
426
  break;
307
427
  }
308
428
  default:
309
429
  throw new Error(`Unknown tool: ${name}`);
310
430
  }
311
- this.record({
431
+ this.record(args.root, {
312
432
  tool: metricToolName(name),
313
433
  zoom,
314
434
  durationMs: Date.now() - started,
@@ -319,7 +439,7 @@ export class McpHandler {
319
439
  }
320
440
  catch (err) {
321
441
  const msg = err instanceof Error ? err.message : String(err);
322
- this.record({
442
+ this.record(args.root, {
323
443
  tool: metricToolName(name),
324
444
  zoom,
325
445
  durationMs: Date.now() - started,
@@ -345,6 +465,7 @@ export class McpHandler {
345
465
  protocolVersion: clientVersion,
346
466
  capabilities: { tools: {} },
347
467
  serverInfo: { name: 'faber-atlas', version: GENERATOR_VERSION },
468
+ instructions: SERVER_INSTRUCTIONS,
348
469
  },
349
470
  };
350
471
  }
@@ -376,12 +497,15 @@ export async function serveMcp(options = {}) {
376
497
  const send = (msg) => output.write(`${JSON.stringify(msg)}\n`);
377
498
  const pending = [];
378
499
  let rootsRequest = 0;
500
+ const log = (msg) => (options.log ?? ((m) => process.stderr.write(`faber-atlas mcp: ${m}\n`)))(msg);
379
501
  const askRoots = () => {
380
502
  if (!handler.clientHasRoots || options.root !== undefined)
381
503
  return;
382
504
  handler.expectRoots();
383
505
  send({ jsonrpc: '2.0', id: `faber-atlas-roots-${++rootsRequest}`, method: 'roots/list' });
384
506
  };
507
+ handler.requestRoots = askRoots;
508
+ log(`started in ${options.cwd ?? process.cwd()}${options.root ? ` (--root ${options.root})` : ''}`);
385
509
  for await (const rawLine of rl) {
386
510
  const line = rawLine.trim();
387
511
  if (!line)
@@ -397,12 +521,17 @@ export async function serveMcp(options = {}) {
397
521
  // The client's answer to our roots/list request.
398
522
  if (req.method === undefined && typeof req.id === 'string' && req.id.startsWith('faber-atlas-roots-')) {
399
523
  handler.setClientRoots(req.error ? {} : req.result);
524
+ log(req.error ? 'the client could not list its workspace roots' : `client workspace roots: ${rootsToPaths(req.result).join(', ') || '(none)'}`);
400
525
  continue;
401
526
  }
402
527
  if (req.method === 'notifications/initialized' || req.method === 'notifications/roots/list_changed') {
403
528
  askRoots();
404
529
  continue;
405
530
  }
531
+ if (req.method === 'initialize') {
532
+ const caps = (req.params?.capabilities ?? {});
533
+ log(caps.roots ? 'client can list workspace roots' : 'client does not list workspace roots; calls need a root argument outside a project');
534
+ }
406
535
  // Answered without blocking the reader, so a roots/list answer can arrive while a tool call waits for it.
407
536
  const done = handler.handleMessage(req).then((resp) => {
408
537
  if (resp)
@@ -4,8 +4,11 @@ import { isTestFile } from './map.js';
4
4
  export class UnknownSymbolError extends Error {
5
5
  }
6
6
  function normKey(key) {
7
- const tail = key.includes('.') ? key.split('.').pop() : key;
8
- return tail.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
7
+ const parts = key.split('.');
8
+ // Strip PascalCase/UPPER enum prefixes (e.g. `JobName.SendReceipt` -> `SendReceipt`),
9
+ // but preserve lowercase dot-namespaced event keys (e.g. `users.suspend` vs `documents.suspend`).
10
+ const target = parts.length > 1 && /^[A-Z]/.test(parts[0]) ? parts[parts.length - 1] : key;
11
+ return target.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();
9
12
  }
10
13
  function simpleType(ref) {
11
14
  return ref.replace(/<.*$/s, '').split('.').pop().trim();
@@ -360,8 +363,12 @@ function formatNodeMeta(node) {
360
363
  const parts = [];
361
364
  if (node.file && node.line)
362
365
  parts.push(`(${node.file}:${node.line})`);
363
- if (node.entrypoints?.length)
364
- parts.push(`[${node.entrypoints.join(', ')}]`);
366
+ if (node.entrypoints?.length) {
367
+ const eps = node.entrypoints.length <= 5
368
+ ? node.entrypoints.join(', ')
369
+ : `${node.entrypoints.slice(0, 4).join(', ')}, +${node.entrypoints.length - 4} more`;
370
+ parts.push(`[${eps}]`);
371
+ }
365
372
  if (node.throws?.length)
366
373
  parts.push(`[throws: ${node.throws.join(', ')}]`);
367
374
  if (node.boundary)
@@ -0,0 +1,43 @@
1
+ import type { CodeMap } from '../model.js';
2
+ import { type SearchResult } from './search.js';
3
+ /**
4
+ * One-call deterministic context pack (`investigate`, Feature 03 FR-02).
5
+ * Combines structural search hits, non-trivial flow/impact chains, token-budgeted
6
+ * line-numbered source excerpts, and related test file pointers in a single call.
7
+ */
8
+ export interface InvestigateOptions {
9
+ /** Token budget for the full rendered pack (default: 3000, clamped to 400..16000). */
10
+ budget?: number;
11
+ /** Optional subfolder prefix to restrict search. */
12
+ folder?: string;
13
+ /** Maximum number of search hits to consider (default: 8, clamped to 1..20). */
14
+ limit?: number;
15
+ /** Maximum flow/impact traversal depth (default: 2, clamped to 1..5). */
16
+ depth?: number;
17
+ /** Include test/spec files in search and chains (default: false). */
18
+ includeTests?: boolean;
19
+ }
20
+ export interface InvestigateChain {
21
+ symbol: string;
22
+ flowText?: string;
23
+ impactText?: string;
24
+ }
25
+ export interface InvestigateExcerpt {
26
+ file: string;
27
+ label: string;
28
+ lineStart: number;
29
+ lineEnd: number;
30
+ truncated: boolean;
31
+ code: string;
32
+ }
33
+ export interface InvestigateResult {
34
+ query: string;
35
+ budget: number;
36
+ estimatedTokens: number;
37
+ search: SearchResult;
38
+ chains: InvestigateChain[];
39
+ excerpts: InvestigateExcerpt[];
40
+ relatedTests: string[];
41
+ }
42
+ export declare function investigate(map: CodeMap, root: string, query: string, options?: InvestigateOptions): InvestigateResult;
43
+ export declare function renderInvestigate(result: InvestigateResult): string;