@redocly/framework 1.0.0-next.12 → 1.0.0-next.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (244) hide show
  1. package/README.md +0 -1
  2. package/dist/bundler/build/dependency-pack.js +1 -1
  3. package/dist/bundler/build/output-metadata.js +1 -1
  4. package/dist/bundler/build/run.js +1 -1
  5. package/dist/bundler/build/theme-global-stylesheets.js +1 -1
  6. package/dist/bundler/build/vite-config.js +2 -2
  7. package/dist/bundler/dev/dev-content-build.js +1 -1
  8. package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
  9. package/dist/bundler/dev/routes/source-sync-route.js +1 -1
  10. package/dist/bundler/dev/run.js +1 -1
  11. package/dist/bundler/dev/runtime-app.js +1 -1
  12. package/dist/bundler/dev/vite-chunk-url.js +1 -1
  13. package/dist/bundler/user-markdoc-schema.js +1 -1
  14. package/dist/bundler/vite-config.base.js +5 -5
  15. package/dist/cli/api-docs-build-event.js +1 -1
  16. package/dist/cli/args.js +1 -1
  17. package/dist/cli/commands/build.js +1 -1
  18. package/dist/cli/commands/dev.js +1 -1
  19. package/dist/cli/commands/ingest.js +1 -1
  20. package/dist/cli/commands/translate.js +1 -1
  21. package/dist/cli/problems-output.js +3 -3
  22. package/dist/cli/validate-react-pages.js +1 -1
  23. package/dist/client/UnversionedVersionButton.js +1 -1
  24. package/dist/client/VersionPicker.js +343 -0
  25. package/dist/client/ai-search/use-ai-search.js +1 -1
  26. package/dist/client/analytics-page-view.js +1 -1
  27. package/dist/client/app.js +2 -2
  28. package/dist/client/classic-webview-sync.js +1 -1
  29. package/dist/client/client-entry.js +1 -1
  30. package/dist/client/contexts.js +1 -1
  31. package/dist/client/feedback.js +1 -1
  32. package/dist/client/history-mount.js +6 -5
  33. package/dist/client/l10n/ssr-l10n.js +1 -1
  34. package/dist/client/l10n/use-l10n-config.js +1 -1
  35. package/dist/client/products.js +1 -1
  36. package/dist/client/review/ReviewBar.js +31 -31
  37. package/dist/client/review/login-url.js +1 -1
  38. package/dist/client/review/use-review.js +1 -1
  39. package/dist/client/revisions-history.js +1 -1
  40. package/dist/client/sidebar/SidebarDataProvider.js +1 -1
  41. package/dist/client/sidebar/drilldown.js +1 -1
  42. package/dist/client/ssr.js +1 -1
  43. package/dist/client/telemetry/config.js +1 -1
  44. package/dist/client/theme-logo.js +1 -1
  45. package/dist/client/use-entity-revisions.js +1 -1
  46. package/dist/client/use-page-versions.js +1 -1
  47. package/dist/client/use-search.js +1 -1
  48. package/dist/client/webmcp/tools/shared.js +1 -1
  49. package/dist/client/webmcp/tools/site-tools.js +1 -1
  50. package/dist/client/webmcp/use-webmcp-tools.js +1 -1
  51. package/dist/content-layer/config-schema.js +1 -1
  52. package/dist/content-layer/config.d.ts +8 -0
  53. package/dist/content-layer/config.js +1 -1
  54. package/dist/content-layer/context-state.js +1 -1
  55. package/dist/content-layer/context.d.ts +6 -0
  56. package/dist/content-layer/context.js +1 -1
  57. package/dist/content-layer/database/assets.js +1 -1
  58. package/dist/content-layer/database/blobs.js +1 -1
  59. package/dist/content-layer/database/entities.d.ts +2 -0
  60. package/dist/content-layer/database/entities.js +1 -1
  61. package/dist/content-layer/database/entity-store.js +1 -1
  62. package/dist/content-layer/database/files.js +1 -1
  63. package/dist/content-layer/database/finalize.js +1 -1
  64. package/dist/content-layer/database/invalidation.js +26 -26
  65. package/dist/content-layer/database/link-refs.js +1 -1
  66. package/dist/content-layer/database/origins.d.ts +2 -1
  67. package/dist/content-layer/database/origins.js +1 -1
  68. package/dist/content-layer/database/problems.js +1 -1
  69. package/dist/content-layer/database/reset.js +1 -1
  70. package/dist/content-layer/database/route-query-deps.d.ts +19 -3
  71. package/dist/content-layer/database/route-query-deps.js +1 -1
  72. package/dist/content-layer/database/search-vocab.js +2 -2
  73. package/dist/content-layer/database/static-files.js +1 -1
  74. package/dist/content-layer/ingest/extract-all-phase.js +1 -1
  75. package/dist/content-layer/ingest/finalize-phase.js +1 -1
  76. package/dist/content-layer/ingest/git-last-modified.d.ts +20 -0
  77. package/dist/content-layer/ingest/git-last-modified.js +5 -4
  78. package/dist/content-layer/ingest/hash.js +1 -1
  79. package/dist/content-layer/ingest/hook-inputs.js +1 -1
  80. package/dist/content-layer/ingest/l10n-warnings.js +1 -1
  81. package/dist/content-layer/ingest/markdoc-schema-problem.js +1 -1
  82. package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
  83. package/dist/content-layer/ingest/run.js +1 -1
  84. package/dist/content-layer/ingest/scan.js +1 -1
  85. package/dist/content-layer/ingest/search-sync.js +1 -1
  86. package/dist/content-layer/ingest/sync.js +1 -1
  87. package/dist/content-layer/link-checker/config-links.js +1 -1
  88. package/dist/content-layer/link-checker/delta.js +1 -1
  89. package/dist/content-layer/link-checker/fingerprint.js +1 -1
  90. package/dist/content-layer/link-checker/load-view.js +1 -1
  91. package/dist/content-layer/link-checker/node-ref.js +1 -1
  92. package/dist/content-layer/link-checker/run-build.js +1 -1
  93. package/dist/content-layer/link-checker/validate.js +1 -1
  94. package/dist/content-layer/loaders/context.js +1 -1
  95. package/dist/content-layer/markdown/client/JsonSchemaTag.js +1 -1
  96. package/dist/content-layer/markdown/client/markdown-text.js +1 -1
  97. package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
  98. package/dist/content-layer/markdown/nodes/fence.js +1 -1
  99. package/dist/content-layer/markdown/nodes/heading.js +1 -1
  100. package/dist/content-layer/markdown/nodes/table.js +1 -1
  101. package/dist/content-layer/markdown/resolve/ast.d.ts +2 -0
  102. package/dist/content-layer/markdown/resolve/ast.js +1 -1
  103. package/dist/content-layer/markdown/resolve/markdoc-resolvers/file-reference.js +1 -1
  104. package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
  105. package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
  106. package/dist/content-layer/markdown/resolve/markdoc-resolvers/svg-content.js +1 -1
  107. package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
  108. package/dist/content-layer/markdown/resolve/references.js +1 -1
  109. package/dist/content-layer/markdown/search/to-markdown.js +3 -3
  110. package/dist/content-layer/markdown/search/to-sections.js +1 -1
  111. package/dist/content-layer/markdown/search/to-text.js +5 -5
  112. package/dist/content-layer/markdown/server/render.js +1 -1
  113. package/dist/content-layer/markdown/service.js +1 -1
  114. package/dist/content-layer/markdown/tags/variant.js +1 -1
  115. package/dist/content-layer/markdown/utils/collect-anchors.js +1 -1
  116. package/dist/content-layer/markdown/utils/first-heading.js +1 -1
  117. package/dist/content-layer/markdown/utils/parse-cache.d.ts +5 -1
  118. package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
  119. package/dist/content-layer/materialization/asset-reconcile.js +1 -1
  120. package/dist/content-layer/materialization/entity.js +1 -1
  121. package/dist/content-layer/materialization/materializer.js +1 -1
  122. package/dist/content-layer/materialization/static-files.js +1 -1
  123. package/dist/content-layer/plugins/execute.js +1 -1
  124. package/dist/content-layer/plugins/index.js +1 -1
  125. package/dist/content-layer/plugins/internal/api-docs/client/template.js +2 -2
  126. package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
  127. package/dist/content-layer/plugins/internal/api-docs/server/build-definition.d.ts +4 -1
  128. package/dist/content-layer/plugins/internal/api-docs/server/build-definition.js +1 -1
  129. package/dist/content-layer/plugins/internal/api-docs/server/markdown-copy.js +12 -10
  130. package/dist/content-layer/plugins/internal/api-docs/server/options.d.ts +1 -1
  131. package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
  132. package/dist/content-layer/plugins/internal/api-docs/server/search-documents.js +1 -1
  133. package/dist/content-layer/plugins/internal/api-docs/server/spec-download.js +1 -1
  134. package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
  135. package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
  136. package/dist/content-layer/plugins/internal/app-data/logo.js +1 -1
  137. package/dist/content-layer/plugins/internal/app-data/products.js +1 -1
  138. package/dist/content-layer/plugins/internal/assets/index.js +1 -1
  139. package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
  140. package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
  141. package/dist/content-layer/plugins/internal/catalog-classic/resolve-items.js +1 -1
  142. package/dist/content-layer/plugins/internal/index.js +1 -1
  143. package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
  144. package/dist/content-layer/plugins/internal/l10n/translations-loader.js +1 -1
  145. package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
  146. package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
  147. package/dist/content-layer/plugins/internal/mcp/app-data.js +1 -1
  148. package/dist/content-layer/plugins/internal/mcp/constants.d.ts +4 -3
  149. package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
  150. package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
  151. package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
  152. package/dist/content-layer/plugins/internal/mcp/index.js +1 -1
  153. package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
  154. package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
  155. package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
  156. package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
  157. package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
  158. package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
  159. package/dist/content-layer/plugins/internal/mcp/server/config-gate.js +1 -1
  160. package/dist/content-layer/plugins/internal/mcp/server/custom-tools.js +1 -1
  161. package/dist/content-layer/plugins/internal/mcp/server/gateway/call-api.js +2 -2
  162. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-handler.js +1 -1
  163. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js +1 -1
  164. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
  165. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
  166. package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +6 -6
  167. package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
  168. package/dist/content-layer/plugins/internal/mcp/server/gateway/subject.js +1 -1
  169. package/dist/content-layer/plugins/internal/mcp/server/gateway/tool-list.js +1 -1
  170. package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
  171. package/dist/content-layer/plugins/internal/mcp/server/handler.js +1 -1
  172. package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
  173. package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
  174. package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
  175. package/dist/content-layer/plugins/internal/mcp/server/oauth/callback.js +1 -1
  176. package/dist/content-layer/plugins/internal/mcp/server/oauth/client-metadata.js +1 -1
  177. package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
  178. package/dist/content-layer/plugins/internal/mcp/server/oauth/register.js +1 -1
  179. package/dist/content-layer/plugins/internal/mcp/server/oauth/token.js +1 -1
  180. package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
  181. package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
  182. package/dist/content-layer/plugins/internal/mcp/server/skills-resources.js +1 -1
  183. package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
  184. package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +2 -2
  185. package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +1 -1
  186. package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +2 -2
  187. package/dist/content-layer/plugins/internal/mcp/server/workflows/resolve-workflows.js +1 -1
  188. package/dist/content-layer/plugins/internal/mcp/server/workflows/schemas.js +2 -1
  189. package/dist/content-layer/plugins/internal/mcp/server/workflows/tools.js +1 -1
  190. package/dist/content-layer/plugins/internal/mcp/setup-page.js +1 -1
  191. package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
  192. package/dist/content-layer/plugins/internal/react-page/index.js +1 -1
  193. package/dist/content-layer/plugins/internal/scorecard-classic/client/template.js +1 -1
  194. package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
  195. package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
  196. package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
  197. package/dist/content-layer/plugins/internal/skills/index.js +1 -1
  198. package/dist/content-layer/plugins/internal/skills/server/routes.js +1 -1
  199. package/dist/content-layer/plugins/io.js +1 -1
  200. package/dist/content-layer/plugins/project/load.js +2 -2
  201. package/dist/content-layer/plugins/source-file.js +1 -1
  202. package/dist/content-layer/plugins/utils/link-access.js +1 -1
  203. package/dist/content-layer/plugins/utils/route-index.js +1 -1
  204. package/dist/content-layer/revisions/delete.js +1 -1
  205. package/dist/content-layer/revisions/read.js +1 -1
  206. package/dist/content-layer/search/engine/core/search-engine.js +1 -1
  207. package/dist/content-layer/search/postings/postings-store.js +1 -1
  208. package/dist/content-layer/server/database.js +1 -1
  209. package/dist/content-layer/static/registry.js +1 -1
  210. package/dist/content-layer/templates/template-set.js +1 -1
  211. package/dist/content-layer/versions/redirect.js +1 -1
  212. package/dist/content-layer/versions/resolve.js +1 -1
  213. package/dist/server/app.js +3 -3
  214. package/dist/server/ask-ai/feature-gate.js +1 -1
  215. package/dist/server/ask-ai/route.js +1 -1
  216. package/dist/server/auth/middleware.js +1 -1
  217. package/dist/server/auth/request.js +1 -1
  218. package/dist/server/auth/routes.js +1 -1
  219. package/dist/server/content.js +12 -12
  220. package/dist/server/cors-proxy/handler.js +1 -1
  221. package/dist/server/feedback/route.js +1 -1
  222. package/dist/server/lambda-entry.js +1 -1
  223. package/dist/server/manifest-assets.js +4 -4
  224. package/dist/server/node-entry.js +1 -1
  225. package/dist/server/page-handlers.js +2 -2
  226. package/dist/server/plugin-context.js +1 -1
  227. package/dist/server/rbac/content-asset-access.js +1 -1
  228. package/dist/server/runtime-config.js +1 -1
  229. package/dist/server/search/route.js +1 -1
  230. package/dist/server/seo-tags.js +2 -2
  231. package/dist/server/sitemap.js +1 -1
  232. package/dist/server/static-files/serve.js +1 -1
  233. package/dist/server/subprocess/child-entry.js +1 -1
  234. package/dist/server/subprocess/host.js +1 -1
  235. package/dist/server/template-ids.js +1 -1
  236. package/dist/shared/constants/system-routes.js +1 -1
  237. package/dist/shared/rbac/engine.js +0 -0
  238. package/dist/shared/rbac/l10n-rules.js +1 -1
  239. package/dist/shared/rbac/route-scope.js +1 -1
  240. package/dist/shared/rbac/team-templates.js +1 -1
  241. package/dist/shared/types/config.d.ts +2 -1
  242. package/dist/shared/utils/l10n.js +1 -1
  243. package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
  244. package/package.json +4 -5
@@ -1,4 +1,4 @@
1
- import{publicOrigin as e}from"../../../../utils/request-origin.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,MANAGE_API_CREDENTIALS_TOOL_NAME as n,READ_ONLY_ANNOTATIONS as r,REMOVE_API_CREDENTIALS_TOOL_NAME as i}from"../../constants.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{createSessionHandle as o,resolveSecretSubject as s}from"./subject.js";import{toolNameForMode as c}from"../codemode/tool-declarations.js";import{apiTitleKey as l,countApiTitles as u}from"../tools/api-titles.js";import{callableApis as d}from"./eligibility.js";import{SecretStore as f}from"./secret-store.js";import{resolveUpstreamApiAuth as p}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as m,buildCredentialsAcceptedHint as h,buildUpstreamCredentialFallback as g,buildUpstreamCredentialInputRequired as _,credentialElicitationAnswer as v,dedupeElicitation as y,isStatelessRequest as b,schemeLabelOf as x,supportsUrlElicitation as S}from"./elicitation.js";import{upstreamAuthKey as C}from"./upstream-auth.js";async function w(e){return(await d(e)).length>0}const T={schema:{name:t,title:`Create anonymous session`,description:`Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:r,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!a(`createAnonymousSession`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:o()};return{content:[{type:`text`,text:JSON.stringify(e)}],structuredContent:e}}};function E(e,t,n){let r=e.map(e=>e.relativePath),i=[...r,...k(e)],a={type:`string`,description:`${n}: its \`filePath\` or the \`name\` from \`${c(`list-apis`,t)}\`.${r.length>0?` The file paths are: ${r.join(`, `)}.`:``}`,minLength:1};return i.length>0&&(a.enum=i),a}const D={type:`string`,description:`Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.`,minLength:1};function O(e,t,r){return{name:n,title:`Manage API credentials`,description:[r?`Get a secure link where the user sets or replaces the credentials this server sends to a documented API.`:`Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.`,r?`Call it when the user wants to change an API key, or when a tool result tells you the stored credentials were rejected. To remove stored credentials, call \`${i}\` instead.`:`Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.`,`The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.`,`It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument.`].join(`
2
- `),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,t,`The API to manage credentials for`),scheme:{type:`string`,description:`Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.`,minLength:1},sessionHandle:D}}}}function k(e){let t=u(e);return e.map(e=>e.name).filter(e=>t.get(l(e))===1)}function A(e,t){let n=e.find(e=>e.relativePath===t||e.name===t);if(n)return{api:n};let r=e.map(e=>e.relativePath).join(`, `);return{error:N(`Unknown API "${typeof t==`string`?t:``}". Credentials can only be managed for the APIs this server can call: ${r||`none`}.`)}}function j(e,t,n){return N(`Unknown scheme "${e}" for api "${t.relativePath}". The security schemes this server can store credentials for are: ${n.join(`, `)}.`)}async function M(t,n,r){let i=new f(n.gatewaySecretSeed),a=s(n,t.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:o}=a,c=A(await d(n),t.api);if(`error`in c)return c.error;let{api:l}=c,u=e(n.request),w=v(r?.mcpReq.inputResponses);if(w===`accepted`){let e=await m(r?.mcpReq.requestState(),{secretStore:i,kv:n.kv,subject:o,baseUrl:u,apis:[l.relativePath]});return{content:[{type:`text`,text:h(l.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(w===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${l.name}" API, so this call minted no link.`}],isError:!1};let T=p(l),E=typeof t.scheme==`string`?t.scheme:void 0,D=Object.keys(T.schemes);if(E&&!T.schemes[E])return j(E,l,D);let O=E??T.defaultScheme,k={subject:o,baseUrl:u,target:{api:l.relativePath,name:l.name,scheme:O,schemeLabel:E?x(T.schemes,E):void 0},auth:T.schemes[O],apiAuth:T,secretStore:i,kv:n.kv,hasExistingSecret:await i.hasSecret(n.kv,o,l.relativePath,O),reason:{kind:`requested`}};if(r&&b(r.mcpReq)&&S(r.mcpReq))return _(k);let M=C({api:l.relativePath,scheme:O});return{content:[{type:`text`,text:await y(`${o}:${M}`,()=>g(k))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await d(e),e.mcpMode,!a(i,e.metadata)),isAvailable:async e=>!a(`manageApiCredentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n?.serverContext)};function F(e,t,r){return{name:i,title:`Remove API credentials`,description:[`Delete the credentials this server stores for the caller and sends to documented APIs. The user opens no link.`,`Call it only when the user asks to remove, clear, or forget their credentials.${r?` To replace a credential, call \`${n}\` instead.`:``}`,`Pass api to remove the credentials of one API, and add scheme to remove only one of them. To remove the credentials of every API, pass all: true instead of api.`].join(`
3
- `),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,t,`The API to remove credentials for`),scheme:{type:`string`,description:`Name of the security scheme to remove the credential for, as named in the API description. Needs api. Omit it to remove every credential of the API.`,minLength:1},all:{type:`boolean`,description:`Set to true, without api, to remove the credentials of every API. Use it only when the user asks to remove all their credentials.`},sessionHandle:D}}}}async function I(e,t){let n=new f(t.gatewaySecretSeed),r=s(t,e.sessionHandle);if(r.kind!==`resolved`)return N(r.message);let{subject:i}=r,a=await d(t),o=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return o===void 0?e.all===!0?L(await n.deleteSecrets(t.kv,i),a,`No credentials are stored for this caller, so nothing was removed.`):N(`Name the api to remove credentials for. To remove the credentials of every API, pass all: true instead.`):N(`Pass api together with scheme "${o}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let c=A(a,e.api);if(`error`in c)return c.error;let{api:l}=c;if(o===void 0)return L(await n.deleteSecrets(t.kv,i,l.relativePath),a,`No credentials are stored for the "${l.name}" API, so nothing was removed.`);let u=Object.keys(p(l).schemes);if(!u.includes(o))return j(o,l,u);let m=`No credential is stored for the "${o}" scheme of the "${l.name}" API, so nothing was removed.`;return await n.hasSecret(t.kv,i,l.relativePath,o)?(await n.deleteSecret(t.kv,i,l.relativePath,o),L([{api:l.relativePath,scheme:o}],a,m)):L([],a,m)}function L(e,t,n){if(e.length===0)return{content:[{type:`text`,text:n}],isError:!1};let r=/* @__PURE__ */ new Map;for(let{api:t,scheme:n}of e)r.set(t,[...r.get(t)??[],n]);return{content:[{type:`text`,text:[`Removed the stored credentials:`,...[...r].map(([e,n])=>`- "${t.find(t=>t.relativePath===e)?.name??e}" (${e}): ${n.sort().join(`, `)}`),``,`This server no longer sends them. The next call that an API rejects with HTTP 401 asks the user for new credentials.`].join(`
4
- `)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!a(n,e.metadata)),isAvailable:async e=>!a(`removeApiCredentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{D as SESSION_HANDLE_PROPERTY,T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
1
+ import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,MANAGE_API_CREDENTIALS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,REMOVE_API_CREDENTIALS_TOOL_NAME as r}from"../../constants.js";import{publicOrigin as i}from"../../../../utils/request-origin.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{createSessionHandle as o,resolveSecretSubject as s}from"./subject.js";import{toolNameForMode as c}from"../codemode/tool-declarations.js";import{apiTitleKey as l,countApiTitles as u}from"../tools/api-titles.js";import{callableApis as d}from"./eligibility.js";import{SecretStore as f}from"./secret-store.js";import{resolveUpstreamApiAuth as p}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as m,buildCredentialsAcceptedHint as h,buildUpstreamCredentialFallback as g,buildUpstreamCredentialInputRequired as _,credentialElicitationAnswer as v,dedupeElicitation as y,isStatelessRequest as b,schemeLabelOf as x,supportsUrlElicitation as S}from"./elicitation.js";import{upstreamAuthKey as C}from"./upstream-auth.js";async function w(e){return(await d(e)).length>0}const T={schema:{name:e,title:`Create anonymous session`,description:`Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:n,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!a(`create-anonymous-session`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:o()};return{content:[{type:`text`,text:JSON.stringify(e)}],structuredContent:e}}};function E(e,t,n){let r=e.map(e=>e.relativePath),i=[...r,...k(e)],a={type:`string`,description:`${n}: its \`filePath\` or the \`name\` from \`${c(`list-apis`,t)}\`.${r.length>0?` The file paths are: ${r.join(`, `)}.`:``}`,minLength:1};return i.length>0&&(a.enum=i),a}const D={type:`string`,description:"Handle returned by `create-anonymous-session`. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1};function O(e,n,i){return{name:t,title:`Manage API credentials`,description:[i?`Get a secure link where the user sets or replaces the credentials this server sends to a documented API.`:`Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.`,i?`Call it when the user wants to change an API key, or when a tool result tells you the stored credentials were rejected. To remove stored credentials, call \`${r}\` instead.`:`Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.`,`The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.`,`It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument.`].join(`
2
+ `),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,n,`The API to manage credentials for`),scheme:{type:`string`,description:`Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.`,minLength:1},sessionHandle:D}}}}function k(e){let t=u(e);return e.map(e=>e.name).filter(e=>t.get(l(e))===1)}function A(e,t){let n=e.find(e=>e.relativePath===t||e.name===t);if(n)return{api:n};let r=e.map(e=>e.relativePath).join(`, `);return{error:N(`Unknown API "${typeof t==`string`?t:``}". Credentials can only be managed for the APIs this server can call: ${r||`none`}.`)}}function j(e,t,n){return N(`Unknown scheme "${e}" for api "${t.relativePath}". The security schemes this server can store credentials for are: ${n.join(`, `)}.`)}async function M(e,t,n){let r=new f(t.gatewaySecretSeed),a=s(t,e.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:o}=a,c=A(await d(t),e.api);if(`error`in c)return c.error;let{api:l}=c,u=i(t.request),w=v(n?.mcpReq.inputResponses);if(w===`accepted`){let e=await m(n?.mcpReq.requestState(),{secretStore:r,kv:t.kv,subject:o,baseUrl:u,apis:[l.relativePath]});return{content:[{type:`text`,text:h(l.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(w===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${l.name}" API, so this call minted no link.`}],isError:!1};let T=p(l),E=typeof e.scheme==`string`?e.scheme:void 0,D=Object.keys(T.schemes);if(E&&!T.schemes[E])return j(E,l,D);let O=E??T.defaultScheme,k={subject:o,baseUrl:u,target:{api:l.relativePath,name:l.name,scheme:O,schemeLabel:E?x(T.schemes,E):void 0},auth:T.schemes[O],apiAuth:T,secretStore:r,kv:t.kv,hasExistingSecret:await r.hasSecret(t.kv,o,l.relativePath,O),reason:{kind:`requested`}};if(n&&b(n.mcpReq)&&S(n.mcpReq))return _(k);let M=C({api:l.relativePath,scheme:O});return{content:[{type:`text`,text:await y(`${o}:${M}`,()=>g(k))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await d(e),e.mcpMode,!a(r,e.metadata)),isAvailable:async e=>!a(`manage-api-credentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n?.serverContext)};function F(e,n,i){return{name:r,title:`Remove API credentials`,description:[`Delete the credentials this server stores for the caller and sends to documented APIs. The user opens no link.`,`Call it only when the user asks to remove, clear, or forget their credentials.${i?` To replace a credential, call \`${t}\` instead.`:``}`,`Pass api to remove the credentials of one API, and add scheme to remove only one of them. To remove the credentials of every API, pass all: true instead of api.`].join(`
3
+ `),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,n,`The API to remove credentials for`),scheme:{type:`string`,description:`Name of the security scheme to remove the credential for, as named in the API description. Needs api. Omit it to remove every credential of the API.`,minLength:1},all:{type:`boolean`,description:`Set to true, without api, to remove the credentials of every API. Use it only when the user asks to remove all their credentials.`},sessionHandle:D}}}}async function I(e,t){let n=new f(t.gatewaySecretSeed),r=s(t,e.sessionHandle);if(r.kind!==`resolved`)return N(r.message);let{subject:i}=r,a=await d(t),o=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return o===void 0?e.all===!0?L(await n.deleteSecrets(t.kv,i),a,`No credentials are stored for this caller, so nothing was removed.`):N(`Name the api to remove credentials for. To remove the credentials of every API, pass all: true instead.`):N(`Pass api together with scheme "${o}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let c=A(a,e.api);if(`error`in c)return c.error;let{api:l}=c;if(o===void 0)return L(await n.deleteSecrets(t.kv,i,l.relativePath),a,`No credentials are stored for the "${l.name}" API, so nothing was removed.`);let u=Object.keys(p(l).schemes);if(!u.includes(o))return j(o,l,u);let m=`No credential is stored for the "${o}" scheme of the "${l.name}" API, so nothing was removed.`;return await n.hasSecret(t.kv,i,l.relativePath,o)?(await n.deleteSecret(t.kv,i,l.relativePath,o),L([{api:l.relativePath,scheme:o}],a,m)):L([],a,m)}function L(e,t,n){if(e.length===0)return{content:[{type:`text`,text:n}],isError:!1};let r=/* @__PURE__ */ new Map;for(let{api:t,scheme:n}of e)r.set(t,[...r.get(t)??[],n]);return{content:[{type:`text`,text:[`Removed the stored credentials:`,...[...r].map(([e,n])=>`- "${t.find(t=>t.relativePath===e)?.name??e}" (${e}): ${n.sort().join(`, `)}`),``,`This server no longer sends them. The next call that an API rejects with HTTP 401 asks the user for new credentials.`].join(`
4
+ `)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!a(t,e.metadata)),isAvailable:async e=>!a(`remove-api-credentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{D as SESSION_HANDLE_PROPERTY,T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
@@ -1 +1 @@
1
- import{notFoundResponse as e}from"../../../../../server/plugin-context.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{isMcpHidden as n,isPublicEndpointServed as r,resolveMcpAccess as i}from"./config-gate.js";import{AI_METADATA_HEADER as a}from"../constants.js";import{formatError as o,jsonRpcErrorResponse as s}from"./tool-errors.js";import{buildMcpFileTools as c,createCustomTool as l,invokeCustomTool as u}from"./custom-tools.js";import{authorizeMcpRequest as d}from"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p,resolveRequestInstructionsStyle as m,resolveRequestMcpMode as h}from"./mode.js";import{narrowMcpConfigForCaller as g}from"./gateway/caller-api-calls.js";import{isGatewayEnabled as _}from"./gateway/env.js";import{userSubject as v}from"./gateway/subject.js";import{parseUserAgent as y}from"./mcp-client.js";import{createMcpTelemetry as b}from"./mcp-telemetry.js";import{applyMcpRateLimit as x}from"./rate-limit.js";import{createToolRegistry as S}from"./tool-registry.js";import{mcpToolRegistry as C}from"./registry-instance.js";const w=`POST`;function T(e){return(e??``).split(`,`).some(e=>{let[t,...n]=e.split(`;`).map(e=>e.trim().toLowerCase());if(t!==`text/html`)return!1;let r=n.find(e=>e.startsWith(`q=`));return r===void 0||Number(r.slice(2))>0})}function E(){return s(405,`Method not allowed`,{Allow:w})}function D(e){let t={error:`Method Not Allowed`,message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${e}`};return new Response(JSON.stringify(t),{status:405,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,Allow:w}})}function O(){return s(501,`MCP transport is not available in this environment`)}function k(e){if(!e)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function A(e,t,n,r){let i=k(e.headers.get(a)),{userAgent:o}=t.request,{client:s,clientVersion:c}=y(o),l=h(e.url,p()),u=crypto.randomUUID(),d=v(t.request.viewer),f=t.request.ip??void 0;return{config:{...t.config,mcp:g(t.config.mcp,i)},entities:t.entities,hasRoute:e=>t.hasRoute(e),isSlugVisible:(e,n)=>t.isSlugVisible(e,n),kv:t.kv,gatewaySecretSeed:t.gatewaySecretSeed,logger:t.logger,pageMarkdown:t.pageMarkdown,search:t.search,request:t.request,metadata:i,mcpMode:l,instructionsStyle:m(e.url),requestId:u,executeDeadline:r,messageId:typeof i.messageId==`string`?i.messageId:void 0,callerSubject:d,client:s,clientVersion:c,accessToken:n.accessToken,isProtected:n.isProtected??!1,isAvailableMemo:/* @__PURE__ */ new Map,subprocess:t.subprocess,claims:n.claims,telemetry:b({userAgent:o,request:e,metadata:i,mode:l,requestId:u,callerSubject:d,clientIp:f,logger:t.logger})}}async function j(e){let t=_(e.config)?(await import(`./gateway/tool-list.js`)).gatewayTools():[],n=e.subprocess?e.mcpToolEntries??[]:[],r=C.list(),i=/* @__PURE__ */ new Set([...r.map(e=>e.schema.name),...t.map(e=>e.schema.name),...n.map(e=>e.declaration.name)]),a=e.subprocess?await c({entities:e.entities,loadContentModule:e.loadContentModule,reservedNames:i,logger:e.logger}):[];if(t.length===0&&n.length===0&&a.length===0)return C;let o=S();for(let e of r)o.register(e);for(let e of t)o.register(e);for(let e of n)o.register(l(e));for(let e of a)o.register(e);return o}async function M(e,t,n,r={}){let i=await j(e),a;try{a=await import(`./mcp-server.js`)}catch(t){return e.logger?.error(`MCP transport failed to load: ${o(t)}`),async()=>O()}let s;return a.createMcpRequestHandler({registry:i,logger:e.logger,buildToolContext:r=>s??=A(r,e,t,n),onError:r.onError})}function N(a={}){return async(o,s,c)=>{let l=Date.now()+f;if(n(c.config)||a.publicEndpoint&&!r(c.config,i(c.config)))return e();if(o.req.method===`GET`&&T(o.req.header(`accept`)))return s();let u=await x({kv:c.kv,ip:c.request.ip,bucket:`mcp`,logger:c.logger});if(u)return u;let p=await d({c:o,ctx:c,forceAnonymous:a.forceAnonymous});return p.kind===`deny`?p.response:o.req.method===`GET`?D(`${t(c.request)}${new URL(c.request.url).pathname}`):o.req.method===`POST`?(await M(p.ctx,{isProtected:p.isProtected,accessToken:p.accessToken,claims:p.claims},l))(o.req.raw):E()}}const P=N(),F=N({forceAnonymous:!0,publicEndpoint:!0});export{A as buildToolContext,N as createMcpHandler,M as createServedMcpRequestHandler,u as invokeCustomTool,P as mcp,F as mcpPublic};
1
+ import{AI_METADATA_HEADER as e}from"../constants.js";import{isMcpHidden as t,isPublicEndpointServed as n,resolveMcpAccess as r}from"./config-gate.js";import{publicOrigin as i}from"../../../utils/request-origin.js";import{formatError as a,jsonRpcErrorResponse as o}from"./tool-errors.js";import{buildMcpFileTools as s,createCustomTool as c,invokeCustomTool as l}from"./custom-tools.js";import{notFoundResponse as u}from"../../../../../server/plugin-context.js";import{authorizeMcpRequest as d}from"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p,resolveRequestInstructionsStyle as m,resolveRequestMcpMode as h}from"./mode.js";import{narrowMcpConfigForCaller as g}from"./gateway/caller-api-calls.js";import{isGatewayEnabled as _}from"./gateway/env.js";import{userSubject as v}from"./gateway/subject.js";import{parseUserAgent as y}from"./mcp-client.js";import{createMcpTelemetry as b}from"./mcp-telemetry.js";import{applyMcpRateLimit as x}from"./rate-limit.js";import{createToolRegistry as S}from"./tool-registry.js";import{mcpToolRegistry as C}from"./registry-instance.js";const w=`POST`;function T(e){return(e??``).split(`,`).some(e=>{let[t,...n]=e.split(`;`).map(e=>e.trim().toLowerCase());if(t!==`text/html`)return!1;let r=n.find(e=>e.startsWith(`q=`));return r===void 0||Number(r.slice(2))>0})}function E(){return o(405,`Method not allowed`,{Allow:w})}function D(e){let t={error:`Method Not Allowed`,message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${e}`};return new Response(JSON.stringify(t),{status:405,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,Allow:w}})}function O(){return o(501,`MCP transport is not available in this environment`)}function k(e){if(!e)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function A(t,n,r,i){let a=k(t.headers.get(e)),{userAgent:o}=n.request,{client:s,clientVersion:c}=y(o),l=h(t.url,p()),u=crypto.randomUUID(),d=v(n.request.viewer),f=n.request.ip??void 0;return{config:{...n.config,mcp:g(n.config.mcp,a)},entities:n.entities,hasRoute:e=>n.hasRoute(e),isSlugVisible:(e,t)=>n.isSlugVisible(e,t),kv:n.kv,gatewaySecretSeed:n.gatewaySecretSeed,logger:n.logger,pageMarkdown:n.pageMarkdown,search:n.search,request:n.request,metadata:a,mcpMode:l,instructionsStyle:m(t.url),requestId:u,executeDeadline:i,messageId:typeof a.messageId==`string`?a.messageId:void 0,callerSubject:d,client:s,clientVersion:c,accessToken:r.accessToken,isProtected:r.isProtected??!1,isAvailableMemo:/* @__PURE__ */ new Map,subprocess:n.subprocess,claims:r.claims,telemetry:b({userAgent:o,request:t,metadata:a,mode:l,requestId:u,callerSubject:d,clientIp:f,logger:n.logger})}}async function j(e){let t=_(e.config)?(await import(`./gateway/tool-list.js`)).gatewayTools():[],n=e.subprocess?e.mcpToolEntries??[]:[],r=C.list(),i=/* @__PURE__ */ new Set([...r.map(e=>e.schema.name),...t.map(e=>e.schema.name),...n.map(e=>e.declaration.name)]),a=e.subprocess?await s({entities:e.entities,loadContentModule:e.loadContentModule,reservedNames:i,logger:e.logger}):[];if(t.length===0&&n.length===0&&a.length===0)return C;let o=S();for(let e of r)o.register(e);for(let e of t)o.register(e);for(let e of n)o.register(c(e));for(let e of a)o.register(e);return o}async function M(e,t,n,r={}){let i=await j(e),o;try{o=await import(`./mcp-server.js`)}catch(t){return e.logger?.error(`MCP transport failed to load: ${a(t)}`),async()=>O()}let s;return o.createMcpRequestHandler({registry:i,logger:e.logger,buildToolContext:r=>s??=A(r,e,t,n),onError:r.onError})}function N(e={}){return async(a,o,s)=>{let c=Date.now()+f;if(t(s.config)||e.publicEndpoint&&!n(s.config,r(s.config)))return u();if(a.req.method===`GET`&&T(a.req.header(`accept`)))return o();let l=await x({kv:s.kv,ip:s.request.ip,bucket:`mcp`,logger:s.logger});if(l)return l;let p=await d({c:a,ctx:s,forceAnonymous:e.forceAnonymous});return p.kind===`deny`?p.response:a.req.method===`GET`?D(`${i(s.request)}${new URL(s.request.url).pathname}`):a.req.method===`POST`?(await M(p.ctx,{isProtected:p.isProtected,accessToken:p.accessToken,claims:p.claims},c))(a.req.raw):E()}}const P=N(),F=N({forceAnonymous:!0,publicEndpoint:!0});export{A as buildToolContext,N as createMcpHandler,M as createServedMcpRequestHandler,l as invokeCustomTool,P as mcp,F as mcpPublic};
@@ -1 +1 @@
1
- import{isObject as e}from"../../../../../shared/utils/is-object.js";import{CALL_API_WRITE_TOOL_NAME as t,CREATE_ANONYMOUS_SESSION_TOOL_NAME as n,DISCOVER_TOOL_NAME as r,EXECUTE_TOOL_NAME as i,LIST_WORKFLOWS_TOOL_NAME as a}from"../constants.js";import{formatError as o}from"./tool-errors.js";import{auditToolCall as s,callAttribution as c}from"./audit.js";import{CODE_MODE_TOOL_NAMES as l,FETCH_TOOL_NAME as u}from"./codemode/constants.js";import{resolveMcpMode as d,resolveRequestMcpMode as f}from"./mode.js";import{sendMcpRequestError as p}from"./mcp-telemetry.js";import{availableTools as m,isToolAvailable as h,normalizeToolDisplayName as g}from"./tool-registry.js";import{mcpJsonSchemaValidator as _}from"./json-schema-validator.js";import{toToolListEntries as v}from"./codemode/tool-list.js";import{buildCodeModeInstructions as y,buildExecuteDescription as b,buildToolsModeInstructions as x}from"./codemode/prompts.js";import{composeExecuteAnnotations as S,getActiveCapabilities as C}from"./codemode/capabilities.js";import{discover as w,discoverSchema as T}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as E,executeOutputSchema as D,executeToolTitle as O}from"./codemode/execute-schema.js";import{runCodeMode as k}from"./codemode/index.js";import{docsServerInfo as A}from"./server-info.js";import{loadSkillResources as j}from"./skills-resources.js";import{randomUUID as M}from"node:crypto";import{McpServer as N,createMcpHandler as P,fromJsonSchema as F,isCallToolResult as I,isInputRequiredResult as L}from"@modelcontextprotocol/server";const R=`text/markdown`,z={listChanged:!1};function B(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a,_meta:o}=g(e);return{title:t,description:n,inputSchema:F(r,_),outputSchema:i?F(i,_):void 0,annotations:a,_meta:o}}function V(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function H(t,n){if(I(t)||L(t))return t;let r=[{type:`text`,text:typeof t==`string`?t:JSON.stringify(t)}];return n===`code`&&e(t)?{content:r,structuredContent:t}:{content:r}}function U(e,t){return(n,r)=>s(e,t.schema.name,n,async()=>H(await t.execute(n,e,{serverContext:r}),e.mcpMode))}function W(e,t){return new N(e,{capabilities:{logging:{},tools:z},maxToolInputElements:1e4,instructions:t})}async function G(e,o,c){let[d,f]=await Promise.all([m(c,o),C(o)]),p=f.some(e=>e.id===u),g=d.some(({schema:e})=>e.name===t),_=d.some(({schema:e})=>e.name===a),x=d.filter(e=>!l.has(e.schema.name)).map(e=>e.schema),A=d.filter(({schema:e})=>l.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),j=o.instructionsStyle!==`brief`,M=j?v(x,f):[],N=A.some(e=>e.schema.name===n),P=W(e,y({hasFetch:p,toolList:M,docsUrl:e.websiteUrl,hasCallApiWrite:g,hasWorkflows:_})),F=S(x,f);P.registerTool(i,B({...V(N,E),title:O(F),description:b(p,M,e.websiteUrl),outputSchema:D(p),annotations:F}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,r=t=>s(o,i,e,()=>k({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:c,ctx:o,hostFetch:t}));if(!p)return r();let{runExecuteWithGateway:a}=await import(`./gateway/index.js`);return a({ctx:o,sessionHandle:n,serverContext:t,run:r})});let I=w(x,async e=>{let t=c.get(e);return t!==void 0&&await h(t,o)},f,o);P.registerTool(r,B(T(x,f,j)),e=>s(o,r,e,()=>I(e)));for(let e of A)P.registerTool(e.schema.name,B(V(N,e.schema)),U(o,e));return P}async function K(e,t,n){let r=new Map((await m(n,t)).map(e=>[e.schema.name,e])),i=W(e,x(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,B({...n.schema,outputSchema:void 0}),U(t,n));r.has(n.schema.name)||a.disable()}return i}async function q(e,t,n){let r=A(e.config,e.request),i=e.mcpMode===`code`?await G(r,e,t):await K(r,e,t);n.length>0&&i.server.registerCapabilities({resources:z});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:R},async()=>({contents:[{uri:e.uri,mimeType:R,text:await e.read()}]}));return i}function J(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function Y(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function X(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await j(n),i=await q(n,e.registry,r),a=P(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),J(o)}catch(r){if(e.onError)await e.onError(r);else{let i=n?c(n):{requestId:M()};e.logger?.error(`MCP request failed: ${o(r)}`,{request_id:i.requestId}),p(r,f(t.url,d()),{logger:e.logger,caller:i})}return Y()}}}export{X as createMcpRequestHandler,B as toRegisterToolConfig};
1
+ import{CALL_API_WRITE_TOOL_NAME as e,CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r,LIST_WORKFLOWS_TOOL_NAME as i,RUN_WORKFLOW_WRITE_TOOL_NAME as a}from"../constants.js";import{isObject as o}from"../../../../../shared/utils/is-object.js";import{formatError as s}from"./tool-errors.js";import{auditToolCall as c,callAttribution as l}from"./audit.js";import{CODE_MODE_TOOL_NAMES as u,FETCH_TOOL_NAME as d}from"./codemode/constants.js";import{resolveMcpMode as f,resolveRequestMcpMode as p}from"./mode.js";import{sendMcpRequestError as m}from"./mcp-telemetry.js";import{availableTools as h,isToolAvailable as g,normalizeToolDisplayName as _}from"./tool-registry.js";import{mcpJsonSchemaValidator as v}from"./json-schema-validator.js";import{toToolListEntries as y}from"./codemode/tool-list.js";import{buildCodeModeInstructions as b,buildExecuteDescription as x,buildToolsModeInstructions as S}from"./codemode/prompts.js";import{composeExecuteAnnotations as C,getActiveCapabilities as w}from"./codemode/capabilities.js";import{discover as T,discoverSchema as E}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as D,executeOutputSchema as O,executeToolTitle as k}from"./codemode/execute-schema.js";import{runCodeMode as A}from"./codemode/index.js";import{docsServerInfo as j}from"./server-info.js";import{loadSkillResources as M}from"./skills-resources.js";import{randomUUID as N}from"node:crypto";import{McpServer as P,createMcpHandler as F,fromJsonSchema as I,isCallToolResult as L,isInputRequiredResult as R}from"@modelcontextprotocol/server";const z=`text/markdown`,B={listChanged:!1};function V(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a,_meta:o}=_(e);return{title:t,description:n,inputSchema:I(r,v),outputSchema:i?I(i,v):void 0,annotations:a,_meta:o}}function H(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function U(e,t){if(L(e)||R(e))return e;let n=[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e)}];return t===`code`&&o(e)?{content:n,structuredContent:e}:{content:n}}function W(e,t){return(n,r)=>c(e,t.schema.name,n,async()=>U(await t.execute(n,e,{serverContext:r}),e.mcpMode))}function G(e,t){return new P(e,{capabilities:{logging:{},tools:B},maxToolInputElements:1e4,instructions:t})}async function K(o,s,l){let[f,p]=await Promise.all([h(l,s),w(s)]),m=p.some(e=>e.id===d),_=f.some(({schema:t})=>t.name===e),v=f.some(({schema:e})=>e.name===i),S=f.some(({schema:e})=>e.name===a),j=f.filter(e=>!u.has(e.schema.name)).map(e=>e.schema),M=f.filter(({schema:e})=>u.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),N=s.instructionsStyle!==`brief`,P=N?y(j,p):[],F=M.some(e=>e.schema.name===t),I=G(o,b({hasFetch:m,toolList:P,docsUrl:o.websiteUrl,hasCallApiWrite:_,hasWorkflows:v,hasRunWorkflowWrite:S})),L=C(j,p);I.registerTool(r,V({...H(F,D),title:k(L),description:x(m,P,o.websiteUrl),outputSchema:O(m),annotations:L}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,i=t=>c(s,r,e,()=>A({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:l,ctx:s,hostFetch:t}));if(!m)return i();let{runExecuteWithGateway:a}=await import(`./gateway/index.js`);return a({ctx:s,sessionHandle:n,serverContext:t,run:i})});let R=T(j,async e=>{let t=l.get(e);return t!==void 0&&await g(t,s)},p,s);I.registerTool(n,V(E(j,p,N)),e=>c(s,n,e,()=>R(e)));for(let e of M)I.registerTool(e.schema.name,V(H(F,e.schema)),W(s,e));return I}async function q(e,t,n){let r=new Map((await h(n,t)).map(e=>[e.schema.name,e])),i=G(e,S(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,V({...n.schema,outputSchema:void 0}),W(t,n));r.has(n.schema.name)||a.disable()}return i}async function J(e,t,n){let r=j(e.config,e.request),i=e.mcpMode===`code`?await K(r,e,t):await q(r,e,t);n.length>0&&i.server.registerCapabilities({resources:B});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:z},async()=>({contents:[{uri:e.uri,mimeType:z,text:await e.read()}]}));return i}function Y(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function X(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function Z(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await M(n),i=await J(n,e.registry,r),a=F(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),Y(o)}catch(r){if(e.onError)await e.onError(r);else{let i=n?l(n):{requestId:N()};e.logger?.error(`MCP request failed: ${s(r)}`,{request_id:i.requestId}),m(r,p(t.url,f()),{logger:e.logger,caller:i})}return X()}}}export{Z as createMcpRequestHandler,V as toRegisterToolConfig};
@@ -1 +1 @@
1
- import{errorMessage as e}from"../../../../../shared/utils/error-message.js";import{isServerTelemetryEnabled as t}from"../../../../../server/telemetry/collector.js";import{sendServerEvent as n,sendServerEvents as r}from"../../../../../server/telemetry/sender.js";import"../constants.js";import{innerToolErrorClass as i,thrownErrorClass as a}from"./tool-errors.js";import{auditCode as o,auditInput as s,auditSha256 as c,auditStack as l,isCallToolResult as u,toolOutputText as d,toolResultText as f}from"./audit.js";import{SANDBOX_FAILURE as p}from"./codemode/constants.js";import{parseUserAgent as m,readListingSource as h}from"./mcp-client.js";import{randomUUID as g}from"node:crypto";import{ulid as _}from"ulid";const v={id:`docs`,object:`mcpServer`,uri:`urn:redocly:realm:mcp:server:docs`};function y(e){if(e===void 0)return;let t=c(e);return{id:t,object:`user`,uri:`urn:redocly:realm:mcp:subject:${t}`}}function b(n){let{mode:c,requestId:g,callerSubject:_,clientIp:b,logger:x}=n,S=n.env??process.env,C=t(S),w=y(_),{client:T,clientVersion:E}=m(n.userAgent),D=n.metadata.messageId,O={client:T,client_version:E,message_id:typeof D==`string`?D:void 0,listing_source:h(n.request)},j=[],M=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new WeakSet,P=(e,t)=>{j.push({type:e,data:[t],requestId:g,time:/* @__PURE__ */ new Date,actor:w,clientIp:b})},F=t=>{try{t()}catch(t){x?.warn(`MCP telemetry failed: ${e(t)}`)}},I=(e,t,n)=>P(`com.redocly.mcpServer.toolCalled`,{...v,tool:e,mode:c,output_length:n,duration_ms:t,...O}),L=(e,t,n)=>{n.stack&&x?.error(`MCP tool ${e} failed (${n.error_class})`,{request_id:g,stack:n.stack}),P(`com.redocly.mcpServer.error`,{...v,tool:e,mode:c,duration_ms:t,message:s(n.message),stack:l(n.stack),error_class:n.error_class,...O})},R=async(t,n,r)=>{let a=Date.now(),o;try{o=await n()}catch(n){let o=i(n),s=o===`server_error`;throw r.set(e(n),{tool:t,reason:s?`server_error`:`inner_tool_error`}),F(()=>L(t,Date.now()-a,{message:e(n),stack:s&&n instanceof Error?n.stack??``:``,error_class:o})),n}return F(()=>I(t,Date.now()-a,d(o).length)),o};return{toolReturned(e,t,n){F(()=>{if(!u(n)||n.isError!==!0){I(e,t,d(n).length);return}N.has(n)||L(e,t,{message:f(n,` `),stack:``,error_class:e===`execute`?`sandbox_error`:`tool_error`})})},toolThrew(t,n,r){F(()=>{let i=a(r);L(t,n,{message:e(r),stack:i===`server_error`&&r instanceof Error?r.stack??``:``,error_class:i})})},trackCodeExecution(t,n){let r=Date.now(),i=o(t),a=/* @__PURE__ */ new Map,s=0;return{hostFetch:n&&(t=>(s+=1,n(t).catch(t=>{throw a.set(e(t),{reason:`runtime_error`}),t}))),innerToolCall(e,t){let n=R(e,t,a),r=n.then(()=>void 0,()=>void 0);return M.add(r),r.then(()=>M.delete(r)),n},finish(e,t,n){let o=e.failure===p.HostError&&e.error!==void 0?a.get(e.error):void 0;o?.tool&&N.add(t);let c=e.error===void 0?`ok`:`error`,l=Date.now()-r,u=k(e.failure,o,n),d=o?.tool;F(()=>P(`com.redocly.mcpServer.codeExecuted`,{...v,code_sha256:i.sha256,code_length:i.length,fetch_count:s,outcome:c,flags:i.flags,duration_ms:l,failure_reason:u,failed_tool:d,...O})),x?.info(`Gateway MCP code executed [${i.sha256.slice(0,12)}] outcome=${c} codeLength=${i.length} fetchCount=${s}`+(i.flags?` flags=${i.flags}`:``)+` durationMs=${l}`+(u?` failureReason=${u}`:``)+(d?` failedTool=${d}`:``))}}},gatewayFetchPerformed({host:e,method:t,outcome:n,durationMs:r,path:i,api:a,status:o,bytes:s,injectedScheme:c}){F(()=>P(`com.redocly.mcpServer.gatewayFetchPerformed`,{...v,host:e,method:t,outcome:n,path:i,api:a,status:o,injected_scheme:c,bytes:s,duration_ms:r})),x?.info(`Gateway MCP fetch [${t} ${e}] outcome=${n}`+(i===void 0?``:` path=${i}`)+(a===void 0?``:` api=${a}`)+(o===void 0?``:` status=${o}`)+(c===void 0?``:` injectedScheme=${c}`)+(s===void 0?``:` bytes=${s}`)+` durationMs=${r}`)},gatewayFetchRateLimited({scope:e,limit:t,retryAfterSeconds:n}){F(()=>P(`com.redocly.mcpServer.gatewayFetchRateLimited`,{...v,scope:e,retry_after_seconds:n,limit:t}))},async flush(){if(!C){j=[];return}await A(M,300);let e=j;j=[],await r(e,{env:S,fetcher:n.fetcher,logger:x})}}}function x(e,t){let{requestId:r=g(),callerSubject:i,clientIp:a}=t.caller??{};return n({...e,requestId:r,actor:y(i),clientIp:a},t)}function S(e,t,n={}){return x({type:`com.redocly.mcpServer.error`,data:[{...v,message:s(e instanceof Error?e.message:``),stack:l(e instanceof Error?e.stack??``:``),error_class:`server_error`,mode:t}]},n)}function C({scope:e,retryAfterSeconds:t,limit:n},r={}){return x({type:`com.redocly.mcpServer.rateLimited`,data:[{...v,scope:e,retry_after_seconds:t,limit:n}]},r)}function w(e){let t=e||_(),n=t.startsWith(`mcp_`)?t:`mcp_${t}`;return{id:n,object:`mcpSession`,uri:`urn:redocly:realm:mcp:session:${n}`}}function T(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.started`,data:[{...w(e),redirect_uri:t}]},n)}function E(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.completed`,data:[{...w(e),redirect_uri:t}]},n)}function D(e,t,n,r,i={}){return x({type:`com.redocly.mcpServerAuthorization.failed`,data:[{...w(e),error:n,error_details:r,error_class:t}]},i)}function O(e,t={}){return x({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`,...e},signal:`trace`},t)}function k(e,t,n){return e===p.HostError?t?.reason??p.RuntimeError:e===p.RuntimeError&&n!==void 0?`unknown_tool`:e}async function A(e,t){if(e.size===0)return;let n;await Promise.race([Promise.allSettled(e),new Promise(e=>{n=setTimeout(e,t)})]),clearTimeout(n)}export{b as createMcpTelemetry,E as sendMcpAuthorizationCompleted,D as sendMcpAuthorizationFailed,T as sendMcpAuthorizationStarted,C as sendMcpRateLimited,S as sendMcpRequestError,O as sendMcpServerCardServed};
1
+ import"../constants.js";import{errorMessage as e}from"../../../../../shared/utils/error-message.js";import{innerToolErrorClass as t,thrownErrorClass as n}from"./tool-errors.js";import{isServerTelemetryEnabled as r}from"../../../../../server/telemetry/collector.js";import{sendServerEvent as i,sendServerEvents as a}from"../../../../../server/telemetry/sender.js";import{auditCode as o,auditInput as s,auditSha256 as c,auditStack as l,isCallToolResult as u,toolOutputText as d,toolResultText as f}from"./audit.js";import{SANDBOX_FAILURE as p}from"./codemode/constants.js";import{parseUserAgent as m,readListingSource as h}from"./mcp-client.js";import{randomUUID as g}from"node:crypto";import{ulid as _}from"ulid";const v={id:`docs`,object:`mcpServer`,uri:`urn:redocly:realm:mcp:server:docs`};function y(e){if(e===void 0)return;let t=c(e);return{id:t,object:`user`,uri:`urn:redocly:realm:mcp:subject:${t}`}}function b(i){let{mode:c,requestId:g,callerSubject:_,clientIp:b,logger:x}=i,S=i.env??process.env,C=r(S),w=y(_),{client:T,clientVersion:E}=m(i.userAgent),D=i.metadata.messageId,O={client:T,client_version:E,message_id:typeof D==`string`?D:void 0,listing_source:h(i.request)},j=[],M=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new WeakSet,P=(e,t)=>{j.push({type:e,data:[t],requestId:g,time:/* @__PURE__ */ new Date,actor:w,clientIp:b})},F=t=>{try{t()}catch(t){x?.warn(`MCP telemetry failed: ${e(t)}`)}},I=(e,t,n)=>P(`com.redocly.mcpServer.toolCalled`,{...v,tool:e,mode:c,output_length:n,duration_ms:t,...O}),L=(e,t,n)=>{n.stack&&x?.error(`MCP tool ${e} failed (${n.error_class})`,{request_id:g,stack:n.stack}),P(`com.redocly.mcpServer.error`,{...v,tool:e,mode:c,duration_ms:t,message:s(n.message),stack:l(n.stack),error_class:n.error_class,...O})},R=async(n,r,i)=>{let a=Date.now(),o;try{o=await r()}catch(r){let o=t(r),s=o===`server_error`;throw i.set(e(r),{tool:n,reason:s?`server_error`:`inner_tool_error`}),F(()=>L(n,Date.now()-a,{message:e(r),stack:s&&r instanceof Error?r.stack??``:``,error_class:o})),r}return F(()=>I(n,Date.now()-a,d(o).length)),o};return{toolReturned(e,t,n){F(()=>{if(!u(n)||n.isError!==!0){I(e,t,d(n).length);return}N.has(n)||L(e,t,{message:f(n,` `),stack:``,error_class:e===`execute`?`sandbox_error`:`tool_error`})})},toolThrew(t,r,i){F(()=>{let a=n(i);L(t,r,{message:e(i),stack:a===`server_error`&&i instanceof Error?i.stack??``:``,error_class:a})})},trackCodeExecution(t,n){let r=Date.now(),i=o(t),a=/* @__PURE__ */ new Map,s=0;return{hostFetch:n&&(t=>(s+=1,n(t).catch(t=>{throw a.set(e(t),{reason:`runtime_error`}),t}))),innerToolCall(e,t){let n=R(e,t,a),r=n.then(()=>void 0,()=>void 0);return M.add(r),r.then(()=>M.delete(r)),n},finish(e,t,n){let o=e.failure===p.HostError&&e.error!==void 0?a.get(e.error):void 0;o?.tool&&N.add(t);let c=e.error===void 0?`ok`:`error`,l=Date.now()-r,u=k(e.failure,o,n),d=o?.tool;F(()=>P(`com.redocly.mcpServer.codeExecuted`,{...v,code_sha256:i.sha256,code_length:i.length,fetch_count:s,outcome:c,flags:i.flags,duration_ms:l,failure_reason:u,failed_tool:d,...O})),x?.info(`Gateway MCP code executed [${i.sha256.slice(0,12)}] outcome=${c} codeLength=${i.length} fetchCount=${s}`+(i.flags?` flags=${i.flags}`:``)+` durationMs=${l}`+(u?` failureReason=${u}`:``)+(d?` failedTool=${d}`:``))}}},gatewayFetchPerformed({host:e,method:t,outcome:n,durationMs:r,path:i,api:a,status:o,bytes:s,injectedScheme:c}){F(()=>P(`com.redocly.mcpServer.gatewayFetchPerformed`,{...v,host:e,method:t,outcome:n,path:i,api:a,status:o,injected_scheme:c,bytes:s,duration_ms:r})),x?.info(`Gateway MCP fetch [${t} ${e}] outcome=${n}`+(i===void 0?``:` path=${i}`)+(a===void 0?``:` api=${a}`)+(o===void 0?``:` status=${o}`)+(c===void 0?``:` injectedScheme=${c}`)+(s===void 0?``:` bytes=${s}`)+` durationMs=${r}`)},gatewayFetchRateLimited({scope:e,limit:t,retryAfterSeconds:n}){F(()=>P(`com.redocly.mcpServer.gatewayFetchRateLimited`,{...v,scope:e,retry_after_seconds:n,limit:t}))},async flush(){if(!C){j=[];return}await A(M,300);let e=j;j=[],await a(e,{env:S,fetcher:i.fetcher,logger:x})}}}function x(e,t){let{requestId:n=g(),callerSubject:r,clientIp:a}=t.caller??{};return i({...e,requestId:n,actor:y(r),clientIp:a},t)}function S(e,t,n={}){return x({type:`com.redocly.mcpServer.error`,data:[{...v,message:s(e instanceof Error?e.message:``),stack:l(e instanceof Error?e.stack??``:``),error_class:`server_error`,mode:t}]},n)}function C({scope:e,retryAfterSeconds:t,limit:n},r={}){return x({type:`com.redocly.mcpServer.rateLimited`,data:[{...v,scope:e,retry_after_seconds:t,limit:n}]},r)}function w(e){let t=e||_(),n=t.startsWith(`mcp_`)?t:`mcp_${t}`;return{id:n,object:`mcpSession`,uri:`urn:redocly:realm:mcp:session:${n}`}}function T(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.started`,data:[{...w(e),redirect_uri:t}]},n)}function E(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.completed`,data:[{...w(e),redirect_uri:t}]},n)}function D(e,t,n,r,i={}){return x({type:`com.redocly.mcpServerAuthorization.failed`,data:[{...w(e),error:n,error_details:r,error_class:t}]},i)}function O(e,t={}){return x({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`,...e},signal:`trace`},t)}function k(e,t,n){return e===p.HostError?t?.reason??p.RuntimeError:e===p.RuntimeError&&n!==void 0?`unknown_tool`:e}async function A(e,t){if(e.size===0)return;let n;await Promise.race([Promise.allSettled(e),new Promise(e=>{n=setTimeout(e,t)})]),clearTimeout(n)}export{b as createMcpTelemetry,E as sendMcpAuthorizationCompleted,D as sendMcpAuthorizationFailed,T as sendMcpAuthorizationStarted,C as sendMcpRateLimited,S as sendMcpRequestError,O as sendMcpServerCardServed};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{getSessionIssuer as n}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as r}from"../../../../../../server/plugin-context.js";import{isMcpContentProtected as i,isMcpHidden as a,resolveMcpAccess as o}from"../config-gate.js";import{MCP_CALLBACK_ROUTE as s}from"../../constants.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(a(p.config)||!i(o(p.config)))return r();let m=n(f);if(!m)return r();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${s}/${O}`});return f.redirect(`${e(t.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
1
+ import{MCP_CALLBACK_ROUTE as e}from"../../constants.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{getSessionIssuer as o}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as s}from"../../../../../../server/plugin-context.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(i(p.config)||!r(a(p.config)))return s();let m=o(f);if(!m)return s();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${e}/${O}`});return f.redirect(`${n(t.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
@@ -1 +1 @@
1
- import{REALM_SESSION_COOKIE as e}from"../../../../../../server/auth/constants.js";import{getBearerVerifier as t,getSessionIssuer as n}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as r}from"../../../../../../server/plugin-context.js";import{isMcpHidden as i}from"../config-gate.js";import{MCP_REFRESH_SESSION_LIFETIME_SEC as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import{auditInput as s}from"../audit.js";import{sendMcpAuthorizationCompleted as c}from"../mcp-telemetry.js";import{loadPageSite as l}from"../gateway/credentials-page/site-branding.js";import{isLoopbackRedirect as u,parseRedirectUri as d}from"./redirect-uri.js";import{isClientMetadataDocumentUrl as f}from"./client-metadata.js";import{reportMcpAuthorizationFailure as p,withMcpFailureReporting as m}from"./error-reporting.js";import{sessionClaimsFromSession as h,sha256Base64Url as g,signMcpArtifact as _,verifyMcpArtifact as v}from"./tokens.js";import{CONSENT_PAGE_HEADERS as y,consentInvalidPage as b,consentPage as x}from"./consent-page.js";import{hasConsent as S,saveConsent as C}from"./store.js";import{getCookie as w}from"hono/cookie";const T={"Cache-Control":`no-store`},E=`Missing context token`;function D(e){let t=e.searchParams.get(`context`);if(t)return t;let n=e.pathname.split(`/`).filter(Boolean).pop();return n&&n!==`callback`?n:null}async function O(n,r){let i=new URL(n.req.url),a=w(n,e),o=a?await t(n)?.(a):null;return{method:n.req.method,path:`${i.pathname}${i.search}`,referer:n.req.header(`referer`)??null,user_agent:r.request.userAgent,has_session_cookie:a!==void 0,has_user_session:!!o&&o?.claims.tokenUse!==`mcp_access_token`}}function k(a){return async(o,c)=>{if(i(c.config))return r();let l=n(o);if(!l)return r();let u=D(new URL(o.req.url));if(!u){let e=await O(o,c);return await p(c,E,{details:s(JSON.stringify(e)),logFields:e}),o.text(E,400,T)}let f,m,h;try{if(f=await v(u,l.artifactSecret,`mcp_context`),h=f.sessionId,o.set(`realmMcpSessionId`,h),m=d(f.redirectUri),!m)throw Error(`Invalid MCP context`)}catch(e){let t=await p(c,e,{sessionId:h,errorClass:`client_error`,logMessage:`MCP callback failed`});return o.text(`Invalid MCP callback: ${t}`,400,T)}let g=w(o,e),_=g?await t(o)?.(g):null;return!g||!_||_.claims.tokenUse===`mcp_access_token`?(await p(c,`Authentication required`,{sessionId:h}),o.text(`Authentication required`,401,T)):a(o,c,{issuer:l,contextToken:u,mcpContext:f,redirectUrl:m,sessionToken:g,session:_})}}async function A(e,t,{issuer:n,mcpContext:r,redirectUrl:i,session:o}){let s=Math.floor(Date.now()/1e3),l=await _({type:`mcp_auth_code`,sessionId:r.sessionId,clientId:r.clientId,redirectUri:r.redirectUri,claims:h(o),sessionExp:s+a,codeChallenge:r.codeChallenge,codeChallengeMethod:r.codeChallengeMethod},n.artifactSecret,s+600),u=new URL(i);return u.searchParams.set(`code`,l),r.state&&u.searchParams.set(`state`,r.state),c(r.sessionId,r.redirectUri,{logger:t.logger}),e.header(`Cache-Control`,`no-store`),e.redirect(u.toString(),302)}async function j(e,t,{mcpContext:n,redirectUrl:r}){let i=new URL(r);return i.searchParams.set(`error`,`access_denied`),n.state&&i.searchParams.set(`state`,n.state),await p(t,`access_denied`,{sessionId:n.sessionId}),e.header(`Cache-Control`,`no-store`),e.redirect(i.toString(),302)}function M({mcpContext:e,session:t}){return{idpId:t.claims.idpId,subject:t.viewer.sub,clientId:e.clientId,redirectUri:e.redirectUri}}function N({issuer:e,sessionToken:t,contextToken:n}){return _({type:`mcp_consent`,sessionHash:g(t),contextHash:g(n)},e.artifactSecret,Math.floor(Date.now()/1e3)+300)}async function P(e,{issuer:t,sessionToken:n,contextToken:r}){try{let i=await v(e,t.artifactSecret,`mcp_consent`);return i.sessionHash===g(n)&&i.contextHash===g(r)}catch{return!1}}const F=e=>e.text(`MCP authorization could not be completed`,500,T),I=m(k(async(e,t,n)=>{if(u(n.redirectUrl)||await S(t.kv,M(n)))return A(e,t,n);let{clientId:r,clientName:i}=n.mcpContext,{viewer:s}=n.session,c=x({site:await l(t),user:s.email||s.name||s.sub,clientName:i??void 0,clientIdHost:f(r)?new URL(r).host:void 0,redirectUrl:n.redirectUrl,scopes:o,accessLifetimeHours:a/3600,rememberDays:30,consentToken:await N(n)});return e.set(`realmCacheControlOwned`,!0),new Response(c,{status:200,headers:y})}),F),L=m(k(async(e,t,n)=>{let r=await e.req.formData().catch(()=>null),i=r?.get(`consent`);return typeof i!=`string`||!await P(i,n)?new Response(b(await l(t)),{status:403,headers:y}):r?.get(`decision`)===`allow`?(await C(t.kv,M(n)),A(e,t,n)):j(e,t,n)}),F);export{I as mcpCallback,L as mcpConsent};
1
+ import{isMcpHidden as e}from"../config-gate.js";import{REALM_SESSION_COOKIE as t}from"../../../../../../server/auth/constants.js";import{getBearerVerifier as n,getSessionIssuer as r}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as i}from"../../../../../../server/plugin-context.js";import{MCP_REFRESH_SESSION_LIFETIME_SEC as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import{auditInput as s}from"../audit.js";import{sendMcpAuthorizationCompleted as c}from"../mcp-telemetry.js";import{loadPageSite as l}from"../gateway/credentials-page/site-branding.js";import{isLoopbackRedirect as u,parseRedirectUri as d}from"./redirect-uri.js";import{isClientMetadataDocumentUrl as f}from"./client-metadata.js";import{reportMcpAuthorizationFailure as p,withMcpFailureReporting as m}from"./error-reporting.js";import{sessionClaimsFromSession as h,sha256Base64Url as g,signMcpArtifact as _,verifyMcpArtifact as v}from"./tokens.js";import{CONSENT_PAGE_HEADERS as y,consentInvalidPage as b,consentPage as x}from"./consent-page.js";import{hasConsent as S,saveConsent as C}from"./store.js";import{getCookie as w}from"hono/cookie";const T={"Cache-Control":`no-store`},E=`Missing context token`;function D(e){let t=e.searchParams.get(`context`);if(t)return t;let n=e.pathname.split(`/`).filter(Boolean).pop();return n&&n!==`callback`?n:null}async function O(e,r){let i=new URL(e.req.url),a=w(e,t),o=a?await n(e)?.(a):null;return{method:e.req.method,path:`${i.pathname}${i.search}`,referer:e.req.header(`referer`)??null,user_agent:r.request.userAgent,has_session_cookie:a!==void 0,has_user_session:!!o&&o?.claims.tokenUse!==`mcp_access_token`}}function k(a){return async(o,c)=>{if(e(c.config))return i();let l=r(o);if(!l)return i();let u=D(new URL(o.req.url));if(!u){let e=await O(o,c);return await p(c,E,{details:s(JSON.stringify(e)),logFields:e}),o.text(E,400,T)}let f,m,h;try{if(f=await v(u,l.artifactSecret,`mcp_context`),h=f.sessionId,o.set(`realmMcpSessionId`,h),m=d(f.redirectUri),!m)throw Error(`Invalid MCP context`)}catch(e){let t=await p(c,e,{sessionId:h,errorClass:`client_error`,logMessage:`MCP callback failed`});return o.text(`Invalid MCP callback: ${t}`,400,T)}let g=w(o,t),_=g?await n(o)?.(g):null;return!g||!_||_.claims.tokenUse===`mcp_access_token`?(await p(c,`Authentication required`,{sessionId:h}),o.text(`Authentication required`,401,T)):a(o,c,{issuer:l,contextToken:u,mcpContext:f,redirectUrl:m,sessionToken:g,session:_})}}async function A(e,t,{issuer:n,mcpContext:r,redirectUrl:i,session:o}){let s=Math.floor(Date.now()/1e3),l=await _({type:`mcp_auth_code`,sessionId:r.sessionId,clientId:r.clientId,redirectUri:r.redirectUri,claims:h(o),sessionExp:s+a,codeChallenge:r.codeChallenge,codeChallengeMethod:r.codeChallengeMethod},n.artifactSecret,s+600),u=new URL(i);return u.searchParams.set(`code`,l),r.state&&u.searchParams.set(`state`,r.state),c(r.sessionId,r.redirectUri,{logger:t.logger}),e.header(`Cache-Control`,`no-store`),e.redirect(u.toString(),302)}async function j(e,t,{mcpContext:n,redirectUrl:r}){let i=new URL(r);return i.searchParams.set(`error`,`access_denied`),n.state&&i.searchParams.set(`state`,n.state),await p(t,`access_denied`,{sessionId:n.sessionId}),e.header(`Cache-Control`,`no-store`),e.redirect(i.toString(),302)}function M({mcpContext:e,session:t}){return{idpId:t.claims.idpId,subject:t.viewer.sub,clientId:e.clientId,redirectUri:e.redirectUri}}function N({issuer:e,sessionToken:t,contextToken:n}){return _({type:`mcp_consent`,sessionHash:g(t),contextHash:g(n)},e.artifactSecret,Math.floor(Date.now()/1e3)+300)}async function P(e,{issuer:t,sessionToken:n,contextToken:r}){try{let i=await v(e,t.artifactSecret,`mcp_consent`);return i.sessionHash===g(n)&&i.contextHash===g(r)}catch{return!1}}const F=e=>e.text(`MCP authorization could not be completed`,500,T),I=m(k(async(e,t,n)=>{if(u(n.redirectUrl)||await S(t.kv,M(n)))return A(e,t,n);let{clientId:r,clientName:i}=n.mcpContext,{viewer:s}=n.session,c=x({site:await l(t),user:s.email||s.name||s.sub,clientName:i??void 0,clientIdHost:f(r)?new URL(r).host:void 0,redirectUrl:n.redirectUrl,scopes:o,accessLifetimeHours:a/3600,rememberDays:30,consentToken:await N(n)});return e.set(`realmCacheControlOwned`,!0),new Response(c,{status:200,headers:y})}),F),L=m(k(async(e,t,n)=>{let r=await e.req.formData().catch(()=>null),i=r?.get(`consent`);return typeof i!=`string`||!await P(i,n)?new Response(b(await l(t)),{status:403,headers:y}):r?.get(`decision`)===`allow`?(await C(t.kv,M(n)),A(e,t,n)):j(e,t,n)}),F);export{I as mcpCallback,L as mcpConsent};
@@ -1 +1 @@
1
- import{isLoopbackRedirect as e}from"./redirect-uri.js";const t=65536;function n(e){if(!e)return!1;try{return new URL(e).protocol===`https:`}catch{return!1}}function r(e,t){if(t.includes(e))return!0;let n=i(e);return n!==null&&t.some(e=>i(e)===n)}function i(t){let n=URL.parse(t);return!n||!e(n)?null:(n.port=``,n.href)}async function a(e){if(!n(e))throw Error(`client_id must be an https URL`);let t=await fetch(e,{method:`GET`,redirect:`error`,headers:{Accept:`application/json`},signal:AbortSignal.timeout(5e3)});if(!t.ok)throw Error(`Failed to fetch client metadata: HTTP ${t.status}`);let r=t.headers.get(`content-type`)??``;if(!/^application\/(.+\+)?json/i.test(r))throw Error(`Unexpected content-type for client metadata: ${r}`);return s(await o(t))}async function o(e){let n=e.body;if(!n)throw Error(`Client metadata response has no body`);let r=n.getReader(),i=[],a=0;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw Error(`Client metadata exceeds maximum size of ${t/1024} KB`);i.push(n)}}finally{await r.cancel().catch(()=>{})}return Buffer.concat(i).toString(`utf8`)}function s(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`Invalid JSON in client metadata: ${e.message}`)}let n=t,r=n?.redirect_uris;if(!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`&&e!==``))throw Error(`Invalid client metadata: /redirect_uris must be a non-empty array of strings`);return{redirect_uris:r,...typeof n?.client_name==`string`?{client_name:n.client_name}:{}}}export{a as fetchClientMetadataDocument,n as isClientMetadataDocumentUrl,r as isRedirectUriRegistered};
1
+ import{isBlockedIp as e}from"../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../server/ssrf/ssrf-safe-lookup.js";import{isLoopbackRedirect as n}from"./redirect-uri.js";import{isIP as r}from"node:net";import{Agent as i}from"undici";const a=65536;let o;function s(e){if(!e)return!1;try{return new URL(e).protocol===`https:`}catch{return!1}}function c(e,t){if(t.includes(e))return!0;let n=l(e);return n!==null&&t.some(e=>l(e)===n)}function l(e){let t=URL.parse(e);return!t||!n(t)?null:(t.port=``,t.href)}async function u(n){if(!s(n))throw Error(`client_id must be an https URL`);let a=new URL(n).hostname.replace(/^\[|\]$/g,``);if(r(a)!==0&&e(a))throw Error(`client_id must not be a private network address`);let c={method:`GET`,redirect:`error`,headers:{Accept:`application/json`},signal:AbortSignal.timeout(5e3),dispatcher:o??=new i({connect:{lookup:t()}})},l=await fetch(n,c);if(!l.ok)throw Error(`Failed to fetch client metadata: HTTP ${l.status}`);let u=l.headers.get(`content-type`)??``;if(!/^application\/(.+\+)?json/i.test(u))throw Error(`Unexpected content-type for client metadata: ${u}`);return f(await d(l))}async function d(e){let t=e.body;if(!t)throw Error(`Client metadata response has no body`);let n=t.getReader(),r=[],i=0;try{for(;;){let{done:e,value:t}=await n.read();if(e)break;if(i+=t.byteLength,i>a)throw Error(`Client metadata exceeds maximum size of ${a/1024} KB`);r.push(t)}}finally{await n.cancel().catch(()=>{})}return Buffer.concat(r).toString(`utf8`)}function f(e){let t;try{t=JSON.parse(e)}catch(e){throw Error(`Invalid JSON in client metadata: ${e.message}`)}let n=t,r=n?.redirect_uris;if(!Array.isArray(r)||r.length===0||!r.every(e=>typeof e==`string`&&e!==``))throw Error(`Invalid client metadata: /redirect_uris must be a non-empty array of strings`);return{redirect_uris:r,...typeof n?.client_name==`string`?{client_name:n.client_name}:{}}}export{u as fetchClientMetadataDocument,s as isClientMetadataDocumentUrl,c as isRedirectUriRegistered};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{notFoundResponse as t}from"../../../../../../server/plugin-context.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{MCP_AUTHORIZATION_SERVER_ROUTE as o,MCP_AUTHORIZE_ROUTE as s,MCP_REGISTER_ROUTE as c,MCP_ROUTE as l,MCP_TOKEN_ROUTE as u}from"../../constants.js";import{CORS_ANY_ORIGIN as d,SUPPORTED_MCP_GRANT_TYPES as f,SUPPORTED_MCP_SCOPES as p}from"./constants.js";import"../auth.js";function m(e){return!i(e.config)&&r(a(e.config))}function h(r,i){if(!m(i))return t();let a=n(i.request);return r.json({resource:`${a}${e(l)}`,authorization_servers:[a],bearer_methods_supported:[`header`],resource_documentation:`${a}${e(o)}`,scopes_supported:[...p],bearer_token_types_supported:[`Bearer`]},200,{...d})}function g(r,i){if(!m(i))return t();let a=n(i.request);return r.json({issuer:a,authorization_endpoint:`${a}${e(s)}`,token_endpoint:`${a}${e(u)}`,scopes_supported:[...p],registration_endpoint:`${a}${e(c)}`,response_types_supported:[`code`],grant_types_supported:[...f],subject_types_supported:[`public`],id_token_signing_alg_values_supported:[`RS256`],code_challenge_methods_supported:[`S256`],token_endpoint_auth_methods_supported:[`none`],client_id_metadata_document_supported:!0},200,{...d})}export{g as oauthAuthorizationServer,h as oauthProtectedResource};
1
+ import{MCP_AUTHORIZATION_SERVER_ROUTE as e,MCP_AUTHORIZE_ROUTE as t,MCP_REGISTER_ROUTE as n,MCP_ROUTE as r,MCP_TOKEN_ROUTE as i}from"../../constants.js";import{withPathPrefix as a}from"../../../../../../shared/path-prefix.js";import{isMcpContentProtected as o,isMcpHidden as s,resolveMcpAccess as c}from"../config-gate.js";import{publicOrigin as l}from"../../../../utils/request-origin.js";import{notFoundResponse as u}from"../../../../../../server/plugin-context.js";import{CORS_ANY_ORIGIN as d,SUPPORTED_MCP_GRANT_TYPES as f,SUPPORTED_MCP_SCOPES as p}from"./constants.js";import"../auth.js";function m(e){return!s(e.config)&&o(c(e.config))}function h(t,n){if(!m(n))return u();let i=l(n.request);return t.json({resource:`${i}${a(r)}`,authorization_servers:[i],bearer_methods_supported:[`header`],resource_documentation:`${i}${a(e)}`,scopes_supported:[...p],bearer_token_types_supported:[`Bearer`]},200,{...d})}function g(e,r){if(!m(r))return u();let o=l(r.request);return e.json({issuer:o,authorization_endpoint:`${o}${a(t)}`,token_endpoint:`${o}${a(i)}`,scopes_supported:[...p],registration_endpoint:`${o}${a(n)}`,response_types_supported:[`code`],grant_types_supported:[...f],subject_types_supported:[`public`],id_token_signing_alg_values_supported:[`RS256`],code_challenge_methods_supported:[`S256`],token_endpoint_auth_methods_supported:[`none`],client_id_metadata_document_supported:!0},200,{...d})}export{g as oauthAuthorizationServer,h as oauthProtectedResource};
@@ -1 +1 @@
1
- import{notFoundResponse as e}from"../../../../../../server/plugin-context.js";import{isMcpContentProtected as t,isMcpHidden as n,resolveMcpAccess as r}from"../config-gate.js";import{CORS_ANY_ORIGIN as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import"../auth.js";import{applyMcpRateLimit as s}from"../rate-limit.js";import{writeMcpClient as c}from"./client-registry.js";import{withMcpFailureReporting as l}from"./error-reporting.js";import{ulid as u}from"ulid";function d(e){let t=e.client_name;if(typeof t==`string`&&Buffer.byteLength(t,`utf8`)>256)return{ok:!1,error:`client_name exceeds 256 bytes`};let n=e.redirect_uris;if(n!==void 0&&!Array.isArray(n))return{ok:!1,error:`redirect_uris must be an array`};if(Array.isArray(n)&&n.length>20)return{ok:!1,error:`redirect_uris must hold at most 20 entries`};let r=[];for(let e of Array.isArray(n)?n:[])if(typeof e==`string`&&e!==``){if(Buffer.byteLength(e,`utf8`)>512)return{ok:!1,error:`a redirect_uri exceeds 512 bytes`};r.push(e)}return{ok:!0,clientName:typeof t==`string`&&t?t:`MCP Client`,redirectUris:r}}const f=l(p,e=>e.json({error:`server_error`,error_description:`Unable to register client`},500,{...i}));async function p(l,f){if(n(f.config)||!t(r(f.config)))return e();let p=await s({kv:f.kv,ip:f.request.ip,bucket:`oauth`,logger:f.logger});if(p)return p;let m=await l.req.json().catch(()=>null);if(m!==null&&(typeof m!=`object`||Array.isArray(m)))return l.json({error:`invalid_request`,error_description:`Client metadata must be a JSON object`},400,{...i});let h=d(m??{});if(!h.ok)return l.json({error:`invalid_request`,error_description:h.error},400,{...i});let g=(/* @__PURE__ */ new Date()).toISOString(),_={client_id:`mcp_${u()}`,client_name:h.clientName,redirect_uris:h.redirectUris,grant_types:[...a],response_types:[`code`],scope:o.join(` `),subject_type:`public`,token_endpoint_auth_method:`none`,created_at:g,updated_at:g};return await c(f.kv,_),l.json(_,201,{...i})}export{f as mcpRegister};
1
+ import{isMcpContentProtected as e,isMcpHidden as t,resolveMcpAccess as n}from"../config-gate.js";import{notFoundResponse as r}from"../../../../../../server/plugin-context.js";import{CORS_ANY_ORIGIN as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import"../auth.js";import{applyMcpRateLimit as s}from"../rate-limit.js";import{writeMcpClient as c}from"./client-registry.js";import{withMcpFailureReporting as l}from"./error-reporting.js";import{ulid as u}from"ulid";function d(e){let t=e.client_name;if(typeof t==`string`&&Buffer.byteLength(t,`utf8`)>256)return{ok:!1,error:`client_name exceeds 256 bytes`};let n=e.redirect_uris;if(n!==void 0&&!Array.isArray(n))return{ok:!1,error:`redirect_uris must be an array`};if(Array.isArray(n)&&n.length>20)return{ok:!1,error:`redirect_uris must hold at most 20 entries`};let r=[];for(let e of Array.isArray(n)?n:[])if(typeof e==`string`&&e!==``){if(Buffer.byteLength(e,`utf8`)>512)return{ok:!1,error:`a redirect_uri exceeds 512 bytes`};r.push(e)}return{ok:!0,clientName:typeof t==`string`&&t?t:`MCP Client`,redirectUris:r}}const f=l(p,e=>e.json({error:`server_error`,error_description:`Unable to register client`},500,{...i}));async function p(l,f){if(t(f.config)||!e(n(f.config)))return r();let p=await s({kv:f.kv,ip:f.request.ip,bucket:`oauth`,logger:f.logger});if(p)return p;let m=await l.req.json().catch(()=>null);if(m!==null&&(typeof m!=`object`||Array.isArray(m)))return l.json({error:`invalid_request`,error_description:`Client metadata must be a JSON object`},400,{...i});let h=d(m??{});if(!h.ok)return l.json({error:`invalid_request`,error_description:h.error},400,{...i});let g=(/* @__PURE__ */ new Date()).toISOString(),_={client_id:`mcp_${u()}`,client_name:h.clientName,redirect_uris:h.redirectUris,grant_types:[...a],response_types:[`code`],scope:o.join(` `),subject_type:`public`,token_endpoint_auth_method:`none`,created_at:g,updated_at:g};return await c(f.kv,_),l.json(_,201,{...i})}export{f as mcpRegister};
@@ -1 +1 @@
1
- import{MCP_ACCESS_TOKEN_USE as e}from"../../../../../../server/auth/constants.js";import{getSessionIssuer as t}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as n}from"../../../../../../server/plugin-context.js";import{isMcpHidden as r}from"../config-gate.js";import{MCP_ACCESS_TOKEN_TTL_SEC as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o,TOKEN_RESPONSE_HEADERS as s}from"./constants.js";import{refuseMcpOAuth as c,withMcpFailureReporting as l}from"./error-reporting.js";import{signMcpArtifact as u,verifyMcpArtifact as d,verifyPkce as f}from"./tokens.js";import{redeemAuthorizationCode as p,redeemRefreshToken as m}from"./store.js";async function h(t,n,r,a){t.set(`realmCacheControlOwned`,!0);let l=Math.floor(Date.now()/1e3);if(l>=a.sessionExp)return c(t,n,`invalid_grant`,`Session has expired`);let d=Math.min(i,a.sessionExp-l),[f,p]=await Promise.all([r.mint({...a.claims,tokenUse:e},l+d),u({type:`mcp_refresh_token`,sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp},r.artifactSecret,a.sessionExp)]);return t.json({access_token:f,token_type:`Bearer`,expires_in:d,refresh_token:p,scope:o.join(` `)},200,{...s})}const g=l(_,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500,{...s}));async function _(e,i){if(r(i.config))return n();let o=t(e);if(!o)return n();let s;try{s=await e.req.formData()}catch{return c(e,i,`invalid_request`,`Expected an application/x-www-form-urlencoded body`)}let l=s.get(`grant_type`);return typeof l!=`string`||!a.includes(l)?c(e,i,`invalid_request`,`Invalid grant type`):l===`refresh_token`?y(e,i,o,s):v(e,i,o,s)}async function v(e,t,n,r){let i=r.get(`code`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`Missing authorization code`);let a;try{a=await d(i,n.artifactSecret,`mcp_auth_code`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid authorization code`,`MCP token exchange failed`)}let o=r.get(`redirect_uri`);if(typeof o!=`string`||o!==a.redirectUri)return c(e,t,`invalid_grant`,`redirect_uri mismatch`);let s=r.get(`client_id`);if(typeof s!=`string`||s!==a.clientId)return c(e,t,`invalid_grant`,`Client mismatch`);let l=r.get(`code_verifier`);return typeof l!=`string`||l===``?c(e,t,`invalid_grant`,`code_verifier required`):f(a.codeChallenge,a.codeChallengeMethod,l)?await p(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Authorization code already used`):c(e,t,`invalid_grant`,`code_verifier mismatch`)}async function y(e,t,n,r){let i=r.get(`refresh_token`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`refresh_token is required`);let a;try{a=await d(i,n.artifactSecret,`mcp_refresh_token`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid refresh token`,`MCP refresh token rejected`)}let o=r.get(`client_id`);return typeof o!=`string`||o!==a.clientId?c(e,t,`invalid_grant`,`Client mismatch`):await m(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Refresh token already used`,`MCP refresh rejected: the refresh token was already used`)}export{g as mcpToken};
1
+ import{isMcpHidden as e}from"../config-gate.js";import{MCP_ACCESS_TOKEN_USE as t}from"../../../../../../server/auth/constants.js";import{getSessionIssuer as n}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as r}from"../../../../../../server/plugin-context.js";import{MCP_ACCESS_TOKEN_TTL_SEC as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o,TOKEN_RESPONSE_HEADERS as s}from"./constants.js";import{refuseMcpOAuth as c,withMcpFailureReporting as l}from"./error-reporting.js";import{signMcpArtifact as u,verifyMcpArtifact as d,verifyPkce as f}from"./tokens.js";import{redeemAuthorizationCode as p,redeemRefreshToken as m}from"./store.js";async function h(e,n,r,a){e.set(`realmCacheControlOwned`,!0);let l=Math.floor(Date.now()/1e3);if(l>=a.sessionExp)return c(e,n,`invalid_grant`,`Session has expired`);let d=Math.min(i,a.sessionExp-l),[f,p]=await Promise.all([r.mint({...a.claims,tokenUse:t},l+d),u({type:`mcp_refresh_token`,sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp},r.artifactSecret,a.sessionExp)]);return e.json({access_token:f,token_type:`Bearer`,expires_in:d,refresh_token:p,scope:o.join(` `)},200,{...s})}const g=l(_,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500,{...s}));async function _(t,i){if(e(i.config))return r();let o=n(t);if(!o)return r();let s;try{s=await t.req.formData()}catch{return c(t,i,`invalid_request`,`Expected an application/x-www-form-urlencoded body`)}let l=s.get(`grant_type`);return typeof l!=`string`||!a.includes(l)?c(t,i,`invalid_request`,`Invalid grant type`):l===`refresh_token`?y(t,i,o,s):v(t,i,o,s)}async function v(e,t,n,r){let i=r.get(`code`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`Missing authorization code`);let a;try{a=await d(i,n.artifactSecret,`mcp_auth_code`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid authorization code`,`MCP token exchange failed`)}let o=r.get(`redirect_uri`);if(typeof o!=`string`||o!==a.redirectUri)return c(e,t,`invalid_grant`,`redirect_uri mismatch`);let s=r.get(`client_id`);if(typeof s!=`string`||s!==a.clientId)return c(e,t,`invalid_grant`,`Client mismatch`);let l=r.get(`code_verifier`);return typeof l!=`string`||l===``?c(e,t,`invalid_grant`,`code_verifier required`):f(a.codeChallenge,a.codeChallengeMethod,l)?await p(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Authorization code already used`):c(e,t,`invalid_grant`,`code_verifier mismatch`)}async function y(e,t,n,r){let i=r.get(`refresh_token`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`refresh_token is required`);let a;try{a=await d(i,n.artifactSecret,`mcp_refresh_token`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid refresh token`,`MCP refresh token rejected`)}let o=r.get(`client_id`);return typeof o!=`string`||o!==a.clientId?c(e,t,`invalid_grant`,`Client mismatch`):await m(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Refresh token already used`,`MCP refresh rejected: the refresh token was already used`)}export{g as mcpToken};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as t}from"../../../../../shared/types/auth.js";import{notFoundResponse as n}from"../../../../../server/plugin-context.js";import{publicBaseUrl as r,publicOrigin as i}from"../../../utils/request-origin.js";import{isMcpContentProtected as a,isMcpHidden as o,resolveMcpAccess as s}from"./config-gate.js";import{MCP_ROUTE as c}from"../constants.js";import{formatError as l}from"./tool-errors.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p}from"./mode.js";import{sendMcpServerCardServed as m}from"./mcp-telemetry.js";import{applyMcpRateLimit as h}from"./rate-limit.js";import{createServedMcpRequestHandler as g}from"./handler.js";import{docsServerInfo as _}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as v,CLIENT_INFO_META_KEY as y,LATEST_PROTOCOL_VERSION as b,PROTOCOL_VERSION_META_KEY as x}from"@modelcontextprotocol/server";const S=`2026-07-28`,C=[`dynamic`],w={capabilities:{},tools:C};async function T(e,t,n){let r=await e(new Request(t,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,"mcp-protocol-version":S,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[x]:S,[y]:{name:`server-card`,version:`1.0`},[v]:{}}}})}));if(r.ok)return(await r.json()).result}function E(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${l(t)}`)}async function D(n,r){let a=await n.withViewer(t),o=await g(a,{isProtected:r},Date.now()+f,{onError:e=>E(n,e)}),s=new URL(e(c),i(n.request)).href,[l,u]=await Promise.all([T(o,s,`server/discover`),r?void 0:T(o,s,`tools/list`)]);if(!l)return;if(r)return{capabilities:l.capabilities,tools:C};if(!u)return;let d=u.tools.map(({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a})=>({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:C}}async function O(t,i){if(o(i.config))return n();t.set(`realmCacheControlOwned`,!0);let l=await h({kv:i.kv,ip:i.request.ip,bucket:`card`,headers:u,logger:i.logger});if(l)return l;let f=_(i.config,i.request),g=a(s(i.config)),v=await D(i,g).catch(e=>{E(i,e)}),{capabilities:y,instructions:x,tools:S}=v??w;return m({mode:p(),toolsCount:S===C?0:S.length,authRequired:g},{logger:i.logger}),t.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:b,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:r(i.config,i.request),transport:{type:`streamable-http`,endpoint:e(c)},capabilities:y,authentication:g?{required:!0,schemes:[...d]}:void 0,instructions:x,tools:S},200,{...u,"Cache-Control":v?`public, max-age=3600`:`no-store`})}export{O as mcpServerCard};
1
+ import{MCP_ROUTE as e}from"../constants.js";import{withPathPrefix as t}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as n}from"../../../../../shared/types/auth.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"./config-gate.js";import{publicBaseUrl as o,publicOrigin as s}from"../../../utils/request-origin.js";import{formatError as c}from"./tool-errors.js";import{notFoundResponse as l}from"../../../../../server/plugin-context.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p}from"./mode.js";import{sendMcpServerCardServed as m}from"./mcp-telemetry.js";import{applyMcpRateLimit as h}from"./rate-limit.js";import{createServedMcpRequestHandler as g}from"./handler.js";import{docsServerInfo as _}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as v,CLIENT_INFO_META_KEY as y,LATEST_PROTOCOL_VERSION as b,PROTOCOL_VERSION_META_KEY as x}from"@modelcontextprotocol/server";const S=`2026-07-28`,C=[`dynamic`],w={capabilities:{},tools:C};async function T(e,t,n){let r=await e(new Request(t,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,"mcp-protocol-version":S,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[x]:S,[y]:{name:`server-card`,version:`1.0`},[v]:{}}}})}));if(r.ok)return(await r.json()).result}function E(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${c(t)}`)}async function D(r,i){let a=await r.withViewer(n),o=await g(a,{isProtected:i},Date.now()+f,{onError:e=>E(r,e)}),c=new URL(t(e),s(r.request)).href,[l,u]=await Promise.all([T(o,c,`server/discover`),i?void 0:T(o,c,`tools/list`)]);if(!l)return;if(i)return{capabilities:l.capabilities,tools:C};if(!u)return;let d=u.tools.map(({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a})=>({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:C}}async function O(n,s){if(i(s.config))return l();n.set(`realmCacheControlOwned`,!0);let c=await h({kv:s.kv,ip:s.request.ip,bucket:`card`,headers:u,logger:s.logger});if(c)return c;let f=_(s.config,s.request),g=r(a(s.config)),v=await D(s,g).catch(e=>{E(s,e)}),{capabilities:y,instructions:x,tools:S}=v??w;return m({mode:p(),toolsCount:S===C?0:S.length,authRequired:g},{logger:s.logger}),n.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:b,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:o(s.config,s.request),transport:{type:`streamable-http`,endpoint:t(e)},capabilities:y,authentication:g?{required:!0,schemes:[...d]}:void 0,instructions:x,tools:S},200,{...u,"Cache-Control":v?`public, max-age=3600`:`no-store`})}export{O as mcpServerCard};
@@ -1 +1 @@
1
- import{realmPlusVersion as e}from"../../../../../shared/realm-plus-version.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{PLACEHOLDER_MCP_SERVER_NAMES as n}from"../constants.js";import{resolveDocsSiteUrl as r}from"./docs-site-url.js";import{docsSiteSentence as i}from"./codemode/prompts.js";function a(e){let t=e.mcp?.name?.trim();return t&&!n.includes(t)?t:void 0}function o(n,o){let s=r(n.seo?.siteUrl,t(o));return{name:a(n)||new URL(s).host,version:e(),description:i(s),websiteUrl:s}}export{o as docsServerInfo};
1
+ import{PLACEHOLDER_MCP_SERVER_NAMES as e}from"../constants.js";import{realmPlusVersion as t}from"../../../../../shared/realm-plus-version.js";import{publicOrigin as n}from"../../../utils/request-origin.js";import{resolveDocsSiteUrl as r}from"./docs-site-url.js";import{docsSiteSentence as i}from"./codemode/prompts.js";function a(t){let n=t.mcp?.name?.trim();return n&&!e.includes(n)?n:void 0}function o(e,o){let s=r(e.seo?.siteUrl,n(o));return{name:a(e)||new URL(s).host,version:t(),description:i(s),websiteUrl:s}}export{o as docsServerInfo};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{isEntityScopeVisible as n}from"../../../../../shared/rbac/entity-scope.js";import{publicOrigin as r}from"../../../utils/request-origin.js";import{SKILL_ENTITY_TYPE as i}from"../../../types/skill-entity.js";async function a(a){if(a.config.skills?.hide===!0)return[];let o=await a.entities.list({type:i}),s=r(a.request),c=e=>n(e,a.request.teams,e=>a.logger?.warn(e));return o.flatMap(n=>{let{slug:r,title:i,description:o}=n.metadata??{};return typeof r!=`string`||!c(n)?[]:[{slug:r,title:i??r,description:o??``,uri:`${s}${e(t(r))}`,read:async()=>(await a.entities.load(n.key)).content}]})}export{a as loadSkillResources};
1
+ import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{SKILL_ENTITY_TYPE as n}from"../../../types/skill-entity.js";import{publicOrigin as r}from"../../../utils/request-origin.js";import{isEntityScopeVisible as i}from"../../../../../shared/rbac/entity-scope.js";async function a(a){if(a.config.skills?.hide===!0)return[];let o=await a.entities.list({type:n}),s=r(a.request),c=e=>i(e,a.request.teams,e=>a.logger?.warn(e));return o.flatMap(n=>{let{slug:r,title:i,description:o}=n.metadata??{};return typeof r!=`string`||!c(n)?[]:[{slug:r,title:i??r,description:o??``,uri:`${s}${e(t(r))}`,read:async()=>(await a.entities.load(n.key)).content}]})}export{a as loadSkillResources};
@@ -1 +1 @@
1
- import{stripPathPrefix as e,withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import"../../../../../../shared/constants/app-data.js";import{toAppData as n}from"../../../../../../shared/utils/app-data.js";import{normalizeRouteSlug as r}from"../../../../../../shared/utils/routes/normalize-route-slug.js";import{normalizeRoutePath as i}from"../../../../../../shared/utils/routes/normalize-route-path.js";import{filterRbacAnnotatedValue as a}from"../../../../../../shared/rbac/filter.js";import{FOLDER_SIDEBAR_FILENAME_REGEX as o,SIDEBAR_AGGREGATOR_LOADER_ID as s,SIDEBAR_PLUGIN_ID as c,isTabbedSidebar as l}from"../../../sidebar/index.js";import{readIgnoredRouteSlugs as u}from"../../ignored-routes.js";import{posix as d}from"node:path";const f=/* @__PURE__ */ new Set,p=/(?:\/index(?:\.html\.md|\.html|\.md)|\.md|\.html)$/;async function m(e){let[t,n]=await Promise.all([u(e.entities),e.pageMarkdown.listPages()]);return{pages:n.filter(e=>!t.has(e.slug)),isVisible:n=>!t.has(n)&&e.isSlugVisible(n)}}async function h(e){let[{pages:t,isVisible:n},i,o]=await Promise.all([m(e),w(e),T(e)]),s=o.filter(e=>typeof e.link==`string`&&e.external!==!0&&n(r(e.link))),c=new Map(t.map(e=>[e.slug,e.title])),l=/* @__PURE__ */ new Set,u=[],d=g(i.map(({path:e})=>e)),p=i.map(({path:e,value:t},n)=>({path:e,value:t,id:d[n],links:M(k(t))})),h=D(p.flatMap(({links:e})=>e.slice(0,1)));for(let{path:t,value:r,id:i,links:o}of p){for(let e of o)l.add(e);let d=N(k(a(r,e.request.teams)),e=>n(e)&&c.has(e));if(d.length===0)continue;let p=i===`/`,m=p?e.config.seo?.title||`Documentation`:i,g=O(t,d,s,c,p?f:h)||m;u.push({id:i,title:g,nodes:d})}u.sort((e,t)=>Number(t.id===`/`)-Number(e.id===`/`));let _=t.filter(e=>!l.has(e.slug)).map(e=>({type:`page`,label:e.title,link:e.slug,items:[]}));return _.length>0&&u.push({id:`other-pages`,title:`Other pages`,nodes:_}),{sections:u,pages:t}}function g(e){let t=e.map(e=>{let t=d.dirname(e);return t===`.`?`/`:t}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e,(n.get(e)??0)+1);return e.map((e,r)=>{let i=t[r],a=!o.test(e),s=(n.get(i)??0)>1;return a&&s?e:i})}function _(e){let t=(e,n)=>n.flatMap(n=>{if(n.type!==`section`)return[];let r=v(e,n.label);return[{id:r,title:n.label,link:n.link,nodes:n.items},...t(r,n.items)]});return e.flatMap(e=>[e,...t(e.id,e.nodes)])}function v(e,t){return`${e} > ${t}`}function y(e,t,n){let r=_(e),i=t.trim().toLowerCase(),a=r.find(e=>e.id.toLowerCase()===i);if(a)return a;let o=C(t,n),s=r.find(e=>e.link!==void 0&&e.link===o);if(s)return s;let c=r.filter(e=>e.title.toLowerCase()===i);return c.find(e=>c.every(t=>t===e||t.id.startsWith(`${e.id} > `)))}function b(e){return e.flatMap(e=>[...e.link?[e.link]:[],...b(e.items)])}function x(e){return e.reduce((e,t)=>e+(t.type===`page`?1:x(t.items)),0)}function S(e,n){return`${n}${t(e)}`}function C(t,n){let r;try{r=new URL(t.trim(),n).pathname}catch{return null}let a=e(r)??r;return i(a.replace(p,``))}async function w(e){let t=(await e.entities.list({pluginId:c})).flatMap(e=>{let t=e.metadata?.sourcePath;return e.loaderId===s&&typeof t==`string`?[{path:t,key:e.key}]:[]});return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)),Promise.all(t.map(async({path:t,key:n})=>({path:t,value:await e.entities.load(n)})))}async function T(e){if(!await e.entities.get(`app-data`))return[];let t=n(await e.entities.load(`app-data`)).theme?.navbar?.items??[];return E(a(t,e.request.teams)??[])}function E(e){return e.flatMap(e=>[e,...E(e.items??[])])}function D(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}function O(e,t,n,r,i){let a=n.find(t=>Array.isArray(t.linkedSidebars)&&t.linkedSidebars.includes(e));if(typeof a?.label==`string`&&a.label!==``)return a.label;let o=t.find(e=>!e.link||!i.has(e.link));if(o)return o.link?r.get(o.link):o.label}function k(e){return e===null?[]:l(e)?e.tabs.map(A):e}function A(e){return{label:e.label,link:e.link,items:e.menu??e.items??[]}}function j(e){return e.link!==void 0&&e.external!==!0}function M(e){return e.flatMap(e=>[...j(e)&&e.link?[r(e.link)]:[],...M(e.items??[])])}function N(e,t){return e.flatMap(e=>{let n=j(e)&&e.link?r(e.link):void 0,i=n!==void 0&&t(n)?n:void 0;if(e.items){let n=N(e.items,t);return n.length===0&&!i?[]:[{type:`section`,label:e.label??``,...i?{link:i}:{},items:n}]}return i?[{type:`page`,label:e.label??i,link:i,items:[]}]:[]})}export{b as collectNodeLinks,x as countPages,y as findSection,_ as flattenSections,h as loadPageNavigation,m as loadVisiblePages,C as toPageSlug,S as toPublicUrl,v as toSectionId};
1
+ import{normalizeRouteSlug as e}from"../../../../../../shared/utils/routes/normalize-route-slug.js";import{normalizeRoutePath as t}from"../../../../../../shared/utils/routes/normalize-route-path.js";import"../../../../../../shared/constants/app-data.js";import{filterRbacAnnotatedValue as n}from"../../../../../../shared/rbac/filter.js";import{stripPathPrefix as r,withPathPrefix as i}from"../../../../../../shared/path-prefix.js";import{FOLDER_SIDEBAR_FILENAME_REGEX as a,SIDEBAR_AGGREGATOR_LOADER_ID as o,SIDEBAR_PLUGIN_ID as s,isTabbedSidebar as c}from"../../../sidebar/index.js";import{readIgnoredRouteSlugs as l}from"../../ignored-routes.js";import{toAppData as u}from"../../../../../../shared/utils/app-data.js";import{posix as d}from"node:path";const f=/* @__PURE__ */ new Set,p=/(?:\/index(?:\.html\.md|\.html|\.md)|\.md|\.html)$/;async function m(e){let[t,n]=await Promise.all([l(e.entities),e.pageMarkdown.listPages()]);return{pages:n.filter(e=>!t.has(e.slug)),isVisible:n=>!t.has(n)&&e.isSlugVisible(n)}}async function h(t){let[{pages:r,isVisible:i},a,o]=await Promise.all([m(t),w(t),T(t)]),s=o.filter(t=>typeof t.link==`string`&&t.external!==!0&&i(e(t.link))),c=new Map(r.map(e=>[e.slug,e.title])),l=/* @__PURE__ */ new Set,u=[],d=g(a.map(({path:e})=>e)),p=a.map(({path:e,value:t},n)=>({path:e,value:t,id:d[n],links:M(k(t))})),h=D(p.flatMap(({links:e})=>e.slice(0,1)));for(let{path:e,value:r,id:a,links:o}of p){for(let e of o)l.add(e);let d=N(k(n(r,t.request.teams)),e=>i(e)&&c.has(e));if(d.length===0)continue;let p=a===`/`,m=p?t.config.seo?.title||`Documentation`:a,g=O(e,d,s,c,p?f:h)||m;u.push({id:a,title:g,nodes:d})}u.sort((e,t)=>Number(t.id===`/`)-Number(e.id===`/`));let _=r.filter(e=>!l.has(e.slug)).map(e=>({type:`page`,label:e.title,link:e.slug,items:[]}));return _.length>0&&u.push({id:`other-pages`,title:`Other pages`,nodes:_}),{sections:u,pages:r}}function g(e){let t=e.map(e=>{let t=d.dirname(e);return t===`.`?`/`:t}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e,(n.get(e)??0)+1);return e.map((e,r)=>{let i=t[r],o=!a.test(e),s=(n.get(i)??0)>1;return o&&s?e:i})}function _(e){let t=(e,n)=>n.flatMap(n=>{if(n.type!==`section`)return[];let r=v(e,n.label);return[{id:r,title:n.label,link:n.link,nodes:n.items},...t(r,n.items)]});return e.flatMap(e=>[e,...t(e.id,e.nodes)])}function v(e,t){return`${e} > ${t}`}function y(e,t,n){let r=_(e),i=t.trim().toLowerCase(),a=r.find(e=>e.id.toLowerCase()===i);if(a)return a;let o=C(t,n),s=r.find(e=>e.link!==void 0&&e.link===o);if(s)return s;let c=r.filter(e=>e.title.toLowerCase()===i);return c.find(e=>c.every(t=>t===e||t.id.startsWith(`${e.id} > `)))}function b(e){return e.flatMap(e=>[...e.link?[e.link]:[],...b(e.items)])}function x(e){return e.reduce((e,t)=>e+(t.type===`page`?1:x(t.items)),0)}function S(e,t){return`${t}${i(e)}`}function C(e,n){let i;try{i=new URL(e.trim(),n).pathname}catch{return null}let a=r(i)??i;return t(a.replace(p,``))}async function w(e){let t=(await e.entities.list({pluginId:s})).flatMap(e=>{let t=e.metadata?.sourcePath;return e.loaderId===o&&typeof t==`string`?[{path:t,key:e.key}]:[]});return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)),Promise.all(t.map(async({path:t,key:n})=>({path:t,value:await e.entities.load(n)})))}async function T(e){if(!await e.entities.get(`app-data`))return[];let t=u(await e.entities.load(`app-data`)).theme?.navbar?.items??[];return E(n(t,e.request.teams)??[])}function E(e){return e.flatMap(e=>[e,...E(e.items??[])])}function D(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}function O(e,t,n,r,i){let a=n.find(t=>Array.isArray(t.linkedSidebars)&&t.linkedSidebars.includes(e));if(typeof a?.label==`string`&&a.label!==``)return a.label;let o=t.find(e=>!e.link||!i.has(e.link));if(o)return o.link?r.get(o.link):o.label}function k(e){return e===null?[]:c(e)?e.tabs.map(A):e}function A(e){return{label:e.label,link:e.link,items:e.menu??e.items??[]}}function j(e){return e.link!==void 0&&e.external!==!0}function M(t){return t.flatMap(t=>[...j(t)&&t.link?[e(t.link)]:[],...M(t.items??[])])}function N(t,n){return t.flatMap(t=>{let r=j(t)&&t.link?e(t.link):void 0,i=r!==void 0&&n(r)?r:void 0;if(t.items){let e=N(t.items,n);return e.length===0&&!i?[]:[{type:`section`,label:t.label??``,...i?{link:i}:{},items:e}]}return i?[{type:`page`,label:t.label??i,link:i,items:[]}]:[]})}export{b as collectNodeLinks,x as countPages,y as findSection,_ as flattenSections,h as loadPageNavigation,m as loadVisiblePages,C as toPageSlug,S as toPublicUrl,v as toSectionId};
@@ -1,4 +1,4 @@
1
- import{publicOrigin as e}from"../../../../utils/request-origin.js";import{readIgnoredRouteSlugs as t}from"../../ignored-routes.js";import{MAX_PAGE_LINES as n}from"./pages-constants.js";import{GET_PAGE_SCHEMA as r,GREP_PAGES_SCHEMA as i,LIST_PAGES_SCHEMA as a,grepPagesToolSchema as o,listPagesToolSchema as s}from"./schemas.js";import{recoveryToolNames as c}from"./openapi-document.js";import{collectNodeLinks as l,countPages as u,findSection as d,flattenSections as f,loadPageNavigation as p,loadVisiblePages as m,toPageSlug as h,toPublicUrl as g,toSectionId as _}from"./pages-navigation.js";const v=/^(#{1,3}) +(\S.*)$/,y=/^\s*(```|~~~)/,b={schema:a,schemaFor:e=>s(e.mcpMode),async execute(t,n){let{section:r}=t??{},{sections:i}=await p(n),a=e(n.request);if(!r)return{sections:i.map(e=>({id:e.id,title:e.title,items:w(e.id,e.nodes,a)}))};let o=d(i,r,a);if(!o){let e=f(i).slice(0,50).map(({id:e})=>e);throw Error(`No section "${r}". Pass one of these section ids: ${e.join(`; `)}.`)}return{section:{id:o.id,title:o.title},items:w(o.id,o.nodes,a)}}},x={schema:r,async execute(t,r){let{url:i,startLine:a,lines:o}=t??{};if(typeof i!=`string`||i.trim()===``)throw Error(`The "url" parameter is required: a page URL or path.`);let s=e(r.request),l=h(i,s),u=l===null?null:await C(l,r);if(l===null||u===null)throw Error(`No page you can read is at "${i}": it does not exist, or your access does not include it. Do not describe it from other pages. Call ${c(r.mcpMode).listPages} to see the pages you can read.`);let d=D(u.text),f=Math.max(1,Math.floor(a??1));if(f>d.length)throw Error(`Line ${f} is past the end of "${u.title??l}", which has ${d.length} lines.`);let p=T(o,200,n),m=Math.min(d.length,f+p-1);return{url:g(l,s),title:u.title??l,totalLines:d.length,startLine:f,endLine:m,...m<d.length?{nextStartLine:m+1}:{},outline:O(d),content:d.slice(f-1,m).join(`
2
- `)}}},S={schema:i,schemaFor:e=>o(e.mcpMode),async execute(t,n){let{query:r,section:i,maxMatches:a}=t??{};if(typeof r!=`string`||r===``)throw Error(`The "query" parameter is required: a text to find.`);let o=e(n.request),s,u;if(i){let{sections:e,pages:t}=await p(n),r=d(e,i,o);if(!r)throw Error(`No section "${i}". Call ${c(n.mcpMode).listPages} to see the sections.`);let a=new Set(l(r.nodes));r.link&&a.add(r.link),s=t.filter(e=>a.has(e.slug)),u=r.title}else s=(await m(n)).pages;let f=T(a,20,100),h=r.toLowerCase(),_=s.length,v=[];for(let e=0;e<s.length;e+=100){let t=s.slice(e,e+100),r=await Promise.all(t.map(async e=>(await n.pageMarkdown.readPage(e.slug))?.text??``));for(let[e,n]of t.entries()){let t=r[e];if(t.toLowerCase().includes(h))for(let[e,r]of D(t).entries()){let t=r.toLowerCase().indexOf(h);if(t!==-1){if(v.length===f)return{matches:v,searchedPages:_,truncated:!0};v.push({url:g(n.slug,o),title:n.title,line:e+1,text:E(r,t)})}}}}return v.length>0?{matches:v,searchedPages:_,truncated:!1}:{matches:v,searchedPages:_,truncated:!1,note:`No page you can read ${u?`in "${u}" contains "${r}". All ${_} pages there were searched.`:`contains "${r}". All ${_} pages were searched. API references are not searched: use ${c(n.mcpMode).listApis} for them.`}`}}};async function C(e,n){return(await t(n.entities)).has(e)?null:n.pageMarkdown.readPage(e)}function w(e,t,n){return t.map(t=>t.type===`page`?{type:`page`,title:t.label,url:g(t.link??``,n)}:{type:`section`,id:_(e,t.label),title:t.label,...t.link?{url:g(t.link,n)}:{},pageCount:u(t.items)})}function T(e,t,n){return Math.min(Math.max(1,Math.floor(e??t)),n)}function E(e,t){let n=Math.max(0,Math.min(t-80,e.length-200));return e.slice(n,n+200).trim()}function D(e){return(e.endsWith(`
1
+ import{readIgnoredRouteSlugs as e}from"../../ignored-routes.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{MAX_PAGE_LINES as n}from"./pages-constants.js";import{GET_PAGE_SCHEMA as r,GREP_PAGES_SCHEMA as i,LIST_PAGES_SCHEMA as a,grepPagesToolSchema as o,listPagesToolSchema as s}from"./schemas.js";import{recoveryToolNames as c}from"./openapi-document.js";import{collectNodeLinks as l,countPages as u,findSection as d,flattenSections as f,loadPageNavigation as p,loadVisiblePages as m,toPageSlug as h,toPublicUrl as g,toSectionId as _}from"./pages-navigation.js";const v=/^(#{1,3}) +(\S.*)$/,y=/^\s*(```|~~~)/,b={schema:a,schemaFor:e=>s(e.mcpMode),async execute(e,n){let{section:r}=e??{},{sections:i}=await p(n),a=t(n.request);if(!r)return{sections:i.map(e=>({id:e.id,title:e.title,items:w(e.id,e.nodes,a)}))};let o=d(i,r,a);if(!o){let e=f(i).slice(0,50).map(({id:e})=>e);throw Error(`No section "${r}". Pass one of these section ids: ${e.join(`; `)}.`)}return{section:{id:o.id,title:o.title},items:w(o.id,o.nodes,a)}}},x={schema:r,async execute(e,r){let{url:i,startLine:a,lines:o}=e??{};if(typeof i!=`string`||i.trim()===``)throw Error(`The "url" parameter is required: a page URL or path.`);let s=t(r.request),l=h(i,s),u=l===null?null:await C(l,r);if(l===null||u===null)throw Error(`No page you can read is at "${i}": it does not exist, or your access does not include it. Do not describe it from other pages. Call ${c(r.mcpMode).listPages} to see the pages you can read.`);let d=D(u.text),f=Math.max(1,Math.floor(a??1));if(f>d.length)throw Error(`Line ${f} is past the end of "${u.title??l}", which has ${d.length} lines.`);let p=T(o,200,n),m=Math.min(d.length,f+p-1);return{url:g(l,s),title:u.title??l,totalLines:d.length,startLine:f,endLine:m,...m<d.length?{nextStartLine:m+1}:{},outline:O(d),content:d.slice(f-1,m).join(`
2
+ `)}}},S={schema:i,schemaFor:e=>o(e.mcpMode),async execute(e,n){let{query:r,section:i,maxMatches:a}=e??{};if(typeof r!=`string`||r===``)throw Error(`The "query" parameter is required: a text to find.`);let o=t(n.request),s,u;if(i){let{sections:e,pages:t}=await p(n),r=d(e,i,o);if(!r)throw Error(`No section "${i}". Call ${c(n.mcpMode).listPages} to see the sections.`);let a=new Set(l(r.nodes));r.link&&a.add(r.link),s=t.filter(e=>a.has(e.slug)),u=r.title}else s=(await m(n)).pages;let f=T(a,20,100),h=r.toLowerCase(),_=s.length,v=[];for(let e=0;e<s.length;e+=100){let t=s.slice(e,e+100),r=await Promise.all(t.map(async e=>(await n.pageMarkdown.readPage(e.slug))?.text??``));for(let[e,n]of t.entries()){let t=r[e];if(t.toLowerCase().includes(h))for(let[e,r]of D(t).entries()){let t=r.toLowerCase().indexOf(h);if(t!==-1){if(v.length===f)return{matches:v,searchedPages:_,truncated:!0};v.push({url:g(n.slug,o),title:n.title,line:e+1,text:E(r,t)})}}}}return v.length>0?{matches:v,searchedPages:_,truncated:!1}:{matches:v,searchedPages:_,truncated:!1,note:`No page you can read ${u?`in "${u}" contains "${r}". All ${_} pages there were searched.`:`contains "${r}". All ${_} pages were searched. API references are not searched: use ${c(n.mcpMode).listApis} for them.`}`}}};async function C(t,n){return(await e(n.entities)).has(t)?null:n.pageMarkdown.readPage(t)}function w(e,t,n){return t.map(t=>t.type===`page`?{type:`page`,title:t.label,url:g(t.link??``,n)}:{type:`section`,id:_(e,t.label),title:t.label,...t.link?{url:g(t.link,n)}:{},pageCount:u(t.items)})}function T(e,t,n){return Math.min(Math.max(1,Math.floor(e??t)),n)}function E(e,t){let n=Math.max(0,Math.min(t-80,e.length-200));return e.slice(n,n+200).trim()}function D(e){return(e.endsWith(`
3
3
  `)?e.slice(0,-1):e).split(`
4
4
  `)}function O(e){let t=[],n=!1;return e.forEach((e,r)=>{if(y.test(e)){n=!n;return}let i=n?null:v.exec(e);i&&t.push({line:r+1,level:i[1].length,heading:i[2].trim()})}),t}const k=[b,x,S];export{k as pageTools};
@@ -1 +1 @@
1
- import{OPERATION_METHODS as e}from"../../../../../../shared/constants/openapi-operation-methods.js";import{READ_ONLY_ANNOTATIONS as t,SUBMIT_FEEDBACK_TOOL_NAME as n}from"../../constants.js";import{toolNameForMode as r}from"../codemode/tool-declarations.js";import{GRAPHQL_LIST_SCOPES as i,GRAPHQL_TYPE_KINDS as a}from"./graphql-constants.js";import{MAX_PAGE_LINES as o}from"./pages-constants.js";const s={type:`string`,nullable:!0},c={limit:{type:`number`},total:{type:`number`},page:{type:`number`},totalPages:{type:`number`}},l={codemodeType:`OpenApiServer[]`},u={codemodeType:`OpenApiSecurityRequirement[]`},d={codemodeType:`Record<string, OpenApiSecurityScheme>`},f={codemodeType:`OpenApiDocument`},p={codemodeType:`OpenApiOperation & { path: string; method: string }`},m={codemodeType:`OpenApiComponents`,description:"Components the endpoint references. A `$ref` in `endpoint` resolves against the root of the result."},h={filePath:{type:`string`,description:`API definition file path`},otherMatches:{type:`array`,description:"Other API definitions the lookup also matched. Present only when several matched; pass `filePath` to pick another one",items:{type:`object`,required:[`filePath`],properties:{version:{type:`string`},filePath:{type:`string`}}}}},g="When several definitions match the name, the highest version or the shortest file path is used and the rest are listed in `otherMatches`; tell the user which version or file the answer is based on.";function _(e,n){let r={query:{type:`string`,description:`What to find, as a few words or a short question.`,minLength:1}};return e.length>0&&(r.product={type:`string`,description:`Optional product name to filter search results by specific product.`,enum:[...e,null],nullable:!0}),n.length>0&&(r.locale={type:`string`,description:`Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the site's default locale.`,enum:[...n,null],nullable:!0}),{name:`search`,title:`Search documentation`,description:`Search the documentation. Returns Markdown text: one section per matching page, with its title and URL as a link.`,summary:`Search the documentation.`,schema:{type:`object`,required:[`query`],additionalProperties:!1,properties:r},annotations:t,outputSchema:{type:`string`}}}const v=_([],[]),y={name:`whoami`,title:`Who am I`,description:`Get information about the currently authenticated user`,summary:`Get the signed-in user.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:t,outputSchema:{type:`object`,required:[`authenticated`],properties:{authenticated:{type:`boolean`},email:{type:`string`},name:{type:`string`},subject:{type:`string`},clientId:{type:`string`},scope:{type:`string`},issuedAt:{type:`string`},expiresAt:{type:`string`}}}},b={name:n,title:`Submit feedback`,description:`Report a documentation page that is wrong or incomplete. Use it when the user reports a problem with a page on this site, or agrees to report a problem that you found. Do not use it for product bugs or support questions.`,schema:{type:`object`,required:[`path`,`summary`],additionalProperties:!1,properties:{path:{type:`string`,description:`Path or URL of the documentation page the feedback is about (e.g. /guides/auth)`,minLength:1,maxLength:1e3},summary:{type:`string`,description:`One sentence that names what is wrong with the page`,minLength:1,maxLength:500},details:{type:`string`,description:`Expected versus actual behavior, missing steps, or the snippet that failed`,maxLength:4e3,nullable:!0},targetFeature:{type:`string`,description:`The API or feature the page documents`,maxLength:500,nullable:!0}}},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},outputSchema:{type:`object`,required:[`status`,`page`,`message`],properties:{status:{type:`string`},page:{type:`string`},message:{type:`string`}}}},x={type:`object`,additionalProperties:!1,required:[],properties:{filter:{type:`string`,description:`Matches part of an API name, or of a description when no name matches`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of APIs per page. Default is 300`,minimum:1,default:300,nullable:!0}}};function S(e){return{type:`string`,description:`API definition file path, as returned by \`${r(`list-apis`,e)}\``,nullable:!0}}function C(e){return{type:`object`,required:[],additionalProperties:!1,properties:{name:{type:`string`,description:"API name, or a unique part of it. Required when the project documents more than one API, unless `filePath` is given.",minLength:1,nullable:!0},version:{type:`string`,description:`API version. When omitted and several versions exist, the highest one is used`,nullable:!0},filePath:S(e)}}}function w(t){let{name:n,version:r,filePath:i}=C(t).properties;return{type:`object`,required:[`path`,`method`],additionalProperties:!1,properties:{name:n,path:{type:`string`,description:`Endpoint path (e.g. /api/v1/users)`,minLength:1},method:{type:`string`,description:`HTTP method (GET, POST, PUT, DELETE, etc.)`,enum:[...e.map(e=>e.toUpperCase()),...e],minLength:1},version:r,filePath:i}}}function T(e){let n={name:{type:`string`},description:{type:`string`},version:{type:`string`},servers:l,filePath:{type:`string`,description:`API definition file path`},ambiguousTitle:{type:`boolean`,description:"true = another API shares this title; a lookup picks the highest version, or the shortest file path at the same version, and lists the rest in `otherMatches`. Pass `filePath` to pick another one"}};return e&&(n.callable={type:`boolean`,description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}),{name:`list-apis`,title:`List APIs`,description:`Lists the APIs documented on this site`,summary:`List the available APIs.`,schema:x,annotations:t,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`,`description`,`version`,`servers`,`filePath`],properties:n}},...c}}}}const E=T(!1),D=T(!0);function O(e){return{name:`get-endpoints`,title:`Get endpoints`,description:`Get all endpoints for a specific API. ${g}`,summary:`Get all endpoints for an API.`,schema:C(e),annotations:t,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoints`],properties:{api:{type:`string`},version:{type:`string`},...h,servers:l,endpoints:{type:`array`,items:{type:`object`,required:[`path`,`method`],properties:{path:{type:`string`},method:{type:`string`},summary:s,description:s,security:u}}}}}}}const k=O(`tools`);function A(e){return{name:`get-endpoint-info`,title:`Get endpoint info`,description:`Get comprehensive information about specific endpoint including parameters, security, and examples. A \`$ref\` in \`endpoint\` points into the \`components\` key at the root of the result: read \`#/components/<section>/<name>\` there. ${g}`,summary:`Get the details of an endpoint.`,schema:w(e),annotations:t,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoint`,`globalSecurity`,`securitySchemes`],properties:{api:{type:`string`},version:{type:`string`},...h,servers:l,endpoint:p,globalSecurity:u,securitySchemes:d,components:m}}}}const j=A(`tools`);function M(e){return{name:`get-security-schemes`,title:`Get security schemes`,description:`Get the security schemes for a specific API. ${g}`,summary:`Get the security schemes for an API.`,schema:C(e),annotations:t,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`securitySchemes`,`security`],properties:{api:{type:`string`},version:{type:`string`},...h,securitySchemes:d,security:u}}}}const N=M(`tools`);function P(e){return{name:`get-full-api-description`,title:`Get full API description`,description:`Get the complete OpenAPI description. ${g}`,summary:`Get the complete OpenAPI description.`,schema:C(e),annotations:t,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`definition`],properties:{api:{type:`string`},version:{type:`string`},...h,definition:f}}}}const F=P(`tools`),I={type:`object`,required:[],additionalProperties:!1,properties:{filter:{type:`string`,description:`GraphQL schema name (or part of it)`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},L={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},kind:{type:`string`,description:`Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).`,enum:[...a,null],nullable:!0},scope:{type:`string`,description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions — combine with `filter` to search nested fields anywhere in the schema.',enum:[...i,null],nullable:!0},filter:{type:`string`,description:`Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")`,minLength:1,nullable:!0},referencesType:{type:`string`,description:`Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it — e.g. referencesType "Book" surfaces a search query returning a union that includes Book.`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},R={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},type:{type:`string`,description:`Name of the type, operation, or directive`,minLength:1,nullable:!0},includeReferencedTypes:{type:`boolean`,description:`Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.`,default:!1,nullable:!0}}},z={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1}}},B={name:`list-graphql-apis`,title:`List GraphQL APIs`,description:`Lists available GraphQL schemas with their context and purpose`,summary:`List the available GraphQL schemas.`,schema:I,annotations:t,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`],properties:{name:{type:`string`},description:s}}},...c}}},V={name:`get-graphql-type-list`,title:`Get GraphQL type list`,description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, …) and carries a one-line description; operations also include their return type and argument signature — use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields — not just type names — set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',summary:`List the operations and types in a GraphQL schema.`,schema:L,annotations:t,outputSchema:{type:`object`,required:[`name`,`items`,`limit`,`total`,`page`,`totalPages`],properties:{name:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`kind`,`name`],properties:{kind:{type:`string`,enum:[...a]},name:{type:`string`},description:s,type:{type:`string`},args:{type:`string`},directives:{type:`string`}}}},...c}}};function H(e){return{name:`get-graphql-type`,title:`Get GraphQL type`,description:`Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type's field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively — the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call ${r(`get-graphql-type-list`,e)} with \`referencesType\`.`,summary:`Get the SDL of one GraphQL type or operation.`,schema:R,annotations:t,outputSchema:{type:`string`}}}const U=H(`tools`);function W(e){return{name:`get-graphql-schema`,title:`Get GraphQL schema`,description:`Get the complete GraphQL schema as SDL — the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer ${r(`get-graphql-type-list`,e)} (filter/paginate) plus targeted ${r(`get-graphql-type`,e)} calls, and reach for this only for small schemas or when you truly need the full SDL.`,summary:`Get the complete GraphQL schema.`,schema:z,annotations:t,outputSchema:{type:`string`}}}const G=W(`tools`);function K(e){return`Section id from ${r(`list-pages`,e)} (for example "products/ledger > Integration"), a section title, or a section URL`}function q(e){return{type:`object`,required:[`type`,`title`],properties:{type:{type:`string`,enum:[`page`,`section`]},id:{type:`string`,description:`Section id to pass to ${r(`list-pages`,e)} or ${r(`grep-pages`,e)}`},title:{type:`string`},url:{type:`string`},pageCount:{type:`number`,description:`Pages inside the section`}}}}function J(e){let n=q(e);return{name:`list-pages`,title:`List pages`,description:`Lists the docs navigation, one level per call`,summary:`List the docs navigation, one level per call.`,schema:{type:`object`,additionalProperties:!1,required:[],properties:{section:{type:`string`,nullable:!0,description:`${K(e)}. Omit it to list the top level`}}},annotations:t,outputSchema:{type:`object`,properties:{sections:{type:`array`,description:`Top level, when no section is given`,items:{type:`object`,required:[`id`,`title`,`items`],properties:{id:{type:`string`},title:{type:`string`},items:{type:`array`,items:n}}}},section:{type:`object`,properties:{id:{type:`string`},title:{type:`string`}}},items:{type:`array`,items:n}}}}}const Y=J(`tools`),X={name:`get-page`,title:`Get page`,description:`Reads a docs page as Markdown, in line windows`,summary:`Read a docs page as Markdown, in line windows.`,schema:{type:`object`,additionalProperties:!1,required:[`url`],properties:{url:{type:`string`,minLength:1,description:`Page URL or path, for example "/guides/auth"`},startLine:{type:`integer`,nullable:!0,minimum:1,description:`First line to return (default 1)`},lines:{type:`integer`,nullable:!0,minimum:1,maximum:o,description:`Number of lines to return (default 200)`}}},annotations:t,outputSchema:{type:`object`,required:[`url`,`title`,`totalLines`,`startLine`,`endLine`,`outline`,`content`],properties:{url:{type:`string`},title:{type:`string`},totalLines:{type:`number`},startLine:{type:`number`},endLine:{type:`number`},nextStartLine:{type:`number`,description:`Pass as startLine to read on; absent at the end`},outline:{type:`array`,description:`Headings (levels 1-3) with their line numbers`,items:{type:`object`,required:[`line`,`level`,`heading`],properties:{line:{type:`number`},level:{type:`number`},heading:{type:`string`}}}},content:{type:`string`}}}};function Z(e){return{name:`grep-pages`,title:`Grep pages`,description:`Finds the docs lines that contain a text`,summary:`Find the docs lines that contain a text.`,schema:{type:`object`,additionalProperties:!1,required:[`query`],properties:{query:{type:`string`,minLength:1,description:`Text to find, case-insensitive. Not a regular expression`},section:{type:`string`,nullable:!0,description:`${K(e)}. Omit it to search every page`},maxMatches:{type:`integer`,nullable:!0,minimum:1,maximum:100,description:`Maximum matching lines to return (default 20)`}}},annotations:t,outputSchema:{type:`object`,required:[`matches`,`searchedPages`,`truncated`],properties:{matches:{type:`array`,items:{type:`object`,required:[`url`,`title`,`line`,`text`],properties:{url:{type:`string`},title:{type:`string`},line:{type:`number`},text:{type:`string`}}}},searchedPages:{type:`number`,description:`Pages searched: every page you can read, or every page in the section`},truncated:{type:`boolean`,description:`true = more matches exist; narrow the query or the section`},note:{type:`string`,description:`Present when nothing matches: the docs you can read do not contain the text`}}}}}const Q=Z(`tools`);export{k as GET_ENDPOINTS_SCHEMA,j as GET_ENDPOINT_INFO_SCHEMA,F as GET_FULL_API_DESCRIPTION_SCHEMA,G as GET_GRAPHQL_SCHEMA_SCHEMA,V as GET_GRAPHQL_TYPE_LIST_SCHEMA,U as GET_GRAPHQL_TYPE_SCHEMA,X as GET_PAGE_SCHEMA,N as GET_SECURITY_SCHEMES_SCHEMA,Q as GREP_PAGES_SCHEMA,D as LIST_APIS_CALLABLE_SCHEMA,E as LIST_APIS_SCHEMA,B as LIST_GRAPHQL_APIS_SCHEMA,Y as LIST_PAGES_SCHEMA,v as SEARCH_SCHEMA,b as SUBMIT_FEEDBACK_SCHEMA,y as WHOAMI_SCHEMA,A as getEndpointInfoToolSchema,O as getEndpointsToolSchema,P as getFullApiDescriptionToolSchema,W as getGraphqlSchemaToolSchema,H as getGraphqlTypeToolSchema,M as getSecuritySchemesToolSchema,Z as grepPagesToolSchema,J as listPagesToolSchema,_ as searchSchema};
1
+ import{READ_ONLY_ANNOTATIONS as e,SUBMIT_FEEDBACK_TOOL_NAME as t}from"../../constants.js";import{OPERATION_METHODS as n}from"../../../../../../shared/constants/openapi-operation-methods.js";import{toolNameForMode as r}from"../codemode/tool-declarations.js";import{GRAPHQL_LIST_SCOPES as i,GRAPHQL_TYPE_KINDS as a}from"./graphql-constants.js";import{MAX_PAGE_LINES as o}from"./pages-constants.js";const s={type:`string`,nullable:!0},c={limit:{type:`number`},total:{type:`number`},page:{type:`number`},totalPages:{type:`number`}},l={codemodeType:`OpenApiServer[]`},u={codemodeType:`OpenApiSecurityRequirement[]`},d={codemodeType:`Record<string, OpenApiSecurityScheme>`},f={codemodeType:`OpenApiDocument`},p={codemodeType:`OpenApiOperation & { path: string; method: string }`},m={codemodeType:`OpenApiComponents`,description:"Components the endpoint references. A `$ref` in `endpoint` resolves against the root of the result."},h={filePath:{type:`string`,description:`API definition file path`},otherMatches:{type:`array`,description:"Other API definitions the lookup also matched. Present only when several matched; pass `filePath` to pick another one",items:{type:`object`,required:[`filePath`],properties:{version:{type:`string`},filePath:{type:`string`}}}}},g="When several definitions match the name, the highest version or the shortest file path is used and the rest are listed in `otherMatches`; tell the user which version or file the answer is based on.";function _(t,n){let r={query:{type:`string`,description:`What to find, as a few words or a short question.`,minLength:1}};return t.length>0&&(r.product={type:`string`,description:`Optional product name to filter search results by specific product.`,enum:[...t,null],nullable:!0}),n.length>0&&(r.locale={type:`string`,description:`Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the site's default locale.`,enum:[...n,null],nullable:!0}),{name:`search`,title:`Search documentation`,description:`Search the documentation. Returns Markdown text: one section per matching page, with its title and URL as a link.`,summary:`Search the documentation.`,schema:{type:`object`,required:[`query`],additionalProperties:!1,properties:r},annotations:e,outputSchema:{type:`string`}}}const v=_([],[]),y={name:`whoami`,title:`Who am I`,description:`Get information about the currently authenticated user`,summary:`Get the signed-in user.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:e,outputSchema:{type:`object`,required:[`authenticated`],properties:{authenticated:{type:`boolean`},email:{type:`string`},name:{type:`string`},subject:{type:`string`},clientId:{type:`string`},scope:{type:`string`},issuedAt:{type:`string`},expiresAt:{type:`string`}}}},b={name:t,title:`Submit feedback`,description:`Report a documentation page that is wrong or incomplete. Use it when the user reports a problem with a page on this site, or agrees to report a problem that you found. Do not use it for product bugs or support questions.`,schema:{type:`object`,required:[`path`,`summary`],additionalProperties:!1,properties:{path:{type:`string`,description:`Path or URL of the documentation page the feedback is about (e.g. /guides/auth)`,minLength:1,maxLength:1e3},summary:{type:`string`,description:`One sentence that names what is wrong with the page`,minLength:1,maxLength:500},details:{type:`string`,description:`Expected versus actual behavior, missing steps, or the snippet that failed`,maxLength:4e3,nullable:!0},targetFeature:{type:`string`,description:`The API or feature the page documents`,maxLength:500,nullable:!0}}},annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0},outputSchema:{type:`object`,required:[`status`,`page`,`message`],properties:{status:{type:`string`},page:{type:`string`},message:{type:`string`}}}},x={type:`object`,additionalProperties:!1,required:[],properties:{filter:{type:`string`,description:`Matches part of an API name, or of a description when no name matches`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of APIs per page. Default is 300`,minimum:1,default:300,nullable:!0}}};function S(e){return{type:`string`,description:`API definition file path, as returned by \`${r(`list-apis`,e)}\``,nullable:!0}}function C(e){return{type:`object`,required:[],additionalProperties:!1,properties:{name:{type:`string`,description:"API name, or a unique part of it. Required when the project documents more than one API, unless `filePath` is given.",minLength:1,nullable:!0},version:{type:`string`,description:`API version. When omitted and several versions exist, the highest one is used`,nullable:!0},filePath:S(e)}}}function w(e){let{name:t,version:r,filePath:i}=C(e).properties;return{type:`object`,required:[`path`,`method`],additionalProperties:!1,properties:{name:t,path:{type:`string`,description:`Endpoint path (e.g. /api/v1/users)`,minLength:1},method:{type:`string`,description:`HTTP method (GET, POST, PUT, DELETE, etc.)`,enum:[...n.map(e=>e.toUpperCase()),...n],minLength:1},version:r,filePath:i}}}function T(t){let n={name:{type:`string`},description:{type:`string`},version:{type:`string`},servers:l,filePath:{type:`string`,description:`API definition file path`},ambiguousTitle:{type:`boolean`,description:"true = another API shares this title; a lookup picks the highest version, or the shortest file path at the same version, and lists the rest in `otherMatches`. Pass `filePath` to pick another one"}};return t&&(n.callable={type:`boolean`,description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}),{name:`list-apis`,title:`List APIs`,description:`Lists the APIs documented on this site`,summary:`List the available APIs.`,schema:x,annotations:e,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`,`description`,`version`,`servers`,`filePath`],properties:n}},...c}}}}const E=T(!1),D=T(!0);function O(t){return{name:`get-endpoints`,title:`Get endpoints`,description:`Get all endpoints for a specific API. ${g}`,summary:`Get all endpoints for an API.`,schema:C(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoints`],properties:{api:{type:`string`},version:{type:`string`},...h,servers:l,endpoints:{type:`array`,items:{type:`object`,required:[`path`,`method`],properties:{path:{type:`string`},method:{type:`string`},summary:s,description:s,security:u}}}}}}}const k=O(`tools`);function A(t){return{name:`get-endpoint-info`,title:`Get endpoint info`,description:`Get comprehensive information about specific endpoint including parameters, security, and examples. A \`$ref\` in \`endpoint\` points into the \`components\` key at the root of the result: read \`#/components/<section>/<name>\` there. ${g}`,summary:`Get the details of an endpoint.`,schema:w(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`servers`,`endpoint`,`globalSecurity`,`securitySchemes`],properties:{api:{type:`string`},version:{type:`string`},...h,servers:l,endpoint:p,globalSecurity:u,securitySchemes:d,components:m}}}}const j=A(`tools`);function M(t){return{name:`get-security-schemes`,title:`Get security schemes`,description:`Get the security schemes for a specific API. ${g}`,summary:`Get the security schemes for an API.`,schema:C(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`securitySchemes`,`security`],properties:{api:{type:`string`},version:{type:`string`},...h,securitySchemes:d,security:u}}}}const N=M(`tools`);function P(t){return{name:`get-full-api-description`,title:`Get full API description`,description:`Get the complete OpenAPI description. ${g}`,summary:`Get the complete OpenAPI description.`,schema:C(t),annotations:e,outputSchema:{type:`object`,required:[`api`,`version`,`filePath`,`definition`],properties:{api:{type:`string`},version:{type:`string`},...h,definition:f}}}}const F=P(`tools`),I={type:`object`,required:[],additionalProperties:!1,properties:{filter:{type:`string`,description:`GraphQL schema name (or part of it)`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},L={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},kind:{type:`string`,description:`Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).`,enum:[...a,null],nullable:!0},scope:{type:`string`,description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions — combine with `filter` to search nested fields anywhere in the schema.',enum:[...i,null],nullable:!0},filter:{type:`string`,description:`Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")`,minLength:1,nullable:!0},referencesType:{type:`string`,description:`Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it — e.g. referencesType "Book" surfaces a search query returning a union that includes Book.`,minLength:1,nullable:!0},page:{type:`number`,description:`Page number`,minimum:1,default:1,nullable:!0},limit:{type:`number`,description:`Number of results per page. Default is 300`,minimum:1,default:300,nullable:!0}}},R={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1},type:{type:`string`,description:`Name of the type, operation, or directive`,minLength:1,nullable:!0},includeReferencedTypes:{type:`boolean`,description:`Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.`,default:!1,nullable:!0}}},z={type:`object`,required:[`name`],additionalProperties:!1,properties:{name:{type:`string`,description:`GraphQL schema name`,minLength:1}}},B={name:`list-graphql-apis`,title:`List GraphQL APIs`,description:`Lists available GraphQL schemas with their context and purpose`,summary:`List the available GraphQL schemas.`,schema:I,annotations:e,outputSchema:{type:`object`,required:[`items`,`limit`,`total`,`page`,`totalPages`],properties:{items:{type:`array`,items:{type:`object`,required:[`name`],properties:{name:{type:`string`},description:s}}},...c}}},V={name:`get-graphql-type-list`,title:`Get GraphQL type list`,description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, …) and carries a one-line description; operations also include their return type and argument signature — use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields — not just type names — set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',summary:`List the operations and types in a GraphQL schema.`,schema:L,annotations:e,outputSchema:{type:`object`,required:[`name`,`items`,`limit`,`total`,`page`,`totalPages`],properties:{name:{type:`string`},items:{type:`array`,items:{type:`object`,required:[`kind`,`name`],properties:{kind:{type:`string`,enum:[...a]},name:{type:`string`},description:s,type:{type:`string`},args:{type:`string`},directives:{type:`string`}}}},...c}}};function H(t){return{name:`get-graphql-type`,title:`Get GraphQL type`,description:`Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type's field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively — the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call ${r(`get-graphql-type-list`,t)} with \`referencesType\`.`,summary:`Get the SDL of one GraphQL type or operation.`,schema:R,annotations:e,outputSchema:{type:`string`}}}const U=H(`tools`);function W(t){return{name:`get-graphql-schema`,title:`Get GraphQL schema`,description:`Get the complete GraphQL schema as SDL — the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer ${r(`get-graphql-type-list`,t)} (filter/paginate) plus targeted ${r(`get-graphql-type`,t)} calls, and reach for this only for small schemas or when you truly need the full SDL.`,summary:`Get the complete GraphQL schema.`,schema:z,annotations:e,outputSchema:{type:`string`}}}const G=W(`tools`);function K(e){return`Section id from ${r(`list-pages`,e)} (for example "products/ledger > Integration"), a section title, or a section URL`}function q(e){return{type:`object`,required:[`type`,`title`],properties:{type:{type:`string`,enum:[`page`,`section`]},id:{type:`string`,description:`Section id to pass to ${r(`list-pages`,e)} or ${r(`grep-pages`,e)}`},title:{type:`string`},url:{type:`string`},pageCount:{type:`number`,description:`Pages inside the section`}}}}function J(t){let n=q(t);return{name:`list-pages`,title:`List pages`,description:`Lists the docs navigation, one level per call`,summary:`List the docs navigation, one level per call.`,schema:{type:`object`,additionalProperties:!1,required:[],properties:{section:{type:`string`,nullable:!0,description:`${K(t)}. Omit it to list the top level`}}},annotations:e,outputSchema:{type:`object`,properties:{sections:{type:`array`,description:`Top level, when no section is given`,items:{type:`object`,required:[`id`,`title`,`items`],properties:{id:{type:`string`},title:{type:`string`},items:{type:`array`,items:n}}}},section:{type:`object`,properties:{id:{type:`string`},title:{type:`string`}}},items:{type:`array`,items:n}}}}}const Y=J(`tools`),X={name:`get-page`,title:`Get page`,description:`Reads a docs page as Markdown, in line windows`,summary:`Read a docs page as Markdown, in line windows.`,schema:{type:`object`,additionalProperties:!1,required:[`url`],properties:{url:{type:`string`,minLength:1,description:`Page URL or path, for example "/guides/auth"`},startLine:{type:`integer`,nullable:!0,minimum:1,description:`First line to return (default 1)`},lines:{type:`integer`,nullable:!0,minimum:1,maximum:o,description:`Number of lines to return (default 200)`}}},annotations:e,outputSchema:{type:`object`,required:[`url`,`title`,`totalLines`,`startLine`,`endLine`,`outline`,`content`],properties:{url:{type:`string`},title:{type:`string`},totalLines:{type:`number`},startLine:{type:`number`},endLine:{type:`number`},nextStartLine:{type:`number`,description:`Pass as startLine to read on; absent at the end`},outline:{type:`array`,description:`Headings (levels 1-3) with their line numbers`,items:{type:`object`,required:[`line`,`level`,`heading`],properties:{line:{type:`number`},level:{type:`number`},heading:{type:`string`}}}},content:{type:`string`}}}};function Z(t){return{name:`grep-pages`,title:`Grep pages`,description:`Finds the docs lines that contain a text`,summary:`Find the docs lines that contain a text.`,schema:{type:`object`,additionalProperties:!1,required:[`query`],properties:{query:{type:`string`,minLength:1,description:`Text to find, case-insensitive. Not a regular expression`},section:{type:`string`,nullable:!0,description:`${K(t)}. Omit it to search every page`},maxMatches:{type:`integer`,nullable:!0,minimum:1,maximum:100,description:`Maximum matching lines to return (default 20)`}}},annotations:e,outputSchema:{type:`object`,required:[`matches`,`searchedPages`,`truncated`],properties:{matches:{type:`array`,items:{type:`object`,required:[`url`,`title`,`line`,`text`],properties:{url:{type:`string`},title:{type:`string`},line:{type:`number`},text:{type:`string`}}}},searchedPages:{type:`number`,description:`Pages searched: every page you can read, or every page in the section`},truncated:{type:`boolean`,description:`true = more matches exist; narrow the query or the section`},note:{type:`string`,description:`Present when nothing matches: the docs you can read do not contain the text`}}}}}const Q=Z(`tools`);export{k as GET_ENDPOINTS_SCHEMA,j as GET_ENDPOINT_INFO_SCHEMA,F as GET_FULL_API_DESCRIPTION_SCHEMA,G as GET_GRAPHQL_SCHEMA_SCHEMA,V as GET_GRAPHQL_TYPE_LIST_SCHEMA,U as GET_GRAPHQL_TYPE_SCHEMA,X as GET_PAGE_SCHEMA,N as GET_SECURITY_SCHEMES_SCHEMA,Q as GREP_PAGES_SCHEMA,D as LIST_APIS_CALLABLE_SCHEMA,E as LIST_APIS_SCHEMA,B as LIST_GRAPHQL_APIS_SCHEMA,Y as LIST_PAGES_SCHEMA,v as SEARCH_SCHEMA,b as SUBMIT_FEEDBACK_SCHEMA,y as WHOAMI_SCHEMA,A as getEndpointInfoToolSchema,O as getEndpointsToolSchema,P as getFullApiDescriptionToolSchema,W as getGraphqlSchemaToolSchema,H as getGraphqlTypeToolSchema,M as getSecuritySchemesToolSchema,Z as grepPagesToolSchema,J as listPagesToolSchema,_ as searchSchema};
@@ -1,3 +1,3 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{normalizeL10nConfig as t}from"../../../../../../shared/utils/l10n.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as r}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as i,fetchSemanticSearchDocuments as a,filterSemanticSearchDocuments as o}from"../semantic-search.js";import{readIgnoredRouteSlugs as s}from"../../ignored-routes.js";import{SEARCH_SCHEMA as c,searchSchema as l}from"./schemas.js";const u=`No results found.`;function d(t,n){let r=t=>{try{return new URL(e(t),n).toString()}catch{return t}};return t.map(e=>`### [${e.title}](${r(e.url)})\n\n${e.content}\n`).join(`
1
+ import{normalizeL10nConfig as e}from"../../../../../../shared/utils/l10n.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{resolveDocsSiteUrl as c}from"../docs-site-url.js";import{SEARCH_SCHEMA as l,searchSchema as u}from"./schemas.js";const d=`No results found.`;function f(e,n){let r=e=>{try{return new URL(t(e),n).toString()}catch{return e}};return e.map(e=>`### [${e.title}](${r(e.url)})\n\n${e.content}\n`).join(`
2
2
 
3
- `).trim()}const f=[{schema:c,schemaFor:e=>l(Object.values(e.config.products??{}).map(e=>e.name),t(e.config.l10n).locales?.map(e=>e.code)??[]),isAvailable:()=>r()!==``,async execute(e,r){let{query:c,product:l,locale:f}=e??{},p;try{p=await a({query:c,product:l||void 0,locale:f||t(r.config.l10n).defaultLocale})}catch(e){throw e instanceof i?(r.logger?.warn(`MCP search: ${e.message} ${e.detail}`),Error(`The search service failed. Try the call again later.`)):e}let m=await s(r.entities),h=await o(p,async e=>!m.has(e)&&r.isSlugVisible(e)&&await r.hasRoute(e));return h.length===0?u:d(h,n(r.request))||u}}];export{f as searchTools};
3
+ `).trim()}const p=[{schema:l,schemaFor:t=>u(Object.values(t.config.products??{}).map(e=>e.name),e(t.config.l10n).locales?.map(e=>e.code)??[]),isAvailable:()=>i()!==``,async execute(t,i){let{query:l,product:u,locale:p}=t??{},m;try{m=await o({query:l,product:u||void 0,locale:p||e(i.config.l10n).defaultLocale})}catch(e){throw e instanceof a?(i.logger?.warn(`MCP search: ${e.message} ${e.detail}`),Error(`The search service failed. Try the call again later.`)):e}let h=await n(i.entities),g=await s(m,async e=>!h.has(e)&&i.isSlugVisible(e)&&await i.hasRoute(e));if(g.length===0)return d;let _=r(i.request);return f(g,process.env.REDOCLY_ENV===`production`?c(i.config.seo?.siteUrl,_):_)||d}}];export{p as searchTools};
@@ -1 +1 @@
1
- import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{OPERATION_METHODS as t}from"../../../../../../shared/constants/openapi-operation-methods.js";import{withoutTrailingSlashes as n}from"../tools/openapi-document.js";import{operationHttpMethod as r,pathTemplateKey as i}from"../gateway/route-pattern.js";import{findUnresolvedPlaceholders as a}from"../gateway/fetch/url-placeholders.js";import{SOURCE_REFERENCE as o,UnsupportedWorkflowError as s,failureActionsOf as c,localWorkflowId as l,referencedWorkflowIds as u,successActionsOf as d}from"./workflow-references.js";import{definitionForOperations as f}from"./operations-subset.js";import{stepKey as p}from"./types.js";import{posix as m}from"node:path";import{replaceServerVariables as h}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";import{resolveRef as g}from"@redocly/api-docs/lib/utils/inline-openapi-refs.js";const _=/^\{\$sourceDescriptions\.([\w.-]+)\.url\}#(\/.+)$/,v=/^([\w-]+)\.(.+)$/,y=/^[a-z][a-z0-9+.-]*:/i,b=/^https?:\/\//i,x=/\$components\.(\w+)\.([\w.-]+)/g,S=/\b(?:match|search)\s*\(/,C=[`multipart/form-data`,`application/octet-stream`],w=new Set(t);function T(e){let{filePath:t,document:n}=e,r=E(e),i=new Map((n.workflows??[]).map(e=>[e.workflowId,e])),a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let t of i.values())try{if(R(t,n.components))throw new s(`it generates test data with $faker`);for(let n of t.steps??[]){let i=A(n,t,r,e);i&&a.set(p(t.workflowId,n.stepId),i)}for(let e of u(t,n.components))V(e,r)}catch(e){if(!(e instanceof s))throw e;o.set(t.workflowId,e.message)}H(i,o),G(i,n.components,o);let c=/* @__PURE__ */ new Map;for(let e of i.values())o.has(e.workflowId)||c.set(e.workflowId,{workflow:e,inputs:K(e,i),methods:q(e,i,n.components,a)});return{filePath:t,title:n.info?.title??m.basename(t),document:n,sources:D(n,r,[...a.values()]),operations:a,runnable:c,unsupported:o}}function E({filePath:e,document:t,apis:n}){let r=/* @__PURE__ */ new Map;for(let i of t.sourceDescriptions??[]){let t=k(e,i.url);if(t){if(i.type===`arazzo`&&t===e)r.set(i.name,{kind:`self`});else if(i.type===`openapi`&&!i[`x-serverUrl`]){let e=n.find(e=>e.relativePath===t);e&&r.set(i.name,{kind:`api`,api:e})}}}return r}function D(e,t,n){let r=/* @__PURE__ */ new Map;for(let{name:i,type:a}of e.sourceDescriptions??[]){let e=t.get(i);if(e?.kind!==`self`){if(e?.kind===`api`){let{definition:t,servers:a}=e.api,o=n.filter(e=>e.sourceName===i);r.set(i,{...f(t,o),servers:[...a]})}else r.set(i,O(a,i))}}return r}function O(e,t){let n={title:t,version:`0`};return e===`arazzo`?{arazzo:`1.0.1`,info:n,sourceDescriptions:[],workflows:[]}:{openapi:`3.1.0`,info:n,paths:{}}}function k(e,t){if(!(y.test(t)||t.startsWith(`/`)))return m.normalize(m.join(m.dirname(e),t))}function A(e,t,n,a){if(L(e,t,a.document.components),c(e,t,a.document.components).some(B))throw new s(`step "${e.stepId}" waits more than 5 seconds before a retry`);if(e.workflowId)return;let o=j(e,n);if(!o)throw new s(`step "${e.stepId}" calls no operation of a callable API`);let{sourceName:l,api:u,path:d,method:f,operation:p}=o,m=r(f),h=i(d),g=u.operations.find(e=>e.method===m&&i(e.path)===h);if(!g?.callable||!g.visible)throw new s(`step "${e.stepId}" calls ${m} ${d}, which agents cannot call`);if(!a.allowedHttpMethods.includes(m))throw new s(`step "${e.stepId}" sends ${m}, which this project does not allow`);let _=e.requestBody?.contentType??F(p,u.definition);if(e.requestBody&&_&&C.some(e=>_.includes(e)))throw new s(`step "${e.stepId}" sends ${_}, which workflows cannot send`);if(!I(u))throw new s(`step "${e.stepId}" calls an API without an absolute server URL`);return{sourceName:l,method:m,operationKey:f,path:d}}function j(e,t){if(e.operationPath)return M(e.operationPath,t);if(!e.operationId)return;let n=o.exec(e.operationId)??v.exec(e.operationId),r=n?[[n[1],t.get(n[1])]]:[...t],i=n?n[2]:e.operationId,a=r.flatMap(([e,t])=>t?.kind===`api`?N(e,t.api,i):[]);return a.length===1?a[0]:void 0}function M(e,t){let n=_.exec(e),r=n&&t.get(n[1]);if(!n||r?.kind!==`api`)return;let i=n[2].slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`));if(i.length!==3||i[0]!==`paths`)return;let[,a,o]=i,s=P(r.api,a,o);return s&&{sourceName:n[1],api:r.api,path:a,method:o,operation:s}}function N(t,n,r){return Object.entries(n.definition.paths??{}).flatMap(([i,a])=>Object.keys(e(a)?a:{}).flatMap(e=>{let a=P(n,i,e);return a?.operationId===r?[{sourceName:t,api:n,path:i,method:e,operation:a}]:[]}))}function P(t,n,r){if(!w.has(r.toLowerCase()))return;let i=t.definition.paths?.[n],a=e(i)?i[r]:void 0;return e(a)?a:void 0}function F(t,n){let r=t.requestBody,i=r&&`$ref`in r&&r.$ref?g(r.$ref,n):r,a=e(i)?i.content:void 0;return e(a)?Object.keys(a)[0]:void 0}function I(e){let[t]=e.servers;if(!t)return!1;let r=n(h(t));return b.test(r)&&a(r).length===0}function L(e,t,n){let r=[...d(e,t,n),...c(e,t,n)],i=[...e.successCriteria??[],...r.flatMap(e=>e.criteria??[])];for(let{type:t,condition:n}of i){let r=typeof t==`object`?t.type:t;if(r===`xpath`)throw new s(`step "${e.stepId}" checks an XPath criterion, which workflows cannot evaluate`);if(r===`regex`||r===`jsonpath`&&S.test(n))throw new s(`step "${e.stepId}" checks a regex, which workflows cannot evaluate safely`)}}function R(e,t){let n=JSON.stringify(e);return[n,...[...n.matchAll(x)].map(([,e=``,n=``])=>JSON.stringify(z(t,e,n))??``)].some(e=>e.includes(`$faker`))}function z(t,n,r){let i=t,a=e(i)?i[n]:void 0;return e(a)?a[r]:void 0}function B(e){return e.type===`retry`&&(e.retryAfter??0)>5}function V(e,t){let n=o.exec(e);if(n&&t.get(n[1])?.kind!==`self`)throw new s(`it uses workflow "${e}" of another file`)}function H(e,t){for(let n of e.values()){let r=U(n,e);r&&!t.has(n.workflowId)&&t.set(n.workflowId,`it calls itself through workflow "${r}"`)}}function U(e,t){for(let n of W(e)){let r=/* @__PURE__ */ new Set,i=[n];for(;i.length>0;){let a=i.pop();if(a===e.workflowId)return n;if(r.has(a))continue;r.add(a);let o=t.get(a);o&&i.push(...W(o))}}}function W(e){let t=(e.steps??[]).flatMap(e=>e.workflowId?[l(e.workflowId)]:[]);return[...(e.dependsOn??[]).map(l),...t]}function G(e,t,n){let r=!0;for(;r;){r=!1;for(let i of e.values()){if(n.has(i.workflowId))continue;let a=u(i,t).map(l).find(t=>!e.has(t)||n.has(t));a!==void 0&&(n.set(i.workflowId,`it uses workflow "${a}", which cannot run`),r=!0)}}}function K(e,t){let n={},r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=e=>{if(!i.has(e.workflowId)){i.add(e.workflowId);for(let[t,r]of Object.entries(e.inputs?.properties??{}))t in n||(n[t]=r);for(let t of e.inputs?.required??[])r.add(t);for(let n of e.dependsOn??[]){let e=t.get(l(n));e&&a(e)}}};return a(e),r.size>0?{type:`object`,properties:n,required:[...r]}:{type:`object`,properties:n}}function q(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[e];for(;o.length>0;){let e=o.pop();if(!a.has(e.workflowId)){a.add(e.workflowId);for(let t of e.steps??[]){let n=r.get(p(e.workflowId,t.stepId))?.method;n&&i.add(n)}for(let r of u(e,n)){let e=t.get(l(r));e&&o.push(e)}}}return[...i].sort()}export{T as resolveArazzoFile,k as sourceDescriptionPath};
1
+ import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{OPERATION_METHODS as t}from"../../../../../../shared/constants/openapi-operation-methods.js";import{withoutTrailingSlashes as n}from"../tools/openapi-document.js";import{operationHttpMethod as r,pathTemplateKey as i}from"../gateway/route-pattern.js";import{findUnresolvedPlaceholders as a}from"../gateway/fetch/url-placeholders.js";import{SOURCE_REFERENCE as o,UnsupportedWorkflowError as s,failureActionsOf as c,localWorkflowId as l,referencedWorkflowIds as u,successActionsOf as d}from"./workflow-references.js";import{definitionForOperations as f}from"./operations-subset.js";import{stepKey as p}from"./types.js";import{posix as m}from"node:path";import{replaceServerVariables as h}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";import{resolveRef as g}from"@redocly/api-docs/lib/utils/inline-openapi-refs.js";const _=/^\{\$sourceDescriptions\.([\w.-]+)\.url\}#(\/.+)$/,v=/^([\w-]+)\.(.+)$/,y=/^[a-z][a-z0-9+.-]*:/i,b=/^https?:\/\//i,x=/\$components\.(\w+)\.([\w.-]+)/g,S=/\b(?:match|search)\s*\(/,C=[`multipart/form-data`,`application/octet-stream`],w=new Set(t);function T(e){let{filePath:t,document:n}=e,r=E(e),i=new Map((n.workflows??[]).map(e=>[e.workflowId,e])),a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let t of i.values())try{if(R(t,n.components))throw new s(`it generates test data with $faker`);for(let n of t.steps??[]){let i=A(n,t,r,e);i&&a.set(p(t.workflowId,n.stepId),i)}for(let e of u(t,n.components))V(e,r)}catch(e){if(!(e instanceof s))throw e;o.set(t.workflowId,e.message)}H(i,o),G(i,n.components,o);let c=/* @__PURE__ */ new Map;for(let e of i.values())o.has(e.workflowId)||c.set(e.workflowId,{workflow:e,inputs:K(e,i),methods:q(e,i,n.components,a)});return{filePath:t,title:n.info?.title??m.basename(t),document:n,sources:D(n,r,[...a.values()]),operations:a,runnable:c,unsupported:o}}function E({filePath:e,document:t,apis:n}){let r=/* @__PURE__ */ new Map;for(let i of t.sourceDescriptions??[]){let t=k(e,i.url);if(t){if(i.type===`arazzo`&&t===e)r.set(i.name,{kind:`self`});else if(i.type===`openapi`&&!i[`x-serverUrl`]){let e=n.find(e=>e.relativePath===t);e&&r.set(i.name,{kind:`api`,api:e})}}}return r}function D(e,t,n){let r=/* @__PURE__ */ new Map;for(let{name:i,type:a}of e.sourceDescriptions??[]){let e=t.get(i);if(e?.kind!==`self`){if(e?.kind===`api`){let{definition:t,servers:a}=e.api,o=n.filter(e=>e.sourceName===i);r.set(i,{...f(t,o),servers:[...a]})}else r.set(i,O(a,i))}}return r}function O(e,t){let n={title:t,version:`0`};return e===`arazzo`?{arazzo:`1.0.1`,info:n,sourceDescriptions:[],workflows:[]}:{openapi:`3.1.0`,info:n,paths:{}}}function k(e,t){if(!(y.test(t)||t.startsWith(`/`)))return m.normalize(m.join(m.dirname(e),t))}function A(e,t,n,a){if(L(e,t,a.document.components),c(e,t,a.document.components).some(B))throw new s(`step "${e.stepId}" waits more than 5 seconds before a retry`);if(e.workflowId)return;if(e[`x-operation`])throw new s(`step "${e.stepId}" calls an x-operation URL, not a documented operation`);let o=j(e,n);if(!o)throw new s(`step "${e.stepId}" calls no operation of a callable API`);let{sourceName:l,api:u,path:d,method:f,operation:p}=o,m=r(f),h=i(d),g=u.operations.find(e=>e.method===m&&i(e.path)===h);if(!g?.callable||!g.visible)throw new s(`step "${e.stepId}" calls ${m} ${d}, which agents cannot call`);if(!a.allowedHttpMethods.includes(m))throw new s(`step "${e.stepId}" sends ${m}, which this project does not allow`);let _=e.requestBody?.contentType??F(p,u.definition);if(e.requestBody&&_&&C.some(e=>_.includes(e)))throw new s(`step "${e.stepId}" sends ${_}, which workflows cannot send`);if(!I(u))throw new s(`step "${e.stepId}" calls an API without an absolute server URL`);return{sourceName:l,method:m,operationKey:f,path:d}}function j(e,t){if(e.operationPath)return M(e.operationPath,t);if(!e.operationId)return;let n=o.exec(e.operationId)??v.exec(e.operationId),r=n?[[n[1],t.get(n[1])]]:[...t],i=n?n[2]:e.operationId,a=r.flatMap(([e,t])=>t?.kind===`api`?N(e,t.api,i):[]);return a.length===1?a[0]:void 0}function M(e,t){let n=_.exec(e),r=n&&t.get(n[1]);if(!n||r?.kind!==`api`)return;let i=n[2].slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`));if(i.length!==3||i[0]!==`paths`)return;let[,a,o]=i,s=P(r.api,a,o);return s&&{sourceName:n[1],api:r.api,path:a,method:o,operation:s}}function N(t,n,r){return Object.entries(n.definition.paths??{}).flatMap(([i,a])=>Object.keys(e(a)?a:{}).flatMap(e=>{let a=P(n,i,e);return a?.operationId===r?[{sourceName:t,api:n,path:i,method:e,operation:a}]:[]}))}function P(t,n,r){if(!w.has(r.toLowerCase()))return;let i=t.definition.paths?.[n],a=e(i)?i[r]:void 0;return e(a)?a:void 0}function F(t,n){let r=t.requestBody,i=r&&`$ref`in r&&r.$ref?g(r.$ref,n):r,a=e(i)?i.content:void 0;return e(a)?Object.keys(a)[0]:void 0}function I(e){let[t]=e.servers;if(!t)return!1;let r=n(h(t));return b.test(r)&&a(r).length===0}function L(e,t,n){let r=[...d(e,t,n),...c(e,t,n)],i=[...e.successCriteria??[],...r.flatMap(e=>e.criteria??[])];for(let{type:t,condition:n}of i){let r=typeof t==`object`?t.type:t;if(r===`xpath`)throw new s(`step "${e.stepId}" checks an XPath criterion, which workflows cannot evaluate`);if(r===`regex`||r===`jsonpath`&&S.test(n))throw new s(`step "${e.stepId}" checks a regex, which workflows cannot evaluate safely`)}}function R(e,t){let n=JSON.stringify(e);return[n,...[...n.matchAll(x)].map(([,e=``,n=``])=>JSON.stringify(z(t,e,n))??``)].some(e=>e.includes(`$faker`))}function z(t,n,r){let i=t,a=e(i)?i[n]:void 0;return e(a)?a[r]:void 0}function B(e){return e.type===`retry`&&(e.retryAfter??0)>5}function V(e,t){let n=o.exec(e);if(n&&t.get(n[1])?.kind!==`self`)throw new s(`it uses workflow "${e}" of another file`)}function H(e,t){for(let n of e.values()){let r=U(n,e);r&&!t.has(n.workflowId)&&t.set(n.workflowId,`it calls itself through workflow "${r}"`)}}function U(e,t){for(let n of W(e)){let r=/* @__PURE__ */ new Set,i=[n];for(;i.length>0;){let a=i.pop();if(a===e.workflowId)return n;if(r.has(a))continue;r.add(a);let o=t.get(a);o&&i.push(...W(o))}}}function W(e){let t=(e.steps??[]).flatMap(e=>e.workflowId?[l(e.workflowId)]:[]);return[...(e.dependsOn??[]).map(l),...t]}function G(e,t,n){let r=!0;for(;r;){r=!1;for(let i of e.values()){if(n.has(i.workflowId))continue;let a=u(i,t).map(l).find(t=>!e.has(t)||n.has(t));a!==void 0&&(n.set(i.workflowId,`it uses workflow "${a}", which cannot run`),r=!0)}}}function K(e,t){let n={},r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set,a=e=>{if(!i.has(e.workflowId)){i.add(e.workflowId);for(let[t,r]of Object.entries(e.inputs?.properties??{}))t in n||(n[t]=r);for(let t of e.inputs?.required??[])r.add(t);for(let n of e.dependsOn??[]){let e=t.get(l(n));e&&a(e)}}};return a(e),r.size>0?{type:`object`,properties:n,required:[...r]}:{type:`object`,properties:n}}function q(e,t,n,r){let i=/* @__PURE__ */ new Set,a=/* @__PURE__ */ new Set,o=[e];for(;o.length>0;){let e=o.pop();if(!a.has(e.workflowId)){a.add(e.workflowId);for(let t of e.steps??[]){let n=r.get(p(e.workflowId,t.stepId))?.method;n&&i.add(n)}for(let r of u(e,n)){let e=t.get(l(r));e&&o.push(e)}}}return[...i].sort()}export{T as resolveArazzoFile,k as sourceDescriptionPath};
@@ -1 +1,2 @@
1
- import{GET_WORKFLOW_TOOL_NAME as e,LIST_WORKFLOWS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,RUN_WORKFLOW_TOOL_NAME as r}from"../../constants.js";const i={type:`string`,nullable:!0},a={workflowId:{type:`string`,description:"The `workflowId` from `listWorkflows`."},filePath:{...i,description:"The `filePath` from `listWorkflows`. Needed only when several files declare the workflow ID."}},o={workflowId:{type:`string`},filePath:{type:`string`,description:`The Arazzo description that declares the workflow.`},summary:i,description:i,writes:{type:`boolean`,description:`True when a step can change data. Confirm with the user before such a run.`},inputs:{type:`object`,description:"The JSON Schema of the `inputs` that `runWorkflow` takes."}},s={name:t,title:`List API workflows`,description:'Lists the workflows that `runWorkflow` can run. Each workflow is a ready-made multi-step API action that the docs authors wrote, such as "log in, then place an order". When a workflow matches the task, run it instead of chaining `fetch` calls: it already knows the order of the calls and how data passes between them.',summary:`List the multi-step API workflows you can run.`,annotations:n,schema:{type:`object`,required:[],additionalProperties:!1,properties:{filter:{...i,description:`Case-insensitive text to find in the workflow ID, summary, or description.`}}},outputSchema:{type:`object`,required:[`items`],properties:{items:{type:`array`,items:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`],properties:o}}}}},c={name:e,title:`Get an API workflow`,description:"Gets one workflow from `listWorkflows`: its inputs, outputs, and the request or sub-workflow of each step. Use it to explain a workflow to the user before you run it. For a workflow that cannot run, the error says why.",summary:`Get the inputs, steps, and outputs of one workflow.`,annotations:n,schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:a},outputSchema:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`,`outputs`,`steps`],properties:{...o,outputs:{type:`array`,items:{type:`string`},description:"The names of the `outputs` a successful run returns."},steps:{type:`array`,items:{type:`object`,required:[`stepId`],properties:{stepId:{type:`string`},description:i,request:{...i,description:"The method and the path, such as `POST /orders`."},workflowId:{...i,description:`The sub-workflow the step runs.`}}}}}}},l={name:r,title:`Run an API workflow`,description:'Runs one workflow from `listWorkflows` with its `inputs`, and returns its `outputs` and one `steps` entry per request. Each request goes through `fetch`: the same documented operations, hosts, stored credentials, and limits. A run that fails returns `status: "failed"` with the failed step and its response. The requests in `steps` already reached the API, so do not run a workflow that writes again without asking the user.',summary:`Run a multi-step API workflow with its inputs.`,annotations:{...n,openWorldHint:!0},schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:{...a,inputs:{type:`object`,nullable:!0,description:"The workflow inputs; their JSON Schema is `inputs` in `listWorkflows`."}}},outputSchema:{type:`object`,required:[`workflowId`,`status`,`steps`],properties:{workflowId:{type:`string`},status:{type:`string`,enum:[`succeeded`,`failed`]},outputs:{type:`object`,nullable:!0},steps:{type:`array`,items:{type:`object`,required:[`stepId`,`ms`],properties:{stepId:{type:`string`},workflowId:{...i,description:`Set for a step of a sub-workflow or a dependency.`},request:i,status:{type:`number`,nullable:!0},ms:{type:`number`},error:{...i,description:`Why the request did not reach the API.`}}}},failure:{type:`object`,nullable:!0,required:[`workflowId`,`reason`],properties:{workflowId:{type:`string`},stepId:i,reason:{type:`string`},response:{type:`object`,nullable:!0,required:[`status`,`body`],properties:{status:{type:`number`},body:{type:`string`}}}}}}}};export{c as GET_WORKFLOW_SCHEMA,s as LIST_WORKFLOWS_SCHEMA,l as RUN_WORKFLOW_SCHEMA};
1
+ import{GET_WORKFLOW_TOOL_NAME as e,LIST_WORKFLOWS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,REQUIRES_USER_INTERACTION_META as r,RUN_WORKFLOW_TOOL_NAME as i,RUN_WORKFLOW_WRITE_TOOL_NAME as a,WRITE_TOOL_ANNOTATIONS as o}from"../../constants.js";import{SESSION_HANDLE_PROPERTY as s}from"../gateway/tools.js";const c={type:`string`,nullable:!0},l={workflowId:{type:`string`,description:"The `workflowId` from `listWorkflows`."},filePath:{...c,description:"The `filePath` from `listWorkflows`. Needed only when several files declare the workflow ID."}},u={workflowId:{type:`string`},filePath:{type:`string`,description:`The Arazzo description that declares the workflow.`},summary:c,description:c,writes:{type:`boolean`,description:`True when a step can change data. Such a workflow does not run inside \`execute\`; it runs through the \`${a}\` tool.`},inputs:{type:`object`,description:"The JSON Schema of the `inputs` that `runWorkflow` takes."}},d={name:t,title:`List API workflows`,description:'Lists the workflows that `runWorkflow` can run. Each workflow is a ready-made multi-step API action that the docs authors wrote, such as "log in, then place an order". When a workflow matches the task, run it instead of chaining `fetch` calls: it already knows the order of the calls and how data passes between them.',summary:`List the multi-step API workflows you can run.`,annotations:n,schema:{type:`object`,required:[],additionalProperties:!1,properties:{filter:{...c,description:`Case-insensitive text to find in the workflow ID, summary, or description.`}}},outputSchema:{type:`object`,required:[`items`],properties:{items:{type:`array`,items:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`],properties:u}}}}},f={name:e,title:`Get an API workflow`,description:"Gets one workflow from `listWorkflows`: its inputs, outputs, and the request or sub-workflow of each step. Use it to explain a workflow to the user before you run it. For a workflow that cannot run, the error says why.",summary:`Get the inputs, steps, and outputs of one workflow.`,annotations:n,schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:l},outputSchema:{type:`object`,required:[`workflowId`,`filePath`,`writes`,`inputs`,`outputs`,`steps`],properties:{...u,outputs:{type:`array`,items:{type:`string`},description:"The names of the `outputs` a successful run returns."},steps:{type:`array`,items:{type:`object`,required:[`stepId`],properties:{stepId:{type:`string`},description:c,request:{...c,description:"The method and the path, such as `POST /orders`."},workflowId:{...c,description:`The sub-workflow the step runs.`}}}}}}},p={...l,inputs:{type:`object`,nullable:!0,description:"The workflow inputs; their JSON Schema is `inputs` in `listWorkflows`."}},m={type:`object`,required:[`workflowId`,`status`,`steps`],properties:{workflowId:{type:`string`},status:{type:`string`,enum:[`succeeded`,`failed`]},outputs:{type:`object`,nullable:!0},steps:{type:`array`,items:{type:`object`,required:[`stepId`,`ms`],properties:{stepId:{type:`string`},workflowId:{...c,description:`Set for a step of a sub-workflow or a dependency.`},request:c,status:{type:`number`,nullable:!0},ms:{type:`number`},error:{...c,description:`Why the request did not reach the API.`}}}},failure:{type:`object`,nullable:!0,required:[`workflowId`,`reason`],properties:{workflowId:{type:`string`},stepId:c,reason:{type:`string`},response:{type:`object`,nullable:!0,required:[`status`,`body`],properties:{status:{type:`number`},body:{type:`string`}}}}}}},h={name:i,title:`Run an API workflow`,description:`Runs one workflow from \`listWorkflows\` that does not write (\`writes: false\`) with its \`inputs\`, and returns its \`outputs\` and one \`steps\` entry per request. Each request goes through \`fetch\`: the same documented operations, hosts, stored credentials, and limits. A run that fails returns \`status: "failed"\` with the failed step and its response. Run a workflow with \`writes: true\` with the \`${a}\` tool.`,summary:`Run a read-only multi-step API workflow with its inputs.`,annotations:{...n,openWorldHint:!0},schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:p},outputSchema:m},g={name:a,title:`Run a workflow that writes`,description:["Runs one workflow from `listWorkflows` that has at least one write step (`writes: true`), with its `inputs`.","Read the workflow with `getWorkflow` in `execute` first.",`Run it only when the user asked for the action. A question about what is possible is not a request to run it.`,"It returns the `outputs` and one `steps` entry per request. Do not run it again after a failure without asking the user."].join(`
2
+ `),annotations:o,_meta:r,schema:{type:`object`,required:[`workflowId`],additionalProperties:!1,properties:{...p,sessionHandle:s}},outputSchema:m};export{f as GET_WORKFLOW_SCHEMA,d as LIST_WORKFLOWS_SCHEMA,h as RUN_WORKFLOW_SCHEMA,g as RUN_WORKFLOW_WRITE_SCHEMA};
@@ -1 +1 @@
1
- import{formatCandidates as e}from"../tools/openapi-document.js";import{isSafeHttpMethod as t}from"../gateway/allowed-http-methods.js";import{stepKey as n}from"./types.js";import{hasRunnableWorkflows as r,loadWorkflowCatalog as i}from"./catalog.js";import{runWorkflow as a}from"./run-workflow.js";import{GET_WORKFLOW_SCHEMA as o,LIST_WORKFLOWS_SCHEMA as s,RUN_WORKFLOW_SCHEMA as c}from"./schemas.js";import{Ajv as l,AjvJsonSchemaValidator as u}from"@modelcontextprotocol/server/validators/ajv";const d=new u(new l({allErrors:!0,strict:!1,validateFormats:!1}));function f({methods:e}){return e.some(e=>!t(e))}function p({file:e,runnable:t}){let{workflowId:n,summary:r,description:i}=t.workflow;return{workflowId:n,filePath:e.filePath,summary:r,description:i,writes:f(t),inputs:t.inputs}}function m(e){return e.flatMap(e=>Array.from(e.runnable.values(),t=>({file:e,runnable:t})))}function h({workflowId:t,filePath:n},r){let i=n?r.filter(e=>e.filePath===n):r,a=i.flatMap(e=>{let n=e.runnable.get(t);return n?[{file:e,runnable:n}]:[]});if(a.length===1)return a[0];if(a.length>1)throw Error(`Workflow "${t}" is in several files: ${e(a.map(({file:e})=>`"${e.filePath}"`))}. Pass \`filePath\`.`);let o=i.find(e=>e.unsupported.has(t));if(o)throw Error(`Workflow "${t}" in ${o.filePath} cannot run: ${o.unsupported.get(t)}.`);let s=m(r).map(({runnable:e})=>`"${e.workflow.workflowId}"`);throw Error(`No workflow "${t}"`+(n?` in ${n}`:``)+(s.length>0?`. Available workflows: ${e(s)}.`:`.`))}const g={schema:s,isAvailable:r,async execute(e,t){let n=(e??{}).filter?.trim().toLowerCase(),r=m(await i(t)).map(p);return{items:n?r.filter(e=>[e.workflowId,e.summary,e.description].some(e=>e?.toLowerCase().includes(n))):r}}},_={schema:o,isAvailable:r,async execute(e,t){let r=h(e,await i(t)),{workflow:a}=r.runnable;return{...p(r),outputs:Object.keys(a.outputs??{}),steps:(a.steps??[]).map(e=>{let t=r.file.operations.get(n(a.workflowId,e.stepId));return{stepId:e.stepId,description:e.description,request:t&&`${t.method} ${t.path}`,workflowId:e.workflowId}})}}},v={schema:c,isAvailable:r,async execute(e,t,n){let r=e,{file:o,runnable:s}=h(r,await i(t)),c=r.inputs??{},l=d.getValidator(s.inputs)(c);if(!l.valid)throw Error(`The inputs of workflow "${r.workflowId}" are not valid: ${l.errorMessage}`);let u=n?.gatewayFetch;if(!u)throw Error("`runWorkflow` runs only inside an `execute` script.");return a({file:o,workflowId:r.workflowId,inputs:c,fetch:u,deadline:t.executeDeadline})}};function y(){return[g,_,v]}export{y as workflowTools};
1
+ import{RUN_WORKFLOW_WRITE_TOOL_NAME as e}from"../../constants.js";import{isToolDisabledByCaller as t}from"../disabled-tools.js";import{formatCandidates as n}from"../tools/openapi-document.js";import{getAllowedHttpMethods as r,isSafeHttpMethod as i}from"../gateway/allowed-http-methods.js";import{runExecuteWithGateway as a}from"../gateway/index.js";import{stepKey as o}from"./types.js";import{hasRunnableWorkflows as s,loadWorkflowCatalog as c}from"./catalog.js";import{runWorkflow as l}from"./run-workflow.js";import{GET_WORKFLOW_SCHEMA as u,LIST_WORKFLOWS_SCHEMA as d,RUN_WORKFLOW_SCHEMA as f,RUN_WORKFLOW_WRITE_SCHEMA as p}from"./schemas.js";import{Ajv as m,AjvJsonSchemaValidator as h}from"@modelcontextprotocol/server/validators/ajv";const g=new h(new m({allErrors:!0,strict:!1,validateFormats:!1}));function _({methods:e}){return e.some(e=>!i(e))}function v({file:e,runnable:t}){let{workflowId:n,summary:r,description:i}=t.workflow;return{workflowId:n,filePath:e.filePath,summary:r,description:i,writes:_(t),inputs:t.inputs}}function y(e){return e.flatMap(e=>Array.from(e.runnable.values(),t=>({file:e,runnable:t})))}function b({workflowId:e,filePath:t},r){let i=t?r.filter(e=>e.filePath===t):r,a=i.flatMap(t=>{let n=t.runnable.get(e);return n?[{file:t,runnable:n}]:[]});if(a.length===1)return a[0];if(a.length>1)throw Error(`Workflow "${e}" is in several files: ${n(a.map(({file:e})=>`"${e.filePath}"`))}. Pass \`filePath\`.`);let o=i.find(t=>t.unsupported.has(e));if(o)throw Error(`Workflow "${e}" in ${o.filePath} cannot run: ${o.unsupported.get(e)}.`);let s=y(r).map(({runnable:e})=>`"${e.workflow.workflowId}"`);throw Error(`No workflow "${e}"`+(t?` in ${t}`:``)+(s.length>0?`. Available workflows: ${n(s)}.`:`.`))}const x={schema:d,isAvailable:s,async execute(e,t){let n=(e??{}).filter?.trim().toLowerCase(),r=y(await c(t)).map(v);return{items:n?r.filter(e=>[e.workflowId,e.summary,e.description].some(e=>e?.toLowerCase().includes(n))):r}}},S={schema:u,isAvailable:s,async execute(e,t){let n=b(e,await c(t)),{workflow:r}=n.runnable;return{...v(n),outputs:Object.keys(r.outputs??{}),steps:(r.steps??[]).map(e=>{let t=n.file.operations.get(o(r.workflowId,e.stepId));return{stepId:e.stepId,description:e.description,request:t&&`${t.method} ${t.path}`,workflowId:e.workflowId}})}}};async function C(e,t){let n=b(e,await c(t)),r=e.inputs??{},i=g.getValidator(n.runnable.inputs)(r);if(!i.valid)throw Error(`The inputs of workflow "${e.workflowId}" are not valid: ${i.errorMessage}`);return{...n,inputs:r}}const w={schema:f,isAvailable:s,async execute(n,r,i){let a=n,o=await C(a,r);if(_(o.runnable)){let n=t(`run-workflow_write`,r.metadata)?`Explain the workflow to the user instead of running it.`:`Use the \`${e}\` tool.`;throw Error(`Workflow "${a.workflowId}" was not run. This workflow writes. ${n}`)}let s=i?.gatewayFetch;if(!s)throw Error("`runWorkflow` runs only inside an `execute` script.");return l({file:o.file,workflowId:a.workflowId,inputs:o.inputs,fetch:s,deadline:r.executeDeadline})}},T={schema:p,isAvailable:async e=>y(await c(e)).some(({runnable:e})=>_(e)),async execute(t,n,i){let o=t,s=i?.serverContext;if(!s)throw Error(`\`${e}\` runs only as a top-level tool call.`);let c=await C(o,n);if(!_(c.runnable))throw Error(`Workflow "${o.workflowId}" does not write. Run it with \`site.runWorkflow\` inside \`execute\`.`);return a({ctx:n,sessionHandle:o.sessionHandle,serverContext:s,allowedHttpMethods:r(n.config.mcp),run:async e=>{let t=await l({file:c.file,workflowId:o.workflowId,inputs:c.inputs,fetch:e,deadline:n.executeDeadline});return{content:[{type:`text`,text:JSON.stringify(t)}],structuredContent:t,isError:t.status===`failed`}}})}};function E(){return[x,S,w]}export{T as runWorkflowWriteTool,E as workflowTools};
@@ -1 +1 @@
1
- import{isMcpHidden as e,isPublicEndpointServedFromConfig as t}from"./server/config-gate.js";import{MCP_ROUTE as n,MCP_SETUP_TEMPLATE_ID as r,PUBLIC_MCP_ROUTE as i}from"./constants.js";const a={title:`Connect to the MCP server`,rbac:{"*":`read`},excludeFromSearch:!0};function o(o){return e(o)?[]:[{routeId:`mcp-setup`,slug:n,template:r,metadata:a},...t(o)?[{routeId:`mcp-public-setup`,slug:i,template:r,metadata:a}]:[]]}export{o as buildMcpSetupPageRoutes};
1
+ import{MCP_ROUTE as e,MCP_SETUP_TEMPLATE_ID as t,PUBLIC_MCP_ROUTE as n}from"./constants.js";import{isMcpHidden as r,isPublicEndpointServedFromConfig as i}from"./server/config-gate.js";const a={title:`Connect to the MCP server`,rbac:{"*":`read`},excludeFromSearch:!0};function o(o){return r(o)?[]:[{routeId:`mcp-setup`,slug:e,template:t,metadata:a},...i(o)?[{routeId:`mcp-public-setup`,slug:n,template:t,metadata:a}]:[]]}export{o as buildMcpSetupPageRoutes};