@burdenoff/mcp-libs 2026.825.1 → 2026.825.3

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 (123) hide show
  1. package/dist/{chunk-YOSQUY3M.js → chunk-BSNL65PZ.js} +2 -2
  2. package/dist/{chunk-YOSQUY3M.js.map → chunk-BSNL65PZ.js.map} +1 -1
  3. package/dist/{chunk-RHWHUY5Y.js → chunk-QQYJVKJE.js} +3 -3
  4. package/dist/{chunk-RHWHUY5Y.js.map → chunk-QQYJVKJE.js.map} +1 -1
  5. package/dist/core/index.cjs.map +1 -1
  6. package/dist/core/index.js +1 -1
  7. package/dist/index.cjs.map +1 -1
  8. package/dist/index.js +1 -1
  9. package/dist/modules/adaptercloud/index.cjs +20 -6
  10. package/dist/modules/adaptercloud/index.cjs.map +1 -1
  11. package/dist/modules/adaptercloud/index.js +21 -7
  12. package/dist/modules/adaptercloud/index.js.map +1 -1
  13. package/dist/modules/artistrybase/index.cjs.map +1 -1
  14. package/dist/modules/artistrybase/index.js +1 -1
  15. package/dist/modules/assethandler/index.cjs.map +1 -1
  16. package/dist/modules/assethandler/index.js +1 -1
  17. package/dist/modules/atheletebridge/index.cjs.map +1 -1
  18. package/dist/modules/atheletebridge/index.js +1 -1
  19. package/dist/modules/auth/index.cjs.map +1 -1
  20. package/dist/modules/auth/index.js +3 -3
  21. package/dist/modules/billing/index.cjs.map +1 -1
  22. package/dist/modules/billing/index.js +1 -1
  23. package/dist/modules/brainyrich/index.cjs +13 -3
  24. package/dist/modules/brainyrich/index.cjs.map +1 -1
  25. package/dist/modules/brainyrich/index.js +14 -4
  26. package/dist/modules/brainyrich/index.js.map +1 -1
  27. package/dist/modules/buildmyiq/index.cjs.map +1 -1
  28. package/dist/modules/buildmyiq/index.js +1 -1
  29. package/dist/modules/channels/index.cjs.map +1 -1
  30. package/dist/modules/channels/index.js +1 -1
  31. package/dist/modules/collabkin/index.cjs.map +1 -1
  32. package/dist/modules/collabkin/index.js +1 -1
  33. package/dist/modules/comradecircle/index.cjs.map +1 -1
  34. package/dist/modules/comradecircle/index.js +1 -1
  35. package/dist/modules/conversations/index.cjs.map +1 -1
  36. package/dist/modules/conversations/index.js +1 -1
  37. package/dist/modules/coolandlovely/index.cjs.map +1 -1
  38. package/dist/modules/coolandlovely/index.js +1 -1
  39. package/dist/modules/cosmicintersection/index.cjs.map +1 -1
  40. package/dist/modules/cosmicintersection/index.js +1 -1
  41. package/dist/modules/crewfoundry/index.cjs.map +1 -1
  42. package/dist/modules/crewfoundry/index.js +1 -1
  43. package/dist/modules/devportal/index.cjs.map +1 -1
  44. package/dist/modules/devportal/index.js +1 -1
  45. package/dist/modules/ecoimpacthub/index.cjs.map +1 -1
  46. package/dist/modules/ecoimpacthub/index.js +1 -1
  47. package/dist/modules/eventfullymanaged/index.cjs.map +1 -1
  48. package/dist/modules/eventfullymanaged/index.js +1 -1
  49. package/dist/modules/export/index.cjs.map +1 -1
  50. package/dist/modules/export/index.js +1 -1
  51. package/dist/modules/files/index.cjs.map +1 -1
  52. package/dist/modules/files/index.js +1 -1
  53. package/dist/modules/ggnomad/index.cjs.map +1 -1
  54. package/dist/modules/ggnomad/index.js +1 -1
  55. package/dist/modules/govcitizenhub/index.cjs.map +1 -1
  56. package/dist/modules/govcitizenhub/index.js +1 -1
  57. package/dist/modules/groups/index.cjs.map +1 -1
  58. package/dist/modules/groups/index.js +1 -1
  59. package/dist/modules/headshotmarketing/index.cjs.map +1 -1
  60. package/dist/modules/headshotmarketing/index.js +1 -1
  61. package/dist/modules/health/index.cjs.map +1 -1
  62. package/dist/modules/health/index.js +1 -1
  63. package/dist/modules/hookmovies/index.cjs.map +1 -1
  64. package/dist/modules/hookmovies/index.js +1 -1
  65. package/dist/modules/housingvista/index.cjs.map +1 -1
  66. package/dist/modules/housingvista/index.js +1 -1
  67. package/dist/modules/integrations/index.cjs.map +1 -1
  68. package/dist/modules/integrations/index.js +1 -1
  69. package/dist/modules/intelwatchtower/index.cjs.map +1 -1
  70. package/dist/modules/intelwatchtower/index.js +1 -1
  71. package/dist/modules/kadaikodi/index.cjs.map +1 -1
  72. package/dist/modules/kadaikodi/index.js +1 -1
  73. package/dist/modules/labsofscience/index.cjs.map +1 -1
  74. package/dist/modules/labsofscience/index.js +1 -1
  75. package/dist/modules/manufacturedops/index.cjs.map +1 -1
  76. package/dist/modules/manufacturedops/index.js +1 -1
  77. package/dist/modules/movethewheels/index.cjs.map +1 -1
  78. package/dist/modules/movethewheels/index.js +1 -1
  79. package/dist/modules/mybodyshield/index.cjs.map +1 -1
  80. package/dist/modules/mybodyshield/index.js +1 -1
  81. package/dist/modules/notifications/index.cjs.map +1 -1
  82. package/dist/modules/notifications/index.js +1 -1
  83. package/dist/modules/organizations/index.cjs.map +1 -1
  84. package/dist/modules/organizations/index.js +1 -1
  85. package/dist/modules/planmagnet/index.cjs.map +1 -1
  86. package/dist/modules/planmagnet/index.js +1 -1
  87. package/dist/modules/products/index.cjs.map +1 -1
  88. package/dist/modules/products/index.js +1 -1
  89. package/dist/modules/proserviceworld/index.cjs.map +1 -1
  90. package/dist/modules/proserviceworld/index.js +1 -1
  91. package/dist/modules/rbac/index.cjs.map +1 -1
  92. package/dist/modules/rbac/index.js +1 -1
  93. package/dist/modules/sandbox/index.cjs.map +1 -1
  94. package/dist/modules/sandbox/index.js +1 -1
  95. package/dist/modules/scheduler/index.cjs.map +1 -1
  96. package/dist/modules/scheduler/index.js +1 -1
  97. package/dist/modules/security/index.cjs.map +1 -1
  98. package/dist/modules/security/index.js +1 -1
  99. package/dist/modules/semanticfed/index.cjs.map +1 -1
  100. package/dist/modules/semanticfed/index.js +1 -1
  101. package/dist/modules/store/index.cjs.map +1 -1
  102. package/dist/modules/store/index.js +1 -1
  103. package/dist/modules/subscriberbot/index.cjs.map +1 -1
  104. package/dist/modules/subscriberbot/index.js +1 -1
  105. package/dist/modules/support/index.cjs.map +1 -1
  106. package/dist/modules/support/index.js +1 -1
  107. package/dist/modules/tags/index.cjs.map +1 -1
  108. package/dist/modules/tags/index.js +1 -1
  109. package/dist/modules/technospam/index.cjs.map +1 -1
  110. package/dist/modules/technospam/index.js +1 -1
  111. package/dist/modules/theculturepost/index.cjs.map +1 -1
  112. package/dist/modules/theculturepost/index.js +1 -1
  113. package/dist/modules/theglobalfuel/index.cjs.map +1 -1
  114. package/dist/modules/theglobalfuel/index.js +1 -1
  115. package/dist/modules/timecampus/index.cjs.map +1 -1
  116. package/dist/modules/timecampus/index.js +1 -1
  117. package/dist/modules/tours/index.cjs.map +1 -1
  118. package/dist/modules/tours/index.js +1 -1
  119. package/dist/modules/vibecontrols/index.cjs.map +1 -1
  120. package/dist/modules/vibecontrols/index.js +2 -2
  121. package/dist/modules/workspaces/index.cjs.map +1 -1
  122. package/dist/modules/workspaces/index.js +1 -1
  123. package/package.json +28 -15
@@ -981,5 +981,5 @@ function stringifyCause(cause) {
981
981
  }
982
982
 
983
983
  export { CircularDependencyError, McpAuthError, McpInternalError, McpUserError, MissingDependencyError, TOOL_NAME_LIMIT, buildContext, clientCredentialsFlow, createAuthStore, createConfigStore, createGqlClients, createLogger, createMcpServer, createProgress, errorResult, extractGqlErrorMessage, fetchWorkspaces, inferDestructiveHint, inferReadOnlyHint, issueWorkspaceToken, jsonResult, mcpPromptName, mcpResourceUri, mcpToolName, pollDeviceTokenOnce, registerTool, sortModules, startDeviceCodeFlow, textResult, toServerCapabilities, unionCapabilities, wrapServerWithToolGovernance };
984
- //# sourceMappingURL=chunk-YOSQUY3M.js.map
985
- //# sourceMappingURL=chunk-YOSQUY3M.js.map
984
+ //# sourceMappingURL=chunk-BSNL65PZ.js.map
985
+ //# sourceMappingURL=chunk-BSNL65PZ.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/core/auth/store.ts","../src/core/config/store.ts","../src/core/auth/device-code.ts","../src/core/gql/client.ts","../src/core/logger.ts","../src/core/progress.ts","../src/core/context.ts","../src/core/errors.ts","../src/core/module.ts","../src/core/capabilities.ts","../src/core/tool-name.ts","../src/core/tool-governance.ts","../src/core/server.ts","../src/core/result.ts"],"names":["authFileName","join","existsSync","mkdirSync","readFileSync","writeFileSync","chmodSync","cfg"],"mappings":";;;;;;;;;;AAyCA,IAAM,eAAA,GAAkB,IAAI,EAAA,GAAK,GAAA;AAE1B,SAAS,eAAA,CAAgB,SAAA,EAAmBA,aAAAA,GAAe,WAAA,EAAwB;AACxF,EAAA,MAAM,QAAA,GAAW,IAAA,CAAK,SAAA,EAAWA,aAAY,CAAA;AAE7C,EAAA,SAAS,eAAA,GAAwB;AAC/B,IAAA,IAAI,CAAC,UAAA,CAAW,SAAS,CAAA,EAAG;AAC1B,MAAA,SAAA,CAAU,WAAW,EAAE,SAAA,EAAW,IAAA,EAAM,IAAA,EAAM,KAAO,CAAA;AAAA,IACvD;AAAA,EACF;AAEA,EAAA,SAAS,IAAA,GAA0B;AACjC,IAAA,IAAI;AACF,MAAA,IAAI,CAAC,UAAA,CAAW,QAAQ,CAAA,EAAG,OAAO,IAAA;AAClC,MAAA,MAAM,GAAA,GAAM,YAAA,CAAa,QAAA,EAAU,MAAM,CAAA;AACzC,MAAA,OAAO,IAAA,CAAK,MAAM,GAAG,CAAA;AAAA,IACvB,CAAA,CAAA,MAAQ;AACN,MAAA,OAAO,IAAA;AAAA,IACT;AAAA,EACF;AAEA,EAAA,SAAS,MAAM,IAAA,EAAwB;AACrC,IAAA,eAAA,EAAgB;AAChB,IAAA,aAAA,CAAc,QAAA,EAAU,IAAA,CAAK,SAAA,CAAU,IAAA,EAAM,IAAA,EAAM,CAAC,CAAA,EAAG,EAAE,QAAA,EAAU,MAAA,EAAQ,IAAA,EAAM,GAAA,EAAO,CAAA;AACxF,IAAA,IAAI;AACF,MAAA,SAAA,CAAU,UAAU,GAAK,CAAA;AAAA,IAC3B,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AAEA,EAAA,SAAS,KAAA,GAAc;AACrB,IAAA,IAAI;AACF,MAAA,IAAI,UAAA,CAA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AA,CAAY,KAAA,CAAM,OAAA,EAAS,KAAA,CAAM,IAAI,CAAA;AAAA,EAC9C;AACA,EAAA,IAAI,iBAAiB,gBAAA,EAAkB;AACrC,IAAA,GAAA,CAAI,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,QAAQ,CAAA,gBAAA,CAAA,EAAoB;AAAA,MAC9C,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,KAAA,EAAO,cAAA,CAAe,KAAA,CAAM,KAAK;AAAA,KAClC,CAAA;AACD,IAAA,OAAO,WAAA,CAAY,CAAA,kBAAA,EAAqB,QAAQ,CAAA,CAAA,CAAG,CAAA;AAAA,EACrD;AACA,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,GAAA,CAAI,OAAO,KAAA,CAAM,CAAA,EAAG,QAAQ,CAAA,iBAAA,CAAA,EAAqB,EAAE,SAAS,CAAA;AAC5D,EAAA,OAAO,WAAA,CAAY,CAAA,EAAG,QAAQ,CAAA,EAAA,EAAK,OAAO,CAAA,CAAE,CAAA;AAC9C;AAEA,SAAS,eAAe,KAAA,EAAoC;AAC1D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM,OAAO,MAAA;AAClD,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACF","file":"chunk-YOSQUY3M.js","sourcesContent":["/**\n * Auth token persistence — parameterised on configDir.\n *\n * Stores tokens in <configDir>/auth.json with 0o600 perms.\n *\n * StoredAuth shape is a SUPERSET of cli-sdk's StoredAuth (adds api_key auth\n * method + apiKey field). A parity test in tests/unit/auth-store-parity.test.ts\n * keeps the field set in sync with cli-sdk so a shared token store path\n * (vibecontrols-cli/auth.json) works for both consumers.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, unlinkSync } from 'fs';\nimport { join } from 'path';\n\nexport type AuthMethod = 'device_code' | 'client_credentials' | 'api_key';\n\nexport interface StoredAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt?: number;\n workspaceToken?: string;\n workspaceTokenExpiresAt?: number;\n workspaceId?: string;\n organizationId?: string;\n authMethod?: AuthMethod;\n clientId?: string;\n clientSecret?: string;\n apiKey?: string;\n}\n\nexport interface AuthStore {\n read(): StoredAuth | null;\n write(auth: StoredAuth): void;\n clear(): void;\n isTokenExpired(): boolean;\n isTokenExpiringSoon(): boolean;\n isWorkspaceTokenExpired(): boolean;\n isWorkspaceTokenExpiringSoon(): boolean;\n isAuthenticated(): boolean;\n}\n\nconst TOKEN_BUFFER_MS = 5 * 60 * 1000;\n\nexport function createAuthStore(configDir: string, authFileName = 'auth.json'): AuthStore {\n const authFile = join(configDir, authFileName);\n\n function ensureConfigDir(): void {\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true, mode: 0o700 });\n }\n }\n\n function read(): StoredAuth | null {\n try {\n if (!existsSync(authFile)) return null;\n const raw = readFileSync(authFile, 'utf8');\n return JSON.parse(raw) as StoredAuth;\n } catch {\n return null;\n }\n }\n\n function write(auth: StoredAuth): void {\n ensureConfigDir();\n writeFileSync(authFile, JSON.stringify(auth, null, 2), { encoding: 'utf8', mode: 0o600 });\n try {\n chmodSync(authFile, 0o600);\n } catch {\n // chmod may fail on Windows; non-critical.\n }\n }\n\n function clear(): void {\n try {\n if (existsSync(authFile)) unlinkSync(authFile);\n } catch {\n // ignore\n }\n }\n\n function isTokenExpired(): boolean {\n const auth = read();\n if (!auth?.expiresAt) return false;\n return Date.now() >= auth.expiresAt;\n }\n\n function isTokenExpiringSoon(): boolean {\n const auth = read();\n if (!auth?.expiresAt) return false;\n return Date.now() + TOKEN_BUFFER_MS >= auth.expiresAt;\n }\n\n function isWorkspaceTokenExpired(): boolean {\n const auth = read();\n if (!auth?.workspaceTokenExpiresAt) return false;\n return Date.now() >= auth.workspaceTokenExpiresAt;\n }\n\n function isWorkspaceTokenExpiringSoon(): boolean {\n const auth = read();\n if (!auth?.workspaceTokenExpiresAt) return false;\n return Date.now() + TOKEN_BUFFER_MS >= auth.workspaceTokenExpiresAt;\n }\n\n function isAuthenticated(): boolean {\n const auth = read();\n if (auth?.apiKey) return true;\n if (!auth?.accessToken) return false;\n return !isTokenExpired();\n }\n\n return {\n read,\n write,\n clear,\n isTokenExpired,\n isTokenExpiringSoon,\n isWorkspaceTokenExpired,\n isWorkspaceTokenExpiringSoon,\n isAuthenticated,\n };\n}\n","/**\n * Config store — parameterised on configDirName + product defaults.\n *\n * Persists MCP runtime config to ~/.config/<configDirName>/config.json.\n * Includes both gql-client config (workspace/global endpoints, oidc) and\n * transport config (httpPort, host, corsOrigins, allowedHosts, apiKey).\n *\n * Env-var overrides preserve current vibecontrols-mcp behaviour:\n * VIBECONTROLS_WORKSPACE_ENDPOINT, VIBECONTROLS_GLOBAL_ENDPOINT,\n * VIBECONTROLS_OIDC_ISSUER, VIBECONTROLS_CLIENT_ID,\n * VIBECONTROLS_ACCESS_TOKEN, VIBECONTROLS_REFRESH_TOKEN,\n * VIBECONTROLS_WORKSPACE_TOKEN, VIBECONTROLS_API_KEY (or MCP_API_KEY),\n * VIBECONTROLS_WORKSPACE_ID, VIBECONTROLS_ORGANIZATION_ID,\n * HOST, MCP_HOST, PORT, VIBECONTROLS_HTTP_PORT,\n * CORS_ORIGINS, ALLOWED_HOSTS, LOG_LEVEL, LOG_FORMAT.\n *\n * The shell passes the env-prefix it wants (e.g. VIBECONTROLS_) so other\n * product MCPs don't clash.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\n\nexport interface McpConfig {\n workspaceEndpoint: string;\n globalEndpoint: string;\n oidcIssuer?: string;\n clientId?: string;\n\n /** Pre-loaded auth (typically env-injected for headless service mode). */\n accessToken?: string;\n refreshToken?: string;\n workspaceToken?: string;\n apiKey?: string;\n workspaceId?: string;\n organizationId?: string;\n\n /** HTTP transport */\n host: string;\n httpPort: number;\n corsOrigins: string;\n allowedHosts: string;\n\n /** Logging */\n logLevel: 'error' | 'warn' | 'info' | 'debug';\n logFormat: 'json' | 'text';\n}\n\nexport interface ProductDefaults {\n /** Directory under ~/.config where this product's MCP state lives. */\n configDirName: string;\n /** Default OAuth client id for OIDC device-code flow. */\n oidcClientId: string;\n /** Production OIDC issuer URL (used when endpoints are non-local). */\n oidcIssuerProd?: string;\n /** Default workspace gateway endpoint. */\n workspaceEndpointDefault: string;\n /** Default global gateway endpoint. */\n globalEndpointDefault: string;\n /** Default HTTP transport port. */\n httpPortDefault?: number;\n /** Default host binding (CORS-bound, defaults to 127.0.0.1). */\n hostDefault?: string;\n /** Env-var prefix (e.g. 'VIBECONTROLS'). */\n envPrefix?: string;\n}\n\nexport interface ConfigStore {\n read(): McpConfig;\n write(config: Partial<McpConfig>): void;\n path(): string;\n dir(): string;\n resolveOIDC(): { oidcIssuer: string; clientId: string };\n}\n\nfunction envOr(prefix: string | undefined, key: string, fallback?: string): string | undefined {\n if (prefix) {\n const prefixed = process.env[`${prefix}_${key}`];\n if (prefixed !== undefined && prefixed !== '') return prefixed;\n }\n const direct = process.env[key];\n if (direct !== undefined && direct !== '') return direct;\n return fallback;\n}\n\nexport function createConfigStore(defaults: ProductDefaults): ConfigStore {\n const configDir = join(homedir(), '.config', defaults.configDirName);\n const configFile = join(configDir, 'config.json');\n const envPrefix = defaults.envPrefix ?? defaults.configDirName.toUpperCase().replace(/-/g, '_');\n\n function ensureConfigDir(): void {\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true, mode: 0o700 });\n }\n }\n\n function readPersisted(): Partial<McpConfig> {\n try {\n if (!existsSync(configFile)) return {};\n const raw = readFileSync(configFile, 'utf8');\n return JSON.parse(raw) as Partial<McpConfig>;\n } catch {\n return {};\n }\n }\n\n function read(): McpConfig {\n const persisted = readPersisted();\n\n const workspaceEndpoint =\n envOr(envPrefix, 'WORKSPACE_ENDPOINT') ??\n persisted.workspaceEndpoint ??\n defaults.workspaceEndpointDefault;\n\n const globalEndpoint =\n envOr(envPrefix, 'GLOBAL_ENDPOINT') ??\n persisted.globalEndpoint ??\n defaults.globalEndpointDefault;\n\n const httpPortRaw =\n envOr(envPrefix, 'HTTP_PORT') ??\n envOr(undefined, 'PORT') ??\n String(defaults.httpPortDefault ?? 3000);\n\n const logLevelRaw = envOr(undefined, 'LOG_LEVEL') ?? persisted.logLevel ?? 'info';\n const logFormatRaw = envOr(undefined, 'LOG_FORMAT') ?? persisted.logFormat ?? 'json';\n\n return {\n workspaceEndpoint,\n globalEndpoint,\n oidcIssuer: envOr(envPrefix, 'OIDC_ISSUER') ?? persisted.oidcIssuer,\n clientId: envOr(envPrefix, 'CLIENT_ID') ?? persisted.clientId,\n accessToken: envOr(envPrefix, 'ACCESS_TOKEN'),\n refreshToken: envOr(envPrefix, 'REFRESH_TOKEN'),\n workspaceToken: envOr(envPrefix, 'WORKSPACE_TOKEN'),\n apiKey: envOr(envPrefix, 'API_KEY') ?? envOr(undefined, 'MCP_API_KEY'),\n workspaceId: envOr(envPrefix, 'WORKSPACE_ID'),\n organizationId: envOr(envPrefix, 'ORGANIZATION_ID'),\n host:\n envOr(undefined, 'HOST') ??\n envOr(undefined, 'MCP_HOST') ??\n defaults.hostDefault ??\n '127.0.0.1',\n httpPort: parseInt(httpPortRaw, 10) || (defaults.httpPortDefault ?? 3000),\n corsOrigins:\n envOr(undefined, 'CORS_ORIGINS') ??\n persisted.corsOrigins ??\n 'http://127.0.0.1,http://localhost',\n allowedHosts:\n envOr(undefined, 'ALLOWED_HOSTS') ?? persisted.allowedHosts ?? '127.0.0.1,localhost',\n logLevel: (['error', 'warn', 'info', 'debug'] as const).includes(logLevelRaw as 'info')\n ? (logLevelRaw as McpConfig['logLevel'])\n : 'info',\n logFormat: logFormatRaw === 'text' ? 'text' : 'json',\n };\n }\n\n function write(patch: Partial<McpConfig>): void {\n ensureConfigDir();\n const merged = { ...readPersisted(), ...patch };\n writeFileSync(configFile, JSON.stringify(merged, null, 2), { encoding: 'utf8' });\n try {\n chmodSync(configFile, 0o600);\n } catch {\n // chmod may fail on Windows; non-critical.\n }\n }\n\n function resolveOIDC(): { oidcIssuer: string; clientId: string } {\n const config = read();\n const clientId = config.clientId || defaults.oidcClientId;\n\n let oidcIssuer = config.oidcIssuer;\n if (!oidcIssuer) {\n const globalEndpoint = config.globalEndpoint;\n if (globalEndpoint.includes('localhost') || globalEndpoint.includes('127.0.0.1')) {\n oidcIssuer = globalEndpoint\n .replace(/\\/graphql$/, '')\n .replace(/\\/global\\/graphql$/, '/global');\n } else {\n oidcIssuer = defaults.oidcIssuerProd ?? 'https://graphql.burdenoff.com/global';\n }\n }\n\n return { oidcIssuer, clientId };\n }\n\n return {\n read,\n write,\n path: () => configFile,\n dir: () => configDir,\n resolveOIDC,\n };\n}\n","/**\n * OAuth2 Device Code flow + Client Credentials flow + workspace token issuance.\n * Pure functions — operate on injected endpoints + client ids, no global state.\n *\n * Mirrors cli-sdk/src/core/auth/device-code.ts so a future shared\n * @burdenoff/auth-core extraction is mechanical.\n */\n\nimport fetch from 'cross-fetch';\n\nexport interface DeviceCodeResponse {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string | null;\n expiresIn: number;\n interval: number;\n}\n\nexport interface DeviceCodeTokenResult {\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n}\n\nexport interface ClientCredentialsResult {\n accessToken: string;\n expiresIn: number;\n scopes: string[];\n}\n\nexport interface OIDCConfig {\n oidcIssuer: string;\n clientId: string;\n}\n\nexport async function startDeviceCodeFlow(config: OIDCConfig): Promise<DeviceCodeResponse> {\n const url = `${config.oidcIssuer}/oidc/device/code`;\n const body = new URLSearchParams({\n client_id: config.clientId,\n scope: 'openid profile email offline_access',\n });\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`Device code request failed (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n\n return {\n deviceCode: data['device_code'] as string,\n userCode: data['user_code'] as string,\n verificationUri: data['verification_uri'] as string,\n verificationUriComplete: (data['verification_uri_complete'] as string) ?? null,\n expiresIn: data['expires_in'] as number,\n interval: (data['interval'] as number) ?? 5,\n };\n}\n\nexport type DeviceTokenPollResult =\n | { status: 'authenticated'; tokens: DeviceCodeTokenResult }\n | { status: 'pending' }\n | { status: 'slow_down'; newInterval: number }\n | { status: 'expired' }\n | { status: 'denied' };\n\n/**\n * Single-shot device-code token poll.\n *\n * Unlike cli-sdk's pollForToken which loops until done (suitable for blocking\n * CLI), MCP needs non-blocking semantics: the LLM calls auth_complete tool\n * repeatedly. This helper makes ONE poll attempt and returns a discriminated\n * union the caller can act on.\n */\nexport async function pollDeviceTokenOnce(\n deviceCode: string,\n interval: number,\n config: OIDCConfig,\n): Promise<DeviceTokenPollResult> {\n const url = `${config.oidcIssuer}/oauth/device/token`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: deviceCode,\n client_id: config.clientId,\n }).toString(),\n });\n\n const data = (await response.json()) as Record<string, unknown>;\n\n if (response.ok && data['access_token']) {\n return {\n status: 'authenticated',\n tokens: {\n accessToken: data['access_token'] as string,\n refreshToken: (data['refresh_token'] as string) ?? '',\n expiresIn: (data['expires_in'] as number) ?? 3600,\n },\n };\n }\n\n const errorCode = data['error'] as string | undefined;\n switch (errorCode) {\n case 'authorization_pending':\n return { status: 'pending' };\n case 'slow_down':\n return { status: 'slow_down', newInterval: interval + 5 };\n case 'expired_token':\n return { status: 'expired' };\n case 'access_denied':\n return { status: 'denied' };\n default:\n throw new Error(\n `Device code polling failed: ${(data['error_description'] as string) ?? errorCode ?? 'Unknown error'}`,\n );\n }\n}\n\nexport async function clientCredentialsFlow(\n globalEndpoint: string,\n clientId: string,\n clientSecret: string,\n scopes?: string[],\n): Promise<ClientCredentialsResult> {\n const query = `\n mutation AuthenticateApp($input: AuthenticateAppInput!) {\n authenticateApp(input: $input) {\n accessToken tokenType expiresIn scopes\n }\n }\n `;\n\n const response = await fetch(globalEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n query,\n variables: { input: { clientId, clientSecret, scopes } },\n }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`App authentication failed (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n data?: { authenticateApp: { accessToken: string; expiresIn: number; scopes: string[] } };\n errors?: Array<{ message: string }>;\n };\n\n if (data.errors?.length) {\n throw new Error(`App authentication failed: ${data.errors[0]?.message ?? 'unknown error'}`);\n }\n if (!data.data?.authenticateApp?.accessToken) {\n throw new Error('App authentication failed: no access token returned');\n }\n\n return data.data.authenticateApp;\n}\n\nexport async function issueWorkspaceToken(\n workspaceEndpoint: string,\n authToken: string,\n workspaceId: string,\n organizationId: string,\n): Promise<{ token: string; expiresAt: string; scopes: string[] }> {\n const query = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success token expiresAt scopes\n error { code message }\n }\n }\n `;\n\n const response = await fetch(workspaceEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}` },\n body: JSON.stringify({ query, variables: { input: { workspaceId, organizationId } } }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`Workspace token request failed (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n data?: {\n issueWorkspaceToken: {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n scopes: string[] | null;\n error: { code: string; message: string } | null;\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (data.errors?.length) {\n throw new Error(`Workspace token failed: ${data.errors[0]?.message ?? 'unknown error'}`);\n }\n\n const result = data.data?.issueWorkspaceToken;\n if (!result?.success || !result.token) {\n throw new Error(`Workspace token failed: ${result?.error?.message ?? 'Unknown error'}`);\n }\n\n return { token: result.token, expiresAt: result.expiresAt ?? '', scopes: result.scopes ?? [] };\n}\n\nexport async function fetchWorkspaces(\n globalEndpoint: string,\n authToken: string,\n): Promise<\n Array<{ id: string; name: string; slug: string; tenantId: string; organizationId: string }>\n> {\n const query = `\n query MyWorkspaces($limit: Int) {\n myWorkspaces(limit: $limit) {\n items { id name slug tenantId organizationId }\n }\n }\n `;\n\n const response = await fetch(globalEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}` },\n body: JSON.stringify({ query, variables: { limit: 50 } }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`Failed to fetch workspaces (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n data?: {\n myWorkspaces: {\n items: Array<{\n id: string;\n name: string;\n slug: string;\n tenantId: string;\n organizationId: string;\n }>;\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (data.errors?.length) {\n throw new Error(`Failed to fetch workspaces: ${data.errors[0]?.message ?? 'unknown error'}`);\n }\n\n return data.data?.myWorkspaces?.items ?? [];\n}\n","/**\n * GraphQL client factory — produces three clients (workspace, global,\n * workspaceAuthOnly) sharing an injected ConfigStore + AuthStore.\n *\n * - Auto-refreshes platform + workspace tokens on the workspace client.\n * - Workspace client requires authentication; ensures fresh tokens before each call.\n * - Global client does NOT trigger refresh (avoids loops during auth flows).\n * - workspaceAuthOnly omits X-Workspace-Authorization (used to bootstrap\n * workspace token issuance).\n *\n * Ported from cli-sdk/src/core/gql/client.ts with a minor change: a static\n * `apiKey` is injected as `X-API-Key` header when StoredAuth.apiKey is set\n * (allows headless service-mode auth without device code).\n */\n\nimport { GraphQLClient, type RequestDocument, type Variables } from 'graphql-request';\nimport type { AuthStore, StoredAuth } from '../auth/store.js';\nimport type { ConfigStore } from '../config/store.js';\nimport { clientCredentialsFlow, issueWorkspaceToken } from '../auth/device-code.js';\n\nconst DEFAULT_TIMEOUT = 30_000;\nconst MAX_RETRIES = 3;\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n\nexport interface GqlClient {\n request<T>(document: RequestDocument, variables?: Variables): Promise<T>;\n}\n\nexport interface GqlClients {\n workspace: GqlClient;\n global: GqlClient;\n workspaceAuthOnly: GqlClient;\n reset(): void;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isNetworkOrServerError(error: unknown): boolean {\n if (error instanceof TypeError) return true;\n if (error && typeof error === 'object' && 'response' in error) {\n const resp = (error as { response?: { status?: number } }).response;\n if (resp && typeof resp.status === 'number' && resp.status >= 500) return true;\n }\n return false;\n}\n\nexport function extractGqlErrorMessage(error: unknown): string {\n if (error && typeof error === 'object' && 'response' in error) {\n const resp = error as {\n response?: { errors?: Array<{ message?: string }>; status?: number };\n message?: string;\n };\n const firstError = resp.response?.errors?.[0];\n if (firstError?.message) return firstError.message;\n if (resp.message) return resp.message;\n }\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction getHeaders(auth: StoredAuth | null): Record<string, string> {\n const headers: Record<string, string> = {};\n if (auth?.apiKey) headers['X-API-Key'] = auth.apiKey;\n if (auth?.accessToken) headers['Authorization'] = `Bearer ${auth.accessToken}`;\n if (auth?.organizationId) headers['x-org-id'] = auth.organizationId;\n return headers;\n}\n\nfunction getWorkspaceHeaders(auth: StoredAuth | null): Record<string, string> {\n const headers = getHeaders(auth);\n if (auth?.workspaceToken) {\n headers['X-Workspace-Authorization'] = `Bearer ${auth.workspaceToken}`;\n }\n if (auth?.workspaceId) headers['x-workspace-id'] = auth.workspaceId;\n return headers;\n}\n\nasync function executeWithRetry<T>(\n client: GraphQLClient,\n document: RequestDocument,\n variables?: Variables,\n): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT);\n try {\n return await client.request<T>({ document, variables, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n } catch (error: unknown) {\n lastError = error;\n\n if (error && typeof error === 'object' && 'response' in error) {\n const resp = (error as { response?: { status?: number } }).response;\n if (resp && typeof resp.status === 'number' && resp.status >= 400 && resp.status < 500) {\n break;\n }\n }\n\n if (isNetworkOrServerError(error) && attempt < MAX_RETRIES - 1) {\n const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);\n await sleep(delay);\n continue;\n }\n\n break;\n }\n }\n\n throw new Error(extractGqlErrorMessage(lastError));\n}\n\nexport function createGqlClients(config: ConfigStore, authStore: AuthStore): GqlClients {\n let workspaceClient: GraphQLClient | null = null;\n let globalClient: GraphQLClient | null = null;\n\n function init(): { workspace: GraphQLClient; global: GraphQLClient } {\n const cfg = config.read();\n const auth = authStore.read();\n\n workspaceClient = new GraphQLClient(cfg.workspaceEndpoint);\n workspaceClient.setHeaders(getWorkspaceHeaders(auth));\n\n globalClient = new GraphQLClient(cfg.globalEndpoint);\n globalClient.setHeaders(getHeaders(auth));\n\n return { workspace: workspaceClient, global: globalClient };\n }\n\n async function refreshPlatformToken(): Promise<void> {\n const auth = authStore.read();\n if (!auth) return;\n\n if (auth.authMethod === 'client_credentials' && auth.clientId && auth.clientSecret) {\n const cfg = config.read();\n try {\n const result = await clientCredentialsFlow(\n cfg.globalEndpoint,\n auth.clientId,\n auth.clientSecret,\n );\n authStore.write({\n ...auth,\n accessToken: result.accessToken,\n expiresAt: Date.now() + result.expiresIn * 1000,\n });\n workspaceClient = null;\n globalClient = null;\n } catch {\n // swallow — caller sees expired-token failure on next request\n }\n return;\n }\n\n if (!auth.refreshToken) return;\n\n const cfg = config.read();\n const client = new GraphQLClient(cfg.globalEndpoint);\n client.setHeaders({ Authorization: `Bearer ${auth.accessToken}` });\n\n const REFRESH_MUTATION = `\n mutation RefreshToken($token: String!) {\n refreshToken(token: $token) { accessToken refreshToken expiresIn }\n }\n `;\n\n interface RefreshResponse {\n refreshToken: { accessToken: string; refreshToken: string; expiresIn: number };\n }\n\n try {\n const data = await client.request<RefreshResponse>(REFRESH_MUTATION, {\n token: auth.refreshToken,\n });\n authStore.write({\n ...auth,\n accessToken: data.refreshToken.accessToken,\n refreshToken: data.refreshToken.refreshToken,\n expiresAt: Date.now() + data.refreshToken.expiresIn * 1000,\n });\n workspaceClient = null;\n globalClient = null;\n } catch {\n // swallow — surfaced on next request\n }\n }\n\n async function refreshWorkspaceToken(): Promise<void> {\n const auth = authStore.read();\n if (!auth?.accessToken || !auth.workspaceId || !auth.organizationId) return;\n\n const cfg = config.read();\n try {\n const result = await issueWorkspaceToken(\n cfg.workspaceEndpoint,\n auth.accessToken,\n auth.workspaceId,\n auth.organizationId,\n );\n authStore.write({\n ...auth,\n workspaceToken: result.token,\n workspaceTokenExpiresAt: new Date(result.expiresAt).getTime(),\n });\n workspaceClient = null;\n } catch {\n // swallow — surfaced on next request\n }\n }\n\n async function ensureFreshTokens(): Promise<void> {\n const initial = authStore.read();\n if (initial?.apiKey) return; // API-key auth never expires\n\n if (authStore.isTokenExpiringSoon()) {\n await refreshPlatformToken();\n }\n if (authStore.isWorkspaceTokenExpiringSoon()) {\n await refreshWorkspaceToken();\n }\n }\n\n const workspace: GqlClient = {\n async request<T>(document: RequestDocument, variables?: Variables): Promise<T> {\n await ensureFreshTokens();\n const { workspace: ws } = workspaceClient ? { workspace: workspaceClient } : init();\n ws.setHeaders(getWorkspaceHeaders(authStore.read()));\n return executeWithRetry<T>(ws, document, variables);\n },\n };\n\n const global: GqlClient = {\n async request<T>(document: RequestDocument, variables?: Variables): Promise<T> {\n const { global: g } = globalClient ? { global: globalClient } : init();\n g.setHeaders(getHeaders(authStore.read()));\n return executeWithRetry<T>(g, document, variables);\n },\n };\n\n const workspaceAuthOnly: GqlClient = {\n async request<T>(document: RequestDocument, variables?: Variables): Promise<T> {\n const cfg = config.read();\n const auth = authStore.read();\n const client = new GraphQLClient(cfg.workspaceEndpoint);\n client.setHeaders(getHeaders(auth));\n return executeWithRetry<T>(client, document, variables);\n },\n };\n\n return {\n workspace,\n global,\n workspaceAuthOnly,\n reset(): void {\n workspaceClient = null;\n globalClient = null;\n },\n };\n}\n","/**\n * Structured logger for MCP SDK.\n *\n * Routes through process.stderr only — stdio transport reserves stdout for\n * JSON-RPC protocol messages. Modules NEVER use console.log/console.error\n * directly: that would corrupt the stdio stream.\n *\n * Supports MCP `logging/setLevel` requests via setLevel() — wire this to the\n * server's request handler so clients can dynamically control verbosity.\n */\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug';\nexport type LogFormat = 'json' | 'text';\n\nexport interface LogContext {\n [key: string]: unknown;\n}\n\nexport interface Logger {\n error(message: string, context?: LogContext): void;\n warn(message: string, context?: LogContext): void;\n info(message: string, context?: LogContext): void;\n debug(message: string, context?: LogContext): void;\n setLevel(level: LogLevel): void;\n getLevel(): LogLevel;\n}\n\nexport interface LoggerOptions {\n level?: LogLevel;\n format?: LogFormat;\n}\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nexport function createLogger(opts: LoggerOptions = {}): Logger {\n let level: LogLevel = opts.level ?? (process.env.LOG_LEVEL as LogLevel) ?? 'info';\n const format: LogFormat = opts.format ?? (process.env.LOG_FORMAT as LogFormat) ?? 'json';\n\n function shouldLog(target: LogLevel): boolean {\n return LEVEL_RANK[target] <= LEVEL_RANK[level];\n }\n\n function formatMessage(target: LogLevel, message: string, context?: LogContext): string {\n const timestamp = new Date().toISOString();\n if (format === 'json') {\n return JSON.stringify({ timestamp, level: target, message, ...context });\n }\n const contextStr = context ? ` ${JSON.stringify(context)}` : '';\n return `[${timestamp}] ${target.toUpperCase()}: ${message}${contextStr}`;\n }\n\n function emit(target: LogLevel, message: string, context?: LogContext): void {\n if (!shouldLog(target)) return;\n process.stderr.write(formatMessage(target, message, context) + '\\n');\n }\n\n return {\n error(message, context): void {\n emit('error', message, context);\n },\n warn(message, context): void {\n emit('warn', message, context);\n },\n info(message, context): void {\n emit('info', message, context);\n },\n debug(message, context): void {\n emit('debug', message, context);\n },\n setLevel(newLevel): void {\n level = newLevel;\n },\n getLevel(): LogLevel {\n return level;\n },\n };\n}\n","/**\n * Progress notification helper.\n *\n * MCP supports `notifications/progress` for long-running tool calls. The client\n * passes a `progressToken` in `_meta`; the server emits progress against that\n * token. When no token is present, ctx.progress() no-ops.\n *\n * Pattern in a tool handler:\n * await registerTool(server, ctx, name, meta, async (args, ctx, meta) => {\n * ctx.progress(meta.progressToken, 0, 100, 'starting');\n * // ... work\n * ctx.progress(meta.progressToken, 50, 100, 'halfway');\n * // ... more work\n * ctx.progress(meta.progressToken, 100, 100, 'done');\n * });\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nexport type ProgressFn = (\n token: string | number | undefined,\n current: number,\n total?: number,\n message?: string,\n) => void;\n\nexport function createProgress(serverRef: { current: McpServer | null }): ProgressFn {\n return (token, current, total, message) => {\n if (token === undefined || token === null) return;\n const server = serverRef.current;\n if (!server) return;\n try {\n const params: {\n progressToken: string | number;\n progress: number;\n total?: number;\n message?: string;\n } = { progressToken: token, progress: current };\n if (total !== undefined) params.total = total;\n if (message !== undefined) params.message = message;\n // The McpServer exposes the underlying Server which has a notification method;\n // wrap defensively because shapes vary across SDK versions.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const inner = (server as any).server ?? server;\n inner.notification?.({ method: 'notifications/progress', params });\n } catch {\n // ignore — progress is best-effort\n }\n };\n}\n","/**\n * McpContext — the prop bag injected by the shell into every module.\n *\n * Modules receive this via `register(server, ctx)` and use only what they\n * need. No module should reach for global state.\n */\n\nimport { createAuthStore, type AuthStore } from './auth/store.js';\nimport { createConfigStore, type ConfigStore, type ProductDefaults } from './config/store.js';\nimport { createGqlClients, type GqlClients } from './gql/client.js';\nimport { createLogger, type Logger, type LoggerOptions } from './logger.js';\nimport { createProgress, type ProgressFn } from './progress.js';\n\nexport type Environment = 'prod' | 'alpha' | 'dev' | 'local';\n\nexport interface McpContext {\n productName: string;\n productVersion: string;\n serverName: string;\n serverVersion: string;\n defaults: ProductDefaults;\n config: ConfigStore;\n auth: AuthStore;\n gql: GqlClients;\n logger: Logger;\n progress: ProgressFn;\n env: Environment;\n\n /** Internal: server reference is mutated post-construction in createMcpServer. */\n _internal: {\n serverRef: { current: import('@modelcontextprotocol/sdk/server/mcp.js').McpServer | null };\n };\n}\n\nexport interface BuildContextOptions {\n productName: string;\n productVersion: string;\n serverName: string;\n serverVersion: string;\n defaults: ProductDefaults;\n logger?: LoggerOptions | Logger;\n env?: Environment;\n /**\n * Override the auth file path. Defaults to `<configDir>/auth.json`.\n * Set this to `~/.config/<product>-cli/auth.json` to share token\n * storage with the corresponding CLI.\n */\n tokenStorePath?: string;\n}\n\nfunction inferEnv(workspaceEndpoint: string): Environment {\n if (workspaceEndpoint.includes('localhost') || workspaceEndpoint.includes('127.0.0.1')) {\n return 'local';\n }\n if (workspaceEndpoint.includes('alpha')) return 'alpha';\n return 'prod';\n}\n\nfunction isLogger(value: LoggerOptions | Logger | undefined): value is Logger {\n return (\n !!value &&\n typeof (value as Logger).debug === 'function' &&\n typeof (value as Logger).info === 'function'\n );\n}\n\nexport function buildContext(opts: BuildContextOptions): McpContext {\n const config = createConfigStore(opts.defaults);\n const cfg = config.read();\n\n const logger = isLogger(opts.logger)\n ? opts.logger\n : createLogger({\n ...(opts.logger as LoggerOptions | undefined),\n level: cfg.logLevel,\n format: cfg.logFormat,\n });\n\n const auth = createAuthStore(\n opts.tokenStorePath ? dirOf(opts.tokenStorePath) : config.dir(),\n authFileName(opts.tokenStorePath),\n );\n\n // Seed env-injected tokens if persisted store is empty (headless service mode).\n const existing = auth.read();\n if (!existing && (cfg.accessToken || cfg.apiKey)) {\n auth.write({\n accessToken: cfg.accessToken ?? '',\n refreshToken: cfg.refreshToken ?? '',\n ...(cfg.workspaceToken ? { workspaceToken: cfg.workspaceToken } : {}),\n ...(cfg.workspaceId ? { workspaceId: cfg.workspaceId } : {}),\n ...(cfg.organizationId ? { organizationId: cfg.organizationId } : {}),\n ...(cfg.apiKey ? { apiKey: cfg.apiKey, authMethod: 'api_key' as const } : {}),\n });\n }\n\n const gql = createGqlClients(config, auth);\n const env = opts.env ?? inferEnv(cfg.workspaceEndpoint);\n\n const serverRef: { current: import('@modelcontextprotocol/sdk/server/mcp.js').McpServer | null } =\n { current: null };\n const progress = createProgress(serverRef);\n\n return {\n productName: opts.productName,\n productVersion: opts.productVersion,\n serverName: opts.serverName,\n serverVersion: opts.serverVersion,\n defaults: opts.defaults,\n config,\n auth,\n gql,\n logger,\n progress,\n env,\n _internal: { serverRef },\n };\n}\n\nfunction dirOf(p: string): string {\n const lastSlash = p.lastIndexOf('/');\n return lastSlash > 0 ? p.slice(0, lastSlash) : p;\n}\n\nfunction authFileName(p?: string): string | undefined {\n if (!p) return undefined;\n const lastSlash = p.lastIndexOf('/');\n return lastSlash >= 0 ? p.slice(lastSlash + 1) : p;\n}\n","/**\n * Error classes for MCP SDK.\n *\n * Modules MUST throw these instead of throwing raw Errors. The registerTool\n * wrapper in result.ts catches and maps them to MCP-protocol-compliant\n * `{ isError: true, content: [...] }` responses.\n *\n * Throwing past the wrapper to the protocol surfaces as JSON-RPC -32603 to\n * the client and is a protocol bug.\n */\n\nexport class McpUserError extends Error {\n public readonly hint: string | undefined;\n\n constructor(message: string, opts?: { hint?: string }) {\n super(message);\n this.name = 'McpUserError';\n this.hint = opts?.hint;\n }\n}\n\nexport class McpAuthError extends McpUserError {\n constructor(message: string, opts?: { hint?: string }) {\n super(message, {\n hint: opts?.hint ?? 'Run the auth_login tool to authenticate.',\n });\n this.name = 'McpAuthError';\n }\n}\n\nexport class McpInternalError extends Error {\n public override readonly cause: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'McpInternalError';\n this.cause = cause;\n }\n}\n","/**\n * McpModule contract + dependency-aware loader.\n *\n * Each entry under src/modules/<name>/ default-exports an McpModule. The\n * shell passes an array of modules to createMcpServer(); the loader topo-\n * sorts them, fails fast on missing deps, and calls register() on each.\n *\n * register() returns a ModuleRegistration manifest of what was registered\n * — used by the shell to log a deterministic boot line and by the snapshot\n * test in Phase 1 to diff against a captured pre-refactor manifest.\n *\n * Mirrors cli-sdk/src/core/module.ts with addition of capabilities + manifest.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { McpContext } from './context.js';\nimport type { McpCapabilities } from './capabilities.js';\nimport { McpInternalError } from './errors.js';\n\nexport interface ModuleRegistration {\n tools: readonly string[];\n resources: readonly string[];\n prompts: readonly string[];\n}\n\nexport interface McpModule {\n readonly id: string;\n readonly version: string;\n readonly displayName: string;\n readonly dependsOn?: readonly string[];\n readonly capabilities?: McpCapabilities;\n register(server: McpServer, ctx: McpContext): ModuleRegistration;\n}\n\nexport class MissingDependencyError extends McpInternalError {\n constructor(moduleId: string, missingDep: string) {\n super(\n `Module '${moduleId}' declares dependency on '${missingDep}', but '${missingDep}' is not in the module list.`,\n );\n this.name = 'MissingDependencyError';\n }\n}\n\nexport class CircularDependencyError extends McpInternalError {\n constructor(cycle: readonly string[]) {\n super(`Circular dependency detected among modules: ${cycle.join(' -> ')}`);\n this.name = 'CircularDependencyError';\n }\n}\n\n/**\n * Topologically sort modules by their `dependsOn` declarations.\n * Throws MissingDependencyError or CircularDependencyError on bad input.\n */\nexport function sortModules(modules: readonly McpModule[]): McpModule[] {\n const byId = new Map<string, McpModule>();\n for (const m of modules) {\n if (byId.has(m.id)) {\n throw new McpInternalError(`Duplicate module id: '${m.id}'`);\n }\n byId.set(m.id, m);\n }\n\n for (const m of modules) {\n for (const dep of m.dependsOn ?? []) {\n if (!byId.has(dep)) {\n throw new MissingDependencyError(m.id, dep);\n }\n }\n }\n\n const sorted: McpModule[] = [];\n const visiting = new Set<string>();\n const visited = new Set<string>();\n\n function visit(m: McpModule, path: string[]): void {\n if (visited.has(m.id)) return;\n if (visiting.has(m.id)) {\n throw new CircularDependencyError([...path, m.id]);\n }\n visiting.add(m.id);\n for (const dep of m.dependsOn ?? []) {\n const depModule = byId.get(dep);\n if (depModule) visit(depModule, [...path, m.id]);\n }\n visiting.delete(m.id);\n visited.add(m.id);\n sorted.push(m);\n }\n\n for (const m of modules) {\n visit(m, []);\n }\n return sorted;\n}\n\nexport interface ServerManifest {\n modules: readonly { id: string; version: string }[];\n tools: readonly string[];\n resources: readonly string[];\n prompts: readonly string[];\n}\n","/**\n * Module capability declaration + union helper.\n *\n * Each McpModule declares the MCP capabilities it requires. The shell unions\n * all capabilities before constructing McpServer, so a module that needs\n * resources.subscribe (e.g. live agent heartbeat) gets it without any\n * shell-side knowledge.\n *\n * Reference: https://modelcontextprotocol.io/specification/2025-03-26/server/capabilities\n */\n\nexport interface McpCapabilities {\n resources?: { subscribe?: boolean; listChanged?: boolean };\n prompts?: { listChanged?: boolean };\n tools?: { listChanged?: boolean };\n logging?: boolean;\n completions?: boolean;\n}\n\n/**\n * Union an array of capability declarations. Boolean unions on logging /\n * completions; OR on every nested boolean.\n */\nexport function unionCapabilities(caps: readonly (McpCapabilities | undefined)[]): McpCapabilities {\n const out: McpCapabilities = {};\n\n for (const cap of caps) {\n if (!cap) continue;\n if (cap.resources) {\n out.resources ??= {};\n if (cap.resources.subscribe) out.resources.subscribe = true;\n if (cap.resources.listChanged) out.resources.listChanged = true;\n }\n if (cap.prompts) {\n out.prompts ??= {};\n if (cap.prompts.listChanged) out.prompts.listChanged = true;\n }\n if (cap.tools) {\n out.tools ??= {};\n if (cap.tools.listChanged) out.tools.listChanged = true;\n }\n if (cap.logging) out.logging = true;\n if (cap.completions) out.completions = true;\n }\n\n return out;\n}\n\n/**\n * Convert capability declaration into the shape the MCP SDK accepts at\n * `new McpServer({ capabilities })`. The SDK uses `{}` as truthy markers.\n */\nexport function toServerCapabilities(caps: McpCapabilities): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (caps.tools) out.tools = caps.tools;\n if (caps.resources) out.resources = caps.resources;\n if (caps.prompts) out.prompts = caps.prompts;\n if (caps.logging) out.logging = {};\n if (caps.completions) out.completions = {};\n return out;\n}\n","/**\n * Tool / resource / prompt naming helpers.\n *\n * Mandatory product prefix avoids collisions when Claude Desktop runs\n * multiple MCP servers concurrently (typical setup is ~6).\n *\n * Tool names are capped at 63 characters — Claude Desktop pre-1.x\n * truncated at 64 in some versions.\n */\n\nimport { McpInternalError } from './errors.js';\n\nconst MAX_TOOL_NAME_LENGTH = 63;\n\nfunction assertSafeName(name: string, kind: 'tool' | 'resource' | 'prompt'): string {\n if (kind === 'tool' && name.length > MAX_TOOL_NAME_LENGTH) {\n throw new McpInternalError(\n `Tool name '${name}' exceeds ${MAX_TOOL_NAME_LENGTH} characters (some MCP clients truncate at 64).`,\n );\n }\n return name;\n}\n\n/**\n * Build a tool name. Format: `<productName>_<...parts>` (snake_case).\n * Example: mcpToolName('vibecontrols', 'vibes', 'list') -> 'vibecontrols_vibes_list'\n */\nexport function mcpToolName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpToolName: productName is required');\n }\n const name = [productName, ...parts].filter(Boolean).join('_');\n return assertSafeName(name, 'tool');\n}\n\n/**\n * Build a resource URI. Format: `<productName>://<...parts>`.\n * Example: mcpResourceUri('vibecontrols', 'schema') -> 'vibecontrols://schema'\n */\nexport function mcpResourceUri(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpResourceUri: productName is required');\n }\n return `${productName}://${parts.filter(Boolean).join('/')}`;\n}\n\n/**\n * Build a prompt name. Format: `<productName>-<...parts>` (kebab-case).\n * Example: mcpPromptName('vibecontrols', 'setup') -> 'vibecontrols-setup'\n */\nexport function mcpPromptName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpPromptName: productName is required');\n }\n return [productName, ...parts].filter(Boolean).join('-');\n}\n\nexport const TOOL_NAME_LIMIT = MAX_TOOL_NAME_LENGTH;\n\n/**\n * Name-based hint heuristics for MCP `annotations` (readOnlyHint /\n * destructiveHint). Used by tool-governance.ts to auto-fill annotations for\n * the fleet of product modules that call `server.registerTool` directly\n * (bypassing the `registerTool()` core helper) and so never set them\n * explicitly today (BOFF-3903). Deliberately conservative — matched against\n * whole `_`-delimited segments so e.g. `timeentries_delete` and\n * `pomodoro_delete_goal` match, but a hypothetical `undeletable_check`\n * would not.\n *\n * A module can always override the inference by passing an explicit\n * `annotations` object to `registerTool()` / `server.registerTool()`.\n */\nconst DESTRUCTIVE_NAME_SEGMENT = /(?:^|_)delete(?:_|$)/i;\nconst READ_ONLY_NAME_SEGMENT = /(?:^|_)(?:list|get|search|check|read|count|stats|by_date)(?:_|$)/i;\n\n/** True when a tool name looks destructive (irreversibly deletes data) by naming convention. */\nexport function inferDestructiveHint(toolName: string): boolean {\n return DESTRUCTIVE_NAME_SEGMENT.test(toolName);\n}\n\n/**\n * True when a tool name looks read-only by naming convention. Never true for\n * a name that also looks destructive (a tool can't be both).\n */\nexport function inferReadOnlyHint(toolName: string): boolean {\n return !inferDestructiveHint(toolName) && READ_ONLY_NAME_SEGMENT.test(toolName);\n}\n","/**\n * Fleet-wide tool governance: MCP `annotations` inference + an opt-in\n * confirmation gate on destructive tools.\n *\n * BOFF-3903: an audit of mcp-libs/src/modules/timecampus/tools/ found 163\n * registered tools, ~35 of them destructive (delete/bulk-delete), with ZERO\n * `annotations.destructiveHint`/`readOnlyHint` anywhere and no confirmation\n * step before a destructive call executes. The same is true fleet-wide —\n * every product module calls `server.registerTool` directly (bypassing the\n * `registerTool()` central wrapper in result.ts), so a per-module fix would\n * have to be re-applied ~54 times.\n *\n * `wrapServerWithToolGovernance` fixes this ONCE, at the McpServer boundary\n * inside `createMcpServer`, by monkey-patching `registerTool` before any\n * module receives the server reference. Every subsequent `registerTool`\n * call — whether it goes through result.ts's `registerTool()` helper or\n * calls `server.registerTool` directly — passes through this wrapper:\n *\n * 1. `annotations.readOnlyHint` / `destructiveHint` are filled in from the\n * tool name (see tool-name.ts's inferDestructiveHint/inferReadOnlyHint)\n * whenever a module didn't declare them explicitly. This is pure\n * metadata — it never changes a tool's input schema or behavior, so it\n * is always safe to apply and every consumer gets it automatically.\n * 2. Only when `enforceDestructiveConfirmation` is true (opt-in,\n * defaults to false) does a resolved-destructive tool additionally get\n * a `confirm` input field and a hard gate: the tool's real handler is\n * never invoked unless the caller passes `confirm: true`. This is\n * deliberately opt-in — flipping it on is a real behavior change for\n * any existing MCP client automation calling that tool, so each product\n * shell (starting with timecampus-mcp for BOFF-3903) turns it on\n * explicitly via `createMcpServer`'s options once it's ready, rather\n * than every one of the ~54 modules' existing destructive-tool callers\n * breaking the moment this ships.\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z, type ZodRawShape } from 'zod';\n\nimport { inferDestructiveHint, inferReadOnlyHint } from './tool-name.js';\n\n/** MCP tool annotations (per the MCP spec's `ToolAnnotations` shape). */\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\nexport interface ToolGovernanceOptions {\n /**\n * Require `confirm: true` before invoking any tool resolved as\n * destructive (explicit `annotations.destructiveHint`, or inferred from\n * the tool name). Defaults to false.\n */\n enforceDestructiveConfirmation?: boolean;\n}\n\ninterface GovernedRegisterToolConfig {\n title?: string;\n description?: string;\n inputSchema?: ZodRawShape;\n annotations?: ToolAnnotations;\n}\n\ntype RegisterToolHandler = (...handlerArgs: unknown[]) => unknown;\ntype RegisterToolFn = (\n name: string,\n config: GovernedRegisterToolConfig,\n handler: RegisterToolHandler,\n) => unknown;\n\ninterface RegisterToolCapableServer {\n registerTool: RegisterToolFn;\n}\n\nconst CONFIRM_FIELD_DESCRIPTION =\n 'Must be true to execute this destructive tool. The call is rejected (no changes made) if omitted or false.';\n\nfunction resolveAnnotations(name: string, declared: ToolAnnotations | undefined): ToolAnnotations {\n const destructiveHint = declared?.destructiveHint ?? inferDestructiveHint(name);\n const readOnlyHint =\n declared?.readOnlyHint ?? (destructiveHint ? false : inferReadOnlyHint(name));\n return { ...declared, destructiveHint, readOnlyHint };\n}\n\n/** Rejection result forwarded to the MCP client without invoking the real handler. */\nfunction unconfirmedDestructiveResult(name: string): {\n content: Array<{ type: 'text'; text: string }>;\n isError: true;\n} {\n return {\n content: [\n {\n type: 'text',\n text: `'${name}' is a destructive action and was NOT executed. Re-call with confirm: true once you intend to proceed.`,\n },\n ],\n isError: true,\n };\n}\n\nfunction wrapDestructiveHandler(name: string, handler: RegisterToolHandler): RegisterToolHandler {\n return async (...callbackArgs: unknown[]): Promise<unknown> => {\n const hasArgs = callbackArgs.length === 2;\n const rawArgs = (hasArgs ? callbackArgs[0] : {}) as Record<string, unknown>;\n\n if (rawArgs['confirm'] !== true) {\n return unconfirmedDestructiveResult(name);\n }\n\n // Strip the synthetic `confirm` field before forwarding — the module's\n // own handler/schema never declared it and shouldn't have to know about it.\n const forwardedArgs: Record<string, unknown> = { ...rawArgs };\n delete forwardedArgs['confirm'];\n const forwardedCallbackArgs = hasArgs ? [forwardedArgs, callbackArgs[1]] : callbackArgs;\n return handler(...forwardedCallbackArgs);\n };\n}\n\n/**\n * Monkey-patch `server.registerTool` so every tool registered afterward\n * (by any module, through any call path) gets annotations inference and,\n * when enabled, the destructive-confirmation gate. Returns the same server\n * instance (mutated in place) for convenient chaining.\n */\nexport function wrapServerWithToolGovernance(\n server: McpServer,\n options: ToolGovernanceOptions = {},\n): McpServer {\n const enforceConfirmation = options.enforceDestructiveConfirmation ?? false;\n const target = server as unknown as RegisterToolCapableServer;\n const originalRegisterTool = target.registerTool.bind(target);\n\n target.registerTool = (\n name: string,\n config: GovernedRegisterToolConfig,\n handler: RegisterToolHandler,\n ): unknown => {\n const annotations = resolveAnnotations(name, config.annotations);\n\n if (!enforceConfirmation || !annotations.destructiveHint) {\n return originalRegisterTool(name, { ...config, annotations }, handler);\n }\n\n const gatedInputSchema: ZodRawShape = {\n ...(config.inputSchema ?? {}),\n confirm: z.boolean().optional().describe(CONFIRM_FIELD_DESCRIPTION),\n };\n\n return originalRegisterTool(\n name,\n { ...config, inputSchema: gatedInputSchema, annotations },\n wrapDestructiveHandler(name, handler),\n );\n };\n\n return server;\n}\n","/**\n * createMcpServer — McpServer factory + module loader + central wiring.\n *\n * Sorts modules by dependsOn, unions their capabilities, constructs an\n * McpServer with declared capabilities, calls register() on each module in\n * topo order, threads the server into ctx for progress notifications, and\n * returns both the server + the merged registration manifest.\n *\n * The `logging/setLevel` request handler is wired to ctx.logger.setLevel\n * so MCP clients can dynamically control verbosity.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { SetLevelRequestSchema, type LoggingLevel } from '@modelcontextprotocol/sdk/types.js';\nimport type { McpContext } from './context.js';\nimport { sortModules, type McpModule, type ServerManifest } from './module.js';\nimport { toServerCapabilities, unionCapabilities, type McpCapabilities } from './capabilities.js';\nimport type { LogLevel } from './logger.js';\nimport { wrapServerWithToolGovernance } from './tool-governance.js';\n\nexport interface CreateMcpServerOptions {\n name: string;\n version: string;\n /** Optional extra capabilities to union in (rarely needed). */\n extraCapabilities?: McpCapabilities;\n /**\n * Require `confirm: true` before invoking any tool resolved as\n * destructive (explicit `annotations.destructiveHint`, or inferred from\n * the tool name — see tool-governance.ts). Defaults to false so existing\n * consumers are unaffected until they opt in. `annotations` inference\n * itself always applies regardless of this flag.\n */\n enforceDestructiveConfirmation?: boolean;\n}\n\nexport interface McpServerHandle {\n server: McpServer;\n manifest: ServerManifest;\n}\n\nconst MCP_TO_LOGGER_LEVEL: Record<LoggingLevel, LogLevel> = {\n debug: 'debug',\n info: 'info',\n notice: 'info',\n warning: 'warn',\n error: 'error',\n critical: 'error',\n alert: 'error',\n emergency: 'error',\n};\n\nexport function createMcpServer(\n ctx: McpContext,\n modules: readonly McpModule[],\n opts: CreateMcpServerOptions,\n): McpServerHandle {\n const sorted = sortModules(modules);\n\n // Always declare logging so logging/setLevel works (ctx.logger uses setLevel internally).\n const baseCapabilities: McpCapabilities = { logging: true };\n const capabilities = unionCapabilities([\n baseCapabilities,\n ...sorted.map((m) => m.capabilities),\n opts.extraCapabilities,\n ]);\n\n const server = new McpServer(\n { name: opts.name, version: opts.version },\n { capabilities: toServerCapabilities(capabilities) },\n );\n\n // Wrap BEFORE any module receives the server reference so every\n // registerTool call — through the core registerTool() helper or called\n // directly by a module, the fleet-wide norm today (BOFF-3903) — is\n // governed uniformly, with zero changes required in any product module.\n wrapServerWithToolGovernance(server, {\n enforceDestructiveConfirmation: opts.enforceDestructiveConfirmation,\n });\n\n ctx._internal.serverRef.current = server;\n\n // Wire MCP logging/setLevel → ctx.logger.setLevel\n // The McpServer wraps a Server instance; reach inner for setRequestHandler.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const inner = (server as any).server ?? server;\n if (typeof inner.setRequestHandler === 'function') {\n inner.setRequestHandler(\n SetLevelRequestSchema,\n async (req: { params: { level: LoggingLevel } }) => {\n const target = MCP_TO_LOGGER_LEVEL[req.params.level] ?? 'info';\n ctx.logger.setLevel(target);\n ctx.logger.info('MCP logging level set', { level: req.params.level, mapped: target });\n return {};\n },\n );\n }\n\n const tools: string[] = [];\n const resources: string[] = [];\n const prompts: string[] = [];\n const moduleManifest: { id: string; version: string }[] = [];\n\n for (const mod of sorted) {\n try {\n const reg = mod.register(server, ctx);\n tools.push(...reg.tools);\n resources.push(...reg.resources);\n prompts.push(...reg.prompts);\n moduleManifest.push({ id: mod.id, version: mod.version });\n ctx.logger.debug(`Registered module: ${mod.id}`, {\n tools: reg.tools.length,\n resources: reg.resources.length,\n prompts: reg.prompts.length,\n });\n } catch (error) {\n ctx.logger.error(`Failed to register module: ${mod.id}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n const manifest: ServerManifest = {\n modules: moduleManifest,\n tools,\n resources,\n prompts,\n };\n\n ctx.logger.info(`MCP server ready: ${opts.name}@${opts.version}`, {\n modules: manifest.modules.length,\n tools: manifest.tools.length,\n resources: manifest.resources.length,\n prompts: manifest.prompts.length,\n });\n\n return { server, manifest };\n}\n","/**\n * MCP tool result helpers + central handler.\n *\n * Modules NEVER call server.registerTool directly — they use registerTool()\n * from this module so the central try/catch wraps the handler and:\n * - maps thrown McpUserError / McpAuthError / McpInternalError to\n * MCP-protocol-compliant `{ isError: true, content: [...] }` shapes\n * - threads `_meta.progressToken` into ctx.progress for long ops\n * - emits a structured log line on every error\n * - never leaks `cause` from McpInternalError to the client\n *\n * This is the analog of cli-sdk's createProgram() central error handler.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ZodRawShape } from 'zod';\nimport type { McpContext } from './context.js';\nimport { McpAuthError, McpInternalError, McpUserError } from './errors.js';\nimport type { ToolAnnotations } from './tool-governance.js';\n\nexport interface ToolTextContent {\n type: 'text';\n text: string;\n [k: string]: unknown;\n}\n\nexport interface ToolResult {\n content: ToolTextContent[];\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ToolMeta {\n progressToken?: string | number;\n}\n\n/**\n * Build a successful tool result with JSON content (pretty-printed).\n */\nexport function jsonResult(data: unknown, structured?: Record<string, unknown>): ToolResult {\n const result: ToolResult = {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n };\n if (structured !== undefined) {\n result.structuredContent = structured;\n }\n return result;\n}\n\n/**\n * Build a successful tool result with plain text content.\n */\nexport function textResult(text: string): ToolResult {\n return { content: [{ type: 'text', text }] };\n}\n\n/**\n * Build an error tool result. Honors MCP's `{ isError: true, content }` shape.\n * Optional hint is appended on a new line so the LLM can react.\n */\nexport function errorResult(message: string, hint?: string): ToolResult {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return { content: [{ type: 'text', text }], isError: true };\n}\n\nexport interface ToolMetadata {\n title: string;\n description: string;\n inputSchema?: ZodRawShape;\n /**\n * Explicit MCP annotations (readOnlyHint / destructiveHint / ...). Optional\n * — when omitted, `wrapServerWithToolGovernance` (applied centrally in\n * `createMcpServer`) infers them from the tool name. Set this to override\n * the inference for a tool whose name doesn't match the naming convention.\n */\n annotations?: ToolAnnotations;\n}\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n ctx: McpContext,\n meta: ToolMeta,\n) => Promise<unknown>;\n\n/**\n * Register a tool with the central error wrapper.\n *\n * The handler returns a plain value or void. The wrapper:\n * - wraps non-undefined returns in jsonResult()\n * - if the value already looks like a ToolResult (has `content`), passes through\n * - catches McpAuthError / McpUserError / McpInternalError / generic Error\n * - logs every error via ctx.logger.error\n */\nexport function registerTool<TArgs extends Record<string, unknown>>(\n server: McpServer,\n ctx: McpContext,\n name: string,\n metadata: ToolMetadata,\n handler: ToolHandler<TArgs>,\n): void {\n const sdkConfig = {\n title: metadata.title,\n description: metadata.description,\n ...(metadata.inputSchema ? { inputSchema: metadata.inputSchema } : {}),\n ...(metadata.annotations ? { annotations: metadata.annotations } : {}),\n };\n\n // The MCP SDK's registerTool signature is `(name, config, handler)`. The\n // handler arity depends on whether inputSchema is present (1-arg without,\n // 2-arg with). We accept a unified handler shape and dispatch at runtime.\n // The SDK's typing is strict and conditional on the inputSchema generic;\n // bypass with a cast since runtime acceptance is unconditional.\n const wrapped = async (...callbackArgs: unknown[]): Promise<ToolResult> => {\n const hasArgs = callbackArgs.length === 2;\n const args = (hasArgs ? callbackArgs[0] : {}) as TArgs;\n const extra = (hasArgs ? callbackArgs[1] : callbackArgs[0]) as\n | { _meta?: { progressToken?: string | number } }\n | undefined;\n\n const progressToken = extra?._meta?.progressToken;\n const meta: ToolMeta = progressToken !== undefined ? { progressToken } : {};\n\n try {\n const result = await handler(args, ctx, meta);\n if (isToolResult(result)) return result;\n if (result === undefined) return textResult('OK');\n return jsonResult(result);\n } catch (error) {\n return mapErrorToResult(error, ctx, name);\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (server as any).registerTool(name, sdkConfig, wrapped);\n}\n\nfunction isToolResult(value: unknown): value is ToolResult {\n return (\n !!value &&\n typeof value === 'object' &&\n 'content' in value &&\n Array.isArray((value as ToolResult).content)\n );\n}\n\nfunction mapErrorToResult(error: unknown, ctx: McpContext, toolName: string): ToolResult {\n if (error instanceof McpAuthError) {\n ctx.logger.warn(`${toolName}: auth required`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpUserError) {\n ctx.logger.info(`${toolName}: user error`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpInternalError) {\n ctx.logger.error(`${toolName}: internal error`, {\n message: error.message,\n cause: stringifyCause(error.cause),\n });\n return errorResult(`Internal error in ${toolName}.`);\n }\n const message = error instanceof Error ? error.message : String(error);\n ctx.logger.error(`${toolName}: unhandled error`, { message });\n return errorResult(`${toolName}: ${message}`);\n}\n\nfunction stringifyCause(cause: unknown): string | undefined {\n if (cause === undefined || cause === null) return undefined;\n if (cause instanceof Error) return cause.message;\n try {\n return JSON.stringify(cause);\n } catch {\n return String(cause);\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/core/auth/store.ts","../src/core/config/store.ts","../src/core/auth/device-code.ts","../src/core/gql/client.ts","../src/core/logger.ts","../src/core/progress.ts","../src/core/context.ts","../src/core/errors.ts","../src/core/module.ts","../src/core/capabilities.ts","../src/core/tool-name.ts","../src/core/tool-governance.ts","../src/core/server.ts","../src/core/result.ts"],"names":["authFileName","join","existsSync","mkdirSync","readFileSync","writeFileSync","chmodSync","cfg"],"mappings":";;;;;;;;;;AAyCA,IAAM,eAAA,GAAkB,IAAI,EAAA,GAAK,GAA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AAA,gBAAA,CAAA,EAAoB;AAAA,MAC9C,SAAS,KAAA,CAAM,OAAA;AAAA,MACf,KAAA,EAAO,cAAA,CAAe,KAAA,CAAM,KAAK;AAAA,KAClC,CAAA;AACD,IAAA,OAAO,WAAA,CAAY,CAAA,kBAAA,EAAqB,QAAQ,CAAA,CAAA,CAAG,CAAA;AAAA,EACrD;AACA,EAAA,MAAM,UAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,OAAO,KAAK,CAAA;AACrE,EAAA,GAAA,CAAI,OAAO,KAAA,CAAM,CAAA,EAAG,QAAQ,CAAA,iBAAA,CAAA,EAAqB,EAAE,SAAS,CAAA;AAC5D,EAAA,OAAO,WAAA,CAAY,CAAA,EAAG,QAAQ,CAAA,EAAA,EAAK,OAAO,CAAA,CAAE,CAAA;AAC9C;AAEA,SAAS,eAAe,KAAA,EAAoC;AAC1D,EAAA,IAAI,KAAA,KAAU,MAAA,IAAa,KAAA,KAAU,IAAA,EAAM,OAAO,MAAA;AAClD,EAAA,IAAI,KAAA,YAAiB,KAAA,EAAO,OAAO,KAAA,CAAM,OAAA;AACzC,EAAA,IAAI;AACF,IAAA,OAAO,IAAA,CAAK,UAAU,KAAK,CAAA;AAAA,EAC7B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,OAAO,KAAK,CAAA;AAAA,EACrB;AACF","file":"chunk-BSNL65PZ.js","sourcesContent":["/**\n * Auth token persistence — parameterised on configDir.\n *\n * Stores tokens in <configDir>/auth.json with 0o600 perms.\n *\n * StoredAuth shape is a SUPERSET of cli-sdk's StoredAuth (adds api_key auth\n * method + apiKey field). A parity test in tests/unit/auth-store-parity.test.ts\n * keeps the field set in sync with cli-sdk so a shared token store path\n * (vibecontrols-cli/auth.json) works for both consumers.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync, unlinkSync } from 'fs';\nimport { join } from 'path';\n\nexport type AuthMethod = 'device_code' | 'client_credentials' | 'api_key';\n\nexport interface StoredAuth {\n accessToken: string;\n refreshToken: string;\n expiresAt?: number;\n workspaceToken?: string;\n workspaceTokenExpiresAt?: number;\n workspaceId?: string;\n organizationId?: string;\n authMethod?: AuthMethod;\n clientId?: string;\n clientSecret?: string;\n apiKey?: string;\n}\n\nexport interface AuthStore {\n read(): StoredAuth | null;\n write(auth: StoredAuth): void;\n clear(): void;\n isTokenExpired(): boolean;\n isTokenExpiringSoon(): boolean;\n isWorkspaceTokenExpired(): boolean;\n isWorkspaceTokenExpiringSoon(): boolean;\n isAuthenticated(): boolean;\n}\n\nconst TOKEN_BUFFER_MS = 5 * 60 * 1000;\n\nexport function createAuthStore(configDir: string, authFileName = 'auth.json'): AuthStore {\n const authFile = join(configDir, authFileName);\n\n function ensureConfigDir(): void {\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true, mode: 0o700 });\n }\n }\n\n function read(): StoredAuth | null {\n try {\n if (!existsSync(authFile)) return null;\n const raw = readFileSync(authFile, 'utf8');\n return JSON.parse(raw) as StoredAuth;\n } catch {\n return null;\n }\n }\n\n function write(auth: StoredAuth): void {\n ensureConfigDir();\n writeFileSync(authFile, JSON.stringify(auth, null, 2), { encoding: 'utf8', mode: 0o600 });\n try {\n chmodSync(authFile, 0o600);\n } catch {\n // chmod may fail on Windows; non-critical.\n }\n }\n\n function clear(): void {\n try {\n if (existsSync(authFile)) unlinkSync(authFile);\n } catch {\n // ignore\n }\n }\n\n function isTokenExpired(): boolean {\n const auth = read();\n if (!auth?.expiresAt) return false;\n return Date.now() >= auth.expiresAt;\n }\n\n function isTokenExpiringSoon(): boolean {\n const auth = read();\n if (!auth?.expiresAt) return false;\n return Date.now() + TOKEN_BUFFER_MS >= auth.expiresAt;\n }\n\n function isWorkspaceTokenExpired(): boolean {\n const auth = read();\n if (!auth?.workspaceTokenExpiresAt) return false;\n return Date.now() >= auth.workspaceTokenExpiresAt;\n }\n\n function isWorkspaceTokenExpiringSoon(): boolean {\n const auth = read();\n if (!auth?.workspaceTokenExpiresAt) return false;\n return Date.now() + TOKEN_BUFFER_MS >= auth.workspaceTokenExpiresAt;\n }\n\n function isAuthenticated(): boolean {\n const auth = read();\n if (auth?.apiKey) return true;\n if (!auth?.accessToken) return false;\n return !isTokenExpired();\n }\n\n return {\n read,\n write,\n clear,\n isTokenExpired,\n isTokenExpiringSoon,\n isWorkspaceTokenExpired,\n isWorkspaceTokenExpiringSoon,\n isAuthenticated,\n };\n}\n","/**\n * Config store — parameterised on configDirName + product defaults.\n *\n * Persists MCP runtime config to ~/.config/<configDirName>/config.json.\n * Includes both gql-client config (workspace/global endpoints, oidc) and\n * transport config (httpPort, host, corsOrigins, allowedHosts, apiKey).\n *\n * Env-var overrides preserve current vibecontrols-mcp behaviour:\n * VIBECONTROLS_WORKSPACE_ENDPOINT, VIBECONTROLS_GLOBAL_ENDPOINT,\n * VIBECONTROLS_OIDC_ISSUER, VIBECONTROLS_CLIENT_ID,\n * VIBECONTROLS_ACCESS_TOKEN, VIBECONTROLS_REFRESH_TOKEN,\n * VIBECONTROLS_WORKSPACE_TOKEN, VIBECONTROLS_API_KEY (or MCP_API_KEY),\n * VIBECONTROLS_WORKSPACE_ID, VIBECONTROLS_ORGANIZATION_ID,\n * HOST, MCP_HOST, PORT, VIBECONTROLS_HTTP_PORT,\n * CORS_ORIGINS, ALLOWED_HOSTS, LOG_LEVEL, LOG_FORMAT.\n *\n * The shell passes the env-prefix it wants (e.g. VIBECONTROLS_) so other\n * product MCPs don't clash.\n */\n\nimport { readFileSync, writeFileSync, mkdirSync, existsSync, chmodSync } from 'fs';\nimport { join } from 'path';\nimport { homedir } from 'os';\n\nexport interface McpConfig {\n workspaceEndpoint: string;\n globalEndpoint: string;\n oidcIssuer?: string;\n clientId?: string;\n\n /** Pre-loaded auth (typically env-injected for headless service mode). */\n accessToken?: string;\n refreshToken?: string;\n workspaceToken?: string;\n apiKey?: string;\n workspaceId?: string;\n organizationId?: string;\n\n /** HTTP transport */\n host: string;\n httpPort: number;\n corsOrigins: string;\n allowedHosts: string;\n\n /** Logging */\n logLevel: 'error' | 'warn' | 'info' | 'debug';\n logFormat: 'json' | 'text';\n}\n\nexport interface ProductDefaults {\n /** Directory under ~/.config where this product's MCP state lives. */\n configDirName: string;\n /** Default OAuth client id for OIDC device-code flow. */\n oidcClientId: string;\n /** Production OIDC issuer URL (used when endpoints are non-local). */\n oidcIssuerProd?: string;\n /** Default workspace gateway endpoint. */\n workspaceEndpointDefault: string;\n /** Default global gateway endpoint. */\n globalEndpointDefault: string;\n /** Default HTTP transport port. */\n httpPortDefault?: number;\n /** Default host binding (CORS-bound, defaults to 127.0.0.1). */\n hostDefault?: string;\n /** Env-var prefix (e.g. 'VIBECONTROLS'). */\n envPrefix?: string;\n}\n\nexport interface ConfigStore {\n read(): McpConfig;\n write(config: Partial<McpConfig>): void;\n path(): string;\n dir(): string;\n resolveOIDC(): { oidcIssuer: string; clientId: string };\n}\n\nfunction envOr(prefix: string | undefined, key: string, fallback?: string): string | undefined {\n if (prefix) {\n const prefixed = process.env[`${prefix}_${key}`];\n if (prefixed !== undefined && prefixed !== '') return prefixed;\n }\n const direct = process.env[key];\n if (direct !== undefined && direct !== '') return direct;\n return fallback;\n}\n\nexport function createConfigStore(defaults: ProductDefaults): ConfigStore {\n const configDir = join(homedir(), '.config', defaults.configDirName);\n const configFile = join(configDir, 'config.json');\n const envPrefix = defaults.envPrefix ?? defaults.configDirName.toUpperCase().replace(/-/g, '_');\n\n function ensureConfigDir(): void {\n if (!existsSync(configDir)) {\n mkdirSync(configDir, { recursive: true, mode: 0o700 });\n }\n }\n\n function readPersisted(): Partial<McpConfig> {\n try {\n if (!existsSync(configFile)) return {};\n const raw = readFileSync(configFile, 'utf8');\n return JSON.parse(raw) as Partial<McpConfig>;\n } catch {\n return {};\n }\n }\n\n function read(): McpConfig {\n const persisted = readPersisted();\n\n const workspaceEndpoint =\n envOr(envPrefix, 'WORKSPACE_ENDPOINT') ??\n persisted.workspaceEndpoint ??\n defaults.workspaceEndpointDefault;\n\n const globalEndpoint =\n envOr(envPrefix, 'GLOBAL_ENDPOINT') ??\n persisted.globalEndpoint ??\n defaults.globalEndpointDefault;\n\n const httpPortRaw =\n envOr(envPrefix, 'HTTP_PORT') ??\n envOr(undefined, 'PORT') ??\n String(defaults.httpPortDefault ?? 3000);\n\n const logLevelRaw = envOr(undefined, 'LOG_LEVEL') ?? persisted.logLevel ?? 'info';\n const logFormatRaw = envOr(undefined, 'LOG_FORMAT') ?? persisted.logFormat ?? 'json';\n\n return {\n workspaceEndpoint,\n globalEndpoint,\n oidcIssuer: envOr(envPrefix, 'OIDC_ISSUER') ?? persisted.oidcIssuer,\n clientId: envOr(envPrefix, 'CLIENT_ID') ?? persisted.clientId,\n accessToken: envOr(envPrefix, 'ACCESS_TOKEN'),\n refreshToken: envOr(envPrefix, 'REFRESH_TOKEN'),\n workspaceToken: envOr(envPrefix, 'WORKSPACE_TOKEN'),\n apiKey: envOr(envPrefix, 'API_KEY') ?? envOr(undefined, 'MCP_API_KEY'),\n workspaceId: envOr(envPrefix, 'WORKSPACE_ID'),\n organizationId: envOr(envPrefix, 'ORGANIZATION_ID'),\n host:\n envOr(undefined, 'HOST') ??\n envOr(undefined, 'MCP_HOST') ??\n defaults.hostDefault ??\n '127.0.0.1',\n httpPort: parseInt(httpPortRaw, 10) || (defaults.httpPortDefault ?? 3000),\n corsOrigins:\n envOr(undefined, 'CORS_ORIGINS') ??\n persisted.corsOrigins ??\n 'http://127.0.0.1,http://localhost',\n allowedHosts:\n envOr(undefined, 'ALLOWED_HOSTS') ?? persisted.allowedHosts ?? '127.0.0.1,localhost',\n logLevel: (['error', 'warn', 'info', 'debug'] as const).includes(logLevelRaw as 'info')\n ? (logLevelRaw as McpConfig['logLevel'])\n : 'info',\n logFormat: logFormatRaw === 'text' ? 'text' : 'json',\n };\n }\n\n function write(patch: Partial<McpConfig>): void {\n ensureConfigDir();\n const merged = { ...readPersisted(), ...patch };\n writeFileSync(configFile, JSON.stringify(merged, null, 2), { encoding: 'utf8' });\n try {\n chmodSync(configFile, 0o600);\n } catch {\n // chmod may fail on Windows; non-critical.\n }\n }\n\n function resolveOIDC(): { oidcIssuer: string; clientId: string } {\n const config = read();\n const clientId = config.clientId || defaults.oidcClientId;\n\n let oidcIssuer = config.oidcIssuer;\n if (!oidcIssuer) {\n const globalEndpoint = config.globalEndpoint;\n if (globalEndpoint.includes('localhost') || globalEndpoint.includes('127.0.0.1')) {\n oidcIssuer = globalEndpoint\n .replace(/\\/graphql$/, '')\n .replace(/\\/global\\/graphql$/, '/global');\n } else {\n oidcIssuer = defaults.oidcIssuerProd ?? 'https://graphql.burdenoff.com/global';\n }\n }\n\n return { oidcIssuer, clientId };\n }\n\n return {\n read,\n write,\n path: () => configFile,\n dir: () => configDir,\n resolveOIDC,\n };\n}\n","/**\n * OAuth2 Device Code flow + Client Credentials flow + workspace token issuance.\n * Pure functions — operate on injected endpoints + client ids, no global state.\n *\n * Mirrors cli-sdk/src/core/auth/device-code.ts so a future shared\n * @burdenoff/auth-core extraction is mechanical.\n */\n\nimport fetch from 'cross-fetch';\n\nexport interface DeviceCodeResponse {\n deviceCode: string;\n userCode: string;\n verificationUri: string;\n verificationUriComplete: string | null;\n expiresIn: number;\n interval: number;\n}\n\nexport interface DeviceCodeTokenResult {\n accessToken: string;\n refreshToken: string;\n expiresIn: number;\n}\n\nexport interface ClientCredentialsResult {\n accessToken: string;\n expiresIn: number;\n scopes: string[];\n}\n\nexport interface OIDCConfig {\n oidcIssuer: string;\n clientId: string;\n}\n\nexport async function startDeviceCodeFlow(config: OIDCConfig): Promise<DeviceCodeResponse> {\n const url = `${config.oidcIssuer}/oidc/device/code`;\n const body = new URLSearchParams({\n client_id: config.clientId,\n scope: 'openid profile email offline_access',\n });\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`Device code request failed (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as Record<string, unknown>;\n\n return {\n deviceCode: data['device_code'] as string,\n userCode: data['user_code'] as string,\n verificationUri: data['verification_uri'] as string,\n verificationUriComplete: (data['verification_uri_complete'] as string) ?? null,\n expiresIn: data['expires_in'] as number,\n interval: (data['interval'] as number) ?? 5,\n };\n}\n\nexport type DeviceTokenPollResult =\n | { status: 'authenticated'; tokens: DeviceCodeTokenResult }\n | { status: 'pending' }\n | { status: 'slow_down'; newInterval: number }\n | { status: 'expired' }\n | { status: 'denied' };\n\n/**\n * Single-shot device-code token poll.\n *\n * Unlike cli-sdk's pollForToken which loops until done (suitable for blocking\n * CLI), MCP needs non-blocking semantics: the LLM calls auth_complete tool\n * repeatedly. This helper makes ONE poll attempt and returns a discriminated\n * union the caller can act on.\n */\nexport async function pollDeviceTokenOnce(\n deviceCode: string,\n interval: number,\n config: OIDCConfig,\n): Promise<DeviceTokenPollResult> {\n const url = `${config.oidcIssuer}/oauth/device/token`;\n\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: new URLSearchParams({\n grant_type: 'urn:ietf:params:oauth:grant-type:device_code',\n device_code: deviceCode,\n client_id: config.clientId,\n }).toString(),\n });\n\n const data = (await response.json()) as Record<string, unknown>;\n\n if (response.ok && data['access_token']) {\n return {\n status: 'authenticated',\n tokens: {\n accessToken: data['access_token'] as string,\n refreshToken: (data['refresh_token'] as string) ?? '',\n expiresIn: (data['expires_in'] as number) ?? 3600,\n },\n };\n }\n\n const errorCode = data['error'] as string | undefined;\n switch (errorCode) {\n case 'authorization_pending':\n return { status: 'pending' };\n case 'slow_down':\n return { status: 'slow_down', newInterval: interval + 5 };\n case 'expired_token':\n return { status: 'expired' };\n case 'access_denied':\n return { status: 'denied' };\n default:\n throw new Error(\n `Device code polling failed: ${(data['error_description'] as string) ?? errorCode ?? 'Unknown error'}`,\n );\n }\n}\n\nexport async function clientCredentialsFlow(\n globalEndpoint: string,\n clientId: string,\n clientSecret: string,\n scopes?: string[],\n): Promise<ClientCredentialsResult> {\n const query = `\n mutation AuthenticateApp($input: AuthenticateAppInput!) {\n authenticateApp(input: $input) {\n accessToken tokenType expiresIn scopes\n }\n }\n `;\n\n const response = await fetch(globalEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n query,\n variables: { input: { clientId, clientSecret, scopes } },\n }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`App authentication failed (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n data?: { authenticateApp: { accessToken: string; expiresIn: number; scopes: string[] } };\n errors?: Array<{ message: string }>;\n };\n\n if (data.errors?.length) {\n throw new Error(`App authentication failed: ${data.errors[0]?.message ?? 'unknown error'}`);\n }\n if (!data.data?.authenticateApp?.accessToken) {\n throw new Error('App authentication failed: no access token returned');\n }\n\n return data.data.authenticateApp;\n}\n\nexport async function issueWorkspaceToken(\n workspaceEndpoint: string,\n authToken: string,\n workspaceId: string,\n organizationId: string,\n): Promise<{ token: string; expiresAt: string; scopes: string[] }> {\n const query = `\n mutation IssueWorkspaceToken($input: IssueWorkspaceTokenInput!) {\n issueWorkspaceToken(input: $input) {\n success token expiresAt scopes\n error { code message }\n }\n }\n `;\n\n const response = await fetch(workspaceEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}` },\n body: JSON.stringify({ query, variables: { input: { workspaceId, organizationId } } }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`Workspace token request failed (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n data?: {\n issueWorkspaceToken: {\n success: boolean;\n token: string | null;\n expiresAt: string | null;\n scopes: string[] | null;\n error: { code: string; message: string } | null;\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (data.errors?.length) {\n throw new Error(`Workspace token failed: ${data.errors[0]?.message ?? 'unknown error'}`);\n }\n\n const result = data.data?.issueWorkspaceToken;\n if (!result?.success || !result.token) {\n throw new Error(`Workspace token failed: ${result?.error?.message ?? 'Unknown error'}`);\n }\n\n return { token: result.token, expiresAt: result.expiresAt ?? '', scopes: result.scopes ?? [] };\n}\n\nexport async function fetchWorkspaces(\n globalEndpoint: string,\n authToken: string,\n): Promise<\n Array<{ id: string; name: string; slug: string; tenantId: string; organizationId: string }>\n> {\n const query = `\n query MyWorkspaces($limit: Int) {\n myWorkspaces(limit: $limit) {\n items { id name slug tenantId organizationId }\n }\n }\n `;\n\n const response = await fetch(globalEndpoint, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${authToken}` },\n body: JSON.stringify({ query, variables: { limit: 50 } }),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => 'Unknown error');\n throw new Error(`Failed to fetch workspaces (${response.status}): ${text}`);\n }\n\n const data = (await response.json()) as {\n data?: {\n myWorkspaces: {\n items: Array<{\n id: string;\n name: string;\n slug: string;\n tenantId: string;\n organizationId: string;\n }>;\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (data.errors?.length) {\n throw new Error(`Failed to fetch workspaces: ${data.errors[0]?.message ?? 'unknown error'}`);\n }\n\n return data.data?.myWorkspaces?.items ?? [];\n}\n","/**\n * GraphQL client factory — produces three clients (workspace, global,\n * workspaceAuthOnly) sharing an injected ConfigStore + AuthStore.\n *\n * - Auto-refreshes platform + workspace tokens on the workspace client.\n * - Workspace client requires authentication; ensures fresh tokens before each call.\n * - Global client does NOT trigger refresh (avoids loops during auth flows).\n * - workspaceAuthOnly omits X-Workspace-Authorization (used to bootstrap\n * workspace token issuance).\n *\n * Ported from cli-sdk/src/core/gql/client.ts with a minor change: a static\n * `apiKey` is injected as `X-API-Key` header when StoredAuth.apiKey is set\n * (allows headless service-mode auth without device code).\n */\n\nimport { GraphQLClient, type RequestDocument, type Variables } from 'graphql-request';\nimport type { AuthStore, StoredAuth } from '../auth/store.js';\nimport type { ConfigStore } from '../config/store.js';\nimport { clientCredentialsFlow, issueWorkspaceToken } from '../auth/device-code.js';\n\nconst DEFAULT_TIMEOUT = 30_000;\nconst MAX_RETRIES = 3;\nconst INITIAL_RETRY_DELAY_MS = 1_000;\n\nexport interface GqlClient {\n request<T>(document: RequestDocument, variables?: Variables): Promise<T>;\n}\n\nexport interface GqlClients {\n workspace: GqlClient;\n global: GqlClient;\n workspaceAuthOnly: GqlClient;\n reset(): void;\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction isNetworkOrServerError(error: unknown): boolean {\n if (error instanceof TypeError) return true;\n if (error && typeof error === 'object' && 'response' in error) {\n const resp = (error as { response?: { status?: number } }).response;\n if (resp && typeof resp.status === 'number' && resp.status >= 500) return true;\n }\n return false;\n}\n\nexport function extractGqlErrorMessage(error: unknown): string {\n if (error && typeof error === 'object' && 'response' in error) {\n const resp = error as {\n response?: { errors?: Array<{ message?: string }>; status?: number };\n message?: string;\n };\n const firstError = resp.response?.errors?.[0];\n if (firstError?.message) return firstError.message;\n if (resp.message) return resp.message;\n }\n if (error instanceof Error) return error.message;\n return String(error);\n}\n\nfunction getHeaders(auth: StoredAuth | null): Record<string, string> {\n const headers: Record<string, string> = {};\n if (auth?.apiKey) headers['X-API-Key'] = auth.apiKey;\n if (auth?.accessToken) headers['Authorization'] = `Bearer ${auth.accessToken}`;\n if (auth?.organizationId) headers['x-org-id'] = auth.organizationId;\n return headers;\n}\n\nfunction getWorkspaceHeaders(auth: StoredAuth | null): Record<string, string> {\n const headers = getHeaders(auth);\n if (auth?.workspaceToken) {\n headers['X-Workspace-Authorization'] = `Bearer ${auth.workspaceToken}`;\n }\n if (auth?.workspaceId) headers['x-workspace-id'] = auth.workspaceId;\n return headers;\n}\n\nasync function executeWithRetry<T>(\n client: GraphQLClient,\n document: RequestDocument,\n variables?: Variables,\n): Promise<T> {\n let lastError: unknown;\n\n for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), DEFAULT_TIMEOUT);\n try {\n return await client.request<T>({ document, variables, signal: controller.signal });\n } finally {\n clearTimeout(timer);\n }\n } catch (error: unknown) {\n lastError = error;\n\n if (error && typeof error === 'object' && 'response' in error) {\n const resp = (error as { response?: { status?: number } }).response;\n if (resp && typeof resp.status === 'number' && resp.status >= 400 && resp.status < 500) {\n break;\n }\n }\n\n if (isNetworkOrServerError(error) && attempt < MAX_RETRIES - 1) {\n const delay = INITIAL_RETRY_DELAY_MS * Math.pow(2, attempt);\n await sleep(delay);\n continue;\n }\n\n break;\n }\n }\n\n throw new Error(extractGqlErrorMessage(lastError));\n}\n\nexport function createGqlClients(config: ConfigStore, authStore: AuthStore): GqlClients {\n let workspaceClient: GraphQLClient | null = null;\n let globalClient: GraphQLClient | null = null;\n\n function init(): { workspace: GraphQLClient; global: GraphQLClient } {\n const cfg = config.read();\n const auth = authStore.read();\n\n workspaceClient = new GraphQLClient(cfg.workspaceEndpoint);\n workspaceClient.setHeaders(getWorkspaceHeaders(auth));\n\n globalClient = new GraphQLClient(cfg.globalEndpoint);\n globalClient.setHeaders(getHeaders(auth));\n\n return { workspace: workspaceClient, global: globalClient };\n }\n\n async function refreshPlatformToken(): Promise<void> {\n const auth = authStore.read();\n if (!auth) return;\n\n if (auth.authMethod === 'client_credentials' && auth.clientId && auth.clientSecret) {\n const cfg = config.read();\n try {\n const result = await clientCredentialsFlow(\n cfg.globalEndpoint,\n auth.clientId,\n auth.clientSecret,\n );\n authStore.write({\n ...auth,\n accessToken: result.accessToken,\n expiresAt: Date.now() + result.expiresIn * 1000,\n });\n workspaceClient = null;\n globalClient = null;\n } catch {\n // swallow — caller sees expired-token failure on next request\n }\n return;\n }\n\n if (!auth.refreshToken) return;\n\n const cfg = config.read();\n const client = new GraphQLClient(cfg.globalEndpoint);\n client.setHeaders({ Authorization: `Bearer ${auth.accessToken}` });\n\n const REFRESH_MUTATION = `\n mutation RefreshToken($token: String!) {\n refreshToken(token: $token) { accessToken refreshToken expiresIn }\n }\n `;\n\n interface RefreshResponse {\n refreshToken: { accessToken: string; refreshToken: string; expiresIn: number };\n }\n\n try {\n const data = await client.request<RefreshResponse>(REFRESH_MUTATION, {\n token: auth.refreshToken,\n });\n authStore.write({\n ...auth,\n accessToken: data.refreshToken.accessToken,\n refreshToken: data.refreshToken.refreshToken,\n expiresAt: Date.now() + data.refreshToken.expiresIn * 1000,\n });\n workspaceClient = null;\n globalClient = null;\n } catch {\n // swallow — surfaced on next request\n }\n }\n\n async function refreshWorkspaceToken(): Promise<void> {\n const auth = authStore.read();\n if (!auth?.accessToken || !auth.workspaceId || !auth.organizationId) return;\n\n const cfg = config.read();\n try {\n const result = await issueWorkspaceToken(\n cfg.workspaceEndpoint,\n auth.accessToken,\n auth.workspaceId,\n auth.organizationId,\n );\n authStore.write({\n ...auth,\n workspaceToken: result.token,\n workspaceTokenExpiresAt: new Date(result.expiresAt).getTime(),\n });\n workspaceClient = null;\n } catch {\n // swallow — surfaced on next request\n }\n }\n\n async function ensureFreshTokens(): Promise<void> {\n const initial = authStore.read();\n if (initial?.apiKey) return; // API-key auth never expires\n\n if (authStore.isTokenExpiringSoon()) {\n await refreshPlatformToken();\n }\n if (authStore.isWorkspaceTokenExpiringSoon()) {\n await refreshWorkspaceToken();\n }\n }\n\n const workspace: GqlClient = {\n async request<T>(document: RequestDocument, variables?: Variables): Promise<T> {\n await ensureFreshTokens();\n const { workspace: ws } = workspaceClient ? { workspace: workspaceClient } : init();\n ws.setHeaders(getWorkspaceHeaders(authStore.read()));\n return executeWithRetry<T>(ws, document, variables);\n },\n };\n\n const global: GqlClient = {\n async request<T>(document: RequestDocument, variables?: Variables): Promise<T> {\n const { global: g } = globalClient ? { global: globalClient } : init();\n g.setHeaders(getHeaders(authStore.read()));\n return executeWithRetry<T>(g, document, variables);\n },\n };\n\n const workspaceAuthOnly: GqlClient = {\n async request<T>(document: RequestDocument, variables?: Variables): Promise<T> {\n const cfg = config.read();\n const auth = authStore.read();\n const client = new GraphQLClient(cfg.workspaceEndpoint);\n client.setHeaders(getHeaders(auth));\n return executeWithRetry<T>(client, document, variables);\n },\n };\n\n return {\n workspace,\n global,\n workspaceAuthOnly,\n reset(): void {\n workspaceClient = null;\n globalClient = null;\n },\n };\n}\n","/**\n * Structured logger for MCP SDK.\n *\n * Routes through process.stderr only — stdio transport reserves stdout for\n * JSON-RPC protocol messages. Modules NEVER use console.log/console.error\n * directly: that would corrupt the stdio stream.\n *\n * Supports MCP `logging/setLevel` requests via setLevel() — wire this to the\n * server's request handler so clients can dynamically control verbosity.\n */\n\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug';\nexport type LogFormat = 'json' | 'text';\n\nexport interface LogContext {\n [key: string]: unknown;\n}\n\nexport interface Logger {\n error(message: string, context?: LogContext): void;\n warn(message: string, context?: LogContext): void;\n info(message: string, context?: LogContext): void;\n debug(message: string, context?: LogContext): void;\n setLevel(level: LogLevel): void;\n getLevel(): LogLevel;\n}\n\nexport interface LoggerOptions {\n level?: LogLevel;\n format?: LogFormat;\n}\n\nconst LEVEL_RANK: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n};\n\nexport function createLogger(opts: LoggerOptions = {}): Logger {\n let level: LogLevel = opts.level ?? (process.env.LOG_LEVEL as LogLevel) ?? 'info';\n const format: LogFormat = opts.format ?? (process.env.LOG_FORMAT as LogFormat) ?? 'json';\n\n function shouldLog(target: LogLevel): boolean {\n return LEVEL_RANK[target] <= LEVEL_RANK[level];\n }\n\n function formatMessage(target: LogLevel, message: string, context?: LogContext): string {\n const timestamp = new Date().toISOString();\n if (format === 'json') {\n return JSON.stringify({ timestamp, level: target, message, ...context });\n }\n const contextStr = context ? ` ${JSON.stringify(context)}` : '';\n return `[${timestamp}] ${target.toUpperCase()}: ${message}${contextStr}`;\n }\n\n function emit(target: LogLevel, message: string, context?: LogContext): void {\n if (!shouldLog(target)) return;\n process.stderr.write(formatMessage(target, message, context) + '\\n');\n }\n\n return {\n error(message, context): void {\n emit('error', message, context);\n },\n warn(message, context): void {\n emit('warn', message, context);\n },\n info(message, context): void {\n emit('info', message, context);\n },\n debug(message, context): void {\n emit('debug', message, context);\n },\n setLevel(newLevel): void {\n level = newLevel;\n },\n getLevel(): LogLevel {\n return level;\n },\n };\n}\n","/**\n * Progress notification helper.\n *\n * MCP supports `notifications/progress` for long-running tool calls. The client\n * passes a `progressToken` in `_meta`; the server emits progress against that\n * token. When no token is present, ctx.progress() no-ops.\n *\n * Pattern in a tool handler:\n * await registerTool(server, ctx, name, meta, async (args, ctx, meta) => {\n * ctx.progress(meta.progressToken, 0, 100, 'starting');\n * // ... work\n * ctx.progress(meta.progressToken, 50, 100, 'halfway');\n * // ... more work\n * ctx.progress(meta.progressToken, 100, 100, 'done');\n * });\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n\nexport type ProgressFn = (\n token: string | number | undefined,\n current: number,\n total?: number,\n message?: string,\n) => void;\n\nexport function createProgress(serverRef: { current: McpServer | null }): ProgressFn {\n return (token, current, total, message) => {\n if (token === undefined || token === null) return;\n const server = serverRef.current;\n if (!server) return;\n try {\n const params: {\n progressToken: string | number;\n progress: number;\n total?: number;\n message?: string;\n } = { progressToken: token, progress: current };\n if (total !== undefined) params.total = total;\n if (message !== undefined) params.message = message;\n // The McpServer exposes the underlying Server which has a notification method;\n // wrap defensively because shapes vary across SDK versions.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const inner = (server as any).server ?? server;\n inner.notification?.({ method: 'notifications/progress', params });\n } catch {\n // ignore — progress is best-effort\n }\n };\n}\n","/**\n * McpContext — the prop bag injected by the shell into every module.\n *\n * Modules receive this via `register(server, ctx)` and use only what they\n * need. No module should reach for global state.\n */\n\nimport { createAuthStore, type AuthStore } from './auth/store.js';\nimport { createConfigStore, type ConfigStore, type ProductDefaults } from './config/store.js';\nimport { createGqlClients, type GqlClients } from './gql/client.js';\nimport { createLogger, type Logger, type LoggerOptions } from './logger.js';\nimport { createProgress, type ProgressFn } from './progress.js';\n\nexport type Environment = 'prod' | 'alpha' | 'dev' | 'local';\n\nexport interface McpContext {\n productName: string;\n productVersion: string;\n serverName: string;\n serverVersion: string;\n defaults: ProductDefaults;\n config: ConfigStore;\n auth: AuthStore;\n gql: GqlClients;\n logger: Logger;\n progress: ProgressFn;\n env: Environment;\n\n /** Internal: server reference is mutated post-construction in createMcpServer. */\n _internal: {\n serverRef: { current: import('@modelcontextprotocol/sdk/server/mcp.js').McpServer | null };\n };\n}\n\nexport interface BuildContextOptions {\n productName: string;\n productVersion: string;\n serverName: string;\n serverVersion: string;\n defaults: ProductDefaults;\n logger?: LoggerOptions | Logger;\n env?: Environment;\n /**\n * Override the auth file path. Defaults to `<configDir>/auth.json`.\n * Set this to `~/.config/<product>-cli/auth.json` to share token\n * storage with the corresponding CLI.\n */\n tokenStorePath?: string;\n}\n\nfunction inferEnv(workspaceEndpoint: string): Environment {\n if (workspaceEndpoint.includes('localhost') || workspaceEndpoint.includes('127.0.0.1')) {\n return 'local';\n }\n if (workspaceEndpoint.includes('alpha')) return 'alpha';\n return 'prod';\n}\n\nfunction isLogger(value: LoggerOptions | Logger | undefined): value is Logger {\n return (\n !!value &&\n typeof (value as Logger).debug === 'function' &&\n typeof (value as Logger).info === 'function'\n );\n}\n\nexport function buildContext(opts: BuildContextOptions): McpContext {\n const config = createConfigStore(opts.defaults);\n const cfg = config.read();\n\n const logger = isLogger(opts.logger)\n ? opts.logger\n : createLogger({\n ...(opts.logger as LoggerOptions | undefined),\n level: cfg.logLevel,\n format: cfg.logFormat,\n });\n\n const auth = createAuthStore(\n opts.tokenStorePath ? dirOf(opts.tokenStorePath) : config.dir(),\n authFileName(opts.tokenStorePath),\n );\n\n // Seed env-injected tokens if persisted store is empty (headless service mode).\n const existing = auth.read();\n if (!existing && (cfg.accessToken || cfg.apiKey)) {\n auth.write({\n accessToken: cfg.accessToken ?? '',\n refreshToken: cfg.refreshToken ?? '',\n ...(cfg.workspaceToken ? { workspaceToken: cfg.workspaceToken } : {}),\n ...(cfg.workspaceId ? { workspaceId: cfg.workspaceId } : {}),\n ...(cfg.organizationId ? { organizationId: cfg.organizationId } : {}),\n ...(cfg.apiKey ? { apiKey: cfg.apiKey, authMethod: 'api_key' as const } : {}),\n });\n }\n\n const gql = createGqlClients(config, auth);\n const env = opts.env ?? inferEnv(cfg.workspaceEndpoint);\n\n const serverRef: { current: import('@modelcontextprotocol/sdk/server/mcp.js').McpServer | null } =\n { current: null };\n const progress = createProgress(serverRef);\n\n return {\n productName: opts.productName,\n productVersion: opts.productVersion,\n serverName: opts.serverName,\n serverVersion: opts.serverVersion,\n defaults: opts.defaults,\n config,\n auth,\n gql,\n logger,\n progress,\n env,\n _internal: { serverRef },\n };\n}\n\nfunction dirOf(p: string): string {\n const lastSlash = p.lastIndexOf('/');\n return lastSlash > 0 ? p.slice(0, lastSlash) : p;\n}\n\nfunction authFileName(p?: string): string | undefined {\n if (!p) return undefined;\n const lastSlash = p.lastIndexOf('/');\n return lastSlash >= 0 ? p.slice(lastSlash + 1) : p;\n}\n","/**\n * Error classes for MCP SDK.\n *\n * Modules MUST throw these instead of throwing raw Errors. The registerTool\n * wrapper in result.ts catches and maps them to MCP-protocol-compliant\n * `{ isError: true, content: [...] }` responses.\n *\n * Throwing past the wrapper to the protocol surfaces as JSON-RPC -32603 to\n * the client and is a protocol bug.\n */\n\nexport class McpUserError extends Error {\n public readonly hint: string | undefined;\n\n constructor(message: string, opts?: { hint?: string }) {\n super(message);\n this.name = 'McpUserError';\n this.hint = opts?.hint;\n }\n}\n\nexport class McpAuthError extends McpUserError {\n constructor(message: string, opts?: { hint?: string }) {\n super(message, {\n hint: opts?.hint ?? 'Run the auth_login tool to authenticate.',\n });\n this.name = 'McpAuthError';\n }\n}\n\nexport class McpInternalError extends Error {\n public override readonly cause: unknown;\n\n constructor(message: string, cause?: unknown) {\n super(message);\n this.name = 'McpInternalError';\n this.cause = cause;\n }\n}\n","/**\n * McpModule contract + dependency-aware loader.\n *\n * Each entry under src/modules/<name>/ default-exports an McpModule. The\n * shell passes an array of modules to createMcpServer(); the loader topo-\n * sorts them, fails fast on missing deps, and calls register() on each.\n *\n * register() returns a ModuleRegistration manifest of what was registered\n * — used by the shell to log a deterministic boot line and by the snapshot\n * test in Phase 1 to diff against a captured pre-refactor manifest.\n *\n * Mirrors cli-sdk/src/core/module.ts with addition of capabilities + manifest.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { McpContext } from './context.js';\nimport type { McpCapabilities } from './capabilities.js';\nimport { McpInternalError } from './errors.js';\n\nexport interface ModuleRegistration {\n tools: readonly string[];\n resources: readonly string[];\n prompts: readonly string[];\n}\n\nexport interface McpModule {\n readonly id: string;\n readonly version: string;\n readonly displayName: string;\n readonly dependsOn?: readonly string[];\n readonly capabilities?: McpCapabilities;\n register(server: McpServer, ctx: McpContext): ModuleRegistration;\n}\n\nexport class MissingDependencyError extends McpInternalError {\n constructor(moduleId: string, missingDep: string) {\n super(\n `Module '${moduleId}' declares dependency on '${missingDep}', but '${missingDep}' is not in the module list.`,\n );\n this.name = 'MissingDependencyError';\n }\n}\n\nexport class CircularDependencyError extends McpInternalError {\n constructor(cycle: readonly string[]) {\n super(`Circular dependency detected among modules: ${cycle.join(' -> ')}`);\n this.name = 'CircularDependencyError';\n }\n}\n\n/**\n * Topologically sort modules by their `dependsOn` declarations.\n * Throws MissingDependencyError or CircularDependencyError on bad input.\n */\nexport function sortModules(modules: readonly McpModule[]): McpModule[] {\n const byId = new Map<string, McpModule>();\n for (const m of modules) {\n if (byId.has(m.id)) {\n throw new McpInternalError(`Duplicate module id: '${m.id}'`);\n }\n byId.set(m.id, m);\n }\n\n for (const m of modules) {\n for (const dep of m.dependsOn ?? []) {\n if (!byId.has(dep)) {\n throw new MissingDependencyError(m.id, dep);\n }\n }\n }\n\n const sorted: McpModule[] = [];\n const visiting = new Set<string>();\n const visited = new Set<string>();\n\n function visit(m: McpModule, path: string[]): void {\n if (visited.has(m.id)) return;\n if (visiting.has(m.id)) {\n throw new CircularDependencyError([...path, m.id]);\n }\n visiting.add(m.id);\n for (const dep of m.dependsOn ?? []) {\n const depModule = byId.get(dep);\n if (depModule) visit(depModule, [...path, m.id]);\n }\n visiting.delete(m.id);\n visited.add(m.id);\n sorted.push(m);\n }\n\n for (const m of modules) {\n visit(m, []);\n }\n return sorted;\n}\n\nexport interface ServerManifest {\n modules: readonly { id: string; version: string }[];\n tools: readonly string[];\n resources: readonly string[];\n prompts: readonly string[];\n}\n","/**\n * Module capability declaration + union helper.\n *\n * Each McpModule declares the MCP capabilities it requires. The shell unions\n * all capabilities before constructing McpServer, so a module that needs\n * resources.subscribe (e.g. live agent heartbeat) gets it without any\n * shell-side knowledge.\n *\n * Reference: https://modelcontextprotocol.io/specification/2025-03-26/server/capabilities\n */\n\nexport interface McpCapabilities {\n resources?: { subscribe?: boolean; listChanged?: boolean };\n prompts?: { listChanged?: boolean };\n tools?: { listChanged?: boolean };\n logging?: boolean;\n completions?: boolean;\n}\n\n/**\n * Union an array of capability declarations. Boolean unions on logging /\n * completions; OR on every nested boolean.\n */\nexport function unionCapabilities(caps: readonly (McpCapabilities | undefined)[]): McpCapabilities {\n const out: McpCapabilities = {};\n\n for (const cap of caps) {\n if (!cap) continue;\n if (cap.resources) {\n out.resources ??= {};\n if (cap.resources.subscribe) out.resources.subscribe = true;\n if (cap.resources.listChanged) out.resources.listChanged = true;\n }\n if (cap.prompts) {\n out.prompts ??= {};\n if (cap.prompts.listChanged) out.prompts.listChanged = true;\n }\n if (cap.tools) {\n out.tools ??= {};\n if (cap.tools.listChanged) out.tools.listChanged = true;\n }\n if (cap.logging) out.logging = true;\n if (cap.completions) out.completions = true;\n }\n\n return out;\n}\n\n/**\n * Convert capability declaration into the shape the MCP SDK accepts at\n * `new McpServer({ capabilities })`. The SDK uses `{}` as truthy markers.\n */\nexport function toServerCapabilities(caps: McpCapabilities): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (caps.tools) out.tools = caps.tools;\n if (caps.resources) out.resources = caps.resources;\n if (caps.prompts) out.prompts = caps.prompts;\n if (caps.logging) out.logging = {};\n if (caps.completions) out.completions = {};\n return out;\n}\n","/**\n * Tool / resource / prompt naming helpers.\n *\n * Mandatory product prefix avoids collisions when Claude Desktop runs\n * multiple MCP servers concurrently (typical setup is ~6).\n *\n * Tool names are capped at 63 characters — Claude Desktop pre-1.x\n * truncated at 64 in some versions.\n */\n\nimport { McpInternalError } from './errors.js';\n\nconst MAX_TOOL_NAME_LENGTH = 63;\n\nfunction assertSafeName(name: string, kind: 'tool' | 'resource' | 'prompt'): string {\n if (kind === 'tool' && name.length > MAX_TOOL_NAME_LENGTH) {\n throw new McpInternalError(\n `Tool name '${name}' exceeds ${MAX_TOOL_NAME_LENGTH} characters (some MCP clients truncate at 64).`,\n );\n }\n return name;\n}\n\n/**\n * Build a tool name. Format: `<productName>_<...parts>` (snake_case).\n * Example: mcpToolName('vibecontrols', 'vibes', 'list') -> 'vibecontrols_vibes_list'\n */\nexport function mcpToolName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpToolName: productName is required');\n }\n const name = [productName, ...parts].filter(Boolean).join('_');\n return assertSafeName(name, 'tool');\n}\n\n/**\n * Build a resource URI. Format: `<productName>://<...parts>`.\n * Example: mcpResourceUri('vibecontrols', 'schema') -> 'vibecontrols://schema'\n */\nexport function mcpResourceUri(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpResourceUri: productName is required');\n }\n return `${productName}://${parts.filter(Boolean).join('/')}`;\n}\n\n/**\n * Build a prompt name. Format: `<productName>-<...parts>` (kebab-case).\n * Example: mcpPromptName('vibecontrols', 'setup') -> 'vibecontrols-setup'\n */\nexport function mcpPromptName(productName: string, ...parts: string[]): string {\n if (!productName) {\n throw new McpInternalError('mcpPromptName: productName is required');\n }\n return [productName, ...parts].filter(Boolean).join('-');\n}\n\nexport const TOOL_NAME_LIMIT = MAX_TOOL_NAME_LENGTH;\n\n/**\n * Name-based hint heuristics for MCP `annotations` (readOnlyHint /\n * destructiveHint). Used by tool-governance.ts to auto-fill annotations for\n * the fleet of product modules that call `server.registerTool` directly\n * (bypassing the `registerTool()` core helper) and so never set them\n * explicitly today (BOFF-3903). Deliberately conservative — matched against\n * whole `_`-delimited segments so e.g. `timeentries_delete` and\n * `pomodoro_delete_goal` match, but a hypothetical `undeletable_check`\n * would not.\n *\n * A module can always override the inference by passing an explicit\n * `annotations` object to `registerTool()` / `server.registerTool()`.\n */\nconst DESTRUCTIVE_NAME_SEGMENT = /(?:^|_)delete(?:_|$)/i;\nconst READ_ONLY_NAME_SEGMENT = /(?:^|_)(?:list|get|search|check|read|count|stats|by_date)(?:_|$)/i;\n\n/** True when a tool name looks destructive (irreversibly deletes data) by naming convention. */\nexport function inferDestructiveHint(toolName: string): boolean {\n return DESTRUCTIVE_NAME_SEGMENT.test(toolName);\n}\n\n/**\n * True when a tool name looks read-only by naming convention. Never true for\n * a name that also looks destructive (a tool can't be both).\n */\nexport function inferReadOnlyHint(toolName: string): boolean {\n return !inferDestructiveHint(toolName) && READ_ONLY_NAME_SEGMENT.test(toolName);\n}\n","/**\n * Fleet-wide tool governance: MCP `annotations` inference + an opt-in\n * confirmation gate on destructive tools.\n *\n * BOFF-3903: an audit of mcp-libs/src/modules/timecampus/tools/ found 163\n * registered tools, ~35 of them destructive (delete/bulk-delete), with ZERO\n * `annotations.destructiveHint`/`readOnlyHint` anywhere and no confirmation\n * step before a destructive call executes. The same is true fleet-wide —\n * every product module calls `server.registerTool` directly (bypassing the\n * `registerTool()` central wrapper in result.ts), so a per-module fix would\n * have to be re-applied ~54 times.\n *\n * `wrapServerWithToolGovernance` fixes this ONCE, at the McpServer boundary\n * inside `createMcpServer`, by monkey-patching `registerTool` before any\n * module receives the server reference. Every subsequent `registerTool`\n * call — whether it goes through result.ts's `registerTool()` helper or\n * calls `server.registerTool` directly — passes through this wrapper:\n *\n * 1. `annotations.readOnlyHint` / `destructiveHint` are filled in from the\n * tool name (see tool-name.ts's inferDestructiveHint/inferReadOnlyHint)\n * whenever a module didn't declare them explicitly. This is pure\n * metadata — it never changes a tool's input schema or behavior, so it\n * is always safe to apply and every consumer gets it automatically.\n * 2. Only when `enforceDestructiveConfirmation` is true (opt-in,\n * defaults to false) does a resolved-destructive tool additionally get\n * a `confirm` input field and a hard gate: the tool's real handler is\n * never invoked unless the caller passes `confirm: true`. This is\n * deliberately opt-in — flipping it on is a real behavior change for\n * any existing MCP client automation calling that tool, so each product\n * shell (starting with timecampus-mcp for BOFF-3903) turns it on\n * explicitly via `createMcpServer`'s options once it's ready, rather\n * than every one of the ~54 modules' existing destructive-tool callers\n * breaking the moment this ships.\n */\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { z, type ZodRawShape } from 'zod';\n\nimport { inferDestructiveHint, inferReadOnlyHint } from './tool-name.js';\n\n/** MCP tool annotations (per the MCP spec's `ToolAnnotations` shape). */\nexport interface ToolAnnotations {\n title?: string;\n readOnlyHint?: boolean;\n destructiveHint?: boolean;\n idempotentHint?: boolean;\n openWorldHint?: boolean;\n}\n\nexport interface ToolGovernanceOptions {\n /**\n * Require `confirm: true` before invoking any tool resolved as\n * destructive (explicit `annotations.destructiveHint`, or inferred from\n * the tool name). Defaults to false.\n */\n enforceDestructiveConfirmation?: boolean;\n}\n\ninterface GovernedRegisterToolConfig {\n title?: string;\n description?: string;\n inputSchema?: ZodRawShape;\n annotations?: ToolAnnotations;\n}\n\ntype RegisterToolHandler = (...handlerArgs: unknown[]) => unknown;\ntype RegisterToolFn = (\n name: string,\n config: GovernedRegisterToolConfig,\n handler: RegisterToolHandler,\n) => unknown;\n\ninterface RegisterToolCapableServer {\n registerTool: RegisterToolFn;\n}\n\nconst CONFIRM_FIELD_DESCRIPTION =\n 'Must be true to execute this destructive tool. The call is rejected (no changes made) if omitted or false.';\n\nfunction resolveAnnotations(name: string, declared: ToolAnnotations | undefined): ToolAnnotations {\n const destructiveHint = declared?.destructiveHint ?? inferDestructiveHint(name);\n const readOnlyHint =\n declared?.readOnlyHint ?? (destructiveHint ? false : inferReadOnlyHint(name));\n return { ...declared, destructiveHint, readOnlyHint };\n}\n\n/** Rejection result forwarded to the MCP client without invoking the real handler. */\nfunction unconfirmedDestructiveResult(name: string): {\n content: Array<{ type: 'text'; text: string }>;\n isError: true;\n} {\n return {\n content: [\n {\n type: 'text',\n text: `'${name}' is a destructive action and was NOT executed. Re-call with confirm: true once you intend to proceed.`,\n },\n ],\n isError: true,\n };\n}\n\nfunction wrapDestructiveHandler(name: string, handler: RegisterToolHandler): RegisterToolHandler {\n return async (...callbackArgs: unknown[]): Promise<unknown> => {\n const hasArgs = callbackArgs.length === 2;\n const rawArgs = (hasArgs ? callbackArgs[0] : {}) as Record<string, unknown>;\n\n if (rawArgs['confirm'] !== true) {\n return unconfirmedDestructiveResult(name);\n }\n\n // Strip the synthetic `confirm` field before forwarding — the module's\n // own handler/schema never declared it and shouldn't have to know about it.\n const forwardedArgs: Record<string, unknown> = { ...rawArgs };\n delete forwardedArgs['confirm'];\n const forwardedCallbackArgs = hasArgs ? [forwardedArgs, callbackArgs[1]] : callbackArgs;\n return handler(...forwardedCallbackArgs);\n };\n}\n\n/**\n * Monkey-patch `server.registerTool` so every tool registered afterward\n * (by any module, through any call path) gets annotations inference and,\n * when enabled, the destructive-confirmation gate. Returns the same server\n * instance (mutated in place) for convenient chaining.\n */\nexport function wrapServerWithToolGovernance(\n server: McpServer,\n options: ToolGovernanceOptions = {},\n): McpServer {\n const enforceConfirmation = options.enforceDestructiveConfirmation ?? false;\n const target = server as unknown as RegisterToolCapableServer;\n const originalRegisterTool = target.registerTool.bind(target);\n\n target.registerTool = (\n name: string,\n config: GovernedRegisterToolConfig,\n handler: RegisterToolHandler,\n ): unknown => {\n const annotations = resolveAnnotations(name, config.annotations);\n\n if (!enforceConfirmation || !annotations.destructiveHint) {\n return originalRegisterTool(name, { ...config, annotations }, handler);\n }\n\n const gatedInputSchema: ZodRawShape = {\n ...(config.inputSchema ?? {}),\n confirm: z.boolean().optional().describe(CONFIRM_FIELD_DESCRIPTION),\n };\n\n return originalRegisterTool(\n name,\n { ...config, inputSchema: gatedInputSchema, annotations },\n wrapDestructiveHandler(name, handler),\n );\n };\n\n return server;\n}\n","/**\n * createMcpServer — McpServer factory + module loader + central wiring.\n *\n * Sorts modules by dependsOn, unions their capabilities, constructs an\n * McpServer with declared capabilities, calls register() on each module in\n * topo order, threads the server into ctx for progress notifications, and\n * returns both the server + the merged registration manifest.\n *\n * The `logging/setLevel` request handler is wired to ctx.logger.setLevel\n * so MCP clients can dynamically control verbosity.\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport { SetLevelRequestSchema, type LoggingLevel } from '@modelcontextprotocol/sdk/types.js';\nimport type { McpContext } from './context.js';\nimport { sortModules, type McpModule, type ServerManifest } from './module.js';\nimport { toServerCapabilities, unionCapabilities, type McpCapabilities } from './capabilities.js';\nimport type { LogLevel } from './logger.js';\nimport { wrapServerWithToolGovernance } from './tool-governance.js';\n\nexport interface CreateMcpServerOptions {\n name: string;\n version: string;\n /** Optional extra capabilities to union in (rarely needed). */\n extraCapabilities?: McpCapabilities;\n /**\n * Require `confirm: true` before invoking any tool resolved as\n * destructive (explicit `annotations.destructiveHint`, or inferred from\n * the tool name — see tool-governance.ts). Defaults to false so existing\n * consumers are unaffected until they opt in. `annotations` inference\n * itself always applies regardless of this flag.\n */\n enforceDestructiveConfirmation?: boolean;\n}\n\nexport interface McpServerHandle {\n server: McpServer;\n manifest: ServerManifest;\n}\n\nconst MCP_TO_LOGGER_LEVEL: Record<LoggingLevel, LogLevel> = {\n debug: 'debug',\n info: 'info',\n notice: 'info',\n warning: 'warn',\n error: 'error',\n critical: 'error',\n alert: 'error',\n emergency: 'error',\n};\n\nexport function createMcpServer(\n ctx: McpContext,\n modules: readonly McpModule[],\n opts: CreateMcpServerOptions,\n): McpServerHandle {\n const sorted = sortModules(modules);\n\n // Always declare logging so logging/setLevel works (ctx.logger uses setLevel internally).\n const baseCapabilities: McpCapabilities = { logging: true };\n const capabilities = unionCapabilities([\n baseCapabilities,\n ...sorted.map((m) => m.capabilities),\n opts.extraCapabilities,\n ]);\n\n const server = new McpServer(\n { name: opts.name, version: opts.version },\n { capabilities: toServerCapabilities(capabilities) },\n );\n\n // Wrap BEFORE any module receives the server reference so every\n // registerTool call — through the core registerTool() helper or called\n // directly by a module, the fleet-wide norm today (BOFF-3903) — is\n // governed uniformly, with zero changes required in any product module.\n wrapServerWithToolGovernance(server, {\n enforceDestructiveConfirmation: opts.enforceDestructiveConfirmation,\n });\n\n ctx._internal.serverRef.current = server;\n\n // Wire MCP logging/setLevel → ctx.logger.setLevel\n // The McpServer wraps a Server instance; reach inner for setRequestHandler.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const inner = (server as any).server ?? server;\n if (typeof inner.setRequestHandler === 'function') {\n inner.setRequestHandler(\n SetLevelRequestSchema,\n async (req: { params: { level: LoggingLevel } }) => {\n const target = MCP_TO_LOGGER_LEVEL[req.params.level] ?? 'info';\n ctx.logger.setLevel(target);\n ctx.logger.info('MCP logging level set', { level: req.params.level, mapped: target });\n return {};\n },\n );\n }\n\n const tools: string[] = [];\n const resources: string[] = [];\n const prompts: string[] = [];\n const moduleManifest: { id: string; version: string }[] = [];\n\n for (const mod of sorted) {\n try {\n const reg = mod.register(server, ctx);\n tools.push(...reg.tools);\n resources.push(...reg.resources);\n prompts.push(...reg.prompts);\n moduleManifest.push({ id: mod.id, version: mod.version });\n ctx.logger.debug(`Registered module: ${mod.id}`, {\n tools: reg.tools.length,\n resources: reg.resources.length,\n prompts: reg.prompts.length,\n });\n } catch (error) {\n ctx.logger.error(`Failed to register module: ${mod.id}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n const manifest: ServerManifest = {\n modules: moduleManifest,\n tools,\n resources,\n prompts,\n };\n\n ctx.logger.info(`MCP server ready: ${opts.name}@${opts.version}`, {\n modules: manifest.modules.length,\n tools: manifest.tools.length,\n resources: manifest.resources.length,\n prompts: manifest.prompts.length,\n });\n\n return { server, manifest };\n}\n","/**\n * MCP tool result helpers + central handler.\n *\n * Modules NEVER call server.registerTool directly — they use registerTool()\n * from this module so the central try/catch wraps the handler and:\n * - maps thrown McpUserError / McpAuthError / McpInternalError to\n * MCP-protocol-compliant `{ isError: true, content: [...] }` shapes\n * - threads `_meta.progressToken` into ctx.progress for long ops\n * - emits a structured log line on every error\n * - never leaks `cause` from McpInternalError to the client\n *\n * This is the analog of cli-sdk's createProgram() central error handler.\n */\n\nimport type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\nimport type { ZodRawShape } from 'zod';\nimport type { McpContext } from './context.js';\nimport { McpAuthError, McpInternalError, McpUserError } from './errors.js';\nimport type { ToolAnnotations } from './tool-governance.js';\n\nexport interface ToolTextContent {\n type: 'text';\n text: string;\n [k: string]: unknown;\n}\n\nexport interface ToolResult {\n content: ToolTextContent[];\n isError?: boolean;\n structuredContent?: Record<string, unknown>;\n [k: string]: unknown;\n}\n\nexport interface ToolMeta {\n progressToken?: string | number;\n}\n\n/**\n * Build a successful tool result with JSON content (pretty-printed).\n */\nexport function jsonResult(data: unknown, structured?: Record<string, unknown>): ToolResult {\n const result: ToolResult = {\n content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],\n };\n if (structured !== undefined) {\n result.structuredContent = structured;\n }\n return result;\n}\n\n/**\n * Build a successful tool result with plain text content.\n */\nexport function textResult(text: string): ToolResult {\n return { content: [{ type: 'text', text }] };\n}\n\n/**\n * Build an error tool result. Honors MCP's `{ isError: true, content }` shape.\n * Optional hint is appended on a new line so the LLM can react.\n */\nexport function errorResult(message: string, hint?: string): ToolResult {\n const text = hint ? `${message}\\n\\nHint: ${hint}` : message;\n return { content: [{ type: 'text', text }], isError: true };\n}\n\nexport interface ToolMetadata {\n title: string;\n description: string;\n inputSchema?: ZodRawShape;\n /**\n * Explicit MCP annotations (readOnlyHint / destructiveHint / ...). Optional\n * — when omitted, `wrapServerWithToolGovernance` (applied centrally in\n * `createMcpServer`) infers them from the tool name. Set this to override\n * the inference for a tool whose name doesn't match the naming convention.\n */\n annotations?: ToolAnnotations;\n}\n\nexport type ToolHandler<TArgs = Record<string, unknown>> = (\n args: TArgs,\n ctx: McpContext,\n meta: ToolMeta,\n) => Promise<unknown>;\n\n/**\n * Register a tool with the central error wrapper.\n *\n * The handler returns a plain value or void. The wrapper:\n * - wraps non-undefined returns in jsonResult()\n * - if the value already looks like a ToolResult (has `content`), passes through\n * - catches McpAuthError / McpUserError / McpInternalError / generic Error\n * - logs every error via ctx.logger.error\n */\nexport function registerTool<TArgs extends Record<string, unknown>>(\n server: McpServer,\n ctx: McpContext,\n name: string,\n metadata: ToolMetadata,\n handler: ToolHandler<TArgs>,\n): void {\n const sdkConfig = {\n title: metadata.title,\n description: metadata.description,\n ...(metadata.inputSchema ? { inputSchema: metadata.inputSchema } : {}),\n ...(metadata.annotations ? { annotations: metadata.annotations } : {}),\n };\n\n // The MCP SDK's registerTool signature is `(name, config, handler)`. The\n // handler arity depends on whether inputSchema is present (1-arg without,\n // 2-arg with). We accept a unified handler shape and dispatch at runtime.\n // The SDK's typing is strict and conditional on the inputSchema generic;\n // bypass with a cast since runtime acceptance is unconditional.\n const wrapped = async (...callbackArgs: unknown[]): Promise<ToolResult> => {\n const hasArgs = callbackArgs.length === 2;\n const args = (hasArgs ? callbackArgs[0] : {}) as TArgs;\n const extra = (hasArgs ? callbackArgs[1] : callbackArgs[0]) as\n { _meta?: { progressToken?: string | number } } | undefined;\n\n const progressToken = extra?._meta?.progressToken;\n const meta: ToolMeta = progressToken !== undefined ? { progressToken } : {};\n\n try {\n const result = await handler(args, ctx, meta);\n if (isToolResult(result)) return result;\n if (result === undefined) return textResult('OK');\n return jsonResult(result);\n } catch (error) {\n return mapErrorToResult(error, ctx, name);\n }\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (server as any).registerTool(name, sdkConfig, wrapped);\n}\n\nfunction isToolResult(value: unknown): value is ToolResult {\n return (\n !!value &&\n typeof value === 'object' &&\n 'content' in value &&\n Array.isArray((value as ToolResult).content)\n );\n}\n\nfunction mapErrorToResult(error: unknown, ctx: McpContext, toolName: string): ToolResult {\n if (error instanceof McpAuthError) {\n ctx.logger.warn(`${toolName}: auth required`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpUserError) {\n ctx.logger.info(`${toolName}: user error`, { message: error.message });\n return errorResult(error.message, error.hint);\n }\n if (error instanceof McpInternalError) {\n ctx.logger.error(`${toolName}: internal error`, {\n message: error.message,\n cause: stringifyCause(error.cause),\n });\n return errorResult(`Internal error in ${toolName}.`);\n }\n const message = error instanceof Error ? error.message : String(error);\n ctx.logger.error(`${toolName}: unhandled error`, { message });\n return errorResult(`${toolName}: ${message}`);\n}\n\nfunction stringifyCause(cause: unknown): string | undefined {\n if (cause === undefined || cause === null) return undefined;\n if (cause instanceof Error) return cause.message;\n try {\n return JSON.stringify(cause);\n } catch {\n return String(cause);\n }\n}\n"]}
@@ -1,4 +1,4 @@
1
- import { fetchWorkspaces, issueWorkspaceToken } from './chunk-YOSQUY3M.js';
1
+ import { fetchWorkspaces, issueWorkspaceToken } from './chunk-BSNL65PZ.js';
2
2
 
3
3
  // src/modules/auth/legacy-auth.ts
4
4
  var helpers = /* @__PURE__ */ new WeakMap();
@@ -269,5 +269,5 @@ function createAuthHelper(ctx) {
269
269
  }
270
270
 
271
271
  export { getAuth };
272
- //# sourceMappingURL=chunk-RHWHUY5Y.js.map
273
- //# sourceMappingURL=chunk-RHWHUY5Y.js.map
272
+ //# sourceMappingURL=chunk-QQYJVKJE.js.map
273
+ //# sourceMappingURL=chunk-QQYJVKJE.js.map