@onlyflows/servicenow-mcp 1.0.0 → 2.1.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 (281) hide show
  1. package/.env.example +56 -0
  2. package/CHANGELOG.md +214 -0
  3. package/README.md +939 -101
  4. package/dist/auth.d.ts +88 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +396 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/client.d.ts +111 -17
  9. package/dist/client.d.ts.map +1 -1
  10. package/dist/client.js +554 -79
  11. package/dist/client.js.map +1 -1
  12. package/dist/config.d.ts +41 -4
  13. package/dist/config.d.ts.map +1 -1
  14. package/dist/config.js +44 -34
  15. package/dist/config.js.map +1 -1
  16. package/dist/encoded-query-policy.d.ts +72 -0
  17. package/dist/encoded-query-policy.d.ts.map +1 -0
  18. package/dist/encoded-query-policy.js +409 -0
  19. package/dist/encoded-query-policy.js.map +1 -0
  20. package/dist/execution-context.d.ts +235 -0
  21. package/dist/execution-context.d.ts.map +1 -0
  22. package/dist/execution-context.js +441 -0
  23. package/dist/execution-context.js.map +1 -0
  24. package/dist/field-policy.d.ts +117 -0
  25. package/dist/field-policy.d.ts.map +1 -0
  26. package/dist/field-policy.js +1684 -0
  27. package/dist/field-policy.js.map +1 -0
  28. package/dist/http-auth.d.ts +131 -0
  29. package/dist/http-auth.d.ts.map +1 -0
  30. package/dist/http-auth.js +347 -0
  31. package/dist/http-auth.js.map +1 -0
  32. package/dist/http-entrypoint.d.ts +26 -0
  33. package/dist/http-entrypoint.d.ts.map +1 -0
  34. package/dist/http-entrypoint.js +255 -0
  35. package/dist/http-entrypoint.js.map +1 -0
  36. package/dist/http-observability.d.ts +147 -0
  37. package/dist/http-observability.d.ts.map +1 -0
  38. package/dist/http-observability.js +711 -0
  39. package/dist/http-observability.js.map +1 -0
  40. package/dist/http-request-policy.d.ts +72 -0
  41. package/dist/http-request-policy.d.ts.map +1 -0
  42. package/dist/http-request-policy.js +463 -0
  43. package/dist/http-request-policy.js.map +1 -0
  44. package/dist/http-request-signal.d.ts +12 -0
  45. package/dist/http-request-signal.d.ts.map +1 -0
  46. package/dist/http-request-signal.js +39 -0
  47. package/dist/http-request-signal.js.map +1 -0
  48. package/dist/http-runtime.d.ts +77 -0
  49. package/dist/http-runtime.d.ts.map +1 -0
  50. package/dist/http-runtime.js +1321 -0
  51. package/dist/http-runtime.js.map +1 -0
  52. package/dist/incident-journal-policy.d.ts +22 -0
  53. package/dist/incident-journal-policy.d.ts.map +1 -0
  54. package/dist/incident-journal-policy.js +115 -0
  55. package/dist/incident-journal-policy.js.map +1 -0
  56. package/dist/index.d.ts +14 -4
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +140 -36
  59. package/dist/index.js.map +1 -1
  60. package/dist/metadata-cache.d.ts +71 -0
  61. package/dist/metadata-cache.d.ts.map +1 -0
  62. package/dist/metadata-cache.js +397 -0
  63. package/dist/metadata-cache.js.map +1 -0
  64. package/dist/profile-admin.d.ts +64 -0
  65. package/dist/profile-admin.d.ts.map +1 -0
  66. package/dist/profile-admin.js +351 -0
  67. package/dist/profile-admin.js.map +1 -0
  68. package/dist/profile-credentials.d.ts +68 -0
  69. package/dist/profile-credentials.d.ts.map +1 -0
  70. package/dist/profile-credentials.js +329 -0
  71. package/dist/profile-credentials.js.map +1 -0
  72. package/dist/profile-manager.d.ts +187 -0
  73. package/dist/profile-manager.d.ts.map +1 -0
  74. package/dist/profile-manager.js +1026 -0
  75. package/dist/profile-manager.js.map +1 -0
  76. package/dist/record-identifier-policy.d.ts +39 -0
  77. package/dist/record-identifier-policy.d.ts.map +1 -0
  78. package/dist/record-identifier-policy.js +203 -0
  79. package/dist/record-identifier-policy.js.map +1 -0
  80. package/dist/runtime-environment.d.ts +23 -0
  81. package/dist/runtime-environment.d.ts.map +1 -0
  82. package/dist/runtime-environment.js +58 -0
  83. package/dist/runtime-environment.js.map +1 -0
  84. package/dist/server.d.ts +33 -0
  85. package/dist/server.d.ts.map +1 -0
  86. package/dist/server.js +73 -0
  87. package/dist/server.js.map +1 -0
  88. package/dist/servicenow-identifiers.d.ts +8 -0
  89. package/dist/servicenow-identifiers.d.ts.map +1 -0
  90. package/dist/servicenow-identifiers.js +22 -0
  91. package/dist/servicenow-identifiers.js.map +1 -0
  92. package/dist/setup-prompts.d.ts +7 -0
  93. package/dist/setup-prompts.d.ts.map +1 -0
  94. package/dist/setup-prompts.js +123 -0
  95. package/dist/setup-prompts.js.map +1 -0
  96. package/dist/setup.d.ts +109 -0
  97. package/dist/setup.d.ts.map +1 -0
  98. package/dist/setup.js +1903 -0
  99. package/dist/setup.js.map +1 -0
  100. package/dist/startup.d.ts +43 -0
  101. package/dist/startup.d.ts.map +1 -0
  102. package/dist/startup.js +75 -0
  103. package/dist/startup.js.map +1 -0
  104. package/dist/stdio-runtime.d.ts +106 -0
  105. package/dist/stdio-runtime.d.ts.map +1 -0
  106. package/dist/stdio-runtime.js +231 -0
  107. package/dist/stdio-runtime.js.map +1 -0
  108. package/dist/structured-query.d.ts +187 -0
  109. package/dist/structured-query.d.ts.map +1 -0
  110. package/dist/structured-query.js +503 -0
  111. package/dist/structured-query.js.map +1 -0
  112. package/dist/table-defaults.d.ts +28 -0
  113. package/dist/table-defaults.d.ts.map +1 -0
  114. package/dist/table-defaults.js +85 -0
  115. package/dist/table-defaults.js.map +1 -0
  116. package/dist/table-policy.d.ts +71 -0
  117. package/dist/table-policy.d.ts.map +1 -0
  118. package/dist/table-policy.js +290 -0
  119. package/dist/table-policy.js.map +1 -0
  120. package/dist/tool-error.d.ts +48 -0
  121. package/dist/tool-error.d.ts.map +1 -0
  122. package/dist/tool-error.js +139 -0
  123. package/dist/tool-error.js.map +1 -0
  124. package/dist/tool-table-access.d.ts +19 -0
  125. package/dist/tool-table-access.d.ts.map +1 -0
  126. package/dist/tool-table-access.js +388 -0
  127. package/dist/tool-table-access.js.map +1 -0
  128. package/dist/tools/aggregate.d.ts +22 -42
  129. package/dist/tools/aggregate.d.ts.map +1 -1
  130. package/dist/tools/aggregate.js +103 -47
  131. package/dist/tools/aggregate.js.map +1 -1
  132. package/dist/tools/all-fields-cap.d.ts +45 -0
  133. package/dist/tools/all-fields-cap.d.ts.map +1 -0
  134. package/dist/tools/all-fields-cap.js +151 -0
  135. package/dist/tools/all-fields-cap.js.map +1 -0
  136. package/dist/tools/atf.d.ts +21 -60
  137. package/dist/tools/atf.d.ts.map +1 -1
  138. package/dist/tools/atf.js +180 -116
  139. package/dist/tools/atf.js.map +1 -1
  140. package/dist/tools/attach.d.ts +31 -45
  141. package/dist/tools/attach.d.ts.map +1 -1
  142. package/dist/tools/attach.js +175 -137
  143. package/dist/tools/attach.js.map +1 -1
  144. package/dist/tools/batch.d.ts +78 -42
  145. package/dist/tools/batch.d.ts.map +1 -1
  146. package/dist/tools/batch.js +172 -68
  147. package/dist/tools/batch.js.map +1 -1
  148. package/dist/tools/catalog.d.ts +6 -0
  149. package/dist/tools/catalog.d.ts.map +1 -0
  150. package/dist/tools/catalog.js +203 -0
  151. package/dist/tools/catalog.js.map +1 -0
  152. package/dist/tools/codesearch.d.ts +14 -25
  153. package/dist/tools/codesearch.d.ts.map +1 -1
  154. package/dist/tools/codesearch.js +60 -48
  155. package/dist/tools/codesearch.js.map +1 -1
  156. package/dist/tools/create-module.d.ts +48 -0
  157. package/dist/tools/create-module.d.ts.map +1 -0
  158. package/dist/tools/create-module.js +98 -0
  159. package/dist/tools/create-module.js.map +1 -0
  160. package/dist/tools/create.d.ts +2 -38
  161. package/dist/tools/create.d.ts.map +1 -1
  162. package/dist/tools/create.js +9 -41
  163. package/dist/tools/create.js.map +1 -1
  164. package/dist/tools/delete.d.ts +13 -23
  165. package/dist/tools/delete.d.ts.map +1 -1
  166. package/dist/tools/delete.js +30 -33
  167. package/dist/tools/delete.js.map +1 -1
  168. package/dist/tools/discover.d.ts +15 -27
  169. package/dist/tools/discover.d.ts.map +1 -1
  170. package/dist/tools/discover.js +103 -60
  171. package/dist/tools/discover.js.map +1 -1
  172. package/dist/tools/get-module.d.ts +85 -0
  173. package/dist/tools/get-module.d.ts.map +1 -0
  174. package/dist/tools/get-module.js +221 -0
  175. package/dist/tools/get-module.js.map +1 -0
  176. package/dist/tools/get.d.ts +2 -51
  177. package/dist/tools/get.d.ts.map +1 -1
  178. package/dist/tools/get.js +9 -49
  179. package/dist/tools/get.js.map +1 -1
  180. package/dist/tools/handler-result.d.ts +14 -0
  181. package/dist/tools/handler-result.d.ts.map +1 -0
  182. package/dist/tools/handler-result.js +177 -0
  183. package/dist/tools/handler-result.js.map +1 -0
  184. package/dist/tools/health.d.ts +12 -15
  185. package/dist/tools/health.d.ts.map +1 -1
  186. package/dist/tools/health.js +55 -36
  187. package/dist/tools/health.js.map +1 -1
  188. package/dist/tools/incident-journal-module.d.ts +12 -0
  189. package/dist/tools/incident-journal-module.d.ts.map +1 -0
  190. package/dist/tools/incident-journal-module.js +61 -0
  191. package/dist/tools/incident-journal-module.js.map +1 -0
  192. package/dist/tools/index.d.ts +47 -36
  193. package/dist/tools/index.d.ts.map +1 -1
  194. package/dist/tools/index.js +814 -35
  195. package/dist/tools/index.js.map +1 -1
  196. package/dist/tools/nl.d.ts +10 -24
  197. package/dist/tools/nl.d.ts.map +1 -1
  198. package/dist/tools/nl.js +37 -147
  199. package/dist/tools/nl.js.map +1 -1
  200. package/dist/tools/profile.d.ts +37 -0
  201. package/dist/tools/profile.d.ts.map +1 -0
  202. package/dist/tools/profile.js +39 -0
  203. package/dist/tools/profile.js.map +1 -0
  204. package/dist/tools/query-module.d.ts +119 -0
  205. package/dist/tools/query-module.d.ts.map +1 -0
  206. package/dist/tools/query-module.js +324 -0
  207. package/dist/tools/query-module.js.map +1 -0
  208. package/dist/tools/query.d.ts +2 -72
  209. package/dist/tools/query.d.ts.map +1 -1
  210. package/dist/tools/query.js +8 -72
  211. package/dist/tools/query.js.map +1 -1
  212. package/dist/tools/record-write-shared.d.ts +7 -0
  213. package/dist/tools/record-write-shared.d.ts.map +1 -0
  214. package/dist/tools/record-write-shared.js +65 -0
  215. package/dist/tools/record-write-shared.js.map +1 -0
  216. package/dist/tools/relationships.d.ts +21 -42
  217. package/dist/tools/relationships.d.ts.map +1 -1
  218. package/dist/tools/relationships.js +70 -56
  219. package/dist/tools/relationships.js.map +1 -1
  220. package/dist/tools/result-envelope.d.ts +603 -0
  221. package/dist/tools/result-envelope.d.ts.map +1 -0
  222. package/dist/tools/result-envelope.js +770 -0
  223. package/dist/tools/result-envelope.js.map +1 -0
  224. package/dist/tools/schema-module.d.ts +64 -0
  225. package/dist/tools/schema-module.d.ts.map +1 -0
  226. package/dist/tools/schema-module.js +367 -0
  227. package/dist/tools/schema-module.js.map +1 -0
  228. package/dist/tools/schema.d.ts +2 -37
  229. package/dist/tools/schema.d.ts.map +1 -1
  230. package/dist/tools/schema.js +6 -57
  231. package/dist/tools/schema.js.map +1 -1
  232. package/dist/tools/script.d.ts +33 -27
  233. package/dist/tools/script.d.ts.map +1 -1
  234. package/dist/tools/script.js +43 -37
  235. package/dist/tools/script.js.map +1 -1
  236. package/dist/tools/syslog.d.ts +19 -46
  237. package/dist/tools/syslog.d.ts.map +1 -1
  238. package/dist/tools/syslog.js +101 -67
  239. package/dist/tools/syslog.js.map +1 -1
  240. package/dist/tools/tool-module.d.ts +143 -0
  241. package/dist/tools/tool-module.d.ts.map +1 -0
  242. package/dist/tools/tool-module.js +1095 -0
  243. package/dist/tools/tool-module.js.map +1 -0
  244. package/dist/tools/update-module.d.ts +51 -0
  245. package/dist/tools/update-module.d.ts.map +1 -0
  246. package/dist/tools/update-module.js +111 -0
  247. package/dist/tools/update-module.js.map +1 -0
  248. package/dist/tools/update.d.ts +2 -45
  249. package/dist/tools/update.d.ts.map +1 -1
  250. package/dist/tools/update.js +9 -41
  251. package/dist/tools/update.js.map +1 -1
  252. package/dist/utils.d.ts +68 -1
  253. package/dist/utils.d.ts.map +1 -1
  254. package/dist/utils.js +114 -16
  255. package/dist/utils.js.map +1 -1
  256. package/dist/version.d.ts +10 -0
  257. package/dist/version.d.ts.map +1 -0
  258. package/dist/version.js +13 -0
  259. package/dist/version.js.map +1 -0
  260. package/dist/write-value-policy.d.ts +56 -0
  261. package/dist/write-value-policy.d.ts.map +1 -0
  262. package/dist/write-value-policy.js +310 -0
  263. package/dist/write-value-policy.js.map +1 -0
  264. package/docs/ADDING-TOOLS.md +227 -0
  265. package/docs/CLIENT-SETUP.md +914 -0
  266. package/docs/CONTAINER-DEPLOYMENT.md +310 -0
  267. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +63 -0
  268. package/docs/ENTERPRISE-RELEASE-BOUNDARY.md +149 -0
  269. package/docs/OPERATIONS-RUNBOOK.md +383 -0
  270. package/docs/PRIVATE-CHATGPT-CONNECTIVITY.md +347 -0
  271. package/docs/PRODUCTION-SECURITY.md +368 -0
  272. package/docs/PROFILE-CREDENTIALS.md +126 -0
  273. package/docs/RELEASE-VALIDATION.md +140 -0
  274. package/docs/TESTING-OAUTH.md +101 -0
  275. package/docs/V2-MIGRATION.md +493 -0
  276. package/package.json +60 -13
  277. package/scripts/inspector.mjs +140 -0
  278. package/scripts/release-validate.mjs +201 -0
  279. package/scripts/smoke-test.mjs +274 -0
  280. package/tools/inspector/package-lock.json +3812 -0
  281. package/tools/inspector/package.json +12 -0
package/dist/setup.js ADDED
@@ -0,0 +1,1903 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ /**
4
+ * Interactive-safe local bootstrap for @onlyflows/servicenow-mcp.
5
+ *
6
+ * The server speaks stdio: a client spawns the packaged binary and talks to it
7
+ * over the child's stdin/stdout. There is no service to start, no port, and no
8
+ * endpoint, so setup's job ends at a registered client, a verified credential,
9
+ * and a profile that grants exactly the tables the operator chose.
10
+ *
11
+ * Four subcommands, none of which ever accept, print, or log a secret value:
12
+ *
13
+ * - `init` (default) generates the owner-only local env file, registers the
14
+ * clients that have a CLI, and prints copy-pasteable configuration for the
15
+ * clients that do not.
16
+ * - `client` prints that configuration for one named client on demand.
17
+ * - `grant` writes least-privilege `tableAccess` rules onto an existing
18
+ * profile, which is otherwise only reachable by hand-editing the
19
+ * owner-only profile file.
20
+ * - `doctor` diagnoses a local install end to end and reports the exact
21
+ * remedy for each failure.
22
+ *
23
+ * @module setup
24
+ */
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.WizardAbort = void 0;
27
+ exports.runSetupCli = runSetupCli;
28
+ exports.instanceProblem = instanceProblem;
29
+ exports.classifyVerificationFailure = classifyVerificationFailure;
30
+ exports.createTtyPrompter = createTtyPrompter;
31
+ exports.resolveChoice = resolveChoice;
32
+ const node_crypto_1 = require("node:crypto");
33
+ const node_fs_1 = require("node:fs");
34
+ const node_os_1 = require("node:os");
35
+ const node_path_1 = require("node:path");
36
+ const node_child_process_1 = require("node:child_process");
37
+ const promises_1 = require("node:readline/promises");
38
+ const client_js_1 = require("./client.js");
39
+ const profile_admin_js_1 = require("./profile-admin.js");
40
+ const profile_credentials_js_1 = require("./profile-credentials.js");
41
+ const profile_manager_js_1 = require("./profile-manager.js");
42
+ const tool_error_js_1 = require("./tool-error.js");
43
+ const table_policy_js_1 = require("./table-policy.js");
44
+ /** Raised when the operator aborts; nothing has been written to the profile. */
45
+ class WizardAbort extends Error {
46
+ constructor() {
47
+ super("Setup cancelled. No profile was written.");
48
+ this.name = "WizardAbort";
49
+ }
50
+ }
51
+ exports.WizardAbort = WizardAbort;
52
+ /** Clients this bootstrap can register non-interactively through their own CLI. */
53
+ const AUTO_REGISTERED_CLIENTS = Object.freeze([
54
+ "codex",
55
+ "claude-code",
56
+ ]);
57
+ const ALL_CLIENTS = Object.freeze([
58
+ "codex",
59
+ "claude-code",
60
+ "claude-desktop",
61
+ "cursor",
62
+ "vscode",
63
+ "windsurf",
64
+ ]);
65
+ const CONFIG_RELATIVE_DIR = ".servicenow-mcp";
66
+ const SERVER_ENV_RELATIVE_PATH = `${CONFIG_RELATIVE_DIR}/server.env`;
67
+ const PROFILE_CONFIG_RELATIVE_PATH = `${CONFIG_RELATIVE_DIR}/config.json`;
68
+ const MCP_SERVER_NAME = "servicenow-mcp";
69
+ const ENCRYPTION_KEY_ENV = "SN_PROFILE_ENCRYPTION_KEY";
70
+ /** The command every registered client is told to spawn. */
71
+ const SERVER_COMMAND = "servicenow-mcp";
72
+ /**
73
+ * What `server.env` must hold for a spawned server to attribute its audit
74
+ * records to a stable identity. The server reads this file itself at startup:
75
+ * the client that spawns it supplies its own environment and will not have
76
+ * sourced anything.
77
+ */
78
+ const REQUIRED_SERVER_ENV_VALUES = Object.freeze([
79
+ "MCP_OWNER_ID",
80
+ "MCP_CLIENT_ID",
81
+ ]);
82
+ /**
83
+ * Stated wherever setup reports what it built.
84
+ *
85
+ * There is no port and nothing listening, so the boundary is not a network one
86
+ * and saying "unauthenticated" would name the wrong risk. What is true is that
87
+ * every client registered below can spawn a server that acts as you, with the
88
+ * full reach of these profiles' grants. That is the sentence an operator has to
89
+ * read without opening the docs first.
90
+ */
91
+ const STDIO_BOUNDARY_NOTICE = Object.freeze([
92
+ "The server runs as you. Each registered client starts its own copy on",
93
+ "demand and speaks to it over that process's stdin/stdout. Nothing listens",
94
+ "on a port, and nothing off this machine can reach it.",
95
+ "",
96
+ "So the boundary is the client list and the grants: any client registered",
97
+ "here can read and write every table your profiles allow, as your ServiceNow",
98
+ "account. Keep the grants narrow, and remove a client you no longer use with",
99
+ '"claude mcp remove servicenow-mcp" or "codex mcp remove servicenow-mcp".',
100
+ "",
101
+ "No ServiceNow credential is copied into a client configuration file. The",
102
+ "spawned server reads the profile and its encryption key from the owner-only",
103
+ "~/.servicenow-mcp directory.",
104
+ ]);
105
+ /** Printed under every client recipe, because none of them carries a credential. */
106
+ const CREDENTIAL_FOOTNOTE = "Nothing above carries a ServiceNow credential. The spawned server reads the\n" +
107
+ "profile and its encryption key from ~/.servicenow-mcp, which is owner-only,\n" +
108
+ "so no secret reaches a client configuration file.\n";
109
+ const MINIMUM_NODE_MAJOR = 20;
110
+ /** Tables addressable by a read grant when `--tools` is not given. */
111
+ const DEFAULT_READ_TOOLS = Object.freeze([
112
+ "sn_query",
113
+ "sn_get",
114
+ "sn_aggregate",
115
+ "sn_schema",
116
+ ]);
117
+ /**
118
+ * Tables addressable by a write grant when `--tools` is not given.
119
+ * Deliberately excludes `sn_delete` and `sn_batch`: those are
120
+ * destructive or multi-table and should be named explicitly with `--tools`.
121
+ */
122
+ const DEFAULT_WRITE_TOOLS = Object.freeze([
123
+ "sn_create",
124
+ "sn_update",
125
+ ]);
126
+ async function runSetupCli(dependencies = {}) {
127
+ const env = dependencies.env ?? process.env;
128
+ const argv = normalizeArgv(dependencies.argv ?? process.argv.slice(2));
129
+ const out = dependencies.writeStdout ?? ((value) => process.stdout.write(value));
130
+ const err = dependencies.writeStderr ?? ((value) => process.stderr.write(value));
131
+ const home = dependencies.home ?? env.HOME ?? (0, node_os_1.homedir)();
132
+ const { subcommand, args } = splitSubcommand(argv);
133
+ switch (subcommand) {
134
+ case "client":
135
+ runClient(parseClientArguments(args), out);
136
+ return;
137
+ case "grant":
138
+ runGrant(parseGrantArguments(args), home, dependencies, out);
139
+ return;
140
+ case "doctor":
141
+ await runDoctor(parseDoctorArguments(args), home, env, dependencies, out);
142
+ return;
143
+ case "init": {
144
+ const options = parseInitArguments(args);
145
+ if (shouldRunWizard(options, args, dependencies)) {
146
+ await runWizard(options, home, env, dependencies, out);
147
+ return;
148
+ }
149
+ await runInit(options, home, env, dependencies, out, err);
150
+ return;
151
+ }
152
+ }
153
+ }
154
+ // ── wizard ─────────────────────────────────────────────────────────
155
+ const WIZARD_PROBE_TABLE = "sys_user";
156
+ const DEFAULT_READ_TABLES = "incident";
157
+ const TABLE_ALLOWLIST_WILDCARD = "*";
158
+ const TABLE_NAME = /^[a-z][a-z0-9_]{0,79}$/u;
159
+ /**
160
+ * One command from nothing to a working connection.
161
+ *
162
+ * Order matters for safety: env files first (idempotent, no operator data),
163
+ * then everything else collected in memory, and the profile written **once**
164
+ * at the end with its table-access rules already attached. Nothing reaches the
165
+ * profile file until the credential has been verified against the instance, so
166
+ * an abort or a wrong password leaves no half-written profile behind.
167
+ */
168
+ async function runWizard(options, home, env, dependencies, out) {
169
+ const paths = resolvePaths(home);
170
+ const prompter = dependencies.prompter ??
171
+ createTtyPrompter({
172
+ input: process.stdin,
173
+ output: process.stdout,
174
+ ...(dependencies.secretIo ? { secretIo: dependencies.secretIo } : {}),
175
+ });
176
+ const manager = dependencies.profileManager ?? profileManagerFor(home);
177
+ try {
178
+ prompter.note("ServiceNow MCP setup\n\n" +
179
+ "This walks through one ServiceNow connection end to end. Nothing is\n" +
180
+ "written to the profile until your credential is verified against the\n" +
181
+ "instance. Press Ctrl+C at any point to stop; nothing will be saved.\n");
182
+ // 1. Local identity and key material. Idempotent, so this is silent.
183
+ const values = loadOrCreateBootstrapValues(paths, options);
184
+ writeSecureEnvFile(paths.serverEnv, values);
185
+ // The key just written to server.env is not in this process's environment,
186
+ // so it must be carried in memory. `values` already holds it, whether it
187
+ // was generated now or loaded from an earlier bootstrap. Bound and
188
+ // validated here so a corrupt key fails before anything is prompted for.
189
+ const keyProvider = dependencies.keyProvider ?? (0, profile_credentials_js_1.encryptionKeyProviderFromValue)(values[ENCRYPTION_KEY_ENV]);
190
+ // 2. Re-run safety: never clobber an existing profile without being told.
191
+ const existing = existingProfileNames(manager);
192
+ if (existing.length > 0) {
193
+ prompter.note(`Existing profiles: ${existing.join(", ")}\n`);
194
+ const choice = await prompter.ask("Add another profile, or just re-register MCP clients?", { default: "profile", choices: ["profile", "clients"] });
195
+ if (choice === "clients") {
196
+ const only = await registerClientsInteractively(prompter, options, env, dependencies);
197
+ out(renderClientOnlySummary(only, home));
198
+ return;
199
+ }
200
+ prompter.note("Existing profiles are left untouched.\n");
201
+ }
202
+ const name = await askProfileName(prompter, existing);
203
+ const instance = await askInstance(prompter);
204
+ const authType = await askAuthType(prompter);
205
+ const grantType = authType === "oauth"
206
+ ? (await prompter.ask("OAuth grant type", {
207
+ default: "client_credentials",
208
+ choices: ["client_credentials", "password"],
209
+ }))
210
+ : "client_credentials";
211
+ // Asked here, before any secret is in hand. A mistyped answer to a
212
+ // question adjacent to a credential prompt echoes the credential, so the
213
+ // last thing before the hidden prompts is deliberately not this question.
214
+ const mode = (await prompter.ask("How should the credential be stored?", {
215
+ default: "encrypted",
216
+ choices: ["encrypted", "reference"],
217
+ }));
218
+ const provider = mode === "reference"
219
+ ? await prompter.ask("Secret provider", { default: "env", choices: ["env"] })
220
+ : undefined;
221
+ const profile = { instance, authType };
222
+ if (authType === "basic" || grantType === "password") {
223
+ profile.username = await prompter.ask("ServiceNow username", {
224
+ validate: (value) => value.trim() === "" ? "A username is required for this auth mode." : undefined,
225
+ });
226
+ }
227
+ if (authType === "oauth") {
228
+ profile.grantType = grantType;
229
+ profile.clientId = await prompter.ask("OAuth client id (not a secret)", {
230
+ validate: (value) => value.trim() === "" ? "A client id is required for OAuth." : undefined,
231
+ });
232
+ }
233
+ if (authType === "apikey") {
234
+ profile.apiKeyHeader = await prompter.ask("API key header", {
235
+ default: "x-sn-apikey",
236
+ });
237
+ }
238
+ const fields = (0, profile_admin_js_1.requiredSecretFields)(authType, grantType);
239
+ (0, profile_admin_js_1.validateCreateMetadata)(profile, fields);
240
+ // 3. Capture the secrets. Never echoed, never in argv, never logged.
241
+ prompter.note(mode === "reference"
242
+ ? "\nEnter the NAME of the environment variable holding each secret.\n" +
243
+ "Input is hidden."
244
+ : "\nEnter each secret now. Input is hidden — nothing you type from here\n" +
245
+ "is displayed.");
246
+ const captured = [];
247
+ for (const field of fields) {
248
+ captured.push(Object.freeze({ field, mode, value: await prompter.secret(field) }));
249
+ }
250
+ // 4. Verify against the live instance before anything is persisted.
251
+ const config = wizardConfig(profile, captured, mode, env);
252
+ const verify = dependencies.verifyCredential ?? verifyCredentialAgainstInstance;
253
+ prompter.note("\nVerifying against the instance...");
254
+ let verification = await verify(config);
255
+ while (!verification.ok) {
256
+ prompter.note(`\n FAILED ${verification.detail}`);
257
+ if (verification.remedy)
258
+ prompter.note(` -> ${verification.remedy}`);
259
+ if (!(await prompter.confirm("\nRetry with the same settings?", true))) {
260
+ throw new WizardAbort();
261
+ }
262
+ verification = await verify(config);
263
+ }
264
+ prompter.note(` ok ${verification.detail}`);
265
+ if (verification.authenticatedButDenied) {
266
+ prompter.note(` note this account cannot read ${WIZARD_PROBE_TABLE}, so metadata\n` +
267
+ " caching will stay disabled for it. Not a setup failure.");
268
+ }
269
+ // 5. Table access. A profile without rules denies every call.
270
+ const tableAccess = await askTableAccess(prompter, config, dependencies);
271
+ // 6. One write, with the rules already attached — never a rules-less window.
272
+ //
273
+ // Retryable without re-prompting: everything needed is already in memory,
274
+ // so a failure here must not cost the operator the instance, the auth
275
+ // details, the secret they typed, or the verification round trip.
276
+ profile.tableAccess = tableAccess;
277
+ for (;;) {
278
+ try {
279
+ for (const secret of captured) {
280
+ profile[secret.field] = (0, profile_admin_js_1.materializeProfileSecret)(secret, { mode, ...(provider === undefined ? {} : { provider }) }, name, secret.field, keyProvider);
281
+ }
282
+ manager.addProfile(name, profile);
283
+ break;
284
+ }
285
+ catch (error) {
286
+ prompter.note(`\n FAILED could not save the profile: ${describeError(error)}`);
287
+ prompter.note(" Your answers are still held in memory, including the verified\n" +
288
+ " credential. Fix the cause and retry, and nothing needs re-typing.");
289
+ if (!(await prompter.confirm("\nRetry saving the profile?", true))) {
290
+ throw new WizardAbort();
291
+ }
292
+ }
293
+ }
294
+ prompter.note(`\nWrote profile ${name}.\n${JSON.stringify((0, profile_admin_js_1.safeProfileView)(name, profile), null, 2)}\n`);
295
+ // 7. Client configuration.
296
+ const registered = await registerClientsInteractively(prompter, options, env, dependencies);
297
+ // 8. Verify the install the way `doctor` does, so setup ends by reporting
298
+ // the same facts rather than commands for the operator to copy. There
299
+ // is nothing to start: a registered client spawns the server itself.
300
+ const checks = runInstallChecks(paths, home, env, dependencies, name);
301
+ prompter.note(`\n${renderDoctorText(checks)}`);
302
+ out(renderWizardSummary(name, tableAccess, registered, home, checks));
303
+ }
304
+ finally {
305
+ prompter.close();
306
+ }
307
+ }
308
+ /**
309
+ * The checks that decide whether this install actually works.
310
+ *
311
+ * Shared by the wizard's final report and by `doctor`, so what setup says and
312
+ * what `doctor` says can never drift apart.
313
+ */
314
+ function runInstallChecks(paths, home, env, dependencies, profile) {
315
+ return Object.freeze([
316
+ checkNodeVersion(),
317
+ checkServerCommand(dependencies),
318
+ checkDirectoryMode(paths.configDir),
319
+ ...checkEnvFile(paths.serverEnv, REQUIRED_SERVER_ENV_VALUES),
320
+ ...checkProfiles(paths, home, env, dependencies, profile),
321
+ ]);
322
+ }
323
+ function existingProfileNames(manager) {
324
+ try {
325
+ return manager.listProfiles().map((entry) => entry.name);
326
+ }
327
+ catch {
328
+ return [];
329
+ }
330
+ }
331
+ async function askProfileName(prompter, existing) {
332
+ return prompter.ask("Profile name", {
333
+ default: existing.includes("dev") ? "" : "dev",
334
+ validate: (value) => {
335
+ const name = value.trim();
336
+ if (name === "")
337
+ return "A profile name is required.";
338
+ if (existing.includes(name)) {
339
+ return `Profile "${name}" already exists. Choose another name, or remove it with servicenow-mcp-profile remove --name ${name}.`;
340
+ }
341
+ return undefined;
342
+ },
343
+ });
344
+ }
345
+ const SERVICENOW_SUFFIXES = Object.freeze([".service-now.com", ".servicenowservices.com"]);
346
+ async function askInstance(prompter) {
347
+ const answer = await prompter.ask("ServiceNow instance (for example dev12345.service-now.com)", { validate: instanceProblem });
348
+ return (0, profile_manager_js_1.normalizeInstanceUrl)(answer);
349
+ }
350
+ /**
351
+ * Accept a bare host or a full URL. `.servicenow.com` is the common typo for
352
+ * `.service-now.com` and is worth naming precisely rather than reporting as a
353
+ * generic domain rejection after a failed probe.
354
+ */
355
+ function instanceProblem(value) {
356
+ let normalized;
357
+ try {
358
+ normalized = (0, profile_manager_js_1.normalizeInstanceUrl)(value);
359
+ }
360
+ catch (error) {
361
+ return describeError(error);
362
+ }
363
+ const host = new URL(normalized).hostname.toLowerCase();
364
+ if (SERVICENOW_SUFFIXES.some((suffix) => host.endsWith(suffix)))
365
+ return undefined;
366
+ if (/\.servicenow\.com$/u.test(host)) {
367
+ return `"${host}" looks like a typo: ServiceNow instances are *.service-now.com, with a hyphen.`;
368
+ }
369
+ // Falls back to the server's own rule, which honors SN_ALLOWED_INSTANCE_HOSTS.
370
+ const problem = (0, profile_manager_js_1.instanceHostError)(normalized);
371
+ if (problem === undefined)
372
+ return undefined;
373
+ return (`"${host}" is not a ServiceNow domain. Expected *.service-now.com or ` +
374
+ "*.servicenowservices.com. For a self-hosted or custom-domain instance, set " +
375
+ "SN_ALLOWED_INSTANCE_HOSTS before running setup.");
376
+ }
377
+ async function askAuthType(prompter) {
378
+ return (await prompter.ask("Authentication", {
379
+ default: "basic",
380
+ choices: ["basic", "oauth", "apikey"],
381
+ }));
382
+ }
383
+ /** Build a throwaway config for verification. Never persisted. */
384
+ function wizardConfig(profile, captured, mode, env) {
385
+ const plaintext = (field) => {
386
+ const entry = captured.find((candidate) => candidate.field === field);
387
+ if (entry === undefined)
388
+ return "";
389
+ // A reference stores a variable NAME; resolve it exactly as the server will.
390
+ return mode === "reference" ? (env[entry.value] ?? "") : entry.value;
391
+ };
392
+ return {
393
+ instance: profile.instance,
394
+ user: profile.username ?? "",
395
+ password: plaintext("credential"),
396
+ displayValue: "true",
397
+ relDepth: 1,
398
+ ...(profile.authType ? { authType: profile.authType } : {}),
399
+ ...(profile.clientId ? { clientId: profile.clientId } : {}),
400
+ ...(profile.grantType ? { grantType: profile.grantType } : {}),
401
+ ...(profile.apiKeyHeader ? { apiKeyHeader: profile.apiKeyHeader } : {}),
402
+ clientSecret: plaintext("clientSecret"),
403
+ apiKey: plaintext("apiKey"),
404
+ timeoutMs: 15_000,
405
+ };
406
+ }
407
+ /**
408
+ * One bounded authenticated read. This is the check `doctor` structurally
409
+ * cannot make: doctor resolves a credential locally, this proves ServiceNow
410
+ * accepts it.
411
+ */
412
+ async function verifyCredentialAgainstInstance(config) {
413
+ const client = new client_js_1.ServiceNowClient(config, { maxRetries: 0 });
414
+ try {
415
+ await client.get(`/api/now/table/${WIZARD_PROBE_TABLE}`, {
416
+ sysparm_limit: "1",
417
+ sysparm_fields: "user_name",
418
+ });
419
+ return Object.freeze({
420
+ ok: true,
421
+ detail: `${config.instance} accepted the credential.`,
422
+ });
423
+ }
424
+ catch (error) {
425
+ return classifyVerificationFailure(error, config);
426
+ }
427
+ }
428
+ /** Map a probe failure onto the thing the operator must actually change. */
429
+ function classifyVerificationFailure(error, config) {
430
+ const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
431
+ const host = safeHost(config.instance);
432
+ if (descriptor?.category === "authentication") {
433
+ return Object.freeze({
434
+ ok: false,
435
+ detail: `${host} rejected the credential (HTTP 401).`,
436
+ remedy: config.authType === "oauth"
437
+ ? "Check the OAuth client id and secret, and that the client is active on the instance."
438
+ : "Check the username and password. A ServiceNow account locked out or requiring a password reset also returns 401.",
439
+ });
440
+ }
441
+ if (descriptor?.category === "authorization") {
442
+ // The credential authenticated; the instance refused this specific read.
443
+ return Object.freeze({
444
+ ok: true,
445
+ authenticatedButDenied: true,
446
+ detail: `${host} accepted the credential but denied reading ${WIZARD_PROBE_TABLE} (HTTP 403).`,
447
+ });
448
+ }
449
+ if (descriptor?.category === "not_found") {
450
+ return Object.freeze({
451
+ ok: false,
452
+ detail: `${host} has no Table API at the expected path (HTTP 404).`,
453
+ remedy: "Confirm the instance URL. A hibernating developer instance and a mistyped subdomain both look like this.",
454
+ });
455
+ }
456
+ if (descriptor?.category === "rate_limit") {
457
+ return Object.freeze({
458
+ ok: false,
459
+ detail: `${host} rate-limited the request (HTTP 429).`,
460
+ remedy: "Wait for the instance rate limit to clear, then retry.",
461
+ });
462
+ }
463
+ if (descriptor?.category === "timeout") {
464
+ return Object.freeze({
465
+ ok: false,
466
+ detail: `${host} did not respond before the timeout.`,
467
+ remedy: "The instance may be waking from hibernation, or an IP access control list may be dropping this host. Retry, then check the instance's IP Address Access Control.",
468
+ });
469
+ }
470
+ const message = describeError(error);
471
+ if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/iu.test(message)) {
472
+ return Object.freeze({
473
+ ok: false,
474
+ detail: `${host} does not resolve in DNS.`,
475
+ remedy: "Check the instance name for a typo. Enter just the host, for example dev12345.service-now.com.",
476
+ });
477
+ }
478
+ if (/ECONNREFUSED|ECONNRESET|EHOSTUNREACH|ENETUNREACH|socket hang up/iu.test(message)) {
479
+ return Object.freeze({
480
+ ok: false,
481
+ detail: `${host} refused or dropped the connection.`,
482
+ remedy: "This is what an instance-side IP access control list looks like from here. Check the instance's IP Address Access Control, and any outbound proxy or firewall on this machine.",
483
+ });
484
+ }
485
+ if (/certificate|self-signed|CERT_|unable to verify/iu.test(message)) {
486
+ return Object.freeze({
487
+ ok: false,
488
+ detail: `${host} presented a TLS certificate this machine does not trust.`,
489
+ remedy: "Install the issuing CA on this machine. Do not disable certificate verification.",
490
+ });
491
+ }
492
+ return Object.freeze({
493
+ ok: false,
494
+ detail: `${host} could not be reached: ${message}`,
495
+ remedy: "Check the instance URL and this machine's outbound network access.",
496
+ });
497
+ }
498
+ function safeHost(instance) {
499
+ try {
500
+ return new URL(instance).host;
501
+ }
502
+ catch {
503
+ return "the instance";
504
+ }
505
+ }
506
+ async function askTableAccess(prompter, config, dependencies) {
507
+ prompter.note("\nTable access is deny-by-default: a profile with no rules denies every\n" +
508
+ "tool call. Grant the narrowest set that does the job; you can add more\n" +
509
+ "later with servicenow-mcp-setup grant.\n");
510
+ const read = await askTableSelection(prompter, "READS", DEFAULT_READ_TABLES);
511
+ const write = await askTableSelection(prompter, "WRITES", "");
512
+ const related = new Map();
513
+ for (const table of new Set([...read, ...write])) {
514
+ if (table === TABLE_ALLOWLIST_WILDCARD)
515
+ continue;
516
+ const parent = await lookupParentTable(config, table, dependencies);
517
+ if (parent === undefined || parent === table)
518
+ continue;
519
+ prompter.note(`\n ${table} extends ${parent}.`);
520
+ const include = await prompter.confirm(` Declare ${parent} as a backing table of ${table}? ` +
521
+ `This adds ${parent} to the allowlist without making it directly readable.`, false);
522
+ if (include)
523
+ related.set(table, [parent]);
524
+ }
525
+ const options = Object.freeze({
526
+ profile: "",
527
+ read,
528
+ write,
529
+ related,
530
+ replace: true,
531
+ dryRun: false,
532
+ json: false,
533
+ });
534
+ return buildTableAccess(Object.freeze({}), options);
535
+ }
536
+ const COMMON_ITSM_TABLES = "incident,change_request,problem,task,sys_user";
537
+ /**
538
+ * Offer the shapes operators actually want, including the wildcard. `*` is a
539
+ * supported configuration, so it is presented plainly with its consequence
540
+ * rather than hidden or argued against.
541
+ */
542
+ async function askTableSelection(prompter, operation, fallback) {
543
+ const noneLabel = operation === "WRITES" ? "None" : "None";
544
+ const choices = [
545
+ "Just incident",
546
+ `Common ITSM set (${COMMON_ITSM_TABLES})`,
547
+ "All tables (*)",
548
+ "Enter a custom list",
549
+ noneLabel,
550
+ ];
551
+ const choice = await prompter.ask(`Tables to allow for ${operation}`, {
552
+ default: fallback === "" ? noneLabel : choices[0],
553
+ choices,
554
+ });
555
+ if (choice === noneLabel)
556
+ return Object.freeze([]);
557
+ if (choice === choices[0])
558
+ return Object.freeze(["incident"]);
559
+ if (choice === choices[1])
560
+ return parseTableList(COMMON_ITSM_TABLES, operation);
561
+ if (choice === choices[2]) {
562
+ prompter.note(`\n "*" grants every table for ${operation.toLowerCase()}. ServiceNow's own\n` +
563
+ " per-user ACLs are then the only remaining boundary, so the integration\n" +
564
+ " account's roles become the whole control. It also skips the per-tool\n" +
565
+ " binding and the related-table closure check.\n");
566
+ return Object.freeze(["*"]);
567
+ }
568
+ return askCustomTableList(prompter, operation);
569
+ }
570
+ async function askCustomTableList(prompter, operation) {
571
+ const label = `Comma-separated tables for ${operation}`;
572
+ const answer = await prompter.ask(label, {
573
+ validate: (value) => {
574
+ if (value.trim() === "")
575
+ return "Enter at least one table name.";
576
+ try {
577
+ parseTableList(value, label);
578
+ return undefined;
579
+ }
580
+ catch (error) {
581
+ return describeError(error);
582
+ }
583
+ },
584
+ });
585
+ return parseTableList(answer, label);
586
+ }
587
+ /**
588
+ * Report the table this one extends, so the operator is not required to know
589
+ * ServiceNow's inheritance graph. Best effort: a failure here is not a setup
590
+ * failure, because the self-only closure the wizard writes is valid on its own.
591
+ */
592
+ async function lookupParentTable(config, table, dependencies) {
593
+ const resolve = dependencies.resolveParentTable ?? defaultParentTable;
594
+ try {
595
+ return await resolve(config, table);
596
+ }
597
+ catch {
598
+ return undefined;
599
+ }
600
+ }
601
+ async function defaultParentTable(config, table) {
602
+ if (!TABLE_NAME.test(table))
603
+ return undefined;
604
+ const client = new client_js_1.ServiceNowClient(config, { maxRetries: 0 });
605
+ const response = await client.get("/api/now/table/sys_db_object", {
606
+ sysparm_query: `name=${table}`,
607
+ sysparm_fields: "name,super_class",
608
+ sysparm_limit: "1",
609
+ sysparm_display_value: "true",
610
+ sysparm_exclude_reference_link: "true",
611
+ });
612
+ const row = Array.isArray(response?.result) ? response.result[0] : undefined;
613
+ if (typeof row !== "object" || row === null)
614
+ return undefined;
615
+ const value = row.super_class;
616
+ const parent = typeof value === "string"
617
+ ? value
618
+ : typeof value === "object" && value !== null
619
+ ? value.display_value
620
+ : undefined;
621
+ if (typeof parent !== "string")
622
+ return undefined;
623
+ const normalized = parent.trim().toLowerCase();
624
+ return TABLE_NAME.test(normalized) ? normalized : undefined;
625
+ }
626
+ async function registerClientsInteractively(prompter, options, env, dependencies) {
627
+ const commandExists = dependencies.commandExists ?? defaultCommandExists;
628
+ const runCommand = dependencies.runCommand ?? defaultRunCommand;
629
+ const available = AUTO_REGISTERED_CLIENTS.filter((client) => commandExists(client === "codex" ? "codex" : "claude"));
630
+ if (available.length === 0)
631
+ return Object.freeze([]);
632
+ if (!(await prompter.confirm(`\nRegister this server with ${available.join(" and ")}?`, true))) {
633
+ return Object.freeze([]);
634
+ }
635
+ const context = { commandExists, runCommand, env };
636
+ const configured = [];
637
+ for (const client of available) {
638
+ const result = registerClient(client, options.force, context);
639
+ if (result.ok)
640
+ configured.push(client);
641
+ else
642
+ prompter.note(` skipped ${client}: ${result.reason}`);
643
+ }
644
+ return Object.freeze(configured);
645
+ }
646
+ function renderWizardSummary(profile, tableAccess, registered, home, checks) {
647
+ const failed = checks.filter((check) => !check.ok).length;
648
+ const lines = [
649
+ "",
650
+ "Setup complete.",
651
+ "",
652
+ `Profile ${profile}`,
653
+ `Reads ${(tableAccess.readTables ?? []).join(", ") || "(none)"}`,
654
+ `Writes ${(tableAccess.writeTables ?? []).join(", ") || "(none)"}`,
655
+ `Transport stdio (each client spawns its own ${SERVER_COMMAND})`,
656
+ `Clients ${registered.length > 0 ? registered.join(", ") : "(none registered)"}`,
657
+ "",
658
+ ];
659
+ if (failed > 0) {
660
+ lines.push(`${failed} check${failed === 1 ? "" : "s"} above still need attention; the`, "remedies are printed with them.", "");
661
+ }
662
+ else if (registered.length > 0) {
663
+ lines.push(`Start ${registered.join(" or ")} and it will launch the server itself.`, "There is nothing to keep running between sessions.", "");
664
+ }
665
+ if (registered.length === 0) {
666
+ lines.push("Configure a client by hand:", " servicenow-mcp-setup client --client all", "");
667
+ }
668
+ lines.push("Re-check everything at any time:", ` servicenow-mcp-setup doctor --profile ${profile}`, "");
669
+ lines.push(...STDIO_BOUNDARY_NOTICE, "");
670
+ return `${lines.join("\n")}\n`;
671
+ }
672
+ function renderClientOnlySummary(registered, home) {
673
+ void home;
674
+ return (`\nClients ${registered.length > 0 ? registered.join(", ") : "(none registered)"}\n` +
675
+ `Transport stdio (each client spawns its own ${SERVER_COMMAND})\n\n` +
676
+ `Configure any remaining client by hand:\n` +
677
+ ` servicenow-mcp-setup client --client all\n`);
678
+ }
679
+ /**
680
+ * Detach every reader currently attached to the input stream and return a
681
+ * function that puts them back exactly as they were.
682
+ *
683
+ * readline installs its own data/keypress handling and echoes what it reads.
684
+ * Leaving it attached during a hidden read renders the secret in the terminal
685
+ * under a prompt that says input is hidden — reproduced against a pty, and the
686
+ * reason this exists. Snapshot-and-restore rather than close-and-recreate so
687
+ * later prompts continue on the same interface.
688
+ */
689
+ function detachInputReaders(input) {
690
+ const saved = [];
691
+ for (const event of ["data", "keypress", "readable"]) {
692
+ for (const listener of input.listeners(event)) {
693
+ saved.push([event, listener]);
694
+ }
695
+ input.removeAllListeners(event);
696
+ }
697
+ return () => {
698
+ for (const [event, listener] of saved)
699
+ input.on(event, listener);
700
+ };
701
+ }
702
+ /** Readline prompter. It owns stdin, including the handoff for secrets. */
703
+ function createTtyPrompter(streams) {
704
+ const { input, output } = streams;
705
+ const rl = (0, promises_1.createInterface)({ input, output });
706
+ const secretIo = streams.secretIo ?? (0, profile_admin_js_1.createProtectedInputIO)(input, output);
707
+ let closed = false;
708
+ return {
709
+ async ask(question, options = {}) {
710
+ for (;;) {
711
+ const answer = (await rl.question(renderQuestion(question, options))).trim();
712
+ const resolved = resolveChoice(answer, options);
713
+ if (resolved === undefined) {
714
+ output.write(` Enter a number, or one of: ${options.choices?.join(", ")}\n`);
715
+ continue;
716
+ }
717
+ const problem = options.validate?.(resolved);
718
+ if (problem !== undefined) {
719
+ output.write(` ${problem}\n`);
720
+ continue;
721
+ }
722
+ return resolved;
723
+ }
724
+ },
725
+ async confirm(question, defaultYes) {
726
+ const answer = (await rl.question(`${question} [${defaultYes ? "Y/n" : "y/N"}]: `))
727
+ .trim()
728
+ .toLowerCase();
729
+ if (answer === "")
730
+ return defaultYes;
731
+ return answer === "y" || answer === "yes";
732
+ },
733
+ async secret(label) {
734
+ rl.pause();
735
+ const restore = detachInputReaders(input);
736
+ try {
737
+ return await secretIo.readSensitive(label);
738
+ }
739
+ finally {
740
+ restore();
741
+ rl.resume();
742
+ }
743
+ },
744
+ note(text) {
745
+ output.write(`${text}\n`);
746
+ },
747
+ close() {
748
+ if (!closed) {
749
+ closed = true;
750
+ rl.close();
751
+ }
752
+ },
753
+ };
754
+ }
755
+ /** Render a closed set as a numbered menu; everything else as one line. */
756
+ function renderQuestion(question, options) {
757
+ if (!options.choices || options.choices.length === 0) {
758
+ return options.default ? `${question} [${options.default}]: ` : `${question}: `;
759
+ }
760
+ const lines = [`${question}:`];
761
+ options.choices.forEach((choice, index) => {
762
+ const marker = choice === options.default ? " (default)" : "";
763
+ lines.push(` ${index + 1}) ${choice}${marker}`);
764
+ });
765
+ const defaultIndex = options.default ? options.choices.indexOf(options.default) + 1 : 0;
766
+ lines.push(defaultIndex > 0 ? `Choice [${defaultIndex}]: ` : "Choice: ");
767
+ return lines.join("\n");
768
+ }
769
+ /** Accept either the ordinal or the literal value of a closed set. */
770
+ function resolveChoice(answer, options) {
771
+ const raw = answer.trim();
772
+ if (!options.choices || options.choices.length === 0) {
773
+ return raw === "" ? (options.default ?? "") : raw;
774
+ }
775
+ if (raw === "")
776
+ return options.default;
777
+ if (/^\d+$/u.test(raw)) {
778
+ const index = Number(raw) - 1;
779
+ return options.choices[index];
780
+ }
781
+ return options.choices.includes(raw) ? raw : undefined;
782
+ }
783
+ // ── init ───────────────────────────────────────────────────────────
784
+ async function runInit(options, home, env, dependencies, out, err) {
785
+ const paths = resolvePaths(home);
786
+ if (options.dryRun) {
787
+ out(options.json
788
+ ? `${JSON.stringify(renderDryRunReport(paths, options), null, 2)}\n`
789
+ : renderDryRunText(paths, home, options));
790
+ return;
791
+ }
792
+ const values = loadOrCreateBootstrapValues(paths, options);
793
+ writeSecureEnvFile(paths.serverEnv, values);
794
+ const commandExists = dependencies.commandExists ?? defaultCommandExists;
795
+ const runCommand = dependencies.runCommand ?? defaultRunCommand;
796
+ const configuredClients = [];
797
+ const skippedClients = [];
798
+ for (const client of options.clients) {
799
+ if (!AUTO_REGISTERED_CLIENTS.includes(client)) {
800
+ skippedClients.push(`${client} (no CLI to register with)`);
801
+ continue;
802
+ }
803
+ const registration = registerClient(client, options.force, {
804
+ commandExists,
805
+ runCommand,
806
+ env,
807
+ });
808
+ if (registration.ok)
809
+ configuredClients.push(client);
810
+ else
811
+ skippedClients.push(`${client} (${registration.reason})`);
812
+ }
813
+ const manualClients = options.clients.filter((client) => !configuredClients.includes(client));
814
+ const report = {
815
+ status: "configured",
816
+ files: { server_env: paths.serverEnv },
817
+ transport: "stdio",
818
+ server_command: SERVER_COMMAND,
819
+ clients: configuredClients,
820
+ skipped_clients: skippedClients,
821
+ profile_command: "servicenow-mcp-profile create --name dev --instance https://yourinstance.service-now.com --auth-type oauth --client-id <client-id> --source reference --provider env",
822
+ grant_command: "servicenow-mcp-setup grant --profile dev --read incident --write incident",
823
+ doctor_command: "servicenow-mcp-setup doctor --profile dev",
824
+ notes: [
825
+ "Each registered client spawns its own server over stdio. Nothing listens on a port, and there is no service to start or keep running.",
826
+ "Any registered client can read and write every table these profiles grant, as the configured ServiceNow account. The client list and the grants are the boundary.",
827
+ "Generated owner/client IDs are stored in an owner-only env file, not in client config. They label audit records; they are not credentials.",
828
+ "The spawned server reads that env file itself, so no secret is copied into a client configuration file.",
829
+ "A profile with no tableAccess rules denies every tool call; run the grant command before first use.",
830
+ "Create ServiceNow profiles with servicenow-mcp-profile; protected values are prompted or read from bounded stdin, never argv.",
831
+ ],
832
+ };
833
+ out(options.json
834
+ ? `${JSON.stringify(report, null, 2)}\n`
835
+ : renderInitText(paths, home, options, configuredClients, skippedClients, manualClients));
836
+ if (skippedClients.length > 0) {
837
+ err(`[servicenow-mcp] skipped client setup: ${skippedClients.join(", ")}\n`);
838
+ }
839
+ }
840
+ /**
841
+ * Resolve the command a client should spawn.
842
+ *
843
+ * `servicenow-mcp` on PATH is the normal case and the one worth registering:
844
+ * it survives a reinstall and reads the same in every client's config. When it
845
+ * does not resolve — a project-local install, or a global bin directory the
846
+ * client's own PATH will not have — registering it anyway would produce a
847
+ * client that fails to launch with nothing to point at. So fall back to this
848
+ * CLI's own sibling entrypoint, which is unambiguous and always correct.
849
+ */
850
+ function resolveServerLaunch(commandExists) {
851
+ if (commandExists(SERVER_COMMAND)) {
852
+ return Object.freeze({ command: SERVER_COMMAND, args: Object.freeze([]) });
853
+ }
854
+ return Object.freeze({
855
+ command: process.execPath,
856
+ args: Object.freeze([(0, node_path_1.join)(__dirname, "index.js")]),
857
+ });
858
+ }
859
+ function registerClient(client, force, context) {
860
+ const binary = client === "codex" ? "codex" : "claude";
861
+ if (!context.commandExists(binary)) {
862
+ return { ok: false, reason: `${binary} CLI not found` };
863
+ }
864
+ const launch = resolveServerLaunch(context.commandExists);
865
+ const result = client === "codex"
866
+ ? configureCodex(launch, force, context)
867
+ : configureClaudeCode(launch, force, context);
868
+ if (result.status === 0)
869
+ return { ok: true };
870
+ return {
871
+ ok: false,
872
+ reason: result.error?.message ?? result.stderr ?? "configuration command failed",
873
+ };
874
+ }
875
+ /** `codex mcp add <name> -- <command> [args...]` registers a stdio server. */
876
+ function configureCodex(launch, force, context) {
877
+ const existing = context.runCommand("codex", ["mcp", "get", MCP_SERVER_NAME], context.env);
878
+ if (existing.status === 0) {
879
+ if (!force)
880
+ return Object.freeze({ status: 0 });
881
+ const removed = context.runCommand("codex", ["mcp", "remove", MCP_SERVER_NAME], context.env);
882
+ if (removed.status !== 0)
883
+ return removed;
884
+ }
885
+ return context.runCommand("codex", ["mcp", "add", MCP_SERVER_NAME, "--", launch.command, ...launch.args], context.env);
886
+ }
887
+ /**
888
+ * `claude mcp add <name> -- <command> [args...]` registers a stdio server;
889
+ * stdio is the default transport, so `--transport` is deliberately omitted.
890
+ */
891
+ function configureClaudeCode(launch, force, context) {
892
+ const existing = context.runCommand("claude", ["mcp", "get", MCP_SERVER_NAME], context.env);
893
+ if (existing.status === 0) {
894
+ if (!force)
895
+ return Object.freeze({ status: 0 });
896
+ const removed = context.runCommand("claude", ["mcp", "remove", MCP_SERVER_NAME, "--scope", "user"], context.env);
897
+ if (removed.status !== 0)
898
+ return removed;
899
+ }
900
+ return context.runCommand("claude", ["mcp", "add", "--scope", "user", MCP_SERVER_NAME, "--", launch.command, ...launch.args], context.env);
901
+ }
902
+ // ── client ─────────────────────────────────────────────────────────
903
+ function runClient(options, out) {
904
+ const sections = options.clients.map((client) => renderClientConfiguration(client));
905
+ out(`${sections.join("\n")}\n`);
906
+ }
907
+ /**
908
+ * Every client here speaks stdio natively, so each recipe is the same shape:
909
+ * a command to spawn. The mcp-remote bridge that HTTP required is gone, and
910
+ * with it the only reason a client config ever had to hold a bearer token.
911
+ */
912
+ function renderClientConfiguration(client) {
913
+ const heading = `## ${client}\n`;
914
+ const jsonEntry = (key) => indent(JSON.stringify({ [key]: { [MCP_SERVER_NAME]: { command: SERVER_COMMAND, args: [] } } }, null, 2));
915
+ switch (client) {
916
+ case "codex":
917
+ return (`${heading}\n` +
918
+ ` codex mcp add ${MCP_SERVER_NAME} -- ${SERVER_COMMAND}\n\n` +
919
+ `Equivalent ~/.codex/config.toml entry:\n\n` +
920
+ `${indent(`[mcp_servers.${MCP_SERVER_NAME}]\ncommand = "${SERVER_COMMAND}"\nargs = []`)}\n\n` +
921
+ `${CREDENTIAL_FOOTNOTE}`);
922
+ case "claude-code":
923
+ return (`${heading}\n` +
924
+ ` claude mcp add --scope user ${MCP_SERVER_NAME} -- ${SERVER_COMMAND}\n\n` +
925
+ `stdio is the default, so there is no transport flag to pass.\n\n` +
926
+ `Equivalent .mcp.json entry:\n\n` +
927
+ `${jsonEntry("mcpServers")}\n\n` +
928
+ `${CREDENTIAL_FOOTNOTE}`);
929
+ case "claude-desktop":
930
+ case "cursor":
931
+ case "windsurf": {
932
+ const location = client === "claude-desktop"
933
+ ? "~/Library/Application Support/Claude/claude_desktop_config.json (macOS)\n" +
934
+ " %APPDATA%\\Claude\\claude_desktop_config.json (Windows)"
935
+ : client === "cursor"
936
+ ? "~/.cursor/mcp.json (global) or .cursor/mcp.json (per project)"
937
+ : "~/.codeium/windsurf/mcp_config.json";
938
+ return (`${heading}\n` +
939
+ `Config file:\n ${location}\n\n` +
940
+ `${jsonEntry("mcpServers")}\n\n` +
941
+ `${CREDENTIAL_FOOTNOTE}`);
942
+ }
943
+ case "vscode":
944
+ return (`${heading}\n` +
945
+ `Config file:\n .vscode/mcp.json (workspace) or the user-level mcp.json\n\n` +
946
+ `${indent(JSON.stringify({
947
+ servers: {
948
+ [MCP_SERVER_NAME]: {
949
+ type: "stdio",
950
+ command: SERVER_COMMAND,
951
+ args: [],
952
+ },
953
+ },
954
+ }, null, 2))}\n\n` +
955
+ `${CREDENTIAL_FOOTNOTE}`);
956
+ }
957
+ }
958
+ // ── grant ──────────────────────────────────────────────────────────
959
+ function runGrant(options, home, dependencies, out) {
960
+ const manager = dependencies.profileManager ?? profileManagerFor(home);
961
+ const current = manager.getProfile(options.profile);
962
+ const existing = options.replace
963
+ ? Object.freeze({})
964
+ : (current.tableAccess ?? Object.freeze({}));
965
+ const tableAccess = buildTableAccess(existing, options);
966
+ if (options.dryRun) {
967
+ out(options.json
968
+ ? `${JSON.stringify({ status: "dry-run", profile: options.profile, tableAccess }, null, 2)}\n`
969
+ : `Would write to profile ${options.profile}:\n${indent(JSON.stringify(tableAccess, null, 2))}\n`);
970
+ return;
971
+ }
972
+ manager.addProfile(options.profile, { ...current, tableAccess });
973
+ if (options.json) {
974
+ out(`${JSON.stringify({ status: "granted", profile: options.profile, tableAccess }, null, 2)}\n`);
975
+ return;
976
+ }
977
+ out(`Granted table access on profile ${options.profile}.\n\n` +
978
+ `${indent(JSON.stringify(tableAccess, null, 2))}\n\n` +
979
+ `Each target asserts closureComplete: true, meaning relatedTables lists every\n` +
980
+ `backing, ancestor, and descendant table the operation can reach. Pass\n` +
981
+ `--related "<table>=<t1>,<t2>" when a table extends or views another one;\n` +
982
+ `related tables join the allowlist but get no target, so a caller cannot\n` +
983
+ `address them directly.\n` +
984
+ `Restart the MCP client for the change to take effect: it reads the\n` +
985
+ `profile when it launches the server.\n`);
986
+ }
987
+ /**
988
+ * Build and validate one `tableAccess` object. Shared by `grant` and the
989
+ * wizard so there is a single definition of what a grant means.
990
+ */
991
+ function buildTableAccess(existing, options) {
992
+ const readTables = new Set([...(existing.readTables ?? []), ...options.read]);
993
+ const writeTables = new Set([...(existing.writeTables ?? []), ...options.write]);
994
+ const targets = mergeTargets(existing.targets, options, readTables, writeTables);
995
+ // A target asserts that relatedTables is its complete reachable closure, and
996
+ // the policy loader requires every one of those tables to carry the same
997
+ // operation permission. They stay out of `targets`, so they are reachable
998
+ // through the target but never directly addressable by a caller.
999
+ for (const target of targets) {
1000
+ if (readTables.has(target.table)) {
1001
+ for (const related of target.relatedTables)
1002
+ readTables.add(related);
1003
+ }
1004
+ if (writeTables.has(target.table)) {
1005
+ for (const related of target.relatedTables)
1006
+ writeTables.add(related);
1007
+ }
1008
+ }
1009
+ const tableAccess = Object.freeze({
1010
+ readTables: sorted(readTables),
1011
+ writeTables: sorted(writeTables),
1012
+ targets,
1013
+ });
1014
+ // Validate against the real decision-time policy loader rather than a copy
1015
+ // of its rules, so a rejected grant fails here instead of at first tool call.
1016
+ (0, table_policy_js_1.createTableAccessPolicy)(tableAccess);
1017
+ return tableAccess;
1018
+ }
1019
+ function sorted(values) {
1020
+ return Object.freeze([...values].sort());
1021
+ }
1022
+ function mergeTargets(existing, options, readTables, writeTables) {
1023
+ const byTable = new Map();
1024
+ for (const target of existing ?? [])
1025
+ byTable.set(target.table, target);
1026
+ for (const table of new Set([...options.read, ...options.write])) {
1027
+ if (table === TABLE_ALLOWLIST_WILDCARD)
1028
+ continue;
1029
+ const tools = new Set(byTable.get(table)?.tools ?? []);
1030
+ if (options.tools) {
1031
+ for (const tool of options.tools)
1032
+ tools.add(tool);
1033
+ }
1034
+ else {
1035
+ if (readTables.has(table)) {
1036
+ for (const tool of DEFAULT_READ_TOOLS)
1037
+ tools.add(tool);
1038
+ }
1039
+ if (writeTables.has(table)) {
1040
+ for (const tool of DEFAULT_WRITE_TOOLS)
1041
+ tools.add(tool);
1042
+ }
1043
+ }
1044
+ const related = new Set([
1045
+ table,
1046
+ ...(byTable.get(table)?.relatedTables ?? []),
1047
+ ...(options.related.get(table) ?? []),
1048
+ ]);
1049
+ byTable.set(table, Object.freeze({
1050
+ table,
1051
+ kind: "canonical",
1052
+ tools: Object.freeze([...tools].sort()),
1053
+ closureComplete: true,
1054
+ relatedTables: Object.freeze([...related].sort()),
1055
+ }));
1056
+ }
1057
+ return Object.freeze([...byTable.values()]);
1058
+ }
1059
+ async function runDoctor(options, home, env, dependencies, out) {
1060
+ const paths = resolvePaths(home);
1061
+ const checks = runInstallChecks(paths, home, env, dependencies, options.profile);
1062
+ const failed = checks.filter((check) => !check.ok);
1063
+ if (options.json) {
1064
+ out(`${JSON.stringify({ status: failed.length === 0 ? "ok" : "problems", checks }, null, 2)}\n`);
1065
+ }
1066
+ else {
1067
+ out(renderDoctorText(checks));
1068
+ }
1069
+ if (failed.length > 0)
1070
+ process.exitCode = 1;
1071
+ }
1072
+ /**
1073
+ * Prove the command registered clients spawn can actually be found.
1074
+ *
1075
+ * This is the check a listening service did not need and a spawned one cannot
1076
+ * do without: a client that cannot resolve the command fails at launch with an
1077
+ * error that says nothing about why. It replaces the endpoint probe, and is
1078
+ * strictly more informative, because there is no running process whose absence
1079
+ * could be mistaken for a broken install.
1080
+ *
1081
+ * PATH here is this shell's, which is the best available proxy. A GUI client
1082
+ * launched from the desktop may hold a different one, so the remedy names the
1083
+ * absolute-path registration that removes the question entirely.
1084
+ */
1085
+ function checkServerCommand(dependencies) {
1086
+ const name = "server command";
1087
+ const commandExists = dependencies.commandExists ?? defaultCommandExists;
1088
+ if (commandExists(SERVER_COMMAND)) {
1089
+ return {
1090
+ name,
1091
+ ok: true,
1092
+ detail: `${SERVER_COMMAND} resolves on PATH; clients spawn it over stdio`,
1093
+ };
1094
+ }
1095
+ const fallback = (0, node_path_1.join)(__dirname, "index.js");
1096
+ return {
1097
+ name,
1098
+ ok: false,
1099
+ detail: `${SERVER_COMMAND} is not on this PATH`,
1100
+ remedy: `Install the package globally (npm i -g @onlyflows/servicenow-mcp), or register ` +
1101
+ `the entrypoint by absolute path instead: claude mcp add --scope user ` +
1102
+ `${MCP_SERVER_NAME} -- ${process.execPath} ${fallback}`,
1103
+ };
1104
+ }
1105
+ function checkNodeVersion() {
1106
+ const major = Number.parseInt(process.versions.node.split(".")[0] ?? "0", 10);
1107
+ return major >= MINIMUM_NODE_MAJOR
1108
+ ? { name: "node", ok: true, detail: `v${process.versions.node}` }
1109
+ : {
1110
+ name: "node",
1111
+ ok: false,
1112
+ detail: `v${process.versions.node}`,
1113
+ remedy: `This package requires Node.js ${MINIMUM_NODE_MAJOR} or newer.`,
1114
+ };
1115
+ }
1116
+ function checkDirectoryMode(path) {
1117
+ if (!(0, node_fs_1.existsSync)(path)) {
1118
+ return {
1119
+ name: "config directory",
1120
+ ok: false,
1121
+ detail: `${path} is missing`,
1122
+ remedy: "Run: servicenow-mcp-setup",
1123
+ };
1124
+ }
1125
+ const mode = (0, node_fs_1.statSync)(path).mode & 0o777;
1126
+ if (process.platform === "win32" || mode === 0o700) {
1127
+ return { name: "config directory", ok: true, detail: `${path} (${formatMode(mode)})` };
1128
+ }
1129
+ return {
1130
+ name: "config directory",
1131
+ ok: false,
1132
+ detail: `${path} is ${formatMode(mode)}, expected 0700`,
1133
+ remedy: `Run: chmod 700 ${path}`,
1134
+ };
1135
+ }
1136
+ function checkEnvFile(path, required) {
1137
+ if (!(0, node_fs_1.existsSync)(path)) {
1138
+ return [
1139
+ {
1140
+ name: "server env",
1141
+ ok: false,
1142
+ detail: `${path} is missing`,
1143
+ remedy: "Run: servicenow-mcp-setup",
1144
+ },
1145
+ ];
1146
+ }
1147
+ const checks = [];
1148
+ const mode = (0, node_fs_1.statSync)(path).mode & 0o777;
1149
+ if (process.platform === "win32" || mode === 0o600) {
1150
+ checks.push({ name: "server env", ok: true, detail: `${path} (${formatMode(mode)})` });
1151
+ }
1152
+ else {
1153
+ checks.push({
1154
+ name: "server env",
1155
+ ok: false,
1156
+ detail: `${path} is ${formatMode(mode)}, expected 0600`,
1157
+ remedy: `Run: chmod 600 ${path}`,
1158
+ });
1159
+ }
1160
+ const values = parseEnvFile((0, node_fs_1.readFileSync)(path, "utf8"));
1161
+ const missing = required.filter((key) => !values[key]);
1162
+ checks.push(missing.length === 0
1163
+ ? { name: "server env values", ok: true, detail: `${required.length} required values present` }
1164
+ : {
1165
+ name: "server env values",
1166
+ ok: false,
1167
+ detail: `missing ${missing.join(", ")}`,
1168
+ remedy: `Run: servicenow-mcp-setup --force (this preserves ${ENCRYPTION_KEY_ENV})`,
1169
+ });
1170
+ return checks;
1171
+ }
1172
+ function checkProfiles(paths, home, env, dependencies, only) {
1173
+ const checks = [];
1174
+ if (!(0, node_fs_1.existsSync)(paths.profileConfig) && dependencies.profileManager === undefined) {
1175
+ return [
1176
+ {
1177
+ name: "profiles",
1178
+ ok: false,
1179
+ detail: `${paths.profileConfig} does not exist`,
1180
+ remedy: "Create one: servicenow-mcp-profile create --name dev --instance https://yourinstance.service-now.com --auth-type oauth --client-id <id> --source reference --provider env",
1181
+ },
1182
+ ];
1183
+ }
1184
+ let manager;
1185
+ try {
1186
+ manager = dependencies.profileManager ?? profileManagerFor(home);
1187
+ }
1188
+ catch (error) {
1189
+ return [
1190
+ {
1191
+ name: "profiles",
1192
+ ok: false,
1193
+ detail: describeError(error),
1194
+ remedy: `Inspect ${paths.profileConfig}; it must be owner-only JSON with mode 0600.`,
1195
+ },
1196
+ ];
1197
+ }
1198
+ const names = manager
1199
+ .listProfiles()
1200
+ .map((entry) => entry.name)
1201
+ .filter((name) => only === undefined || name === only);
1202
+ if (names.length === 0) {
1203
+ return [
1204
+ {
1205
+ name: "profiles",
1206
+ ok: false,
1207
+ detail: only ? `profile "${only}" is not configured` : "no profiles configured",
1208
+ remedy: "Create one with servicenow-mcp-profile create.",
1209
+ },
1210
+ ];
1211
+ }
1212
+ for (const name of names) {
1213
+ const profile = manager.getProfile(name);
1214
+ checks.push(checkInstanceUrl(name, profile.instance));
1215
+ checks.push(checkCredential(manager, name));
1216
+ checks.push(checkTableAccess(name, profile.tableAccess));
1217
+ }
1218
+ const envAllowlist = env.SN_ALLOWED_READ_TABLES ?? env.SN_ALLOWED_WRITE_TABLES ?? env.SN_TABLE_ACCESS_TARGETS;
1219
+ if (envAllowlist !== undefined) {
1220
+ checks.push({
1221
+ name: "env table allowlist",
1222
+ ok: false,
1223
+ detail: "SN_ALLOWED_READ_TABLES / SN_ALLOWED_WRITE_TABLES / SN_TABLE_ACCESS_TARGETS are set, but a profile file exists",
1224
+ remedy: "Those variables apply only when no profile file exists. Move the rules onto the profile: servicenow-mcp-setup grant --profile <name> --read <tables>",
1225
+ });
1226
+ }
1227
+ return checks;
1228
+ }
1229
+ function checkInstanceUrl(name, instance) {
1230
+ let url;
1231
+ try {
1232
+ url = new URL(instance);
1233
+ }
1234
+ catch {
1235
+ return {
1236
+ name: `profile ${name}: instance`,
1237
+ ok: false,
1238
+ detail: `"${instance}" is not an absolute URL`,
1239
+ remedy: "Use the full origin, for example https://yourinstance.service-now.com",
1240
+ };
1241
+ }
1242
+ if (url.protocol !== "https:") {
1243
+ return {
1244
+ name: `profile ${name}: instance`,
1245
+ ok: false,
1246
+ detail: `"${instance}" is not https`,
1247
+ remedy: "ServiceNow instances are HTTPS; credentials must never travel in cleartext.",
1248
+ };
1249
+ }
1250
+ if (url.pathname !== "/" || url.search || url.hash) {
1251
+ return {
1252
+ name: `profile ${name}: instance`,
1253
+ ok: false,
1254
+ detail: `"${instance}" carries a path, query, or fragment`,
1255
+ remedy: `Use the bare origin: ${url.origin}`,
1256
+ };
1257
+ }
1258
+ return { name: `profile ${name}: instance`, ok: true, detail: url.origin };
1259
+ }
1260
+ function checkCredential(manager, name) {
1261
+ const profile = manager.getProfile(name);
1262
+ const authType = profile.authType ?? "basic";
1263
+ const field = authType === "oauth" ? "clientSecret" : authType === "apikey" ? "apiKey" : "credential";
1264
+ const kind = (0, profile_credentials_js_1.credentialSourceKind)(profile[field]);
1265
+ try {
1266
+ if (authType === "basic" || profile.grantType === "password") {
1267
+ manager.resolveCredential(profile);
1268
+ }
1269
+ else {
1270
+ manager.getConfig(name);
1271
+ }
1272
+ return {
1273
+ name: `profile ${name}: credential`,
1274
+ ok: true,
1275
+ detail: `${authType} ${field} resolves from its ${kind} source`,
1276
+ };
1277
+ }
1278
+ catch (error) {
1279
+ return {
1280
+ name: `profile ${name}: credential`,
1281
+ ok: false,
1282
+ detail: `${authType} ${field} (${kind} source): ${describeError(error)}`,
1283
+ remedy: credentialRemedy(kind, name, field, describeError(error)),
1284
+ };
1285
+ }
1286
+ }
1287
+ /**
1288
+ * The reference *name* is deliberately not printed: `servicenow-mcp-profile
1289
+ * inspect` reports source kinds only, and doctor keeps that boundary.
1290
+ */
1291
+ function credentialRemedy(kind, profile, field, message) {
1292
+ if (kind === "missing") {
1293
+ return `This profile has no ${field}. Add it: servicenow-mcp-profile rotate --name ${profile} --field ${field}`;
1294
+ }
1295
+ if (kind === "encrypted" || message.toLowerCase().includes("encryption key")) {
1296
+ return (`The value is an encrypted envelope. Inject the matching ${ENCRYPTION_KEY_ENV} ` +
1297
+ `(32 random bytes, base64 or base64url) into this process — it is in the server ` +
1298
+ `env file that setup wrote. A wrong key cannot be distinguished from a corrupt ` +
1299
+ `envelope, so re-enter the value with servicenow-mcp-profile rotate if the key is right.`);
1300
+ }
1301
+ return (`The value is a secret_ref, so the referenced environment variable must be set in ` +
1302
+ `this process and in the process the client spawns. Run "servicenow-mcp-profile inspect --name ` +
1303
+ `${profile}" to confirm the source, then export the variable your operator injects.`);
1304
+ }
1305
+ function checkTableAccess(name, tableAccess) {
1306
+ const readCount = tableAccess?.readTables?.length ?? 0;
1307
+ const writeCount = tableAccess?.writeTables?.length ?? 0;
1308
+ if (readCount === 0 && writeCount === 0) {
1309
+ return {
1310
+ name: `profile ${name}: table access`,
1311
+ ok: false,
1312
+ detail: "no tableAccess rules; every tool call is denied",
1313
+ remedy: `Run: servicenow-mcp-setup grant --profile ${name} --read incident`,
1314
+ };
1315
+ }
1316
+ const targets = tableAccess?.targets ?? [];
1317
+ // A table is accounted for if it has its own target (caller-addressable) or
1318
+ // appears in some target's closure (reachable, deliberately not addressable).
1319
+ const accounted = new Set();
1320
+ for (const target of targets) {
1321
+ accounted.add(target.table);
1322
+ for (const related of target.relatedTables)
1323
+ accounted.add(related);
1324
+ }
1325
+ const wildcard = tableAccess?.readTables?.includes("*") === true ||
1326
+ tableAccess?.writeTables?.includes("*") === true;
1327
+ const unaddressable = [
1328
+ ...(tableAccess?.readTables ?? []),
1329
+ ...(tableAccess?.writeTables ?? []),
1330
+ ].filter((table) => table !== "*" && !accounted.has(table));
1331
+ if (!wildcard && unaddressable.length > 0) {
1332
+ return {
1333
+ name: `profile ${name}: table access`,
1334
+ ok: false,
1335
+ detail: `allowlisted but unreachable — no target entry and in no target's closure: ${[...new Set(unaddressable)].join(", ")}`,
1336
+ remedy: `Run: servicenow-mcp-setup grant --profile ${name} --read ${[...new Set(unaddressable)].join(",")}`,
1337
+ };
1338
+ }
1339
+ return {
1340
+ name: `profile ${name}: table access`,
1341
+ ok: true,
1342
+ detail: `${readCount} read, ${writeCount} write, ${targets.length} target(s)`,
1343
+ };
1344
+ }
1345
+ // ── argument parsing ───────────────────────────────────────────────
1346
+ function normalizeArgv(argv) {
1347
+ const args = [...argv];
1348
+ if (args[0] === "setup")
1349
+ args.shift();
1350
+ return Object.freeze(args);
1351
+ }
1352
+ function splitSubcommand(argv) {
1353
+ const first = argv[0];
1354
+ if (first === "client" || first === "grant" || first === "doctor") {
1355
+ return { subcommand: first, args: Object.freeze(argv.slice(1)) };
1356
+ }
1357
+ if (first === "init")
1358
+ return { subcommand: "init", args: Object.freeze(argv.slice(1)) };
1359
+ return { subcommand: "init", args: argv };
1360
+ }
1361
+ function parseFlags(args, spec, usage) {
1362
+ const flags = new Set();
1363
+ const values = new Map();
1364
+ const repeated = new Map();
1365
+ for (let index = 0; index < args.length; index += 1) {
1366
+ const arg = args[index];
1367
+ if (arg === "--help" || arg === "-h")
1368
+ throw new SetupHelp(usage);
1369
+ if (spec.boolean.has(arg)) {
1370
+ flags.add(arg);
1371
+ continue;
1372
+ }
1373
+ if (spec.value.has(arg)) {
1374
+ const value = args[index + 1];
1375
+ if (value === undefined || value.startsWith("--")) {
1376
+ throw new Error(`${arg} requires a value.\n\n${usage}`);
1377
+ }
1378
+ if (spec.repeatable?.has(arg)) {
1379
+ const list = repeated.get(arg) ?? [];
1380
+ list.push(value);
1381
+ repeated.set(arg, list);
1382
+ }
1383
+ else {
1384
+ values.set(arg, value);
1385
+ }
1386
+ index += 1;
1387
+ continue;
1388
+ }
1389
+ throw new Error(`Unknown option ${arg}.\n\n${usage}`);
1390
+ }
1391
+ return Object.freeze({ flags, values, repeated });
1392
+ }
1393
+ /**
1394
+ * The wizard is what a bare, interactive invocation does. Any flag keeps the
1395
+ * established non-interactive behavior byte for byte, so every documented
1396
+ * command and every CI caller is unaffected.
1397
+ */
1398
+ function shouldRunWizard(options, args, dependencies) {
1399
+ if (options.nonInteractive)
1400
+ return false;
1401
+ if (dependencies.prompter !== undefined)
1402
+ return dependencies.interactive !== false;
1403
+ if (dependencies.interactive === false)
1404
+ return false;
1405
+ if (args.length > 0)
1406
+ return false;
1407
+ return dependencies.interactive ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY));
1408
+ }
1409
+ function parseInitArguments(args) {
1410
+ const usage = renderInitHelp();
1411
+ const parsed = parseFlags(args, {
1412
+ boolean: new Set([
1413
+ "--dry-run",
1414
+ "--force",
1415
+ "--json",
1416
+ "--rotate-encryption-key",
1417
+ "--non-interactive",
1418
+ ]),
1419
+ value: new Set(["--clients"]),
1420
+ }, usage);
1421
+ return Object.freeze({
1422
+ dryRun: parsed.flags.has("--dry-run"),
1423
+ force: parsed.flags.has("--force"),
1424
+ rotateEncryptionKey: parsed.flags.has("--rotate-encryption-key"),
1425
+ json: parsed.flags.has("--json"),
1426
+ nonInteractive: parsed.flags.has("--non-interactive"),
1427
+ clients: parseClients(parsed.values.get("--clients") ?? "auto"),
1428
+ });
1429
+ }
1430
+ function parseClientArguments(args) {
1431
+ const usage = renderClientHelp();
1432
+ const parsed = parseFlags(args, { boolean: new Set([]), value: new Set(["--client"]) }, usage);
1433
+ return Object.freeze({
1434
+ clients: parseClients(parsed.values.get("--client") ?? "all"),
1435
+ });
1436
+ }
1437
+ function parseGrantArguments(args) {
1438
+ const usage = renderGrantHelp();
1439
+ const parsed = parseFlags(args, {
1440
+ boolean: new Set(["--replace", "--dry-run", "--json"]),
1441
+ value: new Set(["--profile", "--read", "--write", "--tools", "--related"]),
1442
+ repeatable: new Set(["--related"]),
1443
+ }, usage);
1444
+ const profile = parsed.values.get("--profile");
1445
+ if (!profile)
1446
+ throw new Error(`--profile is required.\n\n${usage}`);
1447
+ const read = parseTableList(parsed.values.get("--read"), "--read");
1448
+ const write = parseTableList(parsed.values.get("--write"), "--write");
1449
+ if (read.length === 0 && write.length === 0) {
1450
+ throw new Error(`Give at least one of --read or --write.\n\n${usage}`);
1451
+ }
1452
+ return Object.freeze({
1453
+ profile,
1454
+ read,
1455
+ write,
1456
+ ...(parsed.values.has("--tools")
1457
+ ? { tools: parseToolList(parsed.values.get("--tools")) }
1458
+ : {}),
1459
+ related: parseRelated(parsed.repeated.get("--related") ?? []),
1460
+ replace: parsed.flags.has("--replace"),
1461
+ dryRun: parsed.flags.has("--dry-run"),
1462
+ json: parsed.flags.has("--json"),
1463
+ });
1464
+ }
1465
+ function parseDoctorArguments(args) {
1466
+ const usage = renderDoctorHelp();
1467
+ const parsed = parseFlags(args, {
1468
+ boolean: new Set(["--json"]),
1469
+ value: new Set(["--profile"]),
1470
+ }, usage);
1471
+ return Object.freeze({
1472
+ ...(parsed.values.has("--profile") ? { profile: parsed.values.get("--profile") } : {}),
1473
+ json: parsed.flags.has("--json"),
1474
+ });
1475
+ }
1476
+ function parseClients(value) {
1477
+ if (value === "none")
1478
+ return Object.freeze([]);
1479
+ if (value === "auto")
1480
+ return AUTO_REGISTERED_CLIENTS;
1481
+ if (value === "all")
1482
+ return ALL_CLIENTS;
1483
+ const clients = [];
1484
+ for (const raw of value.split(",")) {
1485
+ const client = raw.trim();
1486
+ if (client.length === 0)
1487
+ continue;
1488
+ if (!ALL_CLIENTS.includes(client)) {
1489
+ throw new Error(`Unsupported client "${client}". Supported: ${ALL_CLIENTS.join(", ")}, all, auto, none.`);
1490
+ }
1491
+ if (!clients.includes(client))
1492
+ clients.push(client);
1493
+ }
1494
+ return Object.freeze(clients);
1495
+ }
1496
+ function parseTableList(value, option) {
1497
+ if (value === undefined)
1498
+ return Object.freeze([]);
1499
+ const tables = [];
1500
+ for (const raw of value.split(",")) {
1501
+ const table = raw.trim().toLowerCase();
1502
+ if (table.length === 0)
1503
+ continue;
1504
+ if (table === "*") {
1505
+ throw new Error(`${option} does not accept "*". A wildcard grant skips the per-tool binding and the ` +
1506
+ "related-table closure check; configure it deliberately in the profile file and read " +
1507
+ "docs/PRODUCTION-SECURITY.md first.");
1508
+ }
1509
+ // Check the shape here so a typo is rejected at the prompt that produced
1510
+ // it, rather than by the policy loader after every question is answered.
1511
+ if (!TABLE_NAME.test(table)) {
1512
+ throw new Error(`"${table}" is not a ServiceNow table name. Names are lowercase, start with a ` +
1513
+ "letter, and contain only letters, digits, and underscores.");
1514
+ }
1515
+ if (!tables.includes(table))
1516
+ tables.push(table);
1517
+ }
1518
+ return Object.freeze(tables);
1519
+ }
1520
+ function parseToolList(value) {
1521
+ const tools = [];
1522
+ for (const raw of value.split(",")) {
1523
+ const tool = raw.trim();
1524
+ if (tool.length === 0)
1525
+ continue;
1526
+ if (!tool.startsWith("sn_")) {
1527
+ throw new Error(`"${tool}" is not a tool name; tool names start with sn_.`);
1528
+ }
1529
+ if (!tools.includes(tool))
1530
+ tools.push(tool);
1531
+ }
1532
+ if (tools.length === 0)
1533
+ throw new Error("--tools requires at least one sn_* tool name.");
1534
+ return Object.freeze(tools);
1535
+ }
1536
+ function parseRelated(entries) {
1537
+ const related = new Map();
1538
+ for (const entry of entries) {
1539
+ const separator = entry.indexOf("=");
1540
+ if (separator < 1) {
1541
+ throw new Error(`--related expects <table>=<related,tables>, received "${entry}".`);
1542
+ }
1543
+ const table = entry.slice(0, separator).trim().toLowerCase();
1544
+ const tables = parseTableList(entry.slice(separator + 1), "--related");
1545
+ related.set(table, Object.freeze([...(related.get(table) ?? []), ...tables]));
1546
+ }
1547
+ return related;
1548
+ }
1549
+ // ── file handling ──────────────────────────────────────────────────
1550
+ function resolvePaths(home) {
1551
+ return Object.freeze({
1552
+ configDir: (0, node_path_1.join)(home, CONFIG_RELATIVE_DIR),
1553
+ serverEnv: (0, node_path_1.join)(home, SERVER_ENV_RELATIVE_PATH),
1554
+ profileConfig: (0, node_path_1.join)(home, PROFILE_CONFIG_RELATIVE_PATH),
1555
+ });
1556
+ }
1557
+ /**
1558
+ * Build a manager for an install this process did not create.
1559
+ *
1560
+ * `doctor` and `grant` inspect an existing install, so the encryption key is
1561
+ * normally only on disk in `server.env` — the same reason `doctor` reads that
1562
+ * file for its handshake probe. Falling back to it means a successful setup is
1563
+ * not immediately followed by `doctor` reporting the key as unavailable. When
1564
+ * neither source has a key the env-based provider still raises the original
1565
+ * error, so a genuinely missing key keeps its remedy.
1566
+ */
1567
+ function profileManagerFor(home) {
1568
+ const configFilePath = (0, node_path_1.join)(home, PROFILE_CONFIG_RELATIVE_PATH);
1569
+ if (process.env[ENCRYPTION_KEY_ENV]) {
1570
+ return new profile_manager_js_1.ProfileManager({ configFilePath });
1571
+ }
1572
+ const serverEnv = (0, node_path_1.join)(home, SERVER_ENV_RELATIVE_PATH);
1573
+ if ((0, node_fs_1.existsSync)(serverEnv)) {
1574
+ const stored = parseEnvFile((0, node_fs_1.readFileSync)(serverEnv, "utf8"))[ENCRYPTION_KEY_ENV];
1575
+ if (stored) {
1576
+ try {
1577
+ return new profile_manager_js_1.ProfileManager({
1578
+ configFilePath,
1579
+ encryptionKeyProvider: (0, profile_credentials_js_1.encryptionKeyProviderFromValue)(stored),
1580
+ });
1581
+ }
1582
+ catch {
1583
+ // A corrupt stored key falls through to the environment provider so the
1584
+ // operator gets the existing remedy rather than a parse failure here.
1585
+ }
1586
+ }
1587
+ }
1588
+ return new profile_manager_js_1.ProfileManager({ configFilePath });
1589
+ }
1590
+ /**
1591
+ * Preserve `SN_PROFILE_ENCRYPTION_KEY` across every regeneration. Losing it
1592
+ * makes every AES-256-GCM envelope in the profile file permanently
1593
+ * undecryptable, so rotation is opt-in and refused while a profile file exists.
1594
+ */
1595
+ function loadOrCreateBootstrapValues(paths, options) {
1596
+ const generated = generateBootstrapValues();
1597
+ const existing = (0, node_fs_1.existsSync)(paths.serverEnv)
1598
+ ? parseEnvFile((0, node_fs_1.readFileSync)(paths.serverEnv, "utf8"))
1599
+ : Object.freeze({});
1600
+ const hasProfiles = (0, node_fs_1.existsSync)(paths.profileConfig);
1601
+ if (options.rotateEncryptionKey) {
1602
+ if (hasProfiles) {
1603
+ throw new Error(`Refusing to rotate ${ENCRYPTION_KEY_ENV} while ${paths.profileConfig} exists: every ` +
1604
+ "encrypted credential in it would become permanently unreadable. Re-enter each " +
1605
+ "credential with servicenow-mcp-profile rotate under the new key instead.");
1606
+ }
1607
+ return Object.freeze({ ...existing, ...generated });
1608
+ }
1609
+ if ((0, node_fs_1.existsSync)(paths.serverEnv) && !existing[ENCRYPTION_KEY_ENV] && hasProfiles) {
1610
+ throw new Error(`${paths.serverEnv} exists but has no readable ${ENCRYPTION_KEY_ENV}, and ` +
1611
+ `${paths.profileConfig} may hold credentials encrypted under it. Restore the key line ` +
1612
+ "before rerunning setup; writing a fresh key would make those credentials unreadable.");
1613
+ }
1614
+ // --force regenerates the owner/client identifiers but never the encryption key.
1615
+ if (options.force) {
1616
+ return Object.freeze({
1617
+ ...generated,
1618
+ ...(existing[ENCRYPTION_KEY_ENV]
1619
+ ? { [ENCRYPTION_KEY_ENV]: existing[ENCRYPTION_KEY_ENV] }
1620
+ : {}),
1621
+ });
1622
+ }
1623
+ return Object.freeze({ ...generated, ...existing });
1624
+ }
1625
+ /**
1626
+ * The owner/client identifiers are not secrets. They label every audit record,
1627
+ * so they are generated per install to keep records from two installs
1628
+ * distinguishable.
1629
+ *
1630
+ * No listen address: nothing listens. A client spawns the server on demand and
1631
+ * the pipe between them is the whole transport.
1632
+ */
1633
+ function generateBootstrapValues() {
1634
+ return Object.freeze({
1635
+ MCP_OWNER_ID: `owner-${randomToken(12)}`,
1636
+ MCP_CLIENT_ID: `client-${randomToken(12)}`,
1637
+ [ENCRYPTION_KEY_ENV]: (0, node_crypto_1.randomBytes)(32).toString("base64url"),
1638
+ });
1639
+ }
1640
+ function writeSecureEnvFile(path, values) {
1641
+ const content = `${Object.entries(values)
1642
+ .map(([key, value]) => `${key}=${shellQuote(value)}`)
1643
+ .join("\n")}\n`;
1644
+ writeSecureFile(path, content);
1645
+ }
1646
+ /**
1647
+ * `mode` on writeFileSync applies only when the file is created, so an existing
1648
+ * world-readable file would keep its mode and then receive a fresh key.
1649
+ * chmod unconditionally after the write.
1650
+ */
1651
+ function writeSecureFile(path, content) {
1652
+ (0, node_fs_1.mkdirSync)((0, node_path_1.dirname)(path), { recursive: true, mode: 0o700 });
1653
+ if (process.platform !== "win32")
1654
+ (0, node_fs_1.chmodSync)((0, node_path_1.dirname)(path), 0o700);
1655
+ (0, node_fs_1.writeFileSync)(path, content, { mode: 0o600 });
1656
+ if (process.platform !== "win32")
1657
+ (0, node_fs_1.chmodSync)(path, 0o600);
1658
+ }
1659
+ function parseEnvFile(content) {
1660
+ const values = Object.create(null);
1661
+ for (const line of content.split(/\r?\n/u)) {
1662
+ const trimmed = line.trim();
1663
+ if (!trimmed || trimmed.startsWith("#"))
1664
+ continue;
1665
+ const separator = trimmed.indexOf("=");
1666
+ if (separator < 1)
1667
+ continue;
1668
+ const key = trimmed.slice(0, separator);
1669
+ const raw = trimmed.slice(separator + 1);
1670
+ values[key] = unquoteShellValue(raw);
1671
+ }
1672
+ return Object.freeze(values);
1673
+ }
1674
+ function unquoteShellValue(raw) {
1675
+ if (raw.startsWith("'") && raw.endsWith("'")) {
1676
+ return raw.slice(1, -1).replace(/'\\''/gu, "'");
1677
+ }
1678
+ return raw;
1679
+ }
1680
+ function defaultCommandExists(command) {
1681
+ const result = (0, node_child_process_1.spawnSync)("/bin/sh", ["-lc", `command -v ${shellQuote(command)}`], {
1682
+ encoding: "utf8",
1683
+ stdio: ["ignore", "pipe", "pipe"],
1684
+ });
1685
+ return result.status === 0;
1686
+ }
1687
+ function defaultRunCommand(command, args, env) {
1688
+ const result = (0, node_child_process_1.spawnSync)(command, [...args], {
1689
+ encoding: "utf8",
1690
+ env,
1691
+ stdio: ["ignore", "pipe", "pipe"],
1692
+ });
1693
+ return Object.freeze({
1694
+ status: result.status,
1695
+ stdout: result.stdout,
1696
+ stderr: result.stderr,
1697
+ error: result.error,
1698
+ });
1699
+ }
1700
+ function randomToken(bytes = 32) {
1701
+ return (0, node_crypto_1.randomBytes)(bytes).toString("base64url");
1702
+ }
1703
+ function shellQuote(value) {
1704
+ return `'${value.replace(/'/gu, `'\\''`)}'`;
1705
+ }
1706
+ function indent(value, prefix = " ") {
1707
+ return value
1708
+ .split("\n")
1709
+ .map((line) => (line.length > 0 ? `${prefix}${line}` : line))
1710
+ .join("\n");
1711
+ }
1712
+ /** Render a path under `home` as ~/… so long temp/home prefixes stay readable. */
1713
+ function displayPath(path, home) {
1714
+ return home.length > 0 && path.startsWith(`${home}/`)
1715
+ ? `~/${path.slice(home.length + 1)}`
1716
+ : path;
1717
+ }
1718
+ function formatMode(mode) {
1719
+ return `0${mode.toString(8).padStart(3, "0")}`;
1720
+ }
1721
+ function describeError(error) {
1722
+ return error instanceof Error ? error.message : String(error);
1723
+ }
1724
+ // ── rendering ──────────────────────────────────────────────────────
1725
+ function renderDryRunReport(paths, options) {
1726
+ return {
1727
+ status: "dry-run",
1728
+ would_write: [paths.serverEnv],
1729
+ transport: "stdio",
1730
+ server_command: SERVER_COMMAND,
1731
+ clients: options.clients,
1732
+ };
1733
+ }
1734
+ function renderDryRunText(paths, home, options) {
1735
+ const short = (path) => displayPath(path, home);
1736
+ return (`Dry run: nothing was written.\n\n` +
1737
+ `Would write\n` +
1738
+ ` ${short(paths.serverEnv)}\n\n` +
1739
+ `Transport stdio (each client spawns its own ${SERVER_COMMAND})\n` +
1740
+ `Clients ${options.clients.length > 0 ? options.clients.join(", ") : "(none)"}\n`);
1741
+ }
1742
+ function renderInitText(paths, home, options, configured, skipped, manual) {
1743
+ const short = (path) => displayPath(path, home);
1744
+ const lines = [
1745
+ "ServiceNow MCP setup",
1746
+ "",
1747
+ "Wrote (owner-only, mode 0600, directory 0700)",
1748
+ ` ${short(paths.serverEnv)}`,
1749
+ " owner/client IDs, profile encryption key",
1750
+ " The spawned server reads this file itself; no client holds a secret.",
1751
+ "",
1752
+ `Transport stdio (each client spawns its own ${SERVER_COMMAND})`,
1753
+ "",
1754
+ "Clients",
1755
+ ];
1756
+ for (const client of configured)
1757
+ lines.push(` ${client.padEnd(14)}configured`);
1758
+ for (const entry of skipped)
1759
+ lines.push(` ${entry}`);
1760
+ if (configured.length === 0 && skipped.length === 0)
1761
+ lines.push(" (none requested)");
1762
+ lines.push("", "Next steps", " 1. Create a ServiceNow profile. Secrets are prompted, never passed in argv:", " servicenow-mcp-profile create --name dev \\", " --instance https://yourinstance.service-now.com \\", " --auth-type oauth --client-id <client-id> --source reference --provider env", "", " 2. Grant least-privilege table access. A profile with no rules denies every call:", " servicenow-mcp-setup grant --profile dev --read incident,problem --write incident", "", " 3. Verify the install:", " servicenow-mcp-setup doctor --profile dev", "", " Then start a registered client; it launches the server itself.", "");
1763
+ if (manual.length > 0) {
1764
+ lines.push(`Configure the remaining clients by hand:`, ` servicenow-mcp-setup client --client ${manual.join(",")}`, "");
1765
+ }
1766
+ lines.push(...STDIO_BOUNDARY_NOTICE, "");
1767
+ lines.push("See docs/CLIENT-SETUP.md.", "");
1768
+ return `${lines.join("\n")}\n`;
1769
+ }
1770
+ function renderDoctorText(checks) {
1771
+ const lines = ["ServiceNow MCP doctor", ""];
1772
+ for (const check of checks) {
1773
+ lines.push(`${check.ok ? "ok " : "FAIL"} ${check.name}: ${check.detail}`);
1774
+ if (!check.ok && check.remedy)
1775
+ lines.push(` -> ${check.remedy}`);
1776
+ }
1777
+ const failed = checks.filter((check) => !check.ok).length;
1778
+ lines.push("", failed === 0
1779
+ ? "All checks passed."
1780
+ : `${failed} check${failed === 1 ? "" : "s"} failed; see the remedies above.`, "");
1781
+ return lines.join("\n");
1782
+ }
1783
+ function renderSetupHelp() {
1784
+ return [
1785
+ "Usage: servicenow-mcp-setup <command> [options]",
1786
+ "",
1787
+ "Commands:",
1788
+ " (default) Walk through a complete setup: local auth material, a",
1789
+ " ServiceNow profile with its credential verified against the",
1790
+ " instance, table access, and client registration.",
1791
+ " client Print copy-pasteable configuration for one or more MCP clients.",
1792
+ " grant Add least-privilege table access rules to an existing profile.",
1793
+ " doctor Diagnose a local install and print the remedy for each failure.",
1794
+ "",
1795
+ "Run any command with --help for its options.",
1796
+ ].join("\n");
1797
+ }
1798
+ function renderInitHelp() {
1799
+ return [
1800
+ "Usage: servicenow-mcp-setup [options]",
1801
+ "",
1802
+ "Run bare on a terminal, this is a guided wizard: it generates the local",
1803
+ "auth material, prompts for the instance and credential, verifies that",
1804
+ "credential against the instance, prompts for table access, writes the",
1805
+ "profile with its grant attached, and registers supported clients.",
1806
+ "",
1807
+ "With any flag, or without a terminal, it only generates the env files and",
1808
+ "registers clients \u2014 the established non-interactive behavior.",
1809
+ "",
1810
+ "Options:",
1811
+ ` --clients LIST auto | all | none | ${ALL_CLIENTS.join(",")}`,
1812
+ " --force Regenerate the owner/client identifiers (keeps the encryption key)",
1813
+ " --rotate-encryption-key Also regenerate SN_PROFILE_ENCRYPTION_KEY; refused if profiles exist",
1814
+ " --dry-run Report what would be written and exit",
1815
+ " --json Machine-readable output",
1816
+ " --non-interactive Skip the guided wizard even on a terminal",
1817
+ "",
1818
+ "Run bare on a terminal to be walked through instance, credential,",
1819
+ "table access, and client registration in one command.",
1820
+ ].join("\n");
1821
+ }
1822
+ function renderClientHelp() {
1823
+ return [
1824
+ "Usage: servicenow-mcp-setup client [--client LIST]",
1825
+ "",
1826
+ "Prints copy-pasteable MCP client configuration. No file is written.",
1827
+ "Every client is configured as a stdio server: it spawns servicenow-mcp",
1828
+ "itself and speaks JSON-RPC over that process's stdin/stdout.",
1829
+ "",
1830
+ "Options:",
1831
+ ` --client LIST all (default) | ${ALL_CLIENTS.join(",")}`,
1832
+ ].join("\n");
1833
+ }
1834
+ function renderGrantHelp() {
1835
+ return [
1836
+ "Usage: servicenow-mcp-setup grant --profile NAME [--read TABLES] [--write TABLES]",
1837
+ "",
1838
+ "Writes tableAccess rules onto an existing profile in ~/.servicenow-mcp/config.json.",
1839
+ "A profile with no rules denies every tool call, so this is required before first use.",
1840
+ "Rules are additive unless --replace is given, and the result is validated with the",
1841
+ "same loader the server uses at request time.",
1842
+ "",
1843
+ "Options:",
1844
+ " --profile NAME Profile to modify (required)",
1845
+ " --read TABLES Comma-separated tables to allow for reads",
1846
+ " --write TABLES Comma-separated tables to allow for writes",
1847
+ ` --tools LIST Tools permitted on these targets`,
1848
+ ` (default read: ${DEFAULT_READ_TOOLS.join(",")};`,
1849
+ ` default write adds: ${DEFAULT_WRITE_TOOLS.join(",")})`,
1850
+ " --related TABLE=LIST Backing/ancestor/descendant tables the target reaches;",
1851
+ " repeatable, and required whenever a table extends another",
1852
+ " --replace Discard existing rules instead of adding to them",
1853
+ " --dry-run Print the resulting rules without writing them",
1854
+ " --json Machine-readable output",
1855
+ "",
1856
+ "Wildcards are refused here. A '*' allowlist skips the per-tool binding and the",
1857
+ "related-table closure check; configure it deliberately after reading",
1858
+ "docs/PRODUCTION-SECURITY.md.",
1859
+ ].join("\n");
1860
+ }
1861
+ function renderDoctorHelp() {
1862
+ return [
1863
+ "Usage: servicenow-mcp-setup doctor [--profile NAME]",
1864
+ "",
1865
+ "Checks Node version, that the servicenow-mcp command clients spawn resolves",
1866
+ "on PATH, config file ownership and modes, profile completeness, credential",
1867
+ "resolution, and table access. Exits non-zero when any check fails. Never",
1868
+ "prints a secret value, and never touches the network.",
1869
+ "",
1870
+ "Options:",
1871
+ " --profile NAME Check only this profile (default: every configured profile)",
1872
+ " --json Machine-readable output",
1873
+ ].join("\n");
1874
+ }
1875
+ class SetupHelp extends Error {
1876
+ help;
1877
+ constructor(help) {
1878
+ super("setup help requested");
1879
+ this.help = help;
1880
+ }
1881
+ }
1882
+ async function main() {
1883
+ try {
1884
+ if (process.argv[2] === "--help" || process.argv[2] === "-h") {
1885
+ process.stdout.write(`${renderSetupHelp()}\n`);
1886
+ return;
1887
+ }
1888
+ await runSetupCli();
1889
+ }
1890
+ catch (error) {
1891
+ if (error instanceof SetupHelp) {
1892
+ process.stdout.write(`${error.help}\n`);
1893
+ return;
1894
+ }
1895
+ const message = error instanceof Error ? error.message : "Setup failed";
1896
+ process.stderr.write(`[servicenow-mcp] ${message}\n`);
1897
+ process.exitCode = 1;
1898
+ }
1899
+ }
1900
+ if (require.main === module) {
1901
+ void main();
1902
+ }
1903
+ //# sourceMappingURL=setup.js.map