akbo-cli 0.0.0-stage → 2.0.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 (70) hide show
  1. package/README.md +786 -2
  2. package/dist/catalog_store.d.ts +131 -0
  3. package/dist/catalog_store.js +506 -0
  4. package/dist/cleaner.d.ts +11 -0
  5. package/dist/cleaner.js +92 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.js +1961 -0
  8. package/dist/dream_engine.d.ts +61 -0
  9. package/dist/dream_engine.js +330 -0
  10. package/dist/extractors/base.d.ts +35 -0
  11. package/dist/extractors/base.js +17 -0
  12. package/dist/extractors/custom_extractor.d.ts +55 -0
  13. package/dist/extractors/custom_extractor.js +198 -0
  14. package/dist/extractors/dotnet_extractor.d.ts +11 -0
  15. package/dist/extractors/dotnet_extractor.js +579 -0
  16. package/dist/extractors/golang_extractor.d.ts +11 -0
  17. package/dist/extractors/golang_extractor.js +73 -0
  18. package/dist/extractors/index.d.ts +14 -0
  19. package/dist/extractors/index.js +30 -0
  20. package/dist/extractors/jvm_extractor.d.ts +11 -0
  21. package/dist/extractors/jvm_extractor.js +319 -0
  22. package/dist/extractors/node_extractor.d.ts +11 -0
  23. package/dist/extractors/node_extractor.js +306 -0
  24. package/dist/extractors/proto_graphql_extractor.d.ts +11 -0
  25. package/dist/extractors/proto_graphql_extractor.js +125 -0
  26. package/dist/extractors/python_extractor.d.ts +11 -0
  27. package/dist/extractors/python_extractor.js +298 -0
  28. package/dist/extractors/rust_extractor.d.ts +11 -0
  29. package/dist/extractors/rust_extractor.js +66 -0
  30. package/dist/graph_builder.d.ts +87 -0
  31. package/dist/graph_builder.js +1516 -0
  32. package/dist/guard_service.d.ts +33 -0
  33. package/dist/guard_service.js +167 -0
  34. package/dist/harvester.d.ts +38 -0
  35. package/dist/harvester.js +461 -0
  36. package/dist/hook_generator.d.ts +34 -0
  37. package/dist/hook_generator.js +269 -0
  38. package/dist/importers/skill_importer.d.ts +43 -0
  39. package/dist/importers/skill_importer.js +470 -0
  40. package/dist/index.d.ts +20 -0
  41. package/dist/index.js +20 -0
  42. package/dist/indexer.d.ts +19 -0
  43. package/dist/indexer.js +108 -0
  44. package/dist/init_service.d.ts +37 -0
  45. package/dist/init_service.js +246 -0
  46. package/dist/mcp_server.d.ts +10 -0
  47. package/dist/mcp_server.js +846 -0
  48. package/dist/pool_resolver.d.ts +40 -0
  49. package/dist/pool_resolver.js +84 -0
  50. package/dist/provider.d.ts +135 -0
  51. package/dist/provider.js +880 -0
  52. package/dist/query_service.d.ts +33 -0
  53. package/dist/query_service.js +161 -0
  54. package/dist/schema_generator.d.ts +236 -0
  55. package/dist/schema_generator.js +264 -0
  56. package/dist/standards_loader.d.ts +7 -0
  57. package/dist/standards_loader.js +33 -0
  58. package/dist/types.d.ts +323 -0
  59. package/dist/types.js +123 -0
  60. package/dist/unit_synthesizer.d.ts +22 -0
  61. package/dist/unit_synthesizer.js +196 -0
  62. package/dist/validator.d.ts +13 -0
  63. package/dist/validator.js +152 -0
  64. package/dist/version.d.ts +6 -0
  65. package/dist/version.js +16 -0
  66. package/dist/watcher.d.ts +38 -0
  67. package/dist/watcher.js +132 -0
  68. package/package.json +56 -6
  69. package/schemas/index-schema.json +98 -0
  70. package/schemas/knowledge-unit.json +154 -0
@@ -0,0 +1,846 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
+ import { z } from 'zod';
4
+ import path from 'node:path';
5
+ import fs from 'node:fs';
6
+ import vm from 'node:vm';
7
+ import { Harvester } from './harvester.js';
8
+ import { GraphBuilder } from './graph_builder.js';
9
+ import { KnowledgeValidator } from './validator.js';
10
+ import { QueryService } from './query_service.js';
11
+ import { SkillImporter } from './importers/skill_importer.js';
12
+ import { KnowledgePoolResolver } from './pool_resolver.js';
13
+ import { CatalogStore } from './catalog_store.js';
14
+ import { DreamEngine } from './dream_engine.js';
15
+ import { GuardService } from './guard_service.js';
16
+ import { VERSION } from './version.js';
17
+ export function createMcpServer(repoRoot = process.cwd(), poolDirOrConfig) {
18
+ const root = path.resolve(repoRoot);
19
+ let config;
20
+ if (typeof poolDirOrConfig === 'string') {
21
+ config = { poolDir: poolDirOrConfig };
22
+ }
23
+ else {
24
+ config = poolDirOrConfig || {};
25
+ }
26
+ if (config.poolDir) {
27
+ process.env.AKBO_POOL_DIR = config.poolDir;
28
+ }
29
+ // Parse disabled tools from config and environment variable
30
+ const envDisabled = process.env.AKBO_DISABLE_TOOLS
31
+ ? process.env.AKBO_DISABLE_TOOLS.split(',').map(s => s.trim().toLowerCase())
32
+ : [];
33
+ const configuredDisabled = (config.disableTools || []).map(s => s.trim().toLowerCase());
34
+ const disabledTools = new Set([...configuredDisabled, ...envDisabled]);
35
+ const zeroTokenOnly = config.zeroTokenOnly ||
36
+ process.env.AKBO_ZERO_TOKEN_ONLY === '1' ||
37
+ process.env.AKBO_ZERO_TOKEN_ONLY === 'true';
38
+ if (zeroTokenOnly) {
39
+ disabledTools.add('akbo_query');
40
+ }
41
+ const disallowRootScan = config.disallowRootScan ||
42
+ process.env.AKBO_DISALLOW_ROOT_SCAN === '1' ||
43
+ process.env.AKBO_DISALLOW_ROOT_SCAN === 'true';
44
+ const envDisallowedDirs = process.env.AKBO_DISALLOW_DIRS
45
+ ? process.env.AKBO_DISALLOW_DIRS.split(',').map(s => s.trim())
46
+ : [];
47
+ const disallowedDirs = [...(config.disallowedDirs || []), ...envDisallowedDirs];
48
+ function checkScanAllowed(targetDir) {
49
+ const normTarget = path.resolve(targetDir).replace(/\\/g, '/').toLowerCase();
50
+ const normRoot = path.resolve(root).replace(/\\/g, '/').toLowerCase();
51
+ if (disallowRootScan && normTarget === normRoot) {
52
+ return `Root scan is disallowed by --disallow-root-scan / AKBO_DISALLOW_ROOT_SCAN. Target directory cannot be the root repository: ${root}`;
53
+ }
54
+ if (disallowedDirs.length > 0) {
55
+ for (const d of disallowedDirs) {
56
+ const normD = path.resolve(d).replace(/\\/g, '/').toLowerCase();
57
+ if (normTarget === normD) {
58
+ return `Scanning directory "${targetDir}" is disallowed by configuration (AKBO_DISALLOW_DIRS).`;
59
+ }
60
+ }
61
+ }
62
+ return null;
63
+ }
64
+ const server = new McpServer({
65
+ name: 'akbo',
66
+ version: VERSION
67
+ });
68
+ // Tool 1: akbo_context
69
+ if (!disabledTools.has('akbo_context')) {
70
+ server.tool('akbo_context', 'Extract 0-token topological neighborhood (1-2 hops) & active invariants for an entity, class, file, or endpoint before code generation', {
71
+ target: z.string().describe('Target file, endpoint, class, validator, or message name (e.g. "InvoicesController.cs", "CreateInvoiceValidator")'),
72
+ hops: z.number().optional().default(2).describe('Maximum traversal hops (1 or 2, default: 2)'),
73
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
74
+ pool: z.string().optional().describe('External knowledge base pool directory')
75
+ }, async ({ target, hops = 2, dir, pool }) => {
76
+ const targetDir = path.resolve(dir || root);
77
+ const scanError = checkScanAllowed(targetDir);
78
+ if (scanError) {
79
+ return { content: [{ type: 'text', text: scanError }], isError: true };
80
+ }
81
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
82
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
83
+ const skeleton = await harvester.harvest({ useCache: true });
84
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
85
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: true });
86
+ const neighborhood = graphBuilder.extractNeighborhood(graph, target, hops);
87
+ if (!neighborhood) {
88
+ return {
89
+ content: [
90
+ {
91
+ type: 'text',
92
+ text: `No graph entity matching "${target}" was found in the codebase graph.`
93
+ }
94
+ ]
95
+ };
96
+ }
97
+ return {
98
+ content: [
99
+ {
100
+ type: 'text',
101
+ text: neighborhood.formattedContext
102
+ }
103
+ ]
104
+ };
105
+ });
106
+ }
107
+ // Tool 2: akbo_query
108
+ if (!disabledTools.has('akbo_query')) {
109
+ server.tool('akbo_query', 'Execute a GraphRAG query: Answer questions strictly grounded in the Codebase Knowledge Graph with cross-lingual seed resolution and zero hallucinations', {
110
+ prompt: z.string().describe('Architectural question or inquiry about the codebase'),
111
+ provider: z.enum(['gemini', 'openai', 'anthropic', 'deepseek', 'groq', 'ollama', 'agy', 'cli'])
112
+ .optional()
113
+ .describe('Execution provider (default: AKB_PROVIDER or "agy")'),
114
+ model: z.string().optional().describe('Model override (e.g. gemini-3.5-flash)'),
115
+ forceCli: z.boolean().optional().describe('Use system Gemini CLI instead of direct API call'),
116
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
117
+ pool: z.string().optional().describe('External knowledge base pool directory')
118
+ }, async ({ prompt, provider, model, forceCli, dir, pool }) => {
119
+ const targetDir = path.resolve(dir || root);
120
+ const scanError = checkScanAllowed(targetDir);
121
+ if (scanError) {
122
+ return { content: [{ type: 'text', text: scanError }], isError: true };
123
+ }
124
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
125
+ const chosenProvider = provider || process.env.AKB_PROVIDER || 'agy';
126
+ // Guard against recursive agent execution if running inside an Antigravity/agent session
127
+ if ((chosenProvider === 'agy' || chosenProvider === 'cli') && process.env.AKBO_NESTED_AGENT === '1') {
128
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
129
+ const skeleton = await harvester.harvest({ useCache: true });
130
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
131
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: true });
132
+ const neighborhood = graphBuilder.extractNeighborhood(graph, prompt);
133
+ return {
134
+ content: [
135
+ {
136
+ type: 'text',
137
+ text: JSON.stringify({
138
+ provider: 'direct_graph_slice (nested agent recursion prevented)',
139
+ answer: 'Nested autonomous agent detected (AKBO_NESTED_AGENT=1). Returning grounded architectural context slice directly to avoid recursive agent execution.',
140
+ context: neighborhood?.formattedContext || 'No direct entity match in CKG.',
141
+ keyEntities: neighborhood?.nodes.map(n => n.label) || [],
142
+ activeRules: (neighborhood?.activeInvariants || []).map(i => i.rule)
143
+ }, null, 2)
144
+ }
145
+ ]
146
+ };
147
+ }
148
+ const queryService = new QueryService(targetDir, poolConfig.poolDir);
149
+ const result = await queryService.query(prompt, {
150
+ dir: targetDir,
151
+ poolDir: poolConfig.poolDir,
152
+ model,
153
+ forceCli,
154
+ providerName: chosenProvider
155
+ });
156
+ const responsePayload = {
157
+ provider: chosenProvider,
158
+ answer: result.answer,
159
+ keyEntities: result.keyEntities,
160
+ activeRules: result.activeRules
161
+ };
162
+ return {
163
+ content: [
164
+ {
165
+ type: 'text',
166
+ text: JSON.stringify(responsePayload, null, 2)
167
+ }
168
+ ]
169
+ };
170
+ });
171
+ }
172
+ // Tool 3: akbo_harvest
173
+ if (!disabledTools.has('akbo_harvest')) {
174
+ server.tool('akbo_harvest', 'Deterministically scan codebase topology, manifests, schemas, endpoints, and validation rules (0 LLM tokens)', {
175
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
176
+ pool: z.string().optional().describe('External knowledge base pool directory'),
177
+ useCache: z.boolean().optional().default(true).describe('Use cached skeleton if codebase is unchanged'),
178
+ summaryOnly: z.boolean().optional().default(true).describe('Return concise summary of topology, manifests, schemas, and routes instead of full skeleton JSON (default: true)')
179
+ }, async ({ dir, pool, useCache = true, summaryOnly = true }) => {
180
+ const targetDir = path.resolve(dir || root);
181
+ const scanError = checkScanAllowed(targetDir);
182
+ if (scanError) {
183
+ return { content: [{ type: 'text', text: scanError }], isError: true };
184
+ }
185
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
186
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
187
+ const skeleton = await harvester.harvest({ useCache });
188
+ let outputText;
189
+ if (summaryOnly) {
190
+ const summary = {
191
+ targetDir,
192
+ topology: skeleton.topology,
193
+ manifestsCount: skeleton.manifests.length,
194
+ manifests: skeleton.manifests.map(m => ({ type: m.type, path: m.path, name: m.contentSummary?.name })),
195
+ schemasCount: skeleton.schemas.length,
196
+ schemas: skeleton.schemas.map(s => ({ type: s.type, file: s.file, tablesOrModels: s.tablesOrModels })),
197
+ routesCount: skeleton.routesAndCommands.length,
198
+ sampleRoutes: skeleton.routesAndCommands.slice(0, 20),
199
+ cacheFile: poolConfig.cacheFile
200
+ };
201
+ outputText = JSON.stringify(summary, null, 2);
202
+ }
203
+ else {
204
+ outputText = JSON.stringify(skeleton, null, 2);
205
+ }
206
+ return {
207
+ content: [
208
+ {
209
+ type: 'text',
210
+ text: outputText
211
+ }
212
+ ]
213
+ };
214
+ });
215
+ }
216
+ // Tool 4: akbo_validate
217
+ if (!disabledTools.has('akbo_validate')) {
218
+ server.tool('akbo_validate', 'Validate knowledge/ directory against the AKB runtime schema and federation standards', {
219
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
220
+ pool: z.string().optional().describe('External knowledge base pool directory')
221
+ }, async ({ dir, pool }) => {
222
+ const targetDir = path.resolve(dir || root);
223
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
224
+ const validator = new KnowledgeValidator(targetDir, poolConfig.poolDir);
225
+ const result = await validator.validate();
226
+ return {
227
+ content: [
228
+ {
229
+ type: 'text',
230
+ text: JSON.stringify(result, null, 2)
231
+ }
232
+ ]
233
+ };
234
+ });
235
+ }
236
+ // Tool 5: akbo_graph
237
+ if (!disabledTools.has('akbo_graph')) {
238
+ server.tool('akbo_graph', 'Deterministically build the Codebase Knowledge Graph (CKG) linking projects, endpoints, handlers, messages, schemas, validators, and invariants (0 tokens)', {
239
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
240
+ pool: z.string().optional().describe('External knowledge base pool directory'),
241
+ format: z.enum(['json', 'mermaid', 'markdown']).optional().default('json').describe('Export format: json, mermaid, markdown'),
242
+ clustered: z.boolean().optional().default(true).describe('Group nodes by domain subgraphs in Mermaid format (default: true)'),
243
+ nodeTypes: z.array(z.string()).optional().describe('Filter by node types (e.g. ["project", "endpoint", "handler"])'),
244
+ domain: z.string().optional().describe('Filter by architectural domain'),
245
+ maxNodes: z.number().optional().default(100).describe('Maximum nodes to return (default: 100)'),
246
+ useCache: z.boolean().optional().default(true).describe('Use cached skeleton if codebase is unchanged')
247
+ }, async ({ dir, pool, format = 'json', clustered = true, nodeTypes, domain, maxNodes = 100, useCache = true }) => {
248
+ const targetDir = path.resolve(dir || root);
249
+ const scanError = checkScanAllowed(targetDir);
250
+ if (scanError) {
251
+ return { content: [{ type: 'text', text: scanError }], isError: true };
252
+ }
253
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
254
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
255
+ const skeleton = await harvester.harvest({ useCache });
256
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
257
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache });
258
+ let filteredNodes = graph.nodes;
259
+ if (nodeTypes && nodeTypes.length > 0) {
260
+ filteredNodes = filteredNodes.filter(n => nodeTypes.includes(n.type));
261
+ }
262
+ if (domain) {
263
+ const dLower = domain.toLowerCase();
264
+ filteredNodes = filteredNodes.filter(n => n.domain?.toLowerCase() === dLower);
265
+ }
266
+ const truncatedNodes = filteredNodes.slice(0, maxNodes);
267
+ const allowedNodeIds = new Set(truncatedNodes.map(n => n.id));
268
+ const filteredEdges = graph.edges.filter(e => allowedNodeIds.has(e.source) && allowedNodeIds.has(e.target));
269
+ const processedGraph = {
270
+ ...graph,
271
+ nodes: truncatedNodes,
272
+ edges: filteredEdges
273
+ };
274
+ let output = '';
275
+ if (format === 'mermaid') {
276
+ output = graphBuilder.exportMermaid(processedGraph, { clustered });
277
+ }
278
+ else if (format === 'markdown') {
279
+ output = `# Codebase Knowledge Graph\n\nTotal Entities: ${processedGraph.nodes.length} (of ${graph.nodes.length}) | Relationships: ${processedGraph.edges.length}\n\n\`\`\`mermaid\n${graphBuilder.exportMermaid(processedGraph, { clustered })}\n\`\`\`\n`;
280
+ }
281
+ else {
282
+ output = JSON.stringify({
283
+ totalGraphNodes: graph.nodes.length,
284
+ returnedNodes: processedGraph.nodes.length,
285
+ nodes: processedGraph.nodes,
286
+ edges: processedGraph.edges
287
+ }, null, 2);
288
+ }
289
+ return {
290
+ content: [
291
+ {
292
+ type: 'text',
293
+ text: output
294
+ }
295
+ ]
296
+ };
297
+ });
298
+ }
299
+ // Tool 6: akbo_list_invariants
300
+ if (!disabledTools.has('akbo_list_invariants')) {
301
+ server.tool('akbo_list_invariants', 'Retrieve architectural invariants and compliance rules from knowledge units, optionally filtered by target file, domain, or search query (0 LLM tokens)', {
302
+ file: z.string().optional().describe('Target file path to find applicable invariants for (matches applies_to patterns)'),
303
+ domain: z.string().optional().describe('Domain or category filter (e.g. "architecture", "development", "product", "decisions")'),
304
+ query: z.string().optional().describe('Substring or keyword search across rule, title, id, reason, do, dont'),
305
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
306
+ pool: z.string().optional().describe('External knowledge base pool directory')
307
+ }, async ({ file, domain, query, dir, pool }) => {
308
+ const targetDir = path.resolve(dir || root);
309
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
310
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
311
+ const units = graphBuilder.loadKnowledgeUnits();
312
+ let filtered = units;
313
+ if (domain) {
314
+ const dLower = domain.toLowerCase();
315
+ filtered = filtered.filter(u => (u.domain && u.domain.toLowerCase() === dLower) ||
316
+ (u.id && u.id.toLowerCase().startsWith(dLower)));
317
+ }
318
+ if (file) {
319
+ filtered = filtered.filter(u => graphBuilder.matchesAppliesTo(u, file));
320
+ }
321
+ if (query) {
322
+ const qLower = query.toLowerCase().trim();
323
+ filtered = filtered.filter(u => {
324
+ const matchId = u.id && u.id.toLowerCase().includes(qLower);
325
+ const matchTitle = u.title && u.title.toLowerCase().includes(qLower);
326
+ const matchRule = u.rule && u.rule.toLowerCase().includes(qLower);
327
+ const matchReason = u.reason && u.reason.toLowerCase().includes(qLower);
328
+ const matchDo = Array.isArray(u.do) && u.do.some(d => d.toLowerCase().includes(qLower));
329
+ const matchDont = Array.isArray(u.dont) && u.dont.some(d => d.toLowerCase().includes(qLower));
330
+ const matchApplies = Array.isArray(u.applies_to) && u.applies_to.some(a => a.toLowerCase().includes(qLower));
331
+ return matchId || matchTitle || matchRule || matchReason || matchDo || matchDont || matchApplies;
332
+ });
333
+ }
334
+ const output = filtered.map(u => ({
335
+ id: u.id,
336
+ type: u.type,
337
+ status: u.status,
338
+ title: u.title,
339
+ domain: u.domain || 'general',
340
+ rule: u.rule,
341
+ reason: u.reason,
342
+ applies_to: u.applies_to || [],
343
+ do: u.do || [],
344
+ dont: u.dont || [],
345
+ related_items: u.related_items || [],
346
+ authority: u.authority,
347
+ skill_file: u.skill_file,
348
+ reference_files: u.reference_files,
349
+ workflow_gates: u.workflow_gates
350
+ }));
351
+ return {
352
+ content: [
353
+ {
354
+ type: 'text',
355
+ text: JSON.stringify(output, null, 2)
356
+ }
357
+ ]
358
+ };
359
+ });
360
+ }
361
+ // Tool 7: akbo_search (0-Token Entity & Symbol Search)
362
+ if (!disabledTools.has('akbo_search')) {
363
+ server.tool('akbo_search', 'Fast, zero-token in-memory entity search across symbols, endpoints, handlers, schemas, projects, and invariants in <5ms without calling an LLM', {
364
+ query: z.string().describe('Search query (class name, endpoint route, symbol, or file path)'),
365
+ type: z.enum(['all', 'project', 'endpoint', 'handler', 'schema', 'message', 'invariant']).optional().default('all'),
366
+ domain: z.string().optional().describe('Filter by architectural domain'),
367
+ limit: z.number().optional().default(20).describe('Maximum results to return (default 20)'),
368
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
369
+ pool: z.string().optional().describe('External knowledge base pool directory')
370
+ }, async ({ query, type = 'all', domain, limit = 20, dir, pool }) => {
371
+ const targetDir = path.resolve(dir || root);
372
+ const scanError = checkScanAllowed(targetDir);
373
+ if (scanError) {
374
+ return { content: [{ type: 'text', text: scanError }], isError: true };
375
+ }
376
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
377
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
378
+ const skeleton = await harvester.harvest({ useCache: true });
379
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
380
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: true });
381
+ const results = graphBuilder.searchNodes(graph, {
382
+ query,
383
+ type,
384
+ domain,
385
+ limit
386
+ });
387
+ return {
388
+ content: [
389
+ {
390
+ type: 'text',
391
+ text: JSON.stringify(results, null, 2)
392
+ }
393
+ ]
394
+ };
395
+ });
396
+ }
397
+ // Tool 8: akbo_impact (Blast-Radius & Inbound Dependents)
398
+ if (!disabledTools.has('akbo_impact')) {
399
+ server.tool('akbo_impact', 'Calculate directional blast radius and inbound callers/dependents for a target symbol, endpoint, or project before editing code', {
400
+ target: z.string().describe('Target node ID, symbol name, project name, or file to evaluate impact for'),
401
+ maxDepth: z.number().optional().default(3).describe('Maximum traversal depth along inbound edges (default 3)'),
402
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
403
+ pool: z.string().optional().describe('External knowledge base pool directory')
404
+ }, async ({ target, maxDepth = 3, dir, pool }) => {
405
+ const targetDir = path.resolve(dir || root);
406
+ const scanError = checkScanAllowed(targetDir);
407
+ if (scanError) {
408
+ return { content: [{ type: 'text', text: scanError }], isError: true };
409
+ }
410
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
411
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
412
+ const skeleton = await harvester.harvest({ useCache: true });
413
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
414
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: true });
415
+ const impact = graphBuilder.calculateInboundImpact(graph, target, { maxDepth });
416
+ return {
417
+ content: [
418
+ {
419
+ type: 'text',
420
+ text: JSON.stringify(impact, null, 2)
421
+ }
422
+ ]
423
+ };
424
+ });
425
+ }
426
+ // Tool 8b: akbo_filter (In-Memory Sandboxed Graph Projection & Filtering)
427
+ if (!disabledTools.has('akbo_filter')) {
428
+ server.tool('akbo_filter', 'Execute a fast, in-memory sandboxed JavaScript projection or filter against CKG nodes, edges, or invariants without flooding the context window', {
429
+ target: z.enum(['nodes', 'edges', 'invariants']).describe('Dataset to filter: nodes, edges, or invariants'),
430
+ predicate: z.string().describe('JavaScript predicate expression evaluated per item (variable is item, n, e, or inv), e.g. "n.type === \'endpoint\' && n.domain === \'billing\'"'),
431
+ fields: z.array(z.string()).optional().describe('Optional list of properties to project in the output, e.g. ["id", "label", "file"]'),
432
+ limit: z.number().optional().default(50).describe('Maximum items to return (default: 50, max: 500)'),
433
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
434
+ pool: z.string().optional().describe('External knowledge base pool directory')
435
+ }, async ({ target, predicate, fields, limit = 50, dir, pool }) => {
436
+ const targetDir = path.resolve(dir || root);
437
+ const scanError = checkScanAllowed(targetDir);
438
+ if (scanError) {
439
+ return { content: [{ type: 'text', text: scanError }], isError: true };
440
+ }
441
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
442
+ let dataset = [];
443
+ if (target === 'invariants') {
444
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
445
+ dataset = graphBuilder.loadKnowledgeUnits();
446
+ }
447
+ else {
448
+ const harvester = new Harvester(targetDir, undefined, poolConfig.poolDir);
449
+ const skeleton = await harvester.harvest({ useCache: true });
450
+ const graphBuilder = new GraphBuilder(targetDir, poolConfig.poolDir);
451
+ const graph = await graphBuilder.buildGraph(skeleton, undefined, { useCache: true });
452
+ dataset = target === 'nodes' ? graph.nodes : graph.edges;
453
+ }
454
+ const safeLimit = Math.min(Math.max(1, limit), 500);
455
+ const cleanPred = predicate.trim();
456
+ const fnCode = cleanPred.startsWith('(') || cleanPred.startsWith('function')
457
+ ? `(${cleanPred})`
458
+ : `(function(item) { var n = item, e = item, inv = item; return Boolean(${cleanPred}); })`;
459
+ let filterFn;
460
+ try {
461
+ const sandbox = Object.create(null);
462
+ const script = new vm.Script(fnCode);
463
+ filterFn = script.runInNewContext(sandbox, { timeout: 200 });
464
+ }
465
+ catch (err) {
466
+ return {
467
+ content: [{ type: 'text', text: `Invalid filter predicate: ${err.message}` }],
468
+ isError: true
469
+ };
470
+ }
471
+ const matches = [];
472
+ let totalMatched = 0;
473
+ for (const item of dataset) {
474
+ let matched = false;
475
+ try {
476
+ matched = Boolean(filterFn(item));
477
+ }
478
+ catch {
479
+ matched = false;
480
+ }
481
+ if (matched) {
482
+ totalMatched++;
483
+ if (matches.length < safeLimit) {
484
+ if (fields && fields.length > 0) {
485
+ const projected = {};
486
+ for (const f of fields) {
487
+ if (item[f] !== undefined) {
488
+ projected[f] = item[f];
489
+ }
490
+ }
491
+ matches.push(projected);
492
+ }
493
+ else {
494
+ matches.push(item);
495
+ }
496
+ }
497
+ }
498
+ }
499
+ const payload = {
500
+ target,
501
+ totalDatasetSize: dataset.length,
502
+ totalMatched,
503
+ returnedCount: matches.length,
504
+ truncated: totalMatched > matches.length,
505
+ results: matches
506
+ };
507
+ return {
508
+ content: [
509
+ {
510
+ type: 'text',
511
+ text: JSON.stringify(payload, null, 2)
512
+ }
513
+ ]
514
+ };
515
+ });
516
+ }
517
+ // Tool 8c: akbo_record_observation (Runtime Observation Logging for Compounding Memory)
518
+ if (!disabledTools.has('akbo_record_observation')) {
519
+ server.tool('akbo_record_observation', 'Record an ephemeral runtime finding, bug workaround, or convention discovered during task execution for offline consolidation ("Dreaming")', {
520
+ topic: z.string().describe('Target subsystem, endpoint, file, or library'),
521
+ finding: z.string().describe('The discovered insight, trap, or bug workaround'),
522
+ reproducible_fix: z.string().optional().describe('Actionable do/dont solution or pattern to adhere to'),
523
+ associated_files: z.array(z.string()).optional().describe('Relevant file paths involved in this finding'),
524
+ agent_id: z.string().optional().describe('Identifier or role of the reporting agent (e.g. "gemini-refactor", "claude-debugger")'),
525
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
526
+ pool: z.string().optional().describe('External knowledge base pool directory')
527
+ }, async ({ topic, finding, reproducible_fix, associated_files, agent_id, dir, pool }) => {
528
+ const targetDir = path.resolve(dir || root);
529
+ const obs = CatalogStore.recordObservation({
530
+ targetDir,
531
+ poolDir: pool,
532
+ agentId: agent_id,
533
+ topic,
534
+ finding,
535
+ reproducible_fix,
536
+ associated_files
537
+ });
538
+ return {
539
+ content: [
540
+ {
541
+ type: 'text',
542
+ text: `Observation recorded successfully [ID: ${obs.id}] in session "${obs.agentId}". It will be consolidated during offline dreaming.`
543
+ }
544
+ ]
545
+ };
546
+ });
547
+ }
548
+ // Tool 8d: akbo_scratchpad (Multi-Agent Isolated Session Scratchpad)
549
+ if (!disabledTools.has('akbo_scratchpad')) {
550
+ server.tool('akbo_scratchpad', 'Read or write an isolated session scratchpad (.akb/sessions/<agent_id>/scratchpad.md) to store working notes without write collisions or long-term repo pollution', {
551
+ action: z.enum(['get', 'set', 'append']).describe('Action: get current notes, set/overwrite, or append notes'),
552
+ content: z.string().optional().describe('Markdown content to set or append'),
553
+ agent_id: z.string().optional().describe('Identifier or role of the agent (default: "default")'),
554
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
555
+ pool: z.string().optional().describe('External knowledge base pool directory')
556
+ }, async ({ action, content, agent_id, dir, pool }) => {
557
+ const targetDir = path.resolve(dir || root);
558
+ if (action === 'get') {
559
+ const notes = CatalogStore.getScratchpad({ targetDir, poolDir: pool, agentId: agent_id });
560
+ return {
561
+ content: [{ type: 'text', text: notes || '(Scratchpad is empty)' }]
562
+ };
563
+ }
564
+ else {
565
+ if (!content) {
566
+ return { content: [{ type: 'text', text: 'Error: content is required for set/append actions' }], isError: true };
567
+ }
568
+ const updated = CatalogStore.updateScratchpad({
569
+ targetDir,
570
+ poolDir: pool,
571
+ agentId: agent_id,
572
+ content,
573
+ append: action === 'append'
574
+ });
575
+ return {
576
+ content: [{ type: 'text', text: `Scratchpad updated for agent "${agent_id || 'default'}". Current length: ${updated.length} chars.` }]
577
+ };
578
+ }
579
+ });
580
+ }
581
+ // Tool 8e: akbo_dream (Run Out-of-Band Memory Consolidation)
582
+ if (!disabledTools.has('akbo_dream')) {
583
+ server.tool('akbo_dream', 'Run out-of-band memory consolidation ("Dreaming") to process session observations and synthesize durable compounding knowledge units or staged proposals', {
584
+ sinceHours: z.number().optional().describe('Filter observations recorded within the last N hours'),
585
+ stageOnly: z.boolean().optional().default(false).describe('If true, stage proposals in .akb/staged/ without directly updating knowledge/index.yaml'),
586
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
587
+ pool: z.string().optional().describe('External knowledge base pool directory')
588
+ }, async ({ sinceHours, stageOnly = false, dir, pool }) => {
589
+ const targetDir = path.resolve(dir || root);
590
+ const scanError = checkScanAllowed(targetDir);
591
+ if (scanError) {
592
+ return { content: [{ type: 'text', text: scanError }], isError: true };
593
+ }
594
+ const dreamEngine = new DreamEngine(targetDir, pool);
595
+ const result = await dreamEngine.dream({
596
+ targetDir,
597
+ poolDir: pool,
598
+ sinceHours,
599
+ stageOnly,
600
+ autoApprove: !stageOnly
601
+ });
602
+ return {
603
+ content: [
604
+ {
605
+ type: 'text',
606
+ text: JSON.stringify(result, null, 2)
607
+ }
608
+ ]
609
+ };
610
+ });
611
+ }
612
+ // Tool 8f: akbo_guard (Active Runtime Guardrail & Invariant Pre-Tool Interceptor)
613
+ if (!disabledTools.has('akbo_guard')) {
614
+ server.tool('akbo_guard', 'Evaluate proposed code changes, snippets, or diffs against active invariants and standards before editing files (pre-tool execution rail)', {
615
+ file: z.string().describe('Target file path to evaluate against active invariants'),
616
+ content: z.string().describe('Proposed code content, new snippet, or diff string'),
617
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
618
+ pool: z.string().optional().describe('External knowledge base pool directory')
619
+ }, async ({ file, content, dir, pool }) => {
620
+ const targetDir = path.resolve(dir || root);
621
+ const scanError = checkScanAllowed(targetDir);
622
+ if (scanError) {
623
+ return { content: [{ type: 'text', text: scanError }], isError: true };
624
+ }
625
+ const guardService = new GuardService(targetDir, pool);
626
+ const evalResult = guardService.evaluate(file, content);
627
+ return {
628
+ content: [
629
+ {
630
+ type: 'text',
631
+ text: JSON.stringify(evalResult, null, 2)
632
+ }
633
+ ]
634
+ };
635
+ });
636
+ }
637
+ // Tool 9: akbo_upsert_unit (Write or Update Knowledge Unit)
638
+ if (!disabledTools.has('akbo_upsert_unit')) {
639
+ server.tool('akbo_upsert_unit', 'Add or update knowledge standards or decisions in the external pool. Supports single unit or batch array, validates schema, writes YAML, and updates index.yaml', {
640
+ id: z.string().optional().describe('Unique rule ID (e.g. no-direct-db-in-controllers)'),
641
+ domain: z.string().optional().describe('Architectural domain (e.g. architecture, development, decisions)'),
642
+ title: z.string().optional().describe('Summary title of the standard'),
643
+ applies_to: z.array(z.string()).optional().describe('Glob patterns matching applicable files'),
644
+ rule: z.string().optional().describe('Rule directive statement'),
645
+ do: z.array(z.string()).optional().describe('Required or recommended practices'),
646
+ dont: z.array(z.string()).optional().describe('Forbidden practices'),
647
+ reason: z.string().optional().describe('Architectural reasoning or risk explanation'),
648
+ decision: z.string().optional().describe('Architecture decision statement (for architecture_decision)'),
649
+ context: z.string().optional().describe('Context and problem statement (for architecture_decision)'),
650
+ type: z.string().optional().describe('Unit type (development_standard, architecture_standard, architecture_decision, product_rule)'),
651
+ status: z.string().optional().describe('Approval status (approved, draft, deprecated)'),
652
+ severity: z.enum(['error', 'warning', 'info']).optional().default('warning'),
653
+ authority: z.object({ level: z.string(), confidence: z.string() }).optional().describe('Authority level (default: human_curated)'),
654
+ units: z.array(z.record(z.string(), z.any())).optional().describe('Array of unit objects for atomic batch upsert'),
655
+ validate: z.boolean().optional().default(true).describe('Run KnowledgeValidator after upserting (default: true)'),
656
+ dir: z.string().optional().describe('Codebase directory'),
657
+ pool: z.string().optional().describe('External knowledge base pool directory')
658
+ }, async (args) => {
659
+ const targetDir = path.resolve(args.dir || root);
660
+ let unitsToUpsert = [];
661
+ if (args.units && Array.isArray(args.units) && args.units.length > 0) {
662
+ unitsToUpsert = args.units;
663
+ }
664
+ else if (args.id) {
665
+ unitsToUpsert = [{
666
+ id: args.id,
667
+ type: args.type,
668
+ title: args.title,
669
+ domain: args.domain,
670
+ status: args.status,
671
+ authority: args.authority,
672
+ applies_to: args.applies_to,
673
+ rule: args.rule,
674
+ do: args.do,
675
+ dont: args.dont,
676
+ reason: args.reason,
677
+ decision: args.decision,
678
+ context: args.context
679
+ }];
680
+ }
681
+ else {
682
+ return {
683
+ content: [{ type: 'text', text: 'Either "id" or "units" must be provided to akbo_upsert_unit.' }],
684
+ isError: true
685
+ };
686
+ }
687
+ const result = await CatalogStore.upsertUnits(unitsToUpsert, {
688
+ targetDir,
689
+ poolDir: args.pool,
690
+ validate: args.validate !== false
691
+ });
692
+ if (!result.success) {
693
+ return {
694
+ content: [{ type: 'text', text: `Upsert failed: ${result.error}` }],
695
+ isError: true
696
+ };
697
+ }
698
+ return {
699
+ content: [
700
+ {
701
+ type: 'text',
702
+ text: JSON.stringify(result, null, 2)
703
+ }
704
+ ]
705
+ };
706
+ });
707
+ }
708
+ // Tool 9b: akbo_upsert_units (Explicit Batch Upsert)
709
+ if (!disabledTools.has('akbo_upsert_units') && !disabledTools.has('akbo_upsert_unit')) {
710
+ server.tool('akbo_upsert_units', 'Batch upsert multiple knowledge units atomically into the knowledge pool and return validation report', {
711
+ units: z.array(z.record(z.string(), z.any())).describe('Array of knowledge unit objects to upsert'),
712
+ validate: z.boolean().optional().default(true).describe('Run KnowledgeValidator after upserting (default: true)'),
713
+ dir: z.string().optional().describe('Codebase directory'),
714
+ pool: z.string().optional().describe('External knowledge base pool directory')
715
+ }, async ({ units, validate = true, dir, pool }) => {
716
+ const targetDir = path.resolve(dir || root);
717
+ const result = await CatalogStore.upsertUnits(units, {
718
+ targetDir,
719
+ poolDir: pool,
720
+ validate
721
+ });
722
+ if (!result.success) {
723
+ return {
724
+ content: [{ type: 'text', text: `Batch upsert failed: ${result.error}` }],
725
+ isError: true
726
+ };
727
+ }
728
+ return {
729
+ content: [
730
+ {
731
+ type: 'text',
732
+ text: JSON.stringify(result, null, 2)
733
+ }
734
+ ]
735
+ };
736
+ });
737
+ }
738
+ // Tool 9c: akbo_get_unit (Retrieve Unit by ID)
739
+ if (!disabledTools.has('akbo_get_unit')) {
740
+ server.tool('akbo_get_unit', 'Retrieve a knowledge unit YAML and metadata by its unique ID', {
741
+ id: z.string().min(1).describe('Unique rule ID to fetch'),
742
+ dir: z.string().optional().describe('Codebase directory'),
743
+ pool: z.string().optional().describe('External knowledge base pool directory')
744
+ }, async ({ id, dir, pool }) => {
745
+ const targetDir = path.resolve(dir || root);
746
+ const result = CatalogStore.getUnit(id, { targetDir, poolDir: pool });
747
+ if (!result) {
748
+ return {
749
+ content: [{ type: 'text', text: `Knowledge unit "${id}" not found.` }],
750
+ isError: true
751
+ };
752
+ }
753
+ return {
754
+ content: [
755
+ {
756
+ type: 'text',
757
+ text: JSON.stringify(result, null, 2)
758
+ }
759
+ ]
760
+ };
761
+ });
762
+ }
763
+ // Tool 9d: akbo_delete_unit (Delete Unit by ID)
764
+ if (!disabledTools.has('akbo_delete_unit')) {
765
+ server.tool('akbo_delete_unit', 'Delete a knowledge unit from the pool, remove its index entry, and decrement counts', {
766
+ id: z.string().min(1).describe('Unique rule ID to delete'),
767
+ validate: z.boolean().optional().default(true).describe('Validate catalog after deletion (default: true)'),
768
+ dir: z.string().optional().describe('Codebase directory'),
769
+ pool: z.string().optional().describe('External knowledge base pool directory')
770
+ }, async ({ id, validate = true, dir, pool }) => {
771
+ const targetDir = path.resolve(dir || root);
772
+ const result = await CatalogStore.deleteUnit(id, { targetDir, poolDir: pool, validate });
773
+ if (!result.success) {
774
+ return {
775
+ content: [{ type: 'text', text: result.error || 'Failed to delete unit' }],
776
+ isError: true
777
+ };
778
+ }
779
+ return {
780
+ content: [
781
+ {
782
+ type: 'text',
783
+ text: JSON.stringify(result, null, 2)
784
+ }
785
+ ]
786
+ };
787
+ });
788
+ }
789
+ // Tool 10: akbo_import_skills
790
+ if (!disabledTools.has('akbo_import_skills')) {
791
+ server.tool('akbo_import_skills', 'Import agent skills (.agents/skills/**/SKILL.md) into the central knowledge pool', {
792
+ sourceGlobs: z.array(z.string()).optional().describe('Custom globs to search for SKILL.md files'),
793
+ domain: z.string().optional().default('development').describe('Domain to assign to imported skills'),
794
+ dir: z.string().optional().describe('Codebase directory (default: workspace root)'),
795
+ pool: z.string().optional().describe('External knowledge base pool directory'),
796
+ force: z.boolean().optional().default(false).describe('Overwrite existing units')
797
+ }, async ({ sourceGlobs, domain = 'development', dir, pool, force = false }) => {
798
+ const targetDir = path.resolve(dir || root);
799
+ const poolConfig = KnowledgePoolResolver.resolve(targetDir, { explicitPoolDir: pool });
800
+ const importer = new SkillImporter(targetDir, poolConfig.poolDir);
801
+ const result = await importer.importSkills({
802
+ repoRoot: targetDir,
803
+ poolDir: poolConfig.poolDir,
804
+ sourceGlobs,
805
+ domain,
806
+ force
807
+ });
808
+ GraphBuilder.clearCache();
809
+ return {
810
+ content: [
811
+ {
812
+ type: 'text',
813
+ text: JSON.stringify(result, null, 2)
814
+ }
815
+ ]
816
+ };
817
+ });
818
+ }
819
+ // Resource: akbo://knowledge/index
820
+ server.resource('catalog', 'akbo://knowledge/index', async (uri) => {
821
+ const poolConfig = KnowledgePoolResolver.resolve(root);
822
+ const indexPath = path.join(poolConfig.knowledgeDir, 'index.yaml');
823
+ const text = fs.existsSync(indexPath) ? fs.readFileSync(indexPath, 'utf-8') : '# No index.yaml found';
824
+ return {
825
+ contents: [
826
+ {
827
+ uri: uri.href,
828
+ text
829
+ }
830
+ ]
831
+ };
832
+ });
833
+ return server;
834
+ }
835
+ export async function runMcpServer(repoRoot = process.cwd(), poolDirOrConfig, config) {
836
+ let resolvedConfig;
837
+ if (typeof poolDirOrConfig === 'string') {
838
+ resolvedConfig = { ...(config || {}), poolDir: poolDirOrConfig };
839
+ }
840
+ else {
841
+ resolvedConfig = poolDirOrConfig || config || {};
842
+ }
843
+ const server = createMcpServer(repoRoot, resolvedConfig);
844
+ const transport = new StdioServerTransport();
845
+ await server.connect(transport);
846
+ }