@dimassetoid/septum-mcp 0.3.0 → 0.5.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 (129) hide show
  1. package/README.md +38 -55
  2. package/package.json +7 -5
  3. package/src/cli/commands/check.ts +14 -10
  4. package/src/cli/commands/hook.ts +41 -6
  5. package/src/cli/commands/init.ts +10 -1
  6. package/src/cli/commands/stats.ts +33 -0
  7. package/src/cli/commands/sync-progress.ts +71 -0
  8. package/src/cli/commands/sync.ts +32 -4
  9. package/src/cli/index.ts +7 -0
  10. package/src/cli/templates/hooks.ts +3 -14
  11. package/src/cli/templates/skill.ts +17 -10
  12. package/src/core/boundary/audit.ts +383 -0
  13. package/src/core/boundary/evaluator.ts +251 -114
  14. package/src/core/boundary/staged-auditor.ts +147 -55
  15. package/src/core/config/domain-ownership.ts +6 -4
  16. package/src/core/config/domain-registration.ts +141 -0
  17. package/src/core/config/loader.ts +1 -25
  18. package/src/core/config/schema.ts +24 -36
  19. package/src/core/database/client.ts +2 -0
  20. package/src/core/database/repositories/dependency.repository.ts +334 -572
  21. package/src/core/database/repositories/domain.repository.ts +2 -1
  22. package/src/core/database/repositories/file.repository.ts +10 -0
  23. package/src/core/database/repositories/symbol.repository.ts +97 -398
  24. package/src/core/database/repository.ts +68 -9
  25. package/src/core/database/schema.ts +26 -0
  26. package/src/core/discovery/declarative-routes.ts +69 -0
  27. package/src/core/discovery/framework-detector.ts +149 -0
  28. package/src/core/discovery/navigation.ts +222 -58
  29. package/src/core/discovery/topology-detector.ts +93 -168
  30. package/src/core/errors.ts +19 -0
  31. package/src/core/ingestion/pipeline.ts +287 -88
  32. package/src/core/parser/extractors/base.ts +11 -3
  33. package/src/core/parser/extractors/csharp.ts +2 -2
  34. package/src/core/parser/extractors/django-routing.ts +163 -0
  35. package/src/core/parser/extractors/django-semantic.ts +397 -481
  36. package/src/core/parser/extractors/elysia-semantic.ts +172 -475
  37. package/src/core/parser/extractors/express-semantic.ts +195 -383
  38. package/src/core/parser/extractors/fastapi-semantic.ts +178 -361
  39. package/src/core/parser/extractors/fastify-semantic.ts +216 -717
  40. package/src/core/parser/extractors/flask-semantic.ts +89 -352
  41. package/src/core/parser/extractors/go-routing.ts +344 -0
  42. package/src/core/parser/extractors/go-semantic.ts +205 -562
  43. package/src/core/parser/extractors/go.ts +6 -3
  44. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  45. package/src/core/parser/extractors/hono-semantic.ts +132 -509
  46. package/src/core/parser/extractors/java.ts +2 -2
  47. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  48. package/src/core/parser/extractors/laravel-semantic.ts +143 -335
  49. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  50. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  51. package/src/core/parser/extractors/mcp-cli-semantic.ts +82 -333
  52. package/src/core/parser/extractors/nestjs-semantic.ts +238 -494
  53. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  54. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  55. package/src/core/parser/extractors/php.ts +1 -1
  56. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  57. package/src/core/parser/extractors/python.ts +5 -9
  58. package/src/core/parser/extractors/registry.ts +2 -0
  59. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  60. package/src/core/parser/extractors/ruby.ts +2 -2
  61. package/src/core/parser/extractors/rust.ts +4 -4
  62. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  63. package/src/core/parser/extractors/symfony-semantic.ts +72 -226
  64. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  65. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  66. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  67. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  68. package/src/core/parser/extractors/typescript.ts +23 -216
  69. package/src/core/parser/language-capabilities.ts +1 -1
  70. package/src/core/parser/schema/providers/laravel-migration-provider.ts +4 -1
  71. package/src/core/parser/wasm-loader.ts +6 -2
  72. package/src/core/resolver/ast-method-tracer.ts +230 -0
  73. package/src/core/resolver/call-graph-helpers.ts +72 -0
  74. package/src/core/resolver/call-graph-tracer.ts +169 -414
  75. package/src/core/resolver/dependency-analysis.ts +593 -0
  76. package/src/core/resolver/import-candidates.ts +120 -0
  77. package/src/core/resolver/import-evidence.ts +88 -0
  78. package/src/core/resolver/import-resolver.ts +60 -7
  79. package/src/core/resolver/interpretation-inputs.ts +60 -2
  80. package/src/core/resolver/languages/python.ts +31 -13
  81. package/src/core/resolver/languages/shared.ts +4 -1
  82. package/src/core/resolver/module-resolver.ts +10 -3
  83. package/src/core/resolver/path-resolver.ts +6 -3
  84. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  85. package/src/core/resolver/slice-catalog.ts +21 -6
  86. package/src/core/resolver/slice-format.ts +13 -0
  87. package/src/core/resolver/slice-selection.ts +237 -0
  88. package/src/core/resolver/symbol-impact.ts +104 -8
  89. package/src/core/resolver/symbol-locator.ts +82 -15
  90. package/src/core/resolver/vertical-slice-tracer.ts +31 -230
  91. package/src/core/resources/ignore.ts +0 -1
  92. package/src/core/resources/limits.ts +2 -1
  93. package/src/core/resources/work-queue.ts +167 -4
  94. package/src/core/retrieval/context-page.ts +11 -4
  95. package/src/core/retrieval/context.ts +363 -226
  96. package/src/{mcp/tools/get-symbol.ts → core/retrieval/source-context.ts} +145 -96
  97. package/src/core/retrieval/symbol-details.ts +453 -0
  98. package/src/core/retrieval/symbol-evidence.ts +3 -3
  99. package/src/core/retrieval/typescript-references.ts +38 -7
  100. package/src/core/retrieval/universal-context.ts +182 -0
  101. package/src/core/telemetry/summary.ts +114 -0
  102. package/src/core/telemetry/telemetry.ts +192 -49
  103. package/src/mcp/formatters/compact-text.ts +439 -0
  104. package/src/mcp/resources-and-prompts.ts +253 -0
  105. package/src/mcp/schemas/boundary.ts +145 -0
  106. package/src/mcp/schemas/map.ts +250 -0
  107. package/src/mcp/schemas/shared.ts +52 -0
  108. package/src/mcp/schemas/slice.ts +60 -0
  109. package/src/mcp/schemas/symbol.ts +268 -0
  110. package/src/mcp/schemas.ts +5 -746
  111. package/src/mcp/server.ts +269 -429
  112. package/src/mcp/tool-catalog.ts +331 -0
  113. package/src/mcp/tools/boundary.ts +68 -3
  114. package/src/mcp/tools/map.ts +104 -4
  115. package/src/mcp/tools/slice.ts +101 -3
  116. package/src/mcp/tools/symbol.ts +469 -17
  117. package/src/mcp/ui/app-client.ts +899 -0
  118. package/src/mcp/ui/app.html +478 -0
  119. package/src/mcp/workflow-playbooks.ts +181 -0
  120. package/src/mcp/workspace-boundary.ts +50 -0
  121. package/src/mcp/workspace-manager.ts +88 -15
  122. package/src/mcp/workspace-watcher.ts +30 -11
  123. package/src/types/index.ts +12 -0
  124. package/src/mcp/tools/check-boundary.ts +0 -382
  125. package/src/mcp/tools/get-domain-catalog.ts +0 -39
  126. package/src/mcp/tools/get-symbol-impact.ts +0 -104
  127. package/src/mcp/tools/locate-symbol.ts +0 -236
  128. package/src/mcp/tools/register-domain.ts +0 -113
  129. package/src/mcp/tools/trace-vertical-slice.ts +0 -106
package/src/mcp/server.ts CHANGED
@@ -1,25 +1,35 @@
1
- import { buildUnindexedCatalog } from "./tools/get-domain-catalog.ts";
1
+ import { runWorkspaceBoundary } from "./workspace-boundary.ts";
2
+ import { randomBytes } from "node:crypto";
3
+ import { buildUnindexedCatalog } from "./tools/map.ts";
2
4
  import { WorkspaceManager, resolveServerWorkspace, isWorkspaceInitialized, type WorkspaceLease } from "./workspace-manager.ts";
3
5
  import { RESOURCE_LIMITS } from "../core/resources/limits.ts";
4
6
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
7
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
8
  import {
7
9
  CallToolRequestSchema,
10
+ GetPromptRequestSchema,
11
+ ListPromptsRequestSchema,
12
+ ListResourcesRequestSchema,
13
+ ListResourceTemplatesRequestSchema,
8
14
  ListToolsRequestSchema,
15
+ ReadResourceRequestSchema,
9
16
  } from "@modelcontextprotocol/sdk/types.js";
10
- import { ConfigLoader } from "../core/config/loader.ts";
11
- import { SeptumTelemetry } from "../core/telemetry/telemetry.ts";
12
- import { handleMapTool } from "./tools/map.ts";
13
- import { handleSymbolTool } from "./tools/symbol.ts";
14
- import { handleSliceTool } from "./tools/slice.ts";
15
- import { handleBoundaryTool } from "./tools/boundary.ts";
16
- import { DomainRootConflictError } from "../core/config/domain-ownership.ts";
17
-
18
17
  import {
19
- parseToolRequest,
20
- } from "./schemas.ts";
18
+ getSeptumPrompt,
19
+ listSeptumPrompts,
20
+ listSeptumResources,
21
+ listSeptumResourceTemplates,
22
+ readSeptumResource,
23
+ } from "./resources-and-prompts.ts";
24
+ import { SeptumTelemetry, type ToolCallStage, type ToolResponse } from "../core/telemetry/telemetry.ts";
25
+ import { SeptumError } from "../core/errors.ts";
26
+ import { TOOL_CATALOG, parseToolRequest } from "./tool-catalog.ts";
21
27
  import { SEPTUM_VERSION, checkRuntimeVersion } from "../utils/version-check.ts";
22
28
 
29
+ function explicitWorkspaceAlias(record: Record<string, unknown>): unknown {
30
+ return record.workspace_path ?? record.workspacePath ?? record.workspace ?? record.project_root ?? record.projectRoot;
31
+ }
32
+
23
33
  export function extractPathHint(args: unknown): string | undefined {
24
34
  if (!args) return undefined;
25
35
 
@@ -39,14 +49,7 @@ export function extractPathHint(args: unknown): string | undefined {
39
49
  if (typeof args === "object" && args !== null) {
40
50
  const record = args as Record<string, any>;
41
51
 
42
- const explicitWorkspace =
43
- record.workspace_path ??
44
- record.workspacePath ??
45
- record.workspace ??
46
- record.project_root ??
47
- record.projectRoot ??
48
- record.target_path ??
49
- record.targetPath;
52
+ const explicitWorkspace = explicitWorkspaceAlias(record) ?? record.target_path ?? record.targetPath;
50
53
  if (typeof explicitWorkspace === "string" && explicitWorkspace.trim()) {
51
54
  return explicitWorkspace.trim();
52
55
  }
@@ -91,25 +94,16 @@ export function extractPathHint(args: unknown): string | undefined {
91
94
  return undefined;
92
95
  }
93
96
 
94
- function countLines(text: string): number {
95
- let count = 1;
96
- for (let i = 0; i < text.length; i++) {
97
- if (text.charCodeAt(i) === 10) count++;
98
- }
99
- return count;
100
- }
101
-
102
97
  export const SEPTUM_SERVER_INSTRUCTIONS = `Septum indexes supported declarations, imports, domain policies and static entrypoints.
103
98
  Guidelines for AI Coding Agents:
104
99
  1. CONTEXT: Call septum_symbol(action: 'context') for declaration source and supporting references. Deep TypeScript context uses budget_bytes and continuation; source inspection uses line limits. Read freshness, diagnostics and omissions, then inspect further source when needed.
105
100
  2. NAVIGATION: Call septum_map(action: 'catalog') for domain/file locations, import relationships, static entrypoints and index health.
106
101
  3. CONSUMERS: Before changing public contracts, inspect septum_symbol(action: 'impact') and relevant consumers. Import dependents and caller hints are incomplete static evidence; verify affected application behavior.
107
102
  4. ENTRYPOINTS: Call septum_slice(query: '<route|handler>') for catalog matches and related nodes. Matching confidence does not establish runtime reachability or execution order.
108
- 5. BOUNDARIES: Call septum_boundary(scope: 'file', file_path: '...', proposed_imports: [...]) for candidate imports, or scope: 'all'/'domain'/'staged' for those audit scopes. Proposal approval does not audit existing imports. Unknown is not approval; approved describes only the evaluated static scope.`;
103
+ 5. BOUNDARIES: Call septum_boundary(scope: 'file', file_path: '...', proposed_imports: [...]) for candidate imports, or scope: 'all'/'domain'/'staged' for those audit scopes. Proposal approval does not audit existing imports. Unknown is not approval; approved describes only the evaluated static scope.
104
+ 6. RESOURCES & PROMPTS: Initial-workspace snapshots are available at septum://domains, septum://health, septum://boundaries, septum://apps, and septum://domain/{name}; workflow playbooks at prompts open-apps, audit-coupling, check-staged, plan-refactor, and trace-feature.`;
109
105
 
110
- export async function runMCPServer(): Promise<void> {
111
- const manager = new WorkspaceManager();
112
- void checkRuntimeVersion().catch(() => {});
106
+ export function createMcpServer(manager: WorkspaceManager): Server {
113
107
 
114
108
  const server = new Server(
115
109
  {
@@ -119,422 +113,256 @@ export async function runMCPServer(): Promise<void> {
119
113
  {
120
114
  capabilities: {
121
115
  tools: {},
116
+ resources: {},
117
+ prompts: {},
122
118
  },
123
119
  instructions: SEPTUM_SERVER_INSTRUCTIONS,
124
120
  }
125
121
  );
126
122
 
127
- server.setRequestHandler(ListToolsRequestSchema, async () => {
128
- return {
129
- tools: [
130
- {
131
- name: "septum_map",
132
- description:
133
- "Navigate architecture: workspace domains and cross-domain import adjacency, domain/file neighborhoods, static entrypoints and coverage. Output schema navigation/v1. Signatures, member lists and source belong to septum_symbol; full expands navigation only. Use file_filter to focus, include_evidence for one file's import details, or septum_slice for static handler relationships. Example: {action:'catalog',domain:'mcp'}.",
134
- inputSchema: {
135
- type: "object",
136
- properties: {
137
- action: {
138
- type: "string",
139
- enum: ["catalog", "register"],
140
- default: "catalog",
141
- description: "Sub-operation to execute: 'catalog' (inspect domain/macro map) or 'register' (dynamically register bounded-context domain).",
142
- },
143
- domain: {
144
- type: "string",
145
- description: "Target domain name (e.g. 'orders', 'core'). If omitted in catalog action, returns project-wide Macro Semantic Map.",
146
- },
147
- detail_level: {
148
- type: "string",
149
- enum: ["compact", "full"],
150
- default: "compact",
151
- description: "Navigation extent: compact selects up to 40 files, full up to 100. Neither includes signatures or source; use septum_symbol for declaration inspection.",
152
- },
153
- archetype_filter: {
154
- type: "string",
155
- description: "Optional archetype filter (e.g. 'service', 'model', 'controller', 'repository').",
156
- },
157
- file_filter: {
158
- type: "string",
159
- description: "Optional substring filter to inspect specific file(s) within the domain.",
160
- },
161
- file_offset: { type: "integer", minimum: 0, description: "Start of the catalog file page; copy next_file_offset from pagination." },
162
- file_limit: { type: "integer", minimum: 1, maximum: 100, description: "Optional navigation selection limit. Small scopes return together; pagination appears only when files remain." },
163
- include_evidence: { type: "boolean", description: "Opt in to up to 20 raw import-evidence records; requires file_filter matching exactly one file." },
164
- include_capabilities: { type: "boolean", description: "Opt in to language/parser capabilities; omitted from navigation by default." },
165
- root: {
166
- type: "string",
167
- description: "Root directory path for domain registration (action='register').",
168
- },
169
- description: {
170
- type: "string",
171
- description: "Architectural purpose of the domain (action='register').",
172
- },
173
- allowed_dependencies: {
174
- type: "array",
175
- items: { type: "string" },
176
- description: "List of domain names this domain is allowed to import (action='register').",
177
- },
178
- forbidden_dependencies: {
179
- type: "array",
180
- items: { type: "string" },
181
- description: "List of domain names strictly forbidden from being imported (action='register').",
182
- },
183
- archetypes: {
184
- type: "object",
185
- description: "Layer archetypes mapping (action='register').",
186
- },
187
- ingest_now: {
188
- type: "boolean",
189
- default: false,
190
- description: "Whether to immediately run AST ingestion on domain files upon registration.",
191
- },
192
- workspace_path: {
193
- type: "string",
194
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
195
- },
196
- },
197
- required: [],
198
- },
199
- },
200
- {
201
- name: "septum_symbol",
202
- description:
203
- "Locate indexed declarations, retrieve source/contracts, or inspect potential consumers. action='context' (alias 'inspect') selects deep TypeScript references or bounded source inspection; read mode, freshness, diagnostics and omissions. action='impact' separates import dependents from supported static call sites and inferred caller hints; the caller set is incomplete. Use septum_map for domain/file navigation and septum_slice for static entrypoint context. Example: {action:'context',query:'handleOrder',file_path:'src/orders.ts'}.",
204
- inputSchema: {
205
- type: "object",
206
- properties: {
207
- action: {
208
- type: "string",
209
- enum: ["locate", "context", "inspect", "impact"],
210
- default: "locate",
211
- description: "'locate' finds declarations; 'context' (or 'inspect') retrieves declaration source along with local/import-bound supporting declarations for TypeScript within budget_bytes, or bounded source for polyglot files; 'impact' reports static caller hints. Example: {action:'context',query:'submit',file_path:'src/submit.ts'}.",
212
- },
213
- query: {
214
- type: "string",
215
- description: "Symbol name, call syntax (e.g. 'OrderController::cancelOrder'), or search query.",
216
- },
217
- domain: {
218
- type: "string",
219
- description: "Optional domain filter (e.g. 'orders').",
220
- },
221
- file_path: {
222
- type: "string",
223
- description: "Exact indexed repository-relative file path. Use it to select one candidate when names are ambiguous.",
224
- },
225
- symbol_ref: {
226
- type: "object",
227
- description: "Declaration reference returned by locate or catalog. Stale indexed fingerprints are refused.",
228
- properties: {
229
- file_path: { type: "string", minLength: 1 },
230
- language: { type: "string", minLength: 1 },
231
- name: { type: "string", minLength: 1 },
232
- kind: { type: "string", minLength: 1 },
233
- signature: { type: "string" },
234
- start_line: { type: "integer", minimum: 1 },
235
- end_line: { type: "integer", minimum: 1 },
236
- indexed_content_hash: { type: "string", minLength: 1 },
237
- container: { type: "string" },
238
- receiver: { type: "string" },
239
- },
240
- required: ["file_path", "language", "name", "kind", "signature", "start_line", "end_line", "indexed_content_hash"],
241
- },
242
- include_source: {
243
- type: "boolean",
244
- description: "Explicit true selects bounded source; explicit false selects declaration details without source. Omit for deep TypeScript context or default polyglot source. Source hashes must match disk.",
245
- },
246
- source_start_line: {
247
- type: "number",
248
- minimum: 1,
249
- description: "First line to return within the selected symbol range.",
250
- },
251
- source_line_limit: {
252
- type: "number",
253
- minimum: 1,
254
- maximum: 200,
255
- description: "Select bounded source inspection with this line limit (capped at 200). Bounded mode uses 120 lines when omitted.",
256
- },
257
- context_mode: {
258
- type: "string", enum: ["deep", "source"],
259
- description: "Explicit context mode. deep selects referenced TypeScript declarations; source selects bounded source inspection. Omit for legacy automatic selection.",
260
- },
261
- include_dependencies: {
262
- type: "boolean",
263
- default: true,
264
- description: "Whether to include injected dependencies and outbound calls.",
265
- },
266
- budget_bytes: {
267
- type: "integer",
268
- minimum: 2048,
269
- maximum: 2097152,
270
- default: 16384,
271
- description: "For deep TypeScript context (including inspect alias): maximum UTF-8 bytes of the serialized MCP tool result, including evidence and continuation. Do not combine with bounded source options.",
272
- },
273
- continuation: {
274
- type: "string",
275
- minLength: 1,
276
- maxLength: 4096,
277
- description: "For action='context': copy the previous page token with the same target and budget.",
278
- },
279
- limit: {
280
- type: "number",
281
- description: "Maximum results to return for locate (default: 10).",
282
- },
283
- workspace_path: {
284
- type: "string",
285
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
286
- },
287
- },
288
- required: [],
289
- },
290
- },
291
- {
292
- name: "septum_slice",
293
- description:
294
- "Match a supported static entrypoint and inspect related nodes with relationship evidence and diagnostics. Supports cataloged routes, handlers, jobs, CLI commands and events; results do not establish runtime execution order or complete reachability. Use septum_symbol for declarations and septum_boundary for import policy. Example: {query:'POST /orders/{id}/pay',max_depth:5} or {query:'OrderController@pay'}.",
295
- inputSchema: {
296
- type: "object",
297
- properties: {
298
- query: {
299
- type: "string",
300
- description: "Route URI (e.g. 'POST /orders/{id}/pay'), action (e.g. 'OrderController@pay'), or high-level task intent.",
301
- },
302
- controller_file: {
303
- type: "string",
304
- minLength: 1,
305
- description: "Exact catalog controller/handler file copied from an ambiguity candidate. Filters target selection.",
306
- },
307
- max_depth: {
308
- type: "number",
309
- default: 5,
310
- minimum: 1,
311
- maximum: 8,
312
- description: "Maximum depth to trace (default: 5, min: 1, max: 8). Use 6-8 for deep Event/Job/Queue traces.",
313
- },
314
- workspace_path: {
315
- type: "string",
316
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
317
- },
318
- },
319
- required: ["query"],
320
- },
321
- },
322
- {
323
- name: "septum_boundary",
324
- description:
325
- "Architectural firewall: validate proposed or staged imports against domain boundaries and circular dependency constraints. When to use: (1) scope='file' with proposed_imports BEFORE writing new import statements, (2) scope='staged' BEFORE git commit to prevent cross-domain leaks, (3) scope='all' or 'domain' for codebase audits. When NOT to use: do NOT use to read source code or locate symbols. Status 'approved' confirms zero violations; 'rejected' requires refactoring. Example: {scope:'file',file_path:'src/order/service.ts',proposed_imports:['../billing/repo']}.",
326
- inputSchema: {
327
- type: "object",
328
- properties: {
329
- scope: {
330
- type: "string",
331
- enum: ["file", "staged", "all", "domain"],
332
- default: "file",
333
- description: "'file' evaluates proposed imports against domain policies; 'staged' audits git index changes; 'domain' checks a specific domain's violations; 'all' audits the entire workspace.",
334
- },
335
- file_path: {
336
- type: "string",
337
- description: "Path of the file being edited or created (scope='file' only). Use either file_path or file_paths.",
338
- },
339
- file_paths: {
340
- type: "array",
341
- items: { type: "string" },
342
- description: "Non-empty list of file paths for batch proposed-import checks (scope='file' only).",
343
- },
344
- proposed_imports: {
345
- type: "array",
346
- items: { type: "string" },
347
- description: "List of proposed import statements or target symbols (scope='file' only).",
348
- },
349
- domain: {
350
- type: "string",
351
- description: "Registered domain name, required for scope='domain'; optional for staged/file checks.",
352
- },
353
- staged: {
354
- type: "boolean",
355
- description: "Convenience flag equivalent to scope='staged'.",
356
- },
357
- workspace_path: {
358
- type: "string",
359
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
360
- },
361
- },
362
- required: [],
123
+ server.setRequestHandler(ListResourcesRequestSchema, async () => listSeptumResources());
124
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => listSeptumResourceTemplates());
125
+ server.setRequestHandler(ReadResourceRequestSchema, async (request, extra) => {
126
+ const traceId = randomBytes(16).toString("hex");
127
+ const startTime = performance.now();
128
+ const uri = request.params.uri;
129
+ return SeptumTelemetry.withTrace(traceId, async () => {
130
+ try {
131
+ const result = await readSeptumResource(manager, uri, extra.signal);
132
+ SeptumTelemetry.recordSystemEvent({
133
+ level: "INFO",
134
+ component: "resource",
135
+ event: "resource_read_completed",
136
+ fields: { uri: uri.slice(0, 128), duration_ms: Math.round(performance.now() - startTime) },
137
+ workspaceRoot: manager.initialRoot ?? null,
138
+ emitStderr: false,
139
+ });
140
+ return result;
141
+ } catch (error) {
142
+ SeptumTelemetry.recordSystemEvent({
143
+ level: "ERROR",
144
+ component: "resource",
145
+ event: "resource_read_failed",
146
+ fields: {
147
+ uri: uri.slice(0, 128),
148
+ duration_ms: Math.round(performance.now() - startTime),
149
+ message: (error instanceof Error ? error.message : String(error)).slice(0, 256),
363
150
  },
364
- },
365
- ],
366
- };
151
+ workspaceRoot: manager.initialRoot ?? null,
152
+ emitStderr: false,
153
+ });
154
+ throw error;
155
+ }
156
+ }, manager.initialRoot);
367
157
  });
158
+ server.setRequestHandler(ListPromptsRequestSchema, async () => listSeptumPrompts());
159
+ server.setRequestHandler(GetPromptRequestSchema, async (request) =>
160
+ getSeptumPrompt(request.params.name, request.params.arguments)
161
+ );
162
+
163
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
164
+ tools: TOOL_CATALOG.map(({ name, description, inputSchema, _meta }) => ({ name, description, inputSchema, _meta })),
165
+ }));
368
166
 
369
167
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
370
168
  const { name, arguments: args } = request.params;
371
169
  const startTime = performance.now();
372
- let lease: WorkspaceLease | undefined;
373
- try {
374
- extra?.signal?.throwIfAborted();
375
- let parsed;
376
- try { parsed = parseToolRequest(name, args); }
377
- catch (error) { throw new Error(`[Septum Validation Error] Invalid arguments for ${name}: ${error instanceof Error ? error.message : String(error)}`); }
378
- const record = parsed.args;
379
- const raw = (args ?? {}) as Record<string, any>;
380
- const workspacePath = record.workspace_path ?? raw.workspace_path ?? raw.workspacePath ?? raw.workspace ?? raw.project_root ?? raw.projectRoot;
381
- const knownRoots = manager.activeRoots;
382
- if (manager.initialRoot && !knownRoots.includes(manager.initialRoot)) {
383
- knownRoots.unshift(manager.initialRoot);
384
- }
385
- const fallbackRoot = manager.initialRoot || manager.lastRoot;
386
- const root = resolveServerWorkspace({
387
- workspacePath,
388
- filePath: workspacePath ? undefined : extractPathHint(args),
389
- fallbackRoot,
390
- knownRoots,
391
- });
392
-
393
- if (!isWorkspaceInitialized(root)) {
394
- if (name === "septum_map" && (!("action" in record) || !record.action || record.action === "catalog")) {
395
- const runtimeVersion = await checkRuntimeVersion();
396
- const diagnostic = buildUnindexedCatalog(root, runtimeVersion);
397
- return {
398
- content: [
399
- {
400
- type: "text",
401
- text: JSON.stringify(diagnostic, null, 2),
402
- },
403
- ],
404
- metadata: diagnostic,
405
- runtime_version: runtimeVersion,
406
- };
407
- }
408
- const isRegistration = name === "septum_map" && "action" in record && record.action === "register";
409
- if (!isRegistration) {
410
- return {
411
- isError: true,
412
- content: [
413
- {
414
- type: "text",
415
- text: `[Septum MCP Error] Workspace '${root}' belum diinisialisasi. Jalankan 'septum init' di terminal workspace atau gunakan tool 'septum_map' dengan action='register' untuk mendaftarkan domain.`,
416
- },
417
- ],
418
- };
419
- }
420
- }
421
-
422
- extra?.signal?.throwIfAborted();
423
- const isDomainRegistration = parsed.name === "septum_map" && parsed.args.action === "register";
424
- lease = manager.acquire(root, { deferDiscovery: isDomainRegistration });
425
- const ctx = lease.context;
426
- await ctx.ready;
427
- extra?.signal?.throwIfAborted();
428
- const registrationBeforeDiscovery = isDomainRegistration && Object.keys(ctx.config.domains).length === 0 && ctx.repo.getAllDomains().length === 0;
429
- try { if (!registrationBeforeDiscovery) await ctx.watcher.flush(false, extra?.signal); }
430
- catch (error) { if (!isDomainRegistration || !(error instanceof DomainRootConflictError)) throw error; }
431
- if (ctx.repo.getMeta("sync_error") && !(isDomainRegistration && ctx.repo.getMeta("sync_error_code") === "DOMAIN_ROOT_CONFLICT")) {
432
- throw new Error(`Workspace index synchronization failed: ${ctx.repo.getMeta("sync_error")}`);
433
- }
434
- ctx.config = ConfigLoader.load(undefined, ctx.root);
435
- // External policy writes do not emit source watcher events. Keep this cheap
436
- // ownership gate independent of full reconciliation and target JIT refresh.
437
- if (!isDomainRegistration) ctx.pipeline.assertDomainOwnership(ctx.config, ctx.root);
438
- ctx.evaluator.getResolver().setRepository(ctx.repo);
439
-
440
- const executeTool = async () => {
441
- switch (parsed.name) {
442
- case "septum_map": return handleMapTool(ctx.repo, ctx.config, parsed.args, ctx.root, extra?.signal);
443
- case "septum_symbol": return handleSymbolTool(ctx.repo, ctx.config, parsed.args, ctx.pipeline, ctx.root, extra?.signal);
444
- case "septum_slice": return handleSliceTool(ctx.repo, ctx.config, parsed.args, ctx.root, extra?.signal);
445
- case "septum_boundary": return handleBoundaryTool(ctx.evaluator, ctx.config, parsed.args, ctx.repo, ctx.root);
446
- }
447
- };
448
-
449
- try {
450
- const response = await manager.runTool(executeTool, extra?.signal);
451
- const durationMs = Math.round(performance.now() - startTime);
452
-
453
- let bytesOut = 0;
454
- let linesOut = 0;
455
- let combinedText = "";
456
- if (Array.isArray(response?.content)) {
457
- for (const item of response.content) {
458
- if (typeof item.text === "string") {
459
- bytesOut += Buffer.byteLength(item.text, "utf8");
460
- linesOut += countLines(item.text);
461
- if (combinedText.length < 1500) {
462
- combinedText += item.text;
170
+ const deadline = AbortSignal.timeout(RESOURCE_LIMITS.requestTimeoutMs);
171
+ const signal = AbortSignal.any([extra.signal, deadline]);
172
+ const traceId = randomBytes(16).toString("hex");
173
+ let stage: ToolCallStage = "validation";
174
+ let root: string | undefined;
175
+ let action: string | undefined;
176
+ const toolSpec = TOOL_CATALOG.find(entry => entry.name === name);
177
+ const tool = toolSpec ? name : "unknown";
178
+ const hasUiResource = Boolean((toolSpec?._meta?.ui as { resourceUri?: string } | undefined)?.resourceUri);
179
+ const wantsStructured = (args && typeof args === "object" && (args as Record<string, unknown>).format === "json") || hasUiResource;
180
+ const finish = <T extends ToolResponse>(response: T, error?: Error): T => {
181
+ const shapedResponse = (() => {
182
+ if (!response || typeof response !== "object") return response;
183
+ const record = response as Record<string, unknown>;
184
+ if (
185
+ !wantsStructured &&
186
+ record.structuredContent &&
187
+ Array.isArray(record.content) &&
188
+ record.content.length > 0
189
+ ) {
190
+ const { structuredContent: _omitted, ...withoutStructured } = record;
191
+ return withoutStructured as unknown as T;
192
+ }
193
+ let structured = record.structuredContent;
194
+ if (
195
+ wantsStructured &&
196
+ !structured &&
197
+ Array.isArray(record.content) &&
198
+ typeof (record.content[0] as { text?: unknown } | undefined)?.text === "string"
199
+ ) {
200
+ try {
201
+ const parsed = JSON.parse((record.content[0] as { text: string }).text);
202
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
203
+ structured = parsed;
463
204
  }
205
+ } catch {
206
+ // Non-JSON text content; leave structuredContent unset
464
207
  }
465
208
  }
466
- }
467
-
468
- const inputArgs = (args as Record<string, any>) ?? {};
469
- const actionName = typeof inputArgs.action === "string" ? inputArgs.action : (typeof inputArgs.scope === "string" ? inputArgs.scope : undefined);
470
- const estimatedTokens = Math.round(bytesOut / 4);
471
- const bloatAlert = bytesOut >= SeptumTelemetry.BLOAT_BYTE_THRESHOLD;
472
- const outputDigest = SeptumTelemetry.createOutputDigest(combinedText);
473
- let outcome: string | undefined;
474
- try {
475
- const payload = JSON.parse(combinedText);
476
- const candidate = payload.status ?? (payload.found === false ? "not_found" : undefined);
477
- if (["success", "partial", "unknown", "approved", "rejected", "ambiguous", "not_found", "NOT_INDEXED", "stale_reference", "invalid_context_options", "budget_too_small"].includes(candidate)) outcome = candidate;
478
- } catch { /* Non-JSON results retain transport status only. */ }
209
+ if (wantsStructured && structured && typeof structured === "object") {
210
+ const structuredRecord = structured as Record<string, unknown>;
211
+ const withRoot =
212
+ root && !("workspace_root" in structuredRecord) &&
213
+ structuredRecord.code !== "BUDGET_RESPONSE_TOO_LARGE"
214
+ ? { workspace_root: root, ...structuredRecord }
215
+ : structured;
216
+ if (withRoot !== record.structuredContent) {
217
+ return {
218
+ ...record,
219
+ structuredContent: withRoot,
220
+ } as unknown as T;
221
+ }
222
+ }
223
+ return response;
224
+ })();
225
+ const code = error instanceof SeptumError ? error.code : undefined;
226
+ SeptumTelemetry.recordToolResponse({
227
+ trace_id: traceId,
228
+ stage: extra.signal.aborted ? "cancelled" : deadline.aborted ? "timeout" : stage,
229
+ tool,
230
+ action,
231
+ duration_ms: Math.round(performance.now() - startTime),
232
+ input: root ? args ?? {} : {},
233
+ error: error ? { code, message: root ? error.message : "Tool execution failed.", stack: root ? error.stack : undefined } : undefined,
234
+ }, shapedResponse, root ?? manager.initialRoot ?? null, root !== undefined);
235
+ return shapedResponse;
236
+ };
479
237
 
480
- SeptumTelemetry.recordToolCall({
481
- event: "tool_call_completed",
482
- tool: name,
483
- action: actionName,
484
- duration_ms: durationMs,
485
- input: inputArgs,
486
- metrics: {
487
- bytes_out: bytesOut,
488
- lines_out: linesOut,
489
- estimated_tokens: estimatedTokens,
490
- },
491
- bloat_alert: bloatAlert,
492
- output_digest: outputDigest,
493
- outcome,
494
- session: null,
495
- status: (response as { isError?: boolean } | undefined)?.isError ? "error" : "success",
496
- }, ctx.root);
238
+ const progressToken = request.params._meta?.progressToken;
239
+ const reportProgress = (progress: number, message: string) => {
240
+ if (progressToken === undefined || signal.aborted) return;
241
+ void extra.sendNotification({
242
+ method: "notifications/progress",
243
+ params: { progressToken, progress, message },
244
+ }).catch(() => {});
245
+ };
497
246
 
498
- return response;
499
- } catch (err) {
500
- const durationMs = Math.round(performance.now() - startTime);
501
- const errorInstance = err instanceof Error ? err : new Error(String(err));
502
- const inputArgs = (args as Record<string, any>) ?? {};
503
- const actionName = typeof inputArgs.action === "string" ? inputArgs.action : (typeof inputArgs.scope === "string" ? inputArgs.scope : undefined);
247
+ return SeptumTelemetry.withTrace(traceId, async () => {
248
+ let lease: WorkspaceLease | undefined;
249
+ try {
250
+ signal.throwIfAborted();
251
+ let parsed;
252
+ try { parsed = parseToolRequest(name, args); }
253
+ catch (error) { throw new Error(`[Septum Validation Error] Invalid arguments for ${name}: ${error instanceof Error ? error.message : String(error)}`); }
254
+ const record = parsed.args;
255
+ action = parsed.name === "septum_map" || parsed.name === "septum_symbol"
256
+ ? parsed.args.action
257
+ : parsed.name === "septum_boundary" ? parsed.args.scope : undefined;
258
+ stage = "workspace";
259
+ const rawWorkspace = args && typeof args === "object" ? explicitWorkspaceAlias(args as Record<string, unknown>) : undefined;
260
+ const workspacePath = record.workspace_path ?? (typeof rawWorkspace === "string" ? rawWorkspace : undefined);
261
+ const knownRoots = manager.activeRoots;
262
+ if (manager.initialRoot && !knownRoots.includes(manager.initialRoot)) {
263
+ knownRoots.unshift(manager.initialRoot);
264
+ }
265
+ const fallbackRoot = manager.initialRoot || manager.lastRoot;
266
+ root = resolveServerWorkspace({
267
+ workspacePath,
268
+ filePath: workspacePath ? undefined : extractPathHint(args),
269
+ fallbackRoot,
270
+ knownRoots,
271
+ });
504
272
 
505
- SeptumTelemetry.recordToolCall({
506
- event: "tool_call_failed",
507
- tool: name,
508
- action: actionName,
509
- duration_ms: durationMs,
510
- input: inputArgs,
511
- session: null,
512
- status: "error",
513
- error: {
514
- message: errorInstance.message,
515
- stack: errorInstance.stack,
516
- },
517
- }, ctx.root);
273
+ if (!isWorkspaceInitialized(root)) {
274
+ if (name === "septum_map" && (!("action" in record) || !record.action || record.action === "catalog")) {
275
+ const runtimeVersion = await checkRuntimeVersion();
276
+ const diagnostic = buildUnindexedCatalog(root, runtimeVersion);
277
+ return finish({
278
+ content: [
279
+ {
280
+ type: "text",
281
+ text: JSON.stringify(diagnostic, null, 2),
282
+ },
283
+ ],
284
+ structuredContent: diagnostic,
285
+ metadata: diagnostic,
286
+ runtime_version: runtimeVersion,
287
+ });
288
+ }
289
+ const isRegistration = name === "septum_map" && "action" in record && record.action === "register";
290
+ if (!isRegistration) {
291
+ return finish({
292
+ isError: true,
293
+ content: [
294
+ {
295
+ type: "text",
296
+ text: `[Septum MCP Error] Workspace '${root}' belum diinisialisasi. Jalankan 'septum init' di terminal workspace atau gunakan tool 'septum_map' dengan action='register' untuk mendaftarkan domain.`,
297
+ },
298
+ ],
299
+ });
300
+ }
301
+ }
518
302
 
519
- return {
520
- isError: true,
521
- content: [
522
- {
523
- type: "text",
524
- text: `[Septum MCP Error] ${errorInstance.message}`,
525
- },
526
- ],
303
+ signal.throwIfAborted();
304
+ const isDomainRegistration = parsed.name === "septum_map" && parsed.args.action === "register";
305
+ reportProgress(1, "Preparing workspace");
306
+ lease = manager.acquire(root, { deferDiscovery: isDomainRegistration });
307
+ const onSync = () => reportProgress(2, "Checking index freshness");
308
+ const onAudit = () => {
309
+ stage = "execution";
310
+ reportProgress(3, "Running tool");
527
311
  };
528
- }
312
+ const response = parsed.name === "septum_boundary" && parsed.args.scope !== "staged" && !parsed.args.staged
313
+ ? await runWorkspaceBoundary(manager, lease.context, parsed.args, {
314
+ signal, onSync, onAudit, onRetry: () => reportProgress(4, "Reconciling stale index before retrying audit"),
315
+ })
316
+ : await manager.runInWorkspace(lease.context, prepared => {
317
+ onAudit();
318
+ return parsed.execute(prepared, signal);
319
+ }, {
320
+ signal,
321
+ isDomainRegistration,
322
+ mode: isDomainRegistration || (parsed.name === "septum_slice" && lease.context.repo.getMeta("slices_dirty") === "1")
323
+ ? "write"
324
+ : "read",
325
+ onSync,
326
+ });
327
+ return finish(response);
529
328
  } catch (error) {
530
- return {isError: true, content: [{type: "text" as const, text: `[Septum MCP Error] ${error instanceof Error ? error.message : String(error)}`}]};
531
- } finally { lease?.release(); }
329
+ const failure = error instanceof Error ? error : new Error(String(error));
330
+ return finish({
331
+ isError: true,
332
+ content: [{ type: "text" as const, text: `[Septum MCP Error] ${failure.message}` }],
333
+ metadata: { trace_id: traceId },
334
+ }, failure);
335
+ } finally {
336
+ lease?.release();
337
+ }
338
+ }, manager.initialRoot);
532
339
  });
533
340
 
341
+ return server;
342
+ }
343
+
344
+ export async function runMCPServer(): Promise<void> {
345
+ const initialRoot = resolveServerWorkspace({ initial: true });
346
+ const manager = new WorkspaceManager();
347
+ manager.initialRoot = initialRoot;
348
+ manager.lastRoot = initialRoot;
349
+ const server = createMcpServer(manager);
534
350
  const transport = new StdioServerTransport();
351
+ void checkRuntimeVersion().catch(() => {});
535
352
 
536
353
  let stopping = false;
537
354
  let memoryTimer: ReturnType<typeof setInterval> | undefined;
355
+ const closeResources = async () => {
356
+ process.off("SIGINT", cleanup);
357
+ process.off("SIGTERM", cleanup);
358
+ process.stdin.off("end", cleanup);
359
+ process.stdin.off("close", cleanup);
360
+ try {
361
+ await server.close();
362
+ } finally {
363
+ await manager.close();
364
+ }
365
+ };
538
366
  const cleanup = () => {
539
367
  if (stopping) return;
540
368
  stopping = true;
@@ -545,8 +373,7 @@ export async function runMCPServer(): Promise<void> {
545
373
  }, RESOURCE_LIMITS.shutdownMs);
546
374
  void (async () => {
547
375
  try {
548
- await server.close();
549
- await manager.close();
376
+ await closeResources();
550
377
  clearTimeout(deadline);
551
378
  console.error("[Septum MCP] All workspace resources closed cleanly.");
552
379
  process.exit(0);
@@ -562,15 +389,26 @@ export async function runMCPServer(): Promise<void> {
562
389
  process.stdin.once("end", cleanup);
563
390
  process.stdin.once("close", cleanup);
564
391
  server.onclose = cleanup;
565
- await server.connect(transport);
566
392
  try {
567
- const initialRoot = resolveServerWorkspace({initial:true});
568
- manager.initialRoot = initialRoot;
569
- manager.lastRoot = initialRoot;
393
+ await server.connect(transport);
570
394
  if (isWorkspaceInitialized(initialRoot)) {
571
395
  const initial = manager.acquire(initialRoot);
572
- try { await initial.context.ready; } finally { initial.release(); }
396
+ try {
397
+ await initial.context.ready;
398
+ } catch (err) {
399
+ SeptumTelemetry.recordSystemEvent({
400
+ level: "WARN",
401
+ component: "mcp_server",
402
+ event: "initial_workspace_sync_failed",
403
+ fields: { message: (err instanceof Error ? err.message : String(err)).slice(0, 256) },
404
+ workspaceRoot: initialRoot,
405
+ emitStderr: false,
406
+ });
407
+ } finally {
408
+ initial.release();
409
+ }
573
410
  }
411
+ if (stopping) return;
574
412
  if (process.env.SEPTUM_MEMORY_DIAGNOSTICS === "1") {
575
413
  memoryTimer = setInterval(() => {
576
414
  const sample = { ...process.memoryUsage(), workspaces: manager.size, watches: manager.watchCount, pending_paths: manager.pendingPaths, sync_duration_ms: manager.syncDurationMs };
@@ -583,7 +421,9 @@ export async function runMCPServer(): Promise<void> {
583
421
  memoryTimer.unref();
584
422
  }
585
423
  } catch (error) {
586
- await manager.close();
424
+ if (stopping) return;
425
+ stopping = true;
426
+ await closeResources();
587
427
  throw error;
588
428
  }
589
429