@onlyflows/servicenow-mcp 2.2.0-dev.6 → 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 (244) hide show
  1. package/.env.example +6 -3
  2. package/CHANGELOG.md +286 -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/encoded-query-policy.d.ts +11 -0
  25. package/dist/encoded-query-policy.d.ts.map +1 -1
  26. package/dist/encoded-query-policy.js +10 -1
  27. package/dist/encoded-query-policy.js.map +1 -1
  28. package/dist/field-policy.d.ts +82 -3
  29. package/dist/field-policy.d.ts.map +1 -1
  30. package/dist/field-policy.js +609 -80
  31. package/dist/field-policy.js.map +1 -1
  32. package/dist/html-response.d.ts +34 -0
  33. package/dist/html-response.d.ts.map +1 -0
  34. package/dist/html-response.js +72 -0
  35. package/dist/html-response.js.map +1 -0
  36. package/dist/http-runtime.d.ts.map +1 -1
  37. package/dist/http-runtime.js +8 -0
  38. package/dist/http-runtime.js.map +1 -1
  39. package/dist/incident-journal-policy.d.ts +27 -5
  40. package/dist/incident-journal-policy.d.ts.map +1 -1
  41. package/dist/incident-journal-policy.js +34 -21
  42. package/dist/incident-journal-policy.js.map +1 -1
  43. package/dist/json-shape-limits.d.ts +71 -0
  44. package/dist/json-shape-limits.d.ts.map +1 -0
  45. package/dist/json-shape-limits.js +131 -0
  46. package/dist/json-shape-limits.js.map +1 -0
  47. package/dist/metadata-cache.d.ts +46 -21
  48. package/dist/metadata-cache.d.ts.map +1 -1
  49. package/dist/metadata-cache.js +228 -195
  50. package/dist/metadata-cache.js.map +1 -1
  51. package/dist/policy-card.d.ts +131 -0
  52. package/dist/policy-card.d.ts.map +1 -0
  53. package/dist/policy-card.js +409 -0
  54. package/dist/policy-card.js.map +1 -0
  55. package/dist/profile-manager.d.ts +7 -3
  56. package/dist/profile-manager.d.ts.map +1 -1
  57. package/dist/profile-manager.js +66 -3
  58. package/dist/profile-manager.js.map +1 -1
  59. package/dist/record-identifier-policy.d.ts +2 -8
  60. package/dist/record-identifier-policy.d.ts.map +1 -1
  61. package/dist/risky-grants.d.ts +25 -0
  62. package/dist/risky-grants.d.ts.map +1 -0
  63. package/dist/risky-grants.js +77 -0
  64. package/dist/risky-grants.js.map +1 -0
  65. package/dist/server.d.ts.map +1 -1
  66. package/dist/server.js +26 -5
  67. package/dist/server.js.map +1 -1
  68. package/dist/setup-prompts.js +1 -0
  69. package/dist/setup-prompts.js.map +1 -1
  70. package/dist/setup.d.ts +1 -1
  71. package/dist/setup.d.ts.map +1 -1
  72. package/dist/setup.js +300 -58
  73. package/dist/setup.js.map +1 -1
  74. package/dist/stdio-runtime.d.ts +15 -0
  75. package/dist/stdio-runtime.d.ts.map +1 -1
  76. package/dist/stdio-runtime.js +60 -0
  77. package/dist/stdio-runtime.js.map +1 -1
  78. package/dist/structured-query.d.ts +100 -115
  79. package/dist/structured-query.d.ts.map +1 -1
  80. package/dist/structured-query.js +132 -16
  81. package/dist/structured-query.js.map +1 -1
  82. package/dist/table-policy.d.ts +10 -4
  83. package/dist/table-policy.d.ts.map +1 -1
  84. package/dist/table-policy.js +1 -1
  85. package/dist/table-policy.js.map +1 -1
  86. package/dist/tool-error.d.ts +18 -0
  87. package/dist/tool-error.d.ts.map +1 -1
  88. package/dist/tool-error.js +69 -0
  89. package/dist/tool-error.js.map +1 -1
  90. package/dist/tool-table-access.d.ts.map +1 -1
  91. package/dist/tool-table-access.js +32 -2
  92. package/dist/tool-table-access.js.map +1 -1
  93. package/dist/tools/aggregate.d.ts +13 -19
  94. package/dist/tools/aggregate.d.ts.map +1 -1
  95. package/dist/tools/aggregate.js +2 -3
  96. package/dist/tools/aggregate.js.map +1 -1
  97. package/dist/tools/all-fields-cap.d.ts.map +1 -1
  98. package/dist/tools/all-fields-cap.js +3 -38
  99. package/dist/tools/all-fields-cap.js.map +1 -1
  100. package/dist/tools/atf-author-module.d.ts +28 -7
  101. package/dist/tools/atf-author-module.d.ts.map +1 -1
  102. package/dist/tools/atf-author-module.js +4 -2
  103. package/dist/tools/atf-author-module.js.map +1 -1
  104. package/dist/tools/atf-contracts.d.ts +135 -829
  105. package/dist/tools/atf-contracts.d.ts.map +1 -1
  106. package/dist/tools/atf-shared.js +2 -2
  107. package/dist/tools/atf-shared.js.map +1 -1
  108. package/dist/tools/atf-step-catalog.d.ts +3 -7
  109. package/dist/tools/atf-step-catalog.d.ts.map +1 -1
  110. package/dist/tools/atf-step-catalog.js +12 -5
  111. package/dist/tools/atf-step-catalog.js.map +1 -1
  112. package/dist/tools/atf.d.ts +8 -24
  113. package/dist/tools/atf.d.ts.map +1 -1
  114. package/dist/tools/atf.js +2 -2
  115. package/dist/tools/atf.js.map +1 -1
  116. package/dist/tools/attach.d.ts +6 -22
  117. package/dist/tools/attach.d.ts.map +1 -1
  118. package/dist/tools/batch.d.ts +18 -71
  119. package/dist/tools/batch.d.ts.map +1 -1
  120. package/dist/tools/batch.js +544 -96
  121. package/dist/tools/batch.js.map +1 -1
  122. package/dist/tools/catalog.d.ts +2 -2
  123. package/dist/tools/catalog.d.ts.map +1 -1
  124. package/dist/tools/catalog.js +7 -1
  125. package/dist/tools/catalog.js.map +1 -1
  126. package/dist/tools/codesearch.d.ts +1 -13
  127. package/dist/tools/codesearch.d.ts.map +1 -1
  128. package/dist/tools/create-module.d.ts +9 -14
  129. package/dist/tools/create-module.d.ts.map +1 -1
  130. package/dist/tools/create-module.js +4 -8
  131. package/dist/tools/create-module.js.map +1 -1
  132. package/dist/tools/delete.d.ts +1 -9
  133. package/dist/tools/delete.d.ts.map +1 -1
  134. package/dist/tools/delete.js +2 -3
  135. package/dist/tools/delete.js.map +1 -1
  136. package/dist/tools/discover.d.ts +6 -14
  137. package/dist/tools/discover.d.ts.map +1 -1
  138. package/dist/tools/flow-view-contracts.d.ts +1023 -0
  139. package/dist/tools/flow-view-contracts.d.ts.map +1 -0
  140. package/dist/tools/flow-view-contracts.js +570 -0
  141. package/dist/tools/flow-view-contracts.js.map +1 -0
  142. package/dist/tools/flow-view-graph.d.ts +86 -0
  143. package/dist/tools/flow-view-graph.d.ts.map +1 -0
  144. package/dist/tools/flow-view-graph.js +993 -0
  145. package/dist/tools/flow-view-graph.js.map +1 -0
  146. package/dist/tools/flow-view-gzip.d.ts +52 -0
  147. package/dist/tools/flow-view-gzip.d.ts.map +1 -0
  148. package/dist/tools/flow-view-gzip.js +179 -0
  149. package/dist/tools/flow-view-gzip.js.map +1 -0
  150. package/dist/tools/flow-view-mermaid.d.ts +37 -0
  151. package/dist/tools/flow-view-mermaid.d.ts.map +1 -0
  152. package/dist/tools/flow-view-mermaid.js +337 -0
  153. package/dist/tools/flow-view-mermaid.js.map +1 -0
  154. package/dist/tools/flow-view-module.d.ts +61 -0
  155. package/dist/tools/flow-view-module.d.ts.map +1 -0
  156. package/dist/tools/flow-view-module.js +378 -0
  157. package/dist/tools/flow-view-module.js.map +1 -0
  158. package/dist/tools/flow-view-policy.d.ts +106 -0
  159. package/dist/tools/flow-view-policy.d.ts.map +1 -0
  160. package/dist/tools/flow-view-policy.js +461 -0
  161. package/dist/tools/flow-view-policy.js.map +1 -0
  162. package/dist/tools/flow-view-renderers.d.ts +68 -0
  163. package/dist/tools/flow-view-renderers.d.ts.map +1 -0
  164. package/dist/tools/flow-view-renderers.js +513 -0
  165. package/dist/tools/flow-view-renderers.js.map +1 -0
  166. package/dist/tools/flow-view-table.d.ts +115 -0
  167. package/dist/tools/flow-view-table.d.ts.map +1 -0
  168. package/dist/tools/flow-view-table.js +1002 -0
  169. package/dist/tools/flow-view-table.js.map +1 -0
  170. package/dist/tools/get-module.d.ts +36 -42
  171. package/dist/tools/get-module.d.ts.map +1 -1
  172. package/dist/tools/health.d.ts +9 -6
  173. package/dist/tools/health.d.ts.map +1 -1
  174. package/dist/tools/incident-journal-module.d.ts +8 -7
  175. package/dist/tools/incident-journal-module.d.ts.map +1 -1
  176. package/dist/tools/index.d.ts +4 -4
  177. package/dist/tools/index.d.ts.map +1 -1
  178. package/dist/tools/index.js +43 -6
  179. package/dist/tools/index.js.map +1 -1
  180. package/dist/tools/markdown.d.ts +27 -0
  181. package/dist/tools/markdown.d.ts.map +1 -1
  182. package/dist/tools/markdown.js +104 -1
  183. package/dist/tools/markdown.js.map +1 -1
  184. package/dist/tools/nl.d.ts +1 -11
  185. package/dist/tools/nl.d.ts.map +1 -1
  186. package/dist/tools/profile.d.ts +1 -1
  187. package/dist/tools/profile.d.ts.map +1 -1
  188. package/dist/tools/profile.js +19 -1
  189. package/dist/tools/profile.js.map +1 -1
  190. package/dist/tools/query-module.d.ts +59 -71
  191. package/dist/tools/query-module.d.ts.map +1 -1
  192. package/dist/tools/query-module.js +2 -2
  193. package/dist/tools/query-module.js.map +1 -1
  194. package/dist/tools/record-write-shared.d.ts.map +1 -1
  195. package/dist/tools/record-write-shared.js +19 -2
  196. package/dist/tools/record-write-shared.js.map +1 -1
  197. package/dist/tools/relationships.d.ts +6 -22
  198. package/dist/tools/relationships.d.ts.map +1 -1
  199. package/dist/tools/result-envelope.d.ts +2255 -1357
  200. package/dist/tools/result-envelope.d.ts.map +1 -1
  201. package/dist/tools/result-envelope.js +24 -2
  202. package/dist/tools/result-envelope.js.map +1 -1
  203. package/dist/tools/schema-module.d.ts +36 -21
  204. package/dist/tools/schema-module.d.ts.map +1 -1
  205. package/dist/tools/schema-module.js +106 -65
  206. package/dist/tools/schema-module.js.map +1 -1
  207. package/dist/tools/script.d.ts +1 -11
  208. package/dist/tools/script.d.ts.map +1 -1
  209. package/dist/tools/syslog.d.ts +11 -18
  210. package/dist/tools/syslog.d.ts.map +1 -1
  211. package/dist/tools/syslog.js +2 -3
  212. package/dist/tools/syslog.js.map +1 -1
  213. package/dist/tools/table-hierarchy.d.ts +35 -0
  214. package/dist/tools/table-hierarchy.d.ts.map +1 -0
  215. package/dist/tools/table-hierarchy.js +74 -0
  216. package/dist/tools/table-hierarchy.js.map +1 -0
  217. package/dist/tools/tool-module.d.ts +40 -15
  218. package/dist/tools/tool-module.d.ts.map +1 -1
  219. package/dist/tools/tool-module.js +755 -205
  220. package/dist/tools/tool-module.js.map +1 -1
  221. package/dist/tools/update-module.d.ts +11 -17
  222. package/dist/tools/update-module.d.ts.map +1 -1
  223. package/dist/tools/update-module.js +10 -12
  224. package/dist/tools/update-module.js.map +1 -1
  225. package/dist/version.d.ts +1 -1
  226. package/dist/version.d.ts.map +1 -1
  227. package/dist/version.js +1 -1
  228. package/dist/version.js.map +1 -1
  229. package/dist/write-value-policy.d.ts +20 -12
  230. package/dist/write-value-policy.d.ts.map +1 -1
  231. package/dist/write-value-policy.js +179 -67
  232. package/dist/write-value-policy.js.map +1 -1
  233. package/docs/ADDING-TOOLS.md +22 -13
  234. package/docs/CLIENT-SETUP.md +110 -52
  235. package/docs/CROSS-CLIENT-RELEASE-MATRIX.md +2 -2
  236. package/docs/FLOW-VIEW.md +214 -0
  237. package/docs/PRODUCTION-SECURITY.md +154 -25
  238. package/docs/RELEASE-VALIDATION.md +2 -2
  239. package/docs/TESTING-OAUTH.md +1 -1
  240. package/docs/V2-MIGRATION.md +404 -30
  241. package/package.json +20 -6
  242. package/scripts/release-validate.mjs +56 -0
  243. package/server.json +22 -0
  244. package/tools/inspector/package-lock.json +163 -201
package/dist/setup.js CHANGED
@@ -40,8 +40,13 @@ const command_resolution_js_1 = require("./command-resolution.js");
40
40
  const profile_admin_js_1 = require("./profile-admin.js");
41
41
  const profile_credentials_js_1 = require("./profile-credentials.js");
42
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");
43
45
  const tool_error_js_1 = require("./tool-error.js");
44
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");
45
50
  /** Raised when the operator aborts; nothing has been written to the profile. */
46
51
  class WizardAbort extends Error {
47
52
  constructor() {
@@ -125,6 +130,16 @@ const DEFAULT_WRITE_TOOLS = Object.freeze([
125
130
  "sn_create",
126
131
  "sn_update",
127
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
+ ]);
128
143
  async function runSetupCli(dependencies = {}) {
129
144
  const env = dependencies.env ?? process.env;
130
145
  const argv = normalizeArgv(dependencies.argv ?? process.argv.slice(2));
@@ -139,6 +154,9 @@ async function runSetupCli(dependencies = {}) {
139
154
  case "grant":
140
155
  runGrant(parseGrantArguments(args), home, dependencies, out);
141
156
  return;
157
+ case "policy":
158
+ runPolicy(parsePolicyArguments(args), home, env, dependencies, out);
159
+ return;
142
160
  case "doctor":
143
161
  await runDoctor(parseDoctorArguments(args), home, env, dependencies, out);
144
162
  return;
@@ -275,6 +293,11 @@ async function runWizard(options, home, env, dependencies, out) {
275
293
  }
276
294
  // 5. Table access. A profile without rules denies every call.
277
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}`);
278
301
  // 6. One write, with the rules already attached — never a rules-less window.
279
302
  //
280
303
  // Retryable without re-prompting: everything needed is already in memory,
@@ -434,7 +457,19 @@ function wizardConfig(profile, captured, mode, env) {
434
457
  * accepts it.
435
458
  */
436
459
  async function verifyCredentialAgainstInstance(config) {
437
- 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
+ }
438
473
  try {
439
474
  await client.get(`/api/now/table/${WIZARD_PROBE_TABLE}`, {
440
475
  sysparm_limit: "1",
@@ -453,6 +488,34 @@ async function verifyCredentialAgainstInstance(config) {
453
488
  function classifyVerificationFailure(error, config) {
454
489
  const descriptor = (0, tool_error_js_1.trustedToolErrorDescriptor)(error);
455
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
+ }
456
519
  if (descriptor?.category === "authentication") {
457
520
  return Object.freeze({
458
521
  ok: false,
@@ -515,7 +578,8 @@ function classifyVerificationFailure(error, config) {
515
578
  }
516
579
  return Object.freeze({
517
580
  ok: false,
518
- 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.`,
519
583
  remedy: "Check the instance URL and this machine's outbound network access.",
520
584
  });
521
585
  }
@@ -534,10 +598,11 @@ async function askTableAccess(prompter, config, dependencies) {
534
598
  const read = await askTableSelection(prompter, "READS", DEFAULT_READ_TABLES);
535
599
  const write = await askTableSelection(prompter, "WRITES", "");
536
600
  const related = new Map();
601
+ const resolveParent = dependencies.resolveParentTable ?? parentTableReader();
537
602
  for (const table of new Set([...read, ...write])) {
538
603
  if (table === TABLE_ALLOWLIST_WILDCARD)
539
604
  continue;
540
- const parent = await lookupParentTable(config, table, dependencies);
605
+ const parent = await lookupParentTable(resolveParent, config, table);
541
606
  if (parent === undefined || parent === table)
542
607
  continue;
543
608
  prompter.note(`\n ${table} extends ${parent}.`);
@@ -613,39 +678,39 @@ async function askCustomTableList(prompter, operation) {
613
678
  * ServiceNow's inheritance graph. Best effort: a failure here is not a setup
614
679
  * failure, because the self-only closure the wizard writes is valid on its own.
615
680
  */
616
- async function lookupParentTable(config, table, dependencies) {
617
- const resolve = dependencies.resolveParentTable ?? defaultParentTable;
681
+ async function lookupParentTable(resolve, config, table) {
618
682
  try {
619
- 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;
620
687
  }
621
688
  catch {
622
689
  return undefined;
623
690
  }
624
691
  }
625
- async function defaultParentTable(config, table) {
626
- if (!TABLE_NAME.test(table))
627
- return undefined;
628
- const client = new client_js_1.ServiceNowClient(config, { maxRetries: 0 });
629
- const response = await client.get("/api/now/table/sys_db_object", {
630
- sysparm_query: `name=${table}`,
631
- sysparm_fields: "name,super_class",
632
- sysparm_limit: "1",
633
- sysparm_display_value: "true",
634
- sysparm_exclude_reference_link: "true",
635
- });
636
- const row = Array.isArray(response?.result) ? response.result[0] : undefined;
637
- if (typeof row !== "object" || row === null)
638
- return undefined;
639
- const value = row.super_class;
640
- const parent = typeof value === "string"
641
- ? value
642
- : typeof value === "object" && value !== null
643
- ? value.display_value
644
- : undefined;
645
- if (typeof parent !== "string")
646
- return undefined;
647
- const normalized = parent.trim().toLowerCase();
648
- 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
+ };
649
714
  }
650
715
  async function registerClientsInteractively(prompter, options, clis, context) {
651
716
  if (clis.length === 0) {
@@ -691,6 +756,7 @@ function renderClientCliNote(clis) {
691
756
  }
692
757
  function renderWizardSummary(profile, tableAccess, registered, home, checks) {
693
758
  const failed = checks.filter((check) => !check.ok).length;
759
+ const riskWarning = (0, risky_grants_js_1.riskyGrantWarning)(tableAccess.writeTables ?? [], profile);
694
760
  const lines = [
695
761
  "",
696
762
  "Setup complete.",
@@ -698,6 +764,7 @@ function renderWizardSummary(profile, tableAccess, registered, home, checks) {
698
764
  `Profile ${profile}`,
699
765
  `Reads ${(tableAccess.readTables ?? []).join(", ") || "(none)"}`,
700
766
  `Writes ${(tableAccess.writeTables ?? []).join(", ") || "(none)"}`,
767
+ ...(riskWarning === undefined ? [] : ["", riskWarning.trimEnd(), ""]),
701
768
  `Transport stdio (each client spawns its own ${SERVER_COMMAND})`,
702
769
  `Clients ${registered.length > 0 ? registered.join(", ") : "(none registered)"}`,
703
770
  "",
@@ -1085,27 +1152,49 @@ function runGrant(options, home, dependencies, out) {
1085
1152
  ? Object.freeze({})
1086
1153
  : (current.tableAccess ?? Object.freeze({}));
1087
1154
  const ordinary = buildTableAccess(existing, options);
1088
- const tableAccess = options.atf
1155
+ const withAtf = options.atf
1089
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"] })
1090
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()] };
1091
1173
  if (options.dryRun) {
1092
1174
  out(options.json
1093
- ? `${JSON.stringify({ status: "dry-run", profile: options.profile, tableAccess }, null, 2)}\n`
1094
- : `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}`));
1095
1178
  return;
1096
1179
  }
1097
1180
  manager.addProfile(options.profile, { ...current, tableAccess });
1098
1181
  if (options.json) {
1099
- 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`);
1100
1183
  return;
1101
1184
  }
1102
1185
  out(`Granted table access on profile ${options.profile}.\n\n` +
1103
1186
  `${indent(JSON.stringify(tableAccess, null, 2))}\n\n` +
1104
- `Each target asserts closureComplete: true, meaning relatedTables lists every\n` +
1105
- `backing, ancestor, and descendant table the operation can reach. Pass\n` +
1106
- `--related "<table>=<t1>,<t2>" when a table extends or views another one;\n` +
1107
- `related tables join the allowlist but get no target, so a caller cannot\n` +
1108
- `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` +
1109
1198
  `Restart the MCP client for the change to take effect: it reads the\n` +
1110
1199
  `profile when it launches the server.\n`);
1111
1200
  }
@@ -1116,11 +1205,10 @@ function runGrant(options, home, dependencies, out) {
1116
1205
  function buildTableAccess(existing, options) {
1117
1206
  const readTables = new Set([...(existing.readTables ?? []), ...options.read]);
1118
1207
  const writeTables = new Set([...(existing.writeTables ?? []), ...options.write]);
1119
- const targets = mergeTargets(existing.targets, options, readTables, writeTables);
1120
- // A target asserts that relatedTables is its complete reachable closure, and
1121
- // the policy loader requires every one of those tables to carry the same
1122
- // operation permission. They stay out of `targets`, so they are reachable
1123
- // 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.
1124
1212
  for (const target of targets) {
1125
1213
  if (readTables.has(target.table)) {
1126
1214
  for (const related of target.relatedTables)
@@ -1144,7 +1232,7 @@ function buildTableAccess(existing, options) {
1144
1232
  function sorted(values) {
1145
1233
  return Object.freeze([...values].sort());
1146
1234
  }
1147
- function mergeTargets(existing, options, readTables, writeTables) {
1235
+ function mergeTargets(existing, options) {
1148
1236
  const byTable = new Map();
1149
1237
  for (const target of existing ?? [])
1150
1238
  byTable.set(target.table, target);
@@ -1157,13 +1245,21 @@ function mergeTargets(existing, options, readTables, writeTables) {
1157
1245
  tools.add(tool);
1158
1246
  }
1159
1247
  else {
1160
- 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)) {
1161
1253
  for (const tool of DEFAULT_READ_TOOLS)
1162
1254
  tools.add(tool);
1163
1255
  }
1164
- if (writeTables.has(table)) {
1256
+ if (options.write.includes(table)) {
1165
1257
  for (const tool of DEFAULT_WRITE_TOOLS)
1166
1258
  tools.add(tool);
1259
+ if (table === "incident") {
1260
+ for (const tool of INCIDENT_JOURNAL_TOOLS)
1261
+ tools.add(tool);
1262
+ }
1167
1263
  }
1168
1264
  }
1169
1265
  const related = new Set([
@@ -1181,9 +1277,58 @@ function mergeTargets(existing, options, readTables, writeTables) {
1181
1277
  }
1182
1278
  return Object.freeze([...byTable.values()]);
1183
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
+ }
1184
1324
  async function runDoctor(options, home, env, dependencies, out) {
1185
1325
  const paths = resolvePaths(home);
1186
- 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);
1187
1332
  const failed = checks.filter((check) => !check.ok);
1188
1333
  if (options.json) {
1189
1334
  out(`${JSON.stringify({ status: failed.length === 0 ? "ok" : "problems", checks }, null, 2)}\n`);
@@ -1194,6 +1339,62 @@ async function runDoctor(options, home, env, dependencies, out) {
1194
1339
  if (failed.length > 0)
1195
1340
  process.exitCode = 1;
1196
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
+ }
1197
1398
  /**
1198
1399
  * Prove the command registered clients spawn can actually be found.
1199
1400
  *
@@ -1496,7 +1697,10 @@ function normalizeArgv(argv) {
1496
1697
  }
1497
1698
  function splitSubcommand(argv) {
1498
1699
  const first = argv[0];
1499
- if (first === "client" || first === "grant" || first === "doctor") {
1700
+ if (first === "client" ||
1701
+ first === "grant" ||
1702
+ first === "doctor" ||
1703
+ first === "policy") {
1500
1704
  return { subcommand: first, args: Object.freeze(argv.slice(1)) };
1501
1705
  }
1502
1706
  if (first === "init")
@@ -1582,7 +1786,7 @@ function parseClientArguments(args) {
1582
1786
  function parseGrantArguments(args) {
1583
1787
  const usage = renderGrantHelp();
1584
1788
  const parsed = parseFlags(args, {
1585
- boolean: new Set(["--replace", "--dry-run", "--json", "--atf"]),
1789
+ boolean: new Set(["--replace", "--dry-run", "--json", "--atf", "--flows"]),
1586
1790
  value: new Set(["--profile", "--read", "--write", "--tools", "--related"]),
1587
1791
  repeatable: new Set(["--related"]),
1588
1792
  }, usage);
@@ -1591,8 +1795,8 @@ function parseGrantArguments(args) {
1591
1795
  throw new Error(`--profile is required.\n\n${usage}`);
1592
1796
  const read = parseTableList(parsed.values.get("--read"), "--read");
1593
1797
  const write = parseTableList(parsed.values.get("--write"), "--write");
1594
- if (read.length === 0 && write.length === 0 && !parsed.flags.has("--atf")) {
1595
- 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}`);
1596
1800
  }
1597
1801
  return Object.freeze({
1598
1802
  profile,
@@ -1602,21 +1806,36 @@ function parseGrantArguments(args) {
1602
1806
  ? { tools: parseToolList(parsed.values.get("--tools")) }
1603
1807
  : {}),
1604
1808
  atf: parsed.flags.has("--atf"),
1809
+ flows: parsed.flags.has("--flows"),
1605
1810
  related: parseRelated(parsed.repeated.get("--related") ?? []),
1606
1811
  replace: parsed.flags.has("--replace"),
1607
1812
  dryRun: parsed.flags.has("--dry-run"),
1608
1813
  json: parsed.flags.has("--json"),
1609
1814
  });
1610
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
+ }
1611
1829
  function parseDoctorArguments(args) {
1612
1830
  const usage = renderDoctorHelp();
1613
1831
  const parsed = parseFlags(args, {
1614
- boolean: new Set(["--json"]),
1832
+ boolean: new Set(["--json", "--live"]),
1615
1833
  value: new Set(["--profile"]),
1616
1834
  }, usage);
1617
1835
  return Object.freeze({
1618
1836
  ...(parsed.values.has("--profile") ? { profile: parsed.values.get("--profile") } : {}),
1619
1837
  json: parsed.flags.has("--json"),
1838
+ live: parsed.flags.has("--live"),
1620
1839
  });
1621
1840
  }
1622
1841
  function parseClients(value) {
@@ -1934,6 +2153,7 @@ function renderSetupHelp() {
1934
2153
  " instance, table access, and client registration.",
1935
2154
  " client Print copy-pasteable configuration for one or more MCP clients.",
1936
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).",
1937
2157
  " doctor Diagnose a local install and print the remedy for each failure.",
1938
2158
  "",
1939
2159
  "Run any command with --help for its options.",
@@ -1990,11 +2210,15 @@ function renderGrantHelp() {
1990
2210
  " --write TABLES Comma-separated tables to allow for writes",
1991
2211
  " --atf Grant the ATF authoring tables to sn_atf_author only",
1992
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)",
1993
2215
  ` --tools LIST Tools permitted on these targets`,
1994
2216
  ` (default read: ${DEFAULT_READ_TOOLS.join(",")};`,
1995
- ` default write adds: ${DEFAULT_WRITE_TOOLS.join(",")})`,
1996
- " --related TABLE=LIST Backing/ancestor/descendant tables the target reaches;",
1997
- " 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",
1998
2222
  " --replace Discard existing rules instead of adding to them",
1999
2223
  " --dry-run Print the resulting rules without writing them",
2000
2224
  " --json Machine-readable output",
@@ -2004,17 +2228,35 @@ function renderGrantHelp() {
2004
2228
  "docs/PRODUCTION-SECURITY.md.",
2005
2229
  ].join("\n");
2006
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
+ }
2007
2247
  function renderDoctorHelp() {
2008
2248
  return [
2009
- "Usage: servicenow-mcp-setup doctor [--profile NAME]",
2249
+ "Usage: servicenow-mcp-setup doctor [--profile NAME] [--live]",
2010
2250
  "",
2011
2251
  "Checks Node version, that the servicenow-mcp command clients spawn resolves",
2012
2252
  "on PATH, config file ownership and modes, profile completeness, credential",
2013
2253
  "resolution, and table access. Exits non-zero when any check fails. Never",
2014
- "prints a secret value, and never touches the network.",
2254
+ "prints a secret value. It touches the network only with --live.",
2015
2255
  "",
2016
2256
  "Options:",
2017
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",
2018
2260
  " --json Machine-readable output",
2019
2261
  ].join("\n");
2020
2262
  }