sentinelayer-cli 0.6.2 → 0.8.1

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 (280) hide show
  1. package/README.md +1009 -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/ai-governance/index.js +12 -0
  7. package/src/agents/ai-governance/tools/base.js +171 -0
  8. package/src/agents/ai-governance/tools/eval-regression.js +47 -0
  9. package/src/agents/ai-governance/tools/hitl-audit.js +81 -0
  10. package/src/agents/ai-governance/tools/index.js +52 -0
  11. package/src/agents/ai-governance/tools/prompt-drift.js +42 -0
  12. package/src/agents/ai-governance/tools/provenance-check.js +69 -0
  13. package/src/agents/backend/index.js +12 -0
  14. package/src/agents/backend/tools/base.js +189 -0
  15. package/src/agents/backend/tools/circuit-breaker-check.js +123 -0
  16. package/src/agents/backend/tools/idempotency-audit.js +105 -0
  17. package/src/agents/backend/tools/index.js +87 -0
  18. package/src/agents/backend/tools/retry-audit.js +132 -0
  19. package/src/agents/backend/tools/timeout-audit.js +144 -0
  20. package/src/agents/code-quality/index.js +12 -0
  21. package/src/agents/code-quality/tools/base.js +159 -0
  22. package/src/agents/code-quality/tools/complexity-measure.js +197 -0
  23. package/src/agents/code-quality/tools/coupling-analysis.js +81 -0
  24. package/src/agents/code-quality/tools/cycle-detect.js +49 -0
  25. package/src/agents/code-quality/tools/dep-graph.js +196 -0
  26. package/src/agents/code-quality/tools/index.js +89 -0
  27. package/src/agents/data-layer/index.js +12 -0
  28. package/src/agents/data-layer/tools/base.js +181 -0
  29. package/src/agents/data-layer/tools/index-audit.js +165 -0
  30. package/src/agents/data-layer/tools/index.js +83 -0
  31. package/src/agents/data-layer/tools/migration-scan.js +135 -0
  32. package/src/agents/data-layer/tools/query-explain.js +120 -0
  33. package/src/agents/data-layer/tools/tenancy-scan.js +166 -0
  34. package/src/agents/documentation/index.js +12 -0
  35. package/src/agents/documentation/tools/api-diff.js +91 -0
  36. package/src/agents/documentation/tools/base.js +151 -0
  37. package/src/agents/documentation/tools/dead-link-check.js +58 -0
  38. package/src/agents/documentation/tools/docstring-coverage.js +78 -0
  39. package/src/agents/documentation/tools/index.js +52 -0
  40. package/src/agents/documentation/tools/readme-freshness.js +61 -0
  41. package/src/agents/envelope/fix-cycle.js +45 -0
  42. package/src/agents/envelope/index.js +31 -0
  43. package/src/agents/envelope/loop.js +150 -0
  44. package/src/agents/envelope/pulse.js +18 -0
  45. package/src/agents/envelope/stream.js +40 -0
  46. package/src/agents/infrastructure/index.js +12 -0
  47. package/src/agents/infrastructure/tools/base.js +171 -0
  48. package/src/agents/infrastructure/tools/checkov-run.js +32 -0
  49. package/src/agents/infrastructure/tools/drift-detect.js +59 -0
  50. package/src/agents/infrastructure/tools/iam-least-priv-check.js +78 -0
  51. package/src/agents/infrastructure/tools/index.js +52 -0
  52. package/src/agents/infrastructure/tools/tflint-run.js +31 -0
  53. package/src/agents/jules/config/definition.js +160 -160
  54. package/src/agents/jules/config/system-prompt.js +182 -182
  55. package/src/agents/jules/error-intake.js +51 -51
  56. package/src/agents/jules/fix-cycle.js +17 -17
  57. package/src/agents/jules/loop.js +460 -450
  58. package/src/agents/jules/pulse.js +10 -10
  59. package/src/agents/jules/stream.js +187 -186
  60. package/src/agents/jules/swarm/file-scanner.js +74 -74
  61. package/src/agents/jules/swarm/index.js +11 -11
  62. package/src/agents/jules/swarm/orchestrator.js +362 -362
  63. package/src/agents/jules/swarm/pattern-hunter.js +123 -123
  64. package/src/agents/jules/swarm/sub-agent.js +315 -309
  65. package/src/agents/jules/tools/aidenid-email.js +189 -189
  66. package/src/agents/jules/tools/auth-audit.js +1708 -1691
  67. package/src/agents/jules/tools/dispatch.js +340 -335
  68. package/src/agents/jules/tools/file-edit.js +2 -2
  69. package/src/agents/jules/tools/file-read.js +2 -2
  70. package/src/agents/jules/tools/frontend-analyze.js +570 -570
  71. package/src/agents/jules/tools/glob.js +2 -2
  72. package/src/agents/jules/tools/grep.js +2 -2
  73. package/src/agents/jules/tools/index.js +29 -29
  74. package/src/agents/jules/tools/path-guards.js +2 -2
  75. package/src/agents/jules/tools/runtime-audit.js +507 -507
  76. package/src/agents/jules/tools/shell.js +2 -2
  77. package/src/agents/jules/tools/url-policy.js +100 -100
  78. package/src/agents/mode.js +113 -0
  79. package/src/agents/observability/index.js +12 -0
  80. package/src/agents/observability/tools/alert-audit.js +39 -0
  81. package/src/agents/observability/tools/base.js +181 -0
  82. package/src/agents/observability/tools/dashboard-gap.js +42 -0
  83. package/src/agents/observability/tools/index.js +54 -0
  84. package/src/agents/observability/tools/log-schema-check.js +74 -0
  85. package/src/agents/observability/tools/span-coverage.js +74 -0
  86. package/src/agents/persona-visuals.js +102 -61
  87. package/src/agents/release/index.js +12 -0
  88. package/src/agents/release/tools/base.js +181 -0
  89. package/src/agents/release/tools/changelog-diff.js +86 -0
  90. package/src/agents/release/tools/feature-flag-audit.js +126 -0
  91. package/src/agents/release/tools/index.js +61 -0
  92. package/src/agents/release/tools/rollback-verify.js +129 -0
  93. package/src/agents/release/tools/semver-check.js +109 -0
  94. package/src/agents/reliability/index.js +12 -0
  95. package/src/agents/reliability/tools/backpressure-check.js +129 -0
  96. package/src/agents/reliability/tools/base.js +181 -0
  97. package/src/agents/reliability/tools/chaos-probe.js +109 -0
  98. package/src/agents/reliability/tools/graceful-degradation-check.js +114 -0
  99. package/src/agents/reliability/tools/health-check-audit.js +111 -0
  100. package/src/agents/reliability/tools/index.js +87 -0
  101. package/src/agents/run-persona.js +109 -0
  102. package/src/agents/security/index.js +12 -0
  103. package/src/agents/security/tools/authz-audit.js +134 -0
  104. package/src/agents/security/tools/base.js +190 -0
  105. package/src/agents/security/tools/crypto-review.js +175 -0
  106. package/src/agents/security/tools/index.js +97 -0
  107. package/src/agents/security/tools/sast-scan.js +175 -0
  108. package/src/agents/security/tools/secrets-scan.js +216 -0
  109. package/src/agents/shared-tools/dispatch-core.js +320 -315
  110. package/src/agents/shared-tools/file-edit.js +180 -180
  111. package/src/agents/shared-tools/file-read.js +100 -100
  112. package/src/agents/shared-tools/glob.js +168 -168
  113. package/src/agents/shared-tools/grep.js +228 -228
  114. package/src/agents/shared-tools/index.js +46 -46
  115. package/src/agents/shared-tools/path-guards.js +161 -161
  116. package/src/agents/shared-tools/shell.js +383 -383
  117. package/src/agents/supply-chain/index.js +12 -0
  118. package/src/agents/supply-chain/tools/attestation-check.js +42 -0
  119. package/src/agents/supply-chain/tools/base.js +151 -0
  120. package/src/agents/supply-chain/tools/index.js +52 -0
  121. package/src/agents/supply-chain/tools/lockfile-integrity.js +73 -0
  122. package/src/agents/supply-chain/tools/package-verify.js +56 -0
  123. package/src/agents/supply-chain/tools/sbom-diff.js +34 -0
  124. package/src/agents/testing/index.js +12 -0
  125. package/src/agents/testing/tools/base.js +202 -0
  126. package/src/agents/testing/tools/coverage-gap.js +144 -0
  127. package/src/agents/testing/tools/flake-detect.js +125 -0
  128. package/src/agents/testing/tools/index.js +85 -0
  129. package/src/agents/testing/tools/mutation-test.js +143 -0
  130. package/src/agents/testing/tools/snapshot-diff.js +103 -0
  131. package/src/ai/aidenid.js +1021 -1009
  132. package/src/ai/client.js +553 -553
  133. package/src/ai/domain-target-store.js +268 -268
  134. package/src/ai/identity-store.js +270 -270
  135. package/src/ai/proxy.js +137 -137
  136. package/src/ai/site-store.js +145 -145
  137. package/src/audit/agents/architecture.js +180 -180
  138. package/src/audit/agents/compliance.js +179 -179
  139. package/src/audit/agents/documentation.js +165 -165
  140. package/src/audit/agents/performance.js +145 -145
  141. package/src/audit/agents/security.js +215 -215
  142. package/src/audit/agents/testing.js +172 -172
  143. package/src/audit/orchestrator.js +557 -557
  144. package/src/audit/package.js +204 -204
  145. package/src/audit/registry.js +284 -284
  146. package/src/audit/replay.js +103 -103
  147. package/src/auth/gate.js +428 -371
  148. package/src/auth/http.js +681 -611
  149. package/src/auth/service.js +1106 -1106
  150. package/src/auth/session-store.js +813 -813
  151. package/src/cli.js +257 -252
  152. package/src/commands/ai/identity-lifecycle.js +1338 -1338
  153. package/src/commands/ai/provision-governance.js +1272 -1272
  154. package/src/commands/ai/shared.js +147 -147
  155. package/src/commands/ai.js +11 -11
  156. package/src/commands/apply.js +12 -12
  157. package/src/commands/audit.js +1171 -1166
  158. package/src/commands/auth.js +419 -419
  159. package/src/commands/chat.js +184 -191
  160. package/src/commands/config.js +184 -184
  161. package/src/commands/cost.js +311 -311
  162. package/src/commands/daemon/core.js +850 -850
  163. package/src/commands/daemon/extended.js +1048 -1048
  164. package/src/commands/daemon/shared.js +213 -213
  165. package/src/commands/daemon.js +11 -11
  166. package/src/commands/guide.js +174 -174
  167. package/src/commands/ingest.js +58 -58
  168. package/src/commands/init.js +55 -55
  169. package/src/commands/legacy-args.js +20 -10
  170. package/src/commands/mcp.js +461 -461
  171. package/src/commands/omargate.js +63 -29
  172. package/src/commands/persona.js +65 -20
  173. package/src/commands/plugin.js +260 -260
  174. package/src/commands/policy.js +132 -132
  175. package/src/commands/prompt.js +238 -238
  176. package/src/commands/review.js +704 -704
  177. package/src/commands/scan.js +865 -872
  178. package/src/commands/session.js +1238 -0
  179. package/src/commands/spec.js +771 -716
  180. package/src/commands/swarm.js +651 -651
  181. package/src/commands/telemetry.js +202 -202
  182. package/src/commands/watch.js +511 -511
  183. package/src/config/agent-dictionary.js +182 -182
  184. package/src/config/io.js +56 -56
  185. package/src/config/paths.js +18 -18
  186. package/src/config/schema.js +55 -55
  187. package/src/config/service.js +184 -184
  188. package/src/coord/events-log.js +141 -0
  189. package/src/coord/handshake.js +719 -0
  190. package/src/coord/index.js +35 -0
  191. package/src/coord/paths.js +84 -0
  192. package/src/coord/priority.js +62 -0
  193. package/src/coord/tarjan.js +157 -0
  194. package/src/cost/budget.js +235 -235
  195. package/src/cost/history.js +188 -188
  196. package/src/cost/tokenizer.js +160 -0
  197. package/src/cost/tracker.js +232 -171
  198. package/src/daemon/artifact-lineage.js +896 -534
  199. package/src/daemon/assignment-ledger.js +1083 -770
  200. package/src/daemon/ast-drift.js +496 -0
  201. package/src/daemon/ast-parser-layer.js +258 -258
  202. package/src/daemon/budget-governor.js +633 -633
  203. package/src/daemon/callgraph-overlay.js +646 -646
  204. package/src/daemon/error-worker.js +1209 -626
  205. package/src/daemon/fix-cycle.js +384 -377
  206. package/src/daemon/hybrid-mapper.js +929 -929
  207. package/src/daemon/ingest-refresh.js +79 -11
  208. package/src/daemon/jira-lifecycle.js +767 -632
  209. package/src/daemon/operator-control.js +657 -657
  210. package/src/daemon/pulse.js +327 -327
  211. package/src/daemon/reliability-lane.js +471 -471
  212. package/src/daemon/scope-engine.js +1068 -0
  213. package/src/daemon/watchdog.js +971 -971
  214. package/src/events/schema.js +190 -0
  215. package/src/guide/generator.js +316 -316
  216. package/src/ingest/engine.js +933 -918
  217. package/src/ingest/ownership.js +380 -0
  218. package/src/interactive/index.js +97 -97
  219. package/src/legacy-cli.js +3228 -2994
  220. package/src/mcp/registry.js +695 -695
  221. package/src/memory/blackboard.js +301 -301
  222. package/src/memory/retrieval.js +581 -581
  223. package/src/orchestrator/kai-chen.js +126 -0
  224. package/src/plugin/manifest.js +553 -553
  225. package/src/policy/packs.js +144 -144
  226. package/src/prompt/generator.js +136 -118
  227. package/src/review/ai-review.js +672 -679
  228. package/src/review/compliance-pack.js +389 -0
  229. package/src/review/investor-dd-config.js +54 -0
  230. package/src/review/investor-dd-file-loop.js +303 -0
  231. package/src/review/investor-dd-file-router.js +406 -0
  232. package/src/review/investor-dd-html-report.js +233 -0
  233. package/src/review/investor-dd-notification.js +120 -0
  234. package/src/review/investor-dd-orchestrator.js +405 -0
  235. package/src/review/investor-dd-persona-runner.js +275 -0
  236. package/src/review/live-validator.js +253 -0
  237. package/src/review/local-review.js +1351 -1305
  238. package/src/review/omargate-interactive.js +68 -68
  239. package/src/review/omargate-orchestrator.js +492 -300
  240. package/src/review/persona-prompts.js +484 -296
  241. package/src/review/reconciliation-rules.js +329 -0
  242. package/src/review/replay.js +235 -235
  243. package/src/review/report.js +664 -664
  244. package/src/review/reproducibility-chain.js +136 -0
  245. package/src/review/scan-modes.js +147 -42
  246. package/src/review/spec-binding.js +487 -487
  247. package/src/scaffold/generator.js +67 -67
  248. package/src/scaffold/templates.js +150 -150
  249. package/src/scan/generator.js +418 -418
  250. package/src/scan/gh-secrets.js +107 -107
  251. package/src/session/agent-registry.js +359 -0
  252. package/src/session/analytics.js +479 -0
  253. package/src/session/daemon.js +1396 -0
  254. package/src/session/file-locks.js +666 -0
  255. package/src/session/paths.js +37 -0
  256. package/src/session/recap.js +567 -0
  257. package/src/session/redact.js +82 -0
  258. package/src/session/runtime-bridge.js +762 -0
  259. package/src/session/scoring.js +406 -0
  260. package/src/session/setup-guides.js +304 -0
  261. package/src/session/store.js +704 -0
  262. package/src/session/stream.js +333 -0
  263. package/src/session/sync.js +753 -0
  264. package/src/session/tasks.js +1054 -0
  265. package/src/session/templates.js +188 -0
  266. package/src/spec/generator.js +619 -519
  267. package/src/spec/regenerate.js +237 -237
  268. package/src/spec/templates.js +91 -91
  269. package/src/swarm/dashboard.js +247 -247
  270. package/src/swarm/factory.js +363 -363
  271. package/src/swarm/pentest.js +934 -934
  272. package/src/swarm/registry.js +419 -419
  273. package/src/swarm/report.js +158 -158
  274. package/src/swarm/runtime.js +569 -576
  275. package/src/swarm/scenario-dsl.js +272 -272
  276. package/src/telemetry/ledger.js +302 -302
  277. package/src/telemetry/session-tracker.js +234 -234
  278. package/src/telemetry/sync.js +203 -203
  279. package/src/ui/command-hints.js +13 -13
  280. 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
+ }