@optave/codegraph 3.1.3 → 3.1.4

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 (185) hide show
  1. package/README.md +17 -19
  2. package/package.json +10 -7
  3. package/src/analysis/context.js +408 -0
  4. package/src/analysis/dependencies.js +341 -0
  5. package/src/analysis/exports.js +130 -0
  6. package/src/analysis/impact.js +463 -0
  7. package/src/analysis/module-map.js +322 -0
  8. package/src/analysis/roles.js +45 -0
  9. package/src/analysis/symbol-lookup.js +232 -0
  10. package/src/ast-analysis/shared.js +5 -4
  11. package/src/batch.js +2 -1
  12. package/src/builder/context.js +85 -0
  13. package/src/builder/helpers.js +218 -0
  14. package/src/builder/incremental.js +178 -0
  15. package/src/builder/pipeline.js +130 -0
  16. package/src/builder/stages/build-edges.js +297 -0
  17. package/src/builder/stages/build-structure.js +113 -0
  18. package/src/builder/stages/collect-files.js +44 -0
  19. package/src/builder/stages/detect-changes.js +413 -0
  20. package/src/builder/stages/finalize.js +139 -0
  21. package/src/builder/stages/insert-nodes.js +195 -0
  22. package/src/builder/stages/parse-files.js +28 -0
  23. package/src/builder/stages/resolve-imports.js +143 -0
  24. package/src/builder/stages/run-analyses.js +44 -0
  25. package/src/builder.js +10 -1485
  26. package/src/cfg.js +1 -2
  27. package/src/cli/commands/ast.js +26 -0
  28. package/src/cli/commands/audit.js +46 -0
  29. package/src/cli/commands/batch.js +68 -0
  30. package/src/cli/commands/branch-compare.js +21 -0
  31. package/src/cli/commands/build.js +26 -0
  32. package/src/cli/commands/cfg.js +30 -0
  33. package/src/cli/commands/check.js +79 -0
  34. package/src/cli/commands/children.js +31 -0
  35. package/src/cli/commands/co-change.js +65 -0
  36. package/src/cli/commands/communities.js +23 -0
  37. package/src/cli/commands/complexity.js +45 -0
  38. package/src/cli/commands/context.js +34 -0
  39. package/src/cli/commands/cycles.js +28 -0
  40. package/src/cli/commands/dataflow.js +32 -0
  41. package/src/cli/commands/deps.js +16 -0
  42. package/src/cli/commands/diff-impact.js +30 -0
  43. package/src/cli/commands/embed.js +30 -0
  44. package/src/cli/commands/export.js +75 -0
  45. package/src/cli/commands/exports.js +18 -0
  46. package/src/cli/commands/flow.js +36 -0
  47. package/src/cli/commands/fn-impact.js +30 -0
  48. package/src/cli/commands/impact.js +16 -0
  49. package/src/cli/commands/info.js +76 -0
  50. package/src/cli/commands/map.js +19 -0
  51. package/src/cli/commands/mcp.js +18 -0
  52. package/src/cli/commands/models.js +19 -0
  53. package/src/cli/commands/owners.js +25 -0
  54. package/src/cli/commands/path.js +36 -0
  55. package/src/cli/commands/plot.js +80 -0
  56. package/src/cli/commands/query.js +49 -0
  57. package/src/cli/commands/registry.js +100 -0
  58. package/src/cli/commands/roles.js +34 -0
  59. package/src/cli/commands/search.js +42 -0
  60. package/src/cli/commands/sequence.js +32 -0
  61. package/src/cli/commands/snapshot.js +61 -0
  62. package/src/cli/commands/stats.js +15 -0
  63. package/src/cli/commands/structure.js +32 -0
  64. package/src/cli/commands/triage.js +78 -0
  65. package/src/cli/commands/watch.js +12 -0
  66. package/src/cli/commands/where.js +24 -0
  67. package/src/cli/index.js +118 -0
  68. package/src/cli/shared/options.js +39 -0
  69. package/src/cli/shared/output.js +1 -0
  70. package/src/cli.js +11 -1522
  71. package/src/commands/check.js +5 -5
  72. package/src/commands/manifesto.js +3 -3
  73. package/src/commands/structure.js +1 -1
  74. package/src/communities.js +15 -87
  75. package/src/cycles.js +30 -85
  76. package/src/dataflow.js +1 -2
  77. package/src/db/connection.js +4 -4
  78. package/src/db/migrations.js +41 -0
  79. package/src/db/query-builder.js +6 -5
  80. package/src/db/repository/base.js +201 -0
  81. package/src/db/repository/graph-read.js +5 -2
  82. package/src/db/repository/in-memory-repository.js +584 -0
  83. package/src/db/repository/index.js +5 -1
  84. package/src/db/repository/nodes.js +63 -4
  85. package/src/db/repository/sqlite-repository.js +219 -0
  86. package/src/db.js +5 -0
  87. package/src/embeddings/generator.js +163 -0
  88. package/src/embeddings/index.js +13 -0
  89. package/src/embeddings/models.js +218 -0
  90. package/src/embeddings/search/cli-formatter.js +151 -0
  91. package/src/embeddings/search/filters.js +46 -0
  92. package/src/embeddings/search/hybrid.js +121 -0
  93. package/src/embeddings/search/keyword.js +68 -0
  94. package/src/embeddings/search/prepare.js +66 -0
  95. package/src/embeddings/search/semantic.js +145 -0
  96. package/src/embeddings/stores/fts5.js +27 -0
  97. package/src/embeddings/stores/sqlite-blob.js +24 -0
  98. package/src/embeddings/strategies/source.js +14 -0
  99. package/src/embeddings/strategies/structured.js +43 -0
  100. package/src/embeddings/strategies/text-utils.js +43 -0
  101. package/src/errors.js +78 -0
  102. package/src/export.js +217 -520
  103. package/src/extractors/csharp.js +10 -2
  104. package/src/extractors/go.js +3 -1
  105. package/src/extractors/helpers.js +71 -0
  106. package/src/extractors/java.js +9 -2
  107. package/src/extractors/javascript.js +38 -1
  108. package/src/extractors/php.js +3 -1
  109. package/src/extractors/python.js +14 -3
  110. package/src/extractors/rust.js +3 -1
  111. package/src/graph/algorithms/bfs.js +49 -0
  112. package/src/graph/algorithms/centrality.js +16 -0
  113. package/src/graph/algorithms/index.js +5 -0
  114. package/src/graph/algorithms/louvain.js +26 -0
  115. package/src/graph/algorithms/shortest-path.js +41 -0
  116. package/src/graph/algorithms/tarjan.js +49 -0
  117. package/src/graph/builders/dependency.js +91 -0
  118. package/src/graph/builders/index.js +3 -0
  119. package/src/graph/builders/structure.js +40 -0
  120. package/src/graph/builders/temporal.js +33 -0
  121. package/src/graph/classifiers/index.js +2 -0
  122. package/src/graph/classifiers/risk.js +85 -0
  123. package/src/graph/classifiers/roles.js +64 -0
  124. package/src/graph/index.js +13 -0
  125. package/src/graph/model.js +230 -0
  126. package/src/index.js +33 -210
  127. package/src/infrastructure/result-formatter.js +2 -21
  128. package/src/mcp/index.js +2 -0
  129. package/src/mcp/middleware.js +26 -0
  130. package/src/mcp/server.js +128 -0
  131. package/src/mcp/tool-registry.js +801 -0
  132. package/src/mcp/tools/ast-query.js +14 -0
  133. package/src/mcp/tools/audit.js +21 -0
  134. package/src/mcp/tools/batch-query.js +11 -0
  135. package/src/mcp/tools/branch-compare.js +10 -0
  136. package/src/mcp/tools/cfg.js +21 -0
  137. package/src/mcp/tools/check.js +43 -0
  138. package/src/mcp/tools/co-changes.js +20 -0
  139. package/src/mcp/tools/code-owners.js +12 -0
  140. package/src/mcp/tools/communities.js +15 -0
  141. package/src/mcp/tools/complexity.js +18 -0
  142. package/src/mcp/tools/context.js +17 -0
  143. package/src/mcp/tools/dataflow.js +26 -0
  144. package/src/mcp/tools/diff-impact.js +24 -0
  145. package/src/mcp/tools/execution-flow.js +26 -0
  146. package/src/mcp/tools/export-graph.js +57 -0
  147. package/src/mcp/tools/file-deps.js +12 -0
  148. package/src/mcp/tools/file-exports.js +13 -0
  149. package/src/mcp/tools/find-cycles.js +15 -0
  150. package/src/mcp/tools/fn-impact.js +15 -0
  151. package/src/mcp/tools/impact-analysis.js +12 -0
  152. package/src/mcp/tools/index.js +71 -0
  153. package/src/mcp/tools/list-functions.js +14 -0
  154. package/src/mcp/tools/list-repos.js +11 -0
  155. package/src/mcp/tools/module-map.js +6 -0
  156. package/src/mcp/tools/node-roles.js +14 -0
  157. package/src/mcp/tools/path.js +12 -0
  158. package/src/mcp/tools/query.js +30 -0
  159. package/src/mcp/tools/semantic-search.js +65 -0
  160. package/src/mcp/tools/sequence.js +17 -0
  161. package/src/mcp/tools/structure.js +15 -0
  162. package/src/mcp/tools/symbol-children.js +14 -0
  163. package/src/mcp/tools/triage.js +35 -0
  164. package/src/mcp/tools/where.js +13 -0
  165. package/src/mcp.js +2 -1470
  166. package/src/native.js +3 -1
  167. package/src/presentation/colors.js +44 -0
  168. package/src/presentation/export.js +444 -0
  169. package/src/presentation/result-formatter.js +21 -0
  170. package/src/presentation/sequence-renderer.js +43 -0
  171. package/src/presentation/table.js +47 -0
  172. package/src/presentation/viewer.js +634 -0
  173. package/src/queries.js +35 -2276
  174. package/src/resolve.js +1 -1
  175. package/src/sequence.js +2 -38
  176. package/src/shared/file-utils.js +153 -0
  177. package/src/shared/generators.js +125 -0
  178. package/src/shared/hierarchy.js +27 -0
  179. package/src/shared/normalize.js +59 -0
  180. package/src/snapshot.js +6 -5
  181. package/src/structure.js +15 -40
  182. package/src/triage.js +20 -72
  183. package/src/viewer.js +35 -656
  184. package/src/watcher.js +8 -148
  185. package/src/embedder.js +0 -1097
package/src/index.js CHANGED
@@ -1,243 +1,66 @@
1
1
  /**
2
2
  * codegraph — Programmatic API
3
3
  *
4
+ * Curated public surface: *Data() query functions, graph building,
5
+ * export formats, and essential constants. CLI formatters and internal
6
+ * utilities are not exported — import them directly if needed.
7
+ *
4
8
  * Usage:
5
- * import { buildGraph, queryNameData, findCycles, exportDOT } from 'codegraph';
9
+ * import { buildGraph, queryNameData, findCycles, exportDOT } from '@optave/codegraph';
6
10
  */
7
11
 
8
- // AST node queries
9
- export { AST_NODE_KINDS, astQuery, astQueryData } from './ast.js';
10
- // Audit (composite report)
12
+ export { astQueryData } from './ast.js';
11
13
  export { auditData } from './audit.js';
12
- // Batch querying
13
- export {
14
- BATCH_COMMANDS,
15
- batchData,
16
- multiBatchData,
17
- splitTargets,
18
- } from './batch.js';
19
- // Architecture boundary rules
20
- export { evaluateBoundaries, PRESETS, validateBoundaryConfig } from './boundaries.js';
21
- // Branch comparison
22
- export { branchCompareData, branchCompareMermaid } from './branch-compare.js';
23
- // Graph building
24
- export { buildGraph, collectFiles, loadPathAliases, resolveImportPath } from './builder.js';
25
- // Control flow graph (intraprocedural)
26
- export {
27
- buildCFGData,
28
- buildFunctionCFG,
29
- CFG_RULES,
30
- cfgData,
31
- cfgToDOT,
32
- cfgToMermaid,
33
- } from './cfg.js';
34
- // Check (CI validation predicates)
14
+ export { batchData } from './batch.js';
15
+ export { branchCompareData } from './branch-compare.js';
16
+ export { buildGraph } from './builder.js';
17
+ export { cfgData } from './cfg.js';
35
18
  export { checkData } from './check.js';
36
- // Co-change analysis
37
- export {
38
- analyzeCoChanges,
39
- coChangeData,
40
- coChangeForFiles,
41
- coChangeTopData,
42
- computeCoChanges,
43
- scanGitHistory,
44
- } from './cochange.js';
45
- export { audit } from './commands/audit.js';
46
- export { batch, batchQuery } from './commands/batch.js';
47
- export { cfg } from './commands/cfg.js';
48
- export { check } from './commands/check.js';
49
- export { communities } from './commands/communities.js';
50
- export { complexity } from './commands/complexity.js';
51
- export { dataflow } from './commands/dataflow.js';
52
- export { manifesto } from './commands/manifesto.js';
53
- export { owners } from './commands/owners.js';
54
- export { sequence } from './commands/sequence.js';
55
- export { formatHotspots, formatModuleBoundaries, formatStructure } from './commands/structure.js';
56
- export { triage } from './commands/triage.js';
57
- // Community detection
58
- export { communitiesData, communitySummaryForStats } from './communities.js';
59
- // Complexity metrics
60
- export {
61
- COMPLEXITY_RULES,
62
- complexityData,
63
- computeFunctionComplexity,
64
- computeHalsteadMetrics,
65
- computeLOCMetrics,
66
- computeMaintainabilityIndex,
67
- findFunctionNode,
68
- HALSTEAD_RULES,
69
- iterComplexity,
70
- } from './complexity.js';
71
- // Configuration
19
+ export { coChangeData } from './cochange.js';
20
+ export { communitiesData } from './communities.js';
21
+ export { complexityData } from './complexity.js';
72
22
  export { loadConfig } from './config.js';
73
- // Shared constants
74
- export { EXTENSIONS, IGNORE_DIRS, normalizePath } from './constants.js';
75
- // Circular dependency detection
76
- export { findCycles, formatCycles } from './cycles.js';
77
- // Dataflow analysis
78
- export {
79
- buildDataflowEdges,
80
- dataflowData,
81
- dataflowImpactData,
82
- dataflowPathData,
83
- extractDataflow,
84
- } from './dataflow.js';
85
- // Database utilities
86
- export {
87
- countEdges,
88
- countFiles,
89
- countNodes,
90
- fanInJoinSQL,
91
- fanOutJoinSQL,
92
- findDbPath,
93
- findNodesForTriage,
94
- findNodesWithFanIn,
95
- getBuildMeta,
96
- initSchema,
97
- iterateFunctionNodes,
98
- kindInClause,
99
- listFunctionNodes,
100
- NodeQuery,
101
- openDb,
102
- openReadonlyOrFail,
103
- setBuildMeta,
104
- testFilterSQL,
105
- } from './db.js';
106
- // Embeddings
23
+ export { EXTENSIONS, IGNORE_DIRS } from './constants.js';
24
+ export { findCycles } from './cycles.js';
25
+ export { dataflowData } from './dataflow.js';
107
26
  export {
108
27
  buildEmbeddings,
109
- cosineSim,
110
- DEFAULT_MODEL,
111
- disposeModel,
112
- EMBEDDING_STRATEGIES,
113
- embed,
114
- estimateTokens,
115
- ftsSearchData,
116
28
  hybridSearchData,
117
- MODELS,
118
29
  multiSearchData,
119
- search,
120
30
  searchData,
121
- } from './embedder.js';
122
- // Export (DOT/Mermaid/JSON/GraphML/GraphSON/Neo4j CSV)
123
- export {
124
- exportDOT,
125
- exportGraphML,
126
- exportGraphSON,
127
- exportJSON,
128
- exportMermaid,
129
- exportNeo4jCSV,
130
- } from './export.js';
131
- // Execution flow tracing
132
- export { entryPointType, flowData, listEntryPointsData } from './flow.js';
133
- // Result formatting
134
- export { outputResult } from './infrastructure/result-formatter.js';
135
- // Test file detection
136
- export { isTestFile, TEST_PATTERN } from './infrastructure/test-filter.js';
137
- // Logger
138
- export { setVerbose } from './logger.js';
139
- // Manifesto rule engine
140
- export { manifestoData, RULE_DEFS } from './manifesto.js';
141
- // Native engine
142
- export { isNativeAvailable } from './native.js';
143
- // Ownership (CODEOWNERS)
144
- export { matchOwners, ownersData, ownersForFiles, parseCodeowners } from './owners.js';
145
- // Pagination utilities
146
- export { MCP_DEFAULTS, MCP_MAX_LIMIT, paginate, paginateResult, printNdjson } from './paginate.js';
147
- // Unified parser API
31
+ } from './embeddings/index.js';
148
32
  export {
149
- disposeParsers,
150
- getActiveEngine,
151
- isWasmAvailable,
152
- parseFileAuto,
153
- parseFilesAuto,
154
- } from './parser.js';
155
- // Query functions (data-returning)
33
+ AnalysisError,
34
+ BoundaryError,
35
+ CodegraphError,
36
+ ConfigError,
37
+ DbError,
38
+ EngineError,
39
+ ParseError,
40
+ ResolutionError,
41
+ } from './errors.js';
42
+ export { exportDOT, exportJSON, exportMermaid } from './export.js';
43
+ export { flowData, listEntryPointsData } from './flow.js';
44
+ export { EVERY_EDGE_KIND, EVERY_SYMBOL_KIND } from './kinds.js';
45
+ export { manifestoData } from './manifesto.js';
46
+ export { ownersData } from './owners.js';
156
47
  export {
157
- ALL_SYMBOL_KINDS,
158
- CORE_EDGE_KINDS,
159
- CORE_SYMBOL_KINDS,
160
48
  childrenData,
161
49
  contextData,
162
50
  diffImpactData,
163
- diffImpactMermaid,
164
- EVERY_EDGE_KIND,
165
- EVERY_SYMBOL_KIND,
166
- EXTENDED_SYMBOL_KINDS,
167
51
  explainData,
168
52
  exportsData,
169
- FALSE_POSITIVE_CALLER_THRESHOLD,
170
- FALSE_POSITIVE_NAMES,
171
53
  fileDepsData,
172
54
  fnDepsData,
173
55
  fnImpactData,
174
56
  impactAnalysisData,
175
- iterListFunctions,
176
- iterRoles,
177
- iterWhere,
178
- kindIcon,
179
57
  moduleMapData,
180
- normalizeSymbol,
181
58
  pathData,
182
59
  queryNameData,
183
60
  rolesData,
184
- STRUCTURAL_EDGE_KINDS,
185
61
  statsData,
186
- VALID_ROLES,
187
62
  whereData,
188
63
  } from './queries.js';
189
- // Query CLI display wrappers
190
- export {
191
- children,
192
- context,
193
- diffImpact,
194
- explain,
195
- fileDeps,
196
- fileExports,
197
- fnDeps,
198
- fnImpact,
199
- impactAnalysis,
200
- moduleMap,
201
- queryName,
202
- roles,
203
- stats,
204
- symbolPath,
205
- where,
206
- } from './queries-cli.js';
207
- // Registry (multi-repo)
208
- export {
209
- listRepos,
210
- loadRegistry,
211
- pruneRegistry,
212
- REGISTRY_PATH,
213
- registerRepo,
214
- resolveRepoDbPath,
215
- saveRegistry,
216
- unregisterRepo,
217
- } from './registry.js';
218
- // Sequence diagram generation
219
- export { sequenceData, sequenceToMermaid } from './sequence.js';
220
- // Snapshot management
221
- export {
222
- snapshotDelete,
223
- snapshotList,
224
- snapshotRestore,
225
- snapshotSave,
226
- snapshotsDir,
227
- validateSnapshotName,
228
- } from './snapshot.js';
229
- // Structure analysis
230
- export {
231
- buildStructure,
232
- classifyNodeRoles,
233
- FRAMEWORK_ENTRY_PREFIXES,
234
- hotspotsData,
235
- moduleBoundariesData,
236
- structureData,
237
- } from './structure.js';
238
- // Triage — composite risk audit
64
+ export { sequenceData } from './sequence.js';
65
+ export { hotspotsData, moduleBoundariesData, structureData } from './structure.js';
239
66
  export { triageData } from './triage.js';
240
- // Interactive HTML viewer
241
- export { generatePlotHTML, loadPlotConfig } from './viewer.js';
242
- // Watch mode
243
- export { watchProject } from './watcher.js';
@@ -1,21 +1,2 @@
1
- import { printNdjson } from '../paginate.js';
2
-
3
- /**
4
- * Shared JSON / NDJSON output dispatch for CLI wrappers.
5
- *
6
- * @param {object} data - Result object from a *Data() function
7
- * @param {string} field - Array field name for NDJSON streaming (e.g. 'results')
8
- * @param {object} opts - CLI options ({ json?, ndjson? })
9
- * @returns {boolean} true if output was handled (caller should return early)
10
- */
11
- export function outputResult(data, field, opts) {
12
- if (opts.ndjson) {
13
- printNdjson(data, field);
14
- return true;
15
- }
16
- if (opts.json) {
17
- console.log(JSON.stringify(data, null, 2));
18
- return true;
19
- }
20
- return false;
21
- }
1
+ // Re-export from presentation layer — this file exists for backward compatibility.
2
+ export { outputResult } from '../presentation/result-formatter.js';
@@ -0,0 +1,2 @@
1
+ export { startMCPServer } from './server.js';
2
+ export { buildToolList, TOOLS } from './tool-registry.js';
@@ -0,0 +1,26 @@
1
+ /**
2
+ * MCP middleware helpers — pagination defaults and limits.
3
+ */
4
+
5
+ import { MCP_DEFAULTS, MCP_MAX_LIMIT } from '../paginate.js';
6
+
7
+ export { MCP_DEFAULTS, MCP_MAX_LIMIT };
8
+
9
+ /**
10
+ * Resolve effective limit for a tool call.
11
+ * @param {object} args - Tool arguments
12
+ * @param {string} toolName - Tool name (for default lookup)
13
+ * @returns {number}
14
+ */
15
+ export function effectiveLimit(args, toolName) {
16
+ return Math.min(args.limit ?? MCP_DEFAULTS[toolName] ?? 100, MCP_MAX_LIMIT);
17
+ }
18
+
19
+ /**
20
+ * Resolve effective offset for a tool call.
21
+ * @param {object} args - Tool arguments
22
+ * @returns {number}
23
+ */
24
+ export function effectiveOffset(args) {
25
+ return args.offset ?? 0;
26
+ }
@@ -0,0 +1,128 @@
1
+ /**
2
+ * MCP (Model Context Protocol) server for codegraph.
3
+ * Exposes codegraph queries as tools that AI coding assistants can call.
4
+ *
5
+ * Requires: npm install @modelcontextprotocol/sdk
6
+ */
7
+
8
+ import { createRequire } from 'node:module';
9
+ import { findDbPath } from '../db.js';
10
+ import { CodegraphError, ConfigError } from '../errors.js';
11
+ import { MCP_MAX_LIMIT } from '../paginate.js';
12
+ import { buildToolList } from './tool-registry.js';
13
+ import { TOOL_HANDLERS } from './tools/index.js';
14
+
15
+ /**
16
+ * Start the MCP server.
17
+ * This function requires @modelcontextprotocol/sdk to be installed.
18
+ *
19
+ * @param {string} [customDbPath] - Path to a specific graph.db
20
+ * @param {object} [options]
21
+ * @param {boolean} [options.multiRepo] - Enable multi-repo access (default: false)
22
+ * @param {string[]} [options.allowedRepos] - Restrict access to these repo names only
23
+ */
24
+ export async function startMCPServer(customDbPath, options = {}) {
25
+ const { allowedRepos } = options;
26
+ const multiRepo = options.multiRepo || !!allowedRepos;
27
+ let Server, StdioServerTransport, ListToolsRequestSchema, CallToolRequestSchema;
28
+ try {
29
+ const sdk = await import('@modelcontextprotocol/sdk/server/index.js');
30
+ Server = sdk.Server;
31
+ const transport = await import('@modelcontextprotocol/sdk/server/stdio.js');
32
+ StdioServerTransport = transport.StdioServerTransport;
33
+ const types = await import('@modelcontextprotocol/sdk/types.js');
34
+ ListToolsRequestSchema = types.ListToolsRequestSchema;
35
+ CallToolRequestSchema = types.CallToolRequestSchema;
36
+ } catch {
37
+ throw new ConfigError(
38
+ 'MCP server requires @modelcontextprotocol/sdk.\nInstall it with: npm install @modelcontextprotocol/sdk',
39
+ );
40
+ }
41
+
42
+ // Connect transport FIRST so the server can receive the client's
43
+ // `initialize` request while heavy modules (queries, better-sqlite3)
44
+ // are still loading. These are lazy-loaded on the first tool call
45
+ // and cached for subsequent calls.
46
+ let _queries;
47
+ let _Database;
48
+
49
+ async function getQueries() {
50
+ if (!_queries) {
51
+ _queries = await import('../queries.js');
52
+ }
53
+ return _queries;
54
+ }
55
+
56
+ function getDatabase() {
57
+ if (!_Database) {
58
+ const require = createRequire(import.meta.url);
59
+ _Database = require('better-sqlite3');
60
+ }
61
+ return _Database;
62
+ }
63
+
64
+ const server = new Server(
65
+ { name: 'codegraph', version: '1.0.0' },
66
+ { capabilities: { tools: {} } },
67
+ );
68
+
69
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
70
+ tools: buildToolList(multiRepo),
71
+ }));
72
+
73
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
74
+ const { name, arguments: args } = request.params;
75
+ try {
76
+ if (!multiRepo && args.repo) {
77
+ throw new ConfigError(
78
+ 'Multi-repo access is disabled. Restart with `codegraph mcp --multi-repo` to access other repositories.',
79
+ );
80
+ }
81
+ if (!multiRepo && name === 'list_repos') {
82
+ throw new ConfigError(
83
+ 'Multi-repo access is disabled. Restart with `codegraph mcp --multi-repo` to list repositories.',
84
+ );
85
+ }
86
+
87
+ let dbPath = customDbPath || undefined;
88
+ if (args.repo) {
89
+ if (allowedRepos && !allowedRepos.includes(args.repo)) {
90
+ throw new ConfigError(`Repository "${args.repo}" is not in the allowed repos list.`);
91
+ }
92
+ const { resolveRepoDbPath } = await import('../registry.js');
93
+ const resolved = resolveRepoDbPath(args.repo);
94
+ if (!resolved)
95
+ throw new ConfigError(
96
+ `Repository "${args.repo}" not found in registry or its database is missing.`,
97
+ );
98
+ dbPath = resolved;
99
+ }
100
+
101
+ const toolEntry = TOOL_HANDLERS.get(name);
102
+ if (!toolEntry) {
103
+ return { content: [{ type: 'text', text: `Unknown tool: ${name}` }], isError: true };
104
+ }
105
+
106
+ const ctx = {
107
+ dbPath,
108
+ getQueries,
109
+ getDatabase,
110
+ findDbPath,
111
+ allowedRepos,
112
+ MCP_MAX_LIMIT,
113
+ };
114
+
115
+ const result = await toolEntry.handler(args, ctx);
116
+ if (result?.content) return result; // pass-through MCP responses
117
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
118
+ } catch (err) {
119
+ const code = err instanceof CodegraphError ? err.code : 'UNKNOWN_ERROR';
120
+ const text =
121
+ err instanceof CodegraphError ? `[${code}] ${err.message}` : `Error: ${err.message}`;
122
+ return { content: [{ type: 'text', text }], isError: true };
123
+ }
124
+ });
125
+
126
+ const transport = new StdioServerTransport();
127
+ await server.connect(transport);
128
+ }