@onlyflows/servicenow-mcp 2.2.0-dev.5 → 2.2.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 (251) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +312 -0
  3. package/README.md +504 -101
  4. package/dist/atf-form.d.ts +3 -15
  5. package/dist/atf-form.d.ts.map +1 -1
  6. package/dist/atf-result-cache.d.ts +23 -59
  7. package/dist/atf-result-cache.d.ts.map +1 -1
  8. package/dist/auth.d.ts +1 -0
  9. package/dist/auth.d.ts.map +1 -1
  10. package/dist/auth.js +17 -0
  11. package/dist/auth.js.map +1 -1
  12. package/dist/batch-limits.d.ts +18 -0
  13. package/dist/batch-limits.d.ts.map +1 -0
  14. package/dist/batch-limits.js +21 -0
  15. package/dist/batch-limits.js.map +1 -0
  16. package/dist/bounded-input.d.ts +49 -0
  17. package/dist/bounded-input.d.ts.map +1 -0
  18. package/dist/bounded-input.js +81 -0
  19. package/dist/bounded-input.js.map +1 -0
  20. package/dist/client.d.ts +25 -0
  21. package/dist/client.d.ts.map +1 -1
  22. package/dist/client.js +92 -18
  23. package/dist/client.js.map +1 -1
  24. package/dist/command-resolution.d.ts +53 -0
  25. package/dist/command-resolution.d.ts.map +1 -0
  26. package/dist/command-resolution.js +154 -0
  27. package/dist/command-resolution.js.map +1 -0
  28. package/dist/encoded-query-policy.d.ts +11 -0
  29. package/dist/encoded-query-policy.d.ts.map +1 -1
  30. package/dist/encoded-query-policy.js +10 -1
  31. package/dist/encoded-query-policy.js.map +1 -1
  32. package/dist/field-policy.d.ts +82 -3
  33. package/dist/field-policy.d.ts.map +1 -1
  34. package/dist/field-policy.js +609 -80
  35. package/dist/field-policy.js.map +1 -1
  36. package/dist/html-response.d.ts +34 -0
  37. package/dist/html-response.d.ts.map +1 -0
  38. package/dist/html-response.js +72 -0
  39. package/dist/html-response.js.map +1 -0
  40. package/dist/http-runtime.d.ts.map +1 -1
  41. package/dist/http-runtime.js +8 -0
  42. package/dist/http-runtime.js.map +1 -1
  43. package/dist/incident-journal-policy.d.ts +27 -5
  44. package/dist/incident-journal-policy.d.ts.map +1 -1
  45. package/dist/incident-journal-policy.js +34 -21
  46. package/dist/incident-journal-policy.js.map +1 -1
  47. package/dist/json-shape-limits.d.ts +71 -0
  48. package/dist/json-shape-limits.d.ts.map +1 -0
  49. package/dist/json-shape-limits.js +131 -0
  50. package/dist/json-shape-limits.js.map +1 -0
  51. package/dist/metadata-cache.d.ts +46 -21
  52. package/dist/metadata-cache.d.ts.map +1 -1
  53. package/dist/metadata-cache.js +228 -195
  54. package/dist/metadata-cache.js.map +1 -1
  55. package/dist/policy-card.d.ts +131 -0
  56. package/dist/policy-card.d.ts.map +1 -0
  57. package/dist/policy-card.js +409 -0
  58. package/dist/policy-card.js.map +1 -0
  59. package/dist/profile-admin.d.ts.map +1 -1
  60. package/dist/profile-admin.js +3 -0
  61. package/dist/profile-admin.js.map +1 -1
  62. package/dist/profile-manager.d.ts +17 -3
  63. package/dist/profile-manager.d.ts.map +1 -1
  64. package/dist/profile-manager.js +98 -6
  65. package/dist/profile-manager.js.map +1 -1
  66. package/dist/record-identifier-policy.d.ts +2 -8
  67. package/dist/record-identifier-policy.d.ts.map +1 -1
  68. package/dist/risky-grants.d.ts +25 -0
  69. package/dist/risky-grants.d.ts.map +1 -0
  70. package/dist/risky-grants.js +77 -0
  71. package/dist/risky-grants.js.map +1 -0
  72. package/dist/server.d.ts.map +1 -1
  73. package/dist/server.js +74 -0
  74. package/dist/server.js.map +1 -1
  75. package/dist/setup-prompts.js +1 -0
  76. package/dist/setup-prompts.js.map +1 -1
  77. package/dist/setup.d.ts +8 -1
  78. package/dist/setup.d.ts.map +1 -1
  79. package/dist/setup.js +492 -111
  80. package/dist/setup.js.map +1 -1
  81. package/dist/stdio-runtime.d.ts +15 -0
  82. package/dist/stdio-runtime.d.ts.map +1 -1
  83. package/dist/stdio-runtime.js +60 -0
  84. package/dist/stdio-runtime.js.map +1 -1
  85. package/dist/structured-query.d.ts +100 -115
  86. package/dist/structured-query.d.ts.map +1 -1
  87. package/dist/structured-query.js +132 -16
  88. package/dist/structured-query.js.map +1 -1
  89. package/dist/table-policy.d.ts +10 -4
  90. package/dist/table-policy.d.ts.map +1 -1
  91. package/dist/table-policy.js +1 -1
  92. package/dist/table-policy.js.map +1 -1
  93. package/dist/tool-error.d.ts +18 -0
  94. package/dist/tool-error.d.ts.map +1 -1
  95. package/dist/tool-error.js +69 -0
  96. package/dist/tool-error.js.map +1 -1
  97. package/dist/tool-table-access.d.ts.map +1 -1
  98. package/dist/tool-table-access.js +32 -2
  99. package/dist/tool-table-access.js.map +1 -1
  100. package/dist/tools/aggregate.d.ts +13 -19
  101. package/dist/tools/aggregate.d.ts.map +1 -1
  102. package/dist/tools/aggregate.js +2 -3
  103. package/dist/tools/aggregate.js.map +1 -1
  104. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  105. package/dist/tools/all-fields-cap.js +3 -38
  106. package/dist/tools/all-fields-cap.js.map +1 -1
  107. package/dist/tools/atf-author-module.d.ts +28 -7
  108. package/dist/tools/atf-author-module.d.ts.map +1 -1
  109. package/dist/tools/atf-author-module.js +4 -2
  110. package/dist/tools/atf-author-module.js.map +1 -1
  111. package/dist/tools/atf-contracts.d.ts +135 -829
  112. package/dist/tools/atf-contracts.d.ts.map +1 -1
  113. package/dist/tools/atf-shared.js +2 -2
  114. package/dist/tools/atf-shared.js.map +1 -1
  115. package/dist/tools/atf-step-catalog.d.ts +3 -7
  116. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  117. package/dist/tools/atf-step-catalog.js +12 -5
  118. package/dist/tools/atf-step-catalog.js.map +1 -1
  119. package/dist/tools/atf.d.ts +8 -24
  120. package/dist/tools/atf.d.ts.map +1 -1
  121. package/dist/tools/atf.js +2 -2
  122. package/dist/tools/atf.js.map +1 -1
  123. package/dist/tools/attach.d.ts +6 -22
  124. package/dist/tools/attach.d.ts.map +1 -1
  125. package/dist/tools/batch.d.ts +18 -71
  126. package/dist/tools/batch.d.ts.map +1 -1
  127. package/dist/tools/batch.js +544 -96
  128. package/dist/tools/batch.js.map +1 -1
  129. package/dist/tools/catalog.d.ts +2 -2
  130. package/dist/tools/catalog.d.ts.map +1 -1
  131. package/dist/tools/catalog.js +7 -1
  132. package/dist/tools/catalog.js.map +1 -1
  133. package/dist/tools/codesearch.d.ts +1 -13
  134. package/dist/tools/codesearch.d.ts.map +1 -1
  135. package/dist/tools/create-module.d.ts +9 -14
  136. package/dist/tools/create-module.d.ts.map +1 -1
  137. package/dist/tools/create-module.js +4 -8
  138. package/dist/tools/create-module.js.map +1 -1
  139. package/dist/tools/delete.d.ts +1 -9
  140. package/dist/tools/delete.d.ts.map +1 -1
  141. package/dist/tools/delete.js +2 -3
  142. package/dist/tools/delete.js.map +1 -1
  143. package/dist/tools/discover.d.ts +6 -14
  144. package/dist/tools/discover.d.ts.map +1 -1
  145. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  146. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  147. package/dist/tools/flow-view-contracts.js +570 -0
  148. package/dist/tools/flow-view-contracts.js.map +1 -0
  149. package/dist/tools/flow-view-graph.d.ts +86 -0
  150. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  151. package/dist/tools/flow-view-graph.js +993 -0
  152. package/dist/tools/flow-view-graph.js.map +1 -0
  153. package/dist/tools/flow-view-gzip.d.ts +52 -0
  154. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  155. package/dist/tools/flow-view-gzip.js +179 -0
  156. package/dist/tools/flow-view-gzip.js.map +1 -0
  157. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  158. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  159. package/dist/tools/flow-view-mermaid.js +337 -0
  160. package/dist/tools/flow-view-mermaid.js.map +1 -0
  161. package/dist/tools/flow-view-module.d.ts +61 -0
  162. package/dist/tools/flow-view-module.d.ts.map +1 -0
  163. package/dist/tools/flow-view-module.js +378 -0
  164. package/dist/tools/flow-view-module.js.map +1 -0
  165. package/dist/tools/flow-view-policy.d.ts +106 -0
  166. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  167. package/dist/tools/flow-view-policy.js +461 -0
  168. package/dist/tools/flow-view-policy.js.map +1 -0
  169. package/dist/tools/flow-view-renderers.d.ts +68 -0
  170. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  171. package/dist/tools/flow-view-renderers.js +513 -0
  172. package/dist/tools/flow-view-renderers.js.map +1 -0
  173. package/dist/tools/flow-view-table.d.ts +115 -0
  174. package/dist/tools/flow-view-table.d.ts.map +1 -0
  175. package/dist/tools/flow-view-table.js +1002 -0
  176. package/dist/tools/flow-view-table.js.map +1 -0
  177. package/dist/tools/get-module.d.ts +36 -42
  178. package/dist/tools/get-module.d.ts.map +1 -1
  179. package/dist/tools/health.d.ts +9 -6
  180. package/dist/tools/health.d.ts.map +1 -1
  181. package/dist/tools/incident-journal-module.d.ts +8 -7
  182. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  183. package/dist/tools/index.d.ts +4 -4
  184. package/dist/tools/index.d.ts.map +1 -1
  185. package/dist/tools/index.js +43 -6
  186. package/dist/tools/index.js.map +1 -1
  187. package/dist/tools/markdown.d.ts +27 -0
  188. package/dist/tools/markdown.d.ts.map +1 -1
  189. package/dist/tools/markdown.js +104 -1
  190. package/dist/tools/markdown.js.map +1 -1
  191. package/dist/tools/nl.d.ts +1 -11
  192. package/dist/tools/nl.d.ts.map +1 -1
  193. package/dist/tools/profile.d.ts +1 -1
  194. package/dist/tools/profile.d.ts.map +1 -1
  195. package/dist/tools/profile.js +19 -1
  196. package/dist/tools/profile.js.map +1 -1
  197. package/dist/tools/query-module.d.ts +59 -71
  198. package/dist/tools/query-module.d.ts.map +1 -1
  199. package/dist/tools/query-module.js +2 -2
  200. package/dist/tools/query-module.js.map +1 -1
  201. package/dist/tools/record-write-shared.d.ts.map +1 -1
  202. package/dist/tools/record-write-shared.js +19 -2
  203. package/dist/tools/record-write-shared.js.map +1 -1
  204. package/dist/tools/relationships.d.ts +6 -22
  205. package/dist/tools/relationships.d.ts.map +1 -1
  206. package/dist/tools/result-envelope.d.ts +2255 -1357
  207. package/dist/tools/result-envelope.d.ts.map +1 -1
  208. package/dist/tools/result-envelope.js +24 -2
  209. package/dist/tools/result-envelope.js.map +1 -1
  210. package/dist/tools/schema-module.d.ts +36 -21
  211. package/dist/tools/schema-module.d.ts.map +1 -1
  212. package/dist/tools/schema-module.js +106 -65
  213. package/dist/tools/schema-module.js.map +1 -1
  214. package/dist/tools/script.d.ts +1 -11
  215. package/dist/tools/script.d.ts.map +1 -1
  216. package/dist/tools/syslog.d.ts +11 -18
  217. package/dist/tools/syslog.d.ts.map +1 -1
  218. package/dist/tools/syslog.js +2 -3
  219. package/dist/tools/syslog.js.map +1 -1
  220. package/dist/tools/table-hierarchy.d.ts +35 -0
  221. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  222. package/dist/tools/table-hierarchy.js +74 -0
  223. package/dist/tools/table-hierarchy.js.map +1 -0
  224. package/dist/tools/tool-module.d.ts +40 -15
  225. package/dist/tools/tool-module.d.ts.map +1 -1
  226. package/dist/tools/tool-module.js +755 -205
  227. package/dist/tools/tool-module.js.map +1 -1
  228. package/dist/tools/update-module.d.ts +11 -17
  229. package/dist/tools/update-module.d.ts.map +1 -1
  230. package/dist/tools/update-module.js +10 -12
  231. package/dist/tools/update-module.js.map +1 -1
  232. package/dist/version.d.ts +1 -1
  233. package/dist/version.d.ts.map +1 -1
  234. package/dist/version.js +1 -1
  235. package/dist/version.js.map +1 -1
  236. package/dist/write-value-policy.d.ts +20 -12
  237. package/dist/write-value-policy.d.ts.map +1 -1
  238. package/dist/write-value-policy.js +179 -67
  239. package/dist/write-value-policy.js.map +1 -1
  240. package/docs/ADDING-TOOLS.md +22 -13
  241. package/docs/CLIENT-SETUP.md +110 -52
  242. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  243. package/docs/FLOW-VIEW.md +214 -0
  244. package/docs/PRODUCTION-SECURITY.md +154 -25
  245. package/docs/RELEASE-VALIDATION.md +2 -2
  246. package/docs/TESTING-OAUTH.md +1 -1
  247. package/docs/V2-MIGRATION.md +404 -30
  248. package/package.json +21 -6
  249. package/scripts/release-validate.mjs +56 -0
  250. package/server.json +22 -0
  251. package/tools/inspector/package-lock.json +163 -201
package/dist/setup.js CHANGED
@@ -36,11 +36,17 @@ const node_path_1 = require("node:path");
36
36
  const node_child_process_1 = require("node:child_process");
37
37
  const promises_1 = require("node:readline/promises");
38
38
  const client_js_1 = require("./client.js");
39
+ const command_resolution_js_1 = require("./command-resolution.js");
39
40
  const profile_admin_js_1 = require("./profile-admin.js");
40
41
  const profile_credentials_js_1 = require("./profile-credentials.js");
41
42
  const profile_manager_js_1 = require("./profile-manager.js");
43
+ const policy_card_js_1 = require("./policy-card.js");
44
+ const risky_grants_js_1 = require("./risky-grants.js");
42
45
  const tool_error_js_1 = require("./tool-error.js");
43
46
  const table_policy_js_1 = require("./table-policy.js");
47
+ const encoded_query_policy_js_1 = require("./encoded-query-policy.js");
48
+ const flow_view_contracts_js_1 = require("./tools/flow-view-contracts.js");
49
+ const table_hierarchy_js_1 = require("./tools/table-hierarchy.js");
44
50
  /** Raised when the operator aborts; nothing has been written to the profile. */
45
51
  class WizardAbort extends Error {
46
52
  constructor() {
@@ -124,6 +130,16 @@ const DEFAULT_WRITE_TOOLS = Object.freeze([
124
130
  "sn_create",
125
131
  "sn_update",
126
132
  ]);
133
+ /**
134
+ * Added to the `incident` target by a write grant when `--tools` is not given.
135
+ * These tools append to comments and work_notes and are authorized as incident
136
+ * writes, so an incident target that omitted them would deny them on a profile
137
+ * that can otherwise write incident.
138
+ */
139
+ const INCIDENT_JOURNAL_TOOLS = Object.freeze([
140
+ "sn_incident_add_comment",
141
+ "sn_incident_add_work_note",
142
+ ]);
127
143
  async function runSetupCli(dependencies = {}) {
128
144
  const env = dependencies.env ?? process.env;
129
145
  const argv = normalizeArgv(dependencies.argv ?? process.argv.slice(2));
@@ -138,6 +154,9 @@ async function runSetupCli(dependencies = {}) {
138
154
  case "grant":
139
155
  runGrant(parseGrantArguments(args), home, dependencies, out);
140
156
  return;
157
+ case "policy":
158
+ runPolicy(parsePolicyArguments(args), home, env, dependencies, out);
159
+ return;
141
160
  case "doctor":
142
161
  await runDoctor(parseDoctorArguments(args), home, env, dependencies, out);
143
162
  return;
@@ -188,13 +207,18 @@ async function runWizard(options, home, env, dependencies, out) {
188
207
  // was generated now or loaded from an earlier bootstrap. Bound and
189
208
  // validated here so a corrupt key fails before anything is prompted for.
190
209
  const keyProvider = dependencies.keyProvider ?? (0, profile_credentials_js_1.encryptionKeyProviderFromValue)(values[ENCRYPTION_KEY_ENV]);
210
+ // Which client CLIs are installed, said before anything is asked, so an
211
+ // operator without one learns it now rather than after the credential.
212
+ const clientContext = registrationContext(dependencies, env, home);
213
+ const clis = locateClientClis(clientContext);
214
+ prompter.note(renderClientCliNote(clis));
191
215
  // 2. Re-run safety: never clobber an existing profile without being told.
192
216
  const existing = existingProfileNames(manager);
193
217
  if (existing.length > 0) {
194
218
  prompter.note(`Existing profiles: ${existing.join(", ")}\n`);
195
219
  const choice = await prompter.ask("Add another profile, or just re-register MCP clients?", { default: "profile", choices: ["profile", "clients"] });
196
220
  if (choice === "clients") {
197
- const only = await registerClientsInteractively(prompter, options, env, dependencies);
221
+ const only = await registerClientsInteractively(prompter, options, clis, clientContext);
198
222
  out(renderClientOnlySummary(only, home));
199
223
  return;
200
224
  }
@@ -269,6 +293,11 @@ async function runWizard(options, home, env, dependencies, out) {
269
293
  }
270
294
  // 5. Table access. A profile without rules denies every call.
271
295
  const tableAccess = await askTableAccess(prompter, config, dependencies);
296
+ // Allowed, never blocked: privilege-sensitive tables are controlled by the
297
+ // profile's own configuration. The operator just has to see it said.
298
+ const riskWarning = (0, risky_grants_js_1.riskyGrantWarning)(tableAccess.writeTables ?? [], name);
299
+ if (riskWarning !== undefined)
300
+ prompter.note(`\n${riskWarning}`);
272
301
  // 6. One write, with the rules already attached — never a rules-less window.
273
302
  //
274
303
  // Retryable without re-prompting: everything needed is already in memory,
@@ -294,7 +323,7 @@ async function runWizard(options, home, env, dependencies, out) {
294
323
  }
295
324
  prompter.note(`\nWrote profile ${name}.\n${JSON.stringify((0, profile_admin_js_1.safeProfileView)(name, profile), null, 2)}\n`);
296
325
  // 7. Client configuration.
297
- const registered = await registerClientsInteractively(prompter, options, env, dependencies);
326
+ const registered = await registerClientsInteractively(prompter, options, clis, clientContext);
298
327
  // 8. Verify the install the way `doctor` does, so setup ends by reporting
299
328
  // the same facts rather than commands for the operator to copy. There
300
329
  // is nothing to start: a registered client spawns the server itself.
@@ -330,19 +359,36 @@ function existingProfileNames(manager) {
330
359
  }
331
360
  }
332
361
  async function askProfileName(prompter, existing) {
333
- return prompter.ask("Profile name", {
362
+ return prompter.ask("Profile name (letters, digits, . _ -; no spaces)", {
334
363
  default: existing.includes("dev") ? "" : "dev",
364
+ // The store's own rule, checked here so an unusable name is refused before
365
+ // the credential is typed and verified, not at the final save. The answer
366
+ // is checked exactly as it will be saved, so anything accepted can be.
335
367
  validate: (value) => {
336
- const name = value.trim();
337
- if (name === "")
338
- return "A profile name is required.";
339
- if (existing.includes(name)) {
340
- return `Profile "${name}" already exists. Choose another name, or remove it with servicenow-mcp-profile remove --name ${name}.`;
368
+ const problem = (0, profile_manager_js_1.profileNameProblem)(value);
369
+ if (problem !== undefined) {
370
+ const suggestion = suggestProfileName(value);
371
+ return suggestion !== undefined && !existing.includes(suggestion)
372
+ ? `${problem} Try "${suggestion}".`
373
+ : problem;
374
+ }
375
+ if (existing.includes(value)) {
376
+ return `Profile "${value}" already exists. Choose another name, or remove it with servicenow-mcp-profile remove --name ${value}.`;
341
377
  }
342
378
  return undefined;
343
379
  },
344
380
  });
345
381
  }
382
+ /** The nearest valid name to one that was refused, such as `my-dev` for `my dev`. */
383
+ function suggestProfileName(value) {
384
+ const candidate = value
385
+ .trim()
386
+ .replace(/\s+/gu, "-")
387
+ .replace(/[^A-Za-z0-9._-]/gu, "")
388
+ .replace(/^[.-]+/u, "")
389
+ .slice(0, 64);
390
+ return (0, profile_manager_js_1.profileNameProblem)(candidate) === undefined ? candidate : undefined;
391
+ }
346
392
  const SERVICENOW_SUFFIXES = Object.freeze([".service-now.com", ".servicenowservices.com"]);
347
393
  async function askInstance(prompter) {
348
394
  const answer = await prompter.ask("ServiceNow instance (for example dev12345.service-now.com)", { validate: instanceProblem });
@@ -411,7 +457,19 @@ function wizardConfig(profile, captured, mode, env) {
411
457
  * accepts it.
412
458
  */
413
459
  async function verifyCredentialAgainstInstance(config) {
414
- const client = new client_js_1.ServiceNowClient(config, { maxRetries: 0 });
460
+ let client;
461
+ try {
462
+ client = new client_js_1.ServiceNowClient(config, { maxRetries: 0 });
463
+ }
464
+ catch {
465
+ // Construction failed (for example an OAuth profile with no client
466
+ // secret): no request was sent, so this is not an HTTP 401.
467
+ return Object.freeze({
468
+ ok: false,
469
+ detail: `${safeHost(config.instance)}: the profile's credentials are incomplete, so no request was sent.`,
470
+ remedy: "Re-enter them with servicenow-mcp-setup.",
471
+ });
472
+ }
415
473
  try {
416
474
  await client.get(`/api/now/table/${WIZARD_PROBE_TABLE}`, {
417
475
  sysparm_limit: "1",
@@ -430,6 +488,34 @@ async function verifyCredentialAgainstInstance(config) {
430
488
  function classifyVerificationFailure(error, config) {
431
489
  const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
432
490
  const host = safeHost(config.instance);
491
+ if (descriptor?.reason === "instance_hibernating") {
492
+ return Object.freeze({
493
+ ok: false,
494
+ detail: `Instance hibernating: ${host} answered with a hibernation page instead of the API.`,
495
+ remedy: "Developer instances sleep when idle. Wake it at https://developer.servicenow.com, wait a few minutes, then retry.",
496
+ });
497
+ }
498
+ if (descriptor?.reason === "html_response") {
499
+ return Object.freeze({
500
+ ok: false,
501
+ detail: `${host} returned an HTML page instead of an API response.`,
502
+ remedy: "The instance may be asleep, behind single sign-on, or under maintenance. Check that the instance URL is reachable in a browser.",
503
+ });
504
+ }
505
+ if (descriptor?.reason === "redirected") {
506
+ return Object.freeze({
507
+ ok: false,
508
+ detail: `${host} redirected the request to another location.`,
509
+ remedy: "Check that the profile's instance URL is the instance's canonical URL.",
510
+ });
511
+ }
512
+ if (descriptor?.reason === "invalid_response") {
513
+ return Object.freeze({
514
+ ok: false,
515
+ detail: `${host} returned a response that is not valid JSON.`,
516
+ remedy: "Check that the instance URL is correct and reachable in a browser.",
517
+ });
518
+ }
433
519
  if (descriptor?.category === "authentication") {
434
520
  return Object.freeze({
435
521
  ok: false,
@@ -492,7 +578,8 @@ function classifyVerificationFailure(error, config) {
492
578
  }
493
579
  return Object.freeze({
494
580
  ok: false,
495
- detail: `${host} could not be reached: ${message}`,
581
+ // Fixed text only: the underlying message can quote response bytes.
582
+ detail: `${host} could not be reached.`,
496
583
  remedy: "Check the instance URL and this machine's outbound network access.",
497
584
  });
498
585
  }
@@ -511,10 +598,11 @@ async function askTableAccess(prompter, config, dependencies) {
511
598
  const read = await askTableSelection(prompter, "READS", DEFAULT_READ_TABLES);
512
599
  const write = await askTableSelection(prompter, "WRITES", "");
513
600
  const related = new Map();
601
+ const resolveParent = dependencies.resolveParentTable ?? parentTableReader();
514
602
  for (const table of new Set([...read, ...write])) {
515
603
  if (table === TABLE_ALLOWLIST_WILDCARD)
516
604
  continue;
517
- const parent = await lookupParentTable(config, table, dependencies);
605
+ const parent = await lookupParentTable(resolveParent, config, table);
518
606
  if (parent === undefined || parent === table)
519
607
  continue;
520
608
  prompter.note(`\n ${table} extends ${parent}.`);
@@ -590,62 +678,85 @@ async function askCustomTableList(prompter, operation) {
590
678
  * ServiceNow's inheritance graph. Best effort: a failure here is not a setup
591
679
  * failure, because the self-only closure the wizard writes is valid on its own.
592
680
  */
593
- async function lookupParentTable(config, table, dependencies) {
594
- const resolve = dependencies.resolveParentTable ?? defaultParentTable;
681
+ async function lookupParentTable(resolve, config, table) {
595
682
  try {
596
- return await resolve(config, table);
683
+ const parent = await resolve(config, table);
684
+ // Only a table name is ever offered, whichever resolver produced it: the
685
+ // answer goes into the allowlist and the target's closure as written.
686
+ return typeof parent === "string" && TABLE_NAME.test(parent) ? parent : undefined;
597
687
  }
598
688
  catch {
599
689
  return undefined;
600
690
  }
601
691
  }
602
- async function defaultParentTable(config, table) {
603
- if (!TABLE_NAME.test(table))
604
- return undefined;
605
- const client = new client_js_1.ServiceNowClient(config, { maxRetries: 0 });
606
- const response = await client.get("/api/now/table/sys_db_object", {
607
- sysparm_query: `name=${table}`,
608
- sysparm_fields: "name,super_class",
609
- sysparm_limit: "1",
610
- sysparm_display_value: "true",
611
- sysparm_exclude_reference_link: "true",
612
- });
613
- const row = Array.isArray(response?.result) ? response.result[0] : undefined;
614
- if (typeof row !== "object" || row === null)
615
- return undefined;
616
- const value = row.super_class;
617
- const parent = typeof value === "string"
618
- ? value
619
- : typeof value === "object" && value !== null
620
- ? value.display_value
621
- : undefined;
622
- if (typeof parent !== "string")
623
- return undefined;
624
- const normalized = parent.trim().toLowerCase();
625
- return TABLE_NAME.test(normalized) ? normalized : undefined;
692
+ /** The table itself and its immediate parent: the wizard offers only that one. */
693
+ const PARENT_LOOKUP_DEPTH = 2;
694
+ /**
695
+ * The default resolver: the parent's name from sys_db_object, through the same
696
+ * walk sn_schema uses. super_class's display value is the parent's label, not
697
+ * its name, so following it offered "server" for cmdb_ci_linux_server and
698
+ * nothing at all for a label with a space, such as "Configuration Item".
699
+ *
700
+ * It keeps one client per configuration, so an OAuth profile fetches one token
701
+ * for the run's lookups rather than one per table.
702
+ */
703
+ function parentTableReader() {
704
+ let cached;
705
+ return async (config, table) => {
706
+ if (!TABLE_NAME.test(table))
707
+ return undefined;
708
+ if (cached?.config !== config) {
709
+ cached = { config, client: new client_js_1.ServiceNowClient(config, { maxRetries: 0 }) };
710
+ }
711
+ const [, parent] = await (0, table_hierarchy_js_1.resolveTableHierarchy)(cached.client, table, PARENT_LOOKUP_DEPTH, false);
712
+ return parent;
713
+ };
626
714
  }
627
- async function registerClientsInteractively(prompter, options, env, dependencies) {
628
- const commandExists = dependencies.commandExists ?? defaultCommandExists;
629
- const runCommand = dependencies.runCommand ?? defaultRunCommand;
630
- const available = AUTO_REGISTERED_CLIENTS.filter((client) => commandExists(client === "codex" ? "codex" : "claude"));
631
- if (available.length === 0)
715
+ async function registerClientsInteractively(prompter, options, clis, context) {
716
+ if (clis.length === 0) {
717
+ // Without this, the summary's "(none registered)" is the only sign, and it
718
+ // does not say that no client CLI was found to register with.
719
+ prompter.note("\nNo Claude Code (claude) or Codex (codex) CLI was found, so no client\n" +
720
+ "was registered automatically.");
632
721
  return Object.freeze([]);
633
- if (!(await prompter.confirm(`\nRegister this server with ${available.join(" and ")}?`, true))) {
722
+ }
723
+ if (!(await prompter.confirm(`\nRegister this server with ${clis.map((cli) => cli.client).join(" and ")}?`, true))) {
634
724
  return Object.freeze([]);
635
725
  }
636
- const context = { commandExists, runCommand, env };
637
726
  const configured = [];
638
- for (const client of available) {
639
- const result = registerClient(client, options.force, context);
727
+ for (const cli of clis) {
728
+ const result = registerClient(cli, options.force, context);
640
729
  if (result.ok)
641
- configured.push(client);
730
+ configured.push(cli.client);
642
731
  else
643
- prompter.note(` skipped ${client}: ${result.reason}`);
732
+ prompter.note(` skipped ${cli.client}: ${result.reason}`);
644
733
  }
645
734
  return Object.freeze(configured);
646
735
  }
736
+ /**
737
+ * Say up front which clients setup can register with, before the operator
738
+ * spends time on a credential. With none, they can stop and install Claude
739
+ * Code first, or know that the client is theirs to configure afterwards.
740
+ */
741
+ function renderClientCliNote(clis) {
742
+ if (clis.length === 0) {
743
+ return ("No Claude Code (claude) or Codex (codex) CLI was found, so setup cannot\n" +
744
+ "register this server with a client for you. It will still create and\n" +
745
+ "verify your profile. Afterwards, either install Claude Code and run\n" +
746
+ 'servicenow-mcp-setup again (choose "clients"), or configure your client\n' +
747
+ "by hand: servicenow-mcp-setup client\n");
748
+ }
749
+ const lines = clis.map((cli) => cli.offPath
750
+ ? `Found ${CLIENT_CLI_LABELS[cli.client]} at ${cli.command},\n` +
751
+ "but its folder is not on this terminal's PATH. Setup will run it from\n" +
752
+ `there. To run ${clientBinary(cli.client)} yourself, open a new terminal; if it is\n` +
753
+ `still not recognized, add ${(0, node_path_1.dirname)(cli.command)} to your PATH.`
754
+ : `Found ${CLIENT_CLI_LABELS[cli.client]}.`);
755
+ return `${lines.join("\n")}\n`;
756
+ }
647
757
  function renderWizardSummary(profile, tableAccess, registered, home, checks) {
648
758
  const failed = checks.filter((check) => !check.ok).length;
759
+ const riskWarning = (0, risky_grants_js_1.riskyGrantWarning)(tableAccess.writeTables ?? [], profile);
649
760
  const lines = [
650
761
  "",
651
762
  "Setup complete.",
@@ -653,6 +764,7 @@ function renderWizardSummary(profile, tableAccess, registered, home, checks) {
653
764
  `Profile ${profile}`,
654
765
  `Reads ${(tableAccess.readTables ?? []).join(", ") || "(none)"}`,
655
766
  `Writes ${(tableAccess.writeTables ?? []).join(", ") || "(none)"}`,
767
+ ...(riskWarning === undefined ? [] : ["", riskWarning.trimEnd(), ""]),
656
768
  `Transport stdio (each client spawns its own ${SERVER_COMMAND})`,
657
769
  `Clients ${registered.length > 0 ? registered.join(", ") : "(none registered)"}`,
658
770
  "",
@@ -792,8 +904,7 @@ async function runInit(options, home, env, dependencies, out, err) {
792
904
  }
793
905
  const values = loadOrCreateBootstrapValues(paths, options);
794
906
  writeSecureEnvFile(paths.serverEnv, values);
795
- const commandExists = dependencies.commandExists ?? defaultCommandExists;
796
- const runCommand = dependencies.runCommand ?? defaultRunCommand;
907
+ const context = registrationContext(dependencies, env, home);
797
908
  const configuredClients = [];
798
909
  const skippedClients = [];
799
910
  for (const client of options.clients) {
@@ -801,11 +912,12 @@ async function runInit(options, home, env, dependencies, out, err) {
801
912
  skippedClients.push(`${client} (no CLI to register with)`);
802
913
  continue;
803
914
  }
804
- const registration = registerClient(client, options.force, {
805
- commandExists,
806
- runCommand,
807
- env,
808
- });
915
+ const cli = locateClientCli(client, context);
916
+ if (cli === undefined) {
917
+ skippedClients.push(`${client} (${clientBinary(client)} CLI not found)`);
918
+ continue;
919
+ }
920
+ const registration = registerClient(cli, options.force, context);
809
921
  if (registration.ok)
810
922
  configuredClients.push(client);
811
923
  else
@@ -838,6 +950,82 @@ async function runInit(options, home, env, dependencies, out, err) {
838
950
  err(`[servicenow-mcp] skipped client setup: ${skippedClients.join(", ")}\n`);
839
951
  }
840
952
  }
953
+ function registrationContext(dependencies, env, home) {
954
+ return Object.freeze({
955
+ commandExists: dependencies.commandExists ?? defaultCommandExists,
956
+ runCommand: dependencies.runCommand ?? defaultRunCommand,
957
+ env,
958
+ home,
959
+ platform: dependencies.platform ?? process.platform,
960
+ serverEntrypoint: dependencies.serverEntrypoint ?? defaultServerEntrypoint(),
961
+ });
962
+ }
963
+ const CLIENT_CLI_LABELS = Object.freeze({
964
+ codex: "Codex (codex)",
965
+ "claude-code": "Claude Code (claude)",
966
+ });
967
+ function clientBinary(client) {
968
+ return client === "codex" ? "codex" : "claude";
969
+ }
970
+ function locateClientClis(context) {
971
+ return Object.freeze(AUTO_REGISTERED_CLIENTS.map((client) => locateClientCli(client, context)).filter((cli) => cli !== undefined));
972
+ }
973
+ /**
974
+ * Find a client's CLI on PATH or, failing that, where its installer puts it.
975
+ *
976
+ * Installed but not on PATH is common on Windows: the Claude Code installer
977
+ * adds its folder to the user PATH, but a terminal opened before the install
978
+ * keeps the old PATH, so `claude` is not recognized there. Registering needs
979
+ * only the executable, not PATH, so setup runs it by full path instead of
980
+ * reporting it missing.
981
+ */
982
+ function locateClientCli(client, context) {
983
+ const binary = clientBinary(client);
984
+ if (context.commandExists(binary)) {
985
+ return Object.freeze({ client, command: binary, offPath: false });
986
+ }
987
+ const found = defaultInstallLocations(binary, context).find(isRegularFile);
988
+ return found === undefined
989
+ ? undefined
990
+ : Object.freeze({ client, command: found, offPath: true });
991
+ }
992
+ /**
993
+ * Where each CLI's documented installers put it
994
+ * (https://code.claude.com/docs/en/troubleshoot-install). WinGet and Homebrew
995
+ * installs are left out: their paths are not documented, and they normally
996
+ * land on PATH anyway.
997
+ */
998
+ function defaultInstallLocations(binary, context) {
999
+ const windows = context.platform === "win32";
1000
+ // Claude Code installs under USERPROFILE, which HOME can differ from on
1001
+ // Windows (Git Bash sets it), so check both.
1002
+ const homes = [
1003
+ ...new Set([context.home, windows ? context.env.USERPROFILE : undefined].filter((home) => Boolean(home))),
1004
+ ];
1005
+ const locations = [];
1006
+ if (binary === "claude") {
1007
+ for (const home of homes) {
1008
+ // The native installer.
1009
+ locations.push((0, node_path_1.join)(home, ".local", "bin", windows ? "claude.exe" : "claude"));
1010
+ // The legacy local install older versions created.
1011
+ if (!windows)
1012
+ locations.push((0, node_path_1.join)(home, ".claude", "local", "claude"));
1013
+ }
1014
+ }
1015
+ // npm's default global prefix on Windows, where `npm install -g` writes its
1016
+ // .cmd shims: Codex always installs this way, and Claude Code can.
1017
+ if (windows && context.env.APPDATA) {
1018
+ locations.push((0, node_path_1.join)(context.env.APPDATA, "npm", `${binary}.cmd`));
1019
+ }
1020
+ return locations;
1021
+ }
1022
+ function isRegularFile(path) {
1023
+ return (0, node_fs_1.statSync)(path, { throwIfNoEntry: false })?.isFile() ?? false;
1024
+ }
1025
+ /** The server entrypoint that ships beside this CLI in `dist`. */
1026
+ function defaultServerEntrypoint() {
1027
+ return (0, node_path_1.join)(__dirname, "index.js");
1028
+ }
841
1029
  /**
842
1030
  * Resolve the command a client should spawn.
843
1031
  *
@@ -847,25 +1035,25 @@ async function runInit(options, home, env, dependencies, out, err) {
847
1035
  * client's own PATH will not have — registering it anyway would produce a
848
1036
  * client that fails to launch with nothing to point at. So fall back to this
849
1037
  * CLI's own sibling entrypoint, which is unambiguous and always correct.
1038
+ *
1039
+ * Windows always gets the entrypoint. There, npm installs `servicenow-mcp` as
1040
+ * a `.cmd` shim, and clients spawn stdio servers without a shell, which cannot
1041
+ * run one, so the bare name fails to launch even when it is on PATH.
850
1042
  */
851
- function resolveServerLaunch(commandExists) {
852
- if (commandExists(SERVER_COMMAND)) {
1043
+ function resolveServerLaunch(context) {
1044
+ if (context.platform !== "win32" && context.commandExists(SERVER_COMMAND)) {
853
1045
  return Object.freeze({ command: SERVER_COMMAND, args: Object.freeze([]) });
854
1046
  }
855
1047
  return Object.freeze({
856
1048
  command: process.execPath,
857
- args: Object.freeze([(0, node_path_1.join)(__dirname, "index.js")]),
1049
+ args: Object.freeze([context.serverEntrypoint]),
858
1050
  });
859
1051
  }
860
- function registerClient(client, force, context) {
861
- const binary = client === "codex" ? "codex" : "claude";
862
- if (!context.commandExists(binary)) {
863
- return { ok: false, reason: `${binary} CLI not found` };
864
- }
865
- const launch = resolveServerLaunch(context.commandExists);
866
- const result = client === "codex"
867
- ? configureCodex(launch, force, context)
868
- : configureClaudeCode(launch, force, context);
1052
+ function registerClient(cli, force, context) {
1053
+ const launch = resolveServerLaunch(context);
1054
+ const result = cli.client === "codex"
1055
+ ? configureCodex(cli.command, launch, force, context)
1056
+ : configureClaudeCode(cli.command, launch, force, context);
869
1057
  if (result.status === 0)
870
1058
  return { ok: true };
871
1059
  return {
@@ -874,31 +1062,31 @@ function registerClient(client, force, context) {
874
1062
  };
875
1063
  }
876
1064
  /** `codex mcp add <name> -- <command> [args...]` registers a stdio server. */
877
- function configureCodex(launch, force, context) {
878
- const existing = context.runCommand("codex", ["mcp", "get", MCP_SERVER_NAME], context.env);
1065
+ function configureCodex(codex, launch, force, context) {
1066
+ const existing = context.runCommand(codex, ["mcp", "get", MCP_SERVER_NAME], context.env);
879
1067
  if (existing.status === 0) {
880
1068
  if (!force)
881
1069
  return Object.freeze({ status: 0 });
882
- const removed = context.runCommand("codex", ["mcp", "remove", MCP_SERVER_NAME], context.env);
1070
+ const removed = context.runCommand(codex, ["mcp", "remove", MCP_SERVER_NAME], context.env);
883
1071
  if (removed.status !== 0)
884
1072
  return removed;
885
1073
  }
886
- return context.runCommand("codex", ["mcp", "add", MCP_SERVER_NAME, "--", launch.command, ...launch.args], context.env);
1074
+ return context.runCommand(codex, ["mcp", "add", MCP_SERVER_NAME, "--", launch.command, ...launch.args], context.env);
887
1075
  }
888
1076
  /**
889
1077
  * `claude mcp add <name> -- <command> [args...]` registers a stdio server;
890
1078
  * stdio is the default transport, so `--transport` is deliberately omitted.
891
1079
  */
892
- function configureClaudeCode(launch, force, context) {
893
- const existing = context.runCommand("claude", ["mcp", "get", MCP_SERVER_NAME], context.env);
1080
+ function configureClaudeCode(claude, launch, force, context) {
1081
+ const existing = context.runCommand(claude, ["mcp", "get", MCP_SERVER_NAME], context.env);
894
1082
  if (existing.status === 0) {
895
1083
  if (!force)
896
1084
  return Object.freeze({ status: 0 });
897
- const removed = context.runCommand("claude", ["mcp", "remove", MCP_SERVER_NAME, "--scope", "user"], context.env);
1085
+ const removed = context.runCommand(claude, ["mcp", "remove", MCP_SERVER_NAME, "--scope", "user"], context.env);
898
1086
  if (removed.status !== 0)
899
1087
  return removed;
900
1088
  }
901
- return context.runCommand("claude", ["mcp", "add", "--scope", "user", MCP_SERVER_NAME, "--", launch.command, ...launch.args], context.env);
1089
+ return context.runCommand(claude, ["mcp", "add", "--scope", "user", MCP_SERVER_NAME, "--", launch.command, ...launch.args], context.env);
902
1090
  }
903
1091
  // ── client ─────────────────────────────────────────────────────────
904
1092
  function runClient(options, out) {
@@ -964,27 +1152,49 @@ function runGrant(options, home, dependencies, out) {
964
1152
  ? Object.freeze({})
965
1153
  : (current.tableAccess ?? Object.freeze({}));
966
1154
  const ordinary = buildTableAccess(existing, options);
967
- const tableAccess = options.atf
1155
+ const withAtf = options.atf
968
1156
  ? buildTableAccess(ordinary, { ...options, read: ["sys_atf_test_suite", "sys_atf_test", "sys_atf_step", "sys_atf_step_config", "var_dictionary", "sys_variable_value", "sys_element_mapping"], write: ATF_AUTHOR_TABLES, tools: ["sn_atf_author"] })
969
1157
  : ordinary;
1158
+ const tableAccess = options.flows
1159
+ ? buildTableAccess(withAtf, { ...options, read: flow_view_contracts_js_1.FLOW_VIEW_TABLES, write: [], tools: ["sn_flow_view"] })
1160
+ : withAtf;
1161
+ // What this grant adds to the write allowlist, including related tables
1162
+ // that buildTableAccess pulls in. A re-run that adds nothing new still
1163
+ // names the tables it was asked for.
1164
+ const alreadyWritable = new Set(existing.writeTables ?? []);
1165
+ const grantedWrites = [
1166
+ ...new Set([
1167
+ ...options.write,
1168
+ ...(tableAccess.writeTables ?? []).filter((table) => !alreadyWritable.has(table)),
1169
+ ]),
1170
+ ];
1171
+ const riskWarning = (0, risky_grants_js_1.riskyGrantWarning)(grantedWrites, options.profile);
1172
+ const warnings = riskWarning === undefined ? {} : { warnings: [riskWarning.trim()] };
970
1173
  if (options.dryRun) {
971
1174
  out(options.json
972
- ? `${JSON.stringify({ status: "dry-run", profile: options.profile, tableAccess }, null, 2)}\n`
973
- : `Would write to profile ${options.profile}:\n${indent(JSON.stringify(tableAccess, null, 2))}\n`);
1175
+ ? `${JSON.stringify({ status: "dry-run", profile: options.profile, tableAccess, ...warnings }, null, 2)}\n`
1176
+ : `Would write to profile ${options.profile}:\n${indent(JSON.stringify(tableAccess, null, 2))}\n` +
1177
+ (riskWarning === undefined ? "" : `\n${riskWarning}`));
974
1178
  return;
975
1179
  }
976
1180
  manager.addProfile(options.profile, { ...current, tableAccess });
977
1181
  if (options.json) {
978
- out(`${JSON.stringify({ status: "granted", profile: options.profile, tableAccess }, null, 2)}\n`);
1182
+ out(`${JSON.stringify({ status: "granted", profile: options.profile, tableAccess, ...warnings }, null, 2)}\n`);
979
1183
  return;
980
1184
  }
981
1185
  out(`Granted table access on profile ${options.profile}.\n\n` +
982
1186
  `${indent(JSON.stringify(tableAccess, null, 2))}\n\n` +
983
- `Each target asserts closureComplete: true, meaning relatedTables lists every\n` +
984
- `backing, ancestor, and descendant table the operation can reach. Pass\n` +
985
- `--related "<table>=<t1>,<t2>" when a table extends or views another one;\n` +
986
- `related tables join the allowlist but get no target, so a caller cannot\n` +
987
- `address them directly.\n` +
1187
+ (riskWarning === undefined ? "" : `${riskWarning}\n`) +
1188
+ `relatedTables is a declaration the loader checks: each related table must\n` +
1189
+ `be allowed for every operation its target has, so --related adds it to the\n` +
1190
+ `allowlist of each of those operations, including one a later grant adds.\n` +
1191
+ `On its own that makes the table addressable by no tool, because it has no\n` +
1192
+ `target, unless such an allowlist is "*". If the table has, or later gets,\n` +
1193
+ `a target of its own, that target's tools can then use those operations on\n` +
1194
+ `it.\n` +
1195
+ `Inherited fields are read through the table itself, so a self-only list is\n` +
1196
+ `enough. Pass --related "<table>=<t1>,<t2>" to declare a parent or a view's\n` +
1197
+ `backing table.\n` +
988
1198
  `Restart the MCP client for the change to take effect: it reads the\n` +
989
1199
  `profile when it launches the server.\n`);
990
1200
  }
@@ -995,11 +1205,10 @@ function runGrant(options, home, dependencies, out) {
995
1205
  function buildTableAccess(existing, options) {
996
1206
  const readTables = new Set([...(existing.readTables ?? []), ...options.read]);
997
1207
  const writeTables = new Set([...(existing.writeTables ?? []), ...options.write]);
998
- const targets = mergeTargets(existing.targets, options, readTables, writeTables);
999
- // A target asserts that relatedTables is its complete reachable closure, and
1000
- // the policy loader requires every one of those tables to carry the same
1001
- // operation permission. They stay out of `targets`, so they are reachable
1002
- // through the target but never directly addressable by a caller.
1208
+ const targets = mergeTargets(existing.targets, options);
1209
+ // The policy loader requires every table a target declares in relatedTables
1210
+ // to carry the target's operation permission. They stay out of `targets`,
1211
+ // so they are never directly addressable by a caller.
1003
1212
  for (const target of targets) {
1004
1213
  if (readTables.has(target.table)) {
1005
1214
  for (const related of target.relatedTables)
@@ -1023,7 +1232,7 @@ function buildTableAccess(existing, options) {
1023
1232
  function sorted(values) {
1024
1233
  return Object.freeze([...values].sort());
1025
1234
  }
1026
- function mergeTargets(existing, options, readTables, writeTables) {
1235
+ function mergeTargets(existing, options) {
1027
1236
  const byTable = new Map();
1028
1237
  for (const target of existing ?? [])
1029
1238
  byTable.set(target.table, target);
@@ -1036,13 +1245,21 @@ function mergeTargets(existing, options, readTables, writeTables) {
1036
1245
  tools.add(tool);
1037
1246
  }
1038
1247
  else {
1039
- if (readTables.has(table)) {
1248
+ // Defaults follow what this invocation granted, not the merged
1249
+ // allowlists. Those also hold the profile's earlier grants and the
1250
+ // related tables of other targets, so gating on them would let a
1251
+ // read-only grant add write tools to a target.
1252
+ if (options.read.includes(table)) {
1040
1253
  for (const tool of DEFAULT_READ_TOOLS)
1041
1254
  tools.add(tool);
1042
1255
  }
1043
- if (writeTables.has(table)) {
1256
+ if (options.write.includes(table)) {
1044
1257
  for (const tool of DEFAULT_WRITE_TOOLS)
1045
1258
  tools.add(tool);
1259
+ if (table === "incident") {
1260
+ for (const tool of INCIDENT_JOURNAL_TOOLS)
1261
+ tools.add(tool);
1262
+ }
1046
1263
  }
1047
1264
  }
1048
1265
  const related = new Set([
@@ -1060,9 +1277,58 @@ function mergeTargets(existing, options, readTables, writeTables) {
1060
1277
  }
1061
1278
  return Object.freeze([...byTable.values()]);
1062
1279
  }
1280
+ /**
1281
+ * `policy show`: the profile's effective policy as one table. It is built from
1282
+ * the same loaders the server uses (profile snapshot, table-access policy,
1283
+ * field-policy resolver), and reads no credential: the profile is loaded
1284
+ * without resolving any secret.
1285
+ */
1286
+ function runPolicy(options, home, env, dependencies, out) {
1287
+ const manager = dependencies.profileManager ?? profileManagerFor(home);
1288
+ const profile = manager.getProfile(options.profile);
1289
+ // Raw encoded-query reads are configured in the server's environment, which
1290
+ // this shell may not share. Say so rather than guess.
1291
+ let encodedQueryAccess = (0, encoded_query_policy_js_1.createEncodedQueryAccessPolicy)();
1292
+ let encodedNote = "Raw encoded read queries and ATF grants shown are those of this shell's environment; " +
1293
+ "the server reads its own.";
1294
+ try {
1295
+ encodedQueryAccess = (0, encoded_query_policy_js_1.encodedQueryAccessPolicyFromEnvironment)(env);
1296
+ }
1297
+ catch {
1298
+ encodedNote = "The encoded-query read policy in this shell's environment is invalid; shown as denied.";
1299
+ }
1300
+ const card = (0, policy_card_js_1.buildPolicyCard)({
1301
+ profile: options.profile,
1302
+ instance: profile.instance,
1303
+ authType: profile.authType ?? "basic",
1304
+ ...(profile.grantType === undefined || profile.authType !== "oauth"
1305
+ ? {}
1306
+ : { grantType: profile.grantType }),
1307
+ tableAccess: (0, table_policy_js_1.createTableAccessPolicy)(profile.tableAccess ?? Object.freeze({})),
1308
+ fieldPolicy: {
1309
+ ...(profile.fieldPolicy === undefined ? {} : { fieldPolicy: profile.fieldPolicy }),
1310
+ ...(profile.readableTableFields === undefined
1311
+ ? {}
1312
+ : { readableTableFields: profile.readableTableFields }),
1313
+ ...(profile.writableTableFields === undefined
1314
+ ? {}
1315
+ : { writableTableFields: profile.writableTableFields }),
1316
+ },
1317
+ encodedQueryAccess,
1318
+ atf: manager.getAtfConfig(options.profile),
1319
+ });
1320
+ out(options.json
1321
+ ? `${JSON.stringify({ policy: card, note: encodedNote }, null, 2)}\n`
1322
+ : `${(0, policy_card_js_1.renderPolicyCard)(card)}\n${encodedNote}\n`);
1323
+ }
1063
1324
  async function runDoctor(options, home, env, dependencies, out) {
1064
1325
  const paths = resolvePaths(home);
1065
- const checks = runInstallChecks(paths, home, env, dependencies, options.profile);
1326
+ const checks = options.live
1327
+ ? [
1328
+ ...runInstallChecks(paths, home, env, dependencies, options.profile),
1329
+ ...(await runLiveChecks(paths, home, dependencies, options.profile)),
1330
+ ]
1331
+ : runInstallChecks(paths, home, env, dependencies, options.profile);
1066
1332
  const failed = checks.filter((check) => !check.ok);
1067
1333
  if (options.json) {
1068
1334
  out(`${JSON.stringify({ status: failed.length === 0 ? "ok" : "problems", checks }, null, 2)}\n`);
@@ -1073,6 +1339,62 @@ async function runDoctor(options, home, env, dependencies, out) {
1073
1339
  if (failed.length > 0)
1074
1340
  process.exitCode = 1;
1075
1341
  }
1342
+ /**
1343
+ * `doctor --live`: one bounded authenticated read per profile, through the
1344
+ * same probe the wizard uses, so a hibernating instance is reported as such
1345
+ * with the wake hint instead of a generic failure. Opt-in, because plain
1346
+ * `doctor` never touches the network.
1347
+ */
1348
+ /** Per-profile bound for `doctor --live`; shorter than the client default. */
1349
+ const DOCTOR_LIVE_TIMEOUT_MS = 10_000;
1350
+ async function runLiveChecks(paths, home, dependencies, only) {
1351
+ if (!(0, node_fs_1.existsSync)(paths.profileConfig) && dependencies.profileManager === undefined)
1352
+ return [];
1353
+ const verify = dependencies.verifyCredential ?? verifyCredentialAgainstInstance;
1354
+ const checks = [];
1355
+ try {
1356
+ const manager = dependencies.profileManager ?? profileManagerFor(home);
1357
+ const names = manager
1358
+ .listProfiles()
1359
+ .map((entry) => entry.name)
1360
+ .filter((name) => only === undefined || name === only);
1361
+ // Concurrent, with doctor's own short timeout, so unresponsive profiles
1362
+ // cost one timeout in total. Promise.all keeps the profile-name order.
1363
+ const results = await Promise.all([...names].sort().map(async (name) => {
1364
+ let config;
1365
+ try {
1366
+ config = { ...manager.getConfig(name), timeoutMs: DOCTOR_LIVE_TIMEOUT_MS };
1367
+ }
1368
+ catch {
1369
+ return undefined; // The credential check has already reported why.
1370
+ }
1371
+ try {
1372
+ const result = await verify(config);
1373
+ return {
1374
+ name: `profile ${name}: live instance`,
1375
+ ok: result.ok,
1376
+ detail: result.detail,
1377
+ ...(result.remedy === undefined ? {} : { remedy: result.remedy }),
1378
+ };
1379
+ }
1380
+ catch {
1381
+ return {
1382
+ name: `profile ${name}: live instance`,
1383
+ ok: false,
1384
+ detail: "could not be probed",
1385
+ remedy: "Check the profile's instance URL and credential settings.",
1386
+ };
1387
+ }
1388
+ }));
1389
+ for (const check of results)
1390
+ if (check !== undefined)
1391
+ checks.push(check);
1392
+ }
1393
+ catch {
1394
+ // Profile loading failures are reported by the static checks.
1395
+ }
1396
+ return checks;
1397
+ }
1076
1398
  /**
1077
1399
  * Prove the command registered clients spawn can actually be found.
1078
1400
  *
@@ -1085,9 +1407,30 @@ async function runDoctor(options, home, env, dependencies, out) {
1085
1407
  * PATH here is this shell's, which is the best available proxy. A GUI client
1086
1408
  * launched from the desktop may hold a different one, so the remedy names the
1087
1409
  * absolute-path registration that removes the question entirely.
1410
+ *
1411
+ * On Windows, clients are registered with node and the entrypoint by absolute
1412
+ * path, never the bare name (see `resolveServerLaunch`). PATH is irrelevant
1413
+ * there, so the check is that both files a client will launch exist.
1088
1414
  */
1089
1415
  function checkServerCommand(dependencies) {
1090
1416
  const name = "server command";
1417
+ const fallback = dependencies.serverEntrypoint ?? defaultServerEntrypoint();
1418
+ if ((dependencies.platform ?? process.platform) === "win32") {
1419
+ const missing = [process.execPath, fallback].filter((file) => !(0, node_fs_1.existsSync)(file));
1420
+ return missing.length === 0
1421
+ ? {
1422
+ name,
1423
+ ok: true,
1424
+ detail: `clients launch ${process.execPath} with ${fallback} over stdio`,
1425
+ }
1426
+ : {
1427
+ name,
1428
+ ok: false,
1429
+ detail: `${missing.join(" and ")} not found`,
1430
+ remedy: "Reinstall the package (npm i -g @onlyflows/servicenow-mcp), then run " +
1431
+ "servicenow-mcp-setup again from the new install.",
1432
+ };
1433
+ }
1091
1434
  const commandExists = dependencies.commandExists ?? defaultCommandExists;
1092
1435
  if (commandExists(SERVER_COMMAND)) {
1093
1436
  return {
@@ -1096,7 +1439,6 @@ function checkServerCommand(dependencies) {
1096
1439
  detail: `${SERVER_COMMAND} resolves on PATH; clients spawn it over stdio`,
1097
1440
  };
1098
1441
  }
1099
- const fallback = (0, node_path_1.join)(__dirname, "index.js");
1100
1442
  return {
1101
1443
  name,
1102
1444
  ok: false,
@@ -1355,7 +1697,10 @@ function normalizeArgv(argv) {
1355
1697
  }
1356
1698
  function splitSubcommand(argv) {
1357
1699
  const first = argv[0];
1358
- if (first === "client" || first === "grant" || first === "doctor") {
1700
+ if (first === "client" ||
1701
+ first === "grant" ||
1702
+ first === "doctor" ||
1703
+ first === "policy") {
1359
1704
  return { subcommand: first, args: Object.freeze(argv.slice(1)) };
1360
1705
  }
1361
1706
  if (first === "init")
@@ -1441,7 +1786,7 @@ function parseClientArguments(args) {
1441
1786
  function parseGrantArguments(args) {
1442
1787
  const usage = renderGrantHelp();
1443
1788
  const parsed = parseFlags(args, {
1444
- boolean: new Set(["--replace", "--dry-run", "--json", "--atf"]),
1789
+ boolean: new Set(["--replace", "--dry-run", "--json", "--atf", "--flows"]),
1445
1790
  value: new Set(["--profile", "--read", "--write", "--tools", "--related"]),
1446
1791
  repeatable: new Set(["--related"]),
1447
1792
  }, usage);
@@ -1450,8 +1795,8 @@ function parseGrantArguments(args) {
1450
1795
  throw new Error(`--profile is required.\n\n${usage}`);
1451
1796
  const read = parseTableList(parsed.values.get("--read"), "--read");
1452
1797
  const write = parseTableList(parsed.values.get("--write"), "--write");
1453
- if (read.length === 0 && write.length === 0 && !parsed.flags.has("--atf")) {
1454
- throw new Error(`Give at least one of --read, --write, or --atf.\n\n${usage}`);
1798
+ if (read.length === 0 && write.length === 0 && !parsed.flags.has("--atf") && !parsed.flags.has("--flows")) {
1799
+ throw new Error(`Give at least one of --read, --write, --atf or --flows.\n\n${usage}`);
1455
1800
  }
1456
1801
  return Object.freeze({
1457
1802
  profile,
@@ -1461,21 +1806,36 @@ function parseGrantArguments(args) {
1461
1806
  ? { tools: parseToolList(parsed.values.get("--tools")) }
1462
1807
  : {}),
1463
1808
  atf: parsed.flags.has("--atf"),
1809
+ flows: parsed.flags.has("--flows"),
1464
1810
  related: parseRelated(parsed.repeated.get("--related") ?? []),
1465
1811
  replace: parsed.flags.has("--replace"),
1466
1812
  dryRun: parsed.flags.has("--dry-run"),
1467
1813
  json: parsed.flags.has("--json"),
1468
1814
  });
1469
1815
  }
1816
+ function parsePolicyArguments(args) {
1817
+ const usage = renderPolicyHelp();
1818
+ if (args[0] !== "show") {
1819
+ if (args[0] === "--help" || args[0] === "-h")
1820
+ throw new SetupHelp(usage);
1821
+ throw new Error(`Usage: servicenow-mcp-setup policy show --profile NAME\n\n${usage}`);
1822
+ }
1823
+ const parsed = parseFlags(args.slice(1), { boolean: new Set(["--json"]), value: new Set(["--profile"]) }, usage);
1824
+ const profile = parsed.values.get("--profile");
1825
+ if (!profile)
1826
+ throw new Error(`--profile is required.\n\n${usage}`);
1827
+ return Object.freeze({ profile, json: parsed.flags.has("--json") });
1828
+ }
1470
1829
  function parseDoctorArguments(args) {
1471
1830
  const usage = renderDoctorHelp();
1472
1831
  const parsed = parseFlags(args, {
1473
- boolean: new Set(["--json"]),
1832
+ boolean: new Set(["--json", "--live"]),
1474
1833
  value: new Set(["--profile"]),
1475
1834
  }, usage);
1476
1835
  return Object.freeze({
1477
1836
  ...(parsed.values.has("--profile") ? { profile: parsed.values.get("--profile") } : {}),
1478
1837
  json: parsed.flags.has("--json"),
1838
+ live: parsed.flags.has("--live"),
1479
1839
  });
1480
1840
  }
1481
1841
  function parseClients(value) {
@@ -1683,17 +2043,15 @@ function unquoteShellValue(raw) {
1683
2043
  return raw;
1684
2044
  }
1685
2045
  function defaultCommandExists(command) {
1686
- const result = (0, node_child_process_1.spawnSync)("/bin/sh", ["-lc", `command -v ${shellQuote(command)}`], {
1687
- encoding: "utf8",
1688
- stdio: ["ignore", "pipe", "pipe"],
1689
- });
1690
- return result.status === 0;
2046
+ return (0, command_resolution_js_1.resolveCommand)(command) !== undefined;
1691
2047
  }
1692
2048
  function defaultRunCommand(command, args, env) {
1693
- const result = (0, node_child_process_1.spawnSync)(command, [...args], {
2049
+ const invocation = (0, command_resolution_js_1.commandInvocation)(command, args, { env });
2050
+ const result = (0, node_child_process_1.spawnSync)(invocation.command, [...invocation.args], {
1694
2051
  encoding: "utf8",
1695
2052
  env,
1696
2053
  stdio: ["ignore", "pipe", "pipe"],
2054
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,
1697
2055
  });
1698
2056
  return Object.freeze({
1699
2057
  status: result.status,
@@ -1795,6 +2153,7 @@ function renderSetupHelp() {
1795
2153
  " instance, table access, and client registration.",
1796
2154
  " client Print copy-pasteable configuration for one or more MCP clients.",
1797
2155
  " grant Add least-privilege table access rules to an existing profile.",
2156
+ " policy Show a profile's effective policy as one table (policy show).",
1798
2157
  " doctor Diagnose a local install and print the remedy for each failure.",
1799
2158
  "",
1800
2159
  "Run any command with --help for its options.",
@@ -1851,11 +2210,15 @@ function renderGrantHelp() {
1851
2210
  " --write TABLES Comma-separated tables to allow for writes",
1852
2211
  " --atf Grant the ATF authoring tables to sn_atf_author only",
1853
2212
  " Does not enable execution or script-step authoring",
2213
+ " --flows Grant read on the 15 sn_flow_view tables to sn_flow_view only",
2214
+ " (see docs/FLOW-VIEW.md)",
1854
2215
  ` --tools LIST Tools permitted on these targets`,
1855
2216
  ` (default read: ${DEFAULT_READ_TOOLS.join(",")};`,
1856
- ` default write adds: ${DEFAULT_WRITE_TOOLS.join(",")})`,
1857
- " --related TABLE=LIST Backing/ancestor/descendant tables the target reaches;",
1858
- " repeatable, and required whenever a table extends another",
2217
+ ` default write adds: ${DEFAULT_WRITE_TOOLS.join(",")};`,
2218
+ ` default write on incident also adds:`,
2219
+ ` ${INCIDENT_JOURNAL_TOOLS.join(",")})`,
2220
+ " --related TABLE=LIST Parent or backing tables to declare for a target;",
2221
+ " repeatable. Optional for a table that extends another",
1859
2222
  " --replace Discard existing rules instead of adding to them",
1860
2223
  " --dry-run Print the resulting rules without writing them",
1861
2224
  " --json Machine-readable output",
@@ -1865,17 +2228,35 @@ function renderGrantHelp() {
1865
2228
  "docs/PRODUCTION-SECURITY.md.",
1866
2229
  ].join("\n");
1867
2230
  }
2231
+ function renderPolicyHelp() {
2232
+ return [
2233
+ "Usage: servicenow-mcp-setup policy show --profile NAME [--json]",
2234
+ "",
2235
+ "Prints what the profile may do, from the same policy the server enforces:",
2236
+ "tables readable and writable with their tools, readable and writable fields,",
2237
+ "the explicit-listing fields, auth type, raw encoded-query reads, ATF grants,",
2238
+ "and the sn_batch limits. Warns when write access reaches privilege-sensitive",
2239
+ "tables (roles, approvals, scripts, users). Never prints a secret, a key, or a credential reference, and never",
2240
+ "touches the network.",
2241
+ "",
2242
+ "Options:",
2243
+ " --profile NAME Profile to show (required)",
2244
+ " --json Machine-readable output",
2245
+ ].join("\n");
2246
+ }
1868
2247
  function renderDoctorHelp() {
1869
2248
  return [
1870
- "Usage: servicenow-mcp-setup doctor [--profile NAME]",
2249
+ "Usage: servicenow-mcp-setup doctor [--profile NAME] [--live]",
1871
2250
  "",
1872
2251
  "Checks Node version, that the servicenow-mcp command clients spawn resolves",
1873
2252
  "on PATH, config file ownership and modes, profile completeness, credential",
1874
2253
  "resolution, and table access. Exits non-zero when any check fails. Never",
1875
- "prints a secret value, and never touches the network.",
2254
+ "prints a secret value. It touches the network only with --live.",
1876
2255
  "",
1877
2256
  "Options:",
1878
2257
  " --profile NAME Check only this profile (default: every configured profile)",
2258
+ " --live Also make one authenticated read per profile; reports a",
2259
+ " hibernating instance with how to wake it",
1879
2260
  " --json Machine-readable output",
1880
2261
  ].join("\n");
1881
2262
  }