@redocly/framework 1.0.0-next.4 → 1.0.0-next.6

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 (329) hide show
  1. package/dist/bundler/build/output-metadata.js +1 -1
  2. package/dist/bundler/build/run.js +1 -1
  3. package/dist/bundler/build/theme-global-style-compiler.js +1 -0
  4. package/dist/bundler/build/theme-global-stylesheets.js +1 -0
  5. package/dist/bundler/build/vite-config.js +2 -2
  6. package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
  7. package/dist/bundler/dev/routes/source-sync-route.js +1 -1
  8. package/dist/bundler/dev/run.js +1 -1
  9. package/dist/bundler/dev/runtime-app.js +1 -1
  10. package/dist/bundler/dev/vite-chunk-url.js +1 -1
  11. package/dist/bundler/node-bundle.js +1 -0
  12. package/dist/bundler/runtime-files.js +1 -1
  13. package/dist/bundler/user-markdoc-schema.js +1 -1
  14. package/dist/bundler/vite-config.base.js +12 -12
  15. package/dist/cli/commands/build.js +1 -1
  16. package/dist/cli/commands/dev.js +1 -1
  17. package/dist/cli/commands/ingest.js +1 -1
  18. package/dist/cli/commands/translate.js +2 -2
  19. package/dist/cli/dev-console/index.js +1 -1
  20. package/dist/cli/log-output/index.js +1 -1
  21. package/dist/cli/validate-react-pages.js +1 -1
  22. package/dist/client/ApiAccess.js +3 -0
  23. package/dist/client/NavigationProgress.js +1 -1
  24. package/dist/client/ProductsProvider.js +1 -1
  25. package/dist/client/RouteErrorBoundary.js +1 -1
  26. package/dist/client/RuntimeLink.js +1 -1
  27. package/dist/client/ThemeGlobalStyle.js +1 -0
  28. package/dist/client/UnversionedVersionButton.js +1 -1
  29. package/dist/client/ai-search/use-ai-search.js +1 -1
  30. package/dist/client/analytics-page-view.js +1 -1
  31. package/dist/client/app.js +3 -3
  32. package/dist/client/client-entry.js +1 -1
  33. package/dist/client/contexts.js +1 -1
  34. package/dist/client/dev-problems/ProblemsBar.js +6 -6
  35. package/dist/client/dev-problems/ProblemsModal.js +15 -15
  36. package/dist/client/feedback.js +1 -1
  37. package/dist/client/l10n/use-l10n-config.js +1 -1
  38. package/dist/client/l10n/use-l10n-href.js +1 -1
  39. package/dist/client/l10n/use-translate.js +1 -1
  40. package/dist/client/products.js +1 -1
  41. package/dist/client/review/ReviewBar.js +61 -61
  42. package/dist/client/review/use-review.js +1 -1
  43. package/dist/client/sidebar/PoweredByRedocly.js +2 -2
  44. package/dist/client/sidebar/SidebarDataProvider.js +1 -1
  45. package/dist/client/sidebar/drilldown.js +1 -1
  46. package/dist/client/ssr.js +1 -1
  47. package/dist/client/telemetry/config.js +1 -1
  48. package/dist/client/telemetry/report-preload-failure.js +1 -0
  49. package/dist/client/templates/dev-login.js +4 -4
  50. package/dist/client/templates/unauthorized.js +5 -5
  51. package/dist/client/theme-global-css.js +1 -0
  52. package/dist/client/use-banner.js +1 -1
  53. package/dist/client/use-entity-revisions.js +1 -1
  54. package/dist/client/use-page-versions.js +1 -1
  55. package/dist/client/use-search.js +1 -1
  56. package/dist/client/webmcp/tools/shared.js +1 -1
  57. package/dist/client/webmcp/tools/site-tools.js +1 -1
  58. package/dist/client/webmcp/use-webmcp-tools.js +1 -1
  59. package/dist/content-layer/allowed-packages.js +1 -1
  60. package/dist/content-layer/config-schema.d.ts +5 -1
  61. package/dist/content-layer/config-schema.js +1 -1
  62. package/dist/content-layer/config.d.ts +6 -2
  63. package/dist/content-layer/config.js +1 -1
  64. package/dist/content-layer/database/adapters/node-sqlite-client.js +1 -1
  65. package/dist/content-layer/database/connection.js +1 -1
  66. package/dist/content-layer/database/entity-store.d.ts +9 -1
  67. package/dist/content-layer/database/entity-store.js +1 -1
  68. package/dist/content-layer/database/invalidation.js +26 -26
  69. package/dist/content-layer/database/origins.d.ts +2 -4
  70. package/dist/content-layer/database/origins.js +1 -1
  71. package/dist/content-layer/ingest/extract-all-phase.js +1 -1
  72. package/dist/content-layer/ingest/finalize-phase.js +1 -1
  73. package/dist/content-layer/ingest/hook-inputs.js +1 -1
  74. package/dist/content-layer/ingest/l10n-warnings.js +1 -1
  75. package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
  76. package/dist/content-layer/ingest/rbac-teams.js +1 -1
  77. package/dist/content-layer/ingest/run.js +1 -1
  78. package/dist/content-layer/ingest/scan.d.ts +1 -1
  79. package/dist/content-layer/ingest/scan.js +1 -1
  80. package/dist/content-layer/ingest/search-sync.js +1 -1
  81. package/dist/content-layer/ingest/slugger/resolve-final-slugs.js +1 -1
  82. package/dist/content-layer/ingest/sync.js +1 -1
  83. package/dist/content-layer/link-checker/load-view.js +1 -1
  84. package/dist/content-layer/link-checker/validate.js +1 -1
  85. package/dist/content-layer/loaders/context.js +1 -1
  86. package/dist/content-layer/markdown/client/OpenapiTagComponents.js +2 -2
  87. package/dist/content-layer/markdown/client/dynamic-components.js +1 -1
  88. package/dist/content-layer/markdown/client/markdoc-components.js +2 -2
  89. package/dist/content-layer/markdown/client/markdown-text.js +1 -1
  90. package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
  91. package/dist/content-layer/markdown/constants/markdown-text-tag-set.js +1 -1
  92. package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
  93. package/dist/content-layer/markdown/nodes/fence.js +1 -1
  94. package/dist/content-layer/markdown/nodes/heading.js +1 -1
  95. package/dist/content-layer/markdown/nodes/table.js +1 -1
  96. package/dist/content-layer/markdown/resolve/ast.js +1 -1
  97. package/dist/content-layer/markdown/resolve/audience-tag.d.ts +1 -1
  98. package/dist/content-layer/markdown/resolve/audience-tag.js +1 -1
  99. package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.js +1 -1
  100. package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.d.ts +1 -1
  101. package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
  102. package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
  103. package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
  104. package/dist/content-layer/markdown/resolve/references.js +1 -1
  105. package/dist/content-layer/markdown/search/to-markdown.js +2 -2
  106. package/dist/content-layer/markdown/search/to-sections.js +1 -1
  107. package/dist/content-layer/markdown/server/render.js +1 -1
  108. package/dist/content-layer/markdown/service.js +1 -1
  109. package/dist/content-layer/markdown/tags/html.d.ts +4 -1
  110. package/dist/content-layer/markdown/tags/html.js +1 -1
  111. package/dist/content-layer/markdown/tags/partial.d.ts +7 -2
  112. package/dist/content-layer/markdown/tags/partial.js +1 -1
  113. package/dist/content-layer/markdown/tags/variant.js +1 -1
  114. package/dist/content-layer/markdown/types/service.d.ts +4 -0
  115. package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
  116. package/dist/content-layer/markdown/utils/reparse-example-fences.d.ts +4 -1
  117. package/dist/content-layer/markdown/utils/reparse-example-fences.js +1 -1
  118. package/dist/content-layer/markdown/utils/substitute-variables.js +1 -1
  119. package/dist/content-layer/markdown/utils/walk-markdoc-ast.d.ts +2 -2
  120. package/dist/content-layer/markdown/utils/walk-markdoc-ast.js +1 -1
  121. package/dist/content-layer/materialization/entity.js +1 -1
  122. package/dist/content-layer/materialization/materializer.js +1 -0
  123. package/dist/content-layer/materialization/static-files.js +1 -1
  124. package/dist/content-layer/plan-gates.d.ts +3 -2
  125. package/dist/content-layer/plan-gates.js +1 -1
  126. package/dist/content-layer/plugins/index.js +1 -1
  127. package/dist/content-layer/plugins/internal/api-docs/client/template.js +4 -4
  128. package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
  129. package/dist/content-layer/plugins/internal/api-docs/server/build-definition.d.ts +2 -2
  130. package/dist/content-layer/plugins/internal/api-docs/server/build-definition.js +1 -1
  131. package/dist/content-layer/plugins/internal/api-docs/server/build-sidebar.js +1 -1
  132. package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.js +13 -13
  133. package/dist/content-layer/plugins/internal/api-docs/server/options.d.ts +4 -2
  134. package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
  135. package/dist/content-layer/plugins/internal/api-docs/server/search-documents.js +1 -1
  136. package/dist/content-layer/plugins/internal/api-docs/server/spec-download.js +1 -1
  137. package/dist/content-layer/plugins/internal/api-functions/index.js +1 -1
  138. package/dist/content-layer/plugins/internal/api-functions/server/access.js +1 -1
  139. package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
  140. package/dist/content-layer/plugins/internal/app-data/banner.js +1 -1
  141. package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
  142. package/dist/content-layer/plugins/internal/app-data/products.d.ts +2 -0
  143. package/dist/content-layer/plugins/internal/app-data/products.js +1 -1
  144. package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
  145. package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
  146. package/dist/content-layer/plugins/internal/index.js +1 -1
  147. package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
  148. package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
  149. package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
  150. package/dist/content-layer/plugins/internal/markdoc/server/shared.d.ts +1 -1
  151. package/dist/content-layer/plugins/internal/mcp/constants.d.ts +6 -0
  152. package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
  153. package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
  154. package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
  155. package/dist/content-layer/plugins/internal/mcp/index.js +1 -1
  156. package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
  157. package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
  158. package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
  159. package/dist/content-layer/plugins/internal/mcp/server/codemode/capabilities.js +3 -3
  160. package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
  161. package/dist/content-layer/plugins/internal/mcp/server/codemode/discover.js +1 -1
  162. package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
  163. package/dist/content-layer/plugins/internal/mcp/server/codemode/execution-budget.js +1 -0
  164. package/dist/content-layer/plugins/internal/mcp/server/codemode/index.js +1 -1
  165. package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
  166. package/dist/content-layer/plugins/internal/mcp/server/codemode/read-result.js +1 -0
  167. package/dist/content-layer/plugins/internal/mcp/server/codemode/return-last-expression.js +6 -0
  168. package/dist/content-layer/plugins/internal/mcp/server/codemode/returns-from-top-level.js +1 -0
  169. package/dist/content-layer/plugins/internal/mcp/server/codemode/sandbox.js +1 -1
  170. package/dist/content-layer/plugins/internal/mcp/server/codemode/tool-declarations.js +4 -0
  171. package/dist/content-layer/plugins/internal/mcp/server/codemode/tool-list.js +1 -1
  172. package/dist/content-layer/plugins/internal/mcp/server/codemode/unknown-tool-hint.js +3 -0
  173. package/dist/content-layer/plugins/internal/mcp/server/config-gate.js +1 -1
  174. package/dist/content-layer/plugins/internal/mcp/server/custom-tools.js +1 -1
  175. package/dist/content-layer/plugins/internal/mcp/server/gateway/__tests__/secret-store-fixture.js +1 -0
  176. package/dist/content-layer/plugins/internal/mcp/server/gateway/api-call-operations.js +1 -1
  177. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js +1 -1
  178. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
  179. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
  180. package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +7 -7
  181. package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-bridge.js +1 -1
  182. package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
  183. package/dist/content-layer/plugins/internal/mcp/server/gateway/secret-store.js +1 -1
  184. package/dist/content-layer/plugins/internal/mcp/server/gateway/subject.js +1 -1
  185. package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
  186. package/dist/content-layer/plugins/internal/mcp/server/gateway/upstream-auth-scheme.js +2 -2
  187. package/dist/content-layer/plugins/internal/mcp/server/handler.js +1 -1
  188. package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
  189. package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
  190. package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
  191. package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
  192. package/dist/content-layer/plugins/internal/mcp/server/rate-limit.js +1 -1
  193. package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
  194. package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
  195. package/dist/content-layer/plugins/internal/mcp/server/skills-resources.js +1 -1
  196. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-catalog.js +1 -1
  197. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-constants.js +1 -0
  198. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-document.js +1 -1
  199. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql.js +1 -1
  200. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-catalog.js +1 -1
  201. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-document.js +1 -1
  202. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-refs.js +1 -1
  203. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi.js +1 -1
  204. package/dist/content-layer/plugins/internal/mcp/server/tools/pages-constants.js +1 -0
  205. package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
  206. package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +3 -3
  207. package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +1 -0
  208. package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +1 -1
  209. package/dist/content-layer/plugins/internal/mcp/server/tools/submit-feedback.js +1 -1
  210. package/dist/content-layer/plugins/internal/mcp/server/tools/whoami.js +1 -1
  211. package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
  212. package/dist/content-layer/plugins/internal/react-page/index.js +1 -1
  213. package/dist/content-layer/plugins/internal/scorecard-classic/client/Grid.js +11 -11
  214. package/dist/content-layer/plugins/internal/scorecard-classic/client/ScorecardViews.js +1 -1
  215. package/dist/content-layer/plugins/internal/scorecard-classic/client/ScorecardWidgets.js +7 -7
  216. package/dist/content-layer/plugins/internal/scorecard-classic/client/template.js +2 -2
  217. package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
  218. package/dist/content-layer/plugins/internal/sidebar/bundle.d.ts +1 -1
  219. package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
  220. package/dist/content-layer/plugins/internal/sidebar/index.d.ts +1 -1
  221. package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
  222. package/dist/content-layer/plugins/internal/skills/index.js +1 -1
  223. package/dist/content-layer/plugins/internal/skills/server/routes.js +1 -1
  224. package/dist/content-layer/plugins/project/load.js +2 -2
  225. package/dist/content-layer/plugins/registry.js +1 -1
  226. package/dist/content-layer/plugins/request-context.d.ts +5 -0
  227. package/dist/content-layer/plugins/types/api-entity.d.ts +2 -6
  228. package/dist/content-layer/plugins/types/api-entity.js +1 -1
  229. package/dist/content-layer/plugins/types/plugin.d.ts +8 -0
  230. package/dist/content-layer/plugins/types/search.d.ts +1 -1
  231. package/dist/content-layer/plugins/utils/link-access.js +1 -1
  232. package/dist/content-layer/plugins/utils/route-index.d.ts +1 -1
  233. package/dist/content-layer/plugins/utils/route-index.js +1 -1
  234. package/dist/content-layer/plugins/utils/version-path.js +1 -1
  235. package/dist/content-layer/revisions/config.js +1 -1
  236. package/dist/content-layer/server/context.js +1 -1
  237. package/dist/content-layer/server/materialize.js +1 -1
  238. package/dist/content-layer/static/audience.js +1 -1
  239. package/dist/content-layer/static/registry.js +1 -1
  240. package/dist/content-layer/templates/template-set.js +1 -1
  241. package/dist/content-layer/versions/redirect.d.ts +11 -6
  242. package/dist/content-layer/versions/redirect.js +1 -1
  243. package/dist/content-layer/versions/resolve.js +1 -1
  244. package/dist/plugin-api.d.ts +3 -0
  245. package/dist/plugin-api.js +1 -1
  246. package/dist/server/__tests__/rbac-fixture.js +1 -1
  247. package/dist/server/app.js +3 -3
  248. package/dist/server/ask-ai/feature-gate.js +1 -1
  249. package/dist/server/ask-ai/route.js +1 -1
  250. package/dist/server/auth/gate.js +1 -1
  251. package/dist/server/auth/middleware.js +1 -1
  252. package/dist/server/auth/request.js +1 -1
  253. package/dist/server/auth/routes.js +1 -1
  254. package/dist/server/auth/runtime.js +1 -1
  255. package/dist/server/content-assets/access.js +1 -1
  256. package/dist/server/content.js +12 -12
  257. package/dist/server/cors-proxy/handler.js +1 -1
  258. package/dist/server/feedback/route.js +1 -1
  259. package/dist/server/lambda-entry.js +1 -1
  260. package/dist/server/manifest-assets.js +4 -4
  261. package/dist/server/metrics/request-metrics.js +1 -1
  262. package/dist/server/node-entry.js +1 -1
  263. package/dist/server/plugin-context.js +1 -1
  264. package/dist/server/plugin-routes.js +1 -1
  265. package/dist/server/rbac/content-asset-access.js +1 -1
  266. package/dist/server/replay-oauth2/route.js +1 -1
  267. package/dist/server/review/route.js +1 -1
  268. package/dist/server/runtime-config.js +1 -1
  269. package/dist/server/search/route.js +1 -1
  270. package/dist/server/seo-tags.js +2 -2
  271. package/dist/server/static-files/serve.js +1 -1
  272. package/dist/server/subprocess/runner.js +1 -1
  273. package/dist/server/telemetry/route.js +1 -1
  274. package/dist/server/template-ids.js +1 -1
  275. package/dist/shared/constants/api-spec-kinds.d.ts +6 -0
  276. package/dist/shared/constants/api-spec-kinds.js +1 -0
  277. package/dist/shared/constants/l10n/langs/ar.js +1 -1
  278. package/dist/shared/constants/l10n/langs/de.js +1 -1
  279. package/dist/shared/constants/l10n/langs/en.js +1 -1
  280. package/dist/shared/constants/l10n/langs/es.js +1 -1
  281. package/dist/shared/constants/l10n/langs/fr.js +1 -1
  282. package/dist/shared/constants/l10n/langs/hi.js +1 -1
  283. package/dist/shared/constants/l10n/langs/it.js +1 -1
  284. package/dist/shared/constants/l10n/langs/ja.js +1 -1
  285. package/dist/shared/constants/l10n/langs/ko.js +1 -1
  286. package/dist/shared/constants/l10n/langs/pl.js +1 -1
  287. package/dist/shared/constants/l10n/langs/pt-br.js +1 -1
  288. package/dist/shared/constants/l10n/langs/pt.js +1 -1
  289. package/dist/shared/constants/l10n/langs/ru.js +1 -1
  290. package/dist/shared/constants/l10n/langs/uk.js +1 -1
  291. package/dist/shared/constants/l10n/langs/zh.js +1 -1
  292. package/dist/{server → shared}/constants/system-routes.d.ts +1 -1
  293. package/dist/shared/constants/system-routes.js +1 -0
  294. package/dist/shared/plan-gates.d.ts +6 -1
  295. package/dist/shared/plan-gates.js +1 -1
  296. package/dist/shared/products.js +1 -1
  297. package/dist/{server → shared}/project-env.d.ts +1 -1
  298. package/dist/{server → shared}/rbac/api-docs.d.ts +1 -1
  299. package/dist/{server → shared}/rbac/engine.d.ts +1 -1
  300. package/dist/shared/rbac/engine.js +0 -0
  301. package/dist/shared/rbac/filter.js +1 -0
  302. package/dist/{server → shared}/rbac/l10n-rules.d.ts +1 -1
  303. package/dist/shared/rbac/l10n-rules.js +1 -0
  304. package/dist/shared/rbac/route-scope.js +1 -0
  305. package/dist/{server → shared}/rbac/team-templates.d.ts +6 -2
  306. package/dist/shared/rbac/team-templates.js +1 -0
  307. package/dist/{server → shared}/rbac/teams.d.ts +1 -1
  308. package/dist/shared/rbac/types.js +1 -0
  309. package/dist/shared/types/config.d.ts +2 -0
  310. package/dist/shared/utils/l10n.js +1 -1
  311. package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
  312. package/package.json +8 -10
  313. package/dist/content-layer/server/config.js +0 -1
  314. package/dist/server/constants/system-routes.js +0 -1
  315. package/dist/server/rbac/engine.js +0 -0
  316. package/dist/server/rbac/filter.js +0 -1
  317. package/dist/server/rbac/l10n-rules.js +0 -1
  318. package/dist/server/rbac/route-scope.js +0 -1
  319. package/dist/server/rbac/team-templates.js +0 -1
  320. package/dist/server/rbac/types.js +0 -1
  321. /package/dist/{server → shared}/project-env.js +0 -0
  322. /package/dist/{server → shared}/rbac/api-docs.js +0 -0
  323. /package/dist/{server → shared}/rbac/entity-scope.js +0 -0
  324. /package/dist/{server → shared}/rbac/filter.d.ts +0 -0
  325. /package/dist/{server → shared}/rbac/route-scope.d.ts +0 -0
  326. /package/dist/{server → shared}/rbac/teams.js +0 -0
  327. /package/dist/{server → shared}/rbac/types.d.ts +0 -0
  328. /package/dist/{content-layer/markdown → shared}/utils/packed-ast.d.ts +0 -0
  329. /package/dist/{content-layer/markdown → shared}/utils/packed-ast.js +0 -0
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SLUG as t,skillMarkdownPath as n}from"../../../utils/skill-paths.js";import{A2A_ROUTE as r,MCP_ROUTE as i,MCP_SERVER_CARD_ROUTE as a}from"../constants.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"./config-gate.js";import{SKILL_ENTITY_TYPE as l}from"../../../types/skill-entity.js";import{isEntityScopeVisible as u}from"../../../../../server/rbac/entity-scope.js";import{notFoundResponse as d}from"../../../../../server/plugin-context.js";import{publicBaseUrl as f}from"../../../utils/request-origin.js";import{CORS_ANY_ORIGIN as p,MCP_AUTH_SCHEMES as m}from"./oauth/constants.js";import"./auth.js";const h=[`text/plain`],g=[`text/plain`],_={streaming:!1,pushNotifications:!1},v={"Cache-Control":`no-store`};async function y(t,r){let i=!!t.request.viewer?.isAuthenticated;return o(c(t.config))&&!i?[]:(await t.entities.list({type:l})).flatMap(i=>{let{slug:a,title:o,description:s}=i.metadata??{};return typeof a!=`string`||!u(i,t.request.teams,e=>t.logger?.warn(e))?[]:[{id:a,name:o??a,description:s??``,tags:[],url:`${r}${e(n(a))}`}]})}async function b(t,n){if(s(n.config)||n.config.skills?.hide===!0)return d();t.set(`realmCacheControlOwned`,!0);let a=f(n.config,n.request),l=o(c(n.config)),u=n.config.seo;return t.json({name:u?.title||u?.projectTitle||`Developer Documentation`,description:u?.description||`Documentation agent card announcing this site's agent skills and MCP server.`,url:`${a}${e(r)}`,documentationUrl:`${a}${e(`/`)}`,version:`0.0.1`,protocolVersion:`0.3.0`,preferredTransport:`HTTP+JSON`,capabilities:{..._,extensions:[{uri:`https://modelcontextprotocol.io`,description:`Model Context Protocol server exposing the documentation tools and skills.`,params:{url:`${a}${e(i)}`,...l?{authentication:{required:!0,schemes:[...m]}}:{}}}]},defaultInputModes:h,defaultOutputModes:g,skills:await y(n,a)},200,{...v,...p})}function x(n,r){if(s(r.config))return d();let i=[`<${e(a)}>; rel="mcp-server-card"`];return r.config.skills?.hide!==!0&&i.push(`<${e(t)}>; rel="agent-skills"`),n.json({error:{code:`405`,message:`Method not allowed`}},405,{Link:i.join(`, `),...p,"Access-Control-Expose-Headers":`Link`})}export{x as a2a,b as agentCard};
1
+ import{A2A_ROUTE as e,MCP_ROUTE as t,MCP_SERVER_CARD_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{SKILLS_INDEX_SLUG as i,skillMarkdownPath as a}from"../../../utils/skill-paths.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"./config-gate.js";import{SKILL_ENTITY_TYPE as l}from"../../../types/skill-entity.js";import{isEntityScopeVisible as u}from"../../../../../shared/rbac/entity-scope.js";import{notFoundResponse as d}from"../../../../../server/plugin-context.js";import{publicBaseUrl as f}from"../../../utils/request-origin.js";import{CORS_ANY_ORIGIN as p,MCP_AUTH_SCHEMES as m}from"./oauth/constants.js";import"./auth.js";const h=[`text/plain`],g=[`text/plain`],_={streaming:!1,pushNotifications:!1},v={"Cache-Control":`no-store`};async function y(e,t){let n=!!e.request.viewer?.isAuthenticated;return o(c(e.config))&&!n?[]:(await e.entities.list({type:l})).flatMap(n=>{let{slug:i,title:o,description:s}=n.metadata??{};return typeof i!=`string`||!u(n,e.request.teams,t=>e.logger?.warn(t))?[]:[{id:i,name:o??i,description:s??``,tags:[],url:`${t}${r(a(i))}`}]})}async function b(n,i){if(s(i.config)||i.config.skills?.hide===!0)return d();n.set(`realmCacheControlOwned`,!0);let a=f(i.config,i.request),l=o(c(i.config)),u=i.config.seo;return n.json({name:u?.title||u?.projectTitle||`Developer Documentation`,description:u?.description||`Documentation agent card announcing this site's agent skills and MCP server.`,url:`${a}${r(e)}`,documentationUrl:`${a}${r(`/`)}`,version:`0.0.1`,protocolVersion:`0.3.0`,preferredTransport:`HTTP+JSON`,capabilities:{..._,extensions:[{uri:`https://modelcontextprotocol.io`,description:`Model Context Protocol server exposing the documentation tools and skills.`,params:{url:`${a}${r(t)}`,...l?{authentication:{required:!0,schemes:[...m]}}:{}}}]},defaultInputModes:h,defaultOutputModes:g,skills:await y(i,a)},200,{...v,...p})}function x(e,t){if(s(t.config))return d();let a=[`<${r(n)}>; rel="mcp-server-card"`];return t.config.skills?.hide!==!0&&a.push(`<${r(i)}>; rel="agent-skills"`),e.json({error:{code:`405`,message:`Method not allowed`}},405,{Link:a.join(`, `),...p,"Access-Control-Expose-Headers":`Link`})}export{x as a2a,b as agentCard};
@@ -1 +1 @@
1
- import{isObject as e}from"../../../../../shared/utils/is-object.js";import{thrownErrorClass as t}from"./tool-errors.js";import{maskCodeCredentials as n}from"./code-credentials.js";import{redactSecretsFromString as r}from"./gateway/fetch/redact.js";import{redactSecretShapes as i}from"./secret-patterns.js";import{createHash as a}from"node:crypto";import{EXECUTE_TOOL_NAME as o}from"@redocly/mcp";function s(e){return{client:e.client,clientVersion:e.clientVersion,requestId:e.requestId,messageId:e.messageId,callerSubject:e.callerSubject,clientIp:e.request.ip??void 0}}const c=`[mcp-audit]`,l=4096;function u(e){return a(`sha256`).update(e,`utf8`).digest(`hex`)}function d(e){if(e.length<=4096)return e;let t=e.slice(0,l),n=t.search(/\s\S*$/),r=n>0?t.slice(0,n):t;return`${r}…[truncated: kept ${r.length} of ${e.length} chars]`}function f(e,t=[]){return i(r(d(e),t))}const p=/(?<=^|[\s('"])(?:file:\/\/\/?|\/)(?:[^\s()/:'"]+\/)+/gm;function m(e){return f(e.replace(p,``))}function h(e){return{sha256:u(e),bytes:Buffer.byteLength(e,`utf8`)}}function g(e){return Object.keys(e??{}).map(e=>e.toLowerCase()).sort().join(`,`)}const _=/* @__PURE__ */ new Set([`access_token`,`api-key`,`api_key`,`apikey`,`assertion`,`auth`,`client_secret`,`code`,`code_verifier`,`id_token`,`id_token_hint`,`key`,`password`,`refresh_token`,`samlresponse`,`secret`,`session`,`sig`,`signature`,`token`,`x-amz-credential`,`x-amz-security-token`,`x-amz-signature`]);function v(e,t=[],n=[]){let r;try{r=new URL(e)}catch{return f(e,t)}let i=new Set(n.map(e=>e.toLowerCase()));for(let e of[...r.searchParams.keys()]){let t=e.toLowerCase();(_.has(t)||i.has(t))&&r.searchParams.set(e,`redacted`)}return r.username=``,r.password=``,f(r.href,t)}function y(e,t,n){let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0&&e!==``));try{e?.info(`${c} ${t}`,r)}catch{}}const b=/(169\.254\.169\.254|metadata\.google\.internal|\.consul\b|\.internal\b|localhost|127\.0\.0\.1|\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|\b192\.168\.\d{1,3}\.\d{1,3}\b|\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b)/i,x=/(process\s*(?:\.\s*env\b|\[)|globalThis|require\s*\(|__proto__)/;function S(e){let t=[];return x.test(e)&&t.push(`env_probe`),b.test(e)&&t.push(`internal_target`),{sha256:u(e),length:e.length,flags:t.sort().join(`,`)}}function C(e){try{return JSON.stringify(e)??String(e)}catch{return`«[unserializable]»`}}function w(e,{tool:t,mode:n,args:r,result:i,errorClass:a,client:s,clientVersion:c,requestId:l,messageId:d,callerSubject:p,clientIp:m}){if(t===o)return;let g=C(r),_=i===void 0?void 0:h(i),v=r?.sessionHandle,b=typeof v==`string`&&v!==``?v:void 0,x=p??b;y(e,`Record MCP tool call`,{tool:t,mode:n,server_type:`docs`,error_class:a,client:s,client_version:c,request_id:l,message_id:d,subject_sha256:x?u(x):void 0,client_ip:m,args_sha256:u(g),args:f(g,b?[b]:[]),result_sha256:_?.sha256,result_bytes:_?.bytes})}async function T(e,n,r,i){let a={tool:n,mode:e.mcpMode,args:r,...s(e)},o=Date.now(),c;try{c=await i()}catch(r){throw w(e.logger,{...a,errorClass:t(r)}),e.telemetry?.toolThrew(n,Date.now()-o,r),await e.telemetry?.flush(),r}let l=D(c)&&c.isError===!0;return w(e.logger,{...a,result:A(c),errorClass:l?`tool_error`:void 0}),e.telemetry?.toolReturned(n,Date.now()-o,c),await e.telemetry?.flush(),c}const E=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function D(t){return e(t)&&Array.isArray(t.content)&&t.content.every(t=>e(t)&&E.has(t.type))}function O(t){return e(t)&&t.resultType===`input_required`}function k(e,t=``){return e.content.map(e=>e.type===`text`?e.text:``).join(t)}function A(e){if(typeof e==`string`)return e;if(D(e))return k(e);if(O(e))return``;try{return JSON.stringify(e)??``}catch{return``}}function j(e,{audit:t,code:r,description:i,sessionHandle:a,toolNames:o,fetchBudget:s,fetchCapable:c,requestId:l,messageId:d,callerSubject:p,clientIp:m}){let h=p??a;y(e,`Record code execution input`,{code_sha256:t.sha256,code_length:t.length,request_id:l,message_id:d,flags:t.flags,subject_sha256:h?u(h):void 0,client_ip:m,description:f(i),tools:[...o].sort().join(`,`),fetch_capable:c,fetch_budget:s,code:f(n(r))})}function M(e,{rawUrl:t,method:n,host:r,outcome:i,durationMs:a,injectedSecretValues:o,credentialQueryParams:s,path:c,api:l,status:d,injectedScheme:p,requestHeaders:m,requestBody:_,responseHeaders:b,responseBody:x,caller:S={}}){let{requestId:C,callerSubject:w,clientIp:T}=S,E=x===void 0?void 0:h(x);y(e,`Record gateway fetch`,{url_sha256:u(t),host:r,method:n,path:c,api:l,outcome:i,status:d,injected_scheme:p,duration_ms:a,request_id:C,subject_sha256:w?u(w):void 0,client_ip:T,url:v(t,o,s),request_header_names:g(m),request_body:_===void 0?void 0:f(_,o),response_header_names:g(b),response_sha256:E?.sha256,response_bytes:E?.bytes})}export{l as AUDIT_FIELD_MAX_CHARS,c as AUDIT_LOG_PREFIX,S as auditCode,g as auditHeaderNames,f as auditInput,u as auditSha256,m as auditStack,T as auditToolCall,v as auditUrl,s as callAttribution,D as isCallToolResult,y as logAuditRecord,j as logCodeExecutionAudit,M as logGatewayFetchAudit,w as logMcpToolCallAudit,A as toolOutputText,k as toolResultText,d as truncateAuditField};
1
+ import"../constants.js";import{isObject as e}from"../../../../../shared/utils/is-object.js";import{thrownErrorClass as t}from"./tool-errors.js";import{maskCodeCredentials as n}from"./code-credentials.js";import{redactSecretsFromString as r}from"./gateway/fetch/redact.js";import{redactSecretShapes as i}from"./secret-patterns.js";import{createHash as a}from"node:crypto";function o(e){return{client:e.client,clientVersion:e.clientVersion,requestId:e.requestId,messageId:e.messageId,callerSubject:e.callerSubject,clientIp:e.request.ip??void 0}}const s=`[mcp-audit]`,c=4096;function l(e){return a(`sha256`).update(e,`utf8`).digest(`hex`)}function u(e){if(e.length<=4096)return e;let t=e.slice(0,c),n=t.search(/\s\S*$/),r=n>0?t.slice(0,n):t;return`${r}…[truncated: kept ${r.length} of ${e.length} chars]`}function d(e,t=[]){return i(r(u(e),t))}const f=/(?<=^|[\s('"])(?:file:\/\/\/?|\/)(?:[^\s()/:'"]+\/)+/gm;function p(e){return d(e.replace(f,``))}function m(e){return{sha256:l(e),bytes:Buffer.byteLength(e,`utf8`)}}function h(e){return Object.keys(e??{}).map(e=>e.toLowerCase()).sort().join(`,`)}const g=/* @__PURE__ */ new Set([`access_token`,`api-key`,`api_key`,`apikey`,`assertion`,`auth`,`client_secret`,`code`,`code_verifier`,`id_token`,`id_token_hint`,`key`,`password`,`refresh_token`,`samlresponse`,`secret`,`session`,`sig`,`signature`,`token`,`x-amz-credential`,`x-amz-security-token`,`x-amz-signature`]);function _(e,t=[],n=[]){let r;try{r=new URL(e)}catch{return d(e,t)}let i=new Set(n.map(e=>e.toLowerCase()));for(let e of[...r.searchParams.keys()]){let t=e.toLowerCase();(g.has(t)||i.has(t))&&r.searchParams.set(e,`redacted`)}return r.username=``,r.password=``,d(r.href,t)}function v(e,t,n){let r=Object.fromEntries(Object.entries(n).filter(([,e])=>e!==void 0&&e!==``));try{e?.info(`${s} ${t}`,r)}catch{}}const y=/(169\.254\.169\.254|metadata\.google\.internal|\.consul\b|\.internal\b|localhost|127\.0\.0\.1|\b10\.\d{1,3}\.\d{1,3}\.\d{1,3}\b|\b192\.168\.\d{1,3}\.\d{1,3}\b|\b172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}\b)/i,b=/(process\s*(?:\.\s*env\b|\[)|globalThis|require\s*\(|__proto__)/;function x(e){let t=[];return b.test(e)&&t.push(`env_probe`),y.test(e)&&t.push(`internal_target`),{sha256:l(e),length:e.length,flags:t.sort().join(`,`)}}function S(e){try{return JSON.stringify(e)??String(e)}catch{return`«[unserializable]»`}}function C(e,{tool:t,mode:n,args:r,result:i,errorClass:a,client:o,clientVersion:s,requestId:c,messageId:u,callerSubject:f,clientIp:p}){if(t===`execute`)return;let h=S(r),g=i===void 0?void 0:m(i),_=r?.sessionHandle,y=typeof _==`string`&&_!==``?_:void 0,b=f??y;v(e,`Record MCP tool call`,{tool:t,mode:n,server_type:`docs`,error_class:a,client:o,client_version:s,request_id:c,message_id:u,subject_sha256:b?l(b):void 0,client_ip:p,args_sha256:l(h),args:d(h,y?[y]:[]),result_sha256:g?.sha256,result_bytes:g?.bytes})}async function w(e,n,r,i){let a={tool:n,mode:e.mcpMode,args:r,...o(e)},s=Date.now(),c;try{c=await i()}catch(r){throw C(e.logger,{...a,errorClass:t(r)}),e.telemetry?.toolThrew(n,Date.now()-s,r),await e.telemetry?.flush(),r}let l=E(c)&&c.isError===!0;return C(e.logger,{...a,result:k(c),errorClass:l?`tool_error`:void 0}),e.telemetry?.toolReturned(n,Date.now()-s,c),await e.telemetry?.flush(),c}const T=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function E(t){return e(t)&&Array.isArray(t.content)&&t.content.every(t=>e(t)&&T.has(t.type))}function D(t){return e(t)&&t.resultType===`input_required`}function O(e,t=``){return e.content.map(e=>e.type===`text`?e.text:``).join(t)}function k(e){if(typeof e==`string`)return e;if(E(e))return O(e);if(D(e))return``;try{return JSON.stringify(e)??``}catch{return``}}function A(e,{audit:t,code:r,description:i,sessionHandle:a,toolNames:o,fetchBudget:s,fetchCapable:c,requestId:u,messageId:f,callerSubject:p,clientIp:m}){let h=p??a;v(e,`Record code execution input`,{code_sha256:t.sha256,code_length:t.length,request_id:u,message_id:f,flags:t.flags,subject_sha256:h?l(h):void 0,client_ip:m,description:d(i),tools:[...o].sort().join(`,`),fetch_capable:c,fetch_budget:s,code:d(n(r))})}function j(e,{rawUrl:t,method:n,host:r,outcome:i,durationMs:a,injectedSecretValues:o,credentialQueryParams:s,path:c,api:u,status:f,injectedScheme:p,requestHeaders:g,requestBody:y,responseHeaders:b,responseBody:x,caller:S={}}){let{requestId:C,callerSubject:w,clientIp:T}=S,E=x===void 0?void 0:m(x);v(e,`Record gateway fetch`,{url_sha256:l(t),host:r,method:n,path:c,api:u,outcome:i,status:f,injected_scheme:p,duration_ms:a,request_id:C,subject_sha256:w?l(w):void 0,client_ip:T,url:_(t,o,s),request_header_names:h(g),request_body:y===void 0?void 0:d(y,o),response_header_names:h(b),response_sha256:E?.sha256,response_bytes:E?.bytes})}export{c as AUDIT_FIELD_MAX_CHARS,s as AUDIT_LOG_PREFIX,x as auditCode,h as auditHeaderNames,d as auditInput,l as auditSha256,p as auditStack,w as auditToolCall,_ as auditUrl,o as callAttribution,E as isCallToolResult,v as logAuditRecord,A as logCodeExecutionAudit,j as logGatewayFetchAudit,C as logMcpToolCallAudit,k as toolOutputText,O as toolResultText,u as truncateAuditField};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{MCP_AUTHORIZATION_SERVER_ROUTE as t,MCP_PROTECTED_RESOURCE_ROUTE as n,PUBLIC_MCP_ROUTE as r}from"../constants.js";import{ANONYMOUS_VIEWER as i}from"../../../../../shared/types/auth.js";import{canAccessMcpFeature as a,isMcpContentProtected as o,isPublicEndpointServed as s,resolveMcpAccess as c}from"./config-gate.js";import{getBearerVerifier as l,getSessionIssuer as u}from"../../../../../server/auth/middleware.js";import{publicOrigin as d}from"../../../utils/request-origin.js";import{isAssistantAnonymousToken as f}from"../../../../../server/ask-ai/assistant-anonymous-token.js";import{CORS_ANY_ORIGIN as p,CORS_EXPOSE_CHALLENGE as m,SUPPORTED_MCP_SCOPES as h}from"./oauth/constants.js";function g(e){let t=/^Bearer\s+(\S+)$/i.exec((e??``).trim());return t?t[1]:null}function _(r,i){let a=i?[`error="${i.code}"`,`error_description="${i.description}"`]:[];return a.push(`resource_metadata="${r}${e(n)}"`,`scope="${h.join(` `)}"`,`authorization_uri="${r}${e(t)}"`),`Bearer ${a.join(`, `)}`}function v(e,t){return t?`${e}. A public endpoint that serves anonymous-accessible content is available at ${t}.`:e}function y(e,t,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,...n}})}function b(e,t){return y(401,{error:`unauthorized`,message:v(`Authentication required`,t)},{"WWW-Authenticate":_(e),...m})}function x(e,t){return y(401,{error:`invalid_token`,message:v(`Invalid or expired token`,t)},{"WWW-Authenticate":_(e,{code:`invalid_token`,description:`Invalid or expired token`}),...m})}function S(){return y(403,{error:`forbidden`,message:`You do not have access to this MCP server`},{...p})}async function C(t){let{c:n,ctx:p}=t,m=e=>p.logger?.warn(e),h=c(p.config),_=o(h);if(t.forceAnonymous){let e=await p.withViewer(i);return a(h,e.request.teams,!1,m)?{kind:`allow`,ctx:e,isProtected:_}:{kind:`deny`,response:S()}}let v=t=>{let n=d(p.request);return{kind:`deny`,response:t(n,s(p.config,h)?`${n}${e(r)}`:void 0)}},y=p.request.viewer??i,C,w,T=p,E=g(n.req.header(`authorization`)),D=u(n)?.artifactSecret,O=E!==null&&D!==void 0&&await f(E,D);if(!_)w=O||E===null?void 0:E;else if(O)y=i,T=await p.withViewer(i);else if(E!==null){let e=await l(n)?.(E);if(!e)return v(x);y=e.viewer,C=e.claims,w=E,T=await p.withViewer(y)}else if(!y.isAuthenticated)return v(b);return a(h,T.request.teams,y.isAuthenticated,m)?{kind:`allow`,ctx:T,isProtected:_,accessToken:w,claims:C}:{kind:`deny`,response:S()}}export{C as authorizeMcpRequest,o as isMcpContentProtected,s as isPublicEndpointServed,g as readBearerToken,c as resolveMcpAccess};
1
+ import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_PROTECTED_RESOURCE_ROUTE as t,PUBLIC_MCP_ROUTE as n}from"../constants.js";import{withPathPrefix as r}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as i}from"../../../../../shared/types/auth.js";import{canAccessMcpFeature as a,isMcpContentProtected as o,isPublicEndpointServed as s,resolveMcpAccess as c}from"./config-gate.js";import{getBearerVerifier as l,getSessionIssuer as u}from"../../../../../server/auth/middleware.js";import{publicOrigin as d}from"../../../utils/request-origin.js";import{isAssistantAnonymousToken as f}from"../../../../../server/ask-ai/assistant-anonymous-token.js";import{CORS_ANY_ORIGIN as p,CORS_EXPOSE_CHALLENGE as m,SUPPORTED_MCP_SCOPES as h}from"./oauth/constants.js";function g(e){let t=/^Bearer\s+(\S+)$/i.exec((e??``).trim());return t?t[1]:null}function _(n,i){let a=i?[`error="${i.code}"`,`error_description="${i.description}"`]:[];return a.push(`resource_metadata="${n}${r(t)}"`,`scope="${h.join(` `)}"`,`authorization_uri="${n}${r(e)}"`),`Bearer ${a.join(`, `)}`}function v(e,t){return t?`${e}. A public endpoint that serves anonymous-accessible content is available at ${t}.`:e}function y(e,t,n){return new Response(JSON.stringify(t),{status:e,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,...n}})}function b(e,t){return y(401,{error:`unauthorized`,message:v(`Authentication required`,t)},{"WWW-Authenticate":_(e),...m})}function x(e,t){return y(401,{error:`invalid_token`,message:v(`Invalid or expired token`,t)},{"WWW-Authenticate":_(e,{code:`invalid_token`,description:`Invalid or expired token`}),...m})}function S(){return y(403,{error:`forbidden`,message:`You do not have access to this MCP server`},{...p})}async function C(e){let{c:t,ctx:p}=e,m=e=>p.logger?.warn(e),h=c(p.config),_=o(h);if(e.forceAnonymous){let e=await p.withViewer(i);return a(h,e.request.teams,!1,m)?{kind:`allow`,ctx:e,isProtected:_}:{kind:`deny`,response:S()}}let v=e=>{let t=d(p.request);return{kind:`deny`,response:e(t,s(p.config,h)?`${t}${r(n)}`:void 0)}},y=p.request.viewer??i,C,w,T=p,E=g(t.req.header(`authorization`)),D=u(t)?.artifactSecret,O=E!==null&&D!==void 0&&await f(E,D);if(!_)w=O||E===null?void 0:E;else if(O)y=i,T=await p.withViewer(i);else if(E!==null){let e=await l(t)?.(E);if(!e)return v(x);y=e.viewer,C=e.claims,w=E,T=await p.withViewer(y)}else if(!y.isAuthenticated)return v(b);return a(h,T.request.teams,y.isAuthenticated,m)?{kind:`allow`,ctx:T,isProtected:_,accessToken:w,claims:C}:{kind:`deny`,response:S()}}export{C as authorizeMcpRequest,o as isMcpContentProtected,s as isPublicEndpointServed,g as readBearerToken,c as resolveMcpAccess};
@@ -1,7 +1,7 @@
1
- import{FETCH_TOOL_NAME as e}from"./constants.js";import{callableApis as t}from"../gateway/eligibility.js";import{allowsOnlySafeHttpMethods as n,getAllowedHttpMethods as r}from"../gateway/allowed-http-methods.js";import{EXECUTE_ARGS_NOTE as i,USAGE_NOTES as a,buildExecuteExample as o}from"./prompts.js";import{PLAIN_JAVASCRIPT_RULE as s,READ_ONLY_ANNOTATIONS as c,buildToolTypeDeclarations as l,sanitizeToolName as u}from"@redocly/mcp";const d=["```ts",`/**`,` * Call a documented operation of a callable API. Undocumented paths and methods are refused.`,` * Responses cap at 1 MiB and redirects are not followed.`,` */`,`declare function fetch(url: string | URL, init?: {`,` method?: string;`," /** `content-type` is set automatically for URLSearchParams/FormData unless you set one. */",` headers?: Record<string, string>;`,` /** string · URLSearchParams (→ application/x-www-form-urlencoded) · FormData (→ multipart/form-data) */`,` body?: string | URLSearchParams | FormData;`," /** Security scheme name (from the operation's `security` or `getSecuritySchemes`) whose credential to send. Omit to let the server choose. */",` securityScheme?: string;`,`}): Promise<{`,` status: number;`,` statusText: string;`,` ok: boolean;`,` headers: { get(name: string): string | null };`,` json(): Promise<unknown>;`,` text(): Promise<string>;`,`}>;`,"```"].join(`
1
+ import{FETCH_TOOL_NAME as e}from"./constants.js";import{buildToolTypeDeclarations as t,sanitizeToolName as n}from"./tool-declarations.js";import{READ_ONLY_ANNOTATIONS as r}from"../tools/schemas.js";import{callableApis as i}from"../gateway/eligibility.js";import{allowsOnlySafeHttpMethods as a,getAllowedHttpMethods as o}from"../gateway/allowed-http-methods.js";import{EXECUTE_ARGS_NOTE as s,PLAIN_JAVASCRIPT_RULE as c,USAGE_NOTES as l,buildExecuteExample as u}from"./prompts.js";const d=["```ts",`/**`,` * Call a documented operation of a callable API. Undocumented paths and methods are refused.`,` * Responses cap at 1 MiB and redirects are not followed.`,` */`,`declare function fetch(url: string | URL, init?: {`,` method?: string;`," /** `content-type` is set automatically for URLSearchParams/FormData unless you set one. */",` headers?: Record<string, string>;`,` /** string · URLSearchParams (→ application/x-www-form-urlencoded) · FormData (→ multipart/form-data) */`,` body?: string | URLSearchParams | FormData;`," /** Security scheme name (from the operation's `security` or `getSecuritySchemes`) whose credential to send. Omit to let the server choose. */",` securityScheme?: string;`,`}): Promise<{`,` status: number;`,` statusText: string;`,` ok: boolean;`,` headers: { get(name: string): string | null };`,` json(): Promise<unknown>;`,` text(): Promise<string>;`,`}>;`,"```"].join(`
2
2
  `),f=[`listApis`,`getEndpoints`,`getEndpointInfo`],p=[`Example - list the paid invoices of a billing API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const ep = endpoints.find((e) => e.method === 'GET' && e.path.includes('invoices'));`,`const info = await site.getEndpointInfo({ name: api.name, path: ep.path, method: ep.method });`,"// Replace every `{placeholder}` first.",`const url = new URL((info.servers?.[0]?.url ?? '') + ep.path);`,"// Every name below comes from `info.endpoint.parameters` - read them first, never guess them.",`url.searchParams.set('filter', 'status:paid');`,`url.searchParams.set('sort', '-createdTime');`,`url.searchParams.set('limit', '100');`,`try {`,` const res = await fetch(url, { method: ep.method });`,` return res.ok ? await res.json() : { status: res.status, error: await res.text() };`,`} catch (error) {`,` return { error: error instanceof Error ? error.message : String(error), endpointId: info };`,`}`,"```"].join(`
3
3
  `),m=[`Example - call an endpoint you already read:`,``,"```js","// Call `getEndpointInfo` first for the server URL, the path, and the parameter names.","// Replace every `{placeholder}` first.",`const url = new URL('https://api.example.com/invoices');`,`url.searchParams.set('filter', 'status:paid');`,`try {`,` const res = await fetch(url, { method: 'GET' });`,` return res.ok ? await res.json() : { status: res.status, error: await res.text() };`,`} catch (error) {`,` return { error: error instanceof Error ? error.message : String(error) };`,`}`,"```"].join(`
4
- `);function h(e){return f.every(t=>e.includes(t))?p:m}function g(e){let t=/* @__PURE__ */ new Map;for(let{name:n,version:r}of e){if(!n)continue;let e=t.get(n)??[];r&&e.push(r),t.set(n,e)}return[...t.entries()].map(([e,t])=>t.length>1?`${e} (${t.map(e=>`v${e}`).join(`, `)})`:e).join(`, `)}const _={id:e,purpose:`Call the documented APIs over HTTP`,isActive:async e=>(await t(e)).length>0,annotations:e=>n(e)?{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0}:{readOnlyHint:!1,destructiveHint:!0,openWorldHint:!0},async renderSection(e,n){let i=g(await t(e));return["## `fetch` — call the documented APIs",``,d,``,"Always call `getEndpointInfo` before `fetch` for the exact URL, required parameters, and body shape. Put filtering, sorting, and paging in the query parameters, and keep sandbox JS for what the endpoint cannot express. Never guess.",``,"An endpoint path can hold `{placeholders}`. Fill each one from `endpoint.parameters` before you call `fetch`. Server URLs come with their variable defaults filled in. A `{placeholder}` left in a server URL has no usable default, so ask the user for its value.",``,`\`fetch\` sends only the methods this project allows: ${r(e.config.mcp).join(`, `)}. Explain any other call to the user instead of making it.`,``,`Callable APIs (their documented hosts are reachable via \`fetch\`): ${i}`,``,h(n)].join(`
5
- `)}},v=[_];async function y(e){let t=await Promise.all(v.map(t=>t.isActive(e)));return v.filter((e,n)=>t[n])}function b(e,t,n){let r=[...e.map(e=>e.annotations??{}),...t.map(e=>e.annotations(n))],i=r.filter(e=>e.readOnlyHint!==!0),a=r.some(e=>e.openWorldHint!==!1);return i.length===0?{...c,openWorldHint:a}:{readOnlyHint:!1,destructiveHint:i.some(e=>e.destructiveHint!==!1),idempotentHint:i.every(e=>e.idempotentHint===!0),openWorldHint:a}}async function x(e,t,n){let r=e.map(e=>u(e.name)),c=[];if(e.length>0){let t=l(e),n=t.includes(`OpenApi`)?`\n\n${a}`:``;c.push(`## Sandbox functions\n\nThe signatures are TypeScript declarations. ${s}\n\n${t}${n}`)}c.push(i),e.length>0&&!t.some(e=>e.id===`fetch`)&&c.push(o(r));for(let e of t)c.push(await e.renderSection(n,r));return c.join(`
4
+ `);function h(e){return f.every(t=>e.includes(t))?p:m}function g(e){let t=/* @__PURE__ */ new Map;for(let{name:n,version:r}of e){if(!n)continue;let e=t.get(n)??[];r&&e.push(r),t.set(n,e)}return[...t.entries()].map(([e,t])=>t.length>1?`${e} (${t.map(e=>`v${e}`).join(`, `)})`:e).join(`, `)}const _={id:e,purpose:`Call the documented APIs over HTTP`,isActive:async e=>(await i(e)).length>0,annotations:e=>a(e)?{readOnlyHint:!0,destructiveHint:!1,openWorldHint:!0}:{readOnlyHint:!1,destructiveHint:!0,openWorldHint:!0},async renderSection(e,t){let n=g(await i(e));return["## `fetch` — call the documented APIs",``,d,``,"Always call `getEndpointInfo` before `fetch` for the exact URL, required parameters, and body shape. Put filtering, sorting, and paging in the query parameters, and keep sandbox JS for what the endpoint cannot express. Never guess.",``,"An endpoint path can hold `{placeholders}`. Fill each one from `endpoint.parameters` before you call `fetch`. Server URLs come with their variable defaults filled in. A `{placeholder}` left in a server URL has no usable default, so ask the user for its value.",``,`\`fetch\` sends only the methods this project allows: ${o(e.config.mcp).join(`, `)}. Explain any other call to the user instead of making it.`,``,`Callable APIs (their documented hosts are reachable via \`fetch\`): ${n}`,``,h(t)].join(`
5
+ `)}},v=[_];async function y(e){let t=await Promise.all(v.map(t=>t.isActive(e)));return v.filter((e,n)=>t[n])}function b(e,t,n){let i=[...e.map(e=>e.annotations??{}),...t.map(e=>e.annotations(n))],a=i.filter(e=>e.readOnlyHint!==!0),o=i.some(e=>e.openWorldHint!==!1);return a.length===0?{...r,openWorldHint:o}:{readOnlyHint:!1,destructiveHint:a.some(e=>e.destructiveHint!==!1),idempotentHint:a.every(e=>e.idempotentHint===!0),openWorldHint:o}}async function x(e,r,i){let a=e.map(e=>n(e.name)),o=[];if(e.length>0){let n=t(e),r=n.includes(`OpenApi`)?`\n\n${l}`:``;o.push(`## Sandbox functions\n\nThe signatures are TypeScript declarations. ${c}\n\n${n}${r}`)}o.push(s),e.length>0&&!r.some(e=>e.id===`fetch`)&&o.push(u(a));for(let e of r)o.push(await e.renderSection(i,a));return o.join(`
6
6
 
7
7
  `)}export{v as ALL_CAPABILITIES,d as FETCH_DECLARATION,b as composeExecuteAnnotations,_ as fetchCapability,y as getActiveCapabilities,x as renderDiscoverOutput};
@@ -1 +1 @@
1
- import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,DISCOVER_TOOL_NAME as t,EXECUTE_TOOL_NAME as n,MANAGE_API_CREDENTIALS_TOOL_NAME as r,REMOVE_API_CREDENTIALS_TOOL_NAME as i,SUBMIT_FEEDBACK_TOOL_NAME as a}from"@redocly/mcp";const o=`fetch`,s=/* @__PURE__ */ new Set([n,t,e,r,i,a]),c=`site`,l=`tools`,u=`__fetchBridge`,d=`fetch`,f=1e4,p=45e3,m=5e4,h=1e3,g=50,_=50,v={ratePerMin:600,quotaPerDay:1e5},y=8388608,b=1048576,x=262144,S=67108864,C=134217728,w=16777216,T=65536,E=2,D=4,O=5e3,k=`The sandbox failed to run this code. The cause was logged on the server.`,A=`HostFunctionError`,j=`HostOutputTooLargeError`;export{O as ACQUIRE_TIMEOUT_MS,s as CODE_MODE_TOOL_NAMES,p as DEFAULT_MAX_LIFETIME_MS,f as DEFAULT_TIMEOUT_MS,m as EXECUTE_DEADLINE_MS,d as FETCH_BRIDGE_FUNCTION_NAME,u as FETCH_BRIDGE_GLOBAL_NAME,o as FETCH_TOOL_NAME,_ as GATEWAY_FETCH_BUDGET_PER_EXEC,v as GATEWAY_FETCH_LIMITS,A as HOST_FUNCTION_ERROR_NAME,j as HOST_OUTPUT_TOO_LARGE_ERROR_NAME,w as INITIAL_TOTAL_MEMORY_BYTES,k as INTERNAL_ERROR_MESSAGE,S as MAX_ALLOCATION_BYTES,E as MAX_CONCURRENT_RUNS,g as MAX_FETCH_CALLS,b as MAX_FETCH_OUTPUT_BYTES,D as MAX_QUEUED_RUNS,x as MAX_STACK_SIZE_BYTES,h as MAX_TOOL_CALLS,y as MAX_TOOL_OUTPUT_BYTES,C as MAX_TOTAL_MEMORY_BYTES,c as SITE_GLOBAL_NAME,l as TOOLS_GLOBAL_ALIAS,T as WASM_PAGE_BYTES};
1
+ import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,DISCOVER_TOOL_NAME as t,EXECUTE_TOOL_NAME as n,MANAGE_API_CREDENTIALS_TOOL_NAME as r,REMOVE_API_CREDENTIALS_TOOL_NAME as i,SUBMIT_FEEDBACK_TOOL_NAME as a}from"../../constants.js";const o=`fetch`,s=/* @__PURE__ */ new Set([n,t,e,r,i,a]),c=`site`,l=`tools`,u=`__fetchBridge`,d=`fetch`,f=1e4,p=45e3,m=5e4,h=1e3,g=50,_=50,v={ratePerMin:600,quotaPerDay:1e5},y=8388608,b=1048576,x=1048576,S=262144,C=67108864,w=134217728,T=16777216,E=65536,D=2,O=4,k=5e3,A=`The sandbox failed to run this code. The cause was logged on the server.`,j=`HostFunctionError`,M=`HostOutputTooLargeError`,N={NoReturn:`no_return`,OutputTooLarge:`output_too_large`,Timeout:`timeout`,MemoryLimit:`memory_limit`,SyntaxError:`syntax_error`,HostError:`host_error`,RuntimeError:`runtime_error`};export{k as ACQUIRE_TIMEOUT_MS,s as CODE_MODE_TOOL_NAMES,p as DEFAULT_MAX_LIFETIME_MS,f as DEFAULT_TIMEOUT_MS,m as EXECUTE_DEADLINE_MS,d as FETCH_BRIDGE_FUNCTION_NAME,u as FETCH_BRIDGE_GLOBAL_NAME,o as FETCH_TOOL_NAME,_ as GATEWAY_FETCH_BUDGET_PER_EXEC,v as GATEWAY_FETCH_LIMITS,j as HOST_FUNCTION_ERROR_NAME,M as HOST_OUTPUT_TOO_LARGE_ERROR_NAME,T as INITIAL_TOTAL_MEMORY_BYTES,A as INTERNAL_ERROR_MESSAGE,C as MAX_ALLOCATION_BYTES,D as MAX_CONCURRENT_RUNS,g as MAX_FETCH_CALLS,b as MAX_FETCH_OUTPUT_BYTES,O as MAX_QUEUED_RUNS,x as MAX_RESULT_BYTES,S as MAX_STACK_SIZE_BYTES,h as MAX_TOOL_CALLS,y as MAX_TOOL_OUTPUT_BYTES,w as MAX_TOTAL_MEMORY_BYTES,N as SANDBOX_FAILURE,c as SITE_GLOBAL_NAME,l as TOOLS_GLOBAL_ALIAS,E as WASM_PAGE_BYTES};
@@ -1,3 +1,3 @@
1
- import{UnknownToolError as e}from"../tool-errors.js";import{buildDiscoverDescription as t}from"./prompts.js";import{renderDiscoverOutput as n}from"./capabilities.js";import{DISCOVER_TOOL_NAME as r,READ_ONLY_ANNOTATIONS as i,sanitizeToolName as a}from"@redocly/mcp";function o(e,n,o=!0){let s=[.../* @__PURE__ */ new Set([...e.map(e=>a(e.name)),...n.map(e=>a(e.id))])];return{name:r,title:`Get docs function signatures`,description:t(o),annotations:i,schema:{type:`object`,required:[],additionalProperties:!1,properties:{names:{type:`array`,description:o?`Names of the sandbox functions to discover: ${s.join(`, `)}. Omit to discover all of them.`:`Names of the sandbox functions to discover. Omit to discover all of them.`,items:s.length>0?{type:`string`,enum:s}:{type:`string`},nullable:!0}}}}}function s(t,r,i,o){let s=new Map(t.map(e=>[a(e.name),e])),c=new Set(i.map(e=>a(e.id)));return async l=>{let u=[...new Set((l.names??[]).map(a))],d=u.filter(e=>!s.has(e)&&!c.has(e));if(d.length>0){let t=[...s.keys(),...c];throw new e(`Unknown function name(s): ${d.join(`, `)}. Valid names: ${t.join(`, `)}.`)}let f=u.length===0?i:i.filter(e=>u.includes(a(e.id))),p=u.length===0?t:u.filter(e=>s.has(e)).map(e=>s.get(e)),m=await Promise.all(p.map(e=>r(e.name))),h=p.filter((e,t)=>m[t]),g=p.filter((e,t)=>!m[t]),_=[await n(h,f,o)];return g.length>0&&_.push(`Not available for this request: ${g.map(e=>a(e.name)).join(`, `)}`),{content:[{type:`text`,text:_.join(`
1
+ import{DISCOVER_TOOL_NAME as e}from"../../constants.js";import{UnknownToolError as t}from"../tool-errors.js";import{sanitizeToolName as n}from"./tool-declarations.js";import{READ_ONLY_ANNOTATIONS as r}from"../tools/schemas.js";import{buildDiscoverDescription as i}from"./prompts.js";import{renderDiscoverOutput as a}from"./capabilities.js";function o(t,a,o=!0){let s=[.../* @__PURE__ */ new Set([...t.map(e=>n(e.name)),...a.map(e=>n(e.id))])];return{name:e,title:`Get docs function signatures`,description:i(o),annotations:r,schema:{type:`object`,required:[],additionalProperties:!1,properties:{names:{type:`array`,description:o?`Names of the sandbox functions to discover: ${s.join(`, `)}. Omit to discover all of them.`:`Names of the sandbox functions to discover. Omit to discover all of them.`,items:s.length>0?{type:`string`,enum:s}:{type:`string`},nullable:!0}}}}}function s(e,r,i,o){let s=new Map(e.map(e=>[n(e.name),e])),c=new Set(i.map(e=>n(e.id)));return async l=>{let u=[...new Set((l.names??[]).map(n))],d=u.filter(e=>!s.has(e)&&!c.has(e));if(d.length>0){let e=[...s.keys(),...c];throw new t(`Unknown function name(s): ${d.join(`, `)}. Valid names: ${e.join(`, `)}.`)}let f=u.length===0?i:i.filter(e=>u.includes(n(e.id))),p=u.length===0?e:u.filter(e=>s.has(e)).map(e=>s.get(e)),m=await Promise.all(p.map(e=>r(e.name))),h=p.filter((e,t)=>m[t]),g=p.filter((e,t)=>!m[t]),_=[await a(h,f,o)];return g.length>0&&_.push(`Not available for this request: ${g.map(e=>n(e.name)).join(`, `)}`),{content:[{type:`text`,text:_.join(`
2
2
 
3
3
  `)}]}}}export{s as discover,o as discoverSchema};
@@ -1 +1 @@
1
- import{buildExecuteDescription as e}from"./prompts.js";import{EXECUTE_TOOL_NAME as t}from"@redocly/mcp";const n=`Execute code`;function r(e){return e.readOnlyHint?`Query the docs with code`:n}const i={name:t,title:n,description:e(!1),schema:{type:`object`,required:[`code`,`description`],additionalProperties:!1,properties:{code:{type:`string`,description:`JavaScript to run in the sandbox. Return a value to receive it as the result.`,minLength:1},description:{type:`string`,description:`A short, human-readable summary of what this code does.`,minLength:1},sessionHandle:{type:`string`,description:`Handle returned by createAnonymousSession. Required when an API needs credentials. This parameter is only offered when createAnonymousSession is available, so pass it whenever you have called that tool.`,minLength:1}}}},a={result:{description:`The value the code returned, as JSON`},error:{type:`string`,description:`Why the code failed. Set only on a failed call`}},o={type:`array`,description:"Every `fetch` request that reached an API before the failure, with its status; running the code again sends them again. Set only on a failed call",items:{type:`object`,properties:{method:{type:`string`},url:{type:`string`},status:{type:`number`,description:`Unset when no response arrived`}}}};function s(e){return{type:`object`,properties:e?{...a,sentFetches:o}:a}}export{i as EXECUTE_TOOL_SCHEMA,s as executeOutputSchema,r as executeToolTitle};
1
+ import{EXECUTE_TOOL_NAME as e}from"../../constants.js";import{buildExecuteDescription as t}from"./prompts.js";const n=`Execute code`;function r(e){return e.readOnlyHint?`Query the docs with code`:n}const i={name:e,title:n,description:t(!1),schema:{type:`object`,required:[`code`,`description`],additionalProperties:!1,properties:{code:{type:`string`,description:`JavaScript to run in the sandbox. Return a value to receive it as the result.`,minLength:1},description:{type:`string`,description:`A short, human-readable summary of what this code does.`,minLength:1},sessionHandle:{type:`string`,description:`Handle returned by createAnonymousSession. Required when an API needs credentials. This parameter is only offered when createAnonymousSession is available, so pass it whenever you have called that tool.`,minLength:1}}}},a={result:{description:`The value the code returned, as JSON`},error:{type:`string`,description:`Why the code failed. Set only on a failed call`}},o={type:`array`,description:"Every `fetch` request that reached an API before the failure, with its status; running the code again sends them again. Set only on a failed call",items:{type:`object`,properties:{method:{type:`string`},url:{type:`string`},status:{type:`number`,description:`Unset when no response arrived`}}}};function s(e){return{type:`object`,properties:e?{...a,sentFetches:o}:a}}export{i as EXECUTE_TOOL_SCHEMA,s as executeOutputSchema,r as executeToolTitle};
@@ -0,0 +1 @@
1
+ function e(e,t,n){let r=Math.max(0,n-Date.now()),i=`Execution timed out after ${t}ms. Do less processing in the script, or ask the functions for less data.`,a=`Exceeded the maximum lifetime of ${r}ms. Make fewer function calls in one script, or ask for less data.`,o=Date.now()+t,s=t,c,l=()=>{},u=new Promise((e,t)=>{l=e=>{c=e,t(Error(e))}}),d,f=()=>{clearTimeout(d),d=setTimeout(()=>l(i),t)};e.runtime.setInterruptHandler(()=>{let e=Date.now();return e>o?c=i:e>n&&(c=a),c!==void 0}),f();let p=setTimeout(()=>l(a),r),m=0;return{hostCall:t=>{s=o-Date.now(),m++,clearTimeout(d);let n=()=>{e.alive&&(o=Date.now()+s,--m===0&&f())},r=t();return r.then(n,n),r},aborted:u,expiredMessage:()=>c,dispose(){clearTimeout(d),clearTimeout(p)}}}export{e as createExecutionBudget};
@@ -1 +1 @@
1
- import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{formatError as t,innerToolErrorClass as n}from"../tool-errors.js";import{auditCode as r,callAttribution as i,logCodeExecutionAudit as a,logMcpToolCallAudit as o,toolOutputText as s,toolResultText as c}from"../audit.js";import{CODE_MODE_TOOL_NAMES as l,INTERNAL_ERROR_MESSAGE as u}from"./constants.js";import{availableTools as d}from"../tool-registry.js";import{SandboxBusyError as f,sandboxAdmission as p}from"./admission.js";import{createSandboxSetup as m}from"./sandbox-setup.js";import{createToolInputValidator as h}from"./tool-input-validator.js";import{SANDBOX_FAILURE as g,authoredPosition as _,describeGuestError as v,returnLastExpression as y,sanitizeToolName as b}from"@redocly/mcp";import{isCallToolResult as x}from"@modelcontextprotocol/server";async function S(e){let{code:n,registry:o,ctx:s,timeoutMs:c}=e,h=await d(o,s),x=s.telemetry?.trackCodeExecution(n,e.hostFetch),S=x?.hostFetch??e.hostFetch,w=Object.create(null);for(let e of h){if(l.has(e.schema.name))continue;let t=b(e.schema.name);w[t]=C(e,t,s,x)}let T=Object.keys(w);a(s.logger,{audit:r(n),code:n,description:e.description??``,sessionHandle:e.sessionHandle,toolNames:T,fetchBudget:e.fetchBudget,fetchCapable:S!==void 0,...i(s)});let E=y(n),D;try{let{runInSandbox:e}=await import(`./sandbox.js`);D=await p.run(()=>e(E.code,{setupContext:m(w,S),authoredCode:n,timeoutMs:c,deadline:s.executeDeadline,logger:s.logger}))}catch(e){e instanceof f?D={error:e.message}:(s.logger?.error(`MCP code mode failed before a result: ${t(e)}`),D={error:u,failure:g.RuntimeError})}let O=D.error===void 0?void 0:v(n,D.error,D.errorPosition&&_(E,D.errorPosition),T,D.failure),k=O===void 0?{result:D.result}:{error:O.message},A={content:[{type:`text`,text:JSON.stringify(k)}],structuredContent:k,isError:O!==void 0};return x?.finish(D,A,O?.unknownTool),A}function C(e,r,a,l){let{name:u}=e.schema,d=h(r,e.schema.schema),f={tool:u,mode:`code`,...i(a)},p=async r=>{let i=w(r,e.inputAliases),l=d(i);if(l)throw Error(l);let p;try{p=await e.execute(i,a)}catch(e){throw a.logger?.warn(`MCP tool "${u}" failed in code mode: ${t(e)}`),o(a.logger,{...f,args:r,errorClass:n(e)}),e}let m=x(p)&&p.isError===!0?p:void 0;if(o(a.logger,{...f,args:r,result:s(p),errorClass:m?`tool_error`:void 0}),m)throw Error(c(m));return p};return async e=>T(await(l?l.innerToolCall(u,()=>p(e)):p(e)))}function w(t,n){if(!n||!e(t))return t;let r={...t};for(let[e,t]of Object.entries(n))e in r&&(r[t]??=r[e],delete r[e]);return r}function T(e){if(!x(e))return e;if(e.structuredContent!==void 0)return e.structuredContent;let t=c(e);try{return JSON.parse(t)}catch{return t}}export{S as runCodeMode};
1
+ import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{formatError as t,innerToolErrorClass as n}from"../tool-errors.js";import{auditCode as r,callAttribution as i,logCodeExecutionAudit as a,logMcpToolCallAudit as o,toolOutputText as s,toolResultText as c}from"../audit.js";import{CODE_MODE_TOOL_NAMES as l,INTERNAL_ERROR_MESSAGE as u,SANDBOX_FAILURE as d}from"./constants.js";import{availableTools as f}from"../tool-registry.js";import{sanitizeToolName as p}from"./tool-declarations.js";import{SandboxBusyError as m,sandboxAdmission as h}from"./admission.js";import{authoredPosition as g,returnLastExpression as _}from"./return-last-expression.js";import{createSandboxSetup as v}from"./sandbox-setup.js";import{createToolInputValidator as y}from"./tool-input-validator.js";import{describeGuestError as b}from"./unknown-tool-hint.js";import{isCallToolResult as x}from"@modelcontextprotocol/server";async function S(e){let{code:n,registry:o,ctx:s,timeoutMs:c}=e,y=await f(o,s),x=s.telemetry?.trackCodeExecution(n,e.hostFetch),S=x?.hostFetch??e.hostFetch,w=Object.create(null);for(let e of y){if(l.has(e.schema.name))continue;let t=p(e.schema.name);w[t]=C(e,t,s,x)}let T=Object.keys(w);a(s.logger,{audit:r(n),code:n,description:e.description??``,sessionHandle:e.sessionHandle,toolNames:T,fetchBudget:e.fetchBudget,fetchCapable:S!==void 0,...i(s)});let E=_(n),D;try{let{runInSandbox:e}=await import(`./sandbox.js`);D=await h.run(()=>e(E.code,{setupContext:v(w,S),authoredCode:n,timeoutMs:c,deadline:s.executeDeadline,logger:s.logger}))}catch(e){e instanceof m?D={error:e.message}:(s.logger?.error(`MCP code mode failed before a result: ${t(e)}`),D={error:u,failure:d.RuntimeError})}let O=D.error===void 0?void 0:b(n,D.error,D.errorPosition&&g(E,D.errorPosition),T,D.failure),k=O===void 0?{result:D.result}:{error:O.message},A={content:[{type:`text`,text:JSON.stringify(k)}],structuredContent:k,isError:O!==void 0};return x?.finish(D,A,O?.unknownTool),A}function C(e,r,a,l){let{name:u}=e.schema,d=y(r,e.schema.schema),f={tool:u,mode:`code`,...i(a)},p=async r=>{let i=w(r,e.inputAliases),l=d(i);if(l)throw Error(l);let p;try{p=await e.execute(i,a)}catch(e){throw a.logger?.warn(`MCP tool "${u}" failed in code mode: ${t(e)}`),o(a.logger,{...f,args:r,errorClass:n(e)}),e}let m=x(p)&&p.isError===!0?p:void 0;if(o(a.logger,{...f,args:r,result:s(p),errorClass:m?`tool_error`:void 0}),m)throw Error(c(m));return p};return async e=>T(await(l?l.innerToolCall(u,()=>p(e)):p(e)))}function w(t,n){if(!n||!e(t))return t;let r={...t};for(let[e,t]of Object.entries(n))e in r&&(r[t]??=r[e],delete r[e]);return r}function T(e){if(!x(e))return e;if(e.structuredContent!==void 0)return e.structuredContent;let t=c(e);try{return JSON.parse(t)}catch{return t}}export{S as runCodeMode};
@@ -1,8 +1,8 @@
1
- import{buildToolList as e}from"./tool-list.js";const t=2048,n="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).";function r(n,r){if(r.length===0)return n;let i=t-n.length-66-3,a=e(r,i);return a?[n,``,"Functions for `execute` scripts (signatures come from `discover`):",a].join(`
2
- `):n}function i(e,t){return[t?`Run plain JavaScript (no TypeScript syntax) in a sandbox against the documentation at ${t}. The script calls the sandbox functions on the global \`site\` object.`:"Run plain JavaScript (no TypeScript syntax) in a sandbox against this documentation site. The script calls the sandbox functions on the global `site` object.",e?"The extra globals are `site`, `fetch`, `URL`, `URLSearchParams`, and `FormData` - there is no `console`, `setTimeout`, `require`, or Node.js API; all other I/O goes through `site`.":"The only extra global is `site` - there is no `fetch`, `console`, `setTimeout`, `require`, or Node.js API; all I/O goes through `site`.",``,"Workflow - minimize round-trips; one `discover` call plus one `execute` call covers most requests:",`1. Analyze the request and decide which sandbox functions it needs.`,"2. Call `discover` with those names to get their exact TypeScript signatures - inputs, result shapes, and a worked example. NEVER call `execute` with guessed function names, parameter names, enum values, or result field names: read fields off the declared return types, not from assumptions.","3. Batch everything into a SINGLE script: chain function calls, pass one call's output into the next, process results in plain JavaScript, and `return` only what the request needs."].join(`
3
- `)}function a(e,n){let r=e&&n(e);return r&&r.length<=t?r:n()}function o(e,t=[],n){return r(a(n,t=>i(e,t)),t)}function s(e){return e?`Tools for the documentation at ${e}.`:`Tools for this documentation site.`}function c(e){return`${s(e)} Use them to answer questions about the content of these docs.`}function l(e){return a(e,c)}function u(e){return["Get the exact TypeScript signatures of the sandbox functions that `execute` scripts can call.",`Analyze the user request first, then pass \`names\` with only the functions the request needs (${e?`every name is listed in this input schema / description`:`every name is in the enum of this input schema`}); omit \`names\` only when you cannot tell which functions apply.`,"Always call this before your first `execute` and never guess signatures. Request every function the task may need in ONE call instead of calling this repeatedly."].join(`
4
- `)}function d(e,t){let n=[c(t),"- `discover` returns the exact TypeScript signatures of the sandbox functions.","- `execute` runs a JavaScript script that calls those functions on the global `site` object.","Workflow: analyze the request, call `discover` once with `names` set to only the functions it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess function signatures."];return e&&n.push("The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `discover` call to get its contract and the list of callable APIs."),n.join(`
5
- `)}function f(e,t=[],n){return r(a(n,t=>d(e,t)),t)}const p=[`listApis`,`getEndpoints`],m=[`Example - list the write endpoints of an API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const writes = endpoints.filter((e) => e.method !== 'GET');`,"return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
6
- `);function h(e){if(p.every(t=>e.includes(t)))return m;let[t]=e;return t?[`Example - call \`${t}\` and return what the request needs:`,``,"```js",`const result = await site.${t}({ /* the input its signature above declares */ });`,`return result;`,"```"].join(`
7
- `):``}const g=["Types named `OpenApi…` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
8
- `);export{n as EXECUTE_ARGS_NOTE,g as USAGE_NOTES,f as buildCodeModeInstructions,u as buildDiscoverDescription,o as buildExecuteDescription,h as buildExecuteExample,l as buildToolsModeInstructions,s as docsSiteSentence};
1
+ import{buildToolList as e}from"./tool-list.js";const t=2048,n="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).",r="Write plain JavaScript: no type annotations, interfaces or `as` casts.";function i(n,r){if(r.length===0)return n;let i=t-n.length-66-3,a=e(r,i);return a?[n,``,"Functions for `execute` scripts (signatures come from `discover`):",a].join(`
2
+ `):n}function a(e,t){return[t?`Run plain JavaScript (no TypeScript syntax) in a sandbox against the documentation at ${t}. The script calls the sandbox functions on the global \`site\` object.`:"Run plain JavaScript (no TypeScript syntax) in a sandbox against this documentation site. The script calls the sandbox functions on the global `site` object.",e?"The extra globals are `site`, `fetch`, `URL`, `URLSearchParams`, and `FormData` - there is no `console`, `setTimeout`, `require`, or Node.js API; all other I/O goes through `site`.":"The only extra global is `site` - there is no `fetch`, `console`, `setTimeout`, `require`, or Node.js API; all I/O goes through `site`.",``,"Workflow - minimize round-trips; one `discover` call plus one `execute` call covers most requests:",`1. Analyze the request and decide which sandbox functions it needs.`,"2. Call `discover` with those names to get their exact TypeScript signatures - inputs, result shapes, and a worked example. NEVER call `execute` with guessed function names, parameter names, enum values, or result field names: read fields off the declared return types, not from assumptions.","3. Batch everything into a SINGLE script: chain function calls, pass one call's output into the next, process results in plain JavaScript, and `return` only what the request needs."].join(`
3
+ `)}function o(e,n){let r=e&&n(e);return r&&r.length<=t?r:n()}function s(e,t=[],n){return i(o(n,t=>a(e,t)),t)}function c(e){return e?`Tools for the documentation at ${e}.`:`Tools for this documentation site.`}function l(e){return`${c(e)} Use them to answer questions about the content of these docs.`}function u(e){return o(e,l)}function d(e){return["Get the exact TypeScript signatures of the sandbox functions that `execute` scripts can call.",`Analyze the user request first, then pass \`names\` with only the functions the request needs (${e?`every name is listed in this input schema / description`:`every name is in the enum of this input schema`}); omit \`names\` only when you cannot tell which functions apply.`,"Always call this before your first `execute` and never guess signatures. Request every function the task may need in ONE call instead of calling this repeatedly."].join(`
4
+ `)}function f(e,t){let n=[l(t),"- `discover` returns the exact TypeScript signatures of the sandbox functions.","- `execute` runs a JavaScript script that calls those functions on the global `site` object.","Workflow: analyze the request, call `discover` once with `names` set to only the functions it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess function signatures."];return e&&n.push("The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `discover` call to get its contract and the list of callable APIs."),n.join(`
5
+ `)}function p(e,t=[],n){return i(o(n,t=>f(e,t)),t)}const m=[`listApis`,`getEndpoints`],h=[`Example - list the write endpoints of an API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const writes = endpoints.filter((e) => e.method !== 'GET');`,"return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
6
+ `);function g(e){if(m.every(t=>e.includes(t)))return h;let[t]=e;return t?[`Example - call \`${t}\` and return what the request needs:`,``,"```js",`const result = await site.${t}({ /* the input its signature above declares */ });`,`return result;`,"```"].join(`
7
+ `):``}const _=["Types named `OpenApi…` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
8
+ `);export{n as EXECUTE_ARGS_NOTE,r as PLAIN_JAVASCRIPT_RULE,_ as USAGE_NOTES,p as buildCodeModeInstructions,d as buildDiscoverDescription,s as buildExecuteDescription,g as buildExecuteExample,u as buildToolsModeInstructions,c as docsSiteSentence};
@@ -0,0 +1 @@
1
+ import{SANDBOX_FAILURE as e}from"./constants.js";function t(t,a,o){try{let s=t.callFunction(a,t.undefined,o);return s.error?i(s.error.consume(e=>r(t,e))):s.value.consume(r=>{if(t.typeof(r)!==`string`)return i(n(t,o));let a=t.getProp(r,`length`).consume(e=>t.getNumber(e));return a>1048576?{error:`Result is too large (${a} bytes); return less data`,failure:e.OutputTooLarge}:{result:JSON.parse(t.getString(r))}})}finally{o.dispose()}}function n(e,t){let n=e.typeof(t);return n===`function`||n===`symbol`?`the value is a ${n}`:`the value has no JSON form`}function r(e,t){let n=e.typeof(t);if(n===`string`)return e.getString(t);if(n===`object`&&!e.eq(t,e.null)){let n=e.getProp(t,`message`).consume(t=>e.typeof(t)===`string`?e.getString(t):void 0);if(n!==void 0)return n}return`${n===`object`?`an`:`a`} ${n} was thrown`}function i(t){return t.includes(`out of memory`)?{error:`Result is too large to serialize; return less data`,failure:e.OutputTooLarge}:{error:`The result could not be converted to JSON (${t}); return plain data instead`,failure:e.RuntimeError}}export{t as readResult};
@@ -0,0 +1,6 @@
1
+ const e=(async()=>{}).constructor,t=/^(?:[)\]}]|(?:async\s+)?(?:function|class|const|let|var|if|for|while|do|switch|try|return|throw)\b)/,n=`return (`;function r(e){let r=e.length;for(;r>0&&` \r
2
+ ;`.includes(e[r-1]);)r--;let i=e.slice(0,r);for(let e of a(i)){let r=i.slice(e);if(t.test(r.slice(o(r))))continue;let a=`${i.slice(0,e)}${n}${r}\n)`;if(s(`${n}${r}\n)`)&&s(a))return{code:a,returnAt:e}}return{code:e}}function i({code:e,returnAt:t},n){if(t===void 0)return n;let r=e.slice(0,t).split(`
3
+ `),i=r.length,a=(r.at(-1)??``).length+1;return n.line!==i||n.column<a?n:{line:i,column:Math.max(a,n.column-8)}}function a(e){let t=[0];for(let n=e.length-1;n>=0&&t.length<=50;n--)(e[n]===`
4
+ `||e[n]===`;`)&&t.push(n+1);return t.sort((e,t)=>e-t)}function o(e){let t=0;for(;;){for(;t<e.length&&` \r
5
+ `.includes(e[t]);)t++;if(e.startsWith(`//`,t)){let n=e.indexOf(`
6
+ `,t);t=n===-1?e.length:n}else if(e.startsWith(`/*`,t)){let n=e.indexOf(`*/`,t+2);t=n===-1?e.length:n+2}else return t}}function s(t){try{return new e(t),!0}catch{return!1}}export{i as authoredPosition,r as returnLastExpression};
@@ -0,0 +1 @@
1
+ function e(e,t){let n=e.evalCode(t,`returns-from-top-level.js`,{type:`module`,compileOnly:!0});return n.error?n.error.consume(t=>e.dump(t))?.message===`return not in a function`:(n.value.dispose(),!1)}export{e as returnsFromTopLevel};
@@ -1 +1 @@
1
- import{errorMessage as e}from"../../../../../../shared/utils/error-message.js";import{formatError as t}from"../tool-errors.js";import{DEFAULT_MAX_LIFETIME_MS as n,DEFAULT_TIMEOUT_MS as r,INITIAL_TOTAL_MEMORY_BYTES as i,INTERNAL_ERROR_MESSAGE as a,MAX_ALLOCATION_BYTES as o,MAX_STACK_SIZE_BYTES as s,MAX_TOTAL_MEMORY_BYTES as c,WASM_PAGE_BYTES as l}from"./constants.js";import{SANDBOX_FAILURE as u,createExecutionBudget as d,readResult as f,returnsFromTopLevel as p}from"@redocly/mcp";import m from"@jitl/quickjs-singlefile-mjs-release-sync";import{newQuickJSWASMModuleFromVariant as h,newVariant as g}from"quickjs-emscripten-core";var _=class extends Error{guestError;name=`ReportableError`;constructor(e,t){super(e),this.guestError=t}};function v(t){try{return t()}catch(t){throw new _(e(t),w(t))}}let y;function b(){return y??=h(g(m,{wasmMemory:new WebAssembly.Memory({initial:i/l,maximum:c/l})}))}async function x(e,i={}){let{timeoutMs:c=r,deadline:l=Date.now()+n,setupContext:m,authoredCode:h=e,logger:g}=i,x,C,w,D,O;try{let t=x=(await b()).newContext();t.runtime.setMemoryLimit(o),t.runtime.setMaxStackSize(s),C=d(t,c,l),O=t.unwrapResult(t.evalCode(`JSON.stringify`)),w=m?.(t,C)??void 0,D=v(()=>t.unwrapResult(t.evalCode(`(async () => {\n${e}\n})()`,S)));let n=t.resolvePromise(D);t.runtime.executePendingJobs();let r=await Promise.race([n,C.aborted]),i=v(()=>t.unwrapResult(r));if(t.typeof(i)===`undefined`)return i.dispose(),{error:p(t,h)?"The code returned undefined: the `return` ran but produced no value. Read fields off the declared return types — a field name that does not exist reads as undefined — and do not `return;` or `return undefined`.":"The code returned undefined because nothing was returned. Add a top-level `return` of the value to send back.",failure:u.NoReturn};let a=f(t,O,i);if(a.error===void 0)return a;let g=C.expiredMessage();return g===void 0?a:{error:g,failure:u.Timeout}}catch(e){let n=C?.expiredMessage();return n===void 0?e instanceof _?{error:e.message,failure:T(e.guestError,D!==void 0),errorPosition:E(e.guestError.stack)}:(g?.error(`MCP code mode sandbox failed: ${t(e)}`),{error:a,failure:u.RuntimeError}):{error:n,failure:u.Timeout}}finally{C?.dispose(),D?.dispose(),O?.dispose();try{w?.()}catch{}try{x?.dispose()}catch{y=void 0}}}const S=`sandbox-code.js`,C=/sandbox-code\.js:(\d+):(\d+)/;function w(e){let{cause:t}=e;return typeof t==`object`&&t?t:{}}function T({name:e,message:t},n){return e===`InternalError`&&t===`out of memory`?u.MemoryLimit:e===`SyntaxError`&&!n?u.SyntaxError:e===`HostOutputTooLargeError`?u.OutputTooLarge:e===`HostFunctionError`?u.HostError:u.RuntimeError}function E(e){let t=typeof e==`string`?C.exec(e):null;if(!t)return;let n=Number(t[1])-1;return n>=1?{line:n,column:Number(t[2])}:void 0}export{x as runInSandbox};
1
+ import{errorMessage as e}from"../../../../../../shared/utils/error-message.js";import{formatError as t}from"../tool-errors.js";import{DEFAULT_MAX_LIFETIME_MS as n,DEFAULT_TIMEOUT_MS as r,INITIAL_TOTAL_MEMORY_BYTES as i,INTERNAL_ERROR_MESSAGE as a,MAX_ALLOCATION_BYTES as o,MAX_STACK_SIZE_BYTES as s,MAX_TOTAL_MEMORY_BYTES as c,SANDBOX_FAILURE as l,WASM_PAGE_BYTES as u}from"./constants.js";import{createExecutionBudget as d}from"./execution-budget.js";import{readResult as f}from"./read-result.js";import{returnsFromTopLevel as p}from"./returns-from-top-level.js";import m from"@jitl/quickjs-singlefile-mjs-release-sync";import{newQuickJSWASMModuleFromVariant as h,newVariant as g}from"quickjs-emscripten-core";var _=class extends Error{guestError;name=`ReportableError`;constructor(e,t){super(e),this.guestError=t}};function v(t){try{return t()}catch(t){throw new _(e(t),w(t))}}let y;function b(){return y??=h(g(m,{wasmMemory:new WebAssembly.Memory({initial:i/u,maximum:c/u})}))}async function x(e,i={}){let{timeoutMs:c=r,deadline:u=Date.now()+n,setupContext:m,authoredCode:h=e,logger:g}=i,x,C,w,D,O;try{let t=x=(await b()).newContext();t.runtime.setMemoryLimit(o),t.runtime.setMaxStackSize(s),C=d(t,c,u),O=t.unwrapResult(t.evalCode(`JSON.stringify`)),w=m?.(t,C)??void 0,D=v(()=>t.unwrapResult(t.evalCode(`(async () => {\n${e}\n})()`,S)));let n=t.resolvePromise(D);t.runtime.executePendingJobs();let r=await Promise.race([n,C.aborted]),i=v(()=>t.unwrapResult(r));if(t.typeof(i)===`undefined`)return i.dispose(),{error:p(t,h)?"The code returned undefined: the `return` ran but produced no value. Read fields off the declared return types — a field name that does not exist reads as undefined — and do not `return;` or `return undefined`.":"The code returned undefined because nothing was returned. Add a top-level `return` of the value to send back.",failure:l.NoReturn};let a=f(t,O,i);if(a.error===void 0)return a;let g=C.expiredMessage();return g===void 0?a:{error:g,failure:l.Timeout}}catch(e){let n=C?.expiredMessage();return n===void 0?e instanceof _?{error:e.message,failure:T(e.guestError,D!==void 0),errorPosition:E(e.guestError.stack)}:(g?.error(`MCP code mode sandbox failed: ${t(e)}`),{error:a,failure:l.RuntimeError}):{error:n,failure:l.Timeout}}finally{C?.dispose(),D?.dispose(),O?.dispose();try{w?.()}catch{}try{x?.dispose()}catch{y=void 0}}}const S=`sandbox-code.js`,C=/sandbox-code\.js:(\d+):(\d+)/;function w(e){let{cause:t}=e;return typeof t==`object`&&t?t:{}}function T({name:e,message:t},n){return e===`InternalError`&&t===`out of memory`?l.MemoryLimit:e===`SyntaxError`&&!n?l.SyntaxError:e===`HostOutputTooLargeError`?l.OutputTooLarge:e===`HostFunctionError`?l.HostError:l.RuntimeError}function E(e){let t=typeof e==`string`?C.exec(e):null;if(!t)return;let n=Number(t[1])-1;return n>=1?{line:n,column:Number(t[2])}:void 0}export{x as runInSandbox};
@@ -0,0 +1,4 @@
1
+ const e=/^[A-Za-z_$][\w$]*$/;function t(t){let n=t.split(/[^A-Za-z0-9]+/).filter(Boolean).map((e,t)=>t===0?e:e[0].toUpperCase()+e.slice(1)).join(``);return e.test(n)?n:`_${n}`}function n(e,n){return n===`code`?t(e):e}function r(e){return["```ts",`declare const site: {`,e.map(e=>{let n=e.schema,r=e.outputSchema?a(e.outputSchema):`unknown`,o=n.required?.length?`input`:`input?`;return` /** ${i(e.description)} */\n ${t(e.name)}(${o}: ${a(n,` `)}): Promise<${r}>;`}).join(`
2
+ `),`};`,"```"].join(`
3
+ `)}function i(e){return(e??``).replace(/\*\//g,`*\\/`)}function a(e,t=``){if(!e||typeof e!=`object`)return`unknown`;let n=typeof e.codemodeType==`string`?[e.codemodeType]:Array.isArray(e.enum)&&e.enum.length>0?e.enum.map(s):[o(e,t)];return e.nullable&&n.push(`null`),[...new Set(n)].join(` | `)}function o(e,t){switch(e.type){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`array`:return`Array<${a(e.items,t)}>`;case`object`:return c(e,t);default:return`unknown`}}function s(e){return typeof e==`string`?`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}'`:String(e)}function c(t,n){let r=t.properties??{},o=Object.keys(r),s=t.additionalProperties,c=s?s===!0?`unknown`:a(s,n):void 0;if(o.length===0)return s===!1?`{}`:`Record<string, ${c??`unknown`}>`;let l=new Set(t.required??[]),u=o.map(t=>{let i=r[t],o=l.has(t)?``:`?`,s=e.test(t)?t:JSON.stringify(t);return{doc:i.description,field:`${s}${o}: ${a(i,n+` `)}`}});if(c&&u.push({field:`[key: string]: ${c}`}),!u.some(({doc:e})=>e))return`{ ${u.map(({field:e})=>e).join(`; `)} }`;let d=n+` `;return`{\n${u.map(({doc:e,field:t})=>`${e?`${d}/** ${i(e)} */\n`:``}${d}${t};`).join(`
4
+ `)}\n${n}}`}export{r as buildToolTypeDeclarations,t as sanitizeToolName,n as toolNameForMode};
@@ -1,2 +1,2 @@
1
- import{mcpToolRegistry as e}from"../registry-instance.js";import{sanitizeToolName as t}from"@redocly/mcp";function n(n,r){return[...n.map(n=>({name:t(n.name),purpose:n.summary??n.description,builtIn:e.get(n.name)!==void 0})),...r.map(e=>({name:t(e.id),purpose:e.purpose,builtIn:!0}))]}function r(e,t){if(e.length===0||t<=0)return``;let n=e.map(e=>({...e,purpose:(e.purpose??``).replace(/\s+/g,` `).trim()}));for(let e of i()){let r=a(n,e);if(r.length<=t)return r}let r=e.map(e=>e.name),o=r.join(`, `);return o.length<=t?o:s(r,t)}function*i(){for(let e=60;e>=40;e--)yield{builtIn:e,custom:60};for(let e=60;e>=20;e--)yield{builtIn:0,custom:e}}function a(e,t){return e.map(({name:e,purpose:n,builtIn:r})=>{let i=r?t.builtIn:t.custom;return n&&i>0?`- ${e} — ${o(n,i)}`:`- ${e}`}).join(`
1
+ import{sanitizeToolName as e}from"./tool-declarations.js";import{mcpToolRegistry as t}from"../registry-instance.js";function n(n,r){return[...n.map(n=>({name:e(n.name),purpose:n.summary??n.description,builtIn:t.get(n.name)!==void 0})),...r.map(t=>({name:e(t.id),purpose:t.purpose,builtIn:!0}))]}function r(e,t){if(e.length===0||t<=0)return``;let n=e.map(e=>({...e,purpose:(e.purpose??``).replace(/\s+/g,` `).trim()}));for(let e of i()){let r=a(n,e);if(r.length<=t)return r}let r=e.map(e=>e.name),o=r.join(`, `);return o.length<=t?o:s(r,t)}function*i(){for(let e=60;e>=40;e--)yield{builtIn:e,custom:60};for(let e=60;e>=20;e--)yield{builtIn:0,custom:e}}function a(e,t){return e.map(({name:e,purpose:n,builtIn:r})=>{let i=r?t.builtIn:t.custom;return n&&i>0?`- ${e} — ${o(n,i)}`:`- ${e}`}).join(`
2
2
  `)}function o(e,t){return e.length<=t?e:`${e.slice(0,t-1).replace(/[\uD800-\uDBFF]$/,``).trimEnd()}…`}function s(e,t){let n=[];for(let r of e){if([...n,r].join(`, `).length+c(e.length-n.length-1).length>t)break;n.push(r)}return n.length>0?`${n.join(`, `)}${c(e.length-n.length)}`:``}function c(e){return e>0?` … (+${e} more)`:``}export{r as buildToolList,n as toToolListEntries};
@@ -0,0 +1,3 @@
1
+ import{SANDBOX_FAILURE as e}from"./constants.js";import{PLAIN_JAVASCRIPT_RULE as t}from"./prompts.js";const n=/^(?:not a function|cannot read property '.*' of (?:undefined|null)|value is not iterable|cannot convert to object)$/,r=/(?:^|[^\w$.])(?:site|tools)(?:\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)|(?:\s*\?\.)?\s*\[\s*(['"])([^'"]*)\2\s*\])(?:\s*\?\.)?\s*$/;function i(e,t,n,r,i){let l=n&&c(e,n),u=l!==void 0&&t===`not a function`?s(e.slice(0,l),r):void 0;if(u!==void 0)return{message:`Unknown function "site.${u}". Available functions: ${r.join(`, `)}`,unknownTool:u};let d=l===void 0?void 0:n,f=a(t,i);return f===void 0?{message:d?`${t} (line ${d.line})`:t}:{message:`${t}${d?` (line ${d.line}, column ${d.column}: \`${o(e,d)}\`)`:``}. ${f}`}}function a(r,i){if(i===e.SyntaxError)return t;if(i===e.RuntimeError&&n.test(r))return`Check the result shape with discover, for example listApis returns { items }.`}function o(e,{line:t,column:n}){let r=e.split(`
2
+ `)[t-1]??``,i=Math.max(0,Math.min(n-1-60,r.length-120)),a=i+120,o=r.slice(i,a).trim();return`${i>0?`…`:``}${o}${a<r.length?`…`:``}`}function s(e,t){let n=r.exec(e),i=n?.[1]??n?.[3];return i!==void 0&&!t.includes(i)?i:void 0}function c(e,{line:t,column:n}){let r=e.split(`
3
+ `);if(t>r.length)return;let i=r.slice(0,t-1).reduce((e,t)=>e+t.length+1,0)+n-1;return i<=e.length?i:void 0}export{i as describeGuestError};
@@ -1 +1 @@
1
- import{RBAC_TEAM_ANONYMOUS as e}from"../../../../../server/rbac/types.js";import{canView as t,parseRbacScope as n,resolveRole as r}from"../../../../../server/rbac/engine.js";import{resolveViewerTeams as i}from"../../../../../server/rbac/teams.js";import{ANONYMOUS_VIEWER as a}from"../../../../../shared/types/auth.js";function o(e){return!!e.mcp?.hide}function s(e){return e!==void 0&&(Object.keys(e),!0)}function c(i){if(!i||typeof i!=`object`||Object.keys(i).length===0)return!1;let a=n(i,`rbac`,()=>{});return!t(r(a,[e]))}function l(e){let t=e.access?.rbac;return{requiresLogin:e.access?.requiresLogin===!0,rbacConfigured:s(t),rbacDeniesAnonymous:Object.values(t?.content??{}).some(c)||c(t?.features?.mcp),featureScope:t?.features?.mcp}}function u(e){return e.requiresLogin||e.rbacDeniesAnonymous}function d(e,t){return!!e.mcp?.publicEndpoint&&u(t)&&p(t,i(a),!1)}function f(e){return d(e,l(e))}function p(e,i,a,o=()=>{}){return e.rbacConfigured?e.featureScope===void 0||t(r(n(e.featureScope,`features.mcp`,o),i)):!e.requiresLogin||a}export{p as canAccessMcpFeature,u as isMcpContentProtected,o as isMcpHidden,d as isPublicEndpointServed,f as isPublicEndpointServedFromConfig,l as resolveMcpAccess};
1
+ import{RBAC_TEAM_ANONYMOUS as e}from"../../../../../shared/rbac/types.js";import{canView as t,parseRbacScope as n,resolveRole as r}from"../../../../../shared/rbac/engine.js";import{resolveViewerTeams as i}from"../../../../../shared/rbac/teams.js";import{ANONYMOUS_VIEWER as a}from"../../../../../shared/types/auth.js";function o(e){return!!e.mcp?.hide}function s(e){return e!==void 0&&(Object.keys(e),!0)}function c(i){if(!i||typeof i!=`object`||Object.keys(i).length===0)return!1;let a=n(i,`rbac`,()=>{});return!t(r(a,[e]))}function l(e){let t=e.access?.rbac;return{requiresLogin:e.access?.requiresLogin===!0,rbacConfigured:s(t),rbacDeniesAnonymous:Object.values(t?.content??{}).some(c)||c(t?.features?.mcp),featureScope:t?.features?.mcp}}function u(e){return e.requiresLogin||e.rbacDeniesAnonymous}function d(e,t){return!!e.mcp?.publicEndpoint&&u(t)&&p(t,i(a),!1)}function f(e){return d(e,l(e))}function p(e,i,a,o=()=>{}){return e.rbacConfigured?e.featureScope===void 0||t(r(n(e.featureScope,`features.mcp`,o),i)):!e.requiresLogin||a}export{p as canAccessMcpFeature,u as isMcpContentProtected,o as isMcpHidden,d as isPublicEndpointServed,f as isPublicEndpointServedFromConfig,l as resolveMcpAccess};
@@ -1 +1 @@
1
- import{MCP_TOOLS_ENTITY_TYPE as e}from"../constants.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{errorMessage as n}from"../../../../../shared/utils/error-message.js";import{isSubprocessError as r}from"../../../../../server/subprocess/runner.js";import{ToolHandlerError as i}from"./tool-errors.js";import{fileURLToPath as a}from"node:url";import{parse as o}from"hono/utils/cookie";const s=a(import.meta.url);function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(e){return`MCP tool "${e}" is not registered or its module does not export a handler for "${e}". Expected \`export default { '${e}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`}function u(e,t){if(c(e))return typeof e.execute==`function`&&typeof e.description==`string`?e:e[t]}const d=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function f(e){return c(e)&&Array.isArray(e.content)&&e.content.every(e=>c(e)&&d.has(e.type))}function p(e,t){if(f(t))return t;if(typeof t==`string`)return{content:[{type:`text`,text:t}]};let n;try{n=JSON.stringify(t)}catch(t){throw Error(`MCP tool "${e}" returned a value that cannot be serialized to JSON: ${S(t)}`)}if(n===void 0)throw Error(`MCP tool "${e}" returned an invalid result.`);return{content:[{type:`text`,text:n}]}}const m={readFile:async()=>{throw Error(`Project files are not available in this environment.`)}};async function h(e,t){let r=u((await t.loadModule(e.handlerModulePath)).default,e.toolName),i=typeof r==`function`?r:r?.execute;if(typeof i!=`function`)return{ok:!1,code:`no-handler-export`,message:l(e.toolName)};let a={...e.context,fs:m};try{if(e.mode===`isAvailable`){let e=typeof r==`function`?void 0:r?.isAvailable;return{ok:!0,output:!e||await e(a)}}let t=await i(e.args,a,e.extra);return{ok:!0,output:p(e.toolName,t)}}catch(e){return{ok:!1,code:`handler-error`,message:n(e),stack:e instanceof Error?e.stack:void 0}}}function g(e){let n=e.request.viewer;return{user:{teams:e.request.teams,claims:e.claims??{...n},email:n?.email,idpAccessToken:void 0,idpId:void 0,isAuthenticated:n?.isAuthenticated??!1},config:e.config,baseUrl:t(e.request),params:{},query:Object.fromEntries(new URL(e.request.url).searchParams),cookies:o(e.request.headers.cookie??``),products:Object.values(e.config.products??{}).map(e=>e.name),accessToken:e.accessToken,metadata:e.metadata}}function _(e,t,n){if(!c(e)||e.type!==`object`)return null;let r=`Invalid arguments for tool "${n}":`;if(!c(t))return`${r} expected an object.`;let i=Array.isArray(e.required)?e.required:[];for(let e of i)if(typeof e==`string`&&!(e in t))return`${r} missing required field "${e}".`;let a=c(e.properties)?e.properties:{};for(let[e,n]of Object.entries(t)){let t=a[e];if(c(t)){if(typeof t.type==`string`&&!v(n,t.type))return`${r} field "${e}" must be ${t.type}.`;if(Array.isArray(t.enum)&&!t.enum.includes(n))return`${r} field "${e}" must be one of ${JSON.stringify(t.enum)}.`}}return null}function v(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&Number.isFinite(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`object`:return c(e);case`array`:return Array.isArray(e);case`null`:return e===null;default:return!0}}function y(e,t,n,r,i){if(!t.subprocess)throw Error(`MCP tool "${e.toolName}" cannot run on this host: no subprocess.`);return t.subprocess.run({modulePath:s,exportName:`invokeCustomTool`,input:{handlerModulePath:t.subprocess.resolveContentModule(e.handlerFilePath),toolName:e.toolName,mode:n,args:r,context:g(t),extra:{sessionId:i?.sessionId,requestId:i?.mcpReq.id??t.requestId,_meta:i?.mcpReq._meta}},timeoutMs:3e4})}function b(e,t){return{schema:e,isAvailable:t.hasAvailabilityGate?async n=>{if(!n.subprocess)return!1;let r=n.isAvailableMemo?.get(e.name);if(r)return r;let i=(async()=>{try{let e=await y(t,n,`isAvailable`);return e.ok&&e.output===!0}catch(t){return n.logger?.warn(`MCP tool "${e.name}" isAvailable failed: ${S(t)}`),!1}})();return n.isAvailableMemo?.set(e.name,i),i}:void 0,async execute(n,r,a){let o=_(t.argsSchema,n,e.name);if(o)throw Error(o);let s=await y(t,r,`execute`,n,a);if(!s.ok){let e=new i(s.message);throw e.stack=s.stack??e.stack,e}return s.output}}}function x(e){let{declaration:t}=e;return b({name:t.name,title:t.title,description:t.description,schema:t.schema,outputSchema:t.outputSchema,annotations:t.annotations},{toolName:t.name,handlerFilePath:e.handler.filePath,argsSchema:t.schema,hasAvailabilityGate:!0})}function S(e){return r(e)?`${e.code}: ${e.message}`:n(e)}function C(e,t){if(!c(t))return{ok:!1,errors:["the default export must be an object with `description` and `execute` properties. Move shared helper code outside the `@mcp` folder."]};let{description:n,inputSchema:r,outputSchema:i,annotations:a,isAvailable:o,execute:s}=t,l=[];return(typeof n!=`string`||n.trim()===``)&&l.push("`description` must be a non-empty string."),typeof s!=`function`&&l.push("`execute` must be a function."),r!==void 0&&(c(r)?r.type!==void 0&&r.type!==`object`&&l.push('`inputSchema.type` must be "object" because MCP tool arguments are named.'):l.push("`inputSchema` must be a JSON Schema object.")),i!==void 0&&!c(i)&&l.push("`outputSchema` must be a JSON Schema object."),a!==void 0&&!c(a)&&l.push("`annotations` must be an object."),o!==void 0&&typeof o!=`function`&&l.push("`isAvailable` must be a function."),l.length>0||typeof n!=`string`?{ok:!1,errors:l}:{ok:!0,schema:{name:e,description:n,schema:Object.assign({type:`object`},r??{properties:{}}),outputSchema:i,annotations:a},hasAvailabilityGate:typeof o==`function`}}async function w(t){let n=[],r=[];for(let i of await t.entities.list({type:e})){let{name:e,sourcePath:a}=i.metadata,o=e=>r.push(`Invalid MCP tool file "${a}": ${e}`);if(t.reservedNames.has(e)){o(`the tool name "${e}" is already used by a built-in MCP tool. Rename the file.`);continue}let s;try{s=(await t.loadContentModule(a)).default}catch(e){o(`the file failed to load: ${S(e)}. Tool files must not have module-level side effects.`);continue}let c=C(e,s);if(!c.ok){o(c.errors.join(` `));continue}n.push({schema:c.schema,sourcePath:a,hasAvailabilityGate:c.hasAvailabilityGate})}return{tools:n,errors:r}}function T(e){return`MCP tool "${e.schema.name}" in ${e.sourcePath} declares no \`outputSchema\`. Add one that describes the returned value.`}const E=/* @__PURE__ */ new Set;function D(e,t){e&&!E.has(t)&&(E.add(t),e.warn(t))}async function O(e){let{loadContentModule:t,logger:n}=e;if(!t)return[];let{tools:r,errors:i}=await w({entities:e.entities,loadContentModule:t,reservedNames:e.reservedNames});for(let e of i)D(n,e);for(let e of r)e.schema.outputSchema===void 0&&D(n,T(e));return r.map(e=>b(e.schema,{toolName:e.schema.name,handlerFilePath:e.sourcePath,argsSchema:e.schema.schema,hasAvailabilityGate:e.hasAvailabilityGate}))}export{O as buildMcpFileTools,x as createCustomTool,h as invokeCustomTool,w as loadMcpFileTools,T as missingOutputSchemaWarning,C as validateToolDefinition};
1
+ import{MCP_TOOLS_ENTITY_TYPE as e}from"../constants.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{errorMessage as n}from"../../../../../shared/utils/error-message.js";import{isSubprocessError as r}from"../../../../../server/subprocess/runner.js";import{ToolHandlerError as i}from"./tool-errors.js";import{fileURLToPath as a}from"node:url";import{parse as o}from"hono/utils/cookie";const s=a(import.meta.url);function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(e){return`MCP tool "${e}" is not registered or its module does not export a handler for "${e}". Expected \`export default { '${e}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`}function u(e,t){if(c(e))return typeof e.execute==`function`&&typeof e.description==`string`?e:e[t]}const d=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function f(e){return c(e)&&Array.isArray(e.content)&&e.content.every(e=>c(e)&&d.has(e.type))}function p(e,t){if(f(t))return t;if(typeof t==`string`)return{content:[{type:`text`,text:t}]};let n;try{n=JSON.stringify(t)}catch(t){throw Error(`MCP tool "${e}" returned a value that cannot be serialized to JSON: ${S(t)}`)}if(n===void 0)throw Error(`MCP tool "${e}" returned an invalid result.`);return{content:[{type:`text`,text:n}]}}const m={readFile:async()=>{throw Error(`Project files are not available in this environment.`)}};async function h(e,t){let r=u((await t.loadModule(e.handlerModulePath)).default,e.toolName),i=typeof r==`function`?r:r?.execute;if(typeof i!=`function`)return{ok:!1,code:`no-handler-export`,message:l(e.toolName)};let a={...e.context,fs:m};try{if(e.mode===`isAvailable`){let e=typeof r==`function`?void 0:r?.isAvailable;return{ok:!0,output:!e||await e(a)}}let t=await i(e.args,a,e.extra);return{ok:!0,output:p(e.toolName,t)}}catch(e){return{ok:!1,code:`handler-error`,message:n(e),stack:e instanceof Error?e.stack:void 0}}}function g(e){let n=e.request.viewer;return{user:{teams:e.request.teams,claims:e.claims??{...n},email:n?.email,idpAccessToken:void 0,idpId:void 0,isAuthenticated:n?.isAuthenticated??!1},config:e.config,baseUrl:t(e.request),params:{},query:Object.fromEntries(new URL(e.request.url).searchParams),cookies:o(e.request.headers.cookie??``),products:Object.values(e.config.products??{}).map(e=>e.name),accessToken:e.accessToken,metadata:e.metadata}}function _(e,t,n){if(!c(e)||e.type!==`object`)return null;let r=`Invalid arguments for tool "${n}":`;if(!c(t))return`${r} expected an object.`;let i=Array.isArray(e.required)?e.required:[];for(let e of i)if(typeof e==`string`&&!(e in t))return`${r} missing required field "${e}".`;let a=c(e.properties)?e.properties:{};for(let[e,n]of Object.entries(t)){let t=a[e];if(c(t)){if(typeof t.type==`string`&&!v(n,t.type))return`${r} field "${e}" must be ${t.type}.`;if(Array.isArray(t.enum)&&!t.enum.includes(n))return`${r} field "${e}" must be one of ${JSON.stringify(t.enum)}.`}}return null}function v(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&Number.isFinite(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`object`:return c(e);case`array`:return Array.isArray(e);case`null`:return e===null;default:return!0}}function y(e,t,n,r,i){if(!t.subprocess)throw Error(`MCP tool "${e.toolName}" cannot run on this host: no subprocess.`);return t.subprocess.run({modulePath:s,exportName:`invokeCustomTool`,input:{handlerModulePath:t.subprocess.resolveContentModule(e.handlerFilePath),toolName:e.toolName,mode:n,args:r,context:g(t),extra:{sessionId:i?.sessionId,requestId:i?.mcpReq.id??t.requestId,_meta:i?.mcpReq._meta}},reuse:!import.meta.env.DEV,timeoutMs:3e4})}function b(e,t){return{schema:e,isAvailable:t.hasAvailabilityGate?async n=>{if(!n.subprocess)return!1;let r=n.isAvailableMemo?.get(e.name);if(r)return r;let i=(async()=>{try{let e=await y(t,n,`isAvailable`);return e.ok&&e.output===!0}catch(t){return n.logger?.warn(`MCP tool "${e.name}" isAvailable failed: ${S(t)}`),!1}})();return n.isAvailableMemo?.set(e.name,i),i}:void 0,async execute(n,r,a){let o=_(t.argsSchema,n,e.name);if(o)throw Error(o);let s=await y(t,r,`execute`,n,a);if(!s.ok){let e=new i(s.message);throw e.stack=s.stack??e.stack,e}return s.output}}}function x(e){let{declaration:t}=e;return b({name:t.name,title:t.title,description:t.description,schema:t.schema,outputSchema:t.outputSchema,annotations:t.annotations},{toolName:t.name,handlerFilePath:e.handler.filePath,argsSchema:t.schema,hasAvailabilityGate:!0})}function S(e){return r(e)?`${e.code}: ${e.message}`:n(e)}function C(e,t){if(!c(t))return{ok:!1,errors:["the default export must be an object with `description` and `execute` properties. Move shared helper code outside the `@mcp` folder."]};let{description:n,inputSchema:r,outputSchema:i,annotations:a,isAvailable:o,execute:s}=t,l=[];return(typeof n!=`string`||n.trim()===``)&&l.push("`description` must be a non-empty string."),typeof s!=`function`&&l.push("`execute` must be a function."),r!==void 0&&(c(r)?r.type!==void 0&&r.type!==`object`&&l.push('`inputSchema.type` must be "object" because MCP tool arguments are named.'):l.push("`inputSchema` must be a JSON Schema object.")),i!==void 0&&!c(i)&&l.push("`outputSchema` must be a JSON Schema object."),a!==void 0&&!c(a)&&l.push("`annotations` must be an object."),o!==void 0&&typeof o!=`function`&&l.push("`isAvailable` must be a function."),l.length>0||typeof n!=`string`?{ok:!1,errors:l}:{ok:!0,schema:{name:e,description:n,schema:Object.assign({type:`object`},r??{properties:{}}),outputSchema:i,annotations:a},hasAvailabilityGate:typeof o==`function`}}async function w(t){let n=[],r=[];for(let i of await t.entities.list({type:e})){let{name:e,sourcePath:a}=i.metadata,o=e=>r.push(`Invalid MCP tool file "${a}": ${e}`);if(t.reservedNames.has(e)){o(`the tool name "${e}" is already used by a built-in MCP tool. Rename the file.`);continue}let s;try{s=(await t.loadContentModule(a)).default}catch(e){o(`the file failed to load: ${S(e)}. Tool files must not have module-level side effects.`);continue}let c=C(e,s);if(!c.ok){o(c.errors.join(` `));continue}n.push({schema:c.schema,sourcePath:a,hasAvailabilityGate:c.hasAvailabilityGate})}return{tools:n,errors:r}}function T(e){return`MCP tool "${e.schema.name}" in ${e.sourcePath} declares no \`outputSchema\`. Add one that describes the returned value.`}const E=/* @__PURE__ */ new Set;function D(e,t){e&&!E.has(t)&&(E.add(t),e.warn(t))}async function O(e){let{loadContentModule:t,logger:n}=e;if(!t)return[];let{tools:r,errors:i}=await w({entities:e.entities,loadContentModule:t,reservedNames:e.reservedNames});for(let e of i)D(n,e);for(let e of r)e.schema.outputSchema===void 0&&D(n,T(e));return r.map(e=>b(e.schema,{toolName:e.schema.name,handlerFilePath:e.sourcePath,argsSchema:e.schema.schema,hasAvailabilityGate:e.hasAvailabilityGate}))}export{O as buildMcpFileTools,x as createCustomTool,h as invokeCustomTool,w as loadMcpFileTools,T as missingOutputSchemaWarning,C as validateToolDefinition};
@@ -0,0 +1 @@
1
+ import{SecretStore as e}from"../secret-store.js";const t=`test-gateway-secret-seed`,n=new e(t);export{t as TEST_GATEWAY_SECRET_SEED,n as secretStore};
@@ -1 +1 @@
1
- import{isEndpointHidden as e}from"../tools/openapi-document.js";import{basePathPrefix as t,operationHttpMethod as n,pathPattern as r,pathTemplateKey as i,pathVariableCount as a}from"./route-pattern.js";import{OPERATION_METHODS as o}from"@redocly/mcp";const s=new Set(o);function c(t){return e(t,`apiCalls`)||e(t,`docs`)}function l(e,i,o,l=[]){let d=t(o),f=new Set(l.map(({method:e,path:t})=>u(e&&n(e),t))),p=[];for(let[t,o]of Object.entries(e.paths??{})){if(!o||typeof o!=`object`)continue;let e=r(d,t);if(!e)continue;let l=c(o)||f.has(u(void 0,t)),m=i.paths?.[t],h=a(t);for(let[r,i]of Object.entries(o)){if(!s.has(r.toLowerCase())||!i||typeof i!=`object`)continue;let a=n(r);p.push({pattern:e,method:a,callable:!l&&!c(i)&&!f.has(u(a,t)),visible:!!m?.[r],variables:h})}}return p}function u(e,t){return`${e??`*`} ${i(t)}`}function d(e,t,n){return e.filter(e=>e.method===n&&e.pattern.test(t))}export{l as apiCallOperationsOf,d as matchingApiCallOperations};
1
+ import{OPERATION_METHODS as e,isEndpointHidden as t}from"../tools/openapi-document.js";import{basePathPrefix as n,operationHttpMethod as r,pathPattern as i,pathTemplateKey as a,pathVariableCount as o}from"./route-pattern.js";const s=new Set(e);function c(e){return t(e,`apiCalls`)||t(e,`docs`)}function l(e,t,a,l=[]){let d=n(a),f=new Set(l.map(({method:e,path:t})=>u(e&&r(e),t))),p=[];for(let[n,a]of Object.entries(e.paths??{})){if(!a||typeof a!=`object`)continue;let e=i(d,n);if(!e)continue;let l=c(a)||f.has(u(void 0,n)),m=t.paths?.[n],h=o(n);for(let[t,i]of Object.entries(a)){if(!s.has(t.toLowerCase())||!i||typeof i!=`object`)continue;let a=r(t);p.push({pattern:e,method:a,callable:!l&&!c(i)&&!f.has(u(a,n)),visible:!!m?.[t],variables:h})}}return p}function u(e,t){return`${e??`*`} ${a(t)}`}function d(e,t,n){return e.filter(e=>e.method===n&&e.pattern.test(t))}export{l as apiCallOperationsOf,d as matchingApiCallOperations};
@@ -1,4 +1,4 @@
1
- import{withPathPrefix as e}from"../../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../../constants.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{credentialSchemesOf as i,schemeFieldName as a}from"./form-contract.js";import{ELICITATION_TTL_MS as o}from"../secret-store.js";import{ICONS as s,code as c,escapeHtml as l,siteHeader as u,targetTitle as d}from"./layout.js";const f=`form-error`,p=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),m={bearer:{title:`API token`,noun:`API token`,placeholder:`Paste your API token`},apiKey:{title:`API key`,noun:`API key`,placeholder:`Paste your API key`},cookie:{title:`Cookie`,noun:`cookie value`,placeholder:`Paste the cookie value`},oauth2ClientCredentials:{title:`OAuth2`,noun:`access token`,placeholder:`Paste an access token`},raw:{title:`Authorization header`,noun:`header value`,placeholder:`Bearer <token>`}};function h(r){let{site:a,target:c,token:p,error:m}=r,h=e(t),y=i(c),b=y.length>1,x=g(r,y),S=x.some(e=>e.isStored),C=b&&S,w=x.map(e=>b?v(e):_(e)).join(``),O=C?`<button class="text-danger" type="submit" form="remove-all">Remove all credentials</button>`:``,k=m?`<div class="banner" role="alert" id="${f}">${s.alert}<p>${l(m.message)}</p></div>`:``,j=c.subject.startsWith(`anon:`)?`<div class="banner warning">${s.warning}<p>This link is not tied to an account. The person who sent it to you can use the credentials that you save here. Continue only if you asked your AI client for this link at ${A(c.expiresAt-o)} UTC.</p></div>`:``;return{title:`Credentials for ${d(c)}`,body:`<div class="page">
1
+ import{MCP_CREDENTIALS_ROUTE as e}from"../../../constants.js";import{withPathPrefix as t}from"../../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{credentialSchemesOf as i,schemeFieldName as a}from"./form-contract.js";import{ELICITATION_TTL_MS as o}from"../secret-store.js";import{ICONS as s,code as c,escapeHtml as l,siteHeader as u,targetTitle as d}from"./layout.js";const f=`form-error`,p=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),m={bearer:{title:`API token`,noun:`API token`,placeholder:`Paste your API token`},apiKey:{title:`API key`,noun:`API key`,placeholder:`Paste your API key`},cookie:{title:`Cookie`,noun:`cookie value`,placeholder:`Paste the cookie value`},oauth2ClientCredentials:{title:`OAuth2`,noun:`access token`,placeholder:`Paste an access token`},raw:{title:`Authorization header`,noun:`header value`,placeholder:`Bearer <token>`}};function h(r){let{site:a,target:c,token:p,error:m}=r,h=t(e),y=i(c),b=y.length>1,x=g(r,y),S=x.some(e=>e.isStored),C=b&&S,w=x.map(e=>b?v(e):_(e)).join(``),O=C?`<button class="text-danger" type="submit" form="remove-all">Remove all credentials</button>`:``,k=m?`<div class="banner" role="alert" id="${f}">${s.alert}<p>${l(m.message)}</p></div>`:``,j=c.subject.startsWith(`anon:`)?`<div class="banner warning">${s.warning}<p>This link is not tied to an account. The person who sent it to you can use the credentials that you save here. Continue only if you asked your AI client for this link at ${A(c.expiresAt-o)} UTC.</p></div>`:``;return{title:`Credentials for ${d(c)}`,body:`<div class="page">
2
2
  <main class="card">
3
3
  ${u(a)}
4
4
  <h1>${S?`Update`:`Add`} credentials for ${l(d(c))}</h1>
@@ -1 +1 @@
1
- import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{toAppData as t}from"../../../../../../../shared/utils/app-data.js";import{parseSrcSet as n}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as r}from"../../../../../../../shared/constants/mcp.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(n){let a=t(await n.entities.load(e)),s=o({seo:n.config.seo,logo:a.theme?.logo,colorMode:n.config.colorMode}),c=await n.entities.get(`mcp:credentials-theme`)?await n.entities.load(r):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(n.request)).host}}function o({seo:e,logo:t,colorMode:r}){let i={},a=e?.title||e?.projectTitle||t?.altText;a&&(i.name=a);let o=new Map((t?.srcSet?n(t.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??t?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
1
+ import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{parseSrcSet as t}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as n}from"../../../../../../../shared/constants/mcp.js";import{toAppData as r}from"../../../../../../../shared/utils/app-data.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(t){let a=r(await t.entities.load(e)),s=o({seo:t.config.seo,logo:a.theme?.logo,colorMode:t.config.colorMode}),c=await t.entities.get(`mcp:credentials-theme`)?await t.entities.load(n):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(t.request)).host}}function o({seo:e,logo:n,colorMode:r}){let i={},a=e?.title||e?.projectTitle||n?.altText;a&&(i.name=a);let o=new Map((n?.srcSet?t(n.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??n?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../server/constants/system-routes.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{secretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t;if(e.req.method===`GET`){let n=await h(t),i=e.req.query(`token`)??``,a=await s.peekElicitation(r,i);return a?R(a,t,n)??M({kv:r,site:n,token:i,target:a},{},200):L(n)}if(e.req.method===`POST`){let i=await h(t),o=await e.req.formData(),c=F(o,`token`),l=await s.peekElicitation(r,c);if(!l)return L(i);let u=R(l,t,i);if(u)return u;let d={kv:r,site:i,token:c,target:l,form:o,ctx:t};switch(F(o,`action`)){case n.remove:return O(d,k(l,F(o,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{kv:n,target:r}=e,i=await s.getStoredSchemes(n,r.subject,r.api),a=t.filter(e=>i[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return a.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,a)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({kv:e,site:t,token:n}){return await s.consumeElicitation(e,n)?I(t,u(),200):L(t)}async function j({kv:e,site:t,token:n},r){let i=await s.consumeElicitation(e,n);if(!i)return L(t);for(let t of r)t.kind===`remove`?await s.deleteSecret(e,i.subject,i.api,t.scheme):await s.setSecret(e,i.subject,i.api,t.scheme,t.secret);let a=await s.getStoredSchemes(e,i.subject,i.api),o={action:r.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:r.map(e=>e.scheme),stored:Object.keys(a).sort()};return I(t,p(i,o),200)}async function M({kv:e,site:t,token:n,target:r},i,a){let o=await s.getStoredSchemes(e,r.subject,r.api);return I(t,l({site:t,target:r,token:n,stored:o,...i}),a)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${e(t.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
1
+ import{SystemRoute as e}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{SecretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t,i=new s(t.gatewaySecretSeed);if(e.req.method===`GET`){let n=await h(t),a=e.req.query(`token`)??``,o=await i.peekElicitation(r,a);return o?R(o,t,n)??M({secretStore:i,kv:r,site:n,token:a,target:o},{},200):L(n)}if(e.req.method===`POST`){let o=await h(t),s=await e.req.formData(),c=F(s,`token`),l=await i.peekElicitation(r,c);if(!l)return L(o);let u=R(l,t,o);if(u)return u;let d={secretStore:i,kv:r,site:o,token:c,target:l,form:s,ctx:t};switch(F(s,`action`)){case n.remove:return O(d,k(l,F(s,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{secretStore:n,kv:r,target:i}=e,a=await n.getStoredSchemes(r,i.subject,i.api),o=t.filter(e=>a[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return o.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,o)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({secretStore:e,kv:t,site:n,token:r}){return await e.consumeElicitation(t,r)?I(n,u(),200):L(n)}async function j({secretStore:e,kv:t,site:n,token:r},i){let a=await e.consumeElicitation(t,r);if(!a)return L(n);for(let n of i)n.kind===`remove`?await e.deleteSecret(t,a.subject,a.api,n.scheme):await e.setSecret(t,a.subject,a.api,n.scheme,n.secret);let o=await e.getStoredSchemes(t,a.subject,a.api),s={action:i.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:i.map(e=>e.scheme),stored:Object.keys(o).sort()};return I(n,p(a,s),200)}async function M({secretStore:e,kv:t,site:n,token:r,target:i},a,o){let s=await e.getStoredSchemes(t,i.subject,i.api);return I(n,l({site:n,target:i,token:r,stored:s,...a}),o)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${t(e.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
@@ -1,7 +1,7 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as n}from"./subject.js";import{secretStore as r}from"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as o}from"@redocly/mcp";import{CLIENT_CAPABILITIES_META_KEY as s,inputRequired as c,inputResponse as l}from"@modelcontextprotocol/server";const u=`credentials`,d=/* @__PURE__ */ new Map;function f(e,t){let n=d.get(e);if(n)return n;let r=t().finally(()=>{d.delete(e)});return d.set(e,r),r}function p(e){return!!(e.envelope?.[s])?.elicitation?.url}function m(e){return e.envelope!==void 0}function h(e){let t=l(e,u);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function g(e,{url:t,canManageCredentials:n}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...t?[`The credentials page:`,t]:[],``,n?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${o}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
2
- `)}async function _(e,{kv:t,subject:n,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await r.peekElicitation(t,e);if(o?.subject===n&&a.includes(o.api))return{apiName:o.name,url:A(i,e)}}function v(e,t){return Object.keys(e).length>1?t:void 0}async function y(e){let{token:t,url:n}=await w(e);return c({inputRequests:{[u]:c.elicitUrl({message:D(e),url:n})},requestState:t})}async function b(e){let{url:t}=await w(e);return j(e,t,E(e.subject))}function x(e,{schemeLabel:t,canManageCredentials:n}){let r=C(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${r}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
3
- `);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${t?`"${t}" `:``}credential (${r}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...n?[``,...S(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${o}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
4
- `);let i=e.status===401?`The "${e.name}" API rejected the stored ${t?`"${t}" `:``}credential (${r}).`:`The "${e.name}" API rejected the request with ${r}.`;if(!n)return[i,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
5
- `);let a=t?`api: "${e.api}" and scheme: "${t}"`:`api: "${e.api}"`;return[i,``,...S(e),`Do not retry the same call. Call \`${o}\` with ${a} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
6
- `)}function S(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function C({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function w({kv:e,subject:t,baseUrl:n,target:i,auth:a,apiAuth:o}){let s=o?T(o):[],c=await r.createElicitation(e,{subject:t,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:A(n,c)}}function T(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function E(e){return e.startsWith(`anon:`)?e.slice(n.length):void 0}function D({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=O(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${k(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function O({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}function A(n,r){let i=new URL(e(t),n);return i.searchParams.set(`token`,r),i.toString()}function j({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
7
- `)}export{u as CREDENTIALS_INPUT_REQUEST_KEY,_ as acceptedCredentialsLink,g as buildCredentialsAcceptedHint,x as buildCredentialsToolHint,b as buildUpstreamCredentialFallback,y as buildUpstreamCredentialInputRequired,h as credentialElicitationAnswer,f as dedupeElicitation,m as isStatelessRequest,v as schemeLabelOf,p as supportsUrlElicitation};
1
+ import{MANAGE_API_CREDENTIALS_TOOL_NAME as e,MCP_CREDENTIALS_ROUTE as t}from"../../constants.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as o,inputRequired as s,inputResponse as c}from"@modelcontextprotocol/server";const l=`credentials`,u=/* @__PURE__ */ new Map;function d(e,t){let n=u.get(e);if(n)return n;let r=t().finally(()=>{u.delete(e)});return u.set(e,r),r}function f(e){return!!(e.envelope?.[o])?.elicitation?.url}function p(e){return e.envelope!==void 0}function m(e){let t=c(e,l);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function h(t,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${t}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${e}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
2
+ `)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:k(i,e)}}function _(e,t){return Object.keys(e).length>1?t:void 0}async function v(e){let{token:t,url:n}=await C(e);return s({inputRequests:{[l]:s.elicitUrl({message:E(e),url:n})},requestState:t})}async function y(e){let{url:t}=await C(e);return A(e,t,T(e.subject))}function b(t,{schemeLabel:n,canManageCredentials:r}){let i=S(t);if(!t.sentScheme&&(t.status===401||!t.schemes))return[`The "${t.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,t.unsupportedSchemes?`Do not replace them. This operation accepts only ${t.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
3
+ `);if(t.status===403&&t.sentScheme)return[`The "${t.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...x(t),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${e}\` with api: "${t.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
4
+ `);let a=t.status===401?`The "${t.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${t.name}" API rejected the request with ${i}.`;if(!r)return[a,``,t.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
5
+ `);let o=n?`api: "${t.api}" and scheme: "${n}"`:`api: "${t.api}"`;return[a,``,...x(t),`Do not retry the same call. Call \`${e}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
6
+ `)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:k(r,c)}}function w(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function T(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function E({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=D(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${O(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function D({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function O(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(e,r){let i=new URL(n(t),e);return i.searchParams.set(`token`,r),i.toString()}function A({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
7
+ `)}export{l as CREDENTIALS_INPUT_REQUEST_KEY,g as acceptedCredentialsLink,h as buildCredentialsAcceptedHint,b as buildCredentialsToolHint,y as buildUpstreamCredentialFallback,v as buildUpstreamCredentialInputRequired,m as credentialElicitationAnswer,d as dedupeElicitation,p as isStatelessRequest,_ as schemeLabelOf,f as supportsUrlElicitation};
@@ -1 +1 @@
1
- import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as l}from"../api-call-operations.js";import{matchesOrigin as ee}from"./allowed-hosts.js";import{GatewayFetchBlockedError as u,GatewayFetchHostNotAllowedError as d,GatewayFetchSystemError as f,GatewayFetchUserError as p}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as m}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as h}from"undici";const g=`x-forwarded-for`,re=/%2f|%5c/i,_=/* @__PURE__ */ new Set([401,403,407]),ie=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let v;function y(e){if(!v){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),v=new h({connect:{lookup:t({allowLoopback:n})}})}return v}function b({apis:e,onAuthRequired:t,sent:d,runEnded:m,logger:h,telemetry:g,fetchImpl:ie=fetch,dispatcher:v=y(h),timeoutMs:b=3e4,deadline:S=1/0,maxResponseBytes:D=1048576,maxFetchesPerExec:O,beforeSend:_e,caller:k,allowedHttpMethods:A}){let j=e.flatMap(e=>e.matchers),ve=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),M=e.flatMap(e=>Object.values(e.secrets??{})),N=M.flatMap(a),ye=M.map(e=>e.header),P=e.flatMap(e=>e.credentialQueryParams??[]),F=0,I=!1;return async a=>{let y=c(a.method??`GET`),M=Date.now(),L,R,z,B={},V,H,U,W,G=!1;try{if(O!==void 0){let e=Math.max(0,O);if(F+=1,F>e)throw new p(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(A&&!A.includes(y))throw new u(`${y} is not allowed: this project permits only ${A.join(`, `)} API calls`,T(a.url));let o=oe(a.url,j,ve);if(L=o.hostname,R=te(o.pathname),re.test(o.pathname))throw new u(`${y} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>ee(e,o))),f=c.flatMap(e=>e.operations?l(e.operations,o.pathname,y).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),x=Math.min(...f.map(e=>e.variables)),C=f.filter(e=>e.variables===x);if(c.length>0&&(f.length===0||C.some(e=>!e.visible)))throw new u(`${y} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=C.find(e=>!e.callable);if(w)throw new u(`${y} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let E=new Set(C.map(e=>e.api)).size===1?C[0].api:void 0;z=E?.slug;let K=E?.routes?.find(e=>e.method===y&&e.pattern.test(o.pathname));if(K?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${y} ${o.pathname} accepts only ${K.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Call it without securityScheme, and do not replace the stored credentials.`);let be=de(a.securityScheme,E),q=be?[be]:E?K?.schemes??fe(E):void 0,J=E&&q?ue(E,q):void 0,Y=J?E?.secrets?.[J]:void 0;if((y===`GET`||y===`HEAD`)&&a.body!==void 0)throw new p(`A ${y} request cannot have a body; remove \`body\``);B=he({callerHeaders:a.headers,secret:Y,clientIp:k?.clientIp});let xe=pe(a.headers,o,c,Y);if(xe&&(Y||I))throw new p(me(xe,!!Y));if(S-Date.now()<=0)throw new p(`The execute time limit ended before this request was sent`);await _e?.(),I||=!!Y,V=Y?J:void 0;let X=new AbortController,Se=S-Date.now();if(W=Se<b?setTimeout(()=>X.abort(new p(`The request did not finish before the execute time limit`)),Se):setTimeout(()=>{G=!0,X.abort()},b),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);U={method:y,url:i(o.origin+o.pathname,N)},d?.push(U);let Z=await ie(o,{method:y,headers:B,body:a.body,redirect:`manual`,signal:X.signal,dispatcher:v});H=Z.status,U.status=Z.status;let Q=``;try{Q=await le(Z,D)}finally{if(_.has(Z.status)&&E&&t){let e={api:E.slug,name:E.name,status:Z.status};J&&(e.scheme=J),q?.length&&(e.schemes=[...q]),V&&(e.sentScheme=V),K?.unsupportedSchemes&&(e.unsupportedSchemes=[...K.unsupportedSchemes]);let n=ne(Q,Z.headers.get(`content-type`),N);n&&(e.detail=n),t(e)}}let $=r(ge(Z.headers),N);if(se(Z.status)){$=n($,ye);let{location:e}=$;e&&!ce(e,o,j)&&delete $.location}let Ce=ae(Z.status);return g?.gatewayFetchPerformed({host:o.hostname,method:y,outcome:Ce,durationMs:Date.now()-M,path:R,api:z,status:Z.status,bytes:Buffer.byteLength(Q,`utf8`),injectedScheme:V}),s(h,{rawUrl:o.href,method:y,host:o.hostname,outcome:Ce,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:R,api:z,status:Z.status,injectedScheme:V,requestHeaders:B,requestBody:a.body,responseHeaders:$,responseBody:Q,caller:k}),{status:Z.status,statusText:i(Z.statusText,N),ok:Z.ok,headers:$,bodyText:i(Q,N)}}catch(e){let t=U!==void 0&&C(e);t&&U&&d&&d.splice(d.indexOf(U),1);let{outcome:n,userSafe:r}=w(e,H),c=L??(r instanceof u?r.host:void 0)??T(a.url)??`invalid-url`;if(g?.gatewayFetchPerformed({host:c,method:y,outcome:n,durationMs:Date.now()-M,path:R,api:z,status:H,injectedScheme:V}),s(h,{rawUrl:a.url,method:y,host:c,outcome:n,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:R,api:z,status:H,injectedScheme:V,requestHeaders:B,requestBody:a.body,caller:k}),r)throw r;let l=G?{reason:`timeout after ${b} ms`,message:H===void 0?`The API did not answer within ${b/1e3} s`:`The API did not finish its answer within ${b/1e3} s`}:t?{reason:`connect failure ${x(e)??`without a code`}`,message:`Could not connect to ${c}`}:{reason:E(e),message:`Upstream fetch failed due to an internal error`};throw h?.error(`Gateway MCP fetch failed [${y} ${c}]: ${i(l.reason,N)} headers=${o(B)}`),new f(l.message)}finally{W!==void 0&&clearTimeout(W)}}}function x(e){let t=e;for(let e=0;e<5&&t instanceof Error;e++){if(`code`in t&&typeof t.code==`string`)return t.code;if(t instanceof AggregateError)return t.errors.map(x).find(e=>e!==void 0);t=t.cause}}function S(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof p||n instanceof e)return n;n=n.cause}}function C(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;if(n instanceof AggregateError)return n.errors.some(C);let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function ae(e){return _.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function w(t,n){let r=S(t),i=n===void 0?void 0:ae(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof u||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function oe(e,t,n){try{return m(e,t)}catch(e){throw e instanceof d&&n?new u(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function T(e){try{return new URL(e).hostname||void 0}catch{return}}function se(e){return e>=300&&e<400}function ce(e,t,n){try{return!!m(new URL(e,t).href,n)}catch{return!1}}function E(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function le(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw D(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw D(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function D(e,t){return new p(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new p(`securityScheme must be a security scheme name (a string)`);if(!t)throw new p(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new p(`This site cannot send securityScheme "${e}" to ${t.name}; valid values: ${n.join(`, `)}`);return e}function fe(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function pe(e,t,n,r){let i=O([...ie,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=O(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function O(e){return new Set(e.map(e=>e.toLowerCase()))}function me({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function he({callerHeaders:e,secret:t,clientIp:n}){let r={},i=new Headers;for(let[t,n]of Object.entries(e??{})){try{i.append(t,n)}catch{throw new p(`The "${t}" header is invalid: a header name must be a token and a value must hold no line breaks or characters above U+00FF`)}let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==g&&(r[t]=n)}return n&&(r[g]=n),t&&(r[t.header]=t.value),r}function ge(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{b as buildFetchBridge,y as getDefaultAgent,le as readCappedBody};
1
+ import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as l}from"../api-call-operations.js";import{matchesOrigin as ee}from"./allowed-hosts.js";import{GatewayFetchBlockedError as u,GatewayFetchHostNotAllowedError as d,GatewayFetchSystemError as f,GatewayFetchUserError as p}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as m}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as h}from"undici";const g=`x-forwarded-for`,re=/%2f|%5c/i,ie=/* @__PURE__ */ new Set([401,403,407]),ae=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let _;function v(e){if(!_){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),_=new h({connect:{lookup:t({allowLoopback:n})}})}return _}function y({apis:e,onAuthRequired:t,sent:d,runEnded:m,logger:h,telemetry:g,fetchImpl:ae=fetch,dispatcher:_=v(h),timeoutMs:y=3e4,deadline:x=1/0,maxResponseBytes:D=1048576,maxFetchesPerExec:O,beforeSend:be,caller:k,allowedHttpMethods:A}){let j=e.flatMap(e=>e.matchers),xe=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),M=e.flatMap(e=>Object.values(e.secrets??{})),N=M.flatMap(a),Se=M.map(e=>e.header),P=e.flatMap(e=>e.credentialQueryParams??[]),F=0,Ce=!1;return async a=>{let v=c(a.method??`GET`),M=Date.now(),we,I,L,R={},z,B,V,H,Te=!1;try{if(O!==void 0){let e=Math.max(0,O);if(F+=1,F>e)throw new p(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(A&&!A.includes(v))throw new u(`${v} is not allowed: this project permits only ${A.join(`, `)} API calls`,T(a.url));let o=oe(a.url,j,xe);if(we=o.hostname,I=te(o.pathname),re.test(o.pathname))throw new u(`${v} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>ee(e,o))),f=c.flatMap(e=>e.operations?l(e.operations,o.pathname,v).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),b=Math.min(...f.map(e=>e.variables)),S=f.filter(e=>e.variables===b);if(c.length>0&&(f.length===0||S.some(e=>!e.visible)))throw new u(`${v} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=S.find(e=>!e.callable);if(w)throw new u(`${v} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let E=[...new Set(S.map(e=>e.api))];if(E.length>1&&E.some(e=>me(e,v,o.pathname)))throw new u(he(E,`${v} ${o.pathname}`),o.hostname);let U=E.length===1?E[0]:void 0;L=U?.slug;let W=U&&pe(U,v,o.pathname);if(W?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${v} ${o.pathname} accepts only ${W.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Call it without securityScheme, and do not replace the stored credentials.`);let G=de(a.securityScheme,U),K=G?[G]:U?W?.schemes??fe(U):void 0,q=U&&K?ue(U,K):void 0,J=q?U?.secrets?.[q]:void 0;if((v===`GET`||v===`HEAD`)&&a.body!==void 0)throw new p(`A ${v} request cannot have a body; remove \`body\``);R=ve({callerHeaders:a.headers,secret:J,clientIp:k?.clientIp});let Ee=ge(a.headers,o,c,J);if(Ee&&(J||Ce))throw new p(_e(Ee,!!J));if(x-Date.now()<=0)throw new p(`The execute time limit ended before this request was sent`);await be?.(),Ce||=!!J,z=J?q:void 0;let Y=new AbortController,De=x-Date.now();if(H=De<y?setTimeout(()=>Y.abort(new p(`The request did not finish before the execute time limit`)),De):setTimeout(()=>{Te=!0,Y.abort()},y),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);V={method:v,url:i(o.origin+o.pathname,N)},d?.push(V);let X=await ae(o,{method:v,headers:R,body:a.body,redirect:`manual`,signal:Y.signal,dispatcher:_});B=X.status,V.status=X.status;let Z=``;try{Z=await le(X,D)}finally{if(ie.has(X.status)&&U&&t){let e={api:U.slug,name:U.name,status:X.status};q&&(e.scheme=q),K?.length&&(e.schemes=[...K]),z&&(e.sentScheme=z),W?.unsupportedSchemes&&(e.unsupportedSchemes=[...W.unsupportedSchemes]);let n=ne(Z,X.headers.get(`content-type`),N);n&&(e.detail=n),t(e)}}let Q=r(ye(X.headers),N);if(se(X.status)){Q=n(Q,Se);let{location:e}=Q;e&&!ce(e,o,j)&&delete Q.location}let $=C(X.status);return g?.gatewayFetchPerformed({host:o.hostname,method:v,outcome:$,durationMs:Date.now()-M,path:I,api:L,status:X.status,bytes:Buffer.byteLength(Z,`utf8`),injectedScheme:z}),s(h,{rawUrl:o.href,method:v,host:o.hostname,outcome:$,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:I,api:L,status:X.status,injectedScheme:z,requestHeaders:R,requestBody:a.body,responseHeaders:Q,responseBody:Z,caller:k}),{status:X.status,statusText:i(X.statusText,N),ok:X.ok,headers:Q,bodyText:i(Z,N)}}catch(e){let t=V!==void 0&&S(e);t&&V&&d&&d.splice(d.indexOf(V),1);let{outcome:n,userSafe:r}=w(e,B),c=we??(r instanceof u?r.host:void 0)??T(a.url)??`invalid-url`;if(g?.gatewayFetchPerformed({host:c,method:v,outcome:n,durationMs:Date.now()-M,path:I,api:L,status:B,injectedScheme:z}),s(h,{rawUrl:a.url,method:v,host:c,outcome:n,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:I,api:L,status:B,injectedScheme:z,requestHeaders:R,requestBody:a.body,caller:k}),r)throw r;let l=Te?{reason:`timeout after ${y} ms`,message:B===void 0?`The API did not answer within ${y/1e3} s`:`The API did not finish its answer within ${y/1e3} s`}:t?{reason:`connect failure ${b(e)??`without a code`}`,message:`Could not connect to ${c}`}:{reason:E(e),message:`Upstream fetch failed due to an internal error`};throw h?.error(`Gateway MCP fetch failed [${v} ${c}]: ${i(l.reason,N)} headers=${o(R)}`),new f(l.message)}finally{H!==void 0&&clearTimeout(H)}}}function b(e){let t=e;for(let e=0;e<5&&t instanceof Error;e++){if(`code`in t&&typeof t.code==`string`)return t.code;if(t instanceof AggregateError)return t.errors.map(b).find(e=>e!==void 0);t=t.cause}}function x(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof p||n instanceof e)return n;n=n.cause}}function S(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;if(n instanceof AggregateError)return n.errors.some(S);let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function C(e){return ie.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function w(t,n){let r=x(t),i=n===void 0?void 0:C(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof u||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function oe(e,t,n){try{return m(e,t)}catch(e){throw e instanceof d&&n?new u(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function T(e){try{return new URL(e).hostname||void 0}catch{return}}function se(e){return e>=300&&e<400}function ce(e,t,n){try{return!!m(new URL(e,t).href,n)}catch{return!1}}function E(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function le(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw D(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw D(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function D(e,t){return new p(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new p(`securityScheme must be a security scheme name (a string)`);if(!t)throw new p(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new p(`This site cannot send securityScheme "${e}" to ${t.name}; valid values: ${n.join(`, `)}`);return e}function fe(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function pe(e,t,n){return e.routes?.find(e=>e.method===t&&e.pattern.test(n))}function me(e,t,n){return(pe(e,t,n)?.schemes??fe(e)).length>0}function he(e,t){return`${t} is documented by several callable APIs: ${e.map(e=>`"${e.name}" (${e.slug})`).join(`, `)}. This site cannot tell whose stored credential to send, so it does not call the operation. The site owner can keep all but one of these files out of API calls with \`mcp.apiCalls.excludeFiles\`.`}function ge(e,t,n,r){let i=O([...ae,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=O(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function O(e){return new Set(e.map(e=>e.toLowerCase()))}function _e({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function ve({callerHeaders:e,secret:t,clientIp:n}){let r={},i=new Headers;for(let[t,n]of Object.entries(e??{})){try{i.append(t,n)}catch{throw new p(`The "${t}" header is invalid: a header name must be a token and a value must hold no line breaks or characters above U+00FF`)}let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==g&&(r[t]=n)}return n&&(r[g]=n),t&&(r[t.header]=t.value),r}function ye(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{y as buildFetchBridge,v as getDefaultAgent,le as readCappedBody};
@@ -1,5 +1,5 @@
1
- import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{formatError as n}from"../tool-errors.js";import{callAttribution as r}from"../audit.js";import{isToolDisabledByCaller as i}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as a}from"../codemode/constants.js";import{resolveSecretSubject as o}from"./subject.js";import{ipRateLimitKey as s}from"../rate-limit.js";import{callableApis as c,excludedOperations as l}from"./eligibility.js";import{getAllowedHttpMethods as u}from"./allowed-http-methods.js";import{apiCallOperationsOf as d}from"./api-call-operations.js";import{secretStore as f}from"./secret-store.js";import{buildAllowedOriginMatchers as p}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as m}from"./fetch/fetch-errors.js";import{buildFetchBridge as h}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as g,orderedSchemesOf as _,resolveUpstreamApiAuth as v}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as y,buildCredentialsAcceptedHint as b,buildCredentialsToolHint as x,buildUpstreamCredentialFallback as S,buildUpstreamCredentialInputRequired as C,credentialElicitationAnswer as w,dedupeElicitation as T,isStatelessRequest as E,schemeLabelOf as D,supportsUrlElicitation as O}from"./elicitation.js";import{applyFetchCount as k}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as A,upstreamAuthKey as j}from"./upstream-auth.js";import{createAnonymousSessionTool as M,manageApiCredentialsTool as N,removeApiCredentialsTool as P}from"./tools.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as F}from"@redocly/mcp";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[M,N,P]}function R(e){return new Map(e.map(e=>[e.relativePath,v(e)]))}function z(e,t,n,i,a,o,s){return h({apis:t.map(t=>{let r=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:p(t.servers),secrets:i?.[t.relativePath],defaultScheme:r.defaultScheme,routes:r.routes,credentialHeaders:g(r.schemes),credentialQueryParams:r.credentialQueryParams,schemePriority:_(r.schemes),operations:d(t.fullDefinition,t.definition,t.servers,l(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:r(e),allowedHttpMethods:u(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=r(e),i={subject:t,ip:n&&s(n)};return async()=>{let t=await k(e.kv,i,a,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new m(t.message)}}async function V(e,t){if(t)try{return await f.getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${n(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:e,sessionHandle:t,serverContext:n,run:r},a){let s=o(e,t);if(s.kind===`invalid`)return{content:[{type:`text`,text:s.message}],isError:!0};let l=s.kind===`resolved`?s.subject:void 0,[u,d]=await Promise.all([c(e),V(e,l)]),f=R(u),p=[],m=new AbortController,h=await r(z(e,u,f,d,e=>p.push(e),a,m.signal)).finally(()=>m.abort());if(p.length===0)return h;let g=A(p).map(e=>q(e,f));if(s.kind===`anonymous`)return g.some(e=>e.schemes)?K(h,[{type:`text`,text:s.message}]):K(h,[{type:`text`,text:Z(g,{plans:f,canManageCredentials:!1})},...h.content]);let _=E(n.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${_?`2026-07-28`:`2025`} urlElicitation=${O(n.mcpReq)}`);let v={ctx:e,serverContext:n,subject:s.subject,stored:J(d),plans:f,canManageCredentials:!i(F,e.metadata)},y=_?await $(v,g,!a.some(W)):await ee(v,g);switch(y.kind){case`inputRequired`:return y.result;case`prependText`:return K(h,[{type:`text`,text:y.text},...h.content]);case`none`:return h}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(t,n){if(!t.isError||n.length===0)return t;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
1
+ import{MANAGE_API_CREDENTIALS_TOOL_NAME as e}from"../../constants.js";import{isObject as t}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{formatError as r}from"../tool-errors.js";import{callAttribution as i}from"../audit.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as o}from"../codemode/constants.js";import{resolveSecretSubject as s}from"./subject.js";import{ipRateLimitKey as c}from"../rate-limit.js";import{callableApis as l,excludedOperations as u}from"./eligibility.js";import{getAllowedHttpMethods as d}from"./allowed-http-methods.js";import{apiCallOperationsOf as f}from"./api-call-operations.js";import{SecretStore as p}from"./secret-store.js";import{buildAllowedOriginMatchers as m}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as h}from"./fetch/fetch-errors.js";import{buildFetchBridge as g}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as _,orderedSchemesOf as v,resolveUpstreamApiAuth as y}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as b,buildCredentialsAcceptedHint as x,buildCredentialsToolHint as S,buildUpstreamCredentialFallback as C,buildUpstreamCredentialInputRequired as w,credentialElicitationAnswer as T,dedupeElicitation as E,isStatelessRequest as D,schemeLabelOf as O,supportsUrlElicitation as k}from"./elicitation.js";import{applyFetchCount as A}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as j,upstreamAuthKey as M}from"./upstream-auth.js";import{createAnonymousSessionTool as N,manageApiCredentialsTool as P,removeApiCredentialsTool as F}from"./tools.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[N,P,F]}function R(e){return new Map(e.map(e=>[e.relativePath,y(e)]))}function z(e,t,n,r,a,o,s){return g({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:m(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:_(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:v(i.schemes),operations:f(t.fullDefinition,t.definition,t.servers,u(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:i(e),allowedHttpMethods:d(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=i(e),r={subject:t,ip:n&&c(n)};return async()=>{let t=await A(e.kv,r,o,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new h(t.message)}}async function V(e,t){if(t)try{return await new p(e.gatewaySecretSeed).getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${r(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:t,sessionHandle:n,serverContext:r,run:i},o){let c=s(t,n);if(c.kind===`invalid`)return{content:[{type:`text`,text:c.message}],isError:!0};let u=c.kind===`resolved`?c.subject:void 0,[d,f]=await Promise.all([l(t),V(t,u)]),p=R(d),m=[],h=new AbortController,g=await i(z(t,d,p,f,e=>m.push(e),o,h.signal)).finally(()=>h.abort());if(m.length===0)return g;let _=j(m).map(e=>q(e,p));if(c.kind===`anonymous`)return _.some(e=>e.schemes)?K(g,[{type:`text`,text:c.message}]):K(g,[{type:`text`,text:Z(_,{plans:p,canManageCredentials:!1})},...g.content]);let v=D(r.mcpReq);t.logger?.info(`gateway mcp credentials prompt: era=${v?`2026-07-28`:`2025`} urlElicitation=${k(r.mcpReq)}`);let y={ctx:t,serverContext:r,subject:c.subject,stored:J(f),plans:p,canManageCredentials:!a(e,t.metadata)},b=v?await $(y,_,!o.some(W)):await ee(y,_);switch(b.kind){case`inputRequired`:return b.result;case`prependText`:return K(g,[{type:`text`,text:b.text},...g.content]);case`none`:return g}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(e,n){if(!e.isError||n.length===0)return e;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
2
2
  `+r.map(e=>`${e.method} ${e.url} -> ${e.status??`no response`}`).join(`
3
- `);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(j({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(j(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?D(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>x(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
3
+ `);return{...e,content:[...e.content.slice(0,-1),{type:`text`,text:i},...e.content.slice(-1)],structuredContent:{...t(e.structuredContent)?e.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(M({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(M(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?O(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>S(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
4
4
 
5
- `)}function Q({ctx:e,subject:n,plans:r},i){let[a,...o]=i,s=r.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:n,baseUrl:t(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,r),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,n,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=w(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=n.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(n,e)};if(l===`accepted`){let e=await y(a.mcpReq.requestState(),{kv:i.kv,subject:o,baseUrl:t(i.request),apis:u.map(e=>e.api)}),n=e?.apiName??u[0].name;return{kind:`prependText`,text:b(n,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!O(a.mcpReq)?{kind:`prependText`,text:await S(d)}:{kind:`inputRequired`,result:await C(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await T(`${e.subject}:${j(n[0])}`,()=>S(r))}}export{L as gatewayTools,H as runExecuteWithGateway};
5
+ `)}function Q({ctx:e,subject:t,plans:r},i){let[a,...o]=i,s=r.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:t,baseUrl:n(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,r),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,secretStore:new p(e.gatewaySecretSeed),kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,t,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=T(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=t.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(t,e)};if(l===`accepted`){let e=await b(a.mcpReq.requestState(),{secretStore:new p(i.gatewaySecretSeed),kv:i.kv,subject:o,baseUrl:n(i.request),apis:u.map(e=>e.api)}),t=e?.apiName??u[0].name;return{kind:`prependText`,text:x(t,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!k(a.mcpReq)?{kind:`prependText`,text:await C(d)}:{kind:`inputRequired`,result:await w(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await E(`${e.subject}:${M(n[0])}`,()=>C(r))}}export{L as gatewayTools,H as runExecuteWithGateway};
@@ -1 +1 @@
1
- import"../../../../../../server/auth/constants.js";import{secretTtlSeconds as e}from"./subject.js";import{assertHeaderSafe as t}from"./credential-validation.js";import{createCipheriv as n,createDecipheriv as r,createHash as i,hkdfSync as a,randomBytes as o,randomUUID as s}from"node:crypto";const c=15,l=9e5,u=process.env.REALM_AUTH_KEY_SEED||`realm-dev-insecure-auth-seed`;var d=class{#e;constructor(e=u){this.#e=e}async setSecret(n,r,i,a,o){t(o.header,o.value);let s={...o,savedAt:Date.now()},c={api:i,scheme:a,...this.#u(this.#c(r),s,this.#a(i,a))};await n.set(this.#i(r,i,a),c,{ttlInSeconds:e(r)})}async getSecretsForSubject(e,t){return this.#t(e,t,this.#r(t))}async getStoredSchemes(e,t,n){let r=[...this.#r(t),n],i=(await this.#t(e,t,r))[n]??{};return Object.fromEntries(Object.entries(i).map(([e,{savedAt:t}])=>[e,{savedAt:t}]))}async#t(e,t,n){let r=this.#c(t),i=await this.#n(e,n),a={};for(let e of i){if(!e.value?.scheme)continue;let{api:t,scheme:n}=e.value;try{let i=this.#d(r,e.value,this.#a(t,n));a[t]={...a[t],[n]:i}}catch{continue}}return a}async hasSecret(e,t,n,r){return!!await e.get(this.#i(t,n,r))}async deleteSecret(e,t,n,r){await e.delete(this.#i(t,n,r))}async deleteSecrets(e,t,n){let r=n?[...this.#r(t),n]:this.#r(t),i=(await this.#n(e,r)).flatMap(({key:e,value:t})=>t?.scheme?[{key:e,api:t.api,scheme:t.scheme}]:[]);return await Promise.all(i.map(({key:t})=>e.delete(t))),i.map(({api:e,scheme:t})=>({api:e,scheme:t}))}async createElicitation(e,t){let n=s(),r={...t,expiresAt:Date.now()+l};return await e.set(this.#o(n),this.#u(this.#l(),r),{ttlInSeconds:l/1e3}),n}async peekElicitation(e,t){let n=await e.get(this.#o(t));if(n)try{return this.#d(this.#l(),n)}catch{return}}async consumeElicitation(e,t){let n=this.#o(t),r=await e.transaction(async e=>{let t=await e.get(n);return t&&await e.delete(n),t});if(r)try{return this.#d(this.#l(),r)}catch{return}}async#n(e,t){let n=[],r;do{let i=await e.list({prefix:t},{cursor:r});n.push(...i.items),r=i.cursor??void 0}while(r);return n}#r(e){return[`mcp`,`secrets`,this.#s(e)]}#i(e,t,n){return[`mcp`,`secrets`,this.#s(e),t,n]}#a(e,t){return`${e}\x00${t}`}#o(e){return[`mcp`,`elicitation`,e]}#s(e){return i(`sha256`).update(e).digest(`hex`)}#c(e){return Buffer.from(a(`sha256`,this.#e,e,`mcp-upstream-secrets`,32))}#l(){return Buffer.from(a(`sha256`,this.#e,`mcp-elicitation`,`mcp-elicitation`,32))}#u(e,t,r){let i=o(12),a=n(`aes-256-gcm`,e,i);r&&a.setAAD(Buffer.from(r,`utf8`));let s=Buffer.concat([a.update(JSON.stringify(t),`utf8`),a.final()]);return{iv:i.toString(`base64`),tag:a.getAuthTag().toString(`base64`),data:s.toString(`base64`)}}#d(e,t,n){let i=r(`aes-256-gcm`,e,Buffer.from(t.iv,`base64`));n&&i.setAAD(Buffer.from(n,`utf8`)),i.setAuthTag(Buffer.from(t.tag,`base64`));let a=Buffer.concat([i.update(Buffer.from(t.data,`base64`)),i.final()]).toString(`utf8`);return JSON.parse(a)}};const f=new d;export{c as ELICITATION_TTL_MINUTES,l as ELICITATION_TTL_MS,d as SecretStore,f as secretStore};
1
+ import{secretTtlSeconds as e}from"./subject.js";import{assertHeaderSafe as t}from"./credential-validation.js";import{createCipheriv as n,createDecipheriv as r,createHash as i,hkdfSync as a,randomBytes as o,randomUUID as s}from"node:crypto";const c=15,l=9e5;var u=class{#e;constructor(e){this.#e=e}async setSecret(n,r,i,a,o){t(o.header,o.value);let s={...o,savedAt:Date.now()},c={api:i,scheme:a,...this.#d(this.#c(r),s,this.#a(i,a))};await n.set(this.#i(r,i,a),c,{ttlInSeconds:e(r)})}async getSecretsForSubject(e,t){return this.#t(e,t,this.#r(t))}async getStoredSchemes(e,t,n){let r=[...this.#r(t),n],i=(await this.#t(e,t,r))[n]??{};return Object.fromEntries(Object.entries(i).map(([e,{savedAt:t}])=>[e,{savedAt:t}]))}async#t(e,t,n){let r=this.#c(t),i=await this.#n(e,n),a={};for(let e of i){if(!e.value?.scheme)continue;let{api:t,scheme:n}=e.value;try{let i=this.#f(r,e.value,this.#a(t,n));a[t]={...a[t],[n]:i}}catch{continue}}return a}async hasSecret(e,t,n,r){return!!await e.get(this.#i(t,n,r))}async deleteSecret(e,t,n,r){await e.delete(this.#i(t,n,r))}async deleteSecrets(e,t,n){let r=n?[...this.#r(t),n]:this.#r(t),i=(await this.#n(e,r)).flatMap(({key:e,value:t})=>t?.scheme?[{key:e,api:t.api,scheme:t.scheme}]:[]);return await Promise.all(i.map(({key:t})=>e.delete(t))),i.map(({api:e,scheme:t})=>({api:e,scheme:t}))}async createElicitation(e,t){let n=s(),r={...t,expiresAt:Date.now()+l};return await e.set(this.#o(n),this.#d(this.#l(),r),{ttlInSeconds:l/1e3}),n}async peekElicitation(e,t){let n=await e.get(this.#o(t));if(n)try{return this.#f(this.#l(),n)}catch{return}}async consumeElicitation(e,t){let n=this.#o(t),r=await e.transaction(async e=>{let t=await e.get(n);return t&&await e.delete(n),t});if(r)try{return this.#f(this.#l(),r)}catch{return}}async#n(e,t){let n=[],r;do{let i=await e.list({prefix:t},{cursor:r});n.push(...i.items),r=i.cursor??void 0}while(r);return n}#r(e){return[`mcp`,`secrets`,this.#s(e)]}#i(e,t,n){return[`mcp`,`secrets`,this.#s(e),t,n]}#a(e,t){return`${e}\x00${t}`}#o(e){return[`mcp`,`elicitation`,e]}#s(e){return i(`sha256`).update(e).digest(`hex`)}#c(e){return Buffer.from(a(`sha256`,this.#u(),e,`mcp-upstream-secrets`,32))}#l(){return Buffer.from(a(`sha256`,this.#u(),`mcp-elicitation`,`mcp-elicitation`,32))}#u(){if(!this.#e)throw Error(`REALM_AUTH_KEY_SEED is required to store MCP gateway credentials. Set it to a long random string.`);return this.#e}#d(e,t,r){let i=o(12),a=n(`aes-256-gcm`,e,i);r&&a.setAAD(Buffer.from(r,`utf8`));let s=Buffer.concat([a.update(JSON.stringify(t),`utf8`),a.final()]);return{iv:i.toString(`base64`),tag:a.getAuthTag().toString(`base64`),data:s.toString(`base64`)}}#f(e,t,n){let i=r(`aes-256-gcm`,e,Buffer.from(t.iv,`base64`));n&&i.setAAD(Buffer.from(n,`utf8`)),i.setAuthTag(Buffer.from(t.tag,`base64`));let a=Buffer.concat([i.update(Buffer.from(t.data,`base64`)),i.final()]).toString(`utf8`);return JSON.parse(a)}};export{c as ELICITATION_TTL_MINUTES,l as ELICITATION_TTL_MS,u as SecretStore};