sentinelayer-cli 0.6.2 → 0.8.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 (159) hide show
  1. package/README.md +996 -996
  2. package/bin/create-sentinelayer.js +5 -5
  3. package/bin/sentinelayer-cli.js +4 -4
  4. package/bin/sl.js +5 -5
  5. package/package.json +64 -63
  6. package/src/agents/jules/config/definition.js +160 -160
  7. package/src/agents/jules/config/system-prompt.js +182 -182
  8. package/src/agents/jules/error-intake.js +51 -51
  9. package/src/agents/jules/fix-cycle.js +17 -17
  10. package/src/agents/jules/loop.js +457 -450
  11. package/src/agents/jules/pulse.js +10 -10
  12. package/src/agents/jules/stream.js +187 -186
  13. package/src/agents/jules/swarm/file-scanner.js +74 -74
  14. package/src/agents/jules/swarm/index.js +11 -11
  15. package/src/agents/jules/swarm/orchestrator.js +362 -362
  16. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  17. package/src/agents/jules/swarm/sub-agent.js +311 -309
  18. package/src/agents/jules/tools/aidenid-email.js +189 -189
  19. package/src/agents/jules/tools/auth-audit.js +1699 -1691
  20. package/src/agents/jules/tools/dispatch.js +340 -335
  21. package/src/agents/jules/tools/file-edit.js +2 -2
  22. package/src/agents/jules/tools/file-read.js +2 -2
  23. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  24. package/src/agents/jules/tools/glob.js +2 -2
  25. package/src/agents/jules/tools/grep.js +2 -2
  26. package/src/agents/jules/tools/index.js +29 -29
  27. package/src/agents/jules/tools/path-guards.js +2 -2
  28. package/src/agents/jules/tools/runtime-audit.js +507 -507
  29. package/src/agents/jules/tools/shell.js +2 -2
  30. package/src/agents/jules/tools/url-policy.js +100 -100
  31. package/src/agents/persona-visuals.js +64 -61
  32. package/src/agents/shared-tools/dispatch-core.js +320 -315
  33. package/src/agents/shared-tools/file-edit.js +180 -180
  34. package/src/agents/shared-tools/file-read.js +100 -100
  35. package/src/agents/shared-tools/glob.js +168 -168
  36. package/src/agents/shared-tools/grep.js +228 -228
  37. package/src/agents/shared-tools/index.js +46 -46
  38. package/src/agents/shared-tools/path-guards.js +161 -161
  39. package/src/agents/shared-tools/shell.js +383 -383
  40. package/src/ai/aidenid.js +1021 -1009
  41. package/src/ai/client.js +553 -553
  42. package/src/ai/domain-target-store.js +268 -268
  43. package/src/ai/identity-store.js +270 -270
  44. package/src/ai/proxy.js +137 -137
  45. package/src/ai/site-store.js +145 -145
  46. package/src/audit/agents/architecture.js +180 -180
  47. package/src/audit/agents/compliance.js +179 -179
  48. package/src/audit/agents/documentation.js +165 -165
  49. package/src/audit/agents/performance.js +145 -145
  50. package/src/audit/agents/security.js +215 -215
  51. package/src/audit/agents/testing.js +172 -172
  52. package/src/audit/orchestrator.js +557 -557
  53. package/src/audit/package.js +204 -204
  54. package/src/audit/registry.js +284 -284
  55. package/src/audit/replay.js +103 -103
  56. package/src/auth/gate.js +400 -371
  57. package/src/auth/http.js +681 -611
  58. package/src/auth/service.js +1106 -1106
  59. package/src/auth/session-store.js +813 -813
  60. package/src/cli.js +257 -252
  61. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  62. package/src/commands/ai/provision-governance.js +1272 -1272
  63. package/src/commands/ai/shared.js +147 -147
  64. package/src/commands/ai.js +11 -11
  65. package/src/commands/apply.js +12 -12
  66. package/src/commands/audit.js +1171 -1166
  67. package/src/commands/auth.js +419 -419
  68. package/src/commands/chat.js +191 -191
  69. package/src/commands/config.js +184 -184
  70. package/src/commands/cost.js +311 -311
  71. package/src/commands/daemon/core.js +850 -850
  72. package/src/commands/daemon/extended.js +1048 -1048
  73. package/src/commands/daemon/shared.js +213 -213
  74. package/src/commands/daemon.js +11 -11
  75. package/src/commands/guide.js +174 -174
  76. package/src/commands/ingest.js +58 -58
  77. package/src/commands/init.js +55 -55
  78. package/src/commands/legacy-args.js +10 -10
  79. package/src/commands/mcp.js +461 -461
  80. package/src/commands/omargate.js +29 -29
  81. package/src/commands/persona.js +20 -20
  82. package/src/commands/plugin.js +260 -260
  83. package/src/commands/policy.js +132 -132
  84. package/src/commands/prompt.js +238 -238
  85. package/src/commands/review.js +704 -704
  86. package/src/commands/scan.js +872 -872
  87. package/src/commands/session.js +590 -0
  88. package/src/commands/spec.js +778 -716
  89. package/src/commands/swarm.js +651 -651
  90. package/src/commands/telemetry.js +202 -202
  91. package/src/commands/watch.js +511 -511
  92. package/src/config/agent-dictionary.js +182 -182
  93. package/src/config/io.js +56 -56
  94. package/src/config/paths.js +18 -18
  95. package/src/config/schema.js +55 -55
  96. package/src/config/service.js +184 -184
  97. package/src/cost/budget.js +235 -235
  98. package/src/cost/history.js +188 -188
  99. package/src/cost/tracker.js +171 -171
  100. package/src/daemon/artifact-lineage.js +534 -534
  101. package/src/daemon/assignment-ledger.js +966 -770
  102. package/src/daemon/ast-parser-layer.js +258 -258
  103. package/src/daemon/budget-governor.js +633 -633
  104. package/src/daemon/callgraph-overlay.js +646 -646
  105. package/src/daemon/error-worker.js +1209 -626
  106. package/src/daemon/fix-cycle.js +384 -377
  107. package/src/daemon/hybrid-mapper.js +929 -929
  108. package/src/daemon/ingest-refresh.js +10 -9
  109. package/src/daemon/jira-lifecycle.js +767 -632
  110. package/src/daemon/operator-control.js +657 -657
  111. package/src/daemon/pulse.js +327 -327
  112. package/src/daemon/reliability-lane.js +471 -471
  113. package/src/daemon/scope-engine.js +1068 -0
  114. package/src/daemon/watchdog.js +971 -971
  115. package/src/events/schema.js +190 -0
  116. package/src/guide/generator.js +316 -316
  117. package/src/ingest/engine.js +918 -918
  118. package/src/interactive/index.js +97 -97
  119. package/src/legacy-cli.js +3161 -2994
  120. package/src/mcp/registry.js +695 -695
  121. package/src/memory/blackboard.js +301 -301
  122. package/src/memory/retrieval.js +581 -581
  123. package/src/plugin/manifest.js +553 -553
  124. package/src/policy/packs.js +144 -144
  125. package/src/prompt/generator.js +136 -118
  126. package/src/review/ai-review.js +679 -679
  127. package/src/review/local-review.js +1351 -1305
  128. package/src/review/omargate-interactive.js +68 -68
  129. package/src/review/omargate-orchestrator.js +404 -300
  130. package/src/review/persona-prompts.js +296 -296
  131. package/src/review/replay.js +235 -235
  132. package/src/review/report.js +664 -664
  133. package/src/review/scan-modes.js +48 -42
  134. package/src/review/spec-binding.js +487 -487
  135. package/src/scaffold/generator.js +67 -67
  136. package/src/scaffold/templates.js +150 -150
  137. package/src/scan/generator.js +418 -418
  138. package/src/scan/gh-secrets.js +107 -107
  139. package/src/session/agent-registry.js +352 -0
  140. package/src/session/daemon.js +801 -0
  141. package/src/session/paths.js +33 -0
  142. package/src/session/runtime-bridge.js +739 -0
  143. package/src/session/store.js +388 -0
  144. package/src/session/stream.js +325 -0
  145. package/src/spec/generator.js +619 -519
  146. package/src/spec/regenerate.js +237 -237
  147. package/src/spec/templates.js +91 -91
  148. package/src/swarm/dashboard.js +247 -247
  149. package/src/swarm/factory.js +363 -363
  150. package/src/swarm/pentest.js +934 -934
  151. package/src/swarm/registry.js +419 -419
  152. package/src/swarm/report.js +158 -158
  153. package/src/swarm/runtime.js +576 -576
  154. package/src/swarm/scenario-dsl.js +272 -272
  155. package/src/telemetry/ledger.js +302 -302
  156. package/src/telemetry/session-tracker.js +234 -234
  157. package/src/telemetry/sync.js +203 -203
  158. package/src/ui/command-hints.js +13 -13
  159. package/src/ui/markdown.js +220 -220
@@ -1,695 +1,695 @@
1
- import fsp from "node:fs/promises";
2
- import path from "node:path";
3
- import process from "node:process";
4
-
5
- import { z } from "zod";
6
-
7
- import { resolveOutputRoot } from "../config/service.js";
8
-
9
- /** MCP tool-registry schema version used by Sentinelayer CLI generated artifacts. */
10
- export const MCP_TOOL_REGISTRY_SCHEMA_VERSION = "1.0.0";
11
- /** MCP server-config schema version used by Sentinelayer CLI generated artifacts. */
12
- export const MCP_SERVER_CONFIG_SCHEMA_VERSION = "1.0.0";
13
- /** AIdenID adapter-contract schema version used by Sentinelayer CLI generated artifacts. */
14
- export const AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION = "1.0.0";
15
-
16
- const serverIdRegex = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/;
17
- const inputPlaceholderRegex = /^\{\{input\.[a-zA-Z0-9_.-]+\}\}$/;
18
-
19
- const jsonSchemaObject = z.object({
20
- type: z.literal("object"),
21
- properties: z.record(z.string(), z.any()).optional(),
22
- required: z.array(z.string()).optional(),
23
- additionalProperties: z.union([z.boolean(), z.any()]).optional(),
24
- });
25
-
26
- const mcpToolSchema = z
27
- .object({
28
- name: z
29
- .string()
30
- .min(1)
31
- .regex(/^[a-zA-Z0-9_.:-]+$/, "tool name must contain only [a-zA-Z0-9_.:-]"),
32
- title: z.string().min(1).optional(),
33
- description: z.string().min(1),
34
- input_schema: jsonSchemaObject,
35
- transport: z.object({
36
- type: z.enum(["http", "internal", "bridge"]),
37
- method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("POST"),
38
- url: z.string().min(1),
39
- timeout_ms: z.number().int().positive().optional(),
40
- auth: z
41
- .object({
42
- mode: z.enum(["bearer", "api_key", "oauth2", "none"]).default("bearer"),
43
- secret_ref: z.string().min(1).optional(),
44
- })
45
- .optional(),
46
- }),
47
- budgets: z
48
- .object({
49
- max_calls_per_run: z.number().int().positive().default(5),
50
- max_runtime_ms: z.number().int().positive().default(15000),
51
- })
52
- .optional(),
53
- security: z
54
- .object({
55
- requires_human_approval: z.boolean().default(false),
56
- kill_switch: z.enum(["enabled", "disabled"]).default("enabled"),
57
- scopes: z.array(z.string().min(1)).default([]),
58
- })
59
- .optional(),
60
- metadata: z.record(z.string(), z.any()).optional(),
61
- })
62
- .strict();
63
-
64
- const mcpRegistrySchema = z
65
- .object({
66
- version: z.string().min(1),
67
- generated_at: z.string().optional(),
68
- tools: z.array(mcpToolSchema).min(1),
69
- })
70
- .strict();
71
-
72
- const aidenIdProvisioningBindingSchema = z
73
- .object({
74
- tool_name: z
75
- .string()
76
- .min(1)
77
- .regex(/^[a-zA-Z0-9_.:-]+$/, "tool_name must contain only [a-zA-Z0-9_.:-]"),
78
- operation: z.literal("provision_email"),
79
- method: z.literal("POST"),
80
- path: z.literal("/v1/identities"),
81
- request_template: z
82
- .object({
83
- ttl_seconds: z.string().regex(inputPlaceholderRegex),
84
- tags: z.string().regex(inputPlaceholderRegex).optional(),
85
- policy: z.string().regex(inputPlaceholderRegex).optional(),
86
- })
87
- .strict(),
88
- response_contract: z
89
- .object({
90
- identity_id_path: z.string().min(1),
91
- email_path: z.string().min(1),
92
- expires_at_path: z.string().min(1),
93
- })
94
- .strict(),
95
- budgets: z
96
- .object({
97
- max_calls_per_run: z.number().int().positive().default(3),
98
- max_runtime_ms: z.number().int().positive().default(20000),
99
- })
100
- .strict()
101
- .default({
102
- max_calls_per_run: 3,
103
- max_runtime_ms: 20000,
104
- }),
105
- security: z
106
- .object({
107
- requires_human_approval: z.boolean().default(true),
108
- kill_switch: z.enum(["enabled", "disabled"]).default("enabled"),
109
- scopes: z.array(z.string().min(1)).default(["identity:create"]),
110
- })
111
- .strict()
112
- .default({
113
- requires_human_approval: true,
114
- kill_switch: "enabled",
115
- scopes: ["identity:create"],
116
- }),
117
- metadata: z.record(z.string(), z.any()).optional(),
118
- })
119
- .strict();
120
-
121
- const aidenIdAdapterContractSchema = z
122
- .object({
123
- version: z
124
- .literal(AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION)
125
- .default(AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION),
126
- provider: z.literal("aidenid"),
127
- generated_at: z.string().min(1),
128
- registry_file: z.string().min(1),
129
- transport: z
130
- .object({
131
- base_url: z.string().url(),
132
- timeout_ms: z.number().int().positive().default(15000),
133
- auth: z
134
- .object({
135
- mode: z.enum(["bearer", "api_key", "oauth2", "none"]).default("bearer"),
136
- secret_ref: z.string().min(1),
137
- })
138
- .strict(),
139
- })
140
- .strict(),
141
- tool_bindings: z.array(aidenIdProvisioningBindingSchema).min(1),
142
- })
143
- .strict();
144
-
145
- const mcpServerTransportSchema = z.discriminatedUnion("mode", [
146
- z
147
- .object({
148
- mode: z.literal("stdio"),
149
- command: z.string().min(1),
150
- args: z.array(z.string()).default([]),
151
- cwd: z.string().min(1).optional(),
152
- env: z.record(z.string(), z.string()).optional(),
153
- })
154
- .strict(),
155
- z
156
- .object({
157
- mode: z.literal("http"),
158
- url: z.string().min(1),
159
- timeout_ms: z.number().int().positive().default(15000),
160
- auth: z
161
- .object({
162
- mode: z.enum(["bearer", "api_key", "oauth2", "none"]).default("bearer"),
163
- secret_ref: z.string().min(1).optional(),
164
- audience: z.string().min(1).optional(),
165
- })
166
- .strict()
167
- .optional(),
168
- headers: z.record(z.string(), z.string()).optional(),
169
- })
170
- .strict()
171
- .superRefine((transport, ctx) => {
172
- if (!transport.auth) {
173
- return;
174
- }
175
- const mode = transport.auth.mode;
176
- if ((mode === "bearer" || mode === "oauth2") && !transport.auth.audience) {
177
- ctx.addIssue({
178
- code: z.ZodIssueCode.custom,
179
- path: ["auth", "audience"],
180
- message: "audience is required when auth.mode is bearer or oauth2.",
181
- });
182
- }
183
- }),
184
- ]);
185
-
186
- const mcpServerConfigSchema = z
187
- .object({
188
- version: z.literal(MCP_SERVER_CONFIG_SCHEMA_VERSION).default(MCP_SERVER_CONFIG_SCHEMA_VERSION),
189
- server_id: z.string().regex(serverIdRegex),
190
- registry_file: z.string().min(1),
191
- transport: mcpServerTransportSchema,
192
- budgets: z
193
- .object({
194
- max_calls_per_run: z.number().int().positive().default(20),
195
- max_runtime_ms: z.number().int().positive().default(60000),
196
- })
197
- .strict()
198
- .default({
199
- max_calls_per_run: 20,
200
- max_runtime_ms: 60000,
201
- }),
202
- security: z
203
- .object({
204
- requires_human_approval: z.boolean().default(true),
205
- allow_network: z.boolean().default(false),
206
- kill_switch: z.enum(["enabled", "disabled"]).default("enabled"),
207
- })
208
- .strict()
209
- .default({
210
- requires_human_approval: true,
211
- allow_network: false,
212
- kill_switch: "enabled",
213
- }),
214
- metadata: z.record(z.string(), z.any()).optional(),
215
- })
216
- .strict();
217
-
218
- /**
219
- * Build JSON schema for Sentinelayer MCP tool-registry documents.
220
- *
221
- * @returns {Record<string, any>}
222
- */
223
- export function buildMcpToolRegistrySchema() {
224
- return {
225
- $schema: "https://json-schema.org/draft/2020-12/schema",
226
- $id: "https://sentinelayer.com/schemas/mcp-tool-registry.schema.json",
227
- title: "Sentinelayer MCP Tool Registry",
228
- type: "object",
229
- additionalProperties: false,
230
- required: ["version", "tools"],
231
- properties: {
232
- version: {
233
- type: "string",
234
- description: "Registry schema version.",
235
- },
236
- generated_at: {
237
- type: "string",
238
- format: "date-time",
239
- },
240
- tools: {
241
- type: "array",
242
- minItems: 1,
243
- items: {
244
- type: "object",
245
- additionalProperties: false,
246
- required: ["name", "description", "input_schema", "transport"],
247
- properties: {
248
- name: {
249
- type: "string",
250
- pattern: "^[a-zA-Z0-9_.:-]+$",
251
- },
252
- title: {
253
- type: "string",
254
- },
255
- description: {
256
- type: "string",
257
- },
258
- input_schema: {
259
- type: "object",
260
- },
261
- transport: {
262
- type: "object",
263
- additionalProperties: false,
264
- required: ["type", "method", "url"],
265
- properties: {
266
- type: {
267
- type: "string",
268
- enum: ["http", "internal", "bridge"],
269
- },
270
- method: {
271
- type: "string",
272
- enum: ["GET", "POST", "PUT", "PATCH", "DELETE"],
273
- },
274
- url: {
275
- type: "string",
276
- },
277
- timeout_ms: {
278
- type: "integer",
279
- minimum: 1,
280
- },
281
- auth: {
282
- type: "object",
283
- additionalProperties: false,
284
- properties: {
285
- mode: {
286
- type: "string",
287
- enum: ["bearer", "api_key", "oauth2", "none"],
288
- },
289
- secret_ref: {
290
- type: "string",
291
- },
292
- },
293
- },
294
- },
295
- },
296
- budgets: {
297
- type: "object",
298
- additionalProperties: false,
299
- properties: {
300
- max_calls_per_run: {
301
- type: "integer",
302
- minimum: 1,
303
- },
304
- max_runtime_ms: {
305
- type: "integer",
306
- minimum: 1,
307
- },
308
- },
309
- },
310
- security: {
311
- type: "object",
312
- additionalProperties: false,
313
- properties: {
314
- requires_human_approval: {
315
- type: "boolean",
316
- },
317
- kill_switch: {
318
- type: "string",
319
- enum: ["enabled", "disabled"],
320
- },
321
- scopes: {
322
- type: "array",
323
- items: { type: "string" },
324
- },
325
- },
326
- },
327
- metadata: {
328
- type: "object",
329
- },
330
- },
331
- },
332
- },
333
- },
334
- };
335
- }
336
-
337
- /**
338
- * Create a secure-by-default MCP tool-registry template for AIdenID provisioning.
339
- *
340
- * @param {{ generatedAt?: string }} [options]
341
- * @returns {Record<string, any>}
342
- */
343
- export function buildAidenIdRegistryTemplate({ generatedAt = new Date().toISOString() } = {}) {
344
- return {
345
- version: MCP_TOOL_REGISTRY_SCHEMA_VERSION,
346
- generated_at: generatedAt,
347
- tools: [
348
- {
349
- name: "aidenid.provision_email",
350
- title: "AIdenID Provision Email Identity",
351
- description:
352
- "Provision an ephemeral email identity through AIdenID for autonomous agent workflows.",
353
- input_schema: {
354
- type: "object",
355
- additionalProperties: false,
356
- required: ["ttl_seconds"],
357
- properties: {
358
- ttl_seconds: {
359
- type: "integer",
360
- minimum: 60,
361
- maximum: 86400,
362
- description: "Identity TTL in seconds.",
363
- },
364
- tags: {
365
- type: "array",
366
- items: { type: "string" },
367
- },
368
- policy: {
369
- type: "object",
370
- additionalProperties: true,
371
- description: "Optional policy envelope passed to AIdenID.",
372
- },
373
- },
374
- },
375
- transport: {
376
- type: "http",
377
- method: "POST",
378
- url: "https://api.aidenid.com/v1/identities",
379
- timeout_ms: 15000,
380
- auth: {
381
- mode: "bearer",
382
- secret_ref: "AIDENID_API_KEY",
383
- },
384
- },
385
- budgets: {
386
- max_calls_per_run: 3,
387
- max_runtime_ms: 20000,
388
- },
389
- security: {
390
- requires_human_approval: true,
391
- kill_switch: "enabled",
392
- scopes: ["identity:create"],
393
- },
394
- metadata: {
395
- provider: "aidenid",
396
- adapter: "sentinelayer-cli",
397
- adapter_contract_file: ".sentinelayer/mcp/aidenid-provisioning-adapter.json",
398
- },
399
- },
400
- ],
401
- };
402
- }
403
-
404
- /**
405
- * Create an AIdenID adapter contract template that binds MCP tools to provisioning endpoints.
406
- *
407
- * @param {{ generatedAt?: string, registryFile?: string }} [options]
408
- * @returns {Record<string, any>}
409
- */
410
- export function buildAidenIdProvisioningAdapterTemplate({
411
- generatedAt = new Date().toISOString(),
412
- registryFile = ".sentinelayer/mcp/tool-registry.aidenid-template.json",
413
- } = {}) {
414
- return {
415
- version: AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION,
416
- provider: "aidenid",
417
- generated_at: generatedAt,
418
- registry_file: String(registryFile || "").trim() || ".sentinelayer/mcp/tool-registry.aidenid-template.json",
419
- transport: {
420
- base_url: "https://api.aidenid.com",
421
- timeout_ms: 15000,
422
- auth: {
423
- mode: "bearer",
424
- secret_ref: "AIDENID_API_KEY",
425
- },
426
- },
427
- tool_bindings: [
428
- {
429
- tool_name: "aidenid.provision_email",
430
- operation: "provision_email",
431
- method: "POST",
432
- path: "/v1/identities",
433
- request_template: {
434
- ttl_seconds: "{{input.ttl_seconds}}",
435
- tags: "{{input.tags}}",
436
- policy: "{{input.policy}}",
437
- },
438
- response_contract: {
439
- identity_id_path: "$.identity.id",
440
- email_path: "$.identity.email",
441
- expires_at_path: "$.identity.expires_at",
442
- },
443
- budgets: {
444
- max_calls_per_run: 3,
445
- max_runtime_ms: 20000,
446
- },
447
- security: {
448
- requires_human_approval: true,
449
- kill_switch: "enabled",
450
- scopes: ["identity:create"],
451
- },
452
- metadata: {
453
- provider: "aidenid",
454
- adapter: "sentinelayer-cli",
455
- },
456
- },
457
- ],
458
- };
459
- }
460
-
461
- /**
462
- * Create a local MCP server config template with deterministic runtime budgets and security defaults.
463
- *
464
- * @param {{ serverId?: string, registryFile?: string, generatedAt?: string }} [options]
465
- * @returns {Record<string, any>}
466
- */
467
- export function buildMcpServerConfigTemplate({
468
- serverId = "sentinelayer-local",
469
- registryFile = ".sentinelayer/mcp/tool-registry.aidenid-template.json",
470
- generatedAt = new Date().toISOString(),
471
- } = {}) {
472
- const normalizedId = String(serverId || "")
473
- .trim()
474
- .toLowerCase();
475
- if (!serverIdRegex.test(normalizedId)) {
476
- throw new Error("server id must use lowercase [a-z0-9._-] and be 1-64 chars.");
477
- }
478
- return {
479
- version: MCP_SERVER_CONFIG_SCHEMA_VERSION,
480
- server_id: normalizedId,
481
- registry_file: String(registryFile || "").trim() || ".sentinelayer/mcp/tool-registry.aidenid-template.json",
482
- transport: {
483
- mode: "stdio",
484
- command: "create-sentinelayer",
485
- args: ["mcp", "server", "run", "--config", `.sentinelayer/mcp/servers/${normalizedId}.json`],
486
- },
487
- budgets: {
488
- max_calls_per_run: 20,
489
- max_runtime_ms: 60000,
490
- },
491
- security: {
492
- requires_human_approval: true,
493
- allow_network: false,
494
- kill_switch: "enabled",
495
- },
496
- metadata: {
497
- generated_at: generatedAt,
498
- generated_by: "create-sentinelayer",
499
- },
500
- };
501
- }
502
-
503
- /**
504
- * Build VS Code bridge config content that points to Sentinelayer MCP server runtime.
505
- *
506
- * @param {{ serverId?: string, serverConfigFile?: string }} [options]
507
- * @returns {{ mcpServers: Record<string, { command: string, args: string[] }> }}
508
- */
509
- export function buildVsCodeMcpBridgeTemplate({
510
- serverId,
511
- serverConfigFile,
512
- } = {}) {
513
- const normalizedId = String(serverId || "")
514
- .trim()
515
- .toLowerCase();
516
- if (!serverIdRegex.test(normalizedId)) {
517
- throw new Error("server id must use lowercase [a-z0-9._-] and be 1-64 chars.");
518
- }
519
- return {
520
- mcpServers: {
521
- [normalizedId]: {
522
- command: "create-sentinelayer",
523
- args: ["mcp", "server", "run", "--config", String(serverConfigFile || "").trim()],
524
- },
525
- },
526
- };
527
- }
528
-
529
- /**
530
- * Validate and normalize a tool-registry payload against Sentinelayer MCP registry schema.
531
- *
532
- * @param {unknown} payload
533
- * @returns {any}
534
- */
535
- export function validateMcpToolRegistry(payload) {
536
- const parsed = mcpRegistrySchema.parse(payload);
537
- return parsed;
538
- }
539
-
540
- /**
541
- * Validate and normalize AIdenID adapter contract payload.
542
- * Optionally cross-validates adapter tool bindings against a provided registry payload.
543
- *
544
- * @param {unknown} payload
545
- * @param {{ registryPayload?: unknown }} [options]
546
- * @returns {any}
547
- */
548
- export function validateAidenIdAdapterContract(payload, { registryPayload } = {}) {
549
- const parsed = aidenIdAdapterContractSchema.parse(payload);
550
-
551
- if (registryPayload !== undefined) {
552
- const registry = validateMcpToolRegistry(registryPayload);
553
- const toolNameSet = new Set(registry.tools.map((tool) => tool.name));
554
- const missingToolBindings = parsed.tool_bindings
555
- .map((binding) => binding.tool_name)
556
- .filter((toolName) => !toolNameSet.has(toolName));
557
- if (missingToolBindings.length > 0) {
558
- throw new Error(
559
- `Adapter contract references tools not present in registry: ${missingToolBindings.join(", ")}`
560
- );
561
- }
562
- }
563
-
564
- return parsed;
565
- }
566
-
567
- /**
568
- * Validate and normalize MCP server runtime config payload.
569
- *
570
- * @param {unknown} payload
571
- * @returns {any}
572
- */
573
- export function validateMcpServerConfig(payload) {
574
- return mcpServerConfigSchema.parse(payload);
575
- }
576
-
577
- /**
578
- * Serialize a value into pretty-printed JSON with trailing newline for deterministic artifacts.
579
- *
580
- * @param {unknown} value
581
- * @returns {string}
582
- */
583
- export function stringifyJson(value) {
584
- return `${JSON.stringify(value, null, 2)}\n`;
585
- }
586
-
587
- /**
588
- * Write JSON file with optional overwrite protection.
589
- *
590
- * @param {string} filePath
591
- * @param {unknown} value
592
- * @param {{ force?: boolean }} [options]
593
- * @returns {Promise<string>}
594
- */
595
- export async function writeJsonFile(filePath, value, { force = false } = {}) {
596
- const resolvedPath = path.resolve(filePath);
597
- if (!force) {
598
- try {
599
- await fsp.access(resolvedPath);
600
- throw new Error(`File already exists: ${resolvedPath}. Use --force to overwrite.`);
601
- } catch (error) {
602
- if (error && typeof error === "object" && error.code === "ENOENT") {
603
- // missing file is expected
604
- } else if (error instanceof Error && error.message.startsWith("File already exists:")) {
605
- throw error;
606
- } else if (error) {
607
- throw error;
608
- }
609
- }
610
- }
611
- await fsp.mkdir(path.dirname(resolvedPath), { recursive: true });
612
- await fsp.writeFile(resolvedPath, stringifyJson(value), "utf-8");
613
- return resolvedPath;
614
- }
615
-
616
- /**
617
- * Read and parse JSON from disk using an absolute resolved path.
618
- *
619
- * @param {string} filePath
620
- * @returns {Promise<{ path: string, data: any }>}
621
- */
622
- export async function readJsonFile(filePath) {
623
- const resolvedPath = path.resolve(filePath);
624
- const rawText = await fsp.readFile(resolvedPath, "utf-8");
625
- return {
626
- path: resolvedPath,
627
- data: JSON.parse(rawText),
628
- };
629
- }
630
-
631
- /**
632
- * Resolve default output path for generated MCP registry schema artifacts.
633
- *
634
- * @param {{ cwd?: string, outputDir?: string, env?: NodeJS.ProcessEnv }} [options]
635
- * @returns {Promise<string>}
636
- */
637
- export async function resolveDefaultMcpOutputPath({ cwd, outputDir, env } = {}) {
638
- const outputRoot = await resolveOutputRoot({
639
- cwd,
640
- outputDirOverride: outputDir,
641
- env,
642
- });
643
- return path.join(outputRoot, "mcp", "tool-registry.schema.json");
644
- }
645
-
646
- /**
647
- * Resolve default output path for generated AIdenID adapter contract artifacts.
648
- *
649
- * @param {{ cwd?: string, outputDir?: string, env?: NodeJS.ProcessEnv }} [options]
650
- * @returns {Promise<string>}
651
- */
652
- export async function resolveDefaultAidenIdAdapterContractPath({ cwd, outputDir, env } = {}) {
653
- const outputRoot = await resolveOutputRoot({
654
- cwd,
655
- outputDirOverride: outputDir,
656
- env,
657
- });
658
- return path.join(outputRoot, "mcp", "aidenid-provisioning-adapter.json");
659
- }
660
-
661
- /**
662
- * Resolve default MCP server config output path for a specific server id.
663
- *
664
- * @param {{ cwd?: string, outputDir?: string, env?: NodeJS.ProcessEnv, serverId?: string }} [options]
665
- * @returns {Promise<string>}
666
- */
667
- export async function resolveDefaultMcpServerConfigPath({
668
- cwd,
669
- outputDir,
670
- env,
671
- serverId,
672
- } = {}) {
673
- const outputRoot = await resolveOutputRoot({
674
- cwd,
675
- outputDirOverride: outputDir,
676
- env,
677
- });
678
- const normalizedId = String(serverId || "")
679
- .trim()
680
- .toLowerCase();
681
- if (!serverIdRegex.test(normalizedId)) {
682
- throw new Error("server id must use lowercase [a-z0-9._-] and be 1-64 chars.");
683
- }
684
- return path.join(outputRoot, "mcp", "servers", `${normalizedId}.json`);
685
- }
686
-
687
- /**
688
- * Resolve default VS Code MCP bridge file path.
689
- *
690
- * @param {{ cwd?: string }} [options]
691
- * @returns {string}
692
- */
693
- export function resolveDefaultVsCodeBridgePath({ cwd } = {}) {
694
- return path.join(path.resolve(cwd || process.cwd()), ".vscode", "mcp.json");
695
- }
1
+ import fsp from "node:fs/promises";
2
+ import path from "node:path";
3
+ import process from "node:process";
4
+
5
+ import { z } from "zod";
6
+
7
+ import { resolveOutputRoot } from "../config/service.js";
8
+
9
+ /** MCP tool-registry schema version used by Sentinelayer CLI generated artifacts. */
10
+ export const MCP_TOOL_REGISTRY_SCHEMA_VERSION = "1.0.0";
11
+ /** MCP server-config schema version used by Sentinelayer CLI generated artifacts. */
12
+ export const MCP_SERVER_CONFIG_SCHEMA_VERSION = "1.0.0";
13
+ /** AIdenID adapter-contract schema version used by Sentinelayer CLI generated artifacts. */
14
+ export const AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION = "1.0.0";
15
+
16
+ const serverIdRegex = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/;
17
+ const inputPlaceholderRegex = /^\{\{input\.[a-zA-Z0-9_.-]+\}\}$/;
18
+
19
+ const jsonSchemaObject = z.object({
20
+ type: z.literal("object"),
21
+ properties: z.record(z.string(), z.any()).optional(),
22
+ required: z.array(z.string()).optional(),
23
+ additionalProperties: z.union([z.boolean(), z.any()]).optional(),
24
+ });
25
+
26
+ const mcpToolSchema = z
27
+ .object({
28
+ name: z
29
+ .string()
30
+ .min(1)
31
+ .regex(/^[a-zA-Z0-9_.:-]+$/, "tool name must contain only [a-zA-Z0-9_.:-]"),
32
+ title: z.string().min(1).optional(),
33
+ description: z.string().min(1),
34
+ input_schema: jsonSchemaObject,
35
+ transport: z.object({
36
+ type: z.enum(["http", "internal", "bridge"]),
37
+ method: z.enum(["GET", "POST", "PUT", "PATCH", "DELETE"]).default("POST"),
38
+ url: z.string().min(1),
39
+ timeout_ms: z.number().int().positive().optional(),
40
+ auth: z
41
+ .object({
42
+ mode: z.enum(["bearer", "api_key", "oauth2", "none"]).default("bearer"),
43
+ secret_ref: z.string().min(1).optional(),
44
+ })
45
+ .optional(),
46
+ }),
47
+ budgets: z
48
+ .object({
49
+ max_calls_per_run: z.number().int().positive().default(5),
50
+ max_runtime_ms: z.number().int().positive().default(15000),
51
+ })
52
+ .optional(),
53
+ security: z
54
+ .object({
55
+ requires_human_approval: z.boolean().default(false),
56
+ kill_switch: z.enum(["enabled", "disabled"]).default("enabled"),
57
+ scopes: z.array(z.string().min(1)).default([]),
58
+ })
59
+ .optional(),
60
+ metadata: z.record(z.string(), z.any()).optional(),
61
+ })
62
+ .strict();
63
+
64
+ const mcpRegistrySchema = z
65
+ .object({
66
+ version: z.string().min(1),
67
+ generated_at: z.string().optional(),
68
+ tools: z.array(mcpToolSchema).min(1),
69
+ })
70
+ .strict();
71
+
72
+ const aidenIdProvisioningBindingSchema = z
73
+ .object({
74
+ tool_name: z
75
+ .string()
76
+ .min(1)
77
+ .regex(/^[a-zA-Z0-9_.:-]+$/, "tool_name must contain only [a-zA-Z0-9_.:-]"),
78
+ operation: z.literal("provision_email"),
79
+ method: z.literal("POST"),
80
+ path: z.literal("/v1/identities"),
81
+ request_template: z
82
+ .object({
83
+ ttl_seconds: z.string().regex(inputPlaceholderRegex),
84
+ tags: z.string().regex(inputPlaceholderRegex).optional(),
85
+ policy: z.string().regex(inputPlaceholderRegex).optional(),
86
+ })
87
+ .strict(),
88
+ response_contract: z
89
+ .object({
90
+ identity_id_path: z.string().min(1),
91
+ email_path: z.string().min(1),
92
+ expires_at_path: z.string().min(1),
93
+ })
94
+ .strict(),
95
+ budgets: z
96
+ .object({
97
+ max_calls_per_run: z.number().int().positive().default(3),
98
+ max_runtime_ms: z.number().int().positive().default(20000),
99
+ })
100
+ .strict()
101
+ .default({
102
+ max_calls_per_run: 3,
103
+ max_runtime_ms: 20000,
104
+ }),
105
+ security: z
106
+ .object({
107
+ requires_human_approval: z.boolean().default(true),
108
+ kill_switch: z.enum(["enabled", "disabled"]).default("enabled"),
109
+ scopes: z.array(z.string().min(1)).default(["identity:create"]),
110
+ })
111
+ .strict()
112
+ .default({
113
+ requires_human_approval: true,
114
+ kill_switch: "enabled",
115
+ scopes: ["identity:create"],
116
+ }),
117
+ metadata: z.record(z.string(), z.any()).optional(),
118
+ })
119
+ .strict();
120
+
121
+ const aidenIdAdapterContractSchema = z
122
+ .object({
123
+ version: z
124
+ .literal(AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION)
125
+ .default(AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION),
126
+ provider: z.literal("aidenid"),
127
+ generated_at: z.string().min(1),
128
+ registry_file: z.string().min(1),
129
+ transport: z
130
+ .object({
131
+ base_url: z.string().url(),
132
+ timeout_ms: z.number().int().positive().default(15000),
133
+ auth: z
134
+ .object({
135
+ mode: z.enum(["bearer", "api_key", "oauth2", "none"]).default("bearer"),
136
+ secret_ref: z.string().min(1),
137
+ })
138
+ .strict(),
139
+ })
140
+ .strict(),
141
+ tool_bindings: z.array(aidenIdProvisioningBindingSchema).min(1),
142
+ })
143
+ .strict();
144
+
145
+ const mcpServerTransportSchema = z.discriminatedUnion("mode", [
146
+ z
147
+ .object({
148
+ mode: z.literal("stdio"),
149
+ command: z.string().min(1),
150
+ args: z.array(z.string()).default([]),
151
+ cwd: z.string().min(1).optional(),
152
+ env: z.record(z.string(), z.string()).optional(),
153
+ })
154
+ .strict(),
155
+ z
156
+ .object({
157
+ mode: z.literal("http"),
158
+ url: z.string().min(1),
159
+ timeout_ms: z.number().int().positive().default(15000),
160
+ auth: z
161
+ .object({
162
+ mode: z.enum(["bearer", "api_key", "oauth2", "none"]).default("bearer"),
163
+ secret_ref: z.string().min(1).optional(),
164
+ audience: z.string().min(1).optional(),
165
+ })
166
+ .strict()
167
+ .optional(),
168
+ headers: z.record(z.string(), z.string()).optional(),
169
+ })
170
+ .strict()
171
+ .superRefine((transport, ctx) => {
172
+ if (!transport.auth) {
173
+ return;
174
+ }
175
+ const mode = transport.auth.mode;
176
+ if ((mode === "bearer" || mode === "oauth2") && !transport.auth.audience) {
177
+ ctx.addIssue({
178
+ code: z.ZodIssueCode.custom,
179
+ path: ["auth", "audience"],
180
+ message: "audience is required when auth.mode is bearer or oauth2.",
181
+ });
182
+ }
183
+ }),
184
+ ]);
185
+
186
+ const mcpServerConfigSchema = z
187
+ .object({
188
+ version: z.literal(MCP_SERVER_CONFIG_SCHEMA_VERSION).default(MCP_SERVER_CONFIG_SCHEMA_VERSION),
189
+ server_id: z.string().regex(serverIdRegex),
190
+ registry_file: z.string().min(1),
191
+ transport: mcpServerTransportSchema,
192
+ budgets: z
193
+ .object({
194
+ max_calls_per_run: z.number().int().positive().default(20),
195
+ max_runtime_ms: z.number().int().positive().default(60000),
196
+ })
197
+ .strict()
198
+ .default({
199
+ max_calls_per_run: 20,
200
+ max_runtime_ms: 60000,
201
+ }),
202
+ security: z
203
+ .object({
204
+ requires_human_approval: z.boolean().default(true),
205
+ allow_network: z.boolean().default(false),
206
+ kill_switch: z.enum(["enabled", "disabled"]).default("enabled"),
207
+ })
208
+ .strict()
209
+ .default({
210
+ requires_human_approval: true,
211
+ allow_network: false,
212
+ kill_switch: "enabled",
213
+ }),
214
+ metadata: z.record(z.string(), z.any()).optional(),
215
+ })
216
+ .strict();
217
+
218
+ /**
219
+ * Build JSON schema for Sentinelayer MCP tool-registry documents.
220
+ *
221
+ * @returns {Record<string, any>}
222
+ */
223
+ export function buildMcpToolRegistrySchema() {
224
+ return {
225
+ $schema: "https://json-schema.org/draft/2020-12/schema",
226
+ $id: "https://sentinelayer.com/schemas/mcp-tool-registry.schema.json",
227
+ title: "Sentinelayer MCP Tool Registry",
228
+ type: "object",
229
+ additionalProperties: false,
230
+ required: ["version", "tools"],
231
+ properties: {
232
+ version: {
233
+ type: "string",
234
+ description: "Registry schema version.",
235
+ },
236
+ generated_at: {
237
+ type: "string",
238
+ format: "date-time",
239
+ },
240
+ tools: {
241
+ type: "array",
242
+ minItems: 1,
243
+ items: {
244
+ type: "object",
245
+ additionalProperties: false,
246
+ required: ["name", "description", "input_schema", "transport"],
247
+ properties: {
248
+ name: {
249
+ type: "string",
250
+ pattern: "^[a-zA-Z0-9_.:-]+$",
251
+ },
252
+ title: {
253
+ type: "string",
254
+ },
255
+ description: {
256
+ type: "string",
257
+ },
258
+ input_schema: {
259
+ type: "object",
260
+ },
261
+ transport: {
262
+ type: "object",
263
+ additionalProperties: false,
264
+ required: ["type", "method", "url"],
265
+ properties: {
266
+ type: {
267
+ type: "string",
268
+ enum: ["http", "internal", "bridge"],
269
+ },
270
+ method: {
271
+ type: "string",
272
+ enum: ["GET", "POST", "PUT", "PATCH", "DELETE"],
273
+ },
274
+ url: {
275
+ type: "string",
276
+ },
277
+ timeout_ms: {
278
+ type: "integer",
279
+ minimum: 1,
280
+ },
281
+ auth: {
282
+ type: "object",
283
+ additionalProperties: false,
284
+ properties: {
285
+ mode: {
286
+ type: "string",
287
+ enum: ["bearer", "api_key", "oauth2", "none"],
288
+ },
289
+ secret_ref: {
290
+ type: "string",
291
+ },
292
+ },
293
+ },
294
+ },
295
+ },
296
+ budgets: {
297
+ type: "object",
298
+ additionalProperties: false,
299
+ properties: {
300
+ max_calls_per_run: {
301
+ type: "integer",
302
+ minimum: 1,
303
+ },
304
+ max_runtime_ms: {
305
+ type: "integer",
306
+ minimum: 1,
307
+ },
308
+ },
309
+ },
310
+ security: {
311
+ type: "object",
312
+ additionalProperties: false,
313
+ properties: {
314
+ requires_human_approval: {
315
+ type: "boolean",
316
+ },
317
+ kill_switch: {
318
+ type: "string",
319
+ enum: ["enabled", "disabled"],
320
+ },
321
+ scopes: {
322
+ type: "array",
323
+ items: { type: "string" },
324
+ },
325
+ },
326
+ },
327
+ metadata: {
328
+ type: "object",
329
+ },
330
+ },
331
+ },
332
+ },
333
+ },
334
+ };
335
+ }
336
+
337
+ /**
338
+ * Create a secure-by-default MCP tool-registry template for AIdenID provisioning.
339
+ *
340
+ * @param {{ generatedAt?: string }} [options]
341
+ * @returns {Record<string, any>}
342
+ */
343
+ export function buildAidenIdRegistryTemplate({ generatedAt = new Date().toISOString() } = {}) {
344
+ return {
345
+ version: MCP_TOOL_REGISTRY_SCHEMA_VERSION,
346
+ generated_at: generatedAt,
347
+ tools: [
348
+ {
349
+ name: "aidenid.provision_email",
350
+ title: "AIdenID Provision Email Identity",
351
+ description:
352
+ "Provision an ephemeral email identity through AIdenID for autonomous agent workflows.",
353
+ input_schema: {
354
+ type: "object",
355
+ additionalProperties: false,
356
+ required: ["ttl_seconds"],
357
+ properties: {
358
+ ttl_seconds: {
359
+ type: "integer",
360
+ minimum: 60,
361
+ maximum: 86400,
362
+ description: "Identity TTL in seconds.",
363
+ },
364
+ tags: {
365
+ type: "array",
366
+ items: { type: "string" },
367
+ },
368
+ policy: {
369
+ type: "object",
370
+ additionalProperties: true,
371
+ description: "Optional policy envelope passed to AIdenID.",
372
+ },
373
+ },
374
+ },
375
+ transport: {
376
+ type: "http",
377
+ method: "POST",
378
+ url: "https://api.aidenid.com/v1/identities",
379
+ timeout_ms: 15000,
380
+ auth: {
381
+ mode: "bearer",
382
+ secret_ref: "AIDENID_API_KEY",
383
+ },
384
+ },
385
+ budgets: {
386
+ max_calls_per_run: 3,
387
+ max_runtime_ms: 20000,
388
+ },
389
+ security: {
390
+ requires_human_approval: true,
391
+ kill_switch: "enabled",
392
+ scopes: ["identity:create"],
393
+ },
394
+ metadata: {
395
+ provider: "aidenid",
396
+ adapter: "sentinelayer-cli",
397
+ adapter_contract_file: ".sentinelayer/mcp/aidenid-provisioning-adapter.json",
398
+ },
399
+ },
400
+ ],
401
+ };
402
+ }
403
+
404
+ /**
405
+ * Create an AIdenID adapter contract template that binds MCP tools to provisioning endpoints.
406
+ *
407
+ * @param {{ generatedAt?: string, registryFile?: string }} [options]
408
+ * @returns {Record<string, any>}
409
+ */
410
+ export function buildAidenIdProvisioningAdapterTemplate({
411
+ generatedAt = new Date().toISOString(),
412
+ registryFile = ".sentinelayer/mcp/tool-registry.aidenid-template.json",
413
+ } = {}) {
414
+ return {
415
+ version: AIDENID_ADAPTER_CONTRACT_SCHEMA_VERSION,
416
+ provider: "aidenid",
417
+ generated_at: generatedAt,
418
+ registry_file: String(registryFile || "").trim() || ".sentinelayer/mcp/tool-registry.aidenid-template.json",
419
+ transport: {
420
+ base_url: "https://api.aidenid.com",
421
+ timeout_ms: 15000,
422
+ auth: {
423
+ mode: "bearer",
424
+ secret_ref: "AIDENID_API_KEY",
425
+ },
426
+ },
427
+ tool_bindings: [
428
+ {
429
+ tool_name: "aidenid.provision_email",
430
+ operation: "provision_email",
431
+ method: "POST",
432
+ path: "/v1/identities",
433
+ request_template: {
434
+ ttl_seconds: "{{input.ttl_seconds}}",
435
+ tags: "{{input.tags}}",
436
+ policy: "{{input.policy}}",
437
+ },
438
+ response_contract: {
439
+ identity_id_path: "$.identity.id",
440
+ email_path: "$.identity.email",
441
+ expires_at_path: "$.identity.expires_at",
442
+ },
443
+ budgets: {
444
+ max_calls_per_run: 3,
445
+ max_runtime_ms: 20000,
446
+ },
447
+ security: {
448
+ requires_human_approval: true,
449
+ kill_switch: "enabled",
450
+ scopes: ["identity:create"],
451
+ },
452
+ metadata: {
453
+ provider: "aidenid",
454
+ adapter: "sentinelayer-cli",
455
+ },
456
+ },
457
+ ],
458
+ };
459
+ }
460
+
461
+ /**
462
+ * Create a local MCP server config template with deterministic runtime budgets and security defaults.
463
+ *
464
+ * @param {{ serverId?: string, registryFile?: string, generatedAt?: string }} [options]
465
+ * @returns {Record<string, any>}
466
+ */
467
+ export function buildMcpServerConfigTemplate({
468
+ serverId = "sentinelayer-local",
469
+ registryFile = ".sentinelayer/mcp/tool-registry.aidenid-template.json",
470
+ generatedAt = new Date().toISOString(),
471
+ } = {}) {
472
+ const normalizedId = String(serverId || "")
473
+ .trim()
474
+ .toLowerCase();
475
+ if (!serverIdRegex.test(normalizedId)) {
476
+ throw new Error("server id must use lowercase [a-z0-9._-] and be 1-64 chars.");
477
+ }
478
+ return {
479
+ version: MCP_SERVER_CONFIG_SCHEMA_VERSION,
480
+ server_id: normalizedId,
481
+ registry_file: String(registryFile || "").trim() || ".sentinelayer/mcp/tool-registry.aidenid-template.json",
482
+ transport: {
483
+ mode: "stdio",
484
+ command: "create-sentinelayer",
485
+ args: ["mcp", "server", "run", "--config", `.sentinelayer/mcp/servers/${normalizedId}.json`],
486
+ },
487
+ budgets: {
488
+ max_calls_per_run: 20,
489
+ max_runtime_ms: 60000,
490
+ },
491
+ security: {
492
+ requires_human_approval: true,
493
+ allow_network: false,
494
+ kill_switch: "enabled",
495
+ },
496
+ metadata: {
497
+ generated_at: generatedAt,
498
+ generated_by: "create-sentinelayer",
499
+ },
500
+ };
501
+ }
502
+
503
+ /**
504
+ * Build VS Code bridge config content that points to Sentinelayer MCP server runtime.
505
+ *
506
+ * @param {{ serverId?: string, serverConfigFile?: string }} [options]
507
+ * @returns {{ mcpServers: Record<string, { command: string, args: string[] }> }}
508
+ */
509
+ export function buildVsCodeMcpBridgeTemplate({
510
+ serverId,
511
+ serverConfigFile,
512
+ } = {}) {
513
+ const normalizedId = String(serverId || "")
514
+ .trim()
515
+ .toLowerCase();
516
+ if (!serverIdRegex.test(normalizedId)) {
517
+ throw new Error("server id must use lowercase [a-z0-9._-] and be 1-64 chars.");
518
+ }
519
+ return {
520
+ mcpServers: {
521
+ [normalizedId]: {
522
+ command: "create-sentinelayer",
523
+ args: ["mcp", "server", "run", "--config", String(serverConfigFile || "").trim()],
524
+ },
525
+ },
526
+ };
527
+ }
528
+
529
+ /**
530
+ * Validate and normalize a tool-registry payload against Sentinelayer MCP registry schema.
531
+ *
532
+ * @param {unknown} payload
533
+ * @returns {any}
534
+ */
535
+ export function validateMcpToolRegistry(payload) {
536
+ const parsed = mcpRegistrySchema.parse(payload);
537
+ return parsed;
538
+ }
539
+
540
+ /**
541
+ * Validate and normalize AIdenID adapter contract payload.
542
+ * Optionally cross-validates adapter tool bindings against a provided registry payload.
543
+ *
544
+ * @param {unknown} payload
545
+ * @param {{ registryPayload?: unknown }} [options]
546
+ * @returns {any}
547
+ */
548
+ export function validateAidenIdAdapterContract(payload, { registryPayload } = {}) {
549
+ const parsed = aidenIdAdapterContractSchema.parse(payload);
550
+
551
+ if (registryPayload !== undefined) {
552
+ const registry = validateMcpToolRegistry(registryPayload);
553
+ const toolNameSet = new Set(registry.tools.map((tool) => tool.name));
554
+ const missingToolBindings = parsed.tool_bindings
555
+ .map((binding) => binding.tool_name)
556
+ .filter((toolName) => !toolNameSet.has(toolName));
557
+ if (missingToolBindings.length > 0) {
558
+ throw new Error(
559
+ `Adapter contract references tools not present in registry: ${missingToolBindings.join(", ")}`
560
+ );
561
+ }
562
+ }
563
+
564
+ return parsed;
565
+ }
566
+
567
+ /**
568
+ * Validate and normalize MCP server runtime config payload.
569
+ *
570
+ * @param {unknown} payload
571
+ * @returns {any}
572
+ */
573
+ export function validateMcpServerConfig(payload) {
574
+ return mcpServerConfigSchema.parse(payload);
575
+ }
576
+
577
+ /**
578
+ * Serialize a value into pretty-printed JSON with trailing newline for deterministic artifacts.
579
+ *
580
+ * @param {unknown} value
581
+ * @returns {string}
582
+ */
583
+ export function stringifyJson(value) {
584
+ return `${JSON.stringify(value, null, 2)}\n`;
585
+ }
586
+
587
+ /**
588
+ * Write JSON file with optional overwrite protection.
589
+ *
590
+ * @param {string} filePath
591
+ * @param {unknown} value
592
+ * @param {{ force?: boolean }} [options]
593
+ * @returns {Promise<string>}
594
+ */
595
+ export async function writeJsonFile(filePath, value, { force = false } = {}) {
596
+ const resolvedPath = path.resolve(filePath);
597
+ if (!force) {
598
+ try {
599
+ await fsp.access(resolvedPath);
600
+ throw new Error(`File already exists: ${resolvedPath}. Use --force to overwrite.`);
601
+ } catch (error) {
602
+ if (error && typeof error === "object" && error.code === "ENOENT") {
603
+ // missing file is expected
604
+ } else if (error instanceof Error && error.message.startsWith("File already exists:")) {
605
+ throw error;
606
+ } else if (error) {
607
+ throw error;
608
+ }
609
+ }
610
+ }
611
+ await fsp.mkdir(path.dirname(resolvedPath), { recursive: true });
612
+ await fsp.writeFile(resolvedPath, stringifyJson(value), "utf-8");
613
+ return resolvedPath;
614
+ }
615
+
616
+ /**
617
+ * Read and parse JSON from disk using an absolute resolved path.
618
+ *
619
+ * @param {string} filePath
620
+ * @returns {Promise<{ path: string, data: any }>}
621
+ */
622
+ export async function readJsonFile(filePath) {
623
+ const resolvedPath = path.resolve(filePath);
624
+ const rawText = await fsp.readFile(resolvedPath, "utf-8");
625
+ return {
626
+ path: resolvedPath,
627
+ data: JSON.parse(rawText),
628
+ };
629
+ }
630
+
631
+ /**
632
+ * Resolve default output path for generated MCP registry schema artifacts.
633
+ *
634
+ * @param {{ cwd?: string, outputDir?: string, env?: NodeJS.ProcessEnv }} [options]
635
+ * @returns {Promise<string>}
636
+ */
637
+ export async function resolveDefaultMcpOutputPath({ cwd, outputDir, env } = {}) {
638
+ const outputRoot = await resolveOutputRoot({
639
+ cwd,
640
+ outputDirOverride: outputDir,
641
+ env,
642
+ });
643
+ return path.join(outputRoot, "mcp", "tool-registry.schema.json");
644
+ }
645
+
646
+ /**
647
+ * Resolve default output path for generated AIdenID adapter contract artifacts.
648
+ *
649
+ * @param {{ cwd?: string, outputDir?: string, env?: NodeJS.ProcessEnv }} [options]
650
+ * @returns {Promise<string>}
651
+ */
652
+ export async function resolveDefaultAidenIdAdapterContractPath({ cwd, outputDir, env } = {}) {
653
+ const outputRoot = await resolveOutputRoot({
654
+ cwd,
655
+ outputDirOverride: outputDir,
656
+ env,
657
+ });
658
+ return path.join(outputRoot, "mcp", "aidenid-provisioning-adapter.json");
659
+ }
660
+
661
+ /**
662
+ * Resolve default MCP server config output path for a specific server id.
663
+ *
664
+ * @param {{ cwd?: string, outputDir?: string, env?: NodeJS.ProcessEnv, serverId?: string }} [options]
665
+ * @returns {Promise<string>}
666
+ */
667
+ export async function resolveDefaultMcpServerConfigPath({
668
+ cwd,
669
+ outputDir,
670
+ env,
671
+ serverId,
672
+ } = {}) {
673
+ const outputRoot = await resolveOutputRoot({
674
+ cwd,
675
+ outputDirOverride: outputDir,
676
+ env,
677
+ });
678
+ const normalizedId = String(serverId || "")
679
+ .trim()
680
+ .toLowerCase();
681
+ if (!serverIdRegex.test(normalizedId)) {
682
+ throw new Error("server id must use lowercase [a-z0-9._-] and be 1-64 chars.");
683
+ }
684
+ return path.join(outputRoot, "mcp", "servers", `${normalizedId}.json`);
685
+ }
686
+
687
+ /**
688
+ * Resolve default VS Code MCP bridge file path.
689
+ *
690
+ * @param {{ cwd?: string }} [options]
691
+ * @returns {string}
692
+ */
693
+ export function resolveDefaultVsCodeBridgePath({ cwd } = {}) {
694
+ return path.join(path.resolve(cwd || process.cwd()), ".vscode", "mcp.json");
695
+ }