@fabersep/atlas 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/LICENSE +202 -0
  3. package/README.md +139 -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 +201 -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 +186 -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 +371 -0
  48. package/dist/src/graph/build.d.ts +17 -0
  49. package/dist/src/graph/build.js +41 -0
  50. package/dist/src/graph/metrics.d.ts +12 -0
  51. package/dist/src/graph/metrics.js +75 -0
  52. package/dist/src/graph/topology.d.ts +5 -0
  53. package/dist/src/graph/topology.js +54 -0
  54. package/dist/src/health/compare.d.ts +2 -0
  55. package/dist/src/health/compare.js +38 -0
  56. package/dist/src/health/duplicates.d.ts +11 -0
  57. package/dist/src/health/duplicates.js +66 -0
  58. package/dist/src/health/health.d.ts +12 -0
  59. package/dist/src/health/health.js +94 -0
  60. package/dist/src/health/types.d.ts +101 -0
  61. package/dist/src/health/types.js +5 -0
  62. package/dist/src/index.d.ts +23 -0
  63. package/dist/src/index.js +20 -0
  64. package/dist/src/init/init.d.ts +73 -0
  65. package/dist/src/init/init.js +305 -0
  66. package/dist/src/init/scout.d.ts +45 -0
  67. package/dist/src/init/scout.js +208 -0
  68. package/dist/src/jsonc.d.ts +5 -0
  69. package/dist/src/jsonc.js +34 -0
  70. package/dist/src/mcp/server.d.ts +266 -0
  71. package/dist/src/mcp/server.js +414 -0
  72. package/dist/src/metrics/doctor.d.ts +15 -0
  73. package/dist/src/metrics/doctor.js +125 -0
  74. package/dist/src/metrics/log.d.ts +43 -0
  75. package/dist/src/metrics/log.js +101 -0
  76. package/dist/src/metrics/stats.d.ts +43 -0
  77. package/dist/src/metrics/stats.js +172 -0
  78. package/dist/src/model.d.ts +178 -0
  79. package/dist/src/model.js +2 -0
  80. package/dist/src/outputs.d.ts +16 -0
  81. package/dist/src/outputs.js +48 -0
  82. package/dist/src/packs/calls.d.ts +9 -0
  83. package/dist/src/packs/calls.js +119 -0
  84. package/dist/src/packs/dataShape.d.ts +6 -0
  85. package/dist/src/packs/dataShape.js +54 -0
  86. package/dist/src/packs/pack.d.ts +51 -0
  87. package/dist/src/packs/pack.js +3 -0
  88. package/dist/src/packs/packFiles.d.ts +5 -0
  89. package/dist/src/packs/packFiles.js +12 -0
  90. package/dist/src/packs/symbols.d.ts +39 -0
  91. package/dist/src/packs/symbols.js +98 -0
  92. package/dist/src/packs/treeSitter.d.ts +8 -0
  93. package/dist/src/packs/treeSitter.js +107 -0
  94. package/dist/src/queries/flow.d.ts +42 -0
  95. package/dist/src/queries/flow.js +391 -0
  96. package/dist/src/queries/map.d.ts +28 -0
  97. package/dist/src/queries/map.js +102 -0
  98. package/dist/src/queries/neighborhood.d.ts +35 -0
  99. package/dist/src/queries/neighborhood.js +60 -0
  100. package/dist/src/scan/audit.d.ts +2 -0
  101. package/dist/src/scan/audit.js +41 -0
  102. package/dist/src/scan/records.d.ts +12 -0
  103. package/dist/src/scan/records.js +42 -0
  104. package/dist/src/scan/resolveImports.d.ts +3 -0
  105. package/dist/src/scan/resolveImports.js +47 -0
  106. package/dist/src/scan/roles.d.ts +5 -0
  107. package/dist/src/scan/roles.js +87 -0
  108. package/dist/src/scan/scan.d.ts +24 -0
  109. package/dist/src/scan/scan.js +72 -0
  110. package/dist/src/text/briefs.d.ts +13 -0
  111. package/dist/src/text/briefs.js +43 -0
  112. package/dist/src/text/collapse.d.ts +10 -0
  113. package/dist/src/text/collapse.js +58 -0
  114. package/dist/src/text/declarations.d.ts +12 -0
  115. package/dist/src/text/declarations.js +120 -0
  116. package/dist/src/text/structure.d.ts +2 -0
  117. package/dist/src/text/structure.js +15 -0
  118. package/dist/src/text/tree.d.ts +20 -0
  119. package/dist/src/text/tree.js +49 -0
  120. package/dist/src/tokens.d.ts +4 -0
  121. package/dist/src/tokens.js +9 -0
  122. package/dist/src/version.d.ts +10 -0
  123. package/dist/src/version.js +11 -0
  124. package/dist/src/walk/ignoreRules.d.ts +17 -0
  125. package/dist/src/walk/ignoreRules.js +72 -0
  126. package/dist/src/walk/walk.d.ts +11 -0
  127. package/dist/src/walk/walk.js +29 -0
  128. package/grammars/LICENSE-tree-sitter-dart +20 -0
  129. package/grammars/README.md +11 -0
  130. package/grammars/tree-sitter-dart.wasm +0 -0
  131. package/package.json +68 -4
  132. package/packs/csharp/README.md +9 -0
  133. package/packs/csharp/imports.scm +3 -0
  134. package/packs/csharp/symbols.scm +17 -0
  135. package/packs/dart/imports.scm +5 -0
  136. package/packs/dart/symbols.scm +13 -0
  137. package/packs/msbuild/README.md +11 -0
  138. package/packs/typescript/exports.scm +16 -0
  139. package/packs/typescript/imports.scm +9 -0
  140. package/packs/typescript/symbols.scm +19 -0
  141. package/schema/ast_code_map.schema.json +144 -0
  142. package/schema/schema-lock.json +7 -0
  143. package/schema/topology.schema.json +87 -0
@@ -0,0 +1,266 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { CodeMap, Topology } from '../model.js';
3
+ /**
4
+ * Thin zero-dependency stdio MCP server (`faber-atlas mcp`).
5
+ * Exposes `map`, `brief`, `neighborhood`, `flow`, `impact`, `hubs`, and `health`
6
+ * with automatic incremental freshness before every query.
7
+ */
8
+ export interface McpServerOptions {
9
+ /** Project to scan and query. Default: the client's workspace root, else the git root above the current folder. */
10
+ root?: string;
11
+ /** Folder the server starts in (default: process.cwd()); tests set it. */
12
+ cwd?: string;
13
+ /** The user's home folder, which is never mapped as a whole (default: os.homedir()). */
14
+ userHome?: string;
15
+ /** Output directory for `.faber-atlas` artifacts (default: `<root>/.faber-atlas`). */
16
+ out?: string;
17
+ /** Run incremental scan automatically before each query (default: true). */
18
+ fresh?: boolean;
19
+ /** Streams for stdio transport (defaults to process.stdin / process.stdout). */
20
+ input?: Readable;
21
+ output?: Writable;
22
+ }
23
+ interface JsonRpcRequest {
24
+ jsonrpc: '2.0';
25
+ id?: string | number | null;
26
+ method: string;
27
+ params?: Record<string, unknown>;
28
+ }
29
+ interface JsonRpcResponse {
30
+ jsonrpc: '2.0';
31
+ id: string | number | null;
32
+ method?: string;
33
+ result?: unknown;
34
+ error?: {
35
+ code: number;
36
+ message: string;
37
+ };
38
+ }
39
+ export declare const MCP_TOOLS: readonly [{
40
+ readonly name: "map";
41
+ 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
+ readonly inputSchema: {
43
+ readonly type: "object";
44
+ readonly properties: {
45
+ readonly folder: {
46
+ readonly type: "string";
47
+ readonly description: "Optional subfolder or file path relative to repo root.";
48
+ };
49
+ readonly zoom: {
50
+ readonly type: "integer";
51
+ readonly enum: readonly [0, 1, 2];
52
+ readonly description: "0: folders with counts & roles; 1: files + top-level symbols (default); 2: method-level compact map.";
53
+ };
54
+ readonly includeTests: {
55
+ readonly type: "boolean";
56
+ readonly description: "Include test/spec files in zoom 0/1 maps (default: false).";
57
+ };
58
+ readonly fields: {
59
+ readonly type: "boolean";
60
+ readonly description: "Include fields and getters in zoom 2 summaries.";
61
+ };
62
+ readonly full: {
63
+ readonly type: "boolean";
64
+ readonly description: "Print full public declaration signatures.";
65
+ };
66
+ readonly depth: {
67
+ readonly type: "integer";
68
+ readonly minimum: 0;
69
+ readonly description: "Maximum folder depth below root.";
70
+ };
71
+ readonly foldersOnly: {
72
+ readonly type: "boolean";
73
+ readonly description: "Print folder structure only.";
74
+ };
75
+ };
76
+ };
77
+ }, {
78
+ readonly name: "brief";
79
+ readonly description: "Compact declaration skeletons (signatures, roles, entrypoints, thrown exceptions — without bodies) for one or more files.";
80
+ readonly inputSchema: {
81
+ readonly type: "object";
82
+ readonly required: readonly ["files"];
83
+ readonly properties: {
84
+ readonly files: {
85
+ readonly type: "array";
86
+ readonly items: {
87
+ readonly type: "string";
88
+ };
89
+ readonly minItems: 1;
90
+ readonly description: "Project-relative file paths.";
91
+ };
92
+ };
93
+ };
94
+ }, {
95
+ readonly name: "neighborhood";
96
+ readonly description: "Target file(s) plus their direct imports and importers (and optionally second ring within a token budget) with briefs.";
97
+ readonly inputSchema: {
98
+ readonly type: "object";
99
+ readonly required: readonly ["files"];
100
+ readonly properties: {
101
+ readonly files: {
102
+ readonly type: "array";
103
+ readonly items: {
104
+ readonly type: "string";
105
+ };
106
+ readonly minItems: 1;
107
+ readonly description: "Project-relative target file paths.";
108
+ };
109
+ readonly budget: {
110
+ readonly type: "integer";
111
+ readonly minimum: 1;
112
+ readonly description: "Optional token budget to include second-ring dependencies.";
113
+ };
114
+ readonly list: {
115
+ readonly type: "boolean";
116
+ readonly description: "Return only file paths and token counts without briefs.";
117
+ };
118
+ };
119
+ };
120
+ }, {
121
+ readonly name: "flow";
122
+ 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
+ readonly inputSchema: {
124
+ readonly type: "object";
125
+ readonly required: readonly ["symbol"];
126
+ readonly properties: {
127
+ readonly symbol: {
128
+ readonly type: "string";
129
+ readonly description: "Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.";
130
+ };
131
+ readonly depth: {
132
+ readonly type: "integer";
133
+ readonly minimum: 1;
134
+ readonly maximum: 10;
135
+ readonly description: "Maximum traversal depth (default: 4).";
136
+ };
137
+ readonly includeTests: {
138
+ readonly type: "boolean";
139
+ readonly description: "Include test files in traversal (default: false).";
140
+ };
141
+ };
142
+ };
143
+ }, {
144
+ readonly name: "impact";
145
+ readonly description: "Trace upstream callers and entrypoints (HTTP routes, events, jobs) that reach a symbol.";
146
+ readonly inputSchema: {
147
+ readonly type: "object";
148
+ readonly required: readonly ["symbol"];
149
+ readonly properties: {
150
+ readonly symbol: {
151
+ readonly type: "string";
152
+ readonly description: "Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.";
153
+ };
154
+ readonly depth: {
155
+ readonly type: "integer";
156
+ readonly minimum: 1;
157
+ readonly maximum: 10;
158
+ readonly description: "Maximum traversal depth (default: 4).";
159
+ };
160
+ readonly includeTests: {
161
+ readonly type: "boolean";
162
+ readonly description: "Include test files in traversal (default: false).";
163
+ };
164
+ };
165
+ };
166
+ }, {
167
+ readonly name: "hubs";
168
+ readonly description: "List the most central/connected files in the dependency graph by centrality score and PageRank.";
169
+ readonly inputSchema: {
170
+ readonly type: "object";
171
+ readonly properties: {
172
+ readonly top: {
173
+ readonly type: "integer";
174
+ readonly minimum: 1;
175
+ readonly maximum: 100;
176
+ readonly description: "Number of top hubs to return (default: 10).";
177
+ };
178
+ };
179
+ };
180
+ }, {
181
+ readonly name: "health";
182
+ readonly description: "Check code health against explicit limits (file length, function length, nesting depth, duplicate blocks, import cycles).";
183
+ readonly inputSchema: {
184
+ readonly type: "object";
185
+ readonly required: readonly ["maxFileLines", "maxFunctionLines", "hardFunctionLines", "maxNestingDepth", "minDuplicateLines"];
186
+ readonly properties: {
187
+ readonly maxFileLines: {
188
+ readonly type: "integer";
189
+ readonly minimum: 1;
190
+ };
191
+ readonly maxFunctionLines: {
192
+ readonly type: "integer";
193
+ readonly minimum: 1;
194
+ };
195
+ readonly hardFunctionLines: {
196
+ readonly type: "integer";
197
+ readonly minimum: 1;
198
+ };
199
+ readonly maxNestingDepth: {
200
+ readonly type: "integer";
201
+ readonly minimum: 0;
202
+ };
203
+ readonly minDuplicateLines: {
204
+ readonly type: "integer";
205
+ readonly minimum: 1;
206
+ };
207
+ };
208
+ };
209
+ }];
210
+ /** Ensures `.faber-atlas` outputs are up to date via incremental scan (re-parses only modified files). */
211
+ export declare function ensureFreshIndex(root: string, out: string): Promise<{
212
+ map: CodeMap;
213
+ topology: Topology;
214
+ }>;
215
+ /** The nearest folder at or above `start` that holds `.git`; `start` itself when there is none. */
216
+ export declare function projectRootFrom(start: string): string;
217
+ /** Atlas refuses to map the whole home folder or the file system root (an AI tool opened outside any project). */
218
+ export declare class NoProjectError extends Error {
219
+ constructor(folder: string);
220
+ }
221
+ /** Workspace folders a client reported through MCP `roots/list` (file URIs only). */
222
+ export declare function rootsToPaths(result: unknown): string[];
223
+ export declare class McpHandler {
224
+ private readonly explicitRoot?;
225
+ private readonly explicitOut?;
226
+ private readonly cwd;
227
+ private readonly userHome;
228
+ private readonly fresh;
229
+ private clientRoots;
230
+ private rootsWaiter;
231
+ private releaseRoots?;
232
+ private queue;
233
+ /** Set by `initialize` when the client can answer `roots/list`. */
234
+ clientHasRoots: boolean;
235
+ constructor(options?: McpServerOptions);
236
+ /**
237
+ * The project this server maps (02/AC-18): `--root` when given; else the git root at or above the client's workspace
238
+ * root (the one holding the start folder, or the first), or above the folder the tool started the server in.
239
+ */
240
+ get root(): string;
241
+ get out(): string;
242
+ /** A `roots/list` request is on its way; tool calls wait for its answer (at most `timeoutMs`). */
243
+ expectRoots(timeoutMs?: number): void;
244
+ setClientRoots(result: unknown): void;
245
+ private loadIndex;
246
+ /** Tool calls run one at a time, so two scans never write the same index together. */
247
+ callToolQueued(name: string, args?: Record<string, unknown>): Promise<{
248
+ content: Array<{
249
+ type: "text";
250
+ text: string;
251
+ }>;
252
+ isError?: boolean;
253
+ }>;
254
+ private record;
255
+ callTool(name: string, args?: Record<string, unknown>): Promise<{
256
+ content: Array<{
257
+ type: 'text';
258
+ text: string;
259
+ }>;
260
+ isError?: boolean;
261
+ }>;
262
+ handleMessage(req: JsonRpcRequest): Promise<JsonRpcResponse | undefined>;
263
+ }
264
+ /** Runs the stdio MCP server until the input stream closes. */
265
+ export declare function serveMcp(options?: McpServerOptions): Promise<void>;
266
+ export {};
@@ -0,0 +1,414 @@
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 { renderMap } from '../queries/map.js';
13
+ import { neighborhood } from '../queries/neighborhood.js';
14
+ import { scan } from '../scan/scan.js';
15
+ import { briefsText, neighborhoodList, neighborhoodText } from '../text/briefs.js';
16
+ import { estimateTokens } from '../tokens.js';
17
+ import { GENERATOR_VERSION } from '../version.js';
18
+ export const MCP_TOOLS = [
19
+ {
20
+ name: 'map',
21
+ 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
+ inputSchema: {
23
+ type: 'object',
24
+ properties: {
25
+ folder: { type: 'string', description: 'Optional subfolder or file path relative to repo root.' },
26
+ 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
+ includeTests: { type: 'boolean', description: 'Include test/spec files in zoom 0/1 maps (default: false).' },
28
+ fields: { type: 'boolean', description: 'Include fields and getters in zoom 2 summaries.' },
29
+ full: { type: 'boolean', description: 'Print full public declaration signatures.' },
30
+ depth: { type: 'integer', minimum: 0, description: 'Maximum folder depth below root.' },
31
+ foldersOnly: { type: 'boolean', description: 'Print folder structure only.' },
32
+ },
33
+ },
34
+ },
35
+ {
36
+ name: 'brief',
37
+ description: 'Compact declaration skeletons (signatures, roles, entrypoints, thrown exceptions — without bodies) for one or more files.',
38
+ inputSchema: {
39
+ type: 'object',
40
+ required: ['files'],
41
+ properties: {
42
+ files: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Project-relative file paths.' },
43
+ },
44
+ },
45
+ },
46
+ {
47
+ name: 'neighborhood',
48
+ description: 'Target file(s) plus their direct imports and importers (and optionally second ring within a token budget) with briefs.',
49
+ inputSchema: {
50
+ type: 'object',
51
+ required: ['files'],
52
+ properties: {
53
+ files: { type: 'array', items: { type: 'string' }, minItems: 1, description: 'Project-relative target file paths.' },
54
+ budget: { type: 'integer', minimum: 1, description: 'Optional token budget to include second-ring dependencies.' },
55
+ list: { type: 'boolean', description: 'Return only file paths and token counts without briefs.' },
56
+ },
57
+ },
58
+ },
59
+ {
60
+ name: 'flow',
61
+ 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
+ inputSchema: {
63
+ type: 'object',
64
+ required: ['symbol'],
65
+ properties: {
66
+ symbol: { type: 'string', description: 'Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.' },
67
+ depth: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum traversal depth (default: 4).' },
68
+ includeTests: { type: 'boolean', description: 'Include test files in traversal (default: false).' },
69
+ },
70
+ },
71
+ },
72
+ {
73
+ name: 'impact',
74
+ description: 'Trace upstream callers and entrypoints (HTTP routes, events, jobs) that reach a symbol.',
75
+ inputSchema: {
76
+ type: 'object',
77
+ required: ['symbol'],
78
+ properties: {
79
+ symbol: { type: 'string', description: 'Symbol name: Class.method, file#Class.method, functionName, event:<name>, or job:<name>.' },
80
+ depth: { type: 'integer', minimum: 1, maximum: 10, description: 'Maximum traversal depth (default: 4).' },
81
+ includeTests: { type: 'boolean', description: 'Include test files in traversal (default: false).' },
82
+ },
83
+ },
84
+ },
85
+ {
86
+ name: 'hubs',
87
+ description: 'List the most central/connected files in the dependency graph by centrality score and PageRank.',
88
+ inputSchema: {
89
+ type: 'object',
90
+ properties: {
91
+ top: { type: 'integer', minimum: 1, maximum: 100, description: 'Number of top hubs to return (default: 10).' },
92
+ },
93
+ },
94
+ },
95
+ {
96
+ name: 'health',
97
+ description: 'Check code health against explicit limits (file length, function length, nesting depth, duplicate blocks, import cycles).',
98
+ inputSchema: {
99
+ type: 'object',
100
+ required: ['maxFileLines', 'maxFunctionLines', 'hardFunctionLines', 'maxNestingDepth', 'minDuplicateLines'],
101
+ properties: {
102
+ maxFileLines: { type: 'integer', minimum: 1 },
103
+ maxFunctionLines: { type: 'integer', minimum: 1 },
104
+ hardFunctionLines: { type: 'integer', minimum: 1 },
105
+ maxNestingDepth: { type: 'integer', minimum: 0 },
106
+ minDuplicateLines: { type: 'integer', minimum: 1 },
107
+ },
108
+ },
109
+ },
110
+ ];
111
+ /** Ensures `.faber-atlas` outputs are up to date via incremental scan (re-parses only modified files). */
112
+ export async function ensureFreshIndex(root, out) {
113
+ const result = await scan({ root, out, packs: PACKS });
114
+ return { map: result.map, topology: result.topology };
115
+ }
116
+ /** The nearest folder at or above `start` that holds `.git`; `start` itself when there is none. */
117
+ export function projectRootFrom(start) {
118
+ const begin = path.resolve(start);
119
+ for (let dir = begin;; dir = path.dirname(dir)) {
120
+ if (fs.existsSync(path.join(dir, '.git')))
121
+ return dir;
122
+ if (path.dirname(dir) === dir)
123
+ return begin;
124
+ }
125
+ }
126
+ /** Atlas refuses to map the whole home folder or the file system root (an AI tool opened outside any project). */
127
+ export class NoProjectError extends Error {
128
+ 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>).');
131
+ }
132
+ }
133
+ function assertProject(root, userHome) {
134
+ const real = (p) => (fs.existsSync(p) ? fs.realpathSync(p) : path.resolve(p));
135
+ const r = real(root);
136
+ if (r === real(userHome) || path.dirname(r) === r)
137
+ throw new NoProjectError(root);
138
+ return root;
139
+ }
140
+ /** Workspace folders a client reported through MCP `roots/list` (file URIs only). */
141
+ export function rootsToPaths(result) {
142
+ const roots = result?.roots;
143
+ if (!Array.isArray(roots))
144
+ return [];
145
+ const paths = [];
146
+ for (const r of roots) {
147
+ const uri = r?.uri;
148
+ if (typeof uri === 'string' && uri.startsWith('file://')) {
149
+ try {
150
+ paths.push(fileURLToPath(uri));
151
+ }
152
+ catch {
153
+ // Not a local file URI.
154
+ }
155
+ }
156
+ }
157
+ return paths;
158
+ }
159
+ function asStringArray(val, field) {
160
+ if (!Array.isArray(val) || val.length === 0 || !val.every((v) => typeof v === 'string')) {
161
+ throw new Error(`${field} must be a non-empty array of strings.`);
162
+ }
163
+ return val;
164
+ }
165
+ function asNumber(val) {
166
+ return typeof val === 'number' && !Number.isNaN(val) ? val : undefined;
167
+ }
168
+ const TOOL_NAMES = new Set(MCP_TOOLS.map((t) => t.name));
169
+ /** Metrics keep only Atlas's own tool names; anything else a client sends is logged as "unknown" (02/AC-16). */
170
+ const metricToolName = (name) => (TOOL_NAMES.has(name) ? name : 'unknown');
171
+ export class McpHandler {
172
+ explicitRoot;
173
+ explicitOut;
174
+ cwd;
175
+ userHome;
176
+ fresh;
177
+ clientRoots = [];
178
+ rootsWaiter = Promise.resolve();
179
+ releaseRoots;
180
+ queue = Promise.resolve();
181
+ /** Set by `initialize` when the client can answer `roots/list`. */
182
+ clientHasRoots = false;
183
+ constructor(options = {}) {
184
+ this.explicitRoot = options.root === undefined ? undefined : path.resolve(options.root);
185
+ this.explicitOut = options.out === undefined ? undefined : path.resolve(options.out);
186
+ this.cwd = path.resolve(options.cwd ?? process.cwd());
187
+ this.userHome = options.userHome ?? os.homedir();
188
+ this.fresh = options.fresh !== false;
189
+ }
190
+ /**
191
+ * The project this server maps (02/AC-18): `--root` when given; else the git root at or above the client's workspace
192
+ * root (the one holding the start folder, or the first), or above the folder the tool started the server in.
193
+ */
194
+ get root() {
195
+ if (this.explicitRoot)
196
+ return this.explicitRoot;
197
+ const inside = this.clientRoots.find((r) => this.cwd === r || this.cwd.startsWith(`${r}${path.sep}`));
198
+ // Claude Code reports the folder it was opened in, which can be a subfolder: go up to its git root too.
199
+ const picked = projectRootFrom(inside ?? this.clientRoots[0] ?? this.cwd);
200
+ return assertProject(picked, this.userHome);
201
+ }
202
+ get out() {
203
+ return this.explicitOut ?? path.join(this.root, '.faber-atlas');
204
+ }
205
+ /** A `roots/list` request is on its way; tool calls wait for its answer (at most `timeoutMs`). */
206
+ expectRoots(timeoutMs = 2000) {
207
+ this.rootsWaiter = new Promise((resolve) => {
208
+ const timer = setTimeout(resolve, timeoutMs);
209
+ this.releaseRoots = () => {
210
+ clearTimeout(timer);
211
+ resolve();
212
+ };
213
+ });
214
+ }
215
+ setClientRoots(result) {
216
+ this.clientRoots = rootsToPaths(result).map((p) => path.resolve(p));
217
+ this.releaseRoots?.();
218
+ }
219
+ async loadIndex() {
220
+ if (this.fresh)
221
+ return ensureFreshIndex(this.root, this.out);
222
+ return { map: readCodeMap(this.out), topology: readTopology(this.out) };
223
+ }
224
+ /** Tool calls run one at a time, so two scans never write the same index together. */
225
+ callToolQueued(name, args = {}) {
226
+ const run = this.queue.then(async () => {
227
+ await this.rootsWaiter;
228
+ return this.callTool(name, args);
229
+ });
230
+ this.queue = run.catch(() => undefined);
231
+ return run;
232
+ }
233
+ record(data) {
234
+ let out;
235
+ try {
236
+ out = this.out;
237
+ }
238
+ catch {
239
+ return; // No project folder: nothing to log into.
240
+ }
241
+ recordMcpMetric(out, data);
242
+ }
243
+ async callTool(name, args = {}) {
244
+ const started = Date.now();
245
+ const zoom = name === 'map' ? (asNumber(args.zoom) ?? 1) : undefined;
246
+ try {
247
+ const { map, topology } = await this.loadIndex();
248
+ let text;
249
+ switch (name) {
250
+ case 'map': {
251
+ const z = (asNumber(args.zoom) ?? 1);
252
+ if (z !== 0 && z !== 1 && z !== 2)
253
+ throw new Error('zoom must be 0, 1, or 2.');
254
+ text = renderMap(map, {
255
+ folder: typeof args.folder === 'string' ? args.folder : undefined,
256
+ zoom: z,
257
+ includeTests: args.includeTests === true,
258
+ fields: args.fields === true,
259
+ full: args.full === true,
260
+ depth: asNumber(args.depth),
261
+ foldersOnly: args.foldersOnly === true,
262
+ });
263
+ break;
264
+ }
265
+ case 'brief': {
266
+ const files = asStringArray(args.files, 'files');
267
+ text = briefsText(map, files);
268
+ break;
269
+ }
270
+ case 'neighborhood': {
271
+ const files = asStringArray(args.files, 'files');
272
+ const result = neighborhood(map, topology, files, { budget: asNumber(args.budget) });
273
+ text = args.list === true ? neighborhoodList(result) : neighborhoodText(result);
274
+ break;
275
+ }
276
+ case 'flow': {
277
+ if (typeof args.symbol !== 'string' || !args.symbol.trim())
278
+ throw new Error('symbol is required.');
279
+ const result = flow(map, args.symbol, { depth: asNumber(args.depth), includeTests: args.includeTests === true });
280
+ text = renderFlow(result);
281
+ break;
282
+ }
283
+ case 'impact': {
284
+ if (typeof args.symbol !== 'string' || !args.symbol.trim())
285
+ throw new Error('symbol is required.');
286
+ const result = impact(map, args.symbol, { depth: asNumber(args.depth), includeTests: args.includeTests === true });
287
+ text = renderFlow(result);
288
+ break;
289
+ }
290
+ case 'hubs': {
291
+ const top = asNumber(args.top) ?? 10;
292
+ const list = rankHubs(topology.nodes, top);
293
+ text = list.map((h, i) => `#${i + 1} ${h.path} score ${h.centralityScore} in ${h.inDegree} out ${h.outDegree} pagerank ${h.pageRank}`).join('\n');
294
+ break;
295
+ }
296
+ case 'health': {
297
+ const limits = checkLimits({
298
+ maxFileLines: asNumber(args.maxFileLines),
299
+ maxFunctionLines: asNumber(args.maxFunctionLines),
300
+ hardFunctionLines: asNumber(args.hardFunctionLines),
301
+ maxNestingDepth: asNumber(args.maxNestingDepth),
302
+ minDuplicateLines: asNumber(args.minDuplicateLines),
303
+ });
304
+ const report = health(map, topology, this.root, limits, PACKS);
305
+ text = JSON.stringify(report, null, 2);
306
+ break;
307
+ }
308
+ default:
309
+ throw new Error(`Unknown tool: ${name}`);
310
+ }
311
+ this.record({
312
+ tool: metricToolName(name),
313
+ zoom,
314
+ durationMs: Date.now() - started,
315
+ responseTokens: estimateTokens(text),
316
+ ok: true,
317
+ });
318
+ return { content: [{ type: 'text', text }] };
319
+ }
320
+ catch (err) {
321
+ const msg = err instanceof Error ? err.message : String(err);
322
+ this.record({
323
+ tool: metricToolName(name),
324
+ zoom,
325
+ durationMs: Date.now() - started,
326
+ responseTokens: estimateTokens(msg),
327
+ ok: false,
328
+ });
329
+ return { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true };
330
+ }
331
+ }
332
+ async handleMessage(req) {
333
+ const id = req.id ?? null;
334
+ if (req.method === 'notifications/initialized' || req.method === 'notifications/cancelled') {
335
+ return undefined;
336
+ }
337
+ if (req.method === 'initialize') {
338
+ const caps = req.params?.capabilities;
339
+ this.clientHasRoots = !!caps && typeof caps === 'object' && !!caps.roots;
340
+ const clientVersion = typeof req.params?.protocolVersion === 'string' ? req.params.protocolVersion : '2024-11-05';
341
+ return {
342
+ jsonrpc: '2.0',
343
+ id,
344
+ result: {
345
+ protocolVersion: clientVersion,
346
+ capabilities: { tools: {} },
347
+ serverInfo: { name: 'faber-atlas', version: GENERATOR_VERSION },
348
+ },
349
+ };
350
+ }
351
+ if (req.method === 'ping') {
352
+ return { jsonrpc: '2.0', id, result: {} };
353
+ }
354
+ if (req.method === 'tools/list') {
355
+ return { jsonrpc: '2.0', id, result: { tools: MCP_TOOLS } };
356
+ }
357
+ if (req.method === 'tools/call') {
358
+ const name = typeof req.params?.name === 'string' ? req.params.name : '';
359
+ const args = (req.params?.arguments && typeof req.params.arguments === 'object')
360
+ ? req.params.arguments
361
+ : {};
362
+ const result = await this.callToolQueued(name, args);
363
+ return { jsonrpc: '2.0', id, result };
364
+ }
365
+ if (req.id === undefined)
366
+ return undefined;
367
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${req.method}` } };
368
+ }
369
+ }
370
+ /** Runs the stdio MCP server until the input stream closes. */
371
+ export async function serveMcp(options = {}) {
372
+ const input = options.input ?? process.stdin;
373
+ const output = options.output ?? process.stdout;
374
+ const handler = new McpHandler(options);
375
+ const rl = readline.createInterface({ input, crlfDelay: Infinity });
376
+ const send = (msg) => output.write(`${JSON.stringify(msg)}\n`);
377
+ const pending = [];
378
+ let rootsRequest = 0;
379
+ const askRoots = () => {
380
+ if (!handler.clientHasRoots || options.root !== undefined)
381
+ return;
382
+ handler.expectRoots();
383
+ send({ jsonrpc: '2.0', id: `faber-atlas-roots-${++rootsRequest}`, method: 'roots/list' });
384
+ };
385
+ for await (const rawLine of rl) {
386
+ const line = rawLine.trim();
387
+ if (!line)
388
+ continue;
389
+ let req;
390
+ try {
391
+ req = JSON.parse(line);
392
+ }
393
+ catch {
394
+ send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
395
+ continue;
396
+ }
397
+ // The client's answer to our roots/list request.
398
+ if (req.method === undefined && typeof req.id === 'string' && req.id.startsWith('faber-atlas-roots-')) {
399
+ handler.setClientRoots(req.error ? {} : req.result);
400
+ continue;
401
+ }
402
+ if (req.method === 'notifications/initialized' || req.method === 'notifications/roots/list_changed') {
403
+ askRoots();
404
+ continue;
405
+ }
406
+ // Answered without blocking the reader, so a roots/list answer can arrive while a tool call waits for it.
407
+ const done = handler.handleMessage(req).then((resp) => {
408
+ if (resp)
409
+ send(resp);
410
+ });
411
+ pending.push(done);
412
+ }
413
+ await Promise.all(pending);
414
+ }