@dimassetoid/septum-mcp 0.2.1 → 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 (161) hide show
  1. package/README.md +46 -45
  2. package/package.json +8 -6
  3. package/src/cli/commands/check.ts +41 -26
  4. package/src/cli/commands/hook.ts +77 -105
  5. package/src/cli/commands/init.ts +35 -9
  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 +35 -9
  9. package/src/cli/hook-payload.ts +43 -0
  10. package/src/cli/index.ts +15 -51
  11. package/src/cli/scaffold/harness-config.ts +48 -8
  12. package/src/cli/templates/hooks.ts +51 -27
  13. package/src/cli/templates/rules.ts +34 -49
  14. package/src/cli/templates/skill.ts +46 -35
  15. package/src/core/boundary/audit.ts +383 -0
  16. package/src/core/boundary/evaluator.ts +299 -178
  17. package/src/core/boundary/staged-auditor.ts +188 -34
  18. package/src/core/config/domain-ownership.ts +47 -0
  19. package/src/core/config/domain-registration.ts +141 -0
  20. package/src/core/config/loader.ts +82 -54
  21. package/src/core/config/schema.ts +24 -46
  22. package/src/core/database/client.ts +2 -0
  23. package/src/core/database/repositories/dependency.repository.ts +326 -543
  24. package/src/core/database/repositories/domain.repository.ts +48 -4
  25. package/src/core/database/repositories/file.repository.ts +10 -0
  26. package/src/core/database/repositories/symbol.repository.ts +97 -259
  27. package/src/core/database/repository.ts +138 -24
  28. package/src/core/database/schema.ts +28 -33
  29. package/src/core/discovery/declarative-routes.ts +69 -0
  30. package/src/core/discovery/framework-detector.ts +149 -0
  31. package/src/core/discovery/navigation.ts +269 -0
  32. package/src/core/discovery/topology-detector.ts +153 -170
  33. package/src/core/errors.ts +19 -0
  34. package/src/core/ingestion/pipeline.ts +378 -212
  35. package/src/core/parser/behavioral-analyzer.ts +26 -22
  36. package/src/core/parser/boundary-tracker.ts +15 -0
  37. package/src/core/parser/extractors/base.ts +16 -4
  38. package/src/core/parser/extractors/csharp.ts +9 -5
  39. package/src/core/parser/extractors/django-routing.ts +163 -0
  40. package/src/core/parser/extractors/django-semantic.ts +400 -516
  41. package/src/core/parser/extractors/elysia-semantic.ts +172 -496
  42. package/src/core/parser/extractors/express-semantic.ts +195 -398
  43. package/src/core/parser/extractors/fastapi-semantic.ts +182 -399
  44. package/src/core/parser/extractors/fastify-semantic.ts +216 -732
  45. package/src/core/parser/extractors/flask-semantic.ts +92 -388
  46. package/src/core/parser/extractors/go-routing.ts +344 -0
  47. package/src/core/parser/extractors/go-semantic.ts +210 -508
  48. package/src/core/parser/extractors/go.ts +6 -3
  49. package/src/core/parser/extractors/graphql-entrypoint.ts +146 -0
  50. package/src/core/parser/extractors/hono-semantic.ts +132 -530
  51. package/src/core/parser/extractors/java.ts +7 -5
  52. package/src/core/parser/extractors/laravel-routing.ts +263 -0
  53. package/src/core/parser/extractors/laravel-semantic.ts +169 -333
  54. package/src/core/parser/extractors/manifest-helpers.ts +64 -0
  55. package/src/core/parser/extractors/mcp-cli-dispatch.ts +268 -0
  56. package/src/core/parser/extractors/mcp-cli-semantic.ts +84 -336
  57. package/src/core/parser/extractors/nestjs-semantic.ts +238 -510
  58. package/src/core/parser/extractors/nextjs-semantic.ts +164 -0
  59. package/src/core/parser/extractors/php-ast-helpers.ts +51 -0
  60. package/src/core/parser/extractors/php.ts +17 -1
  61. package/src/core/parser/extractors/python-route-ast.ts +249 -0
  62. package/src/core/parser/extractors/python.ts +9 -8
  63. package/src/core/parser/extractors/registry.ts +28 -5
  64. package/src/core/parser/extractors/route-prefixes.ts +43 -0
  65. package/src/core/parser/extractors/ruby.ts +10 -7
  66. package/src/core/parser/extractors/rust.ts +35 -17
  67. package/src/core/parser/extractors/semantic-extractor.interface.ts +3 -1
  68. package/src/core/parser/extractors/symfony-routing.ts +114 -0
  69. package/src/core/parser/extractors/symfony-semantic.ts +75 -262
  70. package/src/core/parser/extractors/typescript-bindings.ts +333 -0
  71. package/src/core/parser/extractors/typescript-compiler-fallback.ts +380 -0
  72. package/src/core/parser/extractors/typescript-fallback.ts +207 -0
  73. package/src/core/parser/extractors/typescript-route-context.ts +58 -0
  74. package/src/core/parser/extractors/typescript.ts +36 -216
  75. package/src/core/parser/implementation-fingerprint.ts +97 -0
  76. package/src/core/parser/language-capabilities.ts +23 -7
  77. package/src/core/parser/schema/providers/laravel-migration-provider.ts +77 -51
  78. package/src/core/parser/schema/schema-provider-registry.ts +1 -3
  79. package/src/core/parser/schema/schema-provider.interface.ts +2 -1
  80. package/src/core/parser/semantic-revision.ts +3 -0
  81. package/src/core/parser/static-string.ts +51 -0
  82. package/src/core/parser/wasm-loader.ts +6 -2
  83. package/src/core/resolver/ast-method-tracer.ts +230 -0
  84. package/src/core/resolver/call-graph-helpers.ts +72 -0
  85. package/src/core/resolver/call-graph-tracer.ts +375 -311
  86. package/src/core/resolver/dependency-analysis.ts +593 -0
  87. package/src/core/resolver/import-candidates.ts +120 -0
  88. package/src/core/resolver/import-evidence.ts +88 -0
  89. package/src/core/resolver/import-resolver.ts +162 -181
  90. package/src/core/resolver/interpretation-inputs.ts +65 -0
  91. package/src/core/resolver/languages/go.ts +103 -0
  92. package/src/core/resolver/languages/managed.ts +200 -0
  93. package/src/core/resolver/languages/python.ts +133 -0
  94. package/src/core/resolver/languages/ruby.ts +40 -0
  95. package/src/core/resolver/languages/rust.ts +127 -0
  96. package/src/core/resolver/languages/shared.ts +74 -0
  97. package/src/core/resolver/module-resolver.ts +18 -7
  98. package/src/core/resolver/path-resolver.ts +6 -3
  99. package/src/core/resolver/polyglot-slice-tracer.ts +197 -0
  100. package/src/core/resolver/slice-catalog.ts +94 -0
  101. package/src/core/resolver/slice-format.ts +22 -0
  102. package/src/core/resolver/slice-selection.ts +237 -0
  103. package/src/core/resolver/symbol-impact.ts +477 -0
  104. package/src/core/resolver/symbol-locator.ts +82 -15
  105. package/src/core/resolver/vertical-slice-tracer.ts +57 -278
  106. package/src/core/resources/ignore.ts +21 -1
  107. package/src/core/resources/limits.ts +2 -1
  108. package/src/core/resources/source-files.ts +143 -20
  109. package/src/core/resources/source-inventory.ts +55 -0
  110. package/src/core/resources/work-queue.ts +167 -4
  111. package/src/core/retrieval/context-page.ts +116 -0
  112. package/src/core/retrieval/context.ts +457 -0
  113. package/src/core/retrieval/resolution-warnings.ts +21 -0
  114. package/src/core/retrieval/source-context.ts +448 -0
  115. package/src/core/retrieval/symbol-details.ts +453 -0
  116. package/src/core/retrieval/symbol-evidence.ts +97 -0
  117. package/src/core/retrieval/typescript-references.ts +293 -0
  118. package/src/core/retrieval/universal-context.ts +182 -0
  119. package/src/core/telemetry/summary.ts +114 -0
  120. package/src/core/telemetry/telemetry.ts +225 -37
  121. package/src/index.ts +0 -3
  122. package/src/mcp/formatters/compact-text.ts +439 -0
  123. package/src/mcp/resources-and-prompts.ts +253 -0
  124. package/src/mcp/schemas/boundary.ts +145 -0
  125. package/src/mcp/schemas/map.ts +250 -0
  126. package/src/mcp/schemas/shared.ts +52 -0
  127. package/src/mcp/schemas/slice.ts +60 -0
  128. package/src/mcp/schemas/symbol.ts +268 -0
  129. package/src/mcp/schemas.ts +5 -1105
  130. package/src/mcp/server.ts +263 -597
  131. package/src/mcp/tool-catalog.ts +331 -0
  132. package/src/mcp/tools/boundary.ts +69 -4
  133. package/src/mcp/tools/map.ts +126 -0
  134. package/src/mcp/tools/slice.ts +101 -3
  135. package/src/mcp/tools/symbol.ts +480 -26
  136. package/src/mcp/ui/app-client.ts +899 -0
  137. package/src/mcp/ui/app.html +478 -0
  138. package/src/mcp/workflow-playbooks.ts +181 -0
  139. package/src/mcp/workspace-boundary.ts +50 -0
  140. package/src/mcp/workspace-manager.ts +102 -18
  141. package/src/mcp/workspace-watcher.ts +38 -19
  142. package/src/types/index.ts +47 -53
  143. package/src/cli/commands/topology.ts +0 -161
  144. package/src/core/database/repositories/environment.repository.ts +0 -207
  145. package/src/core/parser/schema/providers/prisma-schema-provider.ts +0 -90
  146. package/src/core/session/session-manager.ts +0 -107
  147. package/src/core/topology/environment-detector.ts +0 -973
  148. package/src/core/topology/types.ts +0 -83
  149. package/src/mcp/tools/check-boundary.ts +0 -387
  150. package/src/mcp/tools/domain.ts +0 -40
  151. package/src/mcp/tools/feature.ts +0 -67
  152. package/src/mcp/tools/get-domain-catalog.ts +0 -226
  153. package/src/mcp/tools/get-environment-topology.ts +0 -138
  154. package/src/mcp/tools/get-feature-context.ts +0 -224
  155. package/src/mcp/tools/get-symbol-hotspots.ts +0 -54
  156. package/src/mcp/tools/get-symbol-impact.ts +0 -64
  157. package/src/mcp/tools/get-symbol.ts +0 -175
  158. package/src/mcp/tools/locate-symbol.ts +0 -196
  159. package/src/mcp/tools/register-domain.ts +0 -75
  160. package/src/mcp/tools/register-feature.ts +0 -110
  161. package/src/mcp/tools/trace-vertical-slice.ts +0 -80
package/src/mcp/server.ts CHANGED
@@ -1,36 +1,34 @@
1
+ import { runWorkspaceBoundary } from "./workspace-boundary.ts";
2
+ import { randomBytes } from "node:crypto";
3
+ import { buildUnindexedCatalog } from "./tools/map.ts";
1
4
  import { WorkspaceManager, resolveServerWorkspace, isWorkspaceInitialized, type WorkspaceLease } from "./workspace-manager.ts";
2
5
  import { RESOURCE_LIMITS } from "../core/resources/limits.ts";
3
6
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
4
7
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
8
  import {
6
9
  CallToolRequestSchema,
10
+ GetPromptRequestSchema,
11
+ ListPromptsRequestSchema,
12
+ ListResourcesRequestSchema,
13
+ ListResourceTemplatesRequestSchema,
7
14
  ListToolsRequestSchema,
15
+ ReadResourceRequestSchema,
8
16
  } from "@modelcontextprotocol/sdk/types.js";
9
- import { ConfigLoader } from "../core/config/loader.ts";
10
- import { SessionManager } from "../core/session/session-manager.ts";
11
- import { SeptumTelemetry } from "../core/telemetry/telemetry.ts";
12
- import { handleDomainTool } from "./tools/domain.ts";
13
- import { handleSymbolTool } from "./tools/symbol.ts";
14
- import { handleSliceTool } from "./tools/slice.ts";
15
- import { handleBoundaryTool } from "./tools/boundary.ts";
16
- import { handleFeatureTool } from "./tools/feature.ts";
17
-
18
17
  import {
19
- DomainToolSchema,
20
- SymbolToolSchema,
21
- SliceToolSchema,
22
- BoundaryToolSchema,
23
- FeatureToolSchema,
24
- } 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";
25
27
  import { SEPTUM_VERSION, checkRuntimeVersion } from "../utils/version-check.ts";
26
28
 
27
- const TOOL_SCHEMAS = {
28
- septum_domain: DomainToolSchema,
29
- septum_symbol: SymbolToolSchema,
30
- septum_slice: SliceToolSchema,
31
- septum_boundary: BoundaryToolSchema,
32
- septum_feature: FeatureToolSchema,
33
- };
29
+ function explicitWorkspaceAlias(record: Record<string, unknown>): unknown {
30
+ return record.workspace_path ?? record.workspacePath ?? record.workspace ?? record.project_root ?? record.projectRoot;
31
+ }
34
32
 
35
33
  export function extractPathHint(args: unknown): string | undefined {
36
34
  if (!args) return undefined;
@@ -51,14 +49,7 @@ export function extractPathHint(args: unknown): string | undefined {
51
49
  if (typeof args === "object" && args !== null) {
52
50
  const record = args as Record<string, any>;
53
51
 
54
- const explicitWorkspace =
55
- record.workspace_path ??
56
- record.workspacePath ??
57
- record.workspace ??
58
- record.project_root ??
59
- record.projectRoot ??
60
- record.target_path ??
61
- record.targetPath;
52
+ const explicitWorkspace = explicitWorkspaceAlias(record) ?? record.target_path ?? record.targetPath;
62
53
  if (typeof explicitWorkspace === "string" && explicitWorkspace.trim()) {
63
54
  return explicitWorkspace.trim();
64
55
  }
@@ -103,16 +94,16 @@ export function extractPathHint(args: unknown): string | undefined {
103
94
  return undefined;
104
95
  }
105
96
 
106
- function countLines(text: string): number {
107
- let count = 1;
108
- for (let i = 0; i < text.length; i++) {
109
- if (text.charCodeAt(i) === 10) count++;
110
- }
111
- return count;
112
- }
97
+ export const SEPTUM_SERVER_INSTRUCTIONS = `Septum indexes supported declarations, imports, domain policies and static entrypoints.
98
+ Guidelines for AI Coding Agents:
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.
100
+ 2. NAVIGATION: Call septum_map(action: 'catalog') for domain/file locations, import relationships, static entrypoints and index health.
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.
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.
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.`;
113
105
 
114
- export async function runMCPServer(): Promise<void> {
115
- const manager = new WorkspaceManager();
106
+ export function createMcpServer(manager: WorkspaceManager): Server {
116
107
 
117
108
  const server = new Server(
118
109
  {
@@ -122,593 +113,256 @@ export async function runMCPServer(): Promise<void> {
122
113
  {
123
114
  capabilities: {
124
115
  tools: {},
116
+ resources: {},
117
+ prompts: {},
125
118
  },
119
+ instructions: SEPTUM_SERVER_INSTRUCTIONS,
126
120
  }
127
121
  );
128
122
 
129
- server.setRequestHandler(ListToolsRequestSchema, async () => {
130
- return {
131
- tools: [
132
- {
133
- name: "septum_domain",
134
- description:
135
- "Domain Catalog, Registration & Environment Topology Engine. Manages macro architecture, domain topology, bounded-context registration, and infrastructure plane (Edge, Gateway, Host, Runtime, Storage, Telemetry). Token-efficient (< 400 tokens).",
136
- inputSchema: {
137
- type: "object",
138
- properties: {
139
- action: {
140
- type: "string",
141
- enum: ["catalog", "register", "topology"],
142
- default: "catalog",
143
- description: "Sub-operation to execute: 'catalog' (inspect domain/macro map), 'register' (dynamically register bounded-context domain), or 'topology' (6-layer infrastructure plane).",
144
- },
145
- domain: {
146
- type: "string",
147
- description: "Target domain name (e.g. 'orders', 'core'). If omitted in catalog action, returns project-wide Macro Semantic Map.",
148
- },
149
- detail_level: {
150
- type: "string",
151
- enum: ["compact", "full"],
152
- default: "compact",
153
- description: "Catalog detail level: 'compact' (default, token-efficient summary with file connections) or 'full' (includes full signatures).",
154
- },
155
- archetype_filter: {
156
- type: "string",
157
- description: "Optional archetype filter (e.g. 'service', 'model', 'controller', 'repository').",
158
- },
159
- file_filter: {
160
- type: "string",
161
- description: "Optional substring filter to inspect specific file(s) within the domain.",
162
- },
163
- root: {
164
- type: "string",
165
- description: "Root directory path for domain registration (action='register').",
166
- },
167
- description: {
168
- type: "string",
169
- description: "Architectural purpose of the domain (action='register').",
170
- },
171
- allowed_dependencies: {
172
- type: "array",
173
- items: { type: "string" },
174
- description: "List of domain names this domain is allowed to import (action='register').",
175
- },
176
- forbidden_dependencies: {
177
- type: "array",
178
- items: { type: "string" },
179
- description: "List of domain names strictly forbidden from being imported (action='register').",
180
- },
181
- archetypes: {
182
- type: "object",
183
- description: "Layer archetypes mapping (action='register').",
184
- },
185
- ingest_now: {
186
- type: "boolean",
187
- default: false,
188
- description: "Whether to immediately run AST ingestion on domain files upon registration.",
189
- },
190
- resolve: {
191
- type: "object",
192
- properties: {
193
- layer: {
194
- type: "string",
195
- enum: ["edge", "gateway", "host", "runtime", "storage", "telemetry"],
196
- },
197
- platform: { type: "string" },
198
- constraints: { type: "array", items: { type: "string" } },
199
- },
200
- description: "Record and verify infrastructure layer in SQLite SSOT (action='topology').",
201
- },
202
- resolve_node: {
203
- type: "object",
204
- properties: {
205
- id: { type: "string" },
206
- layer: { type: "string", enum: ["edge", "gateway", "host", "runtime", "storage", "telemetry"] },
207
- name: { type: "string" },
208
- platform: { type: "string" },
209
- domain_or_ip: { type: "string" },
210
- role: { type: "string" },
211
- connected_to: { type: "array", items: { type: "string" } },
212
- constraints: { type: "array", items: { type: "string" } },
213
- },
214
- description: "Record distributed topology node in SQLite SSOT (action='topology').",
215
- },
216
- refresh: {
217
- type: "boolean",
218
- description: "Force re-detection from codebase files, ignoring cached status (action='topology').",
219
- },
220
- workspace_path: {
221
- type: "string",
222
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
223
- },
224
- },
225
- required: [],
226
- },
227
- },
228
- {
229
- name: "septum_symbol",
230
- description:
231
- "Unified Symbol Engine: single entrypoint for symbol location, full contract inspection, refactoring blast radius (impact), and Single Responsibility / God Function complexity hotspots.",
232
- inputSchema: {
233
- type: "object",
234
- properties: {
235
- action: {
236
- type: "string",
237
- enum: ["locate", "inspect", "impact", "hotspots"],
238
- default: "locate",
239
- description: "Sub-operation: 'locate' (fuzzy search/error log resolution), 'inspect' (physical coordinates & signatures), 'impact' (blast radius & inbound callers), or 'hotspots' (complexity & SRP smells).",
240
- },
241
- query: {
242
- type: "string",
243
- description: "Symbol name, call syntax (e.g. 'OrderController::cancelOrder'), or search query (for locate, inspect, impact).",
244
- },
245
- domain: {
246
- type: "string",
247
- description: "Optional domain filter (e.g. 'orders').",
248
- },
249
- file_path: {
250
- type: "string",
251
- description: "Exact indexed repository-relative file path. Use it to select one candidate when names are ambiguous.",
252
- },
253
- symbol_ref: {
254
- type: "object",
255
- description: "Declaration reference returned by locate/inspect or a full catalog. Selects an overload for locate/inspect; stale indexed fingerprints are refused.",
256
- properties: {
257
- file_path: { type: "string", minLength: 1 },
258
- language: { type: "string", minLength: 1 },
259
- name: { type: "string", minLength: 1 },
260
- kind: { type: "string", minLength: 1 },
261
- signature: { type: "string" },
262
- start_line: { type: "integer", minimum: 1 },
263
- end_line: { type: "integer", minimum: 1 },
264
- indexed_content_hash: { type: "string", minLength: 1 },
265
- container: { type: "string" },
266
- receiver: { type: "string" },
267
- },
268
- required: ["file_path", "language", "name", "kind", "signature", "start_line", "end_line", "indexed_content_hash"],
269
- },
270
- include_source: {
271
- type: "boolean",
272
- default: false,
273
- description: "For action='inspect', include a bounded source slice only when the indexed file fingerprint still matches disk.",
274
- },
275
- source_start_line: {
276
- type: "number",
277
- minimum: 1,
278
- description: "First line to return within the selected symbol range (action='inspect').",
279
- },
280
- source_line_limit: {
281
- type: "number",
282
- minimum: 1,
283
- maximum: 200,
284
- default: 120,
285
- description: "Maximum source lines returned (action='inspect', capped at 200).",
286
- },
287
- include_dependencies: {
288
- type: "boolean",
289
- default: true,
290
- description: "Whether to include injected dependencies and outbound calls (action='inspect').",
291
- },
292
- min_lines: {
293
- type: "number",
294
- description: "Minimum physical lines of code threshold (action='hotspots', default: 30).",
295
- },
296
- min_nesting: {
297
- type: "number",
298
- description: "Minimum control-flow nesting depth threshold (action='hotspots').",
299
- },
300
- kind: {
301
- type: "string",
302
- description: "Filter symbol kind: 'function' | 'method' | 'class' | 'struct' | 'interface' (action='hotspots').",
303
- },
304
- sort_by: {
305
- type: "string",
306
- enum: ["risk_score", "line_count", "lines", "nesting"],
307
- default: "risk_score",
308
- description: "Sorting criteria for hotspots (action='hotspots').",
309
- },
310
- limit: {
311
- type: "number",
312
- description: "Maximum results to return (default: 10 for locate, 30 for hotspots).",
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: [],
320
- },
321
- },
322
- {
323
- name: "septum_slice",
324
- description:
325
- "Vertical Execution Slice Tracer: traces end-to-end execution flow (Ingress -> Validation -> Controller -> Service -> Repository -> Entity) from route URI, controller action, or high-level intent without guessing files.",
326
- inputSchema: {
327
- type: "object",
328
- properties: {
329
- query: {
330
- type: "string",
331
- description: "Route URI (e.g. 'POST /orders/{id}/pay'), action (e.g. 'OrderController@pay'), or high-level task intent.",
332
- },
333
- max_depth: {
334
- type: "number",
335
- default: 5,
336
- minimum: 1,
337
- maximum: 8,
338
- description: "Maximum depth to trace (default: 5, min: 1, max: 8). Use 6-8 for deep Event/Job/Queue traces.",
339
- },
340
- workspace_path: {
341
- type: "string",
342
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
343
- },
344
- },
345
- required: ["query"],
346
- },
347
- },
348
- {
349
- name: "septum_boundary",
350
- description:
351
- "Architecture Guard & Circular Dependency Gate: Pre-flight boundary check verifying proposed file edits, additions, and imports against domain rules and feature touchpoints, or auditing the entire repository / staged files for cross-domain and circular dependencies.",
352
- inputSchema: {
353
- type: "object",
354
- properties: {
355
- scope: {
356
- type: "string",
357
- enum: ["file", "staged", "all", "domain"],
358
- description: "Audit scope: 'file' requires file_path or non-empty file_paths; 'staged', 'all', and 'domain' reject file targets and proposed_imports. 'domain' requires a registered domain; 'all' rejects domain filters. If omitted, infer file/staged/domain/all from arguments.",
359
- },
360
- file_path: {
361
- type: "string",
362
- description: "Path of the file being edited or created (scope='file' only). Use either file_path or file_paths.",
363
- },
364
- file_paths: {
365
- type: "array",
366
- items: { type: "string" },
367
- description: "Non-empty list of file paths for batch proposed-import checks (scope='file' only). Use either file_path or file_paths.",
368
- },
369
- proposed_imports: {
370
- type: "array",
371
- items: { type: "string" },
372
- description: "List of proposed import statements or target symbols (scope='file' only).",
373
- },
374
- domain: {
375
- type: "string",
376
- description: "Registered domain name, required for scope='domain'; optional for staged/file checks. Explicit scope='all' does not accept a domain filter.",
377
- },
378
- feature_key: {
379
- type: "string",
380
- description: "Optional feature key to validate touchpoints against.",
381
- },
382
- workspace_path: {
383
- type: "string",
384
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
385
- },
386
- },
387
- required: [],
388
- },
389
- },
390
- {
391
- name: "septum_feature",
392
- description:
393
- "Active Touchpoint & Scope Lock Engine: manages feature task context, touchpoint locks (.septum/session.json), and session release to enforce surgical blast-radius boundaries.",
394
- inputSchema: {
395
- type: "object",
396
- properties: {
397
- action: {
398
- type: "string",
399
- enum: ["get", "lock", "release"],
400
- default: "get",
401
- description: "Feature lifecycle action: 'get' (retrieve feature context), 'lock' (register feature & establish active session lease), or 'release' (release active session lock).",
402
- },
403
- feature_key: {
404
- type: "string",
405
- description: "Unique feature identifier (e.g. 'checkout_flow'). Symmetrically accepts 'feature'.",
406
- },
407
- domain: {
408
- type: "string",
409
- description: "Bounded-context domain for this feature (action='lock').",
410
- },
411
- description: {
412
- type: "string",
413
- description: "Scope and rationale for the feature (action='lock').",
414
- },
415
- allowed_touchpoints: {
416
- type: "array",
417
- items: { type: "string" },
418
- description: "Permitted file paths or glob patterns (action='lock').",
419
- },
420
- reuse_symbols: {
421
- type: "array",
422
- items: { type: "string" },
423
- description: "Mandatory reusable symbols (action='lock').",
424
- },
425
- input_contract: {
426
- type: "object",
427
- description: "Expected input payload / DTO schema (action='lock').",
428
- },
429
- output_contract: {
430
- type: "object",
431
- description: "Expected output response contract (action='lock').",
432
- },
433
- force: {
434
- type: "boolean",
435
- default: false,
436
- description: "Force release session (action='release').",
437
- },
438
- workspace_path: {
439
- type: "string",
440
- description: "Explicit workspace root path. Specifies the target project root in multi-root environments.",
441
- },
442
- },
443
- 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),
444
150
  },
445
- },
446
- ],
447
- };
151
+ workspaceRoot: manager.initialRoot ?? null,
152
+ emitStderr: false,
153
+ });
154
+ throw error;
155
+ }
156
+ }, manager.initialRoot);
448
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
+ }));
449
166
 
450
167
  server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
451
168
  const { name, arguments: args } = request.params;
452
169
  const startTime = performance.now();
453
- let lease: WorkspaceLease | undefined;
454
- try {
455
- extra?.signal?.throwIfAborted();
456
- const schema = TOOL_SCHEMAS[name as keyof typeof TOOL_SCHEMAS];
457
- if (!schema) throw new Error(`Unknown tool: '${name}'`);
458
- const validated = schema.safeParse(args ?? {});
459
- if (!validated.success) throw new Error(`[Septum Validation Error] Invalid arguments for ${name}: ${validated.error.message}`);
460
- const record = (validated.data ?? {}) as Record<string, any>;
461
- const raw = (args ?? {}) as Record<string, any>;
462
- const workspacePath = record.workspace_path ?? raw.workspace_path ?? raw.workspacePath ?? raw.workspace ?? raw.project_root ?? raw.projectRoot;
463
- const knownRoots = manager.activeRoots;
464
- if (manager.initialRoot && !knownRoots.includes(manager.initialRoot)) {
465
- knownRoots.unshift(manager.initialRoot);
466
- }
467
- const fallbackRoot = manager.initialRoot || manager.lastRoot;
468
- const root = resolveServerWorkspace({
469
- workspacePath,
470
- filePath: workspacePath ? undefined : extractPathHint(args),
471
- fallbackRoot,
472
- knownRoots,
473
- });
474
-
475
- if (!isWorkspaceInitialized(root)) {
476
- if (name === "septum_domain" && (!record.action || record.action === "catalog")) {
477
- const runtimeVersion = await checkRuntimeVersion();
478
- let agentGuidance =
479
- "Panggil tool 'septum_domain(action: \"register\", name: \"core\", root: \"src\", ingest_now: true)' untuk mendaftarkan dan mengindeks domain utama secara otomatis, atau jalankan 'septum init' di terminal workspace.";
480
- if (runtimeVersion.update_available) {
481
- agentGuidance += ` Update available: v${runtimeVersion.server_version} -> v${runtimeVersion.latest_version}. Recommend running '${runtimeVersion.upgrade_command}' and reloading the MCP server if schema/features differ.`;
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;
482
192
  }
483
- const diagnostic: Record<string, any> = {
484
- status: "NOT_INDEXED",
485
- total_domains: 0,
486
- runtime_version: runtimeVersion,
487
- message: `Workspace '${root}' belum diinisialisasi dengan Septum. Jalankan 'septum init' terlebih dahulu di terminal workspace.`,
488
- suggested_action: {
489
- tool: "septum_domain",
490
- params: {
491
- action: "register",
492
- name: "core",
493
- root: "src",
494
- ingest_now: true,
495
- },
496
- },
497
- agent_guidance: agentGuidance,
498
- ...(runtimeVersion.update_available
499
- ? {
500
- agent_instruction: `Update available: v${runtimeVersion.server_version} -> v${runtimeVersion.latest_version}. Recommend running '${runtimeVersion.upgrade_command}' and reloading the MCP server if schema/features differ.`,
501
- }
502
- : {}),
503
- };
504
- return {
505
- content: [
506
- {
507
- type: "text",
508
- text: JSON.stringify(diagnostic, null, 2),
509
- },
510
- ],
511
- metadata: diagnostic,
512
- runtime_version: runtimeVersion,
513
- };
514
- }
515
- const isRegistration = name === "septum_domain" && record.action === "register";
516
- if (!isRegistration) {
517
- return {
518
- isError: true,
519
- content: [
520
- {
521
- type: "text",
522
- text: `[Septum MCP Error] Workspace '${root}' belum diinisialisasi. Jalankan 'septum init' di terminal workspace atau gunakan tool 'septum_domain' dengan action='register' untuk mendaftarkan domain.`,
523
- },
524
- ],
525
- };
526
- }
527
- }
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;
204
+ }
205
+ } catch {
206
+ // Non-JSON text content; leave structuredContent unset
207
+ }
208
+ }
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
+ };
528
237
 
529
- extra?.signal?.throwIfAborted();
530
- lease = manager.acquire(root);
531
- const ctx = lease.context;
532
- await ctx.ready;
533
- extra?.signal?.throwIfAborted();
534
- await ctx.watcher.flush(true, extra?.signal);
535
- if (ctx.repo.getMeta("sync_error")) throw new Error(`Workspace index synchronization failed: ${ctx.repo.getMeta("sync_error")}`);
536
- ctx.config = ConfigLoader.load(undefined, ctx.root);
537
- ctx.evaluator.getResolver().setRepository(ctx.repo);
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
+ };
538
246
 
539
- let activeSession = null;
540
- let sessionCorruptError: Error | null = null;
541
- try {
542
- activeSession = SessionManager.getActiveSession(ctx.root);
543
- } catch (err: any) {
544
- sessionCorruptError = err instanceof Error ? err : new Error(String(err));
545
- }
546
- const sessionPayload = activeSession
547
- ? { feature_key: activeSession.feature_key, domain: activeSession.domain }
548
- : null;
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
+ });
549
272
 
550
- const executeTool = async () => {
551
- // 5 Unified Tools Handlers
552
- if (name === "septum_domain") {
553
- const parsed = DomainToolSchema.safeParse(args ?? {});
554
- if (!parsed.success) {
555
- return {
556
- isError: true,
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({
557
278
  content: [
558
279
  {
559
280
  type: "text",
560
- text: `[Septum Validation Error] Invalid arguments for ${name}: ${parsed.error.message}`,
281
+ text: JSON.stringify(diagnostic, null, 2),
561
282
  },
562
283
  ],
563
- };
284
+ structuredContent: diagnostic,
285
+ metadata: diagnostic,
286
+ runtime_version: runtimeVersion,
287
+ });
564
288
  }
565
- return await handleDomainTool(ctx.repo, ctx.config, parsed.data, ctx.root, extra?.signal);
566
- } else if (name === "septum_symbol") {
567
- const parsed = SymbolToolSchema.safeParse(args ?? {});
568
- if (!parsed.success) {
569
- return {
289
+ const isRegistration = name === "septum_map" && "action" in record && record.action === "register";
290
+ if (!isRegistration) {
291
+ return finish({
570
292
  isError: true,
571
293
  content: [
572
294
  {
573
295
  type: "text",
574
- text: `[Septum Validation Error] Invalid arguments for ${name}: ${parsed.error.message}`,
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.`,
575
297
  },
576
298
  ],
577
- };
299
+ });
578
300
  }
579
- return await handleSymbolTool(ctx.repo, ctx.config, parsed.data, ctx.pipeline, ctx.root);
580
- } else if (name === "septum_slice") {
581
- const parsed = SliceToolSchema.safeParse(args ?? {});
582
- if (!parsed.success) {
583
- return {
584
- isError: true,
585
- content: [
586
- {
587
- type: "text",
588
- text: `[Septum Validation Error] Invalid arguments for ${name}: ${parsed.error.message}`,
589
- },
590
- ],
591
- };
592
- }
593
- return handleSliceTool(ctx.repo, ctx.config, parsed.data, ctx.root, extra?.signal);
594
- } else if (name === "septum_boundary") {
595
- if (sessionCorruptError) {
596
- return {
597
- isError: true,
598
- content: [
599
- {
600
- type: "text",
601
- text: `[Septum Session Error] Active feature session in '.septum/session.json' is corrupted or invalid: ${sessionCorruptError.message}. Release it explicitly with 'septum_feature({action: "release", force: true})' before evaluating boundaries.`,
602
- },
603
- ],
604
- };
605
- }
606
- const parsed = BoundaryToolSchema.safeParse(args ?? {});
607
- if (!parsed.success) {
608
- return {
609
- isError: true,
610
- content: [
611
- {
612
- type: "text",
613
- text: `[Septum Validation Error] Invalid arguments for ${name}: ${parsed.error.message}`,
614
- },
615
- ],
616
- };
617
- }
618
- return await handleBoundaryTool(ctx.evaluator, ctx.config, parsed.data, ctx.repo, ctx.root);
619
- } else if (name === "septum_feature") {
620
- const parsed = FeatureToolSchema.safeParse(args ?? {});
621
- if (!parsed.success) {
622
- return {
623
- isError: true,
624
- content: [
625
- {
626
- type: "text",
627
- text: `[Septum Validation Error] Invalid arguments for ${name}: ${parsed.error.message}`,
628
- },
629
- ],
630
- };
631
- }
632
- if (sessionCorruptError && (parsed.data.action !== "release" || !parsed.data.force)) {
633
- return {
634
- isError: true,
635
- content: [
636
- {
637
- type: "text",
638
- text: `[Septum Session Error] Active feature session in '.septum/session.json' is corrupted or invalid: ${sessionCorruptError.message}. Release it explicitly with 'septum_feature({action: "release", force: true})'.`,
639
- },
640
- ],
641
- };
642
- }
643
- extra?.signal?.throwIfAborted();
644
- return await handleFeatureTool(ctx.repo, ctx.config, parsed.data, ctx.root);
645
- } else {
646
- throw new Error(`Unknown tool: '${name}'`);
647
301
  }
648
- };
649
-
650
- try {
651
- const response = await manager.runTool(executeTool, extra?.signal);
652
- const durationMs = Math.round(performance.now() - startTime);
653
-
654
- let bytesOut = 0;
655
- let linesOut = 0;
656
- if (Array.isArray(response?.content)) {
657
- for (const item of response.content) {
658
- if (typeof item.text === "string") {
659
- bytesOut += Buffer.byteLength(item.text, "utf8");
660
- linesOut += countLines(item.text);
661
- }
662
- }
663
- }
664
-
665
- SeptumTelemetry.recordToolCall({
666
- event: "tool_call_completed",
667
- tool: name,
668
- duration_ms: durationMs,
669
- input: (args as Record<string, any>) ?? {},
670
- metrics: { bytes_out: bytesOut, lines_out: linesOut },
671
- session: sessionPayload,
672
- status: (response as { isError?: boolean } | undefined)?.isError ? "error" : "success",
673
- }, ctx.root);
674
-
675
- return response;
676
- } catch (err) {
677
- const durationMs = Math.round(performance.now() - startTime);
678
- const errorInstance = err instanceof Error ? err : new Error(String(err));
679
302
 
680
- SeptumTelemetry.recordToolCall({
681
- event: "tool_call_failed",
682
- tool: name,
683
- duration_ms: durationMs,
684
- input: (args as Record<string, any>) ?? {},
685
- session: sessionPayload,
686
- status: "error",
687
- error: {
688
- message: errorInstance.message,
689
- stack: errorInstance.stack,
690
- },
691
- }, ctx.root);
692
-
693
- return {
694
- isError: true,
695
- content: [
696
- {
697
- type: "text",
698
- text: `[Septum MCP Error] ${errorInstance.message}`,
699
- },
700
- ],
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");
701
311
  };
702
- }
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);
703
328
  } catch (error) {
704
- return {isError: true, content: [{type: "text" as const, text: `[Septum MCP Error] ${error instanceof Error ? error.message : String(error)}`}]};
705
- } 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);
706
339
  });
707
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);
708
350
  const transport = new StdioServerTransport();
351
+ void checkRuntimeVersion().catch(() => {});
709
352
 
710
353
  let stopping = false;
711
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
+ };
712
366
  const cleanup = () => {
713
367
  if (stopping) return;
714
368
  stopping = true;
@@ -719,8 +373,7 @@ export async function runMCPServer(): Promise<void> {
719
373
  }, RESOURCE_LIMITS.shutdownMs);
720
374
  void (async () => {
721
375
  try {
722
- await server.close();
723
- await manager.close();
376
+ await closeResources();
724
377
  clearTimeout(deadline);
725
378
  console.error("[Septum MCP] All workspace resources closed cleanly.");
726
379
  process.exit(0);
@@ -736,15 +389,26 @@ export async function runMCPServer(): Promise<void> {
736
389
  process.stdin.once("end", cleanup);
737
390
  process.stdin.once("close", cleanup);
738
391
  server.onclose = cleanup;
739
- await server.connect(transport);
740
392
  try {
741
- const initialRoot = resolveServerWorkspace({initial:true});
742
- manager.initialRoot = initialRoot;
743
- manager.lastRoot = initialRoot;
393
+ await server.connect(transport);
744
394
  if (isWorkspaceInitialized(initialRoot)) {
745
395
  const initial = manager.acquire(initialRoot);
746
- 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
+ }
747
410
  }
411
+ if (stopping) return;
748
412
  if (process.env.SEPTUM_MEMORY_DIAGNOSTICS === "1") {
749
413
  memoryTimer = setInterval(() => {
750
414
  const sample = { ...process.memoryUsage(), workspaces: manager.size, watches: manager.watchCount, pending_paths: manager.pendingPaths, sync_duration_ms: manager.syncDurationMs };
@@ -757,7 +421,9 @@ export async function runMCPServer(): Promise<void> {
757
421
  memoryTimer.unref();
758
422
  }
759
423
  } catch (error) {
760
- await manager.close();
424
+ if (stopping) return;
425
+ stopping = true;
426
+ await closeResources();
761
427
  throw error;
762
428
  }
763
429