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

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 (163) hide show
  1. package/dist/bundler/build/output-metadata.js +1 -1
  2. package/dist/bundler/build/run.js +1 -1
  3. package/dist/bundler/build/vite-config.js +2 -2
  4. package/dist/bundler/dev/materialization-sweeper.js +1 -1
  5. package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
  6. package/dist/bundler/dev/routes/source-sync-route.js +1 -1
  7. package/dist/bundler/dev/run.js +1 -1
  8. package/dist/bundler/dev/runtime-app.js +1 -1
  9. package/dist/bundler/dev/vite-chunk-url.js +1 -1
  10. package/dist/bundler/user-markdoc-schema.js +1 -1
  11. package/dist/bundler/vite-config.base.js +3 -3
  12. package/dist/cli/commands/build.js +1 -1
  13. package/dist/cli/commands/dev.js +1 -1
  14. package/dist/cli/commands/ingest.js +1 -1
  15. package/dist/cli/commands/translate.js +2 -2
  16. package/dist/cli/dev-console/index.js +1 -1
  17. package/dist/cli/log-output/index.js +1 -1
  18. package/dist/cli/validate-react-pages.js +1 -1
  19. package/dist/client/RuntimeLink.js +1 -1
  20. package/dist/client/ai-search/use-ai-search.js +1 -1
  21. package/dist/client/analytics-page-view.js +1 -1
  22. package/dist/client/app.js +3 -3
  23. package/dist/client/client-entry.js +1 -1
  24. package/dist/client/contexts.js +1 -1
  25. package/dist/client/dev-problems/ProblemsBar.js +1 -1
  26. package/dist/client/feedback.js +1 -1
  27. package/dist/client/l10n/use-l10n-config.js +1 -1
  28. package/dist/client/products.js +1 -1
  29. package/dist/client/review/ReviewBar.js +50 -50
  30. package/dist/client/review/use-review.js +1 -1
  31. package/dist/client/sidebar/SidebarDataProvider.js +1 -1
  32. package/dist/client/sidebar/drilldown.js +1 -1
  33. package/dist/client/ssr.js +1 -1
  34. package/dist/client/telemetry/config.js +1 -1
  35. package/dist/client/use-entity-revisions.js +1 -1
  36. package/dist/client/use-page-versions.js +1 -1
  37. package/dist/client/use-search.js +1 -1
  38. package/dist/client/webmcp/tools/shared.js +1 -1
  39. package/dist/client/webmcp/tools/site-tools.js +1 -1
  40. package/dist/client/webmcp/use-webmcp-tools.js +1 -1
  41. package/dist/content-layer/config.js +1 -1
  42. package/dist/content-layer/database/invalidation.js +26 -26
  43. package/dist/content-layer/ingest/finalize-phase.js +1 -1
  44. package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
  45. package/dist/content-layer/ingest/run.js +1 -1
  46. package/dist/content-layer/ingest/search-sync.js +1 -1
  47. package/dist/content-layer/ingest/sync.js +1 -1
  48. package/dist/content-layer/link-checker/load-view.js +1 -1
  49. package/dist/content-layer/link-checker/validate.js +1 -1
  50. package/dist/content-layer/loaders/context.js +1 -1
  51. package/dist/content-layer/markdown/client/markdown-text.js +1 -1
  52. package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
  53. package/dist/content-layer/markdown/constants/markdown-text-tag-set.js +1 -1
  54. package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
  55. package/dist/content-layer/markdown/nodes/heading.js +1 -1
  56. package/dist/content-layer/markdown/resolve/ast.js +1 -1
  57. package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.js +1 -1
  58. package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
  59. package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
  60. package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
  61. package/dist/content-layer/markdown/resolve/references.js +1 -1
  62. package/dist/content-layer/markdown/search/to-markdown.js +1 -1
  63. package/dist/content-layer/markdown/search/to-sections.js +1 -1
  64. package/dist/content-layer/markdown/server/render.js +1 -1
  65. package/dist/content-layer/markdown/service.js +1 -1
  66. package/dist/content-layer/markdown/tags/partial.d.ts +7 -2
  67. package/dist/content-layer/markdown/tags/partial.js +1 -1
  68. package/dist/content-layer/markdown/tags/variant.js +1 -1
  69. package/dist/content-layer/markdown/types/service.d.ts +2 -0
  70. package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
  71. package/dist/content-layer/markdown/utils/reparse-example-fences.d.ts +4 -1
  72. package/dist/content-layer/markdown/utils/reparse-example-fences.js +1 -1
  73. package/dist/content-layer/markdown/utils/substitute-variables.js +1 -1
  74. package/dist/content-layer/markdown/utils/walk-markdoc-ast.d.ts +2 -2
  75. package/dist/content-layer/markdown/utils/walk-markdoc-ast.js +1 -1
  76. package/dist/content-layer/plugins/index.js +1 -1
  77. package/dist/content-layer/plugins/internal/api-docs/client/template.js +2 -2
  78. package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
  79. package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.js +13 -13
  80. package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
  81. package/dist/content-layer/plugins/internal/app-data/banner.js +1 -1
  82. package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
  83. package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
  84. package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
  85. package/dist/content-layer/plugins/internal/index.js +1 -1
  86. package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
  87. package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
  88. package/dist/content-layer/plugins/internal/mcp/constants.d.ts +6 -0
  89. package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
  90. package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
  91. package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
  92. package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
  93. package/dist/content-layer/plugins/internal/mcp/server/codemode/capabilities.js +3 -3
  94. package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
  95. package/dist/content-layer/plugins/internal/mcp/server/codemode/discover.js +1 -1
  96. package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
  97. package/dist/content-layer/plugins/internal/mcp/server/codemode/execution-budget.js +1 -0
  98. package/dist/content-layer/plugins/internal/mcp/server/codemode/index.js +1 -1
  99. package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
  100. package/dist/content-layer/plugins/internal/mcp/server/codemode/read-result.js +1 -0
  101. package/dist/content-layer/plugins/internal/mcp/server/codemode/return-last-expression.js +6 -0
  102. package/dist/content-layer/plugins/internal/mcp/server/codemode/returns-from-top-level.js +1 -0
  103. package/dist/content-layer/plugins/internal/mcp/server/codemode/sandbox.js +1 -1
  104. package/dist/content-layer/plugins/internal/mcp/server/codemode/tool-declarations.js +4 -0
  105. package/dist/content-layer/plugins/internal/mcp/server/codemode/tool-list.js +1 -1
  106. package/dist/content-layer/plugins/internal/mcp/server/codemode/unknown-tool-hint.js +3 -0
  107. package/dist/content-layer/plugins/internal/mcp/server/gateway/api-call-operations.js +1 -1
  108. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
  109. package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
  110. package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +6 -6
  111. package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
  112. package/dist/content-layer/plugins/internal/mcp/server/gateway/subject.js +1 -1
  113. package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
  114. package/dist/content-layer/plugins/internal/mcp/server/gateway/upstream-auth-scheme.js +2 -2
  115. package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
  116. package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
  117. package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
  118. package/dist/content-layer/plugins/internal/mcp/server/rate-limit.js +1 -1
  119. package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
  120. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-constants.js +1 -0
  121. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-document.js +1 -1
  122. package/dist/content-layer/plugins/internal/mcp/server/tools/graphql.js +1 -1
  123. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-catalog.js +1 -1
  124. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-document.js +1 -1
  125. package/dist/content-layer/plugins/internal/mcp/server/tools/openapi.js +1 -1
  126. package/dist/content-layer/plugins/internal/mcp/server/tools/pages-constants.js +1 -0
  127. package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
  128. package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +3 -3
  129. package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +1 -0
  130. package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +1 -1
  131. package/dist/content-layer/plugins/internal/mcp/server/tools/submit-feedback.js +1 -1
  132. package/dist/content-layer/plugins/internal/mcp/server/tools/whoami.js +1 -1
  133. package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
  134. package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
  135. package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
  136. package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
  137. package/dist/content-layer/plugins/internal/skills/index.js +1 -1
  138. package/dist/content-layer/plugins/project/load.js +2 -2
  139. package/dist/content-layer/plugins/utils/link-access.js +1 -1
  140. package/dist/content-layer/plugins/utils/route-index.js +1 -1
  141. package/dist/content-layer/versions/redirect.js +1 -1
  142. package/dist/content-layer/versions/resolve.js +1 -1
  143. package/dist/server/__tests__/rbac-fixture.js +1 -1
  144. package/dist/server/app.js +3 -3
  145. package/dist/server/ask-ai/route.js +1 -1
  146. package/dist/server/auth/middleware.js +1 -1
  147. package/dist/server/auth/request.js +1 -1
  148. package/dist/server/auth/routes.js +1 -1
  149. package/dist/server/constants/system-routes.js +1 -1
  150. package/dist/server/content.js +13 -13
  151. package/dist/server/cors-proxy/handler.js +1 -1
  152. package/dist/server/feedback/route.js +1 -1
  153. package/dist/server/lambda-entry.js +1 -1
  154. package/dist/server/manifest-assets.js +4 -4
  155. package/dist/server/node-entry.js +1 -1
  156. package/dist/server/plugin-context.js +1 -1
  157. package/dist/server/rbac/l10n-rules.js +1 -1
  158. package/dist/server/rbac/team-templates.js +1 -1
  159. package/dist/server/search/route.js +1 -1
  160. package/dist/server/seo-tags.js +2 -2
  161. package/dist/server/static-files/serve.js +1 -1
  162. package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
  163. package/package.json +2 -4
@@ -1 +1 @@
1
- import{errorMessage as e}from"../../../../../../shared/utils/error-message.js";import{formatError as t}from"../tool-errors.js";import{DEFAULT_MAX_LIFETIME_MS as n,DEFAULT_TIMEOUT_MS as r,INITIAL_TOTAL_MEMORY_BYTES as i,INTERNAL_ERROR_MESSAGE as a,MAX_ALLOCATION_BYTES as o,MAX_STACK_SIZE_BYTES as s,MAX_TOTAL_MEMORY_BYTES as c,WASM_PAGE_BYTES as l}from"./constants.js";import{SANDBOX_FAILURE as u,createExecutionBudget as d,readResult as f,returnsFromTopLevel as p}from"@redocly/mcp";import m from"@jitl/quickjs-singlefile-mjs-release-sync";import{newQuickJSWASMModuleFromVariant as h,newVariant as g}from"quickjs-emscripten-core";var _=class extends Error{guestError;name=`ReportableError`;constructor(e,t){super(e),this.guestError=t}};function v(t){try{return t()}catch(t){throw new _(e(t),w(t))}}let y;function b(){return y??=h(g(m,{wasmMemory:new WebAssembly.Memory({initial:i/l,maximum:c/l})}))}async function x(e,i={}){let{timeoutMs:c=r,deadline:l=Date.now()+n,setupContext:m,authoredCode:h=e,logger:g}=i,x,C,w,D,O;try{let t=x=(await b()).newContext();t.runtime.setMemoryLimit(o),t.runtime.setMaxStackSize(s),C=d(t,c,l),O=t.unwrapResult(t.evalCode(`JSON.stringify`)),w=m?.(t,C)??void 0,D=v(()=>t.unwrapResult(t.evalCode(`(async () => {\n${e}\n})()`,S)));let n=t.resolvePromise(D);t.runtime.executePendingJobs();let r=await Promise.race([n,C.aborted]),i=v(()=>t.unwrapResult(r));if(t.typeof(i)===`undefined`)return i.dispose(),{error:p(t,h)?"The code returned undefined: the `return` ran but produced no value. Read fields off the declared return types — a field name that does not exist reads as undefined — and do not `return;` or `return undefined`.":"The code returned undefined because nothing was returned. Add a top-level `return` of the value to send back.",failure:u.NoReturn};let a=f(t,O,i);if(a.error===void 0)return a;let g=C.expiredMessage();return g===void 0?a:{error:g,failure:u.Timeout}}catch(e){let n=C?.expiredMessage();return n===void 0?e instanceof _?{error:e.message,failure:T(e.guestError,D!==void 0),errorPosition:E(e.guestError.stack)}:(g?.error(`MCP code mode sandbox failed: ${t(e)}`),{error:a,failure:u.RuntimeError}):{error:n,failure:u.Timeout}}finally{C?.dispose(),D?.dispose(),O?.dispose();try{w?.()}catch{}try{x?.dispose()}catch{y=void 0}}}const S=`sandbox-code.js`,C=/sandbox-code\.js:(\d+):(\d+)/;function w(e){let{cause:t}=e;return typeof t==`object`&&t?t:{}}function T({name:e,message:t},n){return e===`InternalError`&&t===`out of memory`?u.MemoryLimit:e===`SyntaxError`&&!n?u.SyntaxError:e===`HostOutputTooLargeError`?u.OutputTooLarge:e===`HostFunctionError`?u.HostError:u.RuntimeError}function E(e){let t=typeof e==`string`?C.exec(e):null;if(!t)return;let n=Number(t[1])-1;return n>=1?{line:n,column:Number(t[2])}:void 0}export{x as runInSandbox};
1
+ import{errorMessage as e}from"../../../../../../shared/utils/error-message.js";import{formatError as t}from"../tool-errors.js";import{DEFAULT_MAX_LIFETIME_MS as n,DEFAULT_TIMEOUT_MS as r,INITIAL_TOTAL_MEMORY_BYTES as i,INTERNAL_ERROR_MESSAGE as a,MAX_ALLOCATION_BYTES as o,MAX_STACK_SIZE_BYTES as s,MAX_TOTAL_MEMORY_BYTES as c,SANDBOX_FAILURE as l,WASM_PAGE_BYTES as u}from"./constants.js";import{createExecutionBudget as d}from"./execution-budget.js";import{readResult as f}from"./read-result.js";import{returnsFromTopLevel as p}from"./returns-from-top-level.js";import m from"@jitl/quickjs-singlefile-mjs-release-sync";import{newQuickJSWASMModuleFromVariant as h,newVariant as g}from"quickjs-emscripten-core";var _=class extends Error{guestError;name=`ReportableError`;constructor(e,t){super(e),this.guestError=t}};function v(t){try{return t()}catch(t){throw new _(e(t),w(t))}}let y;function b(){return y??=h(g(m,{wasmMemory:new WebAssembly.Memory({initial:i/u,maximum:c/u})}))}async function x(e,i={}){let{timeoutMs:c=r,deadline:u=Date.now()+n,setupContext:m,authoredCode:h=e,logger:g}=i,x,C,w,D,O;try{let t=x=(await b()).newContext();t.runtime.setMemoryLimit(o),t.runtime.setMaxStackSize(s),C=d(t,c,u),O=t.unwrapResult(t.evalCode(`JSON.stringify`)),w=m?.(t,C)??void 0,D=v(()=>t.unwrapResult(t.evalCode(`(async () => {\n${e}\n})()`,S)));let n=t.resolvePromise(D);t.runtime.executePendingJobs();let r=await Promise.race([n,C.aborted]),i=v(()=>t.unwrapResult(r));if(t.typeof(i)===`undefined`)return i.dispose(),{error:p(t,h)?"The code returned undefined: the `return` ran but produced no value. Read fields off the declared return types — a field name that does not exist reads as undefined — and do not `return;` or `return undefined`.":"The code returned undefined because nothing was returned. Add a top-level `return` of the value to send back.",failure:l.NoReturn};let a=f(t,O,i);if(a.error===void 0)return a;let g=C.expiredMessage();return g===void 0?a:{error:g,failure:l.Timeout}}catch(e){let n=C?.expiredMessage();return n===void 0?e instanceof _?{error:e.message,failure:T(e.guestError,D!==void 0),errorPosition:E(e.guestError.stack)}:(g?.error(`MCP code mode sandbox failed: ${t(e)}`),{error:a,failure:l.RuntimeError}):{error:n,failure:l.Timeout}}finally{C?.dispose(),D?.dispose(),O?.dispose();try{w?.()}catch{}try{x?.dispose()}catch{y=void 0}}}const S=`sandbox-code.js`,C=/sandbox-code\.js:(\d+):(\d+)/;function w(e){let{cause:t}=e;return typeof t==`object`&&t?t:{}}function T({name:e,message:t},n){return e===`InternalError`&&t===`out of memory`?l.MemoryLimit:e===`SyntaxError`&&!n?l.SyntaxError:e===`HostOutputTooLargeError`?l.OutputTooLarge:e===`HostFunctionError`?l.HostError:l.RuntimeError}function E(e){let t=typeof e==`string`?C.exec(e):null;if(!t)return;let n=Number(t[1])-1;return n>=1?{line:n,column:Number(t[2])}:void 0}export{x as runInSandbox};
@@ -0,0 +1,4 @@
1
+ const e=/^[A-Za-z_$][\w$]*$/;function t(t){let n=t.split(/[^A-Za-z0-9]+/).filter(Boolean).map((e,t)=>t===0?e:e[0].toUpperCase()+e.slice(1)).join(``);return e.test(n)?n:`_${n}`}function n(e,n){return n===`code`?t(e):e}function r(e){return["```ts",`declare const site: {`,e.map(e=>{let n=e.schema,r=e.outputSchema?a(e.outputSchema):`unknown`,o=n.required?.length?`input`:`input?`;return` /** ${i(e.description)} */\n ${t(e.name)}(${o}: ${a(n,` `)}): Promise<${r}>;`}).join(`
2
+ `),`};`,"```"].join(`
3
+ `)}function i(e){return(e??``).replace(/\*\//g,`*\\/`)}function a(e,t=``){if(!e||typeof e!=`object`)return`unknown`;let n=typeof e.codemodeType==`string`?[e.codemodeType]:Array.isArray(e.enum)&&e.enum.length>0?e.enum.map(s):[o(e,t)];return e.nullable&&n.push(`null`),[...new Set(n)].join(` | `)}function o(e,t){switch(e.type){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`array`:return`Array<${a(e.items,t)}>`;case`object`:return c(e,t);default:return`unknown`}}function s(e){return typeof e==`string`?`'${e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`)}'`:String(e)}function c(t,n){let r=t.properties??{},o=Object.keys(r),s=t.additionalProperties,c=s?s===!0?`unknown`:a(s,n):void 0;if(o.length===0)return s===!1?`{}`:`Record<string, ${c??`unknown`}>`;let l=new Set(t.required??[]),u=o.map(t=>{let i=r[t],o=l.has(t)?``:`?`,s=e.test(t)?t:JSON.stringify(t);return{doc:i.description,field:`${s}${o}: ${a(i,n+` `)}`}});if(c&&u.push({field:`[key: string]: ${c}`}),!u.some(({doc:e})=>e))return`{ ${u.map(({field:e})=>e).join(`; `)} }`;let d=n+` `;return`{\n${u.map(({doc:e,field:t})=>`${e?`${d}/** ${i(e)} */\n`:``}${d}${t};`).join(`
4
+ `)}\n${n}}`}export{r as buildToolTypeDeclarations,t as sanitizeToolName,n as toolNameForMode};
@@ -1,2 +1,2 @@
1
- import{mcpToolRegistry as e}from"../registry-instance.js";import{sanitizeToolName as t}from"@redocly/mcp";function n(n,r){return[...n.map(n=>({name:t(n.name),purpose:n.summary??n.description,builtIn:e.get(n.name)!==void 0})),...r.map(e=>({name:t(e.id),purpose:e.purpose,builtIn:!0}))]}function r(e,t){if(e.length===0||t<=0)return``;let n=e.map(e=>({...e,purpose:(e.purpose??``).replace(/\s+/g,` `).trim()}));for(let e of i()){let r=a(n,e);if(r.length<=t)return r}let r=e.map(e=>e.name),o=r.join(`, `);return o.length<=t?o:s(r,t)}function*i(){for(let e=60;e>=40;e--)yield{builtIn:e,custom:60};for(let e=60;e>=20;e--)yield{builtIn:0,custom:e}}function a(e,t){return e.map(({name:e,purpose:n,builtIn:r})=>{let i=r?t.builtIn:t.custom;return n&&i>0?`- ${e} — ${o(n,i)}`:`- ${e}`}).join(`
1
+ import{sanitizeToolName as e}from"./tool-declarations.js";import{mcpToolRegistry as t}from"../registry-instance.js";function n(n,r){return[...n.map(n=>({name:e(n.name),purpose:n.summary??n.description,builtIn:t.get(n.name)!==void 0})),...r.map(t=>({name:e(t.id),purpose:t.purpose,builtIn:!0}))]}function r(e,t){if(e.length===0||t<=0)return``;let n=e.map(e=>({...e,purpose:(e.purpose??``).replace(/\s+/g,` `).trim()}));for(let e of i()){let r=a(n,e);if(r.length<=t)return r}let r=e.map(e=>e.name),o=r.join(`, `);return o.length<=t?o:s(r,t)}function*i(){for(let e=60;e>=40;e--)yield{builtIn:e,custom:60};for(let e=60;e>=20;e--)yield{builtIn:0,custom:e}}function a(e,t){return e.map(({name:e,purpose:n,builtIn:r})=>{let i=r?t.builtIn:t.custom;return n&&i>0?`- ${e} — ${o(n,i)}`:`- ${e}`}).join(`
2
2
  `)}function o(e,t){return e.length<=t?e:`${e.slice(0,t-1).replace(/[\uD800-\uDBFF]$/,``).trimEnd()}…`}function s(e,t){let n=[];for(let r of e){if([...n,r].join(`, `).length+c(e.length-n.length-1).length>t)break;n.push(r)}return n.length>0?`${n.join(`, `)}${c(e.length-n.length)}`:``}function c(e){return e>0?` … (+${e} more)`:``}export{r as buildToolList,n as toToolListEntries};
@@ -0,0 +1,3 @@
1
+ import{SANDBOX_FAILURE as e}from"./constants.js";import{PLAIN_JAVASCRIPT_RULE as t}from"./prompts.js";const n=/^(?:not a function|cannot read property '.*' of (?:undefined|null)|value is not iterable|cannot convert to object)$/,r=/(?:^|[^\w$.])(?:site|tools)(?:\s*(?:\?\.|\.)\s*([A-Za-z_$][\w$]*)|(?:\s*\?\.)?\s*\[\s*(['"])([^'"]*)\2\s*\])(?:\s*\?\.)?\s*$/;function i(e,t,n,r,i){let l=n&&c(e,n),u=l!==void 0&&t===`not a function`?s(e.slice(0,l),r):void 0;if(u!==void 0)return{message:`Unknown function "site.${u}". Available functions: ${r.join(`, `)}`,unknownTool:u};let d=l===void 0?void 0:n,f=a(t,i);return f===void 0?{message:d?`${t} (line ${d.line})`:t}:{message:`${t}${d?` (line ${d.line}, column ${d.column}: \`${o(e,d)}\`)`:``}. ${f}`}}function a(r,i){if(i===e.SyntaxError)return t;if(i===e.RuntimeError&&n.test(r))return`Check the result shape with discover, for example listApis returns { items }.`}function o(e,{line:t,column:n}){let r=e.split(`
2
+ `)[t-1]??``,i=Math.max(0,Math.min(n-1-60,r.length-120)),a=i+120,o=r.slice(i,a).trim();return`${i>0?`…`:``}${o}${a<r.length?`…`:``}`}function s(e,t){let n=r.exec(e),i=n?.[1]??n?.[3];return i!==void 0&&!t.includes(i)?i:void 0}function c(e,{line:t,column:n}){let r=e.split(`
3
+ `);if(t>r.length)return;let i=r.slice(0,t-1).reduce((e,t)=>e+t.length+1,0)+n-1;return i<=e.length?i:void 0}export{i as describeGuestError};
@@ -1 +1 @@
1
- import{isEndpointHidden as e}from"../tools/openapi-document.js";import{basePathPrefix as t,operationHttpMethod as n,pathPattern as r,pathTemplateKey as i,pathVariableCount as a}from"./route-pattern.js";import{OPERATION_METHODS as o}from"@redocly/mcp";const s=new Set(o);function c(t){return e(t,`apiCalls`)||e(t,`docs`)}function l(e,i,o,l=[]){let d=t(o),f=new Set(l.map(({method:e,path:t})=>u(e&&n(e),t))),p=[];for(let[t,o]of Object.entries(e.paths??{})){if(!o||typeof o!=`object`)continue;let e=r(d,t);if(!e)continue;let l=c(o)||f.has(u(void 0,t)),m=i.paths?.[t],h=a(t);for(let[r,i]of Object.entries(o)){if(!s.has(r.toLowerCase())||!i||typeof i!=`object`)continue;let a=n(r);p.push({pattern:e,method:a,callable:!l&&!c(i)&&!f.has(u(a,t)),visible:!!m?.[r],variables:h})}}return p}function u(e,t){return`${e??`*`} ${i(t)}`}function d(e,t,n){return e.filter(e=>e.method===n&&e.pattern.test(t))}export{l as apiCallOperationsOf,d as matchingApiCallOperations};
1
+ import{OPERATION_METHODS as e,isEndpointHidden as t}from"../tools/openapi-document.js";import{basePathPrefix as n,operationHttpMethod as r,pathPattern as i,pathTemplateKey as a,pathVariableCount as o}from"./route-pattern.js";const s=new Set(e);function c(e){return t(e,`apiCalls`)||t(e,`docs`)}function l(e,t,a,l=[]){let d=n(a),f=new Set(l.map(({method:e,path:t})=>u(e&&r(e),t))),p=[];for(let[n,a]of Object.entries(e.paths??{})){if(!a||typeof a!=`object`)continue;let e=i(d,n);if(!e)continue;let l=c(a)||f.has(u(void 0,n)),m=t.paths?.[n],h=o(n);for(let[t,i]of Object.entries(a)){if(!s.has(t.toLowerCase())||!i||typeof i!=`object`)continue;let a=r(t);p.push({pattern:e,method:a,callable:!l&&!c(i)&&!f.has(u(a,n)),visible:!!m?.[t],variables:h})}}return p}function u(e,t){return`${e??`*`} ${a(t)}`}function d(e,t,n){return e.filter(e=>e.method===n&&e.pattern.test(t))}export{l as apiCallOperationsOf,d as matchingApiCallOperations};
@@ -1 +1 @@
1
- import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{toAppData as t}from"../../../../../../../shared/utils/app-data.js";import{parseSrcSet as n}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as r}from"../../../../../../../shared/constants/mcp.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(n){let a=t(await n.entities.load(e)),s=o({seo:n.config.seo,logo:a.theme?.logo,colorMode:n.config.colorMode}),c=await n.entities.get(`mcp:credentials-theme`)?await n.entities.load(r):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(n.request)).host}}function o({seo:e,logo:t,colorMode:r}){let i={},a=e?.title||e?.projectTitle||t?.altText;a&&(i.name=a);let o=new Map((t?.srcSet?n(t.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??t?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
1
+ import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{parseSrcSet as t}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as n}from"../../../../../../../shared/constants/mcp.js";import{toAppData as r}from"../../../../../../../shared/utils/app-data.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(t){let a=r(await t.entities.load(e)),s=o({seo:t.config.seo,logo:a.theme?.logo,colorMode:t.config.colorMode}),c=await t.entities.get(`mcp:credentials-theme`)?await t.entities.load(n):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(t.request)).host}}function o({seo:e,logo:n,colorMode:r}){let i={},a=e?.title||e?.projectTitle||n?.altText;a&&(i.name=a);let o=new Map((n?.srcSet?t(n.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??n?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
@@ -1 +1 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../server/constants/system-routes.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{secretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t;if(e.req.method===`GET`){let n=await h(t),i=e.req.query(`token`)??``,a=await s.peekElicitation(r,i);return a?R(a,t,n)??M({kv:r,site:n,token:i,target:a},{},200):L(n)}if(e.req.method===`POST`){let i=await h(t),o=await e.req.formData(),c=F(o,`token`),l=await s.peekElicitation(r,c);if(!l)return L(i);let u=R(l,t,i);if(u)return u;let d={kv:r,site:i,token:c,target:l,form:o,ctx:t};switch(F(o,`action`)){case n.remove:return O(d,k(l,F(o,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{kv:n,target:r}=e,i=await s.getStoredSchemes(n,r.subject,r.api),a=t.filter(e=>i[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return a.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,a)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({kv:e,site:t,token:n}){return await s.consumeElicitation(e,n)?I(t,u(),200):L(t)}async function j({kv:e,site:t,token:n},r){let i=await s.consumeElicitation(e,n);if(!i)return L(t);for(let t of r)t.kind===`remove`?await s.deleteSecret(e,i.subject,i.api,t.scheme):await s.setSecret(e,i.subject,i.api,t.scheme,t.secret);let a=await s.getStoredSchemes(e,i.subject,i.api),o={action:r.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:r.map(e=>e.scheme),stored:Object.keys(a).sort()};return I(t,p(i,o),200)}async function M({kv:e,site:t,token:n,target:r},i,a){let o=await s.getStoredSchemes(e,r.subject,r.api);return I(t,l({site:t,target:r,token:n,stored:o,...i}),a)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${e(t.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
1
+ import{SystemRoute as e}from"../../../../../../server/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./credentials-page/form-contract.js";import{secretStore as s}from"./secret-store.js";import{htmlDocument as c}from"./credentials-page/layout.js";import{formPage as l}from"./credentials-page/form-page.js";import{declinedPage as u,expiredPage as d,otherAccountPage as f,outcomePage as p,signInPage as m}from"./credentials-page/outcome-pages.js";import{loadPageSite as h}from"./credentials-page/site-branding.js";import{buildAllowedOriginMatchers as g}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as _}from"./fetch/ssrf-guard.js";import{getDefaultAgent as v,readCappedBody as y}from"./fetch/fetch-bridge.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t;if(e.req.method===`GET`){let n=await h(t),i=e.req.query(`token`)??``,a=await s.peekElicitation(r,i);return a?R(a,t,n)??M({kv:r,site:n,token:i,target:a},{},200):L(n)}if(e.req.method===`POST`){let i=await h(t),o=await e.req.formData(),c=F(o,`token`),l=await s.peekElicitation(r,c);if(!l)return L(i);let u=R(l,t,i);if(u)return u;let d={kv:r,site:i,token:c,target:l,form:o,ctx:t};switch(F(o,`action`)){case n.remove:return O(d,k(l,F(o,`scheme`)));case n.removeAll:return O(d,a(l));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=a(t),s=i.map((e,t)=>F(n,o(`client_id`,t)).trim()),c=t=>M(e,{error:t,clientIds:s},400),l=T(i,n);if(`error`in l)return c(l.error);if(l.writes.length===0)return c(E(i));let u=[];for(let e of l.writes){if(e.kind!==`exchange`){u.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),c(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));u.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,u)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let s=F(t,o(`secret`,r)).trim();if(s){let t=i(a.auth,s);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,s)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let c=F(t,o(`client_id`,r)).trim(),l=F(t,o(`client_secret`,r)).trim();if(c&&l)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:c,clientSecret:l});else if(c||l)return{error:D(e,r,c?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{kv:n,target:r}=e,i=await s.getStoredSchemes(n,r.subject,r.api),a=t.filter(e=>i[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return a.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,a)}function k(e,t){let n=S.test(t)?a(e)[Number(t)]:void 0;return n?[n]:[]}async function A({kv:e,site:t,token:n}){return await s.consumeElicitation(e,n)?I(t,u(),200):L(t)}async function j({kv:e,site:t,token:n},r){let i=await s.consumeElicitation(e,n);if(!i)return L(t);for(let t of r)t.kind===`remove`?await s.deleteSecret(e,i.subject,i.api,t.scheme):await s.setSecret(e,i.subject,i.api,t.scheme,t.secret);let a=await s.getStoredSchemes(e,i.subject,i.api),o={action:r.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:r.map(e=>e.scheme),stored:Object.keys(a).sort()};return I(t,p(i,o),200)}async function M({kv:e,site:t,token:n,target:r},i,a){let o=await s.getStoredSchemes(e,r.subject,r.api);return I(t,l({site:t,target:r,token:n,stored:o,...i}),a)}async function N(e,t,n){try{let r=g([{url:e.tokenUrl}]),a=_(e.tokenUrl,r),o=new AbortController,s=setTimeout(()=>o.abort(),3e4),c;try{c=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:o.signal,dispatcher:v()})}finally{clearTimeout(s)}if(!c.ok)return P(`token endpoint returned ${c.status}`);let l;try{l=await y(c,65536)}catch{return P(`token response exceeded the size cap`)}let u;try{u=JSON.parse(l)}catch{return P(`token response was not valid JSON`)}let d=typeof u==`object`&&u&&`access_token`in u?u.access_token:void 0,f=typeof d==`string`?d.trim():``;return f?i(e,f)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${f}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(c(t,e),{status:n,headers:b})}function L(e){return I(e,d(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,f(o?.email),403);let c=`${t(e.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,m(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
@@ -1,7 +1,7 @@
1
- import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as n}from"./subject.js";import{secretStore as r}from"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as o}from"@redocly/mcp";import{CLIENT_CAPABILITIES_META_KEY as s,inputRequired as c,inputResponse as l}from"@modelcontextprotocol/server";const u=`credentials`,d=/* @__PURE__ */ new Map;function f(e,t){let n=d.get(e);if(n)return n;let r=t().finally(()=>{d.delete(e)});return d.set(e,r),r}function p(e){return!!(e.envelope?.[s])?.elicitation?.url}function m(e){return e.envelope!==void 0}function h(e){let t=l(e,u);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function g(e,{url:t,canManageCredentials:n}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...t?[`The credentials page:`,t]:[],``,n?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${o}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
2
- `)}async function _(e,{kv:t,subject:n,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await r.peekElicitation(t,e);if(o?.subject===n&&a.includes(o.api))return{apiName:o.name,url:A(i,e)}}function v(e,t){return Object.keys(e).length>1?t:void 0}async function y(e){let{token:t,url:n}=await w(e);return c({inputRequests:{[u]:c.elicitUrl({message:D(e),url:n})},requestState:t})}async function b(e){let{url:t}=await w(e);return j(e,t,E(e.subject))}function x(e,{schemeLabel:t,canManageCredentials:n}){let r=C(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${r}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
3
- `);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${t?`"${t}" `:``}credential (${r}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...n?[``,...S(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${o}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
4
- `);let i=e.status===401?`The "${e.name}" API rejected the stored ${t?`"${t}" `:``}credential (${r}).`:`The "${e.name}" API rejected the request with ${r}.`;if(!n)return[i,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
5
- `);let a=t?`api: "${e.api}" and scheme: "${t}"`:`api: "${e.api}"`;return[i,``,...S(e),`Do not retry the same call. Call \`${o}\` with ${a} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
6
- `)}function S(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function C({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function w({kv:e,subject:t,baseUrl:n,target:i,auth:a,apiAuth:o}){let s=o?T(o):[],c=await r.createElicitation(e,{subject:t,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:A(n,c)}}function T(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function E(e){return e.startsWith(`anon:`)?e.slice(n.length):void 0}function D({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=O(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${k(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function O({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}function A(n,r){let i=new URL(e(t),n);return i.searchParams.set(`token`,r),i.toString()}function j({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
1
+ import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t,MCP_CREDENTIALS_ROUTE as n}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import{secretStore as i}from"./secret-store.js";import{operationsForScheme as a,orderedSchemesOf as o}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as s,inputRequired as c,inputResponse as l}from"@modelcontextprotocol/server";const u=`credentials`,d=/* @__PURE__ */ new Map;function f(e,t){let n=d.get(e);if(n)return n;let r=t().finally(()=>{d.delete(e)});return d.set(e,r),r}function p(e){return!!(e.envelope?.[s])?.elicitation?.url}function m(e){return e.envelope!==void 0}function h(e){let t=l(e,u);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function g(e,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${t}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
2
+ `)}async function _(e,{kv:t,subject:n,baseUrl:r,apis:a}){if(typeof e!=`string`)return;let o=await i.peekElicitation(t,e);if(o?.subject===n&&a.includes(o.api))return{apiName:o.name,url:A(r,e)}}function v(e,t){return Object.keys(e).length>1?t:void 0}async function y(e){let{token:t,url:n}=await w(e);return c({inputRequests:{[u]:c.elicitUrl({message:D(e),url:n})},requestState:t})}async function b(e){let{url:t}=await w(e);return j(e,t,E(e.subject))}function x(e,{schemeLabel:n,canManageCredentials:r}){let i=C(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
3
+ `);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...S(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${t}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
4
+ `);let a=e.status===401?`The "${e.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${e.name}" API rejected the request with ${i}.`;if(!r)return[a,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
5
+ `);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"`;return[a,``,...S(e),`Do not retry the same call. Call \`${t}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
6
+ `)}function S(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function C({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function w({kv:e,subject:t,baseUrl:n,target:r,auth:a,apiAuth:o}){let s=o?T(o):[],c=await i.createElicitation(e,{subject:t,api:r.api,name:r.name,scheme:r.scheme,schemeLabel:r.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?r.acceptedSchemes:void 0});return{token:c,url:A(n,c)}}function T(e){return o(e.schemes).map(t=>{let n=a(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function E(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function D({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=O(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${k(i)} needs credentials.${a} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function O({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function k(e){return e.charAt(0).toUpperCase()+e.slice(1)}function A(t,r){let i=new URL(e(n),t);return i.searchParams.set(`token`,r),i.toString()}function j({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
7
7
  `)}export{u as CREDENTIALS_INPUT_REQUEST_KEY,_ as acceptedCredentialsLink,g as buildCredentialsAcceptedHint,x as buildCredentialsToolHint,b as buildUpstreamCredentialFallback,y as buildUpstreamCredentialInputRequired,h as credentialElicitationAnswer,f as dedupeElicitation,m as isStatelessRequest,v as schemeLabelOf,p as supportsUrlElicitation};
@@ -1,5 +1,5 @@
1
- import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{formatError as n}from"../tool-errors.js";import{callAttribution as r}from"../audit.js";import{isToolDisabledByCaller as i}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as a}from"../codemode/constants.js";import{resolveSecretSubject as o}from"./subject.js";import{ipRateLimitKey as s}from"../rate-limit.js";import{callableApis as c,excludedOperations as l}from"./eligibility.js";import{getAllowedHttpMethods as u}from"./allowed-http-methods.js";import{apiCallOperationsOf as d}from"./api-call-operations.js";import{secretStore as f}from"./secret-store.js";import{buildAllowedOriginMatchers as p}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as m}from"./fetch/fetch-errors.js";import{buildFetchBridge as h}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as g,orderedSchemesOf as _,resolveUpstreamApiAuth as v}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as y,buildCredentialsAcceptedHint as b,buildCredentialsToolHint as x,buildUpstreamCredentialFallback as S,buildUpstreamCredentialInputRequired as C,credentialElicitationAnswer as w,dedupeElicitation as T,isStatelessRequest as E,schemeLabelOf as D,supportsUrlElicitation as O}from"./elicitation.js";import{applyFetchCount as k}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as A,upstreamAuthKey as j}from"./upstream-auth.js";import{createAnonymousSessionTool as M,manageApiCredentialsTool as N,removeApiCredentialsTool as P}from"./tools.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as F}from"@redocly/mcp";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[M,N,P]}function R(e){return new Map(e.map(e=>[e.relativePath,v(e)]))}function z(e,t,n,i,a,o,s){return h({apis:t.map(t=>{let r=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:p(t.servers),secrets:i?.[t.relativePath],defaultScheme:r.defaultScheme,routes:r.routes,credentialHeaders:g(r.schemes),credentialQueryParams:r.credentialQueryParams,schemePriority:_(r.schemes),operations:d(t.fullDefinition,t.definition,t.servers,l(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:r(e),allowedHttpMethods:u(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=r(e),i={subject:t,ip:n&&s(n)};return async()=>{let t=await k(e.kv,i,a,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new m(t.message)}}async function V(e,t){if(t)try{return await f.getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${n(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:e,sessionHandle:t,serverContext:n,run:r},a){let s=o(e,t);if(s.kind===`invalid`)return{content:[{type:`text`,text:s.message}],isError:!0};let l=s.kind===`resolved`?s.subject:void 0,[u,d]=await Promise.all([c(e),V(e,l)]),f=R(u),p=[],m=new AbortController,h=await r(z(e,u,f,d,e=>p.push(e),a,m.signal)).finally(()=>m.abort());if(p.length===0)return h;let g=A(p).map(e=>q(e,f));if(s.kind===`anonymous`)return g.some(e=>e.schemes)?K(h,[{type:`text`,text:s.message}]):K(h,[{type:`text`,text:Z(g,{plans:f,canManageCredentials:!1})},...h.content]);let _=E(n.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${_?`2026-07-28`:`2025`} urlElicitation=${O(n.mcpReq)}`);let v={ctx:e,serverContext:n,subject:s.subject,stored:J(d),plans:f,canManageCredentials:!i(F,e.metadata)},y=_?await $(v,g,!a.some(W)):await ee(v,g);switch(y.kind){case`inputRequired`:return y.result;case`prependText`:return K(h,[{type:`text`,text:y.text},...h.content]);case`none`:return h}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(t,n){if(!t.isError||n.length===0)return t;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
1
+ import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t}from"../../constants.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{formatError as r}from"../tool-errors.js";import{callAttribution as i}from"../audit.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as o}from"../codemode/constants.js";import{resolveSecretSubject as s}from"./subject.js";import{ipRateLimitKey as c}from"../rate-limit.js";import{callableApis as l,excludedOperations as u}from"./eligibility.js";import{getAllowedHttpMethods as d}from"./allowed-http-methods.js";import{apiCallOperationsOf as f}from"./api-call-operations.js";import{secretStore as p}from"./secret-store.js";import{buildAllowedOriginMatchers as m}from"./fetch/allowed-hosts.js";import{GatewayFetchUserError as h}from"./fetch/fetch-errors.js";import{buildFetchBridge as g}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as _,orderedSchemesOf as v,resolveUpstreamApiAuth as y}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as b,buildCredentialsAcceptedHint as x,buildCredentialsToolHint as S,buildUpstreamCredentialFallback as C,buildUpstreamCredentialInputRequired as w,credentialElicitationAnswer as T,dedupeElicitation as E,isStatelessRequest as D,schemeLabelOf as O,supportsUrlElicitation as k}from"./elicitation.js";import{applyFetchCount as A}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as j,upstreamAuthKey as M}from"./upstream-auth.js";import{createAnonymousSessionTool as N,manageApiCredentialsTool as P,removeApiCredentialsTool as F}from"./tools.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(){return[N,P,F]}function R(e){return new Map(e.map(e=>[e.relativePath,y(e)]))}function z(e,t,n,r,a,o,s){return g({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:m(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:_(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:v(i.schemes),operations:f(t.fullDefinition,t.definition,t.servers,u(e,t.relativePath))}}),onAuthRequired:a,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:i(e),allowedHttpMethods:d(e.config.mcp)})}function B(e){let{callerSubject:t,clientIp:n}=i(e),r={subject:t,ip:n&&c(n)};return async()=>{let t=await A(e.kv,r,o,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new h(t.message)}}async function V(e,t){if(t)try{return await p.getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${r(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:e,sessionHandle:n,serverContext:r,run:i},o){let c=s(e,n);if(c.kind===`invalid`)return{content:[{type:`text`,text:c.message}],isError:!0};let u=c.kind===`resolved`?c.subject:void 0,[d,f]=await Promise.all([l(e),V(e,u)]),p=R(d),m=[],h=new AbortController,g=await i(z(e,d,p,f,e=>m.push(e),o,h.signal)).finally(()=>h.abort());if(m.length===0)return g;let _=j(m).map(e=>q(e,p));if(c.kind===`anonymous`)return _.some(e=>e.schemes)?K(g,[{type:`text`,text:c.message}]):K(g,[{type:`text`,text:Z(_,{plans:p,canManageCredentials:!1})},...g.content]);let v=D(r.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${v?`2026-07-28`:`2025`} urlElicitation=${k(r.mcpReq)}`);let y={ctx:e,serverContext:r,subject:c.subject,stored:J(f),plans:p,canManageCredentials:!a(t,e.metadata)},b=v?await $(y,_,!o.some(W)):await ee(y,_);switch(b.kind){case`inputRequired`:return b.result;case`prependText`:return K(g,[{type:`text`,text:b.text},...g.content]);case`none`:return g}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(t,n){if(!t.isError||n.length===0)return t;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
2
2
  `+r.map(e=>`${e.method} ${e.url} -> ${e.status??`no response`}`).join(`
3
- `);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(j({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(j(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?D(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>x(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
3
+ `);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(M({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(M(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?O(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>S(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
4
4
 
5
- `)}function Q({ctx:e,subject:n,plans:r},i){let[a,...o]=i,s=r.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:n,baseUrl:t(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,r),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,n,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=w(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=n.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(n,e)};if(l===`accepted`){let e=await y(a.mcpReq.requestState(),{kv:i.kv,subject:o,baseUrl:t(i.request),apis:u.map(e=>e.api)}),n=e?.apiName??u[0].name;return{kind:`prependText`,text:b(n,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!O(a.mcpReq)?{kind:`prependText`,text:await S(d)}:{kind:`inputRequired`,result:await C(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await T(`${e.subject}:${j(n[0])}`,()=>S(r))}}export{L as gatewayTools,H as runExecuteWithGateway};
5
+ `)}function Q({ctx:e,subject:t,plans:r},i){let[a,...o]=i,s=r.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:t,baseUrl:n(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,r),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,t,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=T(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=t.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(t,e)};if(l===`accepted`){let e=await b(a.mcpReq.requestState(),{kv:i.kv,subject:o,baseUrl:n(i.request),apis:u.map(e=>e.api)}),t=e?.apiName??u[0].name;return{kind:`prependText`,text:x(t,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!k(a.mcpReq)?{kind:`prependText`,text:await C(d)}:{kind:`inputRequired`,result:await w(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await E(`${e.subject}:${M(n[0])}`,()=>C(r))}}export{L as gatewayTools,H as runExecuteWithGateway};
@@ -1 +1 @@
1
- import{isToolDisabledByCaller as e}from"../disabled-tools.js";import{randomBytes as t}from"node:crypto";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as n}from"@redocly/mcp";const r=/^[A-Za-z0-9_-]{43}$/,i=`anon:`,a=`user:`,o=`This API requires credentials and the caller is anonymous; call createAnonymousSession first, then retry with sessionHandle`,s=`The sessionHandle is not a valid handle; call createAnonymousSession to obtain one`,c=`This API requires credentials, and this client cannot add them for an anonymous caller. Tell the user that the API needs credentials and that, if this site offers sign-in, they can sign in and ask again. Do not retry the call.`;function l(){return t(32).toString(`base64url`)}function u(e){return r.test(e)}function d(e){if(!e?.isAuthenticated)return;let t=e.sub||e.email;if(t)return`${a}${e.idpId||`local`}:${t}`}function f(t,r){let a=d(t.request.viewer);return a?{kind:`resolved`,subject:a}:e(n,t.metadata)?{kind:`anonymous`,message:c}:typeof r==`string`?u(r)?{kind:`resolved`,subject:`${i}${r}`}:{kind:`invalid`,message:s}:{kind:`anonymous`,message:o}}function p(e){return e.startsWith(`anon:`)?86400:604800}export{c as ANONYMOUS_CREDENTIALS_UNAVAILABLE_MESSAGE,i as ANONYMOUS_SUBJECT_PREFIX,s as MALFORMED_SESSION_HANDLE_MESSAGE,o as MISSING_SESSION_HANDLE_MESSAGE,a as USER_SUBJECT_PREFIX,l as createSessionHandle,u as isValidSessionHandle,f as resolveSecretSubject,p as secretTtlSeconds,d as userSubject};
1
+ import"../../constants.js";import{isToolDisabledByCaller as e}from"../disabled-tools.js";import{randomBytes as t}from"node:crypto";const n=/^[A-Za-z0-9_-]{43}$/,r=`anon:`,i=`user:`,a=`This API requires credentials and the caller is anonymous; call createAnonymousSession first, then retry with sessionHandle`,o=`The sessionHandle is not a valid handle; call createAnonymousSession to obtain one`,s=`This API requires credentials, and this client cannot add them for an anonymous caller. Tell the user that the API needs credentials and that, if this site offers sign-in, they can sign in and ask again. Do not retry the call.`;function c(){return t(32).toString(`base64url`)}function l(e){return n.test(e)}function u(e){if(!e?.isAuthenticated)return;let t=e.sub||e.email;if(t)return`${i}${e.idpId||`local`}:${t}`}function d(t,n){let i=u(t.request.viewer);return i?{kind:`resolved`,subject:i}:e(`createAnonymousSession`,t.metadata)?{kind:`anonymous`,message:s}:typeof n==`string`?l(n)?{kind:`resolved`,subject:`${r}${n}`}:{kind:`invalid`,message:o}:{kind:`anonymous`,message:a}}function f(e){return e.startsWith(`anon:`)?86400:604800}export{s as ANONYMOUS_CREDENTIALS_UNAVAILABLE_MESSAGE,r as ANONYMOUS_SUBJECT_PREFIX,o as MALFORMED_SESSION_HANDLE_MESSAGE,a as MISSING_SESSION_HANDLE_MESSAGE,i as USER_SUBJECT_PREFIX,c as createSessionHandle,l as isValidSessionHandle,d as resolveSecretSubject,f as secretTtlSeconds,u as userSubject};
@@ -1,4 +1,4 @@
1
- import{publicOrigin as e}from"../../../../utils/request-origin.js";import{isToolDisabledByCaller as t}from"../disabled-tools.js";import{createSessionHandle as n,resolveSecretSubject as r}from"./subject.js";import{apiTitleKey as i,countApiTitles as a}from"../tools/api-titles.js";import{callableApis as o}from"./eligibility.js";import{secretStore as s}from"./secret-store.js";import{resolveUpstreamApiAuth as c}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as l,buildCredentialsAcceptedHint as u,buildUpstreamCredentialFallback as d,buildUpstreamCredentialInputRequired as f,credentialElicitationAnswer as p,dedupeElicitation as m,isStatelessRequest as h,schemeLabelOf as g,supportsUrlElicitation as _}from"./elicitation.js";import{upstreamAuthKey as v}from"./upstream-auth.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as y,MANAGE_API_CREDENTIALS_TOOL_NAME as b,READ_ONLY_ANNOTATIONS as x,REMOVE_API_CREDENTIALS_TOOL_NAME as S,toolNameForMode as C}from"@redocly/mcp";async function w(e){return(await o(e)).length>0}const T={schema:{name:y,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:x,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!t(y,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:n()};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,n){return{name:b,title:`Manage API credentials`,description:[n?`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.`,n?`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 \`${S}\` 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=a(e);return e.map(e=>e.name).filter(e=>t.get(i(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,i){let a=r(n,t.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:y}=a,b=A(await o(n),t.api);if(`error`in b)return b.error;let{api:x}=b,S=e(n.request),C=p(i?.mcpReq.inputResponses);if(C===`accepted`){let e=await l(i?.mcpReq.requestState(),{kv:n.kv,subject:y,baseUrl:S,apis:[x.relativePath]});return{content:[{type:`text`,text:u(x.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(C===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${x.name}" API, so this call minted no link.`}],isError:!1};let w=c(x),T=typeof t.scheme==`string`?t.scheme:void 0,E=Object.keys(w.schemes);if(T&&!w.schemes[T])return j(T,x,E);let D=T??w.defaultScheme,O={subject:y,baseUrl:S,target:{api:x.relativePath,name:x.name,scheme:D,schemeLabel:T?g(w.schemes,T):void 0},auth:w.schemes[D],apiAuth:w,kv:n.kv,hasExistingSecret:await s.hasSecret(n.kv,y,x.relativePath,D),reason:{kind:`requested`}};if(i&&h(i.mcpReq)&&_(i.mcpReq))return f(O);let k=v({api:x.relativePath,scheme:D});return{content:[{type:`text`,text:await m(`${y}:${k}`,()=>d(O))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await o(e),e.mcpMode,!t(S,e.metadata)),isAvailable:async e=>!t(b,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n)};function F(e,t,n){return{name:S,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.${n?` To replace a credential, call \`${b}\` 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=r(t,e.sessionHandle);if(n.kind!==`resolved`)return N(n.message);let{subject:i}=n,a=await o(t),l=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return l===void 0?e.all===!0?L(await s.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 "${l}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let u=A(a,e.api);if(`error`in u)return u.error;let{api:d}=u;if(l===void 0)return L(await s.deleteSecrets(t.kv,i,d.relativePath),a,`No credentials are stored for the "${d.name}" API, so nothing was removed.`);let f=Object.keys(c(d).schemes);if(!f.includes(l))return j(l,d,f);let p=`No credential is stored for the "${l}" scheme of the "${d.name}" API, so nothing was removed.`;return await s.hasSecret(t.kv,i,d.relativePath,l)?(await s.deleteSecret(t.kv,i,d.relativePath,l),L([{api:d.relativePath,scheme:l}],a,p)):L([],a,p)}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 o(e),e.mcpMode,!t(b,e.metadata)),isAvailable:async e=>!t(S,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{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,REMOVE_API_CREDENTIALS_TOOL_NAME as n}from"../../constants.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{isToolDisabledByCaller as i}from"../disabled-tools.js";import{createSessionHandle as a,resolveSecretSubject as o}from"./subject.js";import{toolNameForMode as s}from"../codemode/tool-declarations.js";import{READ_ONLY_ANNOTATIONS as c}from"../tools/schemas.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:c,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!i(`createAnonymousSession`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:a()};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 \`${s(`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,r,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 \`${n}\` 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,r,`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 i=o(t,e.sessionHandle);if(i.kind!==`resolved`)return N(i.message);let{subject:a}=i,s=A(await d(t),e.api);if(`error`in s)return s.error;let{api:c}=s,l=r(t.request),u=v(n?.mcpReq.inputResponses);if(u===`accepted`){let e=await m(n?.mcpReq.requestState(),{kv:t.kv,subject:a,baseUrl:l,apis:[c.relativePath]});return{content:[{type:`text`,text:h(c.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(u===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${c.name}" API, so this call minted no link.`}],isError:!1};let w=p(c),T=typeof e.scheme==`string`?e.scheme:void 0,E=Object.keys(w.schemes);if(T&&!w.schemes[T])return j(T,c,E);let D=T??w.defaultScheme,O={subject:a,baseUrl:l,target:{api:c.relativePath,name:c.name,scheme:D,schemeLabel:T?x(w.schemes,T):void 0},auth:w.schemes[D],apiAuth:w,kv:t.kv,hasExistingSecret:await f.hasSecret(t.kv,a,c.relativePath,D),reason:{kind:`requested`}};if(n&&b(n.mcpReq)&&S(n.mcpReq))return _(O);let k=C({api:c.relativePath,scheme:D});return{content:[{type:`text`,text:await y(`${a}:${k}`,()=>g(O))}],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,!i(n,e.metadata)),isAvailable:async e=>!i(`manageApiCredentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n)};function F(e,r,i){return{name:n,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,r,`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=o(t,e.sessionHandle);if(n.kind!==`resolved`)return N(n.message);let{subject:r}=n,i=await d(t),a=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return a===void 0?e.all===!0?L(await f.deleteSecrets(t.kv,r),i,`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 "${a}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let s=A(i,e.api);if(`error`in s)return s.error;let{api:c}=s;if(a===void 0)return L(await f.deleteSecrets(t.kv,r,c.relativePath),i,`No credentials are stored for the "${c.name}" API, so nothing was removed.`);let l=Object.keys(p(c).schemes);if(!l.includes(a))return j(a,c,l);let u=`No credential is stored for the "${a}" scheme of the "${c.name}" API, so nothing was removed.`;return await f.hasSecret(t.kv,r,c.relativePath,a)?(await f.deleteSecret(t.kv,r,c.relativePath,a),L([{api:c.relativePath,scheme:a}],i,u)):L([],i,u)}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,!i(t,e.metadata)),isAvailable:async e=>!i(`removeApiCredentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
@@ -1,2 +1,2 @@
1
- import{basePathPrefix as e,operationHttpMethod as t,pathPattern as n,pathVariableCount as r}from"./route-pattern.js";import{OPERATION_METHODS as i}from"@redocly/mcp";const a=`default`,o={kind:`raw`},s=[`oauth2ClientCredentials`,`bearer`,`apiKey`,`cookie`,`raw`],c=new Set(i);function l(){return{schemes:{[a]:o},defaultScheme:a,routes:[],credentialQueryParams:[]}}function u(e){let{definition:t,servers:n}=e,r=_(t),i=Object.keys(r),a=d(t);if(i.length===0)return{...l(),credentialQueryParams:a};let o={schemes:r,defaultScheme:b(t.security,r)[0]??y(i,r)[0],routes:x(t,r,n),credentialQueryParams:a},s=g(t,i);return Object.keys(s).length>0&&(o.descriptions=s),o}function d(e){let t=/* @__PURE__ */ new Set;for(let n of Object.values(e.components?.securitySchemes??{}))S(n)&&n.type===`apiKey`&&n.in===`query`&&n.name&&t.add(n.name);return[...t]}function f(e){return[...new Set(Object.values(e).map(h))]}function p(e){return y(Object.keys(e),e)}function m(e,t){let n=/* @__PURE__ */ new Set;for(let r of e.routes)r.schemes?.includes(t)&&n.add(`${r.method} ${r.path}`);return[...n]}function h(e){return e.kind===`apiKey`?e.header:e.kind===`cookie`?`Cookie`:`Authorization`}function g(e,t){let n={};for(let r of t){let t=e.components?.securitySchemes?.[r],i=S(t)?t.description:void 0;if(typeof i!=`string`)continue;let a=i.split(`
2
- `)[0].trim();a&&(n[r]=a.slice(0,120))}return n}function _(e){let t={};for(let[n,r]of Object.entries(e.components?.securitySchemes??{})){if(!S(r))continue;let e=v(r);e&&(t[n]=e)}return t}function v(e){if(e.type===`oauth2`){let t=e.flows?.clientCredentials;return t?{kind:`oauth2ClientCredentials`,tokenUrl:t.tokenUrl,scopes:Object.keys(t.scopes??{})}:{kind:`bearer`}}if(e.type===`openIdConnect`||e.type===`http`&&e.scheme?.toLowerCase()===`bearer`)return{kind:`bearer`};if(e.type===`apiKey`&&e.in===`header`)return{kind:`apiKey`,header:e.name||`X-Api-Key`};if(e.type===`apiKey`&&e.in===`cookie`&&e.name)return{kind:`cookie`,name:e.name}}function y(e,t){return[...e].sort((n,r)=>s.indexOf(t[n].kind)-s.indexOf(t[r].kind)||e.indexOf(n)-e.indexOf(r))}function b(e,t){let n=[];for(let r of e??[])for(let e of Object.keys(r))t[e]&&!n.includes(e)&&n.push(e);return n}function x(i,a,o){let s=e(o),l=[];for(let[e,r]of Object.entries(i.paths??{})){if(!r||typeof r!=`object`)continue;let o=n(s,e);if(o)for(let[n,s]of Object.entries(r)){if(!c.has(n.toLowerCase()))continue;let r=s?.security??i.security,u={pattern:o,path:e,method:t(n)};if(l.push(u),r===void 0)continue;let d=b(r,a);u.schemes=y(d,a);let f=r.map(e=>Object.keys(e)),p=d.length===0&&f.every(e=>e.length>0)?[...new Set(f.flat())]:[];p.length>0&&(u.unsupportedSchemes=p)}}return l.sort((e,t)=>r(e.path)-r(t.path))}function S(e){return typeof e==`object`&&!!e&&`type`in e}export{a as DEFAULT_SCHEME_NAME,f as credentialHeadersOf,m as operationsForScheme,p as orderedSchemesOf,u as resolveUpstreamApiAuth};
1
+ import{OPERATION_METHODS as e}from"../tools/openapi-document.js";import{basePathPrefix as t,operationHttpMethod as n,pathPattern as r,pathVariableCount as i}from"./route-pattern.js";const a=`default`,o={kind:`raw`},s=[`oauth2ClientCredentials`,`bearer`,`apiKey`,`cookie`,`raw`],c=new Set(e);function l(){return{schemes:{[a]:o},defaultScheme:a,routes:[],credentialQueryParams:[]}}function u(e){let{definition:t,servers:n}=e,r=_(t),i=Object.keys(r),a=d(t);if(i.length===0)return{...l(),credentialQueryParams:a};let o={schemes:r,defaultScheme:b(t.security,r)[0]??y(i,r)[0],routes:x(t,r,n),credentialQueryParams:a},s=g(t,i);return Object.keys(s).length>0&&(o.descriptions=s),o}function d(e){let t=/* @__PURE__ */ new Set;for(let n of Object.values(e.components?.securitySchemes??{}))S(n)&&n.type===`apiKey`&&n.in===`query`&&n.name&&t.add(n.name);return[...t]}function f(e){return[...new Set(Object.values(e).map(h))]}function p(e){return y(Object.keys(e),e)}function m(e,t){let n=/* @__PURE__ */ new Set;for(let r of e.routes)r.schemes?.includes(t)&&n.add(`${r.method} ${r.path}`);return[...n]}function h(e){return e.kind===`apiKey`?e.header:e.kind===`cookie`?`Cookie`:`Authorization`}function g(e,t){let n={};for(let r of t){let t=e.components?.securitySchemes?.[r],i=S(t)?t.description:void 0;if(typeof i!=`string`)continue;let a=i.split(`
2
+ `)[0].trim();a&&(n[r]=a.slice(0,120))}return n}function _(e){let t={};for(let[n,r]of Object.entries(e.components?.securitySchemes??{})){if(!S(r))continue;let e=v(r);e&&(t[n]=e)}return t}function v(e){if(e.type===`oauth2`){let t=e.flows?.clientCredentials;return t?{kind:`oauth2ClientCredentials`,tokenUrl:t.tokenUrl,scopes:Object.keys(t.scopes??{})}:{kind:`bearer`}}if(e.type===`openIdConnect`||e.type===`http`&&e.scheme?.toLowerCase()===`bearer`)return{kind:`bearer`};if(e.type===`apiKey`&&e.in===`header`)return{kind:`apiKey`,header:e.name||`X-Api-Key`};if(e.type===`apiKey`&&e.in===`cookie`&&e.name)return{kind:`cookie`,name:e.name}}function y(e,t){return[...e].sort((n,r)=>s.indexOf(t[n].kind)-s.indexOf(t[r].kind)||e.indexOf(n)-e.indexOf(r))}function b(e,t){let n=[];for(let r of e??[])for(let e of Object.keys(r))t[e]&&!n.includes(e)&&n.push(e);return n}function x(e,a,o){let s=t(o),l=[];for(let[t,i]of Object.entries(e.paths??{})){if(!i||typeof i!=`object`)continue;let o=r(s,t);if(o)for(let[r,s]of Object.entries(i)){if(!c.has(r.toLowerCase()))continue;let i=s?.security??e.security,u={pattern:o,path:t,method:n(r)};if(l.push(u),i===void 0)continue;let d=b(i,a);u.schemes=y(d,a);let f=i.map(e=>Object.keys(e)),p=d.length===0&&f.every(e=>e.length>0)?[...new Set(f.flat())]:[];p.length>0&&(u.unsupportedSchemes=p)}}return l.sort((e,t)=>i(e.path)-i(t.path))}function S(e){return typeof e==`object`&&!!e&&`type`in e}export{a as DEFAULT_SCHEME_NAME,f as credentialHeadersOf,m as operationsForScheme,p as orderedSchemesOf,u as resolveUpstreamApiAuth};
@@ -1 +1 @@
1
- import{isObject as e}from"../../../../../shared/utils/is-object.js";import{formatError as t}from"./tool-errors.js";import{auditToolCall as n,callAttribution as r}from"./audit.js";import{CODE_MODE_TOOL_NAMES as i,FETCH_TOOL_NAME as a}from"./codemode/constants.js";import{resolveMcpMode as o,resolveRequestMcpMode as s}from"./mode.js";import{sendMcpRequestError as c}from"./mcp-telemetry.js";import{availableTools as l,isToolAvailable as u,normalizeToolDisplayName as d}from"./tool-registry.js";import{mcpJsonSchemaValidator as f}from"./json-schema-validator.js";import{toToolListEntries as p}from"./codemode/tool-list.js";import{buildCodeModeInstructions as m,buildExecuteDescription as h,buildToolsModeInstructions as g}from"./codemode/prompts.js";import{composeExecuteAnnotations as _,getActiveCapabilities as v}from"./codemode/capabilities.js";import{discover as y,discoverSchema as b}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as x,executeOutputSchema as S,executeToolTitle as C}from"./codemode/execute-schema.js";import{runCodeMode as w}from"./codemode/index.js";import{docsServerInfo as T}from"./server-info.js";import{loadSkillResources as E}from"./skills-resources.js";import{randomUUID as D}from"node:crypto";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as O,DISCOVER_TOOL_NAME as k,EXECUTE_TOOL_NAME as A}from"@redocly/mcp";import{McpServer as j,createMcpHandler as M,fromJsonSchema as N,isCallToolResult as P,isInputRequiredResult as F}from"@modelcontextprotocol/server";const I=`text/markdown`,L={listChanged:!1};function R(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a}=d(e);return{title:t,description:n,inputSchema:N(r,f),outputSchema:i?N(i,f):void 0,annotations:a}}function z(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function B(t,n){if(P(t)||F(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 V(e,t){return(r,i)=>n(e,t.schema.name,r,async()=>B(await t.execute(r,e,i),e.mcpMode))}function H(e,t){return new j(e,{capabilities:{logging:{},tools:L},maxToolInputElements:1e4,instructions:t})}async function U(e,t,r){let[o,s]=await Promise.all([l(r,t),v(t)]),c=s.some(e=>e.id===a),d=o.filter(e=>!i.has(e.schema.name)).map(e=>e.schema),f=o.filter(({schema:e})=>i.has(e.name)&&e.name!==A&&e.name!==k),g=t.instructionsStyle!==`brief`,T=g?p(d,s):[],E=f.some(e=>e.schema.name===O),D=H(e,m(c,T,e.websiteUrl)),j=_(d,s,t.config.mcp);D.registerTool(A,R({...z(E,x),title:C(j),description:h(c,T,e.websiteUrl),outputSchema:S(c),annotations:j}),async(e,i)=>{let a=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,o=i=>n(t,A,e,()=>w({code:e.code,description:e.description,sessionHandle:a,fetchBudget:50,registry:r,ctx:t,hostFetch:i}));if(!c)return o();let{runExecuteWithGateway:s}=await import(`./gateway/index.js`);return s({ctx:t,sessionHandle:a,serverContext:i,run:o})});let M=y(d,async e=>{let n=r.get(e);return n!==void 0&&await u(n,t)},s,t);D.registerTool(k,R(b(d,s,g)),e=>n(t,k,e,()=>M(e)));for(let e of f)D.registerTool(e.schema.name,R(z(E,e.schema)),V(t,e));return D}async function W(e,t,n){let r=new Map((await l(n,t)).map(e=>[e.schema.name,e])),i=H(e,g(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,R({...n.schema,outputSchema:void 0}),V(t,n));r.has(n.schema.name)||a.disable()}return i}async function G(e,t,n){let r=T(e.config,e.request),i=e.mcpMode===`code`?await U(r,e,t):await W(r,e,t);n.length>0&&i.server.registerCapabilities({resources:L});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:I},async()=>({contents:[{uri:e.uri,mimeType:I,text:await e.read()}]}));return i}function K(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 q(){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 J(e){return async n=>{let i;try{i=await e.buildToolContext(n);let t=await E(i),r=await G(i,e.registry,t),a=M(()=>r,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(n);return n.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),K(o)}catch(a){if(e.onError)await e.onError(a);else{let l=i?r(i):{requestId:D()};e.logger?.error(`MCP request failed: ${t(a)}`,{request_id:l.requestId}),await c(a,s(n.url,o()),{logger:e.logger,caller:l})}return q()}}}export{J as createMcpRequestHandler,R as toRegisterToolConfig};
1
+ import{isObject as e}from"../../../../../shared/utils/is-object.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r}from"../constants.js";import{formatError as i}from"./tool-errors.js";import{auditToolCall as a,callAttribution as o}from"./audit.js";import{CODE_MODE_TOOL_NAMES as s,FETCH_TOOL_NAME as c}from"./codemode/constants.js";import{resolveMcpMode as l,resolveRequestMcpMode as u}from"./mode.js";import{sendMcpRequestError as d}from"./mcp-telemetry.js";import{availableTools as f,isToolAvailable as p,normalizeToolDisplayName as m}from"./tool-registry.js";import{mcpJsonSchemaValidator as h}from"./json-schema-validator.js";import{toToolListEntries as g}from"./codemode/tool-list.js";import{buildCodeModeInstructions as _,buildExecuteDescription as v,buildToolsModeInstructions as y}from"./codemode/prompts.js";import{composeExecuteAnnotations as b,getActiveCapabilities as x}from"./codemode/capabilities.js";import{discover as S,discoverSchema as C}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as w,executeOutputSchema as T,executeToolTitle as E}from"./codemode/execute-schema.js";import{runCodeMode as D}from"./codemode/index.js";import{docsServerInfo as O}from"./server-info.js";import{loadSkillResources as k}from"./skills-resources.js";import{randomUUID as A}from"node:crypto";import{McpServer as j,createMcpHandler as M,fromJsonSchema as N,isCallToolResult as P,isInputRequiredResult as F}from"@modelcontextprotocol/server";const I=`text/markdown`,L={listChanged:!1};function R(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a}=m(e);return{title:t,description:n,inputSchema:N(r,h),outputSchema:i?N(i,h):void 0,annotations:a}}function z(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function B(t,n){if(P(t)||F(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 V(e,t){return(n,r)=>a(e,t.schema.name,n,async()=>B(await t.execute(n,e,r),e.mcpMode))}function H(e,t){return new j(e,{capabilities:{logging:{},tools:L},maxToolInputElements:1e4,instructions:t})}async function U(e,i,o){let[l,u]=await Promise.all([f(o,i),x(i)]),d=u.some(e=>e.id===c),m=l.filter(e=>!s.has(e.schema.name)).map(e=>e.schema),h=l.filter(({schema:e})=>s.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),y=i.instructionsStyle!==`brief`,O=y?g(m,u):[],k=h.some(e=>e.schema.name===t),A=H(e,_(d,O,e.websiteUrl)),j=b(m,u,i.config.mcp);A.registerTool(r,R({...z(k,w),title:E(j),description:v(d,O,e.websiteUrl),outputSchema:T(d),annotations:j}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,s=t=>a(i,r,e,()=>D({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:o,ctx:i,hostFetch:t}));if(!d)return s();let{runExecuteWithGateway:c}=await import(`./gateway/index.js`);return c({ctx:i,sessionHandle:n,serverContext:t,run:s})});let M=S(m,async e=>{let t=o.get(e);return t!==void 0&&await p(t,i)},u,i);A.registerTool(n,R(C(m,u,y)),e=>a(i,n,e,()=>M(e)));for(let e of h)A.registerTool(e.schema.name,R(z(k,e.schema)),V(i,e));return A}async function W(e,t,n){let r=new Map((await f(n,t)).map(e=>[e.schema.name,e])),i=H(e,y(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,R({...n.schema,outputSchema:void 0}),V(t,n));r.has(n.schema.name)||a.disable()}return i}async function G(e,t,n){let r=O(e.config,e.request),i=e.mcpMode===`code`?await U(r,e,t):await W(r,e,t);n.length>0&&i.server.registerCapabilities({resources:L});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:I},async()=>({contents:[{uri:e.uri,mimeType:I,text:await e.read()}]}));return i}function K(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 q(){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 J(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await k(n),i=await G(n,e.registry,r),a=M(()=>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(),K(o)}catch(r){if(e.onError)await e.onError(r);else{let a=n?o(n):{requestId:A()};e.logger?.error(`MCP request failed: ${i(r)}`,{request_id:a.requestId}),await d(r,u(t.url,l()),{logger:e.logger,caller:a})}return q()}}}export{J as createMcpRequestHandler,R 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{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{parseUserAgent as p,readListingSource as m}from"./mcp-client.js";import{randomUUID as h}from"node:crypto";import{EXECUTE_TOOL_NAME as g,SANDBOX_FAILURE as _}from"@redocly/mcp";import{ulid as v}from"ulid";const y={id:`docs`,object:`mcpServer`,uri:`urn:redocly:realm:mcp:server:docs`};function b(e){if(e===void 0)return;let t=c(e);return{id:t,object:`user`,uri:`urn:redocly:realm:mcp:subject:${t}`}}function x(n){let{mode:c,requestId:h,callerSubject:v,clientIp:x,logger:S}=n,C=n.env??process.env,w=t(C),T=b(v),{client:E,clientVersion:D}=p(n.userAgent),O=n.metadata.messageId,k={client:E,client_version:D,message_id:typeof O==`string`?O:void 0,listing_source:m(n.request)},M=[],N=/* @__PURE__ */ new Set,P=/* @__PURE__ */ new WeakSet,F=(e,t)=>{M.push({type:e,data:[t],requestId:h,time:/* @__PURE__ */ new Date,actor:T,clientIp:x})},I=t=>{try{t()}catch(t){S?.warn(`MCP telemetry failed: ${e(t)}`)}},L=(e,t,n)=>F(`com.redocly.mcpServer.toolCalled`,{...y,tool:e,mode:c,output_length:n,duration_ms:t,...k}),R=(e,t,n)=>{n.stack&&S?.error(`MCP tool ${e} failed (${n.error_class})`,{request_id:h,stack:n.stack}),F(`com.redocly.mcpServer.error`,{...y,tool:e,mode:c,duration_ms:t,message:s(n.message),stack:l(n.stack),error_class:n.error_class,...k})},z=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`}),I(()=>R(t,Date.now()-a,{message:e(n),stack:s&&n instanceof Error?n.stack??``:``,error_class:o})),n}return I(()=>L(t,Date.now()-a,d(o).length)),o};return{toolReturned(e,t,n){I(()=>{if(!u(n)||n.isError!==!0){L(e,t,d(n).length);return}P.has(n)||R(e,t,{message:f(n,` `),stack:``,error_class:e===g?`sandbox_error`:`tool_error`})})},toolThrew(t,n,r){I(()=>{let i=a(r);R(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=z(e,t,a),r=n.then(()=>void 0,()=>void 0);return N.add(r),r.then(()=>N.delete(r)),n},finish(e,t,n){let o=e.failure===_.HostError&&e.error!==void 0?a.get(e.error):void 0;o?.tool&&P.add(t);let c=e.error===void 0?`ok`:`error`,l=Date.now()-r,u=A(e.failure,o,n),d=o?.tool;I(()=>F(`com.redocly.mcpServer.codeExecuted`,{...y,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,...k})),S?.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}){I(()=>F(`com.redocly.mcpServer.gatewayFetchPerformed`,{...y,host:e,method:t,outcome:n,path:i,api:a,status:o,injected_scheme:c,bytes:s,duration_ms:r})),S?.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}){I(()=>F(`com.redocly.mcpServer.gatewayFetchRateLimited`,{...y,scope:e,retry_after_seconds:n,limit:t}))},async flush(){if(!w){M=[];return}await j(N,300);let e=M;M=[],await r(e,{env:C,fetcher:n.fetcher,logger:S})}}}function S(e,t){let{requestId:r=h(),callerSubject:i,clientIp:a}=t.caller??{};return n({...e,requestId:r,actor:b(i),clientIp:a},t)}function C(e,t,n={}){return S({type:`com.redocly.mcpServer.error`,data:[{...y,message:s(e instanceof Error?e.message:``),stack:l(e instanceof Error?e.stack??``:``),error_class:`server_error`,mode:t}]},n)}function w({scope:e,retryAfterSeconds:t,limit:n},r={}){return S({type:`com.redocly.mcpServer.rateLimited`,data:[{...y,scope:e,retry_after_seconds:t,limit:n}]},r)}function T(e){let t=e||v(),n=t.startsWith(`mcp_`)?t:`mcp_${t}`;return{id:n,object:`mcpSession`,uri:`urn:redocly:realm:mcp:session:${n}`}}function E(e,t,n={}){return S({type:`com.redocly.mcpServerAuthorization.started`,data:[{...T(e),redirect_uri:t}]},n)}function D(e,t,n={}){return S({type:`com.redocly.mcpServerAuthorization.completed`,data:[{...T(e),redirect_uri:t}]},n)}function O(e,t,n,r,i={}){return S({type:`com.redocly.mcpServerAuthorization.failed`,data:[{...T(e),error:n,error_details:r,error_class:t}]},i)}function k(e={}){return S({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`},signal:`trace`},e)}function A(e,t,n){return e===_.HostError?t?.reason??_.RuntimeError:e===_.RuntimeError&&n!==void 0?`unknown_tool`:e}async function j(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{x as createMcpTelemetry,D as sendMcpAuthorizationCompleted,O as sendMcpAuthorizationFailed,E as sendMcpAuthorizationStarted,w as sendMcpRateLimited,C as sendMcpRequestError,k as sendMcpServerCardServed};
1
+ import"../constants.js";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{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={}){return x({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`},signal:`trace`},e)}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"../../../../../../server/constants/system-routes.js";import{MCP_CALLBACK_ROUTE as n}from"../../constants.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);await l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${n}/${O}`});return f.redirect(`${e(t.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
1
+ import{SystemRoute as e}from"../../../../../../server/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{MCP_CALLBACK_ROUTE as n}from"../../constants.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);await l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${n}/${O}`});return f.redirect(`${t(e.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
@@ -1 +1 @@
1
- import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r={ratePerMin:600,quotaPerDay:2e4},i={ratePerMin:60,quotaPerDay:2e3},a={ratePerMin:60,quotaPerDay:2e3};function o(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function s(e){return e===`oauth`?i:e===`card`?a:{ratePerMin:o(process.env.MCP_RATE_LIMIT_PER_MINUTE,r.ratePerMin),quotaPerDay:o(process.env.MCP_RATE_LIMIT_PER_DAY,r.quotaPerDay)}}const c={rate:`minute`,quota:`day`};function l(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}function u(e,t,n,r){return[...e===`mcp`?[`mcp`,`request-rl`]:[`mcp`,`request-rl`,e],t,String(n),String(r)]}async function d(e){let{kv:t,bucket:n,ip:r,windowSeconds:i,limit:a,now:o}=e,s=Math.floor(o/1e3),c=Math.floor(s/i),l=u(n,r,i,c),d=(await t.get(l))?.count??0;return d>=a?{allowed:!1,retryAfterSeconds:Math.max(1,(c+1)*i-s)}:(await t.set(l,{count:d+1},{ttlInSeconds:i}),{allowed:!0})}async function f(e){let t=e.now??Date.now(),{bucket:n}=e,r=e.limits??s(n),i=l(e.ip),a=await d({kv:e.kv,bucket:n,ip:i,windowSeconds:60,limit:r.ratePerMin,now:t});if(!a.allowed)return{limited:!0,scope:`rate`,retryAfterSeconds:a.retryAfterSeconds};let o=await d({kv:e.kv,bucket:n,ip:i,windowSeconds:86400,limit:r.quotaPerDay,now:t});return o.allowed?{limited:!1}:{limited:!0,scope:`quota`,retryAfterSeconds:o.retryAfterSeconds}}function p(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function m(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=s(n),a;try{a=await f({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${c[a.scope]})`),await t({scope:a.scope,retryAfterSeconds:a.retryAfterSeconds,limit:a.scope===`rate`?i.ratePerMin:i.quotaPerDay},{logger:r,caller:{clientIp:e.ip}}),p(a,e.headers??{})}export{m as applyMcpRateLimit,f as checkMcpRateLimit,l as ipRateLimitKey};
1
+ import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r=86400,i={ratePerMin:600,quotaPerDay:2e4},a={ratePerMin:60,quotaPerDay:2e3},o={ratePerMin:60,quotaPerDay:2e3};function s(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function c(e){return e===`oauth`?a:e===`card`?o:{ratePerMin:s(process.env.MCP_RATE_LIMIT_PER_MINUTE,i.ratePerMin),quotaPerDay:s(process.env.MCP_RATE_LIMIT_PER_DAY,i.quotaPerDay)}}const l={rate:`minute`,quota:`day`};function u(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}const d=[{scope:`rate`,seconds:60},{scope:`quota`,seconds:r}];function f(e,t){return e===`mcp`?[`mcp`,`request-rl`,t]:[`mcp`,`request-rl`,e,t]}async function p(e){let{kv:t,bucket:n}=e,i=e.limits??c(n),a=Math.floor((e.now??Date.now())/1e3),o=f(n,u(e.ip)),s=await t.get(o),l={};for(let{scope:e,seconds:t}of d){let n=Math.floor(a/t),r=s?.[e],o=r?.id===n?r.count:0;if(o>=(e===`rate`?i.ratePerMin:i.quotaPerDay))return{limited:!0,scope:e,retryAfterSeconds:Math.max(1,(n+1)*t-a)};l[e]={id:n,count:o+1}}return await t.set(o,l,{ttlInSeconds:r}),{limited:!1}}function m(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function h(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=c(n),a;try{a=await p({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${l[a.scope]})`),await t({scope:a.scope,retryAfterSeconds:a.retryAfterSeconds,limit:a.scope===`rate`?i.ratePerMin:i.quotaPerDay},{logger:r,caller:{clientIp:e.ip}}),m(a,e.headers??{})}export{h as applyMcpRateLimit,p as checkMcpRateLimit,u as ipRateLimitKey};
@@ -1 +1 @@
1
- import{realmPlusVersion as e}from"../../../../../shared/realm-plus-version.js";import{PLACEHOLDER_MCP_SERVER_NAMES as t}from"../constants.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(e){let n=e.mcp?.name?.trim();return n&&!t.includes(n)?n:void 0}function o(t,o){let s=r(t.seo?.siteUrl,n(o));return{name:a(t)||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};
@@ -0,0 +1 @@
1
+ const e=[`queries`,`mutations`,`subscriptions`,`objects`,`interfaces`,`unions`,`enums`,`inputs`,`scalars`,`directives`],t=[`members`,`fields`],n=[`objects`,`interfaces`,`inputs`];export{n as FIELD_SCOPE_KINDS,t as GRAPHQL_LIST_SCOPES,e as GRAPHQL_TYPE_KINDS};
@@ -1,4 +1,4 @@
1
- import{FIELD_SCOPE_KINDS as e,GRAPHQL_TYPE_KINDS as t}from"@redocly/mcp";import{getNamedType as n,isEnumType as r,isInputObjectType as i,isInterfaceType as a,isIntrospectionType as o,isObjectType as s,isScalarType as c,isSpecifiedScalarType as l,isUnionType as u,print as d,printSchema as f,printType as p,specifiedDirectives as m}from"graphql";const h=/* @__PURE__ */ new Set([`queries`,`mutations`,`subscriptions`]);function g(n,r,i){if(r===`fields`){if(i&&!e.some(e=>e===i))throw Error(`scope "fields" lists the fields of object, interface, and input types; kind must be ${e.map(e=>`"${e}"`).join(`, `)}, or omitted.`);return A(n,i)}let a=T(n);return(i?[i]:t).flatMap(e=>a[e].map(t=>({kind:e,...t})))}function _(e,t){let n=t.toLowerCase();return e.name.toLowerCase().includes(n)||(e.description?.toLowerCase().includes(n)??!1)}function v(e,t,n){let r=F(e,n);if(!r)return[];let i=/* @__PURE__ */ new Set([r,...P(e,r)]);return t.filter(t=>{if(t.name.includes(`.`)){let n=j(e,t.name);return n?S(n).some(e=>i.has(e)):!1}if(!h.has(t.kind))return i.has(t.name);let n=x(e,t.name);return n?S(n).some(e=>i.has(e)):!1})}function y(e,t,n,r){if(r){let{sdl:r,referencedCount:i}=B(e,n);return`# Schema: ${t}\n# Type: ${n} (+ ${i} referenced types)\n\n${r}`}let i=`# Schema: ${t}\n# Type: ${n}\n\n${R(e,n)}`,a=z(e,n);return a.length===0?i:`${i}\n\n${[`# Referenced types (one level, names only; fetch a type or set includeReferencedTypes for full SDL):`,...a.map(e=>`# ${e}`)].join(`
1
+ import{FIELD_SCOPE_KINDS as e,GRAPHQL_TYPE_KINDS as t}from"./graphql-constants.js";import{getNamedType as n,isEnumType as r,isInputObjectType as i,isInterfaceType as a,isIntrospectionType as o,isObjectType as s,isScalarType as c,isSpecifiedScalarType as l,isUnionType as u,print as d,printSchema as f,printType as p,specifiedDirectives as m}from"graphql";const h=/* @__PURE__ */ new Set([`queries`,`mutations`,`subscriptions`]);function g(n,r,i){if(r===`fields`){if(i&&!e.some(e=>e===i))throw Error(`scope "fields" lists the fields of object, interface, and input types; kind must be ${e.map(e=>`"${e}"`).join(`, `)}, or omitted.`);return A(n,i)}let a=T(n);return(i?[i]:t).flatMap(e=>a[e].map(t=>({kind:e,...t})))}function _(e,t){let n=t.toLowerCase();return e.name.toLowerCase().includes(n)||(e.description?.toLowerCase().includes(n)??!1)}function v(e,t,n){let r=F(e,n);if(!r)return[];let i=/* @__PURE__ */ new Set([r,...P(e,r)]);return t.filter(t=>{if(t.name.includes(`.`)){let n=j(e,t.name);return n?S(n).some(e=>i.has(e)):!1}if(!h.has(t.kind))return i.has(t.name);let n=x(e,t.name);return n?S(n).some(e=>i.has(e)):!1})}function y(e,t,n,r){if(r){let{sdl:r,referencedCount:i}=B(e,n);return`# Schema: ${t}\n# Type: ${n} (+ ${i} referenced types)\n\n${r}`}let i=`# Schema: ${t}\n# Type: ${n}\n\n${R(e,n)}`,a=z(e,n);return a.length===0?i:`${i}\n\n${[`# Referenced types (one level, names only; fetch a type or set includeReferencedTypes for full SDL):`,...a.map(e=>`# ${e}`)].join(`
2
2
  `)}`}function b(e,t){return`# Schema: ${t}\n\n${f(e)}`}function x(e,t){return e.getQueryType()?.getFields()[t]??e.getMutationType()?.getFields()[t]??e.getSubscriptionType()?.getFields()[t]}function S(e){return[n(e.type).name,...(e.args??[]).map(e=>n(e.type).name)]}function C(e){let t=/* @__PURE__ */ new Set;if(s(e)||a(e)){for(let r of Object.values(e.getFields())){t.add(n(r.type).name);for(let e of r.args)t.add(n(e.type).name)}for(let n of e.getInterfaces())t.add(n.name)}else if(u(e))for(let n of e.getTypes())t.add(n.name);else if(i(e))for(let r of Object.values(e.getFields()))t.add(n(r.type).name);return t}function w(e){return new Set([e.getQueryType(),e.getMutationType(),e.getSubscriptionType()].filter(e=>!!e).map(e=>e.name))}function T(e){let t=w(e),n={queries:k(e.getQueryType()),mutations:k(e.getMutationType()),subscriptions:k(e.getSubscriptionType()),objects:[],interfaces:[],unions:[],enums:[],inputs:[],scalars:[],directives:[]};for(let r of Object.values(e.getTypeMap())){if(o(r)||t.has(r.name))continue;let e=E(r);e&&n[e].push({name:r.name,description:r.description??void 0})}let r=new Set(m.map(e=>e.name));return n.directives=e.getDirectives().filter(e=>!r.has(e.name)).map(e=>({name:e.name,description:e.description??void 0})),n}function E(e){if(c(e))return l(e)?void 0:`scalars`;if(s(e))return`objects`;if(a(e))return`interfaces`;if(u(e))return`unions`;if(r(e))return`enums`;if(i(e))return`inputs`}function D(e){return s(e)||a(e)||i(e)?e:void 0}function O(e){let t=e.astNode?.directives;return t?.length?t.map(e=>d(e)).join(` `):void 0}function k(e){return e?Object.values(e.getFields()).map(e=>({name:e.name,description:e.description??void 0,type:e.type.toString(),args:e.args.length?`(${e.args.map(e=>{let t=e.astNode?.defaultValue?` = ${d(e.astNode.defaultValue)}`:``;return`${e.name}: ${e.type}${t}`}).join(`, `)})`:void 0,directives:O(e)})):[]}function A(e,t){let n=w(e),r=[];for(let i of Object.values(e.getTypeMap())){if(o(i)||n.has(i.name))continue;let e=D(i);if(!e)continue;let a=E(e);if(!(!a||t&&t!==a))for(let t of Object.values(e.getFields()))r.push({kind:a,name:`${e.name}.${t.name}`,description:t.description??void 0,type:t.type.toString(),directives:O(t)})}return r}function j(e,t){let n=t.indexOf(`.`);if(n!==-1)return D(e.getType(t.slice(0,n)))?.getFields()[t.slice(n+1)]}function M(e,t){let n=/* @__PURE__ */ new Set,r=[...N(e,t)];for(let t=0;t<r.length;t+=1){let i=r[t];if(n.has(i))continue;n.add(i);let a=e.getType(i);if(a)for(let e of C(a))n.has(e)||r.push(e)}return[...n].filter(n=>n!==t&&I(e,n))}function N(e,t){let r=e.getType(t);if(r)return C(r);let i=x(e,t);if(i)return new Set(S(i));let a=e.getDirective(t);return a?new Set(a.args.map(e=>n(e.type).name)):/* @__PURE__ */ new Set}function P(e,t){let n=/* @__PURE__ */ new Map;for(let t of Object.values(e.getTypeMap()))if(!o(t))for(let e of C(t)){let r=n.get(e);r||(r=/* @__PURE__ */ new Set,n.set(e,r)),r.add(t.name)}let r=/* @__PURE__ */ new Set,i=[t];for(let e=0;e<i.length;e+=1)for(let t of n.get(i[e])??[])r.has(t)||(r.add(t),i.push(t));return r}function F(e,t){let n=t.toLowerCase();return Object.keys(e.getTypeMap()).find(e=>e.toLowerCase()===n)}function I(e,t){let n=e.getType(t);return!n||o(n)?!1:!(c(n)&&l(n))}function L(e){return e.astNode?[e.astNode,...e.extensionASTNodes??[]].map(e=>d(e)).join(`
3
3
 
4
4
  `):p(e)}function R(e,t){let n=e.getType(t);if(n)return L(n);let r=x(e,t);if(r?.astNode)return d(r.astNode);let i=e.getDirective(t);if(i?.astNode)return d(i.astNode);throw Error(`No GraphQL type, operation, or directive named "${t}" found.`)}function z(e,t){let n=[];for(let o of N(e,t)){if(o===t||!I(e,o))continue;let l=e.getType(o);s(l)?n.push(`type ${o} { ${Object.keys(l.getFields()).join(`, `)} }`):a(l)?n.push(`interface ${o} { ${Object.keys(l.getFields()).join(`, `)} }`):i(l)?n.push(`input ${o} { ${Object.keys(l.getFields()).join(`, `)} }`):r(l)?n.push(`enum ${o} { ${l.getValues().map(e=>e.name).join(`, `)} }`):u(l)?n.push(`union ${o} = ${l.getTypes().map(e=>e.name).join(` | `)}`):c(l)&&n.push(`scalar ${o}`)}return n}function B(e,t){let n=R(e,t),r=M(e,t).map(t=>e.getType(t)).filter(e=>!!e).map(e=>L(e));return{sdl:[n,...r].join(`
@@ -1 +1 @@
1
- import{hasGraphqlSchemas as e,listGraphqlSchemas as t,loadGraphqlSchema as n}from"./graphql-catalog.js";import{GET_GRAPHQL_SCHEMA_SCHEMA as r,GET_GRAPHQL_TYPE_LIST_SCHEMA as i,GET_GRAPHQL_TYPE_SCHEMA as a,LIST_GRAPHQL_APIS_SCHEMA as o,getGraphqlSchemaToolSchema as s,getGraphqlTypeToolSchema as c}from"@redocly/mcp";function l(e,t,n){let r=(t-1)*n;return{items:e.slice(r,r+n),limit:n,total:e.length,page:t,totalPages:Math.ceil(e.length/n)}}const u=[{schema:o,isAvailable:e,async execute(e,n){let{filter:r,page:i,limit:a}=e??{},o=await t(n),{items:s,...c}=l(r?o.filter(({name:e})=>e.toLowerCase().includes(r.toLowerCase())):o,i??1,a??300);return{items:s.map(({name:e,description:t})=>({name:e,description:t})),...c}}},{schema:i,isAvailable:e,async execute(e,t){let r=e??{},{kind:i,scope:a=`members`,filter:o,referencesType:s,page:c,limit:u}=r,{name:d,schema:f}=await n(r.name,t),{filterMembersReferencingType:p,listMembers:m,matchesFilter:h}=await import(`./graphql-document.js`),g=m(f,a,i);return s&&(g=p(f,g,s)),o&&(g=g.filter(e=>h(e,o))),{name:d,...l(g,c??1,u??300)}}},{schema:a,schemaFor:e=>c(e.mcpMode),isAvailable:e,inputAliases:{typeName:`type`},async execute(e,t){let r=e??{},{name:i,schema:a}=await n(r.name,t),{type:o}=r;if(!o)throw Error("Pass `type`: the name of the type, operation, or directive.");let{describeType:s}=await import(`./graphql-document.js`);return s(a,i,o,r.includeReferencedTypes===!0)}},{schema:r,schemaFor:e=>s(e.mcpMode),isAvailable:e,async execute(e,t){let{name:r,schema:i}=await n((e??{}).name,t),{describeSchema:a}=await import(`./graphql-document.js`);return a(i,r)}}];export{u as graphqlTools};
1
+ import{hasGraphqlSchemas as e,listGraphqlSchemas as t,loadGraphqlSchema as n}from"./graphql-catalog.js";import{GET_GRAPHQL_SCHEMA_SCHEMA as r,GET_GRAPHQL_TYPE_LIST_SCHEMA as i,GET_GRAPHQL_TYPE_SCHEMA as a,LIST_GRAPHQL_APIS_SCHEMA as o,getGraphqlSchemaToolSchema as s,getGraphqlTypeToolSchema as c}from"./schemas.js";function l(e,t,n){let r=(t-1)*n;return{items:e.slice(r,r+n),limit:n,total:e.length,page:t,totalPages:Math.ceil(e.length/n)}}const u=[{schema:o,isAvailable:e,async execute(e,n){let{filter:r,page:i,limit:a}=e??{},o=await t(n),{items:s,...c}=l(r?o.filter(({name:e})=>e.toLowerCase().includes(r.toLowerCase())):o,i??1,a??300);return{items:s.map(({name:e,description:t})=>({name:e,description:t})),...c}}},{schema:i,isAvailable:e,async execute(e,t){let r=e??{},{kind:i,scope:a=`members`,filter:o,referencesType:s,page:c,limit:u}=r,{name:d,schema:f}=await n(r.name,t),{filterMembersReferencingType:p,listMembers:m,matchesFilter:h}=await import(`./graphql-document.js`),g=m(f,a,i);return s&&(g=p(f,g,s)),o&&(g=g.filter(e=>h(e,o))),{name:d,...l(g,c??1,u??300)}}},{schema:a,schemaFor:e=>c(e.mcpMode),isAvailable:e,inputAliases:{typeName:`type`},async execute(e,t){let r=e??{},{name:i,schema:a}=await n(r.name,t),{type:o}=r;if(!o)throw Error("Pass `type`: the name of the type, operation, or directive.");let{describeType:s}=await import(`./graphql-document.js`);return s(a,i,o,r.includeReferencedTypes===!0)}},{schema:r,schemaFor:e=>s(e.mcpMode),isAvailable:e,async execute(e,t){let{name:r,schema:i}=await n((e??{}).name,t),{describeSchema:a}=await import(`./graphql-document.js`);return a(i,r)}}];export{u as graphqlTools};
@@ -1 +1 @@
1
- import{compileContentGlob as e}from"../../../../utils/glob.js";import{SPEC_KIND_OPENAPI as t}from"../../../../types/api-entity.js";import{filterApiDocsByRbac as n}from"../../../../../../server/rbac/api-docs.js";import{canonicalSlugPath as r}from"../../ignored-routes.js";import{formatError as i}from"../tool-errors.js";import{apiTitleKey as a,compareApiDescriptions as o}from"./api-titles.js";import{absolutePath as s,findDocumentedPath as c,formatCandidates as l,isDefinitionHidden as u,recoveryToolNames as d,visibleMethodsAt as f}from"./openapi-document.js";import{OPERATION_METHODS as p}from"@redocly/mcp";const m=/* @__PURE__ */ new WeakMap;function h(e,r){let a=m.get(e);a||(a=/* @__PURE__ */ new Map,m.set(e,a));let o=a.get(r);if(o)return o;let s=t=>e.logger?.warn(t),c=e.entities.load(r).then(r=>({full:r,visible:n(r,t,e.request.teams,{warn:s})})).catch(e=>(s(`MCP: skipping api entity "${r}": ${i(e)}`),null));return a.set(r,c),c}const g=new Set(p);function _(e){return Object.values(e.paths??{}).some(e=>typeof e==`object`&&!!e&&Object.keys(e).some(e=>g.has(e.toLowerCase())))}function v(e,t,n){let{title:r=``,version:i=``,description:a}=t.info??{};return{entityKey:e.entityKey,definition:t,fullDefinition:n,relativePath:e.relativePath,name:r,description:typeof a==`string`?a:``,version:String(i),servers:t.servers??[]}}async function y(t){let n=t.config.mcp?.ignore??[],i=n.length>0?e(n):()=>!1;return(await t.entities.list({type:`api`})).flatMap(({key:e,metadata:t})=>{let{specType:n,sourcePath:a,routeSlug:o}=t??{};return n!==`openapi`||typeof a!=`string`||i(a)||typeof o==`string`&&i(r(o,a))?[]:[{entityKey:e,relativePath:a}]})}async function b(e,t){let n=await h(e,t.entityKey);return!n?.visible||!_(n.visible)||u(n.visible.info)?null:v(t,n.visible,n.full)}async function x(e){let t=await y(e);return(await Promise.all(t.map(t=>b(e,t)))).filter(e=>e!==null)}const S=/* @__PURE__ */ new Set([`api`,`apis`,`rest`,`restful`,`openapi`,`graphql`,`spec`,`specification`,`service`,`services`]);function C(e){return e.toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean)}function w(e){return new Set(C(e).filter(e=>!S.has(e)))}function T(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function E(e,t,n){let r=w(t);return e.map(e=>{let t=e[n];return{api:e,text:t,score:[...w(t)].filter(e=>r.has(e)).length}}).sort((e,t)=>t.score-e.score||e.text.localeCompare(t.text)).map(({api:e})=>e)}function D(e,t){return l(E(e,t,`name`).map(e=>`"${e.name}" (${e.relativePath})`))}function O(e,t){return l(E(e,t,`relativePath`).map(e=>`"${e.relativePath}"`))}function k(e,t){let n=a(t);if(!n)return{matches:[],isExactTitle:!1};let r=e.map(e=>({api:e,title:a(e.name)})),i=e=>e.map(({api:e})=>e),o=r.filter(({title:e})=>e===n);if(o.length>0)return{matches:i(o),isExactTitle:!0};let s=r.filter(({title:e})=>e.includes(n));if(s.length>0)return{matches:i(s),isExactTitle:!1};let c=w(n);return c.size===0?{matches:[],isExactTitle:!1}:{matches:i(r.filter(({title:e})=>{let t=w(e);return t.size>0&&T(t,c)})),isExactTitle:!1}}function A(e,t,n){let{matches:r,isExactTitle:i}=k(e,t);if(r.length===0)return;if(!i){let e=[...new Set(r.map(({name:e})=>e))];if(e.length>1)throw Error(`"${t}" matches ${e.length} APIs: ${l(e.map(e=>`"${e}"`))}. Pass one of those names exactly, or the "filePath" parameter from list-apis.`)}let a=n?r.filter(e=>e.version===n):r;if(a.length===0){let e=[...new Set(r.map(({version:e})=>e||`(no version)`))];throw Error(`"${r[0].name||t}" has no version "${n}". Available versions: ${l(e)}.`)}let[s,...c]=[...a].sort(o);return{api:s,otherMatches:c.length>0?c:void 0}}function j(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e.filter(({name:e})=>e.toLowerCase().includes(n));return r.length>0?r:e.filter(({description:e})=>e.toLowerCase().includes(n))}function M({version:e,relativePath:t}){return{version:e||void 0,filePath:t}}function N(e,t=[]){return{api:e,otherMatches:t.length>0?t.map(M):void 0}}function P(e){return`Pass \`name\` (the API title, or a unique part of it) or \`filePath\` from ${d(e).listApis}.`}async function F(e,t){let{name:n,version:r,filePath:i}=e;if(!i&&!n)return I(e,t);let a=await y(t),o=i??n,s=a.find(e=>e.relativePath===o),c=s&&await b(t,s);if(c)return N(c);let l=await x(t);if(i){let e=O(l,i);throw Error(`No API found with filePath "${i}". `+(e?`Available file paths: ${e}. `:``)+`File paths come from ${d(t.mcpMode).listApis}.`)}let u=A(l,n??``,r);if(u)return N(u.api,u.otherMatches);let f=D(l,n??``);throw Error(f?`No API found matching "${n}". Available APIs: ${f}. Pass one of those names, or its \`filePath\`.`:`No API found matching "${n}".`)}async function I({path:e,method:t,version:n},r){let i=await x(r);if(i.length===0)throw Error(`This project documents no OpenAPI description.`);if(i.length===1){let[e]=i;if(n&&e.version!==n)throw Error(`"${e.name}" has no version "${n}". Available versions: ${e.version||`(no version)`}.`);return N(e)}if(!e||!t||i.length>10)throw Error(`${P(r.mcpMode)} Available APIs: ${D(i,``)}.`);let a=[],u=/* @__PURE__ */ new Set,d=[],p=t.toUpperCase();for(let t of i){let n=c(t.definition,e);if(!n)continue;let r=f(t.definition,n.path);r.includes(p)?(a.push(t),n.isTemplateMatch&&u.add(t)):r.length>0&&d.push({api:t,methods:r})}if(a.sort(o),a.length===0)throw R(i,d,e,t,r.mcpMode);let m=n?a.filter(e=>e.version===n):a;if(m.length===0){let t=[...new Set(a.map(({version:e})=>e||`(no version)`))];throw Error(`No API documenting "${s(e)}" has version "${n}". Available versions: ${l(t)}.`)}let h=m.filter(e=>!u.has(e));return L(h.length>0?h:m,e,t,r.mcpMode)}function L(e,t,n,r){let i=new Set(e.map(({name:e})=>a(e)));if(i.size>1){let o=[...i].map(t=>{let[n]=e.filter(e=>a(e.name)===t);return`"${n.name}" (${n.relativePath})`});throw Error(`${n.toUpperCase()} ${s(t)} is documented by ${i.size} APIs: ${l(o)}. Pass \`name\` or \`filePath\` from ${d(r).listApis} to pick one.`)}let[o,...c]=e;return N(o,c)}function R(e,t,n,r,i){if(t.length>0){let e=t.map(({api:e,methods:t})=>`"${e.name}" (${e.relativePath}) documents ${l(t)}.`).join(` `);return/* @__PURE__ */ Error(`No API documents ${r.toUpperCase()} ${s(n)}. ${e}`)}let{endpoints:a,search:o}=d(i);return/* @__PURE__ */ Error(`No API in this project documents ${s(n)}. Available APIs: ${D(e,``)}. Call ${a} with one of them, or ${o} with a keyword from the request.`)}export{D as describeAvailableApis,j as filterApisByName,A as findApiByNameAndVersion,x as loadApiCatalog,F as resolveApi};
1
+ import{compileContentGlob as e}from"../../../../utils/glob.js";import{SPEC_KIND_OPENAPI as t}from"../../../../types/api-entity.js";import{filterApiDocsByRbac as n}from"../../../../../../server/rbac/api-docs.js";import{canonicalSlugPath as r}from"../../ignored-routes.js";import{formatError as i}from"../tool-errors.js";import{OPERATION_METHODS as a,absolutePath as o,findDocumentedPath as s,formatCandidates as c,isDefinitionHidden as l,recoveryToolNames as u,visibleMethodsAt as d}from"./openapi-document.js";import{apiTitleKey as f,compareApiDescriptions as p}from"./api-titles.js";const m=/* @__PURE__ */ new WeakMap;function h(e,r){let a=m.get(e);a||(a=/* @__PURE__ */ new Map,m.set(e,a));let o=a.get(r);if(o)return o;let s=t=>e.logger?.warn(t),c=e.entities.load(r).then(r=>({full:r,visible:n(r,t,e.request.teams,{warn:s})})).catch(e=>(s(`MCP: skipping api entity "${r}": ${i(e)}`),null));return a.set(r,c),c}const g=new Set(a);function _(e){return Object.values(e.paths??{}).some(e=>typeof e==`object`&&!!e&&Object.keys(e).some(e=>g.has(e.toLowerCase())))}function v(e,t,n){let{title:r=``,version:i=``,description:a}=t.info??{};return{entityKey:e.entityKey,definition:t,fullDefinition:n,relativePath:e.relativePath,name:r,description:typeof a==`string`?a:``,version:String(i),servers:t.servers??[]}}async function y(t){let n=t.config.mcp?.ignore??[],i=n.length>0?e(n):()=>!1;return(await t.entities.list({type:`api`})).flatMap(({key:e,metadata:t})=>{let{specType:n,sourcePath:a,routeSlug:o}=t??{};return n!==`openapi`||typeof a!=`string`||i(a)||typeof o==`string`&&i(r(o,a))?[]:[{entityKey:e,relativePath:a}]})}async function b(e,t){let n=await h(e,t.entityKey);return!n?.visible||!_(n.visible)||l(n.visible.info)?null:v(t,n.visible,n.full)}async function x(e){let t=await y(e);return(await Promise.all(t.map(t=>b(e,t)))).filter(e=>e!==null)}const S=/* @__PURE__ */ new Set([`api`,`apis`,`rest`,`restful`,`openapi`,`graphql`,`spec`,`specification`,`service`,`services`]);function C(e){return e.toLowerCase().split(/[^a-z0-9_]+/).filter(Boolean)}function w(e){return new Set(C(e).filter(e=>!S.has(e)))}function T(e,t){return e.size===t.size&&[...e].every(e=>t.has(e))}function E(e,t,n){let r=w(t);return e.map(e=>{let t=e[n];return{api:e,text:t,score:[...w(t)].filter(e=>r.has(e)).length}}).sort((e,t)=>t.score-e.score||e.text.localeCompare(t.text)).map(({api:e})=>e)}function D(e,t){return c(E(e,t,`name`).map(e=>`"${e.name}" (${e.relativePath})`))}function O(e,t){return c(E(e,t,`relativePath`).map(e=>`"${e.relativePath}"`))}function k(e,t){let n=f(t);if(!n)return{matches:[],isExactTitle:!1};let r=e.map(e=>({api:e,title:f(e.name)})),i=e=>e.map(({api:e})=>e),a=r.filter(({title:e})=>e===n);if(a.length>0)return{matches:i(a),isExactTitle:!0};let o=r.filter(({title:e})=>e.includes(n));if(o.length>0)return{matches:i(o),isExactTitle:!1};let s=w(n);return s.size===0?{matches:[],isExactTitle:!1}:{matches:i(r.filter(({title:e})=>{let t=w(e);return t.size>0&&T(t,s)})),isExactTitle:!1}}function A(e,t,n){let{matches:r,isExactTitle:i}=k(e,t);if(r.length===0)return;if(!i){let e=[...new Set(r.map(({name:e})=>e))];if(e.length>1)throw Error(`"${t}" matches ${e.length} APIs: ${c(e.map(e=>`"${e}"`))}. Pass one of those names exactly, or the "filePath" parameter from list-apis.`)}let a=n?r.filter(e=>e.version===n):r;if(a.length===0){let e=[...new Set(r.map(({version:e})=>e||`(no version)`))];throw Error(`"${r[0].name||t}" has no version "${n}". Available versions: ${c(e)}.`)}let[o,...s]=[...a].sort(p);return{api:o,otherMatches:s.length>0?s:void 0}}function j(e,t){let n=t.trim().toLowerCase();if(!n)return e;let r=e.filter(({name:e})=>e.toLowerCase().includes(n));return r.length>0?r:e.filter(({description:e})=>e.toLowerCase().includes(n))}function M({version:e,relativePath:t}){return{version:e||void 0,filePath:t}}function N(e,t=[]){return{api:e,otherMatches:t.length>0?t.map(M):void 0}}function P(e){return`Pass \`name\` (the API title, or a unique part of it) or \`filePath\` from ${u(e).listApis}.`}async function F(e,t){let{name:n,version:r,filePath:i}=e;if(!i&&!n)return I(e,t);let a=await y(t),o=i??n,s=a.find(e=>e.relativePath===o),c=s&&await b(t,s);if(c)return N(c);let l=await x(t);if(i){let e=O(l,i);throw Error(`No API found with filePath "${i}". `+(e?`Available file paths: ${e}. `:``)+`File paths come from ${u(t.mcpMode).listApis}.`)}let d=A(l,n??``,r);if(d)return N(d.api,d.otherMatches);let f=D(l,n??``);throw Error(f?`No API found matching "${n}". Available APIs: ${f}. Pass one of those names, or its \`filePath\`.`:`No API found matching "${n}".`)}async function I({path:e,method:t,version:n},r){let i=await x(r);if(i.length===0)throw Error(`This project documents no OpenAPI description.`);if(i.length===1){let[e]=i;if(n&&e.version!==n)throw Error(`"${e.name}" has no version "${n}". Available versions: ${e.version||`(no version)`}.`);return N(e)}if(!e||!t||i.length>10)throw Error(`${P(r.mcpMode)} Available APIs: ${D(i,``)}.`);let a=[],l=/* @__PURE__ */ new Set,u=[],f=t.toUpperCase();for(let t of i){let n=s(t.definition,e);if(!n)continue;let r=d(t.definition,n.path);r.includes(f)?(a.push(t),n.isTemplateMatch&&l.add(t)):r.length>0&&u.push({api:t,methods:r})}if(a.sort(p),a.length===0)throw R(i,u,e,t,r.mcpMode);let m=n?a.filter(e=>e.version===n):a;if(m.length===0){let t=[...new Set(a.map(({version:e})=>e||`(no version)`))];throw Error(`No API documenting "${o(e)}" has version "${n}". Available versions: ${c(t)}.`)}let h=m.filter(e=>!l.has(e));return L(h.length>0?h:m,e,t,r.mcpMode)}function L(e,t,n,r){let i=new Set(e.map(({name:e})=>f(e)));if(i.size>1){let a=[...i].map(t=>{let[n]=e.filter(e=>f(e.name)===t);return`"${n.name}" (${n.relativePath})`});throw Error(`${n.toUpperCase()} ${o(t)} is documented by ${i.size} APIs: ${c(a)}. Pass \`name\` or \`filePath\` from ${u(r).listApis} to pick one.`)}let[a,...s]=e;return N(a,s)}function R(e,t,n,r,i){if(t.length>0){let e=t.map(({api:e,methods:t})=>`"${e.name}" (${e.relativePath}) documents ${c(t)}.`).join(` `);return/* @__PURE__ */ Error(`No API documents ${r.toUpperCase()} ${o(n)}. ${e}`)}let{endpoints:a,search:s}=u(i);return/* @__PURE__ */ Error(`No API in this project documents ${o(n)}. Available APIs: ${D(e,``)}. Call ${a} with one of them, or ${s} with a keyword from the request.`)}export{D as describeAvailableApis,j as filterApisByName,A as findApiByNameAndVersion,x as loadApiCatalog,F as resolveApi};
@@ -1 +1 @@
1
- import{OPERATION_METHODS as e,toolNameForMode as t}from"@redocly/mcp";import{replaceServerVariables as n}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";const r=new Set(e);function i(e,t=`docs`){return!!e?.[`x-mcp`]?.[t]?.hide}function a(e,t=`docs`){return!!e?.[`x-mcp`]?.[t]?.hide}function o(e){if(!(`x-mcp`in e))return e;let{"x-mcp":t,...n}=e;return n}function s(e){return!e||i(e)?[]:Object.entries(e).filter(e=>{let[t,n]=e;return r.has(t.toLowerCase())&&typeof n==`object`&&!!n&&!i(n)})}function c(e){let t=[];for(let[n,r]of Object.entries(e.paths??{}))for(let[e,i]of s(r))t.push({path:n,method:e.toUpperCase(),summary:i.summary,description:i.description,security:i.security});return t}function l(e,t){return s(e.paths?.[t]).map(([e])=>e.toUpperCase()).sort()}function u(e){return Object.keys(e.paths??{}).filter(t=>l(e,t).length>0).sort()}function d(e){let t={};for(let[n,a]of Object.entries(e.paths??{})){if(typeof a!=`object`||!a||i(a))continue;let e=0,s=Object.entries(o(a)).flatMap(([t,n])=>r.has(t.toLowerCase())?i(n)?[]:(e+=1,[[t,typeof n==`object`&&n?o(n):n]]):[[t,n]]);e!==0&&(t[n]=Object.fromEntries(s))}return{...e,info:o(e.info),paths:t}}function f(e){return e.startsWith(`/`)?e:`/${e}`}function p(e){let[t]=e.replace(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*/i,``).split(/[?#]/,1);return f(t)}function m(e){let t=e.length;for(;t>1&&e[t-1]===`/`;)--t;return e.slice(0,t)}function h(e,t){let r=p(t),i=m(r),a=i.toLowerCase(),o=/* @__PURE__ */ new Set([r,i]);for(let t of e.servers??[]){let e=m(p(n(t)));e!==`/`&&a.startsWith(`${e.toLowerCase()}/`)&&o.add(i.slice(e.length))}return[...o]}function g(e){return e.split(`/`).slice(1)}const _=/^\{[^}]+\}$/;function v(e){return e.startsWith(`:`)?e.length>1:_.test(e)}function y(e){let t=[],n=0;for(let r=e.indexOf(`{`);r!==-1;r=e.indexOf(`{`,n)){let i=e.indexOf(`}`,r);if(i===-1)break;t.push(e.slice(n,r)),n=i+1}return t.push(e.slice(n)),t}function b(e,t){let n=y(e);if(n.length===1)return t===n[0];let r=n[0],i=n[n.length-1];if(!t.startsWith(r))return!1;let a=r.length;for(let e of n.slice(1,-1)){let n=t.indexOf(e,a+1);if(n===-1)return!1;a=n+e.length}return t.length-i.length>a&&t.endsWith(i)}function x(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return v(r)?_.test(e):b(e,r)})}function S(e){return e.map(e=>g(e.toLowerCase()))}function C(e,t){let n=g(e.toLowerCase());return t.some(e=>x(n,e))}function w(e,t){let n=f(t);if(e.paths?.[n])return{path:n,isTemplateMatch:!1};let r=h(e,t),i=u(e),a=r.find(e=>i.includes(e));if(a)return{path:a,isTemplateMatch:!1};for(let e of r.map(e=>e.toLowerCase())){let t=i.find(t=>t.toLowerCase()===e);if(t)return{path:t,isTemplateMatch:!1}}for(let e of S(r)){let t=i.filter(t=>C(t,[e]));if(t.length===1)return{path:t[0],isTemplateMatch:!0};if(t.length>1)return}}function T(e,t){return w(e,t)?.path??p(t)}function E(e,t){let n=S(h(e,t)),r=new Set(n.flat());return u(e).map(e=>({path:e,isMatch:C(e,n),sharedSegments:g(e.toLowerCase()).filter(e=>r.has(e)).length})).sort((e,t)=>Number(t.isMatch)-Number(e.isMatch)||t.sharedSegments-e.sharedSegments).map(({path:e})=>e)}const D=15;function O(e){let t=e.slice(0,15),n=e.length-t.length;return n>0?`${t.join(`, `)} (+${n} more)`:t.join(`, `)}function k(e){let n=n=>e===`code`?`site.${t(n,e)}`:n;return{endpoints:n(`get-endpoints`),search:n(`search`),listApis:n(`list-apis`),listPages:n(`list-pages`)}}function A(e,t,n,r){let i=E(e,n);if(i.length===0)return`Endpoint not found`;let{endpoints:a,search:o}=k(r);return`No path "${n}" in "${t}". Documented paths: ${O(i)}. Call ${a} for the full list, or ${o} with a keyword from the request.`}function j(e,t,n,r){let i=l(e,n);return i.length===0?`Endpoint not found`:`"${n}" in "${t}" documents no ${r.toUpperCase()}. Available methods: ${O(i)}.`}export{D as MAX_LISTED_CANDIDATES,f as absolutePath,j as describeMethodMiss,A as describePathMiss,w as findDocumentedPath,O as formatCandidates,a as isDefinitionHidden,i as isEndpointHidden,T as matchDocumentedPath,k as recoveryToolNames,c as visibleEndpoints,l as visibleMethodsAt,s as visibleOperations,u as visiblePaths,d as withVisibleOperationsOnly,o as withoutXMcp};
1
+ import{toolNameForMode as e}from"../codemode/tool-declarations.js";import{replaceServerVariables as t}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";const n=[`get`,`put`,`post`,`delete`,`options`,`head`,`patch`,`trace`,`query`,`x-query`],r=new Set(n);function i(e,t=`docs`){return!!e?.[`x-mcp`]?.[t]?.hide}function a(e,t=`docs`){return!!e?.[`x-mcp`]?.[t]?.hide}function o(e){if(!(`x-mcp`in e))return e;let{"x-mcp":t,...n}=e;return n}function s(e){return!e||i(e)?[]:Object.entries(e).filter(e=>{let[t,n]=e;return r.has(t.toLowerCase())&&typeof n==`object`&&!!n&&!i(n)})}function c(e){let t=[];for(let[n,r]of Object.entries(e.paths??{}))for(let[e,i]of s(r))t.push({path:n,method:e.toUpperCase(),summary:i.summary,description:i.description,security:i.security});return t}function l(e,t){return s(e.paths?.[t]).map(([e])=>e.toUpperCase()).sort()}function u(e){return Object.keys(e.paths??{}).filter(t=>l(e,t).length>0).sort()}function d(e){let t={};for(let[n,a]of Object.entries(e.paths??{})){if(typeof a!=`object`||!a||i(a))continue;let e=0,s=Object.entries(o(a)).flatMap(([t,n])=>r.has(t.toLowerCase())?i(n)?[]:(e+=1,[[t,typeof n==`object`&&n?o(n):n]]):[[t,n]]);e!==0&&(t[n]=Object.fromEntries(s))}return{...e,info:o(e.info),paths:t}}function f(e){return e.startsWith(`/`)?e:`/${e}`}function p(e){let[t]=e.replace(/^[a-z][a-z\d+.-]*:\/\/[^/?#]*/i,``).split(/[?#]/,1);return f(t)}function m(e){let t=e.length;for(;t>1&&e[t-1]===`/`;)--t;return e.slice(0,t)}function h(e,n){let r=p(n),i=m(r),a=i.toLowerCase(),o=/* @__PURE__ */ new Set([r,i]);for(let n of e.servers??[]){let e=m(p(t(n)));e!==`/`&&a.startsWith(`${e.toLowerCase()}/`)&&o.add(i.slice(e.length))}return[...o]}function g(e){return e.split(`/`).slice(1)}const _=/^\{[^}]+\}$/;function v(e){return e.startsWith(`:`)?e.length>1:_.test(e)}function y(e){let t=[],n=0;for(let r=e.indexOf(`{`);r!==-1;r=e.indexOf(`{`,n)){let i=e.indexOf(`}`,r);if(i===-1)break;t.push(e.slice(n,r)),n=i+1}return t.push(e.slice(n)),t}function b(e,t){let n=y(e);if(n.length===1)return t===n[0];let r=n[0],i=n[n.length-1];if(!t.startsWith(r))return!1;let a=r.length;for(let e of n.slice(1,-1)){let n=t.indexOf(e,a+1);if(n===-1)return!1;a=n+e.length}return t.length-i.length>a&&t.endsWith(i)}function x(e,t){return e.length===t.length&&e.every((e,n)=>{let r=t[n];return v(r)?_.test(e):b(e,r)})}function S(e){return e.map(e=>g(e.toLowerCase()))}function C(e,t){let n=g(e.toLowerCase());return t.some(e=>x(n,e))}function w(e,t){let n=f(t);if(e.paths?.[n])return{path:n,isTemplateMatch:!1};let r=h(e,t),i=u(e),a=r.find(e=>i.includes(e));if(a)return{path:a,isTemplateMatch:!1};for(let e of r.map(e=>e.toLowerCase())){let t=i.find(t=>t.toLowerCase()===e);if(t)return{path:t,isTemplateMatch:!1}}for(let e of S(r)){let t=i.filter(t=>C(t,[e]));if(t.length===1)return{path:t[0],isTemplateMatch:!0};if(t.length>1)return}}function T(e,t){return w(e,t)?.path??p(t)}function E(e,t){let n=S(h(e,t)),r=new Set(n.flat());return u(e).map(e=>({path:e,isMatch:C(e,n),sharedSegments:g(e.toLowerCase()).filter(e=>r.has(e)).length})).sort((e,t)=>Number(t.isMatch)-Number(e.isMatch)||t.sharedSegments-e.sharedSegments).map(({path:e})=>e)}const D=15;function O(e){let t=e.slice(0,15),n=e.length-t.length;return n>0?`${t.join(`, `)} (+${n} more)`:t.join(`, `)}function k(t){let n=n=>t===`code`?`site.${e(n,t)}`:n;return{endpoints:n(`get-endpoints`),search:n(`search`),listApis:n(`list-apis`),listPages:n(`list-pages`)}}function A(e,t,n,r){let i=E(e,n);if(i.length===0)return`Endpoint not found`;let{endpoints:a,search:o}=k(r);return`No path "${n}" in "${t}". Documented paths: ${O(i)}. Call ${a} for the full list, or ${o} with a keyword from the request.`}function j(e,t,n,r){let i=l(e,n);return i.length===0?`Endpoint not found`:`"${n}" in "${t}" documents no ${r.toUpperCase()}. Available methods: ${O(i)}.`}export{D as MAX_LISTED_CANDIDATES,n as OPERATION_METHODS,f as absolutePath,j as describeMethodMiss,A as describePathMiss,w as findDocumentedPath,O as formatCandidates,a as isDefinitionHidden,i as isEndpointHidden,T as matchDocumentedPath,k as recoveryToolNames,c as visibleEndpoints,l as visibleMethodsAt,s as visibleOperations,u as visiblePaths,d as withVisibleOperationsOnly,o as withoutXMcp};
@@ -1 +1 @@
1
- import{apiTitleKey as e,countApiTitles as t,orderSharedTitles as n}from"./api-titles.js";import{describeMethodMiss as r,describePathMiss as i,matchDocumentedPath as a,visibleEndpoints as o,visibleOperations as s,withVisibleOperationsOnly as c,withoutXMcp as l}from"./openapi-document.js";import{filterApisByName as u,loadApiCatalog as d,resolveApi as f}from"./openapi-catalog.js";import{callableApis as p}from"../gateway/eligibility.js";import{inlineOperation as m,resolveOperation as h}from"./openapi-refs.js";import{GET_ENDPOINTS_SCHEMA as g,GET_ENDPOINT_INFO_SCHEMA as _,GET_FULL_API_DESCRIPTION_SCHEMA as v,GET_SECURITY_SCHEMES_SCHEMA as y,LIST_APIS_CALLABLE_SCHEMA as b,LIST_APIS_SCHEMA as x,getEndpointInfoToolSchema as S,getEndpointsToolSchema as C,getFullApiDescriptionToolSchema as w,getSecuritySchemesToolSchema as T}from"@redocly/mcp";import{replaceServerVariables as E}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";const D=8388608,O={apiName:`name`,api:`name`};function k(e){return e.map(e=>({...e,url:E(e)}))}async function A(e){return new Set((await p(e)).map(e=>e.entityKey))}const j=[{schema:x,schemaFor:async e=>(await A(e)).size>0?b:x,async execute(r,i){let a=r??{},{filter:o}=a,s=a.page??1,c=a.limit??300,l=await A(i),f=n(await d(i)),p=t(f),m=o?u(f,o):f,h=(s-1)*c;return{items:m.slice(h,h+c).map(({entityKey:t,relativePath:n,name:r,description:i,version:a,servers:o})=>({filePath:n,name:r,description:i,version:a,servers:k(o),ambiguousTitle:(p.get(e(r))??0)>1||void 0,callable:l.size>0?l.has(t):void 0})),limit:c,total:m.length,page:s,totalPages:Math.ceil(m.length/c)}}},{schema:g,schemaFor:e=>C(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await f(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,servers:k(n.servers),endpoints:o(n.definition)}}},{schema:_,schemaFor:e=>S(e.mcpMode),inputAliases:O,async execute(e,t){let n=e??{},{path:o,method:c}=n;if(!o||!c)throw Error(`Both "path" and "method" are required (e.g. path: "/tickets", method: "GET").`);let{api:u,otherMatches:d}=await f(n,t),{definition:p}=u,g=d?` Other definitions share this title: ${d.map(e=>`"${e.filePath}"`).join(`, `)}. Pass "filePath" to check them.`:``,_=a(p,o),v=p.paths?.[_],y=s(v);if(!v||y.length===0)throw Error(i(p,u.name,_,t.mcpMode)+g);let b=y.find(([e])=>e.toLowerCase()===c.toLowerCase())?.[1];if(!b)throw Error(r(p,u.name,_,c)+g);let x={operation:l(b),pathParams:v.parameters??[],definition:p},{operation:S,components:C}=(t.mcpMode===`code`?m(x,1048576):void 0)??h(x),w={api:u.name,version:u.version,filePath:u.relativePath,otherMatches:d,servers:k(u.servers),endpoint:{path:_,method:c.toUpperCase(),...S},globalSecurity:p.security??[],securitySchemes:p.components?.securitySchemes??{},components:C},T=JSON.stringify(w,null,2).length;if(T>D)throw Error(`${c.toUpperCase()} ${_} is ${T} bytes, over the ${D} byte limit.`);return w}},{schema:y,schemaFor:e=>T(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await f(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,securitySchemes:n.definition.components?.securitySchemes??{},security:n.definition.security??[]}}},{schema:v,schemaFor:e=>w(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await f(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,definition:c(n.definition)}}}];export{j as openApiTools};
1
+ import{describeMethodMiss as e,describePathMiss as t,matchDocumentedPath as n,visibleEndpoints as r,visibleOperations as i,withVisibleOperationsOnly as a,withoutXMcp as o}from"./openapi-document.js";import{GET_ENDPOINTS_SCHEMA as s,GET_ENDPOINT_INFO_SCHEMA as c,GET_FULL_API_DESCRIPTION_SCHEMA as l,GET_SECURITY_SCHEMES_SCHEMA as u,LIST_APIS_CALLABLE_SCHEMA as d,LIST_APIS_SCHEMA as f,getEndpointInfoToolSchema as p,getEndpointsToolSchema as m,getFullApiDescriptionToolSchema as h,getSecuritySchemesToolSchema as g}from"./schemas.js";import{apiTitleKey as _,countApiTitles as v,orderSharedTitles as y}from"./api-titles.js";import{filterApisByName as b,loadApiCatalog as x,resolveApi as S}from"./openapi-catalog.js";import{callableApis as C}from"../gateway/eligibility.js";import{inlineOperation as w,resolveOperation as T}from"./openapi-refs.js";import{replaceServerVariables as E}from"@redocly/api-docs/lib/services/code-samples/server-variables.js";const D=8388608,O={apiName:`name`,api:`name`};function k(e){return e.map(e=>({...e,url:E(e)}))}async function A(e){return new Set((await C(e)).map(e=>e.entityKey))}const j=[{schema:f,schemaFor:async e=>(await A(e)).size>0?d:f,async execute(e,t){let n=e??{},{filter:r}=n,i=n.page??1,a=n.limit??300,o=await A(t),s=y(await x(t)),c=v(s),l=r?b(s,r):s,u=(i-1)*a;return{items:l.slice(u,u+a).map(({entityKey:e,relativePath:t,name:n,description:r,version:i,servers:a})=>({filePath:t,name:n,description:r,version:i,servers:k(a),ambiguousTitle:(c.get(_(n))??0)>1||void 0,callable:o.size>0?o.has(e):void 0})),limit:a,total:l.length,page:i,totalPages:Math.ceil(l.length/a)}}},{schema:s,schemaFor:e=>m(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:i}=await S(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:i,servers:k(n.servers),endpoints:r(n.definition)}}},{schema:c,schemaFor:e=>p(e.mcpMode),inputAliases:O,async execute(r,a){let s=r??{},{path:c,method:l}=s;if(!c||!l)throw Error(`Both "path" and "method" are required (e.g. path: "/tickets", method: "GET").`);let{api:u,otherMatches:d}=await S(s,a),{definition:f}=u,p=d?` Other definitions share this title: ${d.map(e=>`"${e.filePath}"`).join(`, `)}. Pass "filePath" to check them.`:``,m=n(f,c),h=f.paths?.[m],g=i(h);if(!h||g.length===0)throw Error(t(f,u.name,m,a.mcpMode)+p);let _=g.find(([e])=>e.toLowerCase()===l.toLowerCase())?.[1];if(!_)throw Error(e(f,u.name,m,l)+p);let v={operation:o(_),pathParams:h.parameters??[],definition:f},{operation:y,components:b}=(a.mcpMode===`code`?w(v,1048576):void 0)??T(v),x={api:u.name,version:u.version,filePath:u.relativePath,otherMatches:d,servers:k(u.servers),endpoint:{path:m,method:l.toUpperCase(),...y},globalSecurity:f.security??[],securitySchemes:f.components?.securitySchemes??{},components:b},C=JSON.stringify(x,null,2).length;if(C>D)throw Error(`${l.toUpperCase()} ${m} is ${C} bytes, over the ${D} byte limit.`);return x}},{schema:u,schemaFor:e=>g(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await S(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,securitySchemes:n.definition.components?.securitySchemes??{},security:n.definition.security??[]}}},{schema:l,schemaFor:e=>h(e.mcpMode),inputAliases:O,async execute(e,t){let{api:n,otherMatches:r}=await S(e??{},t);return{api:n.name,version:n.version,filePath:n.relativePath,otherMatches:r,definition:a(n.definition)}}}];export{j as openApiTools};
@@ -0,0 +1 @@
1
+ const e=200,t=1e3,n=20,r=100;export{n as DEFAULT_GREP_MATCHES,e as DEFAULT_PAGE_LINES,r as MAX_GREP_MATCHES,t as MAX_PAGE_LINES};
@@ -1 +1 @@
1
- import"../../../../../../shared/constants/app-data.js";import{toAppData as e}from"../../../../../../shared/utils/app-data.js";import{normalizeRouteSlug as t}from"../../../../../../shared/utils/routes/normalize-route-slug.js";import{stripPathPrefix as n,withPathPrefix as r}from"../../../../../../shared/path-prefix.js";import{normalizeRoutePath as i}from"../../../../../../shared/utils/routes/normalize-route-path.js";import{filterRbacAnnotatedValue as a}from"../../../../../../server/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:n,isVisible:r},i,o]=await Promise.all([m(e),w(e),T(e)]),s=o.filter(e=>typeof e.link==`string`&&e.external!==!0&&r(t(e.link))),c=new Map(n.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:n,id:i,links:o}of p){for(let e of o)l.add(e);let d=N(k(a(n,e.request.teams)),e=>r(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 _=n.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:n}}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,t){return`${t}${r(e)}`}function C(e,t){let r;try{r=new URL(e.trim(),t).pathname}catch{return null}let a=n(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(t){if(!await t.entities.get(`app-data`))return[];let n=e(await t.entities.load(`app-data`)).theme?.navbar?.items??[];return E(a(n,t.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?[t(e.link)]:[],...M(e.items??[])])}function N(e,n){return e.flatMap(e=>{let r=j(e)&&e.link?t(e.link):void 0,i=r!==void 0&&n(r)?r:void 0;if(e.items){let t=N(e.items,n);return t.length===0&&!i?[]:[{type:`section`,label:e.label??``,...i?{link:i}:{},items:t}]}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"../../../../../../server/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};