@fabersep/atlas 0.0.0-stage → 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.
Files changed (155) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/LICENSE +202 -0
  3. package/README.md +175 -2
  4. package/dist/packs/csharp/calls.d.ts +4 -0
  5. package/dist/packs/csharp/calls.js +167 -0
  6. package/dist/packs/csharp/declarations.d.ts +4 -0
  7. package/dist/packs/csharp/declarations.js +142 -0
  8. package/dist/packs/csharp/pack.d.ts +2 -0
  9. package/dist/packs/csharp/pack.js +39 -0
  10. package/dist/packs/csharp/resolve.d.ts +2 -0
  11. package/dist/packs/csharp/resolve.js +35 -0
  12. package/dist/packs/csharp/signals.d.ts +7 -0
  13. package/dist/packs/csharp/signals.js +143 -0
  14. package/dist/packs/dart/calls.d.ts +4 -0
  15. package/dist/packs/dart/calls.js +130 -0
  16. package/dist/packs/dart/declarations.d.ts +11 -0
  17. package/dist/packs/dart/declarations.js +79 -0
  18. package/dist/packs/dart/members.d.ts +4 -0
  19. package/dist/packs/dart/members.js +62 -0
  20. package/dist/packs/dart/pack.d.ts +2 -0
  21. package/dist/packs/dart/pack.js +37 -0
  22. package/dist/packs/dart/resolve.d.ts +2 -0
  23. package/dist/packs/dart/resolve.js +32 -0
  24. package/dist/packs/index.d.ts +3 -0
  25. package/dist/packs/index.js +8 -0
  26. package/dist/packs/json/pack.d.ts +2 -0
  27. package/dist/packs/json/pack.js +27 -0
  28. package/dist/packs/msbuild/pack.d.ts +2 -0
  29. package/dist/packs/msbuild/pack.js +75 -0
  30. package/dist/packs/msbuild/xml.d.ts +16 -0
  31. package/dist/packs/msbuild/xml.js +123 -0
  32. package/dist/packs/typescript/calls.d.ts +4 -0
  33. package/dist/packs/typescript/calls.js +208 -0
  34. package/dist/packs/typescript/declarations.d.ts +9 -0
  35. package/dist/packs/typescript/declarations.js +74 -0
  36. package/dist/packs/typescript/members.d.ts +4 -0
  37. package/dist/packs/typescript/members.js +92 -0
  38. package/dist/packs/typescript/pack.d.ts +2 -0
  39. package/dist/packs/typescript/pack.js +53 -0
  40. package/dist/packs/typescript/resolve.d.ts +2 -0
  41. package/dist/packs/typescript/resolve.js +68 -0
  42. package/dist/packs/typescript/signals.d.ts +7 -0
  43. package/dist/packs/typescript/signals.js +310 -0
  44. package/dist/packs/yaml/pack.d.ts +2 -0
  45. package/dist/packs/yaml/pack.js +35 -0
  46. package/dist/src/cli.d.ts +2 -0
  47. package/dist/src/cli.js +477 -0
  48. package/dist/src/context/pre-grep.d.ts +15 -0
  49. package/dist/src/context/pre-grep.js +79 -0
  50. package/dist/src/context/pre-invoke.d.ts +20 -0
  51. package/dist/src/context/pre-invoke.js +127 -0
  52. package/dist/src/context/pre-prompt.d.ts +16 -0
  53. package/dist/src/context/pre-prompt.js +66 -0
  54. package/dist/src/context/session.d.ts +17 -0
  55. package/dist/src/context/session.js +57 -0
  56. package/dist/src/graph/build.d.ts +17 -0
  57. package/dist/src/graph/build.js +41 -0
  58. package/dist/src/graph/metrics.d.ts +12 -0
  59. package/dist/src/graph/metrics.js +75 -0
  60. package/dist/src/graph/topology.d.ts +5 -0
  61. package/dist/src/graph/topology.js +54 -0
  62. package/dist/src/health/compare.d.ts +2 -0
  63. package/dist/src/health/compare.js +38 -0
  64. package/dist/src/health/duplicates.d.ts +11 -0
  65. package/dist/src/health/duplicates.js +66 -0
  66. package/dist/src/health/health.d.ts +12 -0
  67. package/dist/src/health/health.js +94 -0
  68. package/dist/src/health/types.d.ts +101 -0
  69. package/dist/src/health/types.js +5 -0
  70. package/dist/src/index.d.ts +25 -0
  71. package/dist/src/index.js +22 -0
  72. package/dist/src/init/init.d.ts +104 -0
  73. package/dist/src/init/init.js +499 -0
  74. package/dist/src/init/scout.d.ts +45 -0
  75. package/dist/src/init/scout.js +217 -0
  76. package/dist/src/jsonc.d.ts +5 -0
  77. package/dist/src/jsonc.js +34 -0
  78. package/dist/src/mcp/server.d.ts +398 -0
  79. package/dist/src/mcp/server.js +543 -0
  80. package/dist/src/metrics/doctor.d.ts +15 -0
  81. package/dist/src/metrics/doctor.js +125 -0
  82. package/dist/src/metrics/log.d.ts +43 -0
  83. package/dist/src/metrics/log.js +101 -0
  84. package/dist/src/metrics/stats.d.ts +43 -0
  85. package/dist/src/metrics/stats.js +172 -0
  86. package/dist/src/model.d.ts +178 -0
  87. package/dist/src/model.js +2 -0
  88. package/dist/src/outputs.d.ts +16 -0
  89. package/dist/src/outputs.js +48 -0
  90. package/dist/src/packs/calls.d.ts +9 -0
  91. package/dist/src/packs/calls.js +119 -0
  92. package/dist/src/packs/dataShape.d.ts +6 -0
  93. package/dist/src/packs/dataShape.js +54 -0
  94. package/dist/src/packs/pack.d.ts +51 -0
  95. package/dist/src/packs/pack.js +3 -0
  96. package/dist/src/packs/packFiles.d.ts +5 -0
  97. package/dist/src/packs/packFiles.js +12 -0
  98. package/dist/src/packs/symbols.d.ts +39 -0
  99. package/dist/src/packs/symbols.js +98 -0
  100. package/dist/src/packs/treeSitter.d.ts +8 -0
  101. package/dist/src/packs/treeSitter.js +107 -0
  102. package/dist/src/queries/flow.d.ts +42 -0
  103. package/dist/src/queries/flow.js +398 -0
  104. package/dist/src/queries/investigate.d.ts +43 -0
  105. package/dist/src/queries/investigate.js +216 -0
  106. package/dist/src/queries/map.d.ts +28 -0
  107. package/dist/src/queries/map.js +102 -0
  108. package/dist/src/queries/neighborhood.d.ts +35 -0
  109. package/dist/src/queries/neighborhood.js +60 -0
  110. package/dist/src/queries/search.d.ts +37 -0
  111. package/dist/src/queries/search.js +279 -0
  112. package/dist/src/scan/audit.d.ts +2 -0
  113. package/dist/src/scan/audit.js +41 -0
  114. package/dist/src/scan/records.d.ts +12 -0
  115. package/dist/src/scan/records.js +42 -0
  116. package/dist/src/scan/resolveImports.d.ts +3 -0
  117. package/dist/src/scan/resolveImports.js +47 -0
  118. package/dist/src/scan/roles.d.ts +5 -0
  119. package/dist/src/scan/roles.js +87 -0
  120. package/dist/src/scan/scan.d.ts +24 -0
  121. package/dist/src/scan/scan.js +72 -0
  122. package/dist/src/text/briefs.d.ts +13 -0
  123. package/dist/src/text/briefs.js +43 -0
  124. package/dist/src/text/collapse.d.ts +10 -0
  125. package/dist/src/text/collapse.js +58 -0
  126. package/dist/src/text/declarations.d.ts +12 -0
  127. package/dist/src/text/declarations.js +120 -0
  128. package/dist/src/text/structure.d.ts +2 -0
  129. package/dist/src/text/structure.js +15 -0
  130. package/dist/src/text/tree.d.ts +20 -0
  131. package/dist/src/text/tree.js +49 -0
  132. package/dist/src/tokens.d.ts +4 -0
  133. package/dist/src/tokens.js +9 -0
  134. package/dist/src/version.d.ts +10 -0
  135. package/dist/src/version.js +11 -0
  136. package/dist/src/walk/ignoreRules.d.ts +17 -0
  137. package/dist/src/walk/ignoreRules.js +72 -0
  138. package/dist/src/walk/walk.d.ts +11 -0
  139. package/dist/src/walk/walk.js +29 -0
  140. package/grammars/LICENSE-tree-sitter-dart +20 -0
  141. package/grammars/README.md +11 -0
  142. package/grammars/tree-sitter-dart.wasm +0 -0
  143. package/package.json +68 -4
  144. package/packs/csharp/README.md +9 -0
  145. package/packs/csharp/imports.scm +3 -0
  146. package/packs/csharp/symbols.scm +17 -0
  147. package/packs/dart/imports.scm +5 -0
  148. package/packs/dart/symbols.scm +13 -0
  149. package/packs/msbuild/README.md +11 -0
  150. package/packs/typescript/exports.scm +16 -0
  151. package/packs/typescript/imports.scm +9 -0
  152. package/packs/typescript/symbols.scm +19 -0
  153. package/schema/ast_code_map.schema.json +144 -0
  154. package/schema/schema-lock.json +7 -0
  155. package/schema/topology.schema.json +87 -0
@@ -0,0 +1,543 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import readline from 'node:readline';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { PACKS } from '../../packs/index.js';
7
+ import { rankHubs } from '../graph/topology.js';
8
+ import { checkLimits, health } from '../health/health.js';
9
+ import { recordMcpMetric } from '../metrics/log.js';
10
+ import { readCodeMap, readTopology } from '../outputs.js';
11
+ import { flow, impact, renderFlow } from '../queries/flow.js';
12
+ import { investigate, renderInvestigate } from '../queries/investigate.js';
13
+ import { renderMap } from '../queries/map.js';
14
+ import { neighborhood } from '../queries/neighborhood.js';
15
+ import { renderSearch, search } from '../queries/search.js';
16
+ import { scan } from '../scan/scan.js';
17
+ import { briefsText, neighborhoodList, neighborhoodText } from '../text/briefs.js';
18
+ import { estimateTokens } from '../tokens.js';
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 };
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
+ },
66
+ {
67
+ name: 'map',
68
+ _meta: ALWAYS_LOAD,
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.',
70
+ inputSchema: {
71
+ type: 'object',
72
+ properties: {
73
+ root: { type: 'string', description: ROOT_DESCRIPTION },
74
+ folder: { type: 'string', description: 'Optional subfolder or file path relative to repo root.' },
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.' },
76
+ includeTests: { type: 'boolean', description: 'Include test/spec files in zoom 0/1 maps (default: false).' },
77
+ fields: { type: 'boolean', description: 'Include fields and getters in zoom 2 summaries.' },
78
+ full: { type: 'boolean', description: 'Print full public declaration signatures.' },
79
+ depth: { type: 'integer', minimum: 0, description: 'Maximum folder depth below root.' },
80
+ foldersOnly: { type: 'boolean', description: 'Print folder structure only.' },
81
+ },
82
+ },
83
+ },
84
+ {
85
+ name: 'brief',
86
+ description: 'Compact declaration skeletons (signatures, roles, entrypoints, thrown exceptions — without bodies) for one or more files.',
87
+ inputSchema: {
88
+ type: 'object',
89
+ required: ['files'],
90
+ properties: {
91
+ root: { type: 'string', description: ROOT_DESCRIPTION },
92
+ files: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Project-relative file paths.' },
93
+ },
94
+ },
95
+ },
96
+ {
97
+ name: 'neighborhood',
98
+ description: 'Target file(s) plus their direct imports and importers (and optionally second ring within a token budget) with briefs.',
99
+ inputSchema: {
100
+ type: 'object',
101
+ required: ['files'],
102
+ properties: {
103
+ root: { type: 'string', description: ROOT_DESCRIPTION },
104
+ files: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Project-relative target file paths.' },
105
+ budget: { type: 'integer', minimum: 1, description: 'Optional token budget to include second-ring dependencies.' },
106
+ list: { type: 'boolean', description: 'Return only file paths and token counts without briefs.' },
107
+ },
108
+ },
109
+ },
110
+ {
111
+ name: 'flow',
112
+ _meta: ALWAYS_LOAD,
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.',
114
+ inputSchema: {
115
+ type: 'object',
116
+ required: ['symbol'],
117
+ properties: {
118
+ root: { type: 'string', description: ROOT_DESCRIPTION },
119
+ symbol: { type: 'string', description: 'Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.' },
120
+ depth: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum traversal depth (default: 4).' },
121
+ includeTests: { type: 'boolean', description: 'Include test files in traversal (default: false).' },
122
+ },
123
+ },
124
+ },
125
+ {
126
+ name: 'impact',
127
+ _meta: ALWAYS_LOAD,
128
+ description: 'Trace upstream callers and entrypoints (HTTP routes, events, jobs) that reach a symbol.',
129
+ inputSchema: {
130
+ type: 'object',
131
+ required: ['symbol'],
132
+ properties: {
133
+ root: { type: 'string', description: ROOT_DESCRIPTION },
134
+ symbol: { type: 'string', description: 'Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.' },
135
+ depth: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum traversal depth (default: 4).' },
136
+ includeTests: { type: 'boolean', description: 'Include test files in traversal (default: false).' },
137
+ },
138
+ },
139
+ },
140
+ {
141
+ name: 'hubs',
142
+ description: 'List the most central/connected files in the dependency graph by centrality score and PageRank.',
143
+ inputSchema: {
144
+ type: 'object',
145
+ properties: {
146
+ root: { type: 'string', description: ROOT_DESCRIPTION },
147
+ top: { type: 'integer', minimum: 1, maximum: 100, description: 'Number of top hubs to return (default: 10).' },
148
+ },
149
+ },
150
+ },
151
+ {
152
+ name: 'health',
153
+ description: 'Check code health against explicit limits (file length, function length, nesting depth, duplicate blocks, import cycles).',
154
+ inputSchema: {
155
+ type: 'object',
156
+ required: ['maxFileLines', 'maxFunctionLines', 'hardFunctionLines', 'maxNestingDepth', 'minDuplicateLines'],
157
+ properties: {
158
+ root: { type: 'string', description: ROOT_DESCRIPTION },
159
+ maxFileLines: { type: 'integer', minimum: 1 },
160
+ maxFunctionLines: { type: 'integer', minimum: 1 },
161
+ hardFunctionLines: { type: 'integer', minimum: 1 },
162
+ maxNestingDepth: { type: 'integer', minimum: 0 },
163
+ minDuplicateLines: { type: 'integer', minimum: 1 },
164
+ },
165
+ },
166
+ },
167
+ ];
168
+ /** Ensures `.faber-atlas` outputs are up to date via incremental scan (re-parses only modified files). */
169
+ export async function ensureFreshIndex(root, out) {
170
+ const result = await scan({ root, out, packs: PACKS });
171
+ return { map: result.map, topology: result.topology };
172
+ }
173
+ /** The nearest folder at or above `start` that holds `.git`; `start` itself when there is none. */
174
+ export function projectRootFrom(start) {
175
+ const begin = path.resolve(start);
176
+ for (let dir = begin;; dir = path.dirname(dir)) {
177
+ if (fs.existsSync(path.join(dir, '.git')))
178
+ return dir;
179
+ if (path.dirname(dir) === dir)
180
+ return begin;
181
+ }
182
+ }
183
+ /** Atlas refuses to map the whole home folder or the file system root (an AI tool opened outside any project). */
184
+ export class NoProjectError extends Error {
185
+ constructor(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>.)');
189
+ }
190
+ }
191
+ function assertProject(root, userHome) {
192
+ const real = (p) => (fs.existsSync(p) ? fs.realpathSync(p) : path.resolve(p));
193
+ const r = real(root);
194
+ if (r === real(userHome) || path.dirname(r) === r)
195
+ throw new NoProjectError(root);
196
+ return root;
197
+ }
198
+ /** Workspace folders a client reported through MCP `roots/list` (file URIs only). */
199
+ export function rootsToPaths(result) {
200
+ const roots = result?.roots;
201
+ if (!Array.isArray(roots))
202
+ return [];
203
+ const paths = [];
204
+ for (const r of roots) {
205
+ const uri = r?.uri;
206
+ if (typeof uri === 'string' && uri.startsWith('file://')) {
207
+ try {
208
+ paths.push(fileURLToPath(uri));
209
+ }
210
+ catch {
211
+ // Not a local file URI.
212
+ }
213
+ }
214
+ }
215
+ return paths;
216
+ }
217
+ function asStringArray(val, field) {
218
+ if (!Array.isArray(val) || val.length === 0 || !val.every((v) => typeof v === 'string')) {
219
+ throw new Error(`${field} must be a non-empty array of strings.`);
220
+ }
221
+ return val;
222
+ }
223
+ function asNumber(val) {
224
+ return typeof val === 'number' && !Number.isNaN(val) ? val : undefined;
225
+ }
226
+ const TOOL_NAMES = new Set(MCP_TOOLS.map((t) => t.name));
227
+ /** Metrics keep only Atlas's own tool names; anything else a client sends is logged as "unknown" (02/AC-16). */
228
+ const metricToolName = (name) => (TOOL_NAMES.has(name) ? name : 'unknown');
229
+ export class McpHandler {
230
+ explicitRoot;
231
+ explicitOut;
232
+ cwd;
233
+ userHome;
234
+ fresh;
235
+ clientRoots = [];
236
+ rootsWaiter = Promise.resolve();
237
+ releaseRoots;
238
+ queue = Promise.resolve();
239
+ /** Set by `initialize` when the client can answer `roots/list`. */
240
+ clientHasRoots = false;
241
+ constructor(options = {}) {
242
+ this.explicitRoot = options.root === undefined ? undefined : path.resolve(options.root);
243
+ this.explicitOut = options.out === undefined ? undefined : path.resolve(options.out);
244
+ this.cwd = path.resolve(options.cwd ?? process.cwd());
245
+ this.userHome = options.userHome ?? os.homedir();
246
+ this.fresh = options.fresh !== false;
247
+ }
248
+ /**
249
+ * The project this server maps (02/AC-18): `--root` when given; else the git root at or above the client's workspace
250
+ * root (the one holding the start folder, or the first), or above the folder the tool started the server in.
251
+ */
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) {
264
+ if (this.explicitRoot)
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
+ }
274
+ const inside = this.clientRoots.find((r) => this.cwd === r || this.cwd.startsWith(`${r}${path.sep}`));
275
+ // Claude Code reports the folder it was opened in, which can be a subfolder: go up to its git root too.
276
+ const picked = projectRootFrom(inside ?? this.clientRoots[0] ?? this.cwd);
277
+ return assertProject(picked, this.userHome);
278
+ }
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
+ }
296
+ }
297
+ /** A `roots/list` request is on its way; tool calls wait for its answer (at most `timeoutMs`). */
298
+ expectRoots(timeoutMs = 2000) {
299
+ this.rootsWaiter = new Promise((resolve) => {
300
+ const timer = setTimeout(resolve, timeoutMs);
301
+ this.releaseRoots = () => {
302
+ clearTimeout(timer);
303
+ resolve();
304
+ };
305
+ });
306
+ }
307
+ setClientRoots(result) {
308
+ this.clientRoots = rootsToPaths(result).map((p) => path.resolve(p));
309
+ this.releaseRoots?.();
310
+ }
311
+ async loadIndex(root, out) {
312
+ if (this.fresh)
313
+ return ensureFreshIndex(root, out);
314
+ return { map: readCodeMap(out), topology: readTopology(out) };
315
+ }
316
+ /** Tool calls run one at a time, so two scans never write the same index together. */
317
+ callToolQueued(name, args = {}) {
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?.();
322
+ await this.rootsWaiter;
323
+ return this.callTool(name, args);
324
+ });
325
+ this.queue = run.catch(() => undefined);
326
+ return run;
327
+ }
328
+ record(argRoot, data) {
329
+ let out;
330
+ try {
331
+ out = this.outFor(argRoot);
332
+ }
333
+ catch {
334
+ return; // No project folder: nothing to log into.
335
+ }
336
+ recordMcpMetric(out, data);
337
+ }
338
+ async callTool(name, args = {}) {
339
+ const started = Date.now();
340
+ const zoom = name === 'map' ? (asNumber(args.zoom) ?? 1) : undefined;
341
+ try {
342
+ const root = this.resolveRoot(args.root);
343
+ const { map, topology } = await this.loadIndex(root, this.outFor(args.root));
344
+ let text;
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
+ }
370
+ case 'map': {
371
+ const z = (asNumber(args.zoom) ?? 1);
372
+ if (z !== 0 && z !== 1 && z !== 2)
373
+ throw new Error('zoom must be 0, 1, or 2.');
374
+ text = renderMap(map, {
375
+ folder: typeof args.folder === 'string' ? args.folder : undefined,
376
+ zoom: z,
377
+ includeTests: args.includeTests === true,
378
+ fields: args.fields === true,
379
+ full: args.full === true,
380
+ depth: asNumber(args.depth),
381
+ foldersOnly: args.foldersOnly === true,
382
+ });
383
+ break;
384
+ }
385
+ case 'brief': {
386
+ const files = asStringArray(args.files, 'files');
387
+ text = briefsText(map, files);
388
+ break;
389
+ }
390
+ case 'neighborhood': {
391
+ const files = asStringArray(args.files, 'files');
392
+ const result = neighborhood(map, topology, files, { budget: asNumber(args.budget) });
393
+ text = args.list === true ? neighborhoodList(result) : neighborhoodText(result);
394
+ break;
395
+ }
396
+ case 'flow': {
397
+ if (typeof args.symbol !== 'string' || !args.symbol.trim())
398
+ throw new Error('symbol is required.');
399
+ const result = flow(map, args.symbol, { depth: asNumber(args.depth), includeTests: args.includeTests === true });
400
+ text = renderFlow(result);
401
+ break;
402
+ }
403
+ case 'impact': {
404
+ if (typeof args.symbol !== 'string' || !args.symbol.trim())
405
+ throw new Error('symbol is required.');
406
+ const result = impact(map, args.symbol, { depth: asNumber(args.depth), includeTests: args.includeTests === true });
407
+ text = renderFlow(result);
408
+ break;
409
+ }
410
+ case 'hubs': {
411
+ const top = asNumber(args.top) ?? 10;
412
+ const list = rankHubs(topology.nodes, top);
413
+ text = list.map((h, i) => `#${i + 1} ${h.path} score ${h.centralityScore} in ${h.inDegree} out ${h.outDegree} pagerank ${h.pageRank}`).join('\n');
414
+ break;
415
+ }
416
+ case 'health': {
417
+ const limits = checkLimits({
418
+ maxFileLines: asNumber(args.maxFileLines),
419
+ maxFunctionLines: asNumber(args.maxFunctionLines),
420
+ hardFunctionLines: asNumber(args.hardFunctionLines),
421
+ maxNestingDepth: asNumber(args.maxNestingDepth),
422
+ minDuplicateLines: asNumber(args.minDuplicateLines),
423
+ });
424
+ const report = health(map, topology, root, limits, PACKS);
425
+ text = JSON.stringify(report, null, 2);
426
+ break;
427
+ }
428
+ default:
429
+ throw new Error(`Unknown tool: ${name}`);
430
+ }
431
+ this.record(args.root, {
432
+ tool: metricToolName(name),
433
+ zoom,
434
+ durationMs: Date.now() - started,
435
+ responseTokens: estimateTokens(text),
436
+ ok: true,
437
+ });
438
+ return { content: [{ type: 'text', text }] };
439
+ }
440
+ catch (err) {
441
+ const msg = err instanceof Error ? err.message : String(err);
442
+ this.record(args.root, {
443
+ tool: metricToolName(name),
444
+ zoom,
445
+ durationMs: Date.now() - started,
446
+ responseTokens: estimateTokens(msg),
447
+ ok: false,
448
+ });
449
+ return { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true };
450
+ }
451
+ }
452
+ async handleMessage(req) {
453
+ const id = req.id ?? null;
454
+ if (req.method === 'notifications/initialized' || req.method === 'notifications/cancelled') {
455
+ return undefined;
456
+ }
457
+ if (req.method === 'initialize') {
458
+ const caps = req.params?.capabilities;
459
+ this.clientHasRoots = !!caps && typeof caps === 'object' && !!caps.roots;
460
+ const clientVersion = typeof req.params?.protocolVersion === 'string' ? req.params.protocolVersion : '2024-11-05';
461
+ return {
462
+ jsonrpc: '2.0',
463
+ id,
464
+ result: {
465
+ protocolVersion: clientVersion,
466
+ capabilities: { tools: {} },
467
+ serverInfo: { name: 'faber-atlas', version: GENERATOR_VERSION },
468
+ instructions: SERVER_INSTRUCTIONS,
469
+ },
470
+ };
471
+ }
472
+ if (req.method === 'ping') {
473
+ return { jsonrpc: '2.0', id, result: {} };
474
+ }
475
+ if (req.method === 'tools/list') {
476
+ return { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };
477
+ }
478
+ if (req.method === 'tools/call') {
479
+ const name = typeof req.params?.name === 'string' ? req.params.name : '';
480
+ const args = (req.params?.arguments && typeof req.params.arguments === 'object')
481
+ ? req.params.arguments
482
+ : {};
483
+ const result = await this.callToolQueued(name, args);
484
+ return { jsonrpc: '2.0', id, result };
485
+ }
486
+ if (req.id === undefined)
487
+ return undefined;
488
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${req.method}` } };
489
+ }
490
+ }
491
+ /** Runs the stdio MCP server until the input stream closes. */
492
+ export async function serveMcp(options = {}) {
493
+ const input = options.input ?? process.stdin;
494
+ const output = options.output ?? process.stdout;
495
+ const handler = new McpHandler(options);
496
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
497
+ const send = (msg) => output.write(`${JSON.stringify(msg)}\n`);
498
+ const pending = [];
499
+ let rootsRequest = 0;
500
+ const log = (msg) => (options.log ?? ((m) => process.stderr.write(`faber-atlas mcp: ${m}\n`)))(msg);
501
+ const askRoots = () => {
502
+ if (!handler.clientHasRoots || options.root !== undefined)
503
+ return;
504
+ handler.expectRoots();
505
+ send({ jsonrpc: '2.0', id: `faber-atlas-roots-${++rootsRequest}`, method: 'roots/list' });
506
+ };
507
+ handler.requestRoots = askRoots;
508
+ log(`started in ${options.cwd ?? process.cwd()}${options.root ? ` (--root ${options.root})` : ''}`);
509
+ for await (const rawLine of rl) {
510
+ const line = rawLine.trim();
511
+ if (!line)
512
+ continue;
513
+ let req;
514
+ try {
515
+ req = JSON.parse(line);
516
+ }
517
+ catch {
518
+ send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
519
+ continue;
520
+ }
521
+ // The client's answer to our roots/list request.
522
+ if (req.method === undefined && typeof req.id === 'string' && req.id.startsWith('faber-atlas-roots-')) {
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)'}`);
525
+ continue;
526
+ }
527
+ if (req.method === 'notifications/initialized' || req.method === 'notifications/roots/list_changed') {
528
+ askRoots();
529
+ continue;
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
+ }
535
+ // Answered without blocking the reader, so a roots/list answer can arrive while a tool call waits for it.
536
+ const done = handler.handleMessage(req).then((resp) => {
537
+ if (resp)
538
+ send(resp);
539
+ });
540
+ pending.push(done);
541
+ }
542
+ await Promise.all(pending);
543
+ }
@@ -0,0 +1,15 @@
1
+ export type CheckStatus = 'PASS' | 'WARN' | 'FAIL';
2
+ export interface DoctorCheck {
3
+ id: string;
4
+ status: CheckStatus;
5
+ message: string;
6
+ }
7
+ export interface DoctorReport {
8
+ ok: boolean;
9
+ root: string;
10
+ out: string;
11
+ checks: DoctorCheck[];
12
+ }
13
+ /** Read-only health check for a repository's FaberSEP Atlas setup. Never mutates files. */
14
+ export declare function runDoctor(rootInput: string, outInput?: string): DoctorReport;
15
+ export declare function formatDoctor(report: DoctorReport): string;