@burdenoff/mcp-libs 2026.1115.1 → 2026.1118.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (156) hide show
  1. package/dist/{core-zmkvPNsI.js → context-CNN-D9dE.js} +78 -606
  2. package/dist/context-CNN-D9dE.js.map +1 -0
  3. package/dist/{core-BKgeqlnN.cjs → context-DE1SuHyv.cjs} +87 -741
  4. package/dist/context-DE1SuHyv.cjs.map +1 -0
  5. package/dist/core/auth/memory-store.d.ts +2 -0
  6. package/dist/core/auth/store.d.ts +1 -0
  7. package/dist/core/context.d.ts +2 -1
  8. package/dist/core/index.cjs +19 -16
  9. package/dist/core/index.d.ts +2 -1
  10. package/dist/core/index.js +3 -2
  11. package/dist/core/tool-governance.d.ts +1 -1
  12. package/dist/core-AqyC7YJc.js +605 -0
  13. package/dist/core-AqyC7YJc.js.map +1 -0
  14. package/dist/core-Es_IX0FS.cjs +748 -0
  15. package/dist/core-Es_IX0FS.cjs.map +1 -0
  16. package/dist/index.cjs +4 -3
  17. package/dist/index.js +3 -2
  18. package/dist/{legacy-auth-BdSPFaEf.js → legacy-auth-DK_-m6hi.js} +2 -2
  19. package/dist/{legacy-auth-BdSPFaEf.js.map → legacy-auth-DK_-m6hi.js.map} +1 -1
  20. package/dist/{legacy-auth-C66oObd-.cjs → legacy-auth-Sk9KJHLW.cjs} +4 -4
  21. package/dist/{legacy-auth-C66oObd-.cjs.map → legacy-auth-Sk9KJHLW.cjs.map} +1 -1
  22. package/dist/modules/adaptercloud/index.cjs +1 -1
  23. package/dist/modules/adaptercloud/index.js +1 -1
  24. package/dist/modules/artistrybase/index.cjs +1 -1
  25. package/dist/modules/artistrybase/index.js +1 -1
  26. package/dist/modules/assethandler/index.cjs +1 -1
  27. package/dist/modules/assethandler/index.js +1 -1
  28. package/dist/modules/atheletebridge/index.cjs +1 -1
  29. package/dist/modules/atheletebridge/index.js +1 -1
  30. package/dist/modules/auth/index.cjs +4 -3
  31. package/dist/modules/auth/index.cjs.map +1 -1
  32. package/dist/modules/auth/index.js +3 -2
  33. package/dist/modules/auth/index.js.map +1 -1
  34. package/dist/modules/bigconsole/index.cjs +1 -1
  35. package/dist/modules/bigconsole/index.js +1 -1
  36. package/dist/modules/billing/index.cjs +1 -1
  37. package/dist/modules/billing/index.js +1 -1
  38. package/dist/modules/botmanor/index.cjs +1 -1
  39. package/dist/modules/botmanor/index.js +1 -1
  40. package/dist/modules/brainyrich/index.cjs +1 -1
  41. package/dist/modules/brainyrich/index.js +1 -1
  42. package/dist/modules/buildmyiq/index.cjs +1 -1
  43. package/dist/modules/buildmyiq/index.js +1 -1
  44. package/dist/modules/channels/index.cjs +1 -1
  45. package/dist/modules/channels/index.js +1 -1
  46. package/dist/modules/collabkin/index.cjs +1 -1
  47. package/dist/modules/collabkin/index.js +1 -1
  48. package/dist/modules/comradecircle/index.cjs +1 -1
  49. package/dist/modules/comradecircle/index.js +1 -1
  50. package/dist/modules/conversations/index.cjs +1 -1
  51. package/dist/modules/conversations/index.js +1 -1
  52. package/dist/modules/coolandlovely/index.cjs +1 -1
  53. package/dist/modules/coolandlovely/index.js +1 -1
  54. package/dist/modules/cosmicintersection/index.cjs +1 -1
  55. package/dist/modules/cosmicintersection/index.js +1 -1
  56. package/dist/modules/crewfoundry/index.cjs +1 -1
  57. package/dist/modules/crewfoundry/index.js +1 -1
  58. package/dist/modules/devportal/index.cjs +1 -1
  59. package/dist/modules/devportal/index.js +1 -1
  60. package/dist/modules/ecoimpacthub/index.cjs +1 -1
  61. package/dist/modules/ecoimpacthub/index.js +1 -1
  62. package/dist/modules/eventfullymanaged/index.cjs +1 -1
  63. package/dist/modules/eventfullymanaged/index.js +1 -1
  64. package/dist/modules/export/index.cjs +1 -1
  65. package/dist/modules/export/index.js +1 -1
  66. package/dist/modules/files/index.cjs +1 -1
  67. package/dist/modules/files/index.js +1 -1
  68. package/dist/modules/fluidgrids/index.cjs +1 -1
  69. package/dist/modules/fluidgrids/index.js +1 -1
  70. package/dist/modules/ggnomad/index.cjs +1 -1
  71. package/dist/modules/ggnomad/index.js +1 -1
  72. package/dist/modules/govcitizenhub/index.cjs +1 -1
  73. package/dist/modules/govcitizenhub/index.js +1 -1
  74. package/dist/modules/groups/index.cjs +1 -1
  75. package/dist/modules/groups/index.js +1 -1
  76. package/dist/modules/headshotmarketing/index.cjs +1 -1
  77. package/dist/modules/headshotmarketing/index.js +1 -1
  78. package/dist/modules/health/index.cjs +1 -1
  79. package/dist/modules/health/index.js +1 -1
  80. package/dist/modules/healthybowl/index.cjs +1 -1
  81. package/dist/modules/healthybowl/index.js +1 -1
  82. package/dist/modules/hookmovies/index.cjs +1 -1
  83. package/dist/modules/hookmovies/index.js +1 -1
  84. package/dist/modules/housingvista/index.cjs +1 -1
  85. package/dist/modules/housingvista/index.js +1 -1
  86. package/dist/modules/integrations/index.cjs +1 -1
  87. package/dist/modules/integrations/index.js +1 -1
  88. package/dist/modules/intelwatchtower/index.cjs +1 -1
  89. package/dist/modules/intelwatchtower/index.js +1 -1
  90. package/dist/modules/kadaikodi/index.cjs +1 -1
  91. package/dist/modules/kadaikodi/index.js +1 -1
  92. package/dist/modules/labsofscience/index.cjs +1 -1
  93. package/dist/modules/labsofscience/index.js +1 -1
  94. package/dist/modules/manufacturedops/index.cjs +1 -1
  95. package/dist/modules/manufacturedops/index.js +1 -1
  96. package/dist/modules/movethewheels/index.cjs +1 -1
  97. package/dist/modules/movethewheels/index.js +1 -1
  98. package/dist/modules/mybodyshield/index.cjs +1 -1
  99. package/dist/modules/mybodyshield/index.js +1 -1
  100. package/dist/modules/notifications/index.cjs +1 -1
  101. package/dist/modules/notifications/index.js +1 -1
  102. package/dist/modules/organizations/index.cjs +1 -1
  103. package/dist/modules/organizations/index.js +1 -1
  104. package/dist/modules/planmagnet/index.cjs +1 -1
  105. package/dist/modules/planmagnet/index.js +1 -1
  106. package/dist/modules/products/index.cjs +1 -1
  107. package/dist/modules/products/index.js +1 -1
  108. package/dist/modules/proserviceworld/index.cjs +1 -1
  109. package/dist/modules/proserviceworld/index.js +1 -1
  110. package/dist/modules/rbac/index.cjs +1 -1
  111. package/dist/modules/rbac/index.js +1 -1
  112. package/dist/modules/sandbox/index.cjs +1 -1
  113. package/dist/modules/sandbox/index.js +1 -1
  114. package/dist/modules/scheduler/index.cjs +1 -1
  115. package/dist/modules/scheduler/index.js +1 -1
  116. package/dist/modules/security/index.cjs +1 -1
  117. package/dist/modules/security/index.js +1 -1
  118. package/dist/modules/semanticfed/index.cjs +1 -1
  119. package/dist/modules/semanticfed/index.js +1 -1
  120. package/dist/modules/store/index.cjs +1 -1
  121. package/dist/modules/store/index.js +1 -1
  122. package/dist/modules/subscriberbot/index.cjs +1 -1
  123. package/dist/modules/subscriberbot/index.js +1 -1
  124. package/dist/modules/support/index.cjs +1 -1
  125. package/dist/modules/support/index.js +1 -1
  126. package/dist/modules/tags/index.cjs +1 -1
  127. package/dist/modules/tags/index.js +1 -1
  128. package/dist/modules/technospam/index.cjs +1 -1
  129. package/dist/modules/technospam/index.js +1 -1
  130. package/dist/modules/theculturepost/index.cjs +1 -1
  131. package/dist/modules/theculturepost/index.js +1 -1
  132. package/dist/modules/theglobalfuel/index.cjs +1 -1
  133. package/dist/modules/theglobalfuel/index.js +1 -1
  134. package/dist/modules/timecampus/index.cjs +1 -1
  135. package/dist/modules/timecampus/index.js +1 -1
  136. package/dist/modules/tours/index.cjs +1 -1
  137. package/dist/modules/tours/index.js +1 -1
  138. package/dist/modules/vibecontrols/index.cjs +2 -2
  139. package/dist/modules/vibecontrols/index.js +2 -2
  140. package/dist/modules/workspaces/index.cjs +1 -1
  141. package/dist/modules/workspaces/index.js +1 -1
  142. package/dist/transports/hosted.d.ts +33 -0
  143. package/dist/transports/index.cjs +3 -1
  144. package/dist/transports/index.d.ts +1 -0
  145. package/dist/transports/index.js +2 -2
  146. package/dist/transports-CWPyypes.js +478 -0
  147. package/dist/transports-CWPyypes.js.map +1 -0
  148. package/dist/transports-LHVn9JhI.cjs +537 -0
  149. package/dist/transports-LHVn9JhI.cjs.map +1 -0
  150. package/package.json +4 -3
  151. package/dist/core-BKgeqlnN.cjs.map +0 -1
  152. package/dist/core-zmkvPNsI.js.map +0 -1
  153. package/dist/transports-BUwYHMg1.js +0 -206
  154. package/dist/transports-BUwYHMg1.js.map +0 -1
  155. package/dist/transports-Cz4PCHmm.cjs +0 -253
  156. package/dist/transports-Cz4PCHmm.cjs.map +0 -1
@@ -3,10 +3,6 @@ import { join } from "path";
3
3
  import { homedir } from "os";
4
4
  import { GraphQLClient } from "graphql-request";
5
5
  import fetch from "cross-fetch";
6
- import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
- import { SetLevelRequestSchema } from "@modelcontextprotocol/sdk/types.js";
8
- import { createHash } from "node:crypto";
9
- import { z } from "zod";
10
6
 
11
7
  // src/core/auth/store.ts
12
8
  /**
@@ -19,7 +15,7 @@ import { z } from "zod";
19
15
  * keeps the field set in sync with cli-sdk so a shared token store path
20
16
  * (vibecontrols-cli/auth.json) works for both consumers.
21
17
  */
22
- const TOKEN_BUFFER_MS = 3e5;
18
+ const TOKEN_BUFFER_MS$1 = 3e5;
23
19
  /** Decode a JWT payload without verifying it. Returns null for anything that is not a JWT. */
24
20
  function decodeJwtPayload(token) {
25
21
  if (!token) return null;
@@ -94,7 +90,7 @@ function createAuthStore(configDir, authFileName = "auth.json") {
94
90
  function isTokenExpiringSoon() {
95
91
  const expiresAt = accessTokenExpiry(read());
96
92
  if (!expiresAt) return false;
97
- return Date.now() + TOKEN_BUFFER_MS >= expiresAt;
93
+ return Date.now() + TOKEN_BUFFER_MS$1 >= expiresAt;
98
94
  }
99
95
  function isWorkspaceTokenExpired() {
100
96
  const expiresAt = workspaceTokenExpiry(read());
@@ -104,7 +100,7 @@ function createAuthStore(configDir, authFileName = "auth.json") {
104
100
  function isWorkspaceTokenExpiringSoon() {
105
101
  const expiresAt = workspaceTokenExpiry(read());
106
102
  if (!expiresAt) return false;
107
- return Date.now() + TOKEN_BUFFER_MS >= expiresAt;
103
+ return Date.now() + TOKEN_BUFFER_MS$1 >= expiresAt;
108
104
  }
109
105
  function isAuthenticated() {
110
106
  const auth = read();
@@ -129,6 +125,60 @@ function createAuthStore(configDir, authFileName = "auth.json") {
129
125
  };
130
126
  }
131
127
 
128
+ // src/core/auth/memory-store.ts
129
+ /**
130
+ * In-memory AuthStore for one hosted request (BOFF-15144).
131
+ *
132
+ * A hosted MCP server serves many users at once. Each request carries the
133
+ * user's own bearer token (minted by the platform's OAuth server for one
134
+ * connector and one workspace), so every request gets its own store instead
135
+ * of the process-wide auth.json store. Nothing is written to disk and nothing
136
+ * outlives the request.
137
+ *
138
+ * Refresh is the connector's job (it holds the refresh token, not us): the
139
+ * store never carries a refresh token, client credentials or an organization
140
+ * id, so the GraphQL client's refresh paths are no-ops.
141
+ */
142
+ const TOKEN_BUFFER_MS = 3e5;
143
+ function createMemoryAuthStore(initial) {
144
+ let current = initial ? { ...initial } : null;
145
+ const expiry = () => current ? current.expiresAt ?? jwtExpiryMs(current.accessToken) : null;
146
+ const workspaceExpiry = () => {
147
+ if (!current?.workspaceToken) return current?.workspaceTokenExpiresAt ?? null;
148
+ return current.workspaceTokenExpiresAt ?? jwtExpiryMs(current.workspaceToken);
149
+ };
150
+ return {
151
+ read: () => current ? { ...current } : null,
152
+ write: (auth) => {
153
+ current = { ...auth };
154
+ },
155
+ clear: () => {
156
+ current = null;
157
+ },
158
+ isTokenExpired: () => {
159
+ const at = expiry();
160
+ return at !== null && Date.now() >= at;
161
+ },
162
+ isTokenExpiringSoon: () => {
163
+ const at = expiry();
164
+ return at !== null && Date.now() >= at - TOKEN_BUFFER_MS;
165
+ },
166
+ isWorkspaceTokenExpired: () => {
167
+ const at = workspaceExpiry();
168
+ return at !== null && Date.now() >= at;
169
+ },
170
+ isWorkspaceTokenExpiringSoon: () => {
171
+ const at = workspaceExpiry();
172
+ return at !== null && Date.now() >= at - TOKEN_BUFFER_MS;
173
+ },
174
+ isAuthenticated: () => !!current?.accessToken,
175
+ getActorUserId: () => {
176
+ const sub = decodeJwtPayload(current?.accessToken)?.sub;
177
+ return typeof sub === "string" && sub ? sub : null;
178
+ }
179
+ };
180
+ }
181
+
132
182
  // src/core/config/store.ts
133
183
  /**
134
184
  * Config store — parameterised on configDirName + product defaults.
@@ -752,6 +802,25 @@ function buildContext(opts) {
752
802
  _internal: { serverRef }
753
803
  };
754
804
  }
805
+ /**
806
+ * A context for one hosted request (BOFF-15144): same configuration, logger
807
+ * and product identity as `base`, but its own in-memory auth store, GraphQL
808
+ * clients and progress channel. Tool handlers capture the context they were
809
+ * registered with, so a hosted server builds one of these per request and a
810
+ * fresh server around it; two users' requests can never share credentials or
811
+ * progress notifications.
812
+ */
813
+ function contextForRequest(base, auth) {
814
+ const store = createMemoryAuthStore(auth);
815
+ const serverRef = { current: null };
816
+ return {
817
+ ...base,
818
+ auth: store,
819
+ gql: createGqlClients(base.config, store),
820
+ progress: createProgress(serverRef),
821
+ _internal: { serverRef }
822
+ };
823
+ }
755
824
  function dirOf(p) {
756
825
  const lastSlash = p.lastIndexOf("/");
757
826
  return lastSlash > 0 ? p.slice(0, lastSlash) : p;
@@ -762,602 +831,5 @@ function authFileName(p) {
762
831
  return lastSlash >= 0 ? p.slice(lastSlash + 1) : p;
763
832
  }
764
833
 
765
- // src/core/errors.ts
766
- /**
767
- * Error classes for MCP SDK.
768
- *
769
- * Modules MUST throw these instead of throwing raw Errors. The registerTool
770
- * wrapper in result.ts catches and maps them to MCP-protocol-compliant
771
- * `{ isError: true, content: [...] }` responses.
772
- *
773
- * Throwing past the wrapper to the protocol surfaces as JSON-RPC -32603 to
774
- * the client and is a protocol bug.
775
- */
776
- var McpUserError = class extends Error {
777
- hint;
778
- constructor(message, opts) {
779
- super(message);
780
- this.name = "McpUserError";
781
- this.hint = opts?.hint;
782
- }
783
- };
784
- var McpAuthError = class extends McpUserError {
785
- constructor(message, opts) {
786
- super(message, { hint: opts?.hint ?? "Run the auth_login tool to authenticate." });
787
- this.name = "McpAuthError";
788
- }
789
- };
790
- var McpInternalError = class extends Error {
791
- cause;
792
- constructor(message, cause) {
793
- super(message);
794
- this.name = "McpInternalError";
795
- this.cause = cause;
796
- }
797
- };
798
-
799
- // src/core/module.ts
800
- var MissingDependencyError = class extends McpInternalError {
801
- constructor(moduleId, missingDep) {
802
- super(`Module '${moduleId}' declares dependency on '${missingDep}', but '${missingDep}' is not in the module list.`);
803
- this.name = "MissingDependencyError";
804
- }
805
- };
806
- var CircularDependencyError = class extends McpInternalError {
807
- constructor(cycle) {
808
- super(`Circular dependency detected among modules: ${cycle.join(" -> ")}`);
809
- this.name = "CircularDependencyError";
810
- }
811
- };
812
- /**
813
- * Topologically sort modules by their `dependsOn` declarations.
814
- * Throws MissingDependencyError or CircularDependencyError on bad input.
815
- */
816
- function sortModules(modules) {
817
- const byId = /* @__PURE__ */ new Map();
818
- for (const m of modules) {
819
- if (byId.has(m.id)) throw new McpInternalError(`Duplicate module id: '${m.id}'`);
820
- byId.set(m.id, m);
821
- }
822
- for (const m of modules) for (const dep of m.dependsOn ?? []) if (!byId.has(dep)) throw new MissingDependencyError(m.id, dep);
823
- const sorted = [];
824
- const visiting = /* @__PURE__ */ new Set();
825
- const visited = /* @__PURE__ */ new Set();
826
- function visit(m, path) {
827
- if (visited.has(m.id)) return;
828
- if (visiting.has(m.id)) throw new CircularDependencyError([...path, m.id]);
829
- visiting.add(m.id);
830
- for (const dep of m.dependsOn ?? []) {
831
- const depModule = byId.get(dep);
832
- if (depModule) visit(depModule, [...path, m.id]);
833
- }
834
- visiting.delete(m.id);
835
- visited.add(m.id);
836
- sorted.push(m);
837
- }
838
- for (const m of modules) visit(m, []);
839
- return sorted;
840
- }
841
-
842
- // src/core/capabilities.ts
843
- /**
844
- * Union an array of capability declarations. Boolean unions on logging /
845
- * completions; OR on every nested boolean.
846
- */
847
- function unionCapabilities(caps) {
848
- const out = {};
849
- for (const cap of caps) {
850
- if (!cap) continue;
851
- if (cap.resources) {
852
- out.resources ??= {};
853
- if (cap.resources.subscribe) out.resources.subscribe = true;
854
- if (cap.resources.listChanged) out.resources.listChanged = true;
855
- }
856
- if (cap.prompts) {
857
- out.prompts ??= {};
858
- if (cap.prompts.listChanged) out.prompts.listChanged = true;
859
- }
860
- if (cap.tools) {
861
- out.tools ??= {};
862
- if (cap.tools.listChanged) out.tools.listChanged = true;
863
- }
864
- if (cap.logging) out.logging = true;
865
- if (cap.completions) out.completions = true;
866
- }
867
- return out;
868
- }
869
- /**
870
- * Convert capability declaration into the shape the MCP SDK accepts at
871
- * `new McpServer({ capabilities })`. The SDK uses `{}` as truthy markers.
872
- */
873
- function toServerCapabilities(caps) {
874
- const out = {};
875
- if (caps.tools) out.tools = caps.tools;
876
- if (caps.resources) out.resources = caps.resources;
877
- if (caps.prompts) out.prompts = caps.prompts;
878
- if (caps.logging) out.logging = {};
879
- if (caps.completions) out.completions = {};
880
- return out;
881
- }
882
-
883
- // src/core/tool-name.ts
884
- /**
885
- * Tool / resource / prompt naming helpers.
886
- *
887
- * Mandatory product prefix avoids collisions when Claude Desktop runs
888
- * multiple MCP servers concurrently (typical setup is ~6).
889
- *
890
- * Tool names are capped at 63 characters — Claude Desktop pre-1.x
891
- * truncated at 64 in some versions.
892
- */
893
- const MAX_TOOL_NAME_LENGTH = 63;
894
- function assertSafeName(name, kind) {
895
- if (kind === "tool" && name.length > MAX_TOOL_NAME_LENGTH) throw new McpInternalError(`Tool name '${name}' exceeds ${MAX_TOOL_NAME_LENGTH} characters (some MCP clients truncate at 64).`);
896
- return name;
897
- }
898
- /**
899
- * Build a tool name. Format: `<productName>_<...parts>` (snake_case).
900
- * Example: mcpToolName('vibecontrols', 'vibes', 'list') -> 'vibecontrols_vibes_list'
901
- */
902
- function mcpToolName(productName, ...parts) {
903
- if (!productName) throw new McpInternalError("mcpToolName: productName is required");
904
- return assertSafeName([productName, ...parts].filter(Boolean).join("_"), "tool");
905
- }
906
- /**
907
- * Build a resource URI. Format: `<productName>://<...parts>`.
908
- * Example: mcpResourceUri('vibecontrols', 'schema') -> 'vibecontrols://schema'
909
- */
910
- function mcpResourceUri(productName, ...parts) {
911
- if (!productName) throw new McpInternalError("mcpResourceUri: productName is required");
912
- return `${productName}://${parts.filter(Boolean).join("/")}`;
913
- }
914
- /**
915
- * Build a prompt name. Format: `<productName>-<...parts>` (kebab-case).
916
- * Example: mcpPromptName('vibecontrols', 'setup') -> 'vibecontrols-setup'
917
- */
918
- function mcpPromptName(productName, ...parts) {
919
- if (!productName) throw new McpInternalError("mcpPromptName: productName is required");
920
- return [productName, ...parts].filter(Boolean).join("-");
921
- }
922
- const TOOL_NAME_LIMIT = MAX_TOOL_NAME_LENGTH;
923
- /**
924
- * Name-based hint heuristics for MCP `annotations` (readOnlyHint /
925
- * destructiveHint). Used by tool-governance.ts to auto-fill annotations for
926
- * the fleet of product modules that call `server.registerTool` directly
927
- * (bypassing the `registerTool()` core helper) and so never set them
928
- * explicitly today (BOFF-3903). Deliberately conservative — matched against
929
- * whole `_`-delimited segments so e.g. `timeentries_delete` and
930
- * `pomodoro_delete_goal` match, but a hypothetical `undeletable_check`
931
- * would not.
932
- *
933
- * The destructive verb set covers more than `delete`: stopping, killing or
934
- * terminating a running process, revoking or rotating a credential/share,
935
- * resetting settings and removing/purging/uninstalling are all actions an
936
- * MCP client must not auto-run without the user's intent (VC/FG parity G57 —
937
- * e.g. `vibecontrols_sessions_kill`, `vibecontrols_tunnels_rotate_credentials`
938
- * were previously reported as non-destructive).
939
- *
940
- * A module can always override the inference by passing an explicit
941
- * `annotations` object to `registerTool()` / `server.registerTool()` — do
942
- * that for the rare verb match that is harmless (e.g. a typing indicator's
943
- * `typing_stop`).
944
- */
945
- const DESTRUCTIVE_NAME_VERBS = [
946
- "delete",
947
- "destroy",
948
- "erase",
949
- "kill",
950
- "purge",
951
- "remove",
952
- "reset",
953
- "revoke",
954
- "rotate",
955
- "stop",
956
- "terminate",
957
- "uninstall",
958
- "wipe"
959
- ];
960
- const DESTRUCTIVE_NAME_SEGMENT = new RegExp(`(?:^|_)(?:${DESTRUCTIVE_NAME_VERBS.join("|")})(?:_|$)`, "i");
961
- const READ_ONLY_NAME_SEGMENT = /(?:^|_)(?:list|get|search|check|read|count|stats|by_date)(?:_|$)/i;
962
- /** True when a tool name looks destructive (irreversibly deletes data) by naming convention. */
963
- function inferDestructiveHint(toolName) {
964
- return DESTRUCTIVE_NAME_SEGMENT.test(toolName);
965
- }
966
- /**
967
- * True when a tool name looks read-only by naming convention. Never true for
968
- * a name that also looks destructive (a tool can't be both).
969
- */
970
- function inferReadOnlyHint(toolName) {
971
- return !inferDestructiveHint(toolName) && READ_ONLY_NAME_SEGMENT.test(toolName);
972
- }
973
-
974
- // src/core/tool-governance.ts
975
- /**
976
- * Fleet-wide tool governance: MCP `annotations` inference + an opt-in
977
- * confirmation gate on destructive tools.
978
- *
979
- * BOFF-3903: an audit of mcp-libs/src/modules/timecampus/tools/ found 163
980
- * registered tools, ~35 of them destructive (delete/bulk-delete), with ZERO
981
- * `annotations.destructiveHint`/`readOnlyHint` anywhere and no confirmation
982
- * step before a destructive call executes. The same is true fleet-wide —
983
- * every product module calls `server.registerTool` directly (bypassing the
984
- * `registerTool()` central wrapper in result.ts), so a per-module fix would
985
- * have to be re-applied ~54 times.
986
- *
987
- * `wrapServerWithToolGovernance` fixes this ONCE, at the McpServer boundary
988
- * inside `createMcpServer`, by monkey-patching `registerTool` before any
989
- * module receives the server reference. Every subsequent `registerTool`
990
- * call — whether it goes through result.ts's `registerTool()` helper or
991
- * calls `server.registerTool` directly — passes through this wrapper:
992
- *
993
- * 1. `annotations.readOnlyHint` / `destructiveHint` are filled in from the
994
- * tool name (see tool-name.ts's inferDestructiveHint/inferReadOnlyHint)
995
- * whenever a module didn't declare them explicitly. This is pure
996
- * metadata — it never changes a tool's input schema or behavior, so it
997
- * is always safe to apply and every consumer gets it automatically.
998
- * 2. Only when `enforceDestructiveConfirmation` is true (opt-in,
999
- * defaults to false) does a resolved-destructive tool additionally get
1000
- * a `confirm` input field and a hard gate: the tool's real handler is
1001
- * never invoked unless the caller passes `confirm: true`. This is
1002
- * deliberately opt-in — flipping it on is a real behavior change for
1003
- * any existing MCP client automation calling that tool, so each product
1004
- * shell (starting with timecampus-mcp for BOFF-3903) turns it on
1005
- * explicitly via `createMcpServer`'s options once it's ready, rather
1006
- * than every one of the ~54 modules' existing destructive-tool callers
1007
- * breaking the moment this ships.
1008
- */
1009
- /**
1010
- * The tool filter for a token's scopes, with the same grammar as the hosted MCP gateway:
1011
- * `mcp:*` allows every tool, `mcp:tool:<name>` one tool; no MCP scope allows nothing.
1012
- */
1013
- function scopeToolFilter(scopes) {
1014
- if (scopes.includes("mcp:*")) return () => true;
1015
- const allowed = new Set(scopes.filter((scope) => scope.startsWith("mcp:tool:")).map((scope) => scope.slice(9)));
1016
- return (toolName) => allowed.has(toolName);
1017
- }
1018
- function canonicalJson(value, seen = /* @__PURE__ */ new Set()) {
1019
- if (value === null || value === void 0) return "null";
1020
- if (typeof value === "number") return Number.isFinite(value) ? JSON.stringify(value) : "null";
1021
- if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
1022
- if (typeof value === "bigint") return JSON.stringify(value.toString());
1023
- if (typeof value !== "object") return "null";
1024
- if (seen.has(value)) return "null";
1025
- seen.add(value);
1026
- try {
1027
- if (Array.isArray(value)) return `[${value.map((item) => canonicalJson(item, seen)).join(",")}]`;
1028
- const record = value;
1029
- return `{${Object.keys(record).filter((key) => record[key] !== void 0).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key], seen)}`).join(",")}}`;
1030
- } finally {
1031
- seen.delete(value);
1032
- }
1033
- }
1034
- /** sha256 of the canonical JSON of tool arguments, so an audit row never stores the arguments. */
1035
- function toolArgsSha256(args) {
1036
- return createHash("sha256").update(canonicalJson(args), "utf8").digest("hex");
1037
- }
1038
- /**
1039
- * Results the confirmation gate returned instead of running a tool, so the
1040
- * audit hook can report them as `refused` rather than as a tool `error`.
1041
- */
1042
- const refusedResults = /* @__PURE__ */ new WeakSet();
1043
- function isRefusedResult(result) {
1044
- return typeof result === "object" && result !== null && refusedResults.has(result);
1045
- }
1046
- function isErrorResult(result) {
1047
- return typeof result === "object" && result !== null && result.isError === true;
1048
- }
1049
- function wrapAuditedHandler(name, handler, onToolCall) {
1050
- return async (...callbackArgs) => {
1051
- const started = Date.now();
1052
- const args = callbackArgs.length === 2 ? callbackArgs[0] : {};
1053
- const report = (status, error) => {
1054
- try {
1055
- onToolCall({
1056
- name,
1057
- argsSha256: toolArgsSha256(args),
1058
- status,
1059
- durationMs: Date.now() - started,
1060
- ...error ? { error } : {}
1061
- });
1062
- } catch {}
1063
- };
1064
- try {
1065
- const result = await handler(...callbackArgs);
1066
- report(isRefusedResult(result) ? "refused" : isErrorResult(result) ? "error" : "ok");
1067
- return result;
1068
- } catch (error) {
1069
- report("error", error instanceof Error ? error.message : String(error));
1070
- throw error;
1071
- }
1072
- };
1073
- }
1074
- const CONFIRM_FIELD_DESCRIPTION = "Must be true to execute this destructive tool. The call is rejected (no changes made) if omitted or false.";
1075
- function resolveAnnotations(name, declared) {
1076
- const destructiveHint = declared?.destructiveHint ?? inferDestructiveHint(name);
1077
- const readOnlyHint = declared?.readOnlyHint ?? (destructiveHint ? false : inferReadOnlyHint(name));
1078
- return {
1079
- ...declared,
1080
- destructiveHint,
1081
- readOnlyHint
1082
- };
1083
- }
1084
- /** Rejection result forwarded to the MCP client without invoking the real handler. */
1085
- function unconfirmedDestructiveResult(name) {
1086
- const result = {
1087
- content: [{
1088
- type: "text",
1089
- text: `'${name}' is a destructive action and was NOT executed. Re-call with confirm: true once you intend to proceed.`
1090
- }],
1091
- isError: true
1092
- };
1093
- refusedResults.add(result);
1094
- return result;
1095
- }
1096
- function wrapDestructiveHandler(name, handler) {
1097
- return async (...callbackArgs) => {
1098
- const hasArgs = callbackArgs.length === 2;
1099
- const rawArgs = hasArgs ? callbackArgs[0] : {};
1100
- if (rawArgs["confirm"] !== true) return unconfirmedDestructiveResult(name);
1101
- const forwardedArgs = { ...rawArgs };
1102
- delete forwardedArgs["confirm"];
1103
- return handler(...hasArgs ? [forwardedArgs, callbackArgs[1]] : callbackArgs);
1104
- };
1105
- }
1106
- /**
1107
- * Monkey-patch `server.registerTool` so every tool registered afterward
1108
- * (by any module, through any call path) gets annotations inference and,
1109
- * when enabled, the destructive-confirmation gate. Returns the same server
1110
- * instance (mutated in place) for convenient chaining.
1111
- */
1112
- function wrapServerWithToolGovernance(server, options = {}) {
1113
- const enforceConfirmation = options.enforceDestructiveConfirmation ?? false;
1114
- const target = server;
1115
- const originalRegisterTool = target.registerTool.bind(target);
1116
- const register = (name, config, handler) => {
1117
- const annotations = resolveAnnotations(name, config.annotations);
1118
- const audit = (inner) => options.onToolCall ? wrapAuditedHandler(name, inner, options.onToolCall) : inner;
1119
- if (!enforceConfirmation || !annotations.destructiveHint) return originalRegisterTool(name, {
1120
- ...config,
1121
- annotations
1122
- }, audit(handler));
1123
- const gatedInputSchema = {
1124
- ...config.inputSchema ?? {},
1125
- confirm: z.boolean().optional().describe(CONFIRM_FIELD_DESCRIPTION)
1126
- };
1127
- return originalRegisterTool(name, {
1128
- ...config,
1129
- inputSchema: gatedInputSchema,
1130
- annotations
1131
- }, audit(wrapDestructiveHandler(name, handler)));
1132
- };
1133
- target.registerTool = (name, config, handler) => {
1134
- const registered = register(name, config, handler);
1135
- if (options.toolFilter && !options.toolFilter(name)) registered?.disable?.();
1136
- return registered;
1137
- };
1138
- return server;
1139
- }
1140
- /**
1141
- * Run `register` with every `server.registerTool` call it makes carrying
1142
- * the annotations `resolve` returns for that tool name. Lets a large module
1143
- * keep its annotations in one reviewed table (VC/FG parity G57: the
1144
- * vibecontrols module registers ~280 tools) instead of scattering them over
1145
- * every call site, while still going through the governance wrapper — the
1146
- * table counts as an *explicit* declaration, so it wins over name
1147
- * inference and drives the confirmation gate.
1148
- *
1149
- * Annotations a call site passes inline take precedence over the table.
1150
- * `server.registerTool` is restored when `register` returns or throws, so
1151
- * resource/prompt registration and later modules are unaffected.
1152
- */
1153
- function withToolAnnotations(server, resolve, register) {
1154
- const target = server;
1155
- const governedRegisterTool = target.registerTool;
1156
- target.registerTool = (name, config, handler) => {
1157
- const declared = resolve(name);
1158
- const annotations = declared === void 0 ? config.annotations : {
1159
- ...declared,
1160
- ...config.annotations
1161
- };
1162
- return governedRegisterTool.call(target, name, {
1163
- ...config,
1164
- annotations
1165
- }, handler);
1166
- };
1167
- try {
1168
- return register();
1169
- } finally {
1170
- target.registerTool = governedRegisterTool;
1171
- }
1172
- }
1173
-
1174
- // src/core/server.ts
1175
- /**
1176
- * createMcpServer — McpServer factory + module loader + central wiring.
1177
- *
1178
- * Sorts modules by dependsOn, unions their capabilities, constructs an
1179
- * McpServer with declared capabilities, calls register() on each module in
1180
- * topo order, threads the server into ctx for progress notifications, and
1181
- * returns both the server + the merged registration manifest.
1182
- *
1183
- * The `logging/setLevel` request handler is wired to ctx.logger.setLevel
1184
- * so MCP clients can dynamically control verbosity.
1185
- */
1186
- const MCP_TO_LOGGER_LEVEL = {
1187
- debug: "debug",
1188
- info: "info",
1189
- notice: "info",
1190
- warning: "warn",
1191
- error: "error",
1192
- critical: "error",
1193
- alert: "error",
1194
- emergency: "error"
1195
- };
1196
- function createMcpServer(ctx, modules, opts) {
1197
- const sorted = sortModules(modules);
1198
- const capabilities = unionCapabilities([
1199
- { logging: true },
1200
- ...sorted.map((m) => m.capabilities),
1201
- opts.extraCapabilities
1202
- ]);
1203
- const server = new McpServer({
1204
- name: opts.name,
1205
- version: opts.version
1206
- }, { capabilities: toServerCapabilities(capabilities) });
1207
- wrapServerWithToolGovernance(server, {
1208
- enforceDestructiveConfirmation: opts.enforceDestructiveConfirmation,
1209
- toolFilter: opts.toolFilter,
1210
- onToolCall: opts.onToolCall
1211
- });
1212
- ctx._internal.serverRef.current = server;
1213
- const inner = server.server ?? server;
1214
- if (typeof inner.setRequestHandler === "function") inner.setRequestHandler(SetLevelRequestSchema, async (req) => {
1215
- const target = MCP_TO_LOGGER_LEVEL[req.params.level] ?? "info";
1216
- ctx.logger.setLevel(target);
1217
- ctx.logger.info("MCP logging level set", {
1218
- level: req.params.level,
1219
- mapped: target
1220
- });
1221
- return {};
1222
- });
1223
- const tools = [];
1224
- const resources = [];
1225
- const prompts = [];
1226
- const moduleManifest = [];
1227
- for (const mod of sorted) try {
1228
- const reg = mod.register(server, ctx);
1229
- tools.push(...reg.tools);
1230
- resources.push(...reg.resources);
1231
- prompts.push(...reg.prompts);
1232
- moduleManifest.push({
1233
- id: mod.id,
1234
- version: mod.version
1235
- });
1236
- ctx.logger.debug(`Registered module: ${mod.id}`, {
1237
- tools: reg.tools.length,
1238
- resources: reg.resources.length,
1239
- prompts: reg.prompts.length
1240
- });
1241
- } catch (error) {
1242
- ctx.logger.error(`Failed to register module: ${mod.id}`, { error: error instanceof Error ? error.message : String(error) });
1243
- throw error;
1244
- }
1245
- const manifest = {
1246
- modules: moduleManifest,
1247
- tools,
1248
- resources,
1249
- prompts
1250
- };
1251
- ctx.logger.info(`MCP server ready: ${opts.name}@${opts.version}`, {
1252
- modules: manifest.modules.length,
1253
- tools: manifest.tools.length,
1254
- resources: manifest.resources.length,
1255
- prompts: manifest.prompts.length
1256
- });
1257
- return {
1258
- server,
1259
- manifest
1260
- };
1261
- }
1262
-
1263
- // src/core/result.ts
1264
- /**
1265
- * Build a successful tool result with JSON content (pretty-printed).
1266
- */
1267
- function jsonResult(data, structured) {
1268
- const result = { content: [{
1269
- type: "text",
1270
- text: JSON.stringify(data, null, 2)
1271
- }] };
1272
- if (structured !== void 0) result.structuredContent = structured;
1273
- return result;
1274
- }
1275
- /**
1276
- * Build a successful tool result with plain text content.
1277
- */
1278
- function textResult(text) {
1279
- return { content: [{
1280
- type: "text",
1281
- text
1282
- }] };
1283
- }
1284
- /**
1285
- * Build an error tool result. Honors MCP's `{ isError: true, content }` shape.
1286
- * Optional hint is appended on a new line so the LLM can react.
1287
- */
1288
- function errorResult(message, hint) {
1289
- return {
1290
- content: [{
1291
- type: "text",
1292
- text: hint ? `${message}\n\nHint: ${hint}` : message
1293
- }],
1294
- isError: true
1295
- };
1296
- }
1297
- /**
1298
- * Register a tool with the central error wrapper.
1299
- *
1300
- * The handler returns a plain value or void. The wrapper:
1301
- * - wraps non-undefined returns in jsonResult()
1302
- * - if the value already looks like a ToolResult (has `content`), passes through
1303
- * - catches McpAuthError / McpUserError / McpInternalError / generic Error
1304
- * - logs every error via ctx.logger.error
1305
- */
1306
- function registerTool(server, ctx, name, metadata, handler) {
1307
- const sdkConfig = {
1308
- title: metadata.title,
1309
- description: metadata.description,
1310
- ...metadata.inputSchema ? { inputSchema: metadata.inputSchema } : {},
1311
- ...metadata.annotations ? { annotations: metadata.annotations } : {}
1312
- };
1313
- const wrapped = async (...callbackArgs) => {
1314
- const hasArgs = callbackArgs.length === 2;
1315
- const args = hasArgs ? callbackArgs[0] : {};
1316
- const progressToken = (hasArgs ? callbackArgs[1] : callbackArgs[0])?._meta?.progressToken;
1317
- const meta = progressToken !== void 0 ? { progressToken } : {};
1318
- try {
1319
- const result = await handler(args, ctx, meta);
1320
- if (isToolResult(result)) return result;
1321
- if (result === void 0) return textResult("OK");
1322
- return jsonResult(result);
1323
- } catch (error) {
1324
- return mapErrorToResult(error, ctx, name);
1325
- }
1326
- };
1327
- server.registerTool(name, sdkConfig, wrapped);
1328
- }
1329
- function isToolResult(value) {
1330
- return !!value && typeof value === "object" && "content" in value && Array.isArray(value.content);
1331
- }
1332
- function mapErrorToResult(error, ctx, toolName) {
1333
- if (error instanceof McpAuthError) {
1334
- ctx.logger.warn(`${toolName}: auth required`, { message: error.message });
1335
- return errorResult(error.message, error.hint);
1336
- }
1337
- if (error instanceof McpUserError) {
1338
- ctx.logger.info(`${toolName}: user error`, { message: error.message });
1339
- return errorResult(error.message, error.hint);
1340
- }
1341
- if (error instanceof McpInternalError) {
1342
- ctx.logger.error(`${toolName}: internal error`, {
1343
- message: error.message,
1344
- cause: stringifyCause(error.cause)
1345
- });
1346
- return errorResult(`Internal error in ${toolName}.`);
1347
- }
1348
- const message = error instanceof Error ? error.message : String(error);
1349
- ctx.logger.error(`${toolName}: unhandled error`, { message });
1350
- return errorResult(`${toolName}: ${message}`);
1351
- }
1352
- function stringifyCause(cause) {
1353
- if (cause === void 0 || cause === null) return void 0;
1354
- if (cause instanceof Error) return cause.message;
1355
- try {
1356
- return JSON.stringify(cause);
1357
- } catch {
1358
- return String(cause);
1359
- }
1360
- }
1361
-
1362
- export { extractGqlErrorMessage as A, McpInternalError as C, createLogger as D, createProgress as E, pollDeviceTokenOnce as F, startDeviceCodeFlow as I, createConfigStore as L, clientCredentialsFlow as M, fetchWorkspaces as N, GqlRequestError as O, issueWorkspaceToken as P, createAuthStore as R, McpAuthError as S, buildContext as T, toServerCapabilities as _, createMcpServer as a, MissingDependencyError as b, withToolAnnotations as c, TOOL_NAME_LIMIT as d, inferDestructiveHint as f, mcpToolName as g, mcpResourceUri as h, textResult as i, isExpiredCredentialError as j, createGqlClients as k, wrapServerWithToolGovernance as l, mcpPromptName as m, jsonResult as n, scopeToolFilter as o, inferReadOnlyHint as p, registerTool as r, toolArgsSha256 as s, errorResult as t, DESTRUCTIVE_NAME_VERBS as u, unionCapabilities as v, McpUserError as w, sortModules as x, CircularDependencyError as y, jwtExpiryMs as z };
1363
- //# sourceMappingURL=core-zmkvPNsI.js.map
834
+ export { decodeJwtPayload as _, GqlRequestError as a, isExpiredCredentialError as c, issueWorkspaceToken as d, pollDeviceTokenOnce as f, createAuthStore as g, createMemoryAuthStore as h, createLogger as i, clientCredentialsFlow as l, createConfigStore as m, contextForRequest as n, createGqlClients as o, startDeviceCodeFlow as p, createProgress as r, extractGqlErrorMessage as s, buildContext as t, fetchWorkspaces as u, jwtExpiryMs as v };
835
+ //# sourceMappingURL=context-CNN-D9dE.js.map