@burdenoff/mcp-libs 2026.511.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 (174) hide show
  1. package/README.md +76 -0
  2. package/dist/chunk-4GBVJ4OY.js +847 -0
  3. package/dist/chunk-4GBVJ4OY.js.map +1 -0
  4. package/dist/chunk-H2OYWLOA.js +919 -0
  5. package/dist/chunk-H2OYWLOA.js.map +1 -0
  6. package/dist/chunk-JFEQYSWM.js +174 -0
  7. package/dist/chunk-JFEQYSWM.js.map +1 -0
  8. package/dist/chunk-WWFVD7BO.js +273 -0
  9. package/dist/chunk-WWFVD7BO.js.map +1 -0
  10. package/dist/context-1jV4NsLv.d.cts +138 -0
  11. package/dist/context-1jV4NsLv.d.ts +138 -0
  12. package/dist/core/index.cjs +953 -0
  13. package/dist/core/index.cjs.map +1 -0
  14. package/dist/core/index.d.cts +59 -0
  15. package/dist/core/index.d.ts +59 -0
  16. package/dist/core/index.js +3 -0
  17. package/dist/core/index.js.map +1 -0
  18. package/dist/http-BP4c721D.d.cts +22 -0
  19. package/dist/http-DXTeCD5r.d.ts +22 -0
  20. package/dist/index.cjs +1013 -0
  21. package/dist/index.cjs.map +1 -0
  22. package/dist/index.d.cts +7 -0
  23. package/dist/index.d.ts +7 -0
  24. package/dist/index.js +4 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/module-DBcfA-i3.d.ts +67 -0
  27. package/dist/module-DFQBZNK6.d.cts +67 -0
  28. package/dist/modules/auth/index.cjs +533 -0
  29. package/dist/modules/auth/index.cjs.map +1 -0
  30. package/dist/modules/auth/index.d.cts +51 -0
  31. package/dist/modules/auth/index.d.ts +51 -0
  32. package/dist/modules/auth/index.js +159 -0
  33. package/dist/modules/auth/index.js.map +1 -0
  34. package/dist/modules/billing/index.cjs +655 -0
  35. package/dist/modules/billing/index.cjs.map +1 -0
  36. package/dist/modules/billing/index.d.cts +8 -0
  37. package/dist/modules/billing/index.d.ts +8 -0
  38. package/dist/modules/billing/index.js +606 -0
  39. package/dist/modules/billing/index.js.map +1 -0
  40. package/dist/modules/channels/index.cjs +443 -0
  41. package/dist/modules/channels/index.cjs.map +1 -0
  42. package/dist/modules/channels/index.d.cts +8 -0
  43. package/dist/modules/channels/index.d.ts +8 -0
  44. package/dist/modules/channels/index.js +394 -0
  45. package/dist/modules/channels/index.js.map +1 -0
  46. package/dist/modules/conversations/index.cjs +288 -0
  47. package/dist/modules/conversations/index.cjs.map +1 -0
  48. package/dist/modules/conversations/index.d.cts +8 -0
  49. package/dist/modules/conversations/index.d.ts +8 -0
  50. package/dist/modules/conversations/index.js +239 -0
  51. package/dist/modules/conversations/index.js.map +1 -0
  52. package/dist/modules/devportal/index.cjs +796 -0
  53. package/dist/modules/devportal/index.cjs.map +1 -0
  54. package/dist/modules/devportal/index.d.cts +8 -0
  55. package/dist/modules/devportal/index.d.ts +8 -0
  56. package/dist/modules/devportal/index.js +747 -0
  57. package/dist/modules/devportal/index.js.map +1 -0
  58. package/dist/modules/export/index.cjs +333 -0
  59. package/dist/modules/export/index.cjs.map +1 -0
  60. package/dist/modules/export/index.d.cts +8 -0
  61. package/dist/modules/export/index.d.ts +8 -0
  62. package/dist/modules/export/index.js +284 -0
  63. package/dist/modules/export/index.js.map +1 -0
  64. package/dist/modules/files/index.cjs +278 -0
  65. package/dist/modules/files/index.cjs.map +1 -0
  66. package/dist/modules/files/index.d.cts +8 -0
  67. package/dist/modules/files/index.d.ts +8 -0
  68. package/dist/modules/files/index.js +229 -0
  69. package/dist/modules/files/index.js.map +1 -0
  70. package/dist/modules/groups/index.cjs +451 -0
  71. package/dist/modules/groups/index.cjs.map +1 -0
  72. package/dist/modules/groups/index.d.cts +8 -0
  73. package/dist/modules/groups/index.d.ts +8 -0
  74. package/dist/modules/groups/index.js +402 -0
  75. package/dist/modules/groups/index.js.map +1 -0
  76. package/dist/modules/health/index.cjs +159 -0
  77. package/dist/modules/health/index.cjs.map +1 -0
  78. package/dist/modules/health/index.d.cts +8 -0
  79. package/dist/modules/health/index.d.ts +8 -0
  80. package/dist/modules/health/index.js +36 -0
  81. package/dist/modules/health/index.js.map +1 -0
  82. package/dist/modules/integrations/index.cjs +316 -0
  83. package/dist/modules/integrations/index.cjs.map +1 -0
  84. package/dist/modules/integrations/index.d.cts +8 -0
  85. package/dist/modules/integrations/index.d.ts +8 -0
  86. package/dist/modules/integrations/index.js +267 -0
  87. package/dist/modules/integrations/index.js.map +1 -0
  88. package/dist/modules/notifications/index.cjs +222 -0
  89. package/dist/modules/notifications/index.cjs.map +1 -0
  90. package/dist/modules/notifications/index.d.cts +8 -0
  91. package/dist/modules/notifications/index.d.ts +8 -0
  92. package/dist/modules/notifications/index.js +173 -0
  93. package/dist/modules/notifications/index.js.map +1 -0
  94. package/dist/modules/organizations/index.cjs +267 -0
  95. package/dist/modules/organizations/index.cjs.map +1 -0
  96. package/dist/modules/organizations/index.d.cts +8 -0
  97. package/dist/modules/organizations/index.d.ts +8 -0
  98. package/dist/modules/organizations/index.js +218 -0
  99. package/dist/modules/organizations/index.js.map +1 -0
  100. package/dist/modules/products/index.cjs +736 -0
  101. package/dist/modules/products/index.cjs.map +1 -0
  102. package/dist/modules/products/index.d.cts +8 -0
  103. package/dist/modules/products/index.d.ts +8 -0
  104. package/dist/modules/products/index.js +687 -0
  105. package/dist/modules/products/index.js.map +1 -0
  106. package/dist/modules/rbac/index.cjs +378 -0
  107. package/dist/modules/rbac/index.cjs.map +1 -0
  108. package/dist/modules/rbac/index.d.cts +8 -0
  109. package/dist/modules/rbac/index.d.ts +8 -0
  110. package/dist/modules/rbac/index.js +329 -0
  111. package/dist/modules/rbac/index.js.map +1 -0
  112. package/dist/modules/sandbox/index.cjs +318 -0
  113. package/dist/modules/sandbox/index.cjs.map +1 -0
  114. package/dist/modules/sandbox/index.d.cts +8 -0
  115. package/dist/modules/sandbox/index.d.ts +8 -0
  116. package/dist/modules/sandbox/index.js +225 -0
  117. package/dist/modules/sandbox/index.js.map +1 -0
  118. package/dist/modules/scheduler/index.cjs +267 -0
  119. package/dist/modules/scheduler/index.cjs.map +1 -0
  120. package/dist/modules/scheduler/index.d.cts +8 -0
  121. package/dist/modules/scheduler/index.d.ts +8 -0
  122. package/dist/modules/scheduler/index.js +218 -0
  123. package/dist/modules/scheduler/index.js.map +1 -0
  124. package/dist/modules/security/index.cjs +529 -0
  125. package/dist/modules/security/index.cjs.map +1 -0
  126. package/dist/modules/security/index.d.cts +8 -0
  127. package/dist/modules/security/index.d.ts +8 -0
  128. package/dist/modules/security/index.js +480 -0
  129. package/dist/modules/security/index.js.map +1 -0
  130. package/dist/modules/store/index.cjs +450 -0
  131. package/dist/modules/store/index.cjs.map +1 -0
  132. package/dist/modules/store/index.d.cts +8 -0
  133. package/dist/modules/store/index.d.ts +8 -0
  134. package/dist/modules/store/index.js +401 -0
  135. package/dist/modules/store/index.js.map +1 -0
  136. package/dist/modules/support/index.cjs +285 -0
  137. package/dist/modules/support/index.cjs.map +1 -0
  138. package/dist/modules/support/index.d.cts +8 -0
  139. package/dist/modules/support/index.d.ts +8 -0
  140. package/dist/modules/support/index.js +236 -0
  141. package/dist/modules/support/index.js.map +1 -0
  142. package/dist/modules/tags/index.cjs +421 -0
  143. package/dist/modules/tags/index.cjs.map +1 -0
  144. package/dist/modules/tags/index.d.cts +8 -0
  145. package/dist/modules/tags/index.d.ts +8 -0
  146. package/dist/modules/tags/index.js +372 -0
  147. package/dist/modules/tags/index.js.map +1 -0
  148. package/dist/modules/tours/index.cjs +225 -0
  149. package/dist/modules/tours/index.cjs.map +1 -0
  150. package/dist/modules/tours/index.d.cts +8 -0
  151. package/dist/modules/tours/index.d.ts +8 -0
  152. package/dist/modules/tours/index.js +176 -0
  153. package/dist/modules/tours/index.js.map +1 -0
  154. package/dist/modules/vibecontrols/index.cjs +5551 -0
  155. package/dist/modules/vibecontrols/index.cjs.map +1 -0
  156. package/dist/modules/vibecontrols/index.d.cts +8 -0
  157. package/dist/modules/vibecontrols/index.d.ts +8 -0
  158. package/dist/modules/vibecontrols/index.js +4380 -0
  159. package/dist/modules/vibecontrols/index.js.map +1 -0
  160. package/dist/modules/workspaces/index.cjs +552 -0
  161. package/dist/modules/workspaces/index.cjs.map +1 -0
  162. package/dist/modules/workspaces/index.d.cts +8 -0
  163. package/dist/modules/workspaces/index.d.ts +8 -0
  164. package/dist/modules/workspaces/index.js +503 -0
  165. package/dist/modules/workspaces/index.js.map +1 -0
  166. package/dist/tool-name-CQf_IqAj.d.cts +47 -0
  167. package/dist/tool-name-DlnrBsZ6.d.ts +47 -0
  168. package/dist/transports/index.cjs +183 -0
  169. package/dist/transports/index.cjs.map +1 -0
  170. package/dist/transports/index.d.cts +13 -0
  171. package/dist/transports/index.d.ts +13 -0
  172. package/dist/transports/index.js +3 -0
  173. package/dist/transports/index.js.map +1 -0
  174. package/package.json +125 -0
@@ -0,0 +1,919 @@
1
+ import { existsSync, readFileSync, writeFileSync, chmodSync, unlinkSync, mkdirSync } from 'fs';
2
+ import { join } from 'path';
3
+ import { homedir } from 'os';
4
+ import { GraphQLClient } from 'graphql-request';
5
+ import fetch from 'cross-fetch';
6
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
7
+ import { SetLevelRequestSchema } from '@modelcontextprotocol/sdk/types.js';
8
+
9
+ // src/core/auth/store.ts
10
+ var TOKEN_BUFFER_MS = 5 * 60 * 1e3;
11
+ function createAuthStore(configDir, authFileName2 = "auth.json") {
12
+ const authFile = join(configDir, authFileName2);
13
+ function ensureConfigDir() {
14
+ if (!existsSync(configDir)) {
15
+ mkdirSync(configDir, { recursive: true, mode: 448 });
16
+ }
17
+ }
18
+ function read() {
19
+ try {
20
+ if (!existsSync(authFile)) return null;
21
+ const raw = readFileSync(authFile, "utf8");
22
+ return JSON.parse(raw);
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+ function write(auth) {
28
+ ensureConfigDir();
29
+ writeFileSync(authFile, JSON.stringify(auth, null, 2), { encoding: "utf8", mode: 384 });
30
+ try {
31
+ chmodSync(authFile, 384);
32
+ } catch {
33
+ }
34
+ }
35
+ function clear() {
36
+ try {
37
+ if (existsSync(authFile)) unlinkSync(authFile);
38
+ } catch {
39
+ }
40
+ }
41
+ function isTokenExpired() {
42
+ const auth = read();
43
+ if (!auth?.expiresAt) return false;
44
+ return Date.now() >= auth.expiresAt;
45
+ }
46
+ function isTokenExpiringSoon() {
47
+ const auth = read();
48
+ if (!auth?.expiresAt) return false;
49
+ return Date.now() + TOKEN_BUFFER_MS >= auth.expiresAt;
50
+ }
51
+ function isWorkspaceTokenExpired() {
52
+ const auth = read();
53
+ if (!auth?.workspaceTokenExpiresAt) return false;
54
+ return Date.now() >= auth.workspaceTokenExpiresAt;
55
+ }
56
+ function isWorkspaceTokenExpiringSoon() {
57
+ const auth = read();
58
+ if (!auth?.workspaceTokenExpiresAt) return false;
59
+ return Date.now() + TOKEN_BUFFER_MS >= auth.workspaceTokenExpiresAt;
60
+ }
61
+ function isAuthenticated() {
62
+ const auth = read();
63
+ if (auth?.apiKey) return true;
64
+ if (!auth?.accessToken) return false;
65
+ return !isTokenExpired();
66
+ }
67
+ return {
68
+ read,
69
+ write,
70
+ clear,
71
+ isTokenExpired,
72
+ isTokenExpiringSoon,
73
+ isWorkspaceTokenExpired,
74
+ isWorkspaceTokenExpiringSoon,
75
+ isAuthenticated
76
+ };
77
+ }
78
+ function envOr(prefix, key, fallback) {
79
+ if (prefix) {
80
+ const prefixed = process.env[`${prefix}_${key}`];
81
+ if (prefixed !== void 0 && prefixed !== "") return prefixed;
82
+ }
83
+ const direct = process.env[key];
84
+ if (direct !== void 0 && direct !== "") return direct;
85
+ return fallback;
86
+ }
87
+ function createConfigStore(defaults) {
88
+ const configDir = join(homedir(), ".config", defaults.configDirName);
89
+ const configFile = join(configDir, "config.json");
90
+ const envPrefix = defaults.envPrefix ?? defaults.configDirName.toUpperCase().replace(/-/g, "_");
91
+ function ensureConfigDir() {
92
+ if (!existsSync(configDir)) {
93
+ mkdirSync(configDir, { recursive: true, mode: 448 });
94
+ }
95
+ }
96
+ function readPersisted() {
97
+ try {
98
+ if (!existsSync(configFile)) return {};
99
+ const raw = readFileSync(configFile, "utf8");
100
+ return JSON.parse(raw);
101
+ } catch {
102
+ return {};
103
+ }
104
+ }
105
+ function read() {
106
+ const persisted = readPersisted();
107
+ const workspaceEndpoint = envOr(envPrefix, "WORKSPACE_ENDPOINT") ?? persisted.workspaceEndpoint ?? defaults.workspaceEndpointDefault;
108
+ const globalEndpoint = envOr(envPrefix, "GLOBAL_ENDPOINT") ?? persisted.globalEndpoint ?? defaults.globalEndpointDefault;
109
+ const httpPortRaw = envOr(envPrefix, "HTTP_PORT") ?? envOr(void 0, "PORT") ?? String(defaults.httpPortDefault ?? 3e3);
110
+ const logLevelRaw = envOr(void 0, "LOG_LEVEL") ?? persisted.logLevel ?? "info";
111
+ const logFormatRaw = envOr(void 0, "LOG_FORMAT") ?? persisted.logFormat ?? "json";
112
+ return {
113
+ workspaceEndpoint,
114
+ globalEndpoint,
115
+ oidcIssuer: envOr(envPrefix, "OIDC_ISSUER") ?? persisted.oidcIssuer,
116
+ clientId: envOr(envPrefix, "CLIENT_ID") ?? persisted.clientId,
117
+ accessToken: envOr(envPrefix, "ACCESS_TOKEN"),
118
+ refreshToken: envOr(envPrefix, "REFRESH_TOKEN"),
119
+ workspaceToken: envOr(envPrefix, "WORKSPACE_TOKEN"),
120
+ apiKey: envOr(envPrefix, "API_KEY") ?? envOr(void 0, "MCP_API_KEY"),
121
+ workspaceId: envOr(envPrefix, "WORKSPACE_ID"),
122
+ organizationId: envOr(envPrefix, "ORGANIZATION_ID"),
123
+ host: envOr(void 0, "HOST") ?? envOr(void 0, "MCP_HOST") ?? defaults.hostDefault ?? "127.0.0.1",
124
+ httpPort: parseInt(httpPortRaw, 10) || (defaults.httpPortDefault ?? 3e3),
125
+ corsOrigins: envOr(void 0, "CORS_ORIGINS") ?? persisted.corsOrigins ?? "http://127.0.0.1,http://localhost",
126
+ allowedHosts: envOr(void 0, "ALLOWED_HOSTS") ?? persisted.allowedHosts ?? "127.0.0.1,localhost",
127
+ logLevel: ["error", "warn", "info", "debug"].includes(logLevelRaw) ? logLevelRaw : "info",
128
+ logFormat: logFormatRaw === "text" ? "text" : "json"
129
+ };
130
+ }
131
+ function write(patch) {
132
+ ensureConfigDir();
133
+ const merged = { ...readPersisted(), ...patch };
134
+ writeFileSync(configFile, JSON.stringify(merged, null, 2), { encoding: "utf8" });
135
+ try {
136
+ chmodSync(configFile, 384);
137
+ } catch {
138
+ }
139
+ }
140
+ function resolveOIDC() {
141
+ const config = read();
142
+ const clientId = config.clientId || defaults.oidcClientId;
143
+ let oidcIssuer = config.oidcIssuer;
144
+ if (!oidcIssuer) {
145
+ const globalEndpoint = config.globalEndpoint;
146
+ if (globalEndpoint.includes("localhost") || globalEndpoint.includes("127.0.0.1")) {
147
+ oidcIssuer = globalEndpoint.replace(/\/graphql$/, "").replace(/\/global\/graphql$/, "/global");
148
+ } else {
149
+ oidcIssuer = defaults.oidcIssuerProd ?? "https://graphql.burdenoff.com/global";
150
+ }
151
+ }
152
+ return { oidcIssuer, clientId };
153
+ }
154
+ return {
155
+ read,
156
+ write,
157
+ path: () => configFile,
158
+ dir: () => configDir,
159
+ resolveOIDC
160
+ };
161
+ }
162
+ async function startDeviceCodeFlow(config) {
163
+ const url = `${config.oidcIssuer}/oidc/device/code`;
164
+ const body = new URLSearchParams({
165
+ client_id: config.clientId,
166
+ scope: "openid profile email offline_access"
167
+ });
168
+ const response = await fetch(url, {
169
+ method: "POST",
170
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
171
+ body: body.toString()
172
+ });
173
+ if (!response.ok) {
174
+ const text = await response.text().catch(() => "Unknown error");
175
+ throw new Error(`Device code request failed (${response.status}): ${text}`);
176
+ }
177
+ const data = await response.json();
178
+ return {
179
+ deviceCode: data["device_code"],
180
+ userCode: data["user_code"],
181
+ verificationUri: data["verification_uri"],
182
+ verificationUriComplete: data["verification_uri_complete"] ?? null,
183
+ expiresIn: data["expires_in"],
184
+ interval: data["interval"] ?? 5
185
+ };
186
+ }
187
+ async function pollDeviceTokenOnce(deviceCode, interval, config) {
188
+ const url = `${config.oidcIssuer}/oauth/device/token`;
189
+ const response = await fetch(url, {
190
+ method: "POST",
191
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
192
+ body: new URLSearchParams({
193
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
194
+ device_code: deviceCode,
195
+ client_id: config.clientId
196
+ }).toString()
197
+ });
198
+ const data = await response.json();
199
+ if (response.ok && data["access_token"]) {
200
+ return {
201
+ status: "authenticated",
202
+ tokens: {
203
+ accessToken: data["access_token"],
204
+ refreshToken: data["refresh_token"] ?? "",
205
+ expiresIn: data["expires_in"] ?? 3600
206
+ }
207
+ };
208
+ }
209
+ const errorCode = data["error"];
210
+ switch (errorCode) {
211
+ case "authorization_pending":
212
+ return { status: "pending" };
213
+ case "slow_down":
214
+ return { status: "slow_down", newInterval: interval + 5 };
215
+ case "expired_token":
216
+ return { status: "expired" };
217
+ case "access_denied":
218
+ return { status: "denied" };
219
+ default:
220
+ throw new Error(
221
+ `Device code polling failed: ${data["error_description"] ?? errorCode ?? "Unknown error"}`
222
+ );
223
+ }
224
+ }
225
+ async function clientCredentialsFlow(globalEndpoint, clientId, clientSecret, scopes) {
226
+ const query = `
227
+ mutation AuthenticateApp($input: AuthenticateAppInput!) {
228
+ authenticateApp(input: $input) {
229
+ accessToken tokenType expiresIn scopes
230
+ }
231
+ }
232
+ `;
233
+ const response = await fetch(globalEndpoint, {
234
+ method: "POST",
235
+ headers: { "Content-Type": "application/json" },
236
+ body: JSON.stringify({
237
+ query,
238
+ variables: { input: { clientId, clientSecret, scopes } }
239
+ })
240
+ });
241
+ if (!response.ok) {
242
+ const text = await response.text().catch(() => "Unknown error");
243
+ throw new Error(`App authentication failed (${response.status}): ${text}`);
244
+ }
245
+ const data = await response.json();
246
+ if (data.errors?.length) {
247
+ throw new Error(`App authentication failed: ${data.errors[0]?.message ?? "unknown error"}`);
248
+ }
249
+ if (!data.data?.authenticateApp?.accessToken) {
250
+ throw new Error("App authentication failed: no access token returned");
251
+ }
252
+ return data.data.authenticateApp;
253
+ }
254
+ async function issueWorkspaceToken(workspaceEndpoint, authToken, workspaceId, organizationId) {
255
+ const query = `
256
+ mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {
257
+ issueWorkspaceToken(input: $input) {
258
+ success token expiresAt scopes
259
+ error { code message }
260
+ }
261
+ }
262
+ `;
263
+ const response = await fetch(workspaceEndpoint, {
264
+ method: "POST",
265
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
266
+ body: JSON.stringify({ query, variables: { input: { workspaceId, organizationId } } })
267
+ });
268
+ if (!response.ok) {
269
+ const text = await response.text().catch(() => "Unknown error");
270
+ throw new Error(`Workspace token request failed (${response.status}): ${text}`);
271
+ }
272
+ const data = await response.json();
273
+ if (data.errors?.length) {
274
+ throw new Error(`Workspace token failed: ${data.errors[0]?.message ?? "unknown error"}`);
275
+ }
276
+ const result = data.data?.issueWorkspaceToken;
277
+ if (!result?.success || !result.token) {
278
+ throw new Error(`Workspace token failed: ${result?.error?.message ?? "Unknown error"}`);
279
+ }
280
+ return { token: result.token, expiresAt: result.expiresAt ?? "", scopes: result.scopes ?? [] };
281
+ }
282
+ async function fetchWorkspaces(globalEndpoint, authToken) {
283
+ const query = `
284
+ query MyWorkspaces($limit: Int) {
285
+ myWorkspaces(limit: $limit) {
286
+ items { id name slug tenantId organizationId }
287
+ }
288
+ }
289
+ `;
290
+ const response = await fetch(globalEndpoint, {
291
+ method: "POST",
292
+ headers: { "Content-Type": "application/json", Authorization: `Bearer ${authToken}` },
293
+ body: JSON.stringify({ query, variables: { limit: 50 } })
294
+ });
295
+ if (!response.ok) {
296
+ const text = await response.text().catch(() => "Unknown error");
297
+ throw new Error(`Failed to fetch workspaces (${response.status}): ${text}`);
298
+ }
299
+ const data = await response.json();
300
+ if (data.errors?.length) {
301
+ throw new Error(`Failed to fetch workspaces: ${data.errors[0]?.message ?? "unknown error"}`);
302
+ }
303
+ return data.data?.myWorkspaces?.items ?? [];
304
+ }
305
+
306
+ // src/core/gql/client.ts
307
+ var DEFAULT_TIMEOUT = 3e4;
308
+ var MAX_RETRIES = 3;
309
+ var INITIAL_RETRY_DELAY_MS = 1e3;
310
+ function sleep(ms) {
311
+ return new Promise((resolve) => setTimeout(resolve, ms));
312
+ }
313
+ function isNetworkOrServerError(error) {
314
+ if (error instanceof TypeError) return true;
315
+ if (error && typeof error === "object" && "response" in error) {
316
+ const resp = error.response;
317
+ if (resp && typeof resp.status === "number" && resp.status >= 500) return true;
318
+ }
319
+ return false;
320
+ }
321
+ function extractGqlErrorMessage(error) {
322
+ if (error && typeof error === "object" && "response" in error) {
323
+ const resp = error;
324
+ const firstError = resp.response?.errors?.[0];
325
+ if (firstError?.message) return firstError.message;
326
+ if (resp.message) return resp.message;
327
+ }
328
+ if (error instanceof Error) return error.message;
329
+ return String(error);
330
+ }
331
+ function getHeaders(auth) {
332
+ const headers = {};
333
+ if (auth?.apiKey) headers["X-API-Key"] = auth.apiKey;
334
+ if (auth?.accessToken) headers["Authorization"] = `Bearer ${auth.accessToken}`;
335
+ if (auth?.organizationId) headers["x-org-id"] = auth.organizationId;
336
+ return headers;
337
+ }
338
+ function getWorkspaceHeaders(auth) {
339
+ const headers = getHeaders(auth);
340
+ if (auth?.workspaceToken) {
341
+ headers["X-Workspace-Authorization"] = `Bearer ${auth.workspaceToken}`;
342
+ }
343
+ if (auth?.workspaceId) headers["x-workspace-id"] = auth.workspaceId;
344
+ return headers;
345
+ }
346
+ async function executeWithRetry(client, document, variables) {
347
+ let lastError;
348
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
349
+ try {
350
+ const controller = new AbortController();
351
+ const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT);
352
+ try {
353
+ return await client.request({ document, variables, signal: controller.signal });
354
+ } finally {
355
+ clearTimeout(timer);
356
+ }
357
+ } catch (error) {
358
+ lastError = error;
359
+ if (error && typeof error === "object" && "response" in error) {
360
+ const resp = error.response;
361
+ if (resp && typeof resp.status === "number" && resp.status >= 400 && resp.status < 500) {
362
+ break;
363
+ }
364
+ }
365
+ if (isNetworkOrServerError(error) && attempt < MAX_RETRIES - 1) {
366
+ const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);
367
+ await sleep(delay);
368
+ continue;
369
+ }
370
+ break;
371
+ }
372
+ }
373
+ throw new Error(extractGqlErrorMessage(lastError));
374
+ }
375
+ function createGqlClients(config, authStore) {
376
+ let workspaceClient = null;
377
+ let globalClient = null;
378
+ function init() {
379
+ const cfg = config.read();
380
+ const auth = authStore.read();
381
+ workspaceClient = new GraphQLClient(cfg.workspaceEndpoint);
382
+ workspaceClient.setHeaders(getWorkspaceHeaders(auth));
383
+ globalClient = new GraphQLClient(cfg.globalEndpoint);
384
+ globalClient.setHeaders(getHeaders(auth));
385
+ return { workspace: workspaceClient, global: globalClient };
386
+ }
387
+ async function refreshPlatformToken() {
388
+ const auth = authStore.read();
389
+ if (!auth) return;
390
+ if (auth.authMethod === "client_credentials" && auth.clientId && auth.clientSecret) {
391
+ const cfg2 = config.read();
392
+ try {
393
+ const result = await clientCredentialsFlow(
394
+ cfg2.globalEndpoint,
395
+ auth.clientId,
396
+ auth.clientSecret
397
+ );
398
+ authStore.write({
399
+ ...auth,
400
+ accessToken: result.accessToken,
401
+ expiresAt: Date.now() + result.expiresIn * 1e3
402
+ });
403
+ workspaceClient = null;
404
+ globalClient = null;
405
+ } catch {
406
+ }
407
+ return;
408
+ }
409
+ if (!auth.refreshToken) return;
410
+ const cfg = config.read();
411
+ const client = new GraphQLClient(cfg.globalEndpoint);
412
+ client.setHeaders({ Authorization: `Bearer ${auth.accessToken}` });
413
+ const REFRESH_MUTATION = `
414
+ mutation RefreshToken($token: String!) {
415
+ refreshToken(token: $token) { accessToken refreshToken expiresIn }
416
+ }
417
+ `;
418
+ try {
419
+ const data = await client.request(REFRESH_MUTATION, {
420
+ token: auth.refreshToken
421
+ });
422
+ authStore.write({
423
+ ...auth,
424
+ accessToken: data.refreshToken.accessToken,
425
+ refreshToken: data.refreshToken.refreshToken,
426
+ expiresAt: Date.now() + data.refreshToken.expiresIn * 1e3
427
+ });
428
+ workspaceClient = null;
429
+ globalClient = null;
430
+ } catch {
431
+ }
432
+ }
433
+ async function refreshWorkspaceToken() {
434
+ const auth = authStore.read();
435
+ if (!auth?.accessToken || !auth.workspaceId || !auth.organizationId) return;
436
+ const cfg = config.read();
437
+ try {
438
+ const result = await issueWorkspaceToken(
439
+ cfg.workspaceEndpoint,
440
+ auth.accessToken,
441
+ auth.workspaceId,
442
+ auth.organizationId
443
+ );
444
+ authStore.write({
445
+ ...auth,
446
+ workspaceToken: result.token,
447
+ workspaceTokenExpiresAt: new Date(result.expiresAt).getTime()
448
+ });
449
+ workspaceClient = null;
450
+ } catch {
451
+ }
452
+ }
453
+ async function ensureFreshTokens() {
454
+ const initial = authStore.read();
455
+ if (initial?.apiKey) return;
456
+ if (authStore.isTokenExpiringSoon()) {
457
+ await refreshPlatformToken();
458
+ }
459
+ if (authStore.isWorkspaceTokenExpiringSoon()) {
460
+ await refreshWorkspaceToken();
461
+ }
462
+ }
463
+ const workspace = {
464
+ async request(document, variables) {
465
+ await ensureFreshTokens();
466
+ const { workspace: ws } = workspaceClient ? { workspace: workspaceClient } : init();
467
+ ws.setHeaders(getWorkspaceHeaders(authStore.read()));
468
+ return executeWithRetry(ws, document, variables);
469
+ }
470
+ };
471
+ const global = {
472
+ async request(document, variables) {
473
+ const { global: g } = globalClient ? { global: globalClient } : init();
474
+ g.setHeaders(getHeaders(authStore.read()));
475
+ return executeWithRetry(g, document, variables);
476
+ }
477
+ };
478
+ const workspaceAuthOnly = {
479
+ async request(document, variables) {
480
+ const cfg = config.read();
481
+ const auth = authStore.read();
482
+ const client = new GraphQLClient(cfg.workspaceEndpoint);
483
+ client.setHeaders(getHeaders(auth));
484
+ return executeWithRetry(client, document, variables);
485
+ }
486
+ };
487
+ return {
488
+ workspace,
489
+ global,
490
+ workspaceAuthOnly,
491
+ reset() {
492
+ workspaceClient = null;
493
+ globalClient = null;
494
+ }
495
+ };
496
+ }
497
+
498
+ // src/core/logger.ts
499
+ var LEVEL_RANK = {
500
+ error: 0,
501
+ warn: 1,
502
+ info: 2,
503
+ debug: 3
504
+ };
505
+ function createLogger(opts = {}) {
506
+ let level = opts.level ?? process.env.LOG_LEVEL ?? "info";
507
+ const format = opts.format ?? process.env.LOG_FORMAT ?? "json";
508
+ function shouldLog(target) {
509
+ return LEVEL_RANK[target] <= LEVEL_RANK[level];
510
+ }
511
+ function formatMessage(target, message, context) {
512
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
513
+ if (format === "json") {
514
+ return JSON.stringify({ timestamp, level: target, message, ...context });
515
+ }
516
+ const contextStr = context ? ` ${JSON.stringify(context)}` : "";
517
+ return `[${timestamp}] ${target.toUpperCase()}: ${message}${contextStr}`;
518
+ }
519
+ function emit(target, message, context) {
520
+ if (!shouldLog(target)) return;
521
+ process.stderr.write(formatMessage(target, message, context) + "\n");
522
+ }
523
+ return {
524
+ error(message, context) {
525
+ emit("error", message, context);
526
+ },
527
+ warn(message, context) {
528
+ emit("warn", message, context);
529
+ },
530
+ info(message, context) {
531
+ emit("info", message, context);
532
+ },
533
+ debug(message, context) {
534
+ emit("debug", message, context);
535
+ },
536
+ setLevel(newLevel) {
537
+ level = newLevel;
538
+ },
539
+ getLevel() {
540
+ return level;
541
+ }
542
+ };
543
+ }
544
+
545
+ // src/core/progress.ts
546
+ function createProgress(serverRef) {
547
+ return (token, current, total, message) => {
548
+ if (token === void 0 || token === null) return;
549
+ const server = serverRef.current;
550
+ if (!server) return;
551
+ try {
552
+ const params = { progressToken: token, progress: current };
553
+ if (total !== void 0) params.total = total;
554
+ if (message !== void 0) params.message = message;
555
+ const inner = server.server ?? server;
556
+ inner.notification?.({ method: "notifications/progress", params });
557
+ } catch {
558
+ }
559
+ };
560
+ }
561
+
562
+ // src/core/context.ts
563
+ function inferEnv(workspaceEndpoint) {
564
+ if (workspaceEndpoint.includes("localhost") || workspaceEndpoint.includes("127.0.0.1")) {
565
+ return "local";
566
+ }
567
+ if (workspaceEndpoint.includes("alpha")) return "alpha";
568
+ return "prod";
569
+ }
570
+ function isLogger(value) {
571
+ return !!value && typeof value.debug === "function" && typeof value.info === "function";
572
+ }
573
+ function buildContext(opts) {
574
+ const config = createConfigStore(opts.defaults);
575
+ const cfg = config.read();
576
+ const logger = isLogger(opts.logger) ? opts.logger : createLogger({
577
+ ...opts.logger,
578
+ level: cfg.logLevel,
579
+ format: cfg.logFormat
580
+ });
581
+ const auth = createAuthStore(
582
+ opts.tokenStorePath ? dirOf(opts.tokenStorePath) : config.dir(),
583
+ authFileName(opts.tokenStorePath)
584
+ );
585
+ const existing = auth.read();
586
+ if (!existing && (cfg.accessToken || cfg.apiKey)) {
587
+ auth.write({
588
+ accessToken: cfg.accessToken ?? "",
589
+ refreshToken: cfg.refreshToken ?? "",
590
+ ...cfg.workspaceToken ? { workspaceToken: cfg.workspaceToken } : {},
591
+ ...cfg.workspaceId ? { workspaceId: cfg.workspaceId } : {},
592
+ ...cfg.organizationId ? { organizationId: cfg.organizationId } : {},
593
+ ...cfg.apiKey ? { apiKey: cfg.apiKey, authMethod: "api_key" } : {}
594
+ });
595
+ }
596
+ const gql = createGqlClients(config, auth);
597
+ const env = opts.env ?? inferEnv(cfg.workspaceEndpoint);
598
+ const serverRef = { current: null };
599
+ const progress = createProgress(serverRef);
600
+ return {
601
+ productName: opts.productName,
602
+ productVersion: opts.productVersion,
603
+ serverName: opts.serverName,
604
+ serverVersion: opts.serverVersion,
605
+ defaults: opts.defaults,
606
+ config,
607
+ auth,
608
+ gql,
609
+ logger,
610
+ progress,
611
+ env,
612
+ _internal: { serverRef }
613
+ };
614
+ }
615
+ function dirOf(p) {
616
+ const lastSlash = p.lastIndexOf("/");
617
+ return lastSlash > 0 ? p.slice(0, lastSlash) : p;
618
+ }
619
+ function authFileName(p) {
620
+ if (!p) return void 0;
621
+ const lastSlash = p.lastIndexOf("/");
622
+ return lastSlash >= 0 ? p.slice(lastSlash + 1) : p;
623
+ }
624
+
625
+ // src/core/errors.ts
626
+ var McpUserError = class extends Error {
627
+ hint;
628
+ constructor(message, opts) {
629
+ super(message);
630
+ this.name = "McpUserError";
631
+ this.hint = opts?.hint;
632
+ }
633
+ };
634
+ var McpAuthError = class extends McpUserError {
635
+ constructor(message, opts) {
636
+ super(message, {
637
+ hint: opts?.hint ?? "Run the auth_login tool to authenticate."
638
+ });
639
+ this.name = "McpAuthError";
640
+ }
641
+ };
642
+ var McpInternalError = class extends Error {
643
+ cause;
644
+ constructor(message, cause) {
645
+ super(message);
646
+ this.name = "McpInternalError";
647
+ this.cause = cause;
648
+ }
649
+ };
650
+
651
+ // src/core/module.ts
652
+ var MissingDependencyError = class extends McpInternalError {
653
+ constructor(moduleId, missingDep) {
654
+ super(
655
+ `Module '${moduleId}' declares dependency on '${missingDep}', but '${missingDep}' is not in the module list.`
656
+ );
657
+ this.name = "MissingDependencyError";
658
+ }
659
+ };
660
+ var CircularDependencyError = class extends McpInternalError {
661
+ constructor(cycle) {
662
+ super(`Circular dependency detected among modules: ${cycle.join(" -> ")}`);
663
+ this.name = "CircularDependencyError";
664
+ }
665
+ };
666
+ function sortModules(modules) {
667
+ const byId = /* @__PURE__ */ new Map();
668
+ for (const m of modules) {
669
+ if (byId.has(m.id)) {
670
+ throw new McpInternalError(`Duplicate module id: '${m.id}'`);
671
+ }
672
+ byId.set(m.id, m);
673
+ }
674
+ for (const m of modules) {
675
+ for (const dep of m.dependsOn ?? []) {
676
+ if (!byId.has(dep)) {
677
+ throw new MissingDependencyError(m.id, dep);
678
+ }
679
+ }
680
+ }
681
+ const sorted = [];
682
+ const visiting = /* @__PURE__ */ new Set();
683
+ const visited = /* @__PURE__ */ new Set();
684
+ function visit(m, path) {
685
+ if (visited.has(m.id)) return;
686
+ if (visiting.has(m.id)) {
687
+ throw new CircularDependencyError([...path, m.id]);
688
+ }
689
+ visiting.add(m.id);
690
+ for (const dep of m.dependsOn ?? []) {
691
+ const depModule = byId.get(dep);
692
+ if (depModule) visit(depModule, [...path, m.id]);
693
+ }
694
+ visiting.delete(m.id);
695
+ visited.add(m.id);
696
+ sorted.push(m);
697
+ }
698
+ for (const m of modules) {
699
+ visit(m, []);
700
+ }
701
+ return sorted;
702
+ }
703
+
704
+ // src/core/capabilities.ts
705
+ function unionCapabilities(caps) {
706
+ const out = {};
707
+ for (const cap of caps) {
708
+ if (!cap) continue;
709
+ if (cap.resources) {
710
+ out.resources ??= {};
711
+ if (cap.resources.subscribe) out.resources.subscribe = true;
712
+ if (cap.resources.listChanged) out.resources.listChanged = true;
713
+ }
714
+ if (cap.prompts) {
715
+ out.prompts ??= {};
716
+ if (cap.prompts.listChanged) out.prompts.listChanged = true;
717
+ }
718
+ if (cap.tools) {
719
+ out.tools ??= {};
720
+ if (cap.tools.listChanged) out.tools.listChanged = true;
721
+ }
722
+ if (cap.logging) out.logging = true;
723
+ if (cap.completions) out.completions = true;
724
+ }
725
+ return out;
726
+ }
727
+ function toServerCapabilities(caps) {
728
+ const out = {};
729
+ if (caps.tools) out.tools = caps.tools;
730
+ if (caps.resources) out.resources = caps.resources;
731
+ if (caps.prompts) out.prompts = caps.prompts;
732
+ if (caps.logging) out.logging = {};
733
+ if (caps.completions) out.completions = {};
734
+ return out;
735
+ }
736
+
737
+ // src/core/server.ts
738
+ var MCP_TO_LOGGER_LEVEL = {
739
+ debug: "debug",
740
+ info: "info",
741
+ notice: "info",
742
+ warning: "warn",
743
+ error: "error",
744
+ critical: "error",
745
+ alert: "error",
746
+ emergency: "error"
747
+ };
748
+ function createMcpServer(ctx, modules, opts) {
749
+ const sorted = sortModules(modules);
750
+ const baseCapabilities = { logging: true };
751
+ const capabilities = unionCapabilities([
752
+ baseCapabilities,
753
+ ...sorted.map((m) => m.capabilities),
754
+ opts.extraCapabilities
755
+ ]);
756
+ const server = new McpServer(
757
+ { name: opts.name, version: opts.version },
758
+ { capabilities: toServerCapabilities(capabilities) }
759
+ );
760
+ ctx._internal.serverRef.current = server;
761
+ const inner = server.server ?? server;
762
+ if (typeof inner.setRequestHandler === "function") {
763
+ inner.setRequestHandler(
764
+ SetLevelRequestSchema,
765
+ async (req) => {
766
+ const target = MCP_TO_LOGGER_LEVEL[req.params.level] ?? "info";
767
+ ctx.logger.setLevel(target);
768
+ ctx.logger.info("MCP logging level set", { level: req.params.level, mapped: target });
769
+ return {};
770
+ }
771
+ );
772
+ }
773
+ const tools = [];
774
+ const resources = [];
775
+ const prompts = [];
776
+ const moduleManifest = [];
777
+ for (const mod of sorted) {
778
+ try {
779
+ const reg = mod.register(server, ctx);
780
+ tools.push(...reg.tools);
781
+ resources.push(...reg.resources);
782
+ prompts.push(...reg.prompts);
783
+ moduleManifest.push({ id: mod.id, version: mod.version });
784
+ ctx.logger.debug(`Registered module: ${mod.id}`, {
785
+ tools: reg.tools.length,
786
+ resources: reg.resources.length,
787
+ prompts: reg.prompts.length
788
+ });
789
+ } catch (error) {
790
+ ctx.logger.error(`Failed to register module: ${mod.id}`, {
791
+ error: error instanceof Error ? error.message : String(error)
792
+ });
793
+ throw error;
794
+ }
795
+ }
796
+ const manifest = {
797
+ modules: moduleManifest,
798
+ tools,
799
+ resources,
800
+ prompts
801
+ };
802
+ ctx.logger.info(`MCP server ready: ${opts.name}@${opts.version}`, {
803
+ modules: manifest.modules.length,
804
+ tools: manifest.tools.length,
805
+ resources: manifest.resources.length,
806
+ prompts: manifest.prompts.length
807
+ });
808
+ return { server, manifest };
809
+ }
810
+
811
+ // src/core/result.ts
812
+ function jsonResult(data, structured) {
813
+ const result = {
814
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
815
+ };
816
+ if (structured !== void 0) {
817
+ result.structuredContent = structured;
818
+ }
819
+ return result;
820
+ }
821
+ function textResult(text) {
822
+ return { content: [{ type: "text", text }] };
823
+ }
824
+ function errorResult(message, hint) {
825
+ const text = hint ? `${message}
826
+
827
+ Hint: ${hint}` : message;
828
+ return { content: [{ type: "text", text }], isError: true };
829
+ }
830
+ function registerTool(server, ctx, name, metadata, handler) {
831
+ const sdkConfig = {
832
+ title: metadata.title,
833
+ description: metadata.description,
834
+ ...metadata.inputSchema ? { inputSchema: metadata.inputSchema } : {}
835
+ };
836
+ const wrapped = async (...callbackArgs) => {
837
+ const hasArgs = callbackArgs.length === 2;
838
+ const args = hasArgs ? callbackArgs[0] : {};
839
+ const extra = hasArgs ? callbackArgs[1] : callbackArgs[0];
840
+ const progressToken = extra?._meta?.progressToken;
841
+ const meta = progressToken !== void 0 ? { progressToken } : {};
842
+ try {
843
+ const result = await handler(args, ctx, meta);
844
+ if (isToolResult(result)) return result;
845
+ if (result === void 0) return textResult("OK");
846
+ return jsonResult(result);
847
+ } catch (error) {
848
+ return mapErrorToResult(error, ctx, name);
849
+ }
850
+ };
851
+ server.registerTool(name, sdkConfig, wrapped);
852
+ }
853
+ function isToolResult(value) {
854
+ return !!value && typeof value === "object" && "content" in value && Array.isArray(value.content);
855
+ }
856
+ function mapErrorToResult(error, ctx, toolName) {
857
+ if (error instanceof McpAuthError) {
858
+ ctx.logger.warn(`${toolName}: auth required`, { message: error.message });
859
+ return errorResult(error.message, error.hint);
860
+ }
861
+ if (error instanceof McpUserError) {
862
+ ctx.logger.info(`${toolName}: user error`, { message: error.message });
863
+ return errorResult(error.message, error.hint);
864
+ }
865
+ if (error instanceof McpInternalError) {
866
+ ctx.logger.error(`${toolName}: internal error`, {
867
+ message: error.message,
868
+ cause: stringifyCause(error.cause)
869
+ });
870
+ return errorResult(`Internal error in ${toolName}.`);
871
+ }
872
+ const message = error instanceof Error ? error.message : String(error);
873
+ ctx.logger.error(`${toolName}: unhandled error`, { message });
874
+ return errorResult(`${toolName}: ${message}`);
875
+ }
876
+ function stringifyCause(cause) {
877
+ if (cause === void 0 || cause === null) return void 0;
878
+ if (cause instanceof Error) return cause.message;
879
+ try {
880
+ return JSON.stringify(cause);
881
+ } catch {
882
+ return String(cause);
883
+ }
884
+ }
885
+
886
+ // src/core/tool-name.ts
887
+ var MAX_TOOL_NAME_LENGTH = 63;
888
+ function assertSafeName(name, kind) {
889
+ if (name.length > MAX_TOOL_NAME_LENGTH) {
890
+ throw new McpInternalError(
891
+ `Tool name '${name}' exceeds ${MAX_TOOL_NAME_LENGTH} characters (some MCP clients truncate at 64).`
892
+ );
893
+ }
894
+ return name;
895
+ }
896
+ function mcpToolName(productName, ...parts) {
897
+ if (!productName) {
898
+ throw new McpInternalError("mcpToolName: productName is required");
899
+ }
900
+ const name = [productName, ...parts].filter(Boolean).join("_");
901
+ return assertSafeName(name);
902
+ }
903
+ function mcpResourceUri(productName, ...parts) {
904
+ if (!productName) {
905
+ throw new McpInternalError("mcpResourceUri: productName is required");
906
+ }
907
+ return `${productName}://${parts.filter(Boolean).join("/")}`;
908
+ }
909
+ function mcpPromptName(productName, ...parts) {
910
+ if (!productName) {
911
+ throw new McpInternalError("mcpPromptName: productName is required");
912
+ }
913
+ return [productName, ...parts].filter(Boolean).join("-");
914
+ }
915
+ var TOOL_NAME_LIMIT = MAX_TOOL_NAME_LENGTH;
916
+
917
+ export { CircularDependencyError, McpAuthError, McpInternalError, McpUserError, MissingDependencyError, TOOL_NAME_LIMIT, buildContext, clientCredentialsFlow, createAuthStore, createConfigStore, createGqlClients, createLogger, createMcpServer, createProgress, errorResult, extractGqlErrorMessage, fetchWorkspaces, issueWorkspaceToken, jsonResult, mcpPromptName, mcpResourceUri, mcpToolName, pollDeviceTokenOnce, registerTool, sortModules, startDeviceCodeFlow, textResult, toServerCapabilities, unionCapabilities };
918
+ //# sourceMappingURL=chunk-H2OYWLOA.js.map
919
+ //# sourceMappingURL=chunk-H2OYWLOA.js.map