@redocly/realm 0.137.0-next.11 → 0.137.0-next.12

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 (62) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/cli/build/index.js +1 -1
  3. package/dist/client/app/Sidebar/useActions.js +1 -1
  4. package/dist/client/app/Sidebar/useSidebarItems.js +1 -1
  5. package/dist/client/app/hooks/catalog/useCatalogFilter.js +1 -1
  6. package/dist/client/app/seo/SeoTags.js +1 -1
  7. package/dist/server/esbuild/esbuild-logger.d.ts +2 -2
  8. package/dist/server/esbuild/esbuild-logger.js +3 -3
  9. package/dist/server/plugins/api-docs/search/get-ai-search-documents.d.ts +1 -1
  10. package/dist/server/plugins/api-docs/search/get-ai-search-documents.js +33 -33
  11. package/dist/server/plugins/mcp/codemode/capabilities/fetch/index.js +5 -4
  12. package/dist/server/plugins/mcp/codemode/capabilities/types.d.ts +5 -2
  13. package/dist/server/plugins/mcp/codemode/capabilities/utils.js +4 -4
  14. package/dist/server/plugins/mcp/codemode/prompts.d.ts +1 -1
  15. package/dist/server/plugins/mcp/codemode/prompts.js +7 -6
  16. package/dist/server/plugins/mcp/codemode/sandbox/create-sandbox-setup.d.ts +2 -2
  17. package/dist/server/plugins/mcp/codemode/sandbox/create-sandbox-setup.js +1 -11
  18. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/console.d.ts +2 -0
  19. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/console.js +5 -0
  20. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/index.d.ts +1 -0
  21. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/index.js +2 -2
  22. package/dist/server/plugins/mcp/codemode/sandbox/tool-input-validator.d.ts +5 -0
  23. package/dist/server/plugins/mcp/codemode/sandbox/tool-input-validator.js +1 -0
  24. package/dist/server/plugins/mcp/codemode/sandbox/unknown-tool-hint.d.ts +8 -0
  25. package/dist/server/plugins/mcp/codemode/sandbox/unknown-tool-hint.js +2 -0
  26. package/dist/server/plugins/mcp/codemode/tools/describe-tools.js +3 -1
  27. package/dist/server/plugins/mcp/codemode/tools/execute.js +1 -1
  28. package/dist/server/plugins/mcp/codemode/tools/manage-credentials.js +2 -2
  29. package/dist/server/plugins/mcp/docs-mcp/tool-schemas.js +1 -1
  30. package/dist/server/plugins/mcp/docs-mcp/tools/core/search.js +2 -2
  31. package/dist/server/plugins/mcp/docs-mcp/tools/core/types.d.ts +2 -2
  32. package/dist/server/plugins/mcp/docs-mcp/tools/graphql/get-graphql-type.js +5 -5
  33. package/dist/server/plugins/mcp/docs-mcp/tools/graphql/types.d.ts +2 -1
  34. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/list-apis.js +1 -1
  35. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/load-api-description.d.ts +4 -2
  36. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/load-api-description.js +1 -1
  37. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/types.d.ts +6 -2
  38. package/dist/server/plugins/mcp/docs-mcp/utils/api-titles.d.ts +6 -0
  39. package/dist/server/plugins/mcp/docs-mcp/utils/api-titles.js +1 -0
  40. package/dist/server/plugins/mcp/gateway-mcp/fetch/ssrf-guard.js +1 -1
  41. package/dist/server/plugins/mcp/gateway-mcp/fetch/url-placeholders.d.ts +5 -0
  42. package/dist/server/plugins/mcp/gateway-mcp/fetch/url-placeholders.js +1 -0
  43. package/dist/server/plugins/mcp/servers/docs-server.js +1 -1
  44. package/dist/server/plugins/mcp/servers/mcp-server.js +2 -2
  45. package/dist/server/plugins/mcp/types.d.ts +1 -0
  46. package/dist/server/plugins/mcp/utils/available-sandbox-tools.js +1 -1
  47. package/dist/server/plugins/search/ai-indexer/prepare-semantic-documents.js +1 -1
  48. package/dist/server/plugins/search/llmstxt/create-llms-txt-generator.js +1 -1
  49. package/dist/server/plugins/search/llmstxt/index.d.ts +3 -1
  50. package/dist/server/plugins/search/llmstxt/index.js +9 -9
  51. package/dist/server/sandbox/sandbox.js +2 -2
  52. package/dist/server/sandbox/types.d.ts +8 -0
  53. package/dist/server/sandbox/utils/execution-budget.js +1 -1
  54. package/dist/server/sandbox/utils/return-last-expression.d.ts +6 -0
  55. package/dist/server/sandbox/utils/return-last-expression.js +1 -0
  56. package/dist/server/sandbox/utils/setup-host-functions.d.ts +1 -0
  57. package/dist/server/sandbox/utils/setup-host-functions.js +2 -2
  58. package/dist/server/store.js +1 -1
  59. package/dist/server/web-server/routes/dynamic-route.js +1 -1
  60. package/dist/server/web-server/routes/mcp-routes/mcp-oauth.js +1 -1
  61. package/dist/server/web-server/routes/mcp-routes/mcp-server-card.js +1 -1
  62. package/package.json +6 -6
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # @redocly/realm
2
2
 
3
+ ## 0.137.0-next.12
4
+
5
+ ### Minor Changes
6
+
7
+ - 7df87b0c29d: Added the `singleExpanded` attribute to the `accordion-group` Markdoc tag to keep only one accordion open at a time.
8
+ - c3957bee9b2: Improved MCP server code mode to reduce AI agent script failures and provide clearer error messages.
9
+
10
+ ### Patch Changes
11
+
12
+ - 43ec2eb3a83: Fixed the `documentationUrl` in the MCP server card to include the path prefix.
13
+ - c09e6eb1c9d: Fixed an issue in Replay where Basic authentication credentials with non-ASCII characters produced a corrupted Authorization header or prevented the request from being sent.
14
+ - e5705e50add: Fixed an issue in Replay and the Try it console where operations with many editable fields got slower on each reopening.
15
+ - 43ec2eb3a83: Fixed broken `llms.txt` links to use the configured `seo.siteUrl` instead of the Redocly-hosted domain.
16
+ - 8e4959baca4: Updated `@redocly/openapi-core` to version `2.53.0`.
17
+ - Updated dependencies [7df87b0c29d]
18
+ - Updated dependencies [0f773ab0bc9]
19
+ - Updated dependencies [8e4959baca4]
20
+ - @redocly/theme@0.69.0-next.11
21
+ - @redocly/realm-asyncapi-sdk@0.15.0-next.4
22
+ - @redocly/api-docs@0.2.0-next.12
23
+ - @redocly/portal-plugin-mock-server@0.22.0-next.9
24
+
3
25
  ## 0.137.0-next.11
4
26
 
5
27
  ### Patch Changes
@@ -1 +1 @@
1
- import b from"node:path";import{unlink as R}from"node:fs/promises";import{writeFileSync as y}from"node:fs";import{envConfig as h}from"../../server/config/env-config.js";import{PORTAL_VERSION as A}from"../../server/version.js";import{logger as e}from"../../server/tools/notifiers/logger.js";import{reporter as T}from"../../server/tools/notifiers/reporter.js";import{shutdowner as O}from"../../server/tools/shutdowner.js";import{promiseMapLimit as D}from"../../server/utils/async/promise-map-limit.js";import{validateReactPages as E}from"../../server/plugins/pages/validators/validate-react-pages.js";import{ensureDir as S}from"../../server/utils/index.js";import{initPlugins as M,runPlugins as j,writeClientEntries as x}from"../../server/plugins/lifecycle.js";import{createClientCompiler as L,createNodeBundleCompiler as J}from"../../server/esbuild/esbuild.js";import{validateAllMarkdowns as k}from"../../server/plugins/markdown/compiler.js";import{copyEnvFiles as F}from"./copy-env-files.js";import{EsbuildError as s,esbuildLogger as d}from"../../server/esbuild/esbuild-logger.js";import{reportAllErrors as U}from"../../server/utils/report-all-errors.js";import{collectAnalytics as z}from"./analytics/collect-analytics.js";import{copyMigrationsFolder as N}from"../../server/providers/database/copy-migrations.js";import{telemetry as c}from"../telemetry/index.js";import{telemetryTraceStep as m}from"../telemetry/helpers/trace-step.js";async function li(v,i){c.initialize(A),e.info("Starting project build.");const C=e.startTiming();await m("com.redocly.build.start",async P=>{x(i);const p=await L(i,i.outdir,"production"),u=await J(i,i.serverOutDir,"production");let o,g;try{await m("com.redocly.build.clientCompilation",async()=>{const l=e.startTiming(),n=await p.rebuild().catch(a=>{throw new s(a)});Array.isArray(n.warnings)&&d(new s({warnings:n.warnings}));const r=e.infoTime(l,"Client JavaScript compiled");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...r}])}),await m("com.redocly.build.serverCompilation",async()=>{const l=e.startTiming(),n=await u.rebuild().catch(a=>{throw new s(a)});Array.isArray(n.warnings)&&d(new s({warnings:n.warnings}));const r=e.infoTime(l,"Server JavaScript compiled");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",message:r.message,timeMs:r.timeMs}])}),await i.reloadMarkdocOptions();let t;({pluginInstances:t,lifecycleContext:o}=await M({outdir:i.outdir,serverOutDir:i.serverOutDir,contentDir:i.contentDir,devLogin:v.devLogin,setGlobalConfig:i.setGlobalConfig})),o.fs.dispose(),i.lifecycleContext=o,N(i),await j(t,i,o),g=z(i,o),await m("com.redocly.build.clientServerRecompile",async()=>{const l=e.startTiming();e.info("Re-compiling JavaScript with user code"),(await Promise.all([p.rebuild(),u.rebuild()]).catch(a=>{throw new s(a)})).forEach(({warnings:a})=>{Array.isArray(a)&&d(new s({warnings:a}))});const r=e.infoTime(l,"JavaScript re-compiled");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...r}])}),await m("com.redocly.build.pagesValidation",async()=>{await E(i,o),await k(i,o)}),await U(o),i.markUserCodeReady()}catch(t){P?.error(t),t instanceof s&&d(t)}finally{g&&await g.catch(()=>{}),await p.dispose(),await u.dispose()}T.printErrors(),e.info("Rendering pages..."),await m("com.redocly.build.prepareStaticData",async t=>{const l=e.startTiming(),n=[...i.getAllRoutes(),...i.getAllApiRoutes()];t?.setAttribute("totalRoutes",n.length.toString()),await D(n,15,a=>i.writeRouteStaticData(a,o));const r=e.successTime(l,"Page static data prepared.");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...r}])}),await m("com.redocly.build.storeSerialization",async()=>{const t=e.startTiming();S(i.serverOutDir),y(b.join(i.serverOutDir,"store.json"),JSON.stringify(await i.toJson())),e.successTime(t,"Store serialized and written."),F(i)});const f=h.REDOCLY_PROBLEMS_OUTPUT_FILE;if(f){const t=e.startTiming();y(S(f),JSON.stringify(T.getProblems()),"utf-8"),e.successTime(t,"Broken links written.")}await R(b.join(i.serverOutDir,"index.css"));const w=e.successTime(C,"All done");w&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...w}])}),await O.exitWithCode(0)}export{li as build};
1
+ import y from"node:path";import{unlink as R}from"node:fs/promises";import{writeFileSync as T}from"node:fs";import{envConfig as h}from"../../server/config/env-config.js";import{PORTAL_VERSION as A}from"../../server/version.js";import{logger as e}from"../../server/tools/notifiers/logger.js";import{reporter as f}from"../../server/tools/notifiers/reporter.js";import{shutdowner as O}from"../../server/tools/shutdowner.js";import{promiseMapLimit as D}from"../../server/utils/async/promise-map-limit.js";import{validateReactPages as E}from"../../server/plugins/pages/validators/validate-react-pages.js";import{ensureDir as S}from"../../server/utils/index.js";import{initPlugins as M,runPlugins as j,writeClientEntries as x}from"../../server/plugins/lifecycle.js";import{createClientCompiler as L,createNodeBundleCompiler as J}from"../../server/esbuild/esbuild.js";import{validateAllMarkdowns as k}from"../../server/plugins/markdown/compiler.js";import{copyEnvFiles as F}from"./copy-env-files.js";import{EsbuildError as s,esbuildLogger as d}from"../../server/esbuild/esbuild-logger.js";import{reportAllErrors as U}from"../../server/utils/report-all-errors.js";import{collectAnalytics as z}from"./analytics/collect-analytics.js";import{copyMigrationsFolder as N}from"../../server/providers/database/copy-migrations.js";import{telemetry as c}from"../telemetry/index.js";import{telemetryTraceStep as m}from"../telemetry/helpers/trace-step.js";async function li(v,i){c.initialize(A),e.info("Starting project build.");const C=e.startTiming();await m("com.redocly.build.start",async P=>{x(i);const p=await L(i,i.outdir,"production"),u=await J(i,i.serverOutDir,"production");let o,g;try{await m("com.redocly.build.clientCompilation",async()=>{const l=e.startTiming(),n=await p.rebuild().catch(a=>{throw new s(a)});Array.isArray(n.warnings)&&d(new s({warnings:n.warnings}));const r=e.infoTime(l,"Client JavaScript compiled");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...r}])}),await m("com.redocly.build.serverCompilation",async()=>{const l=e.startTiming(),n=await u.rebuild().catch(a=>{throw new s(a)});Array.isArray(n.warnings)&&d(new s({warnings:n.warnings}));const r=e.infoTime(l,"Server JavaScript compiled");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",message:r.message,timeMs:r.timeMs}])}),await i.reloadMarkdocOptions();let t;({pluginInstances:t,lifecycleContext:o}=await M({outdir:i.outdir,serverOutDir:i.serverOutDir,contentDir:i.contentDir,devLogin:v.devLogin,setGlobalConfig:i.setGlobalConfig})),o.fs.dispose(),i.lifecycleContext=o,N(i),await j(t,i,o),g=z(i,o),await m("com.redocly.build.clientServerRecompile",async()=>{const l=e.startTiming();e.info("Re-compiling JavaScript with user code"),(await Promise.all([p.rebuild(),u.rebuild()]).catch(a=>{throw new s(a)})).forEach(({warnings:a})=>{Array.isArray(a)&&d(new s({warnings:a}))});const r=e.infoTime(l,"JavaScript re-compiled");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...r}])}),await m("com.redocly.build.pagesValidation",async()=>{await E(i,o),await k(i,o)}),await U(o),i.markUserCodeReady()}catch(t){P?.error(t),t instanceof s&&await d(t),await f.panic(t instanceof Error?t:String(t))}finally{g&&await g.catch(()=>{}),await p.dispose(),await u.dispose()}f.printErrors(),e.info("Rendering pages..."),await m("com.redocly.build.prepareStaticData",async t=>{const l=e.startTiming(),n=[...i.getAllRoutes(),...i.getAllApiRoutes()];t?.setAttribute("totalRoutes",n.length.toString()),await D(n,15,a=>i.writeRouteStaticData(a,o));const r=e.successTime(l,"Page static data prepared.");r&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...r}])}),await m("com.redocly.build.storeSerialization",async()=>{const t=e.startTiming();S(i.serverOutDir),T(y.join(i.serverOutDir,"store.json"),JSON.stringify(await i.toJson())),e.successTime(t,"Store serialized and written."),F(i)});const w=h.REDOCLY_PROBLEMS_OUTPUT_FILE;if(w){const t=e.startTiming();T(S(w),JSON.stringify(f.getProblems()),"utf-8"),e.successTime(t,"Broken links written.")}await R(y.join(i.serverOutDir,"index.css"));const b=e.successTime(C,"All done");b&&c.sendTimingPerformedMessage([{id:"buildStep",object:"timing",uri:"urn:redocly:realm:cli:timing:buildStep",...b}])}),await O.exitWithCode(0)}export{li as build};
@@ -1 +1 @@
1
- import t from"react";import{LayoutVariant as o}from"@redocly/config";import{usePageSharedData as C}from"../../providers/page-data/hooks";function L(){const e=C("apiDocsStore"),c=!!e,a=e?.options?.layout,[n,s]=t.useState(a||o.THREE_PANEL),[i,l]=t.useState(!1),[u,r]=t.useState(!1);t.useEffect(()=>{u||s(a||o.THREE_PANEL)},[a,u]);function f(){s(n===o.STACKED?o.THREE_PANEL:o.STACKED),r(!0)}function p(){l(E=>!E)}return{onChangeViewClick:f,onChangeCollapseSidebarClick:p,layout:n,collapsedSidebar:i,isApiDocs:c}}export{L as useActions};
1
+ import e from"react";import{LayoutVariant as o}from"@redocly/config";import{usePageSharedData as f}from"../../providers/page-data/hooks";function d(){const t=f("apiDocsStore"),n=!!t,s=t?.options?.layout,[c,i]=e.useState(!1),[l,u]=e.useState(null),a=l??s??o.THREE_PANEL;function r(){u(a===o.STACKED?o.THREE_PANEL:o.STACKED)}function p(){i(S=>!S)}return{onChangeViewClick:r,onChangeCollapseSidebarClick:p,layout:a,collapsedSidebar:c,isApiDocs:n}}export{d as useActions};
@@ -1 +1 @@
1
- import{useLocation as _}from"react-router";import{useEffect as k,useMemo as S,useState as b}from"react";import{useActiveSectionId as D}from"@redocly/theme/core/hooks";import{getMenuItemType as v}from"@redocly/theme/core/utils";import{MenuItemType as C}from"@redocly/theme/core/constants";import{CATALOG_BASE_SLUG as T,CATALOG_SLUGS as h}from"../../../constants/catalog-entities";import{usePageSharedData as y,useSidebarItemsData as G,useSidebarConnectedCatalogConfig as E,useSidebarConnectedCatalogEntity as O}from"../../providers/page-data/hooks";import{mapItemsPropsToState as g}from"./utils";import{injectCatalogItems as K}from"../../utils/catalog/inject-catalog-items";import{filterOutVersionedItems as B}from"./helpers/filter-out-versioned-items";const M="catalog.backToAllLabel",P=`${T}/${h.ALL}`;function U(n){const e=G();return S(()=>B(e,n),[e,n])}function J(n){const e=_(),t=D(e,!0),a=O(),p=E(),s=U(n),c=a?K(s,a.key,p?.slug,e.search):s,[u,I]=b(null),r=S(()=>g(c,e,t),[t,e,c]),l=y("current-catalog-info"),L=S(()=>f(r),[c]),[o,m]=b(L),i=o.length>0?o[o.length-1]:void 0,A=i&&g([...i.item.link?[{...i.item,items:[],menuStyle:void 0,separatorLine:!1}]:[],...i.item.items],e,t);k(()=>{if(!u||u!==t){const d=f(r);m(d),I(t)}},[s,e,t,u]);const w=i?{slug:i.previousLink,event:"sidebar_drilldown_back_button.clicked"}:a?{label:"Back to Catalog",labelTranslationKey:M,slug:P,event:"back_to_catalog_button.clicked"}:l?{label:l.catalog.label,labelTranslationKey:l.catalog.labelTranslationKey,slug:l.catalog.link,event:"back_to_catalog_button.clicked"}:void 0;return{currentItems:A||r,allSidebarItems:r,popDrilldownState:()=>{o.length>0&&m(o.slice(0,o.length-1))},pushDrilldownState:d=>{m([...o,d])},backLink:w,versionLabel:a?.version??null}}function f(n,e=[]){for(const t of n){if(!t.active&&!t.hasActiveSubItem)continue;if(v(t)===C.DrillDown&&e.push({item:t}),t.active)return e;if(t.hasActiveSubItem)return f(t.items,e)}return e}export{U as useRawSidebarItems,J as useSidebarItems};
1
+ import{useLocation as A}from"react-router";import{useEffect as w,useMemo as f,useRef as _,useState as k}from"react";import{useActiveSectionId as D}from"@redocly/theme/core/hooks";import{getMenuItemType as C}from"@redocly/theme/core/utils";import{MenuItemType as v}from"@redocly/theme/core/constants";import{CATALOG_BASE_SLUG as T,CATALOG_SLUGS as h}from"../../../constants/catalog-entities";import{usePageSharedData as y,useSidebarItemsData as G,useSidebarConnectedCatalogConfig as E,useSidebarConnectedCatalogEntity as O}from"../../providers/page-data/hooks";import{mapItemsPropsToState as b}from"./utils";import{injectCatalogItems as K}from"../../utils/catalog/inject-catalog-items";import{filterOutVersionedItems as R}from"./helpers/filter-out-versioned-items";const B="catalog.backToAllLabel",M=`${T}/${h.ALL}`;function U(o){const e=G();return f(()=>R(e,o),[e,o])}function J(o){const e=A(),t=D(e,!0),a=O(),g=E(),c=U(o),s=a?K(c,a.key,g?.slug,e.search):c,u=_(null),r=f(()=>b(s,e,t),[t,e,s]),l=y("current-catalog-info"),p=f(()=>S(r),[s]),[n,m]=k(p),i=n.length>0?n[n.length-1]:void 0,I=i&&b([...i.item.link?[{...i.item,items:[],menuStyle:void 0,separatorLine:!1}]:[],...i.item.items],e,t);w(()=>{if(!u.current||u.current!==t){const d=S(r);m(d),u.current=t}},[c,e,t]);const L=i?{slug:i.previousLink,event:"sidebar_drilldown_back_button.clicked"}:a?{label:"Back to Catalog",labelTranslationKey:B,slug:M,event:"back_to_catalog_button.clicked"}:l?{label:l.catalog.label,labelTranslationKey:l.catalog.labelTranslationKey,slug:l.catalog.link,event:"back_to_catalog_button.clicked"}:void 0;return{currentItems:I||r,allSidebarItems:r,popDrilldownState:()=>{n.length>0&&m(n.slice(0,n.length-1))},pushDrilldownState:d=>{m([...n,d])},backLink:L,versionLabel:a?.version??null}}function S(o,e=[]){for(const t of o){if(!t.active&&!t.hasActiveSubItem)continue;if(C(t)===v.DrillDown&&e.push({item:t}),t.active)return e;if(t.hasActiveSubItem)return S(t.items,e)}return e}export{U as useRawSidebarItems,J as useSidebarItems};
@@ -1 +1 @@
1
- import{useCallback as h,useEffect as w,useMemo as y,useState as P}from"react";import{useSearchParams as Q}from"react-router";import{telemetry as b}from"../../telemetry/index.js";import{parseFilterQuery as g,formatFilterQuery as C,collectFilterOptions as U}from"../../../utils";import{getBaseDataAttributes as I}from"@redocly/theme/core/utils";function O(r){return r instanceof Set?r.size>0:!!(r?.from||r?.to)}function x(r,m){const[u,d]=Q(),o=u.get("filter")||"",[i,f]=P(()=>g(o,r?.filters||[])),p=y(()=>U(r?.filters,m),[r?.filters,m]);w(()=>{const t=r?.filters||[];if(t.length>0&&i.length!==t.length){const e=g(o,t);f(e)}},[r?.filters,i.length,o]);const F=h((t,e)=>{f(l=>l.map((s,c)=>{if(c!==t||!(s instanceof Set))return s;const n=new Set(s);return n.has(e)?n.delete(e):n.add(e),n})),window.scrollTo(0,0)},[]),S=h((t,e)=>{f(l=>l.map((a,s)=>s!==t?a:a instanceof Set?e&&typeof e=="string"?new Set([e]):new Set:{from:typeof e=="object"?e?.from:void 0,to:typeof e=="object"?e?.to:void 0})),b.sendCatalogFilterChangedMessage([{...I("catalogFilter","field"),type:"select"}]),window.scrollTo(0,0)},[]);return w(()=>{const t=new URLSearchParams(u),e=C(i,r?.filters||[]);e?t.set("filter",e):t.delete("filter"),d(t,{replace:!0})},[r?.filters,i,u,d]),y(()=>{const t=p.map((l,a)=>{const s=i[a],c=O(s);return{...l,toggleOption:n=>F(a,n),selectOption:n=>S(a,n),selectedOptions:s??new Set,isFilterUsed:c}});return{filters:t.map(l=>{const a=t.findIndex(n=>n.property===l.parentFilter),s=i[a],c=l.parentFilter?O(s):!0;return{...l,parentUsed:c}}),filterQuery:o}},[p,i,F,S,o])}export{x as useCatalogFilter};
1
+ import{useCallback as h,useEffect as P,useMemo as w,useState as Q}from"react";import{useSearchParams as b}from"react-router";import{telemetry as C}from"../../telemetry/index.js";import{parseFilterQuery as y,formatFilterQuery as U,collectFilterOptions as j}from"../../../utils";import{getBaseDataAttributes as I}from"@redocly/theme/core/utils";function O(t){return t instanceof Set?t.size>0:!!(t?.from||t?.to)}function z(t,d){const[u,p]=b(),c=u.get("filter")||"",[o,f]=Q(()=>y(c,t?.filters||[])),F=w(()=>j(t?.filters,d),[t?.filters,d]),m=t?.filters||[];m.length>0&&o.length!==m.length&&f(y(c,m));const S=h((s,e)=>{f(l=>l.map((r,i)=>{if(i!==s||!(r instanceof Set))return r;const n=new Set(r);return n.has(e)?n.delete(e):n.add(e),n})),window.scrollTo(0,0)},[]),g=h((s,e)=>{f(l=>l.map((a,r)=>r!==s?a:a instanceof Set?e&&typeof e=="string"?new Set([e]):new Set:{from:typeof e=="object"?e?.from:void 0,to:typeof e=="object"?e?.to:void 0})),C.sendCatalogFilterChangedMessage([{...I("catalogFilter","field"),type:"select"}]),window.scrollTo(0,0)},[]);return P(()=>{const s=new URLSearchParams(u),e=U(o,t?.filters||[]);e?s.set("filter",e):s.delete("filter"),p(s,{replace:!0})},[t?.filters,o,u,p]),w(()=>{const s=F.map((l,a)=>{const r=o[a],i=O(r);return{...l,toggleOption:n=>S(a,n),selectOption:n=>g(a,n),selectedOptions:r??new Set,isFilterUsed:i}});return{filters:s.map(l=>{const a=s.findIndex(n=>n.property===l.parentFilter),r=o[a],i=l.parentFilter?O(r):!0;return{...l,parentUsed:i}}),filterQuery:c}},[F,o,S,g,c])}export{z as useCatalogFilter};
@@ -1 +1 @@
1
- import n from"react";import{Helmet as u}from"@dr.pogodin/react-helmet";import{combineUrls as p}from"@redocly/theme/core/utils";import{isTruthy as g}from"../../../utils/guards/is-truthy";import{usePageVersions as k}from"../../providers/page-data/hooks";import{getMetaTagsAttributes as d}from"../utils/get-meta-tags-attributes";import{useHreflangLinks as E}from"./hooks/useHreflangLinks";function U(o){const{seo:e,slug:i}=o,{versions:s}=k(),r=e?.siteUrl,{localeAlternates:a}=E(r);if(!e)return null;const m=d(e),c=[e.title,e.projectTitle].filter(g).join(" | "),f=s.find(t=>t.default)?.link||i;return n.createElement(u,null,n.createElement("title",null,c),r?n.createElement("link",{rel:"canonical",href:p(r,f)}):null,a.map(({hrefLang:t,href:l})=>n.createElement("link",{key:t,rel:"alternate",hrefLang:t,href:l})),e.jsonLd?n.createElement("script",{type:"application/ld+json"},JSON.stringify(e.jsonLd)):null,m.map((t,l)=>n.createElement("meta",{key:l,...t})))}export{U as SeoTags};
1
+ import n from"react";import{Helmet as p}from"@dr.pogodin/react-helmet";import{combineUrls as g,withPathPrefix as k}from"@redocly/theme/core/utils";import{isTruthy as d}from"../../../utils/guards/is-truthy";import{usePageVersions as E}from"../../providers/page-data/hooks";import{getMetaTagsAttributes as h}from"../utils/get-meta-tags-attributes";import{useHreflangLinks as j}from"./hooks/useHreflangLinks";function U(o){const{seo:e,slug:s}=o,{versions:a}=E(),r=e?.siteUrl,{localeAlternates:m}=j(r);if(!e)return null;const c=h(e),f=[e.title,e.projectTitle].filter(d).join(" | "),i=a.find(t=>t.default)?.link,u=i?k(i):s;return n.createElement(p,null,n.createElement("title",null,f),r?n.createElement("link",{rel:"canonical",href:g(r,u)}):null,m.map(({hrefLang:t,href:l})=>n.createElement("link",{key:t,rel:"alternate",hrefLang:t,href:l})),e.jsonLd?n.createElement("script",{type:"application/ld+json"},JSON.stringify(e.jsonLd)):null,c.map((t,l)=>n.createElement("meta",{key:l,...t})))}export{U as SeoTags};
@@ -8,9 +8,9 @@ export type Location = {
8
8
  export declare class EsbuildError extends Error {
9
9
  errors: BuildFailure['errors'];
10
10
  warnings: BuildFailure['warnings'];
11
- constructor({ errors, warnings }: Partial<BuildFailure>);
11
+ constructor(failure: Partial<BuildFailure>);
12
12
  }
13
- export declare function esbuildLogger({ errors, warnings }: EsbuildError): Promise<void>;
13
+ export declare function esbuildLogger({ errors, warnings, message }: EsbuildError): Promise<void>;
14
14
  export declare function reportEsbuildError(message: string, sourceFileRelativePath: string, fileContent: string, location?: Location | null): {
15
15
  message: string;
16
16
  sourceFileRelativePath: string;
@@ -1,3 +1,3 @@
1
- import*as E from"esbuild";import{logger as c}from"../tools/notifiers/logger.js";import{reporter as u}from"../tools/notifiers/reporter.js";import{envConfig as f}from"../config/env-config.js";import{telemetry as d}from"../../cli/telemetry/index.js";import{stopAllCompilers as y}from"./esbuild.js";import{getCodeframe as C}from"../utils/codeframes/codeframes.js";import{shutdowner as M}from"../tools/shutdowner.js";class S extends Error{errors;warnings;constructor({errors:r=[],warnings:e=[]}){super(),this.errors=r,this.warnings=e}}async function T({errors:n,warnings:r}){const e=await m(n,"error"),s=await m(r,"warning");r.forEach((t,o)=>{c.warn(s[o])}),n.forEach((t,o)=>{const i=t.location?.file||"";i&&i.includes("node_modules/")?(c.error(e[o]),d.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:JSON.stringify(t)}])):(c.contentError(e[o]),d.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:JSON.stringify(t),scope:"content"}]))}),n.length&&f.isBuildMode&&(await y(),await M.exitWithCode(1))}async function m(n,r){return f.REDOCLY_LOG_FORMAT==="JSON"?n.map(e=>JSON.stringify(e)):await E.formatMessages(n,{kind:r,color:!1,terminalWidth:0})}function w(n,r){if(!r?.lineText)return{line:1,column:1,lines:n.split(`
2
- `),hasMatched:!1};const e=n.split(`
3
- `),{lineText:s}=r,t=i=>{const l=i.indexOf(s);return l===-1?null:l};if(r.line&&r.line<=e.length&&t(e[r.line-1]))return{line:r.line,column:r.column||1,lines:e,hasMatched:!0};const o=e.findIndex(i=>t(i)!==null);if(o>=0){const i=t(e[o]);return{line:o+1,column:(i??0)+1,lines:e,hasMatched:!0}}return{line:1,column:1,lines:e,hasMatched:!1}}function _(n,r,e,s){const{line:t,column:o,lines:i,hasMatched:l}=w(e,s),{frame:h,start:p}=C({start:{line:t,character:o},end:{line:t,character:o+(s?.lineText?.length||0)},lines:i},!0),g=`${n}::${r}::${t}`,a={message:n,sourceFileRelativePath:r,sourceFileLocation:p,codeframe:h,hasMatched:l};return u.getCompilationProblem(g)||u.reportCompilationError({type:"ERROR",severity:"ERROR",...a}),a}export{S as EsbuildError,T as esbuildLogger,_ as reportEsbuildError};
1
+ import*as E from"esbuild";import{logger as c}from"../tools/notifiers/logger.js";import{reporter as f}from"../tools/notifiers/reporter.js";import{envConfig as m}from"../config/env-config.js";import{telemetry as d}from"../../cli/telemetry/index.js";import{stopAllCompilers as y}from"./esbuild.js";import{getCodeframe as C}from"../utils/codeframes/codeframes.js";import{shutdowner as M}from"../tools/shutdowner.js";class N extends Error{errors;warnings;constructor(r){super(r.message,r instanceof Error?{cause:r}:void 0),this.errors=r.errors??[],this.warnings=r.warnings??[]}}async function T({errors:n,warnings:r,message:t}){const s=await h(n,"error"),o=await h(r,"warning");if(r.forEach((e,i)=>{c.warn(o[i])}),n.forEach((e,i)=>{const a=e.location?.file||"";a&&a.includes("node_modules/")?(c.error(s[i]),d.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:JSON.stringify(e)}])):(c.contentError(s[i]),d.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:JSON.stringify(e),scope:"content"}]))}),!n.length&&t){const e=`JavaScript compilation failed: ${t}`;c.error(e),d.sendCliErrorCaughtMessage([{id:"cli",object:"error",uri:"urn:redocly:realm:cli:error:cli",message:e}])}(n.length>0||t)&&m.isBuildMode&&(await y(),await M.exitWithCode(1))}async function h(n,r){return n.length?m.REDOCLY_LOG_FORMAT==="JSON"?n.map(t=>JSON.stringify(t)):await E.formatMessages(n,{kind:r,color:!1,terminalWidth:0}):[]}function w(n,r){if(!r?.lineText)return{line:1,column:1,lines:n.split(`
2
+ `),hasMatched:!1};const t=n.split(`
3
+ `),{lineText:s}=r,o=e=>{const i=e.indexOf(s);return i===-1?null:i};if(r.line&&r.line<=t.length&&o(t[r.line-1]))return{line:r.line,column:r.column||1,lines:t,hasMatched:!0};const l=t.findIndex(e=>o(e)!==null);if(l>=0){const e=o(t[l]);return{line:l+1,column:(e??0)+1,lines:t,hasMatched:!0}}return{line:1,column:1,lines:t,hasMatched:!1}}function _(n,r,t,s){const{line:o,column:l,lines:e,hasMatched:i}=w(t,s),{frame:a,start:g}=C({start:{line:o,character:l},end:{line:o,character:l+(s?.lineText?.length||0)},lines:e},!0),p=`${n}::${r}::${o}`,u={message:n,sourceFileRelativePath:r,sourceFileLocation:g,codeframe:a,hasMatched:i};return f.getCompilationProblem(p)||f.reportCompilationError({type:"ERROR",severity:"ERROR",...u}),u}export{N as EsbuildError,T as esbuildLogger,_ as reportEsbuildError};
@@ -15,6 +15,6 @@ type AiDocumentsStoreParams = {
15
15
  getSearchFacets: () => Map<string, SearchFacet>;
16
16
  markdocTags?: Record<string, MarkdocTagSchema>;
17
17
  };
18
- export declare function getAiDocumentsStore({ items, metadata, store, document, specType, excludeFromSearch, basePath, getSearchFacets, markdocTags, }: AiDocumentsStoreParams): (route: PageRouteDetails, _staticData: unknown, context: AfterRoutesCreatedLifecycleContext, actions: AfterRoutesCreatedActions) => Promise<AiDocumentsStore | undefined>;
18
+ export declare function getAiDocumentsStore({ items, metadata, store, document, specType, excludeFromSearch, basePath, getSearchFacets, markdocTags, }: AiDocumentsStoreParams): (route: PageRouteDetails, _staticData: unknown, _context: AfterRoutesCreatedLifecycleContext, actions: AfterRoutesCreatedActions) => Promise<AiDocumentsStore | undefined>;
19
19
  export {};
20
20
  //# sourceMappingURL=get-ai-search-documents.d.ts.map
@@ -1,34 +1,34 @@
1
- import P from"node:path";import{REDOCLY_TEAMS_RBAC as O}from"@redocly/config";import{nodeTypes as h,contentType as g}from"@redocly/api-docs";import{normalizeApiVersion as sn}from"../utils/normalize-api-version.js";import{replaceFileExtension as v}from"../utils/replace-file-extension.js";import{isResourcePubliclyAccessible as cn,canDownloadApiDefinition as ln,extractTeamsFromScopeItems as fn}from"../../../utils/rbac.js";import{getLlmsTxtMdPathBySlug as J}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{PUBLIC_API_DEFINITIONS_FOLDER as Q}from"../../../constants/common.js";import{GRAPHQL_SPEC_SLUG as an}from"../../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as pn}from"../../../constants/rbac.js";import{toMarkdown as N}from"../../markdown/search/to-markdown.js";import{createRenderTagFn as un}from"../../markdown/search/create-render-tag-fn.js";import{getLocaleFromRelativePath as dn}from"../../../fs/utils/get-locale-from-relative-path.js";import{getBuildTranslateContext as hn}from"../../../utils/l10n/get-build-translate-context.js";import{llmsTxtLink as w}from"../../search/llmstxt/index.js";import{formatDocumentMetadata as mn}from"../../search/utils.js";import{extractDocumentSearchFacets as $n}from"./search-facets.js";import{createApiDocsSearchIndexer as gn}from"./create-indexer.js";function A(t,r){return r==="openapi"&&"openapi"in t}function H(t,r){return r==="asyncapi"&&"asyncapi"in t}function Qn({items:t,metadata:r,store:s,document:n,specType:o,excludeFromSearch:i,basePath:e,getSearchFacets:l,markdocTags:c}){return async(f,a,u,d)=>{if(i)return;const m={...d.markdocOptions?.tags,...c},{locale:X,translate:Z}=await hn(f.slug,d.getGlobalData?.().l10n),C=un(m,X,Z),x=await u.getConfig(),L=dn(f.fsPath),j=gn(e,s?.schemaStore,n,s?.exampleStore),M=y=>{for(const p of y)j.addItem(p),p.items?.length&&M(p.items)};M(t);const nn=j.getResult(),V=new Map;for(const y of nn)V.set(y.url,y);const R=typeof r.title=="string"?r.title:void 0,_=sn(r.version),D=$n(f.metadata||{},R,_,l),S=[],I=[],q=yn(r,n,o),F=bn(o,r,f.fsPath,x),tn=In(t,x,C),en=q+F+`
2
- `+tn,on=q+F;I.push({title:R||"API Overview",description:typeof r.description=="string"?r.description:void 0,content:en,slug:e,fsPath:f.fsPath,includeInLLMsTxt:!0}),S.push({title:R||"API Overview",content:on,url:e,fsPath:f.fsPath,locale:L,product:f.product?.name,facets:D});const rn=n&&A(n,o)?n.security:void 0,E=y=>{for(const p of y){if(!p.content||!p.link){p.items?.length&&E(p.items);continue}const k=V.get(p.link),G=p.content.contentType,z=p[O],W=z?fn(z):void 0,B=W?.length?W:void 0;if(G===g.ITEM){const $=Pn(p,n,o)??Y(p,k,o,_,rn,C);if($){const b=p.label||"";I.push({title:b,description:void 0,content:$,slug:p.link,fsPath:f.fsPath,includeInLLMsTxt:!1}),S.push({title:b,content:$,url:p.link,fsPath:f.fsPath,locale:L,product:f.product?.name,facets:D,rbacTeams:B})}}else if(G===g.GROUP){const $=On(p,x,o,C);if($){const b=p.label||"";I.push({title:b,description:k?Rn(k.text):void 0,content:$.llmstxt,slug:p.link,fsPath:f.fsPath,includeInLLMsTxt:!1}),S.push({title:b,content:$.aiSearch,url:p.link,fsPath:f.fsPath,locale:L,product:f.product?.name,facets:D,rbacTeams:B})}}p.items?.length&&E(p.items)}};return E(t),{async getLLMsTxts(){return I},async getSearchDocuments(){return S}}}}function yn(t,r,s){const n=typeof t.title=="string"?t.title:"",o=typeof t.description=="string"?t.description:"",i=typeof t.summary=="string"?t.summary:"",e=typeof t.version=="string"?t.version:"";let l=n?`# ${n}
1
+ import P from"node:path";import{REDOCLY_TEAMS_RBAC as O}from"@redocly/config";import{nodeTypes as h,contentType as y}from"@redocly/api-docs";import{normalizeApiVersion as sn}from"../utils/normalize-api-version.js";import{replaceFileExtension as U}from"../utils/replace-file-extension.js";import{isResourcePubliclyAccessible as cn,canDownloadApiDefinition as ln,extractTeamsFromScopeItems as fn}from"../../../utils/rbac.js";import{getLlmsTxtMdPathBySlug as J}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{PUBLIC_API_DEFINITIONS_FOLDER as Q}from"../../../constants/common.js";import{GRAPHQL_SPEC_SLUG as an}from"../../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as pn}from"../../../constants/rbac.js";import{toMarkdown as v}from"../../markdown/search/to-markdown.js";import{createRenderTagFn as un}from"../../markdown/search/create-render-tag-fn.js";import{getLocaleFromRelativePath as dn}from"../../../fs/utils/get-locale-from-relative-path.js";import{getBuildTranslateContext as hn}from"../../../utils/l10n/get-build-translate-context.js";import{llmsTxtLink as N}from"../../search/llmstxt/index.js";import{formatDocumentMetadata as mn}from"../../search/utils.js";import{extractDocumentSearchFacets as $n}from"./search-facets.js";import{createApiDocsSearchIndexer as yn}from"./create-indexer.js";function A(t,o){return o==="openapi"&&"openapi"in t}function H(t,o){return o==="asyncapi"&&"asyncapi"in t}function Qn({items:t,metadata:o,store:s,document:n,specType:r,excludeFromSearch:i,basePath:e,getSearchFacets:l,markdocTags:c}){return async(f,a,u,d)=>{if(i)return;const m={...d.markdocOptions?.tags,...c},{locale:X,translate:Z}=await hn(f.slug,d.getGlobalData?.().l10n),x=un(m,X,Z),C=d.getConfig(),L=dn(f.fsPath),j=yn(e,s?.schemaStore,n,s?.exampleStore),M=g=>{for(const p of g)j.addItem(p),p.items?.length&&M(p.items)};M(t);const nn=j.getResult(),V=new Map;for(const g of nn)V.set(g.url,g);const R=typeof o.title=="string"?o.title:void 0,_=sn(o.version),D=$n(f.metadata||{},R,_,l),S=[],I=[],q=gn(o,n,r),F=bn(r,o,f.fsPath,C),tn=In(t,C,x),en=q+F+`
2
+ `+tn,on=q+F;I.push({title:R||"API Overview",description:typeof o.description=="string"?o.description:void 0,content:en,slug:e,fsPath:f.fsPath,includeInLLMsTxt:!0}),S.push({title:R||"API Overview",content:on,url:e,fsPath:f.fsPath,locale:L,product:f.product?.name,facets:D});const rn=n&&A(n,r)?n.security:void 0,E=g=>{for(const p of g){if(!p.content||!p.link){p.items?.length&&E(p.items);continue}const k=V.get(p.link),G=p.content.contentType,z=p[O],W=z?fn(z):void 0,B=W?.length?W:void 0;if(G===y.ITEM){const $=Pn(p,n,r)??Y(p,k,r,_,rn,x);if($){const b=p.label||"";I.push({title:b,description:void 0,content:$,slug:p.link,fsPath:f.fsPath,includeInLLMsTxt:!1}),S.push({title:b,content:$,url:p.link,fsPath:f.fsPath,locale:L,product:f.product?.name,facets:D,rbacTeams:B})}}else if(G===y.GROUP){const $=On(p,C,r,x);if($){const b=p.label||"";I.push({title:b,description:k?Rn(k.text):void 0,content:$.llmstxt,slug:p.link,fsPath:f.fsPath,includeInLLMsTxt:!1}),S.push({title:b,content:$.aiSearch,url:p.link,fsPath:f.fsPath,locale:L,product:f.product?.name,facets:D,rbacTeams:B})}}p.items?.length&&E(p.items)}};return E(t),{async getLLMsTxts(){return I},async getSearchDocuments(){return S}}}}function gn(t,o,s){const n=typeof t.title=="string"?t.title:"",r=typeof t.description=="string"?t.description:"",i=typeof t.summary=="string"?t.summary:"",e=typeof t.version=="string"?t.version:"";let l=n?`# ${n}
3
3
 
4
- `:"";if(l+=o?`${o}
4
+ `:"";if(l+=r?`${r}
5
5
 
6
6
  `:"",l+=i?`${i}
7
7
 
8
8
  `:"",l+=e?`Version: ${e}
9
- `:"",r){if(A(r,s)){const{info:c}=r;c?.license?.name&&(l+=`License: ${c.license.name}
9
+ `:"",o){if(A(o,s)){const{info:c}=o;c?.license?.name&&(l+=`License: ${c.license.name}
10
10
  `);const f=c["x-metadata"],a=mn(f);a&&(l+=`
11
11
  Metadata:
12
12
  ${a}
13
- `)}else if(H(r,s)){const{info:c}=r;c?.license?.name&&(l+=`License: ${c.license.name}
13
+ `)}else if(H(o,s)){const{info:c}=o;c?.license?.name&&(l+=`License: ${c.license.name}
14
14
  `)}}return l+=`
15
- `,l+=An(r,s),l+=Sn(r,s),l}function bn(t,r,s,n){if(!s)return"";let o,i,e;if(t==="openapi")o=P.posix.join(Q,v(s,".yaml")),i="## Download OpenAPI description",e="OpenAPI definition";else if(t==="asyncapi")o=P.posix.join(Q,v(s,".yaml")),i="## Download AsyncAPI description",e="AsyncAPI definition";else if(t==="graphql"){const f=P.posix.extname(s)||".graphql";o=P.posix.join(an,v(s,f)),i="## Download GraphQL schema",e="GraphQL schema"}else return"";if(!ln(o,n.access?.rbac??{},n.access?.requiresLogin??!1,pn))return"";const c=typeof r.title=="string"&&r.title||e;return`${i}
15
+ `,l+=An(o,s),l+=Sn(o,s),l}function bn(t,o,s,n){if(!s)return"";let r,i,e;if(t==="openapi")r=P.posix.join(Q,U(s,".yaml")),i="## Download OpenAPI description",e="OpenAPI definition";else if(t==="asyncapi")r=P.posix.join(Q,U(s,".yaml")),i="## Download AsyncAPI description",e="AsyncAPI definition";else if(t==="graphql"){const f=P.posix.extname(s)||".graphql";r=P.posix.join(an,U(s,f)),i="## Download GraphQL schema",e="GraphQL schema"}else return"";if(!ln(r,n.access?.rbac??{},n.access?.requiresLogin??!1,pn))return"";const c=typeof o.title=="string"&&o.title||e;return`${i}
16
16
 
17
- - ${w({title:c,description:void 0,slug:o})}`}function An(t,r){if(!t)return"";if(A(t,r)){const{servers:s}=t;if(!s?.length)return"";let n=`## Servers
17
+ - ${N({title:c,description:void 0,slug:r,siteUrl:n.seo?.siteUrl})}`}function An(t,o){if(!t)return"";if(A(t,o)){const{servers:s}=t;if(!s?.length)return"";let n=`## Servers
18
18
 
19
- `;for(const o of s)if(o.description&&(n+=`${o.description}
19
+ `;for(const r of s)if(r.description&&(n+=`${r.description}
20
20
  `),n+=`\`\`\`
21
- ${o.url}
21
+ ${r.url}
22
22
  \`\`\`
23
23
 
24
- `,o.variables){n+=`Variables:
25
- `;for(const[i,e]of Object.entries(o.variables))n+=`- \`${i}\`${e.description?`: ${e.description}`:""}
24
+ `,r.variables){n+=`Variables:
25
+ `;for(const[i,e]of Object.entries(r.variables))n+=`- \`${i}\`${e.description?`: ${e.description}`:""}
26
26
  `,e.default&&(n+=` Default: ${JSON.stringify(e.default)}
27
27
  `),e.enum&&(n+=` Enum: ${e.enum.map(l=>JSON.stringify(l)).join(", ")}
28
28
  `);n+=`
29
- `}return n}if(H(t,r)){const{servers:s}=t;if(!s||!Object.keys(s).length)return"";let n=`## Servers
29
+ `}return n}if(H(t,o)){const{servers:s}=t;if(!s||!Object.keys(s).length)return"";let n=`## Servers
30
30
 
31
- `;for(const[o,i]of Object.entries(s))n+=`### ${o}
31
+ `;for(const[r,i]of Object.entries(s))n+=`### ${r}
32
32
 
33
33
  `,i.description&&(n+=`${i.description}
34
34
  `),i.host&&(n+=`Host: ${i.host}
@@ -36,9 +36,9 @@ ${o.url}
36
36
  `),i.protocolVersion&&(n+=`Protocol Version: ${i.protocolVersion}
37
37
  `),i.pathname&&(n+=`Pathname: ${i.pathname}
38
38
  `),n+=`
39
- `;return n}return""}function Sn(t,r){if(!t||!A(t,r))return"";const s=t.components?.securitySchemes;if(!s)return"";let n=`## Security
39
+ `;return n}return""}function Sn(t,o){if(!t||!A(t,o))return"";const s=t.components?.securitySchemes;if(!s)return"";let n=`## Security
40
40
 
41
- `;for(const[o,i]of Object.entries(s)){if(!i||"$ref"in i)continue;const e=i;n+=`### ${o}
41
+ `;for(const[r,i]of Object.entries(s)){if(!i||"$ref"in i)continue;const e=i;n+=`### ${r}
42
42
 
43
43
  `,e.description&&(n+=`${e.description}
44
44
 
@@ -53,43 +53,43 @@ ${o.url}
53
53
  `),c.scopes)){n+=`Scopes:
54
54
  `;for(const[f,a]of Object.entries(c.scopes))n+=`- \`${f}\`: ${a}
55
55
  `}n+=`
56
- `}return n}function In(t,r,s){let n="";const o=(i,e)=>{for(const l of i)if(l.link){if(l.content?.contentType===g.GROUP)n+=`${e} ${l.label||""}
56
+ `}return n}function In(t,o,s){let n="";const r=(i,e)=>{for(const l of i)if(l.link){if(l.content?.contentType===y.GROUP)n+=`${e} ${l.label||""}
57
57
 
58
- `,l.items?.length&&o(l.items,e+"#");else if(l.content?.contentType===g.ITEM){if(!U(l,r))continue;const c=l,f=c.httpVerb,a=c.httpPath,u=f&&a?`${f.toUpperCase()} ${a}`:l.label||"",d=l.content?T(l.content.children,s):void 0;n+=` - ${w({title:u,description:d?d.slice(0,200):void 0,slug:J(l.link)})}`}}};return o(t,"##"),n}function Y(t,r,s,n,o,i){if(!t.content)return;const e=t,l=t.label||"",c=T(t.content.children,i),f=t.content.meta?.deprecated;let a=`# ${l}${f?" (deprecated)":""}
58
+ `,l.items?.length&&r(l.items,e+"#");else if(l.content?.contentType===y.ITEM){if(!w(l,o))continue;const c=l,f=c.httpVerb,a=c.httpPath,u=f&&a?`${f.toUpperCase()} ${a}`:l.label||"",d=l.content?T(l.content.children,s):void 0;n+=` - ${N({title:u,description:d?d.slice(0,200):void 0,slug:J(l.link),siteUrl:o.seo?.siteUrl})}`}}};return r(t,"##"),n}function Y(t,o,s,n,r,i){if(!t.content)return;const e=t,l=t.label||"",c=T(t.content.children,i),f=t.content.meta?.deprecated;let a=`# ${l}${f?" (deprecated)":""}
59
59
 
60
60
  `;if(c&&(a+=`${c}
61
61
 
62
62
  `),s==="openapi"||s==="asyncapi"){const u=e.httpVerb,d=e.httpPath;u&&d?a+=`Endpoint: ${u.toUpperCase()} ${d}
63
63
  `:u&&(a+=`Method: ${u.toUpperCase()}
64
64
  `),n&&(a+=`Version: ${n}
65
- `);const m=Tn(t.content.children,o);m&&(a+=`Security: ${m}
66
- `)}return r?.parameters?.length&&s!=="graphql"&&(a+=`
67
- `+Cn(r.parameters)+`
68
- `),s==="graphql"&&(a+=xn(t.content.children)),a}function Pn(t,r,s){if(t.httpVerb!=="tool"||!r||!A(r,s))return;const n=t.content?.meta?.name,o=n?r["x-mcp"]?.tools?.find(e=>e.name===n):void 0;if(!o)return;let i=`# ${t.label||o.name}
65
+ `);const m=Tn(t.content.children,r);m&&(a+=`Security: ${m}
66
+ `)}return o?.parameters?.length&&s!=="graphql"&&(a+=`
67
+ `+xn(o.parameters)+`
68
+ `),s==="graphql"&&(a+=Cn(t.content.children)),a}function Pn(t,o,s){if(t.httpVerb!=="tool"||!o||!A(o,s))return;const n=t.content?.meta?.name,r=n?o["x-mcp"]?.tools?.find(e=>e.name===n):void 0;if(!r)return;let i=`# ${t.label||r.name}
69
69
 
70
- `;return typeof o.description=="string"&&o.description&&(i+=`${o.description}
70
+ `;return typeof r.description=="string"&&r.description&&(i+=`${r.description}
71
71
 
72
72
  `),i+=`## Input schema:
73
73
 
74
74
  `,i+=`\`\`\`json
75
- ${JSON.stringify(o.inputSchema,null,2)}
75
+ ${JSON.stringify(r.inputSchema,null,2)}
76
76
  \`\`\`
77
77
 
78
- `,o.outputSchema&&(i+=`## Output schema:
78
+ `,r.outputSchema&&(i+=`## Output schema:
79
79
 
80
80
  `,i+=`\`\`\`json
81
- ${JSON.stringify(o.outputSchema,null,2)}
81
+ ${JSON.stringify(r.outputSchema,null,2)}
82
82
  \`\`\`
83
83
 
84
- `),i}function On(t,r,s,n){if(!t.content)return;const o=t.label||"",i=T(t.content.children,n);let e=`# ${o}
84
+ `),i}function On(t,o,s,n){if(!t.content)return;const r=t.label||"",i=T(t.content.children,n);let e=`# ${r}
85
85
 
86
86
  `;if(i&&(e+=`${i}
87
87
 
88
- `),s==="graphql"){let c="";const f=a=>{for(const u of a??[])if(!(!u.content||!U(u,r)))if(u.content.contentType===g.ITEM){const d=Y(u,void 0,s,void 0,void 0,n);d&&(c+=`${d}
88
+ `),s==="graphql"){let c="";const f=a=>{for(const u of a??[])if(!(!u.content||!w(u,o)))if(u.content.contentType===y.ITEM){const d=Y(u,void 0,s,void 0,void 0,n);d&&(c+=`${d}
89
89
 
90
90
  ---
91
91
 
92
- `)}else u.content.contentType===g.GROUP&&f(u.items)};return f(t.items),{llmstxt:e+c,aiSearch:e}}let l="";if(t.items?.length)for(const c of t.items){if(!c.link||!c.content||c.content.contentType!==g.ITEM||!U(c,r))continue;const f=c,a=f.httpVerb,u=f.httpPath,d=a&&u?`${a.toUpperCase()} ${u}`:c.label||"",m=c.content?T(c.content.children,n):void 0;l+=` - ${w({title:d,description:m?m.slice(0,200):void 0,slug:J(c.link)})}`}return{llmstxt:e+l,aiSearch:e}}function Tn(t,r){const s=[],n=o=>{for(const i of o)if(i.nodeType===h.SECURITY){const e=i;for(const l of e.requirements)for(const c of l.schemes)c[O]||c.name&&!s.includes(c.name)&&s.push(c.name)}else(i.nodeType===h.CONTAINER||i.nodeType===h.OVERVIEW_SECTION_WRAPPER)&&n(i.children)};if(n(t),s.length)return s.join(", ");if(r?.length){const o=r.flatMap(i=>Object.keys(i));if(o.length)return[...new Set(o)].join(", ")}}function Cn(t){const r={};for(const n of t){const o=`${n.place}${n.mediaType?` (${n.mediaType})`:""}`;r[o]||(r[o]=[]),r[o].push(n)}return Object.entries(r).map(([n,o])=>{const i=o.map(e=>{const l=[...e.path||[],e.name],c=Array.isArray(e.description)?e.description.join(" "):e.description;let f=` - \`${l.join(".")}\` (${e.type}${e.required?", required":""})
92
+ `)}else u.content.contentType===y.GROUP&&f(u.items)};return f(t.items),{llmstxt:e+c,aiSearch:e}}let l="";if(t.items?.length)for(const c of t.items){if(!c.link||!c.content||c.content.contentType!==y.ITEM||!w(c,o))continue;const f=c,a=f.httpVerb,u=f.httpPath,d=a&&u?`${a.toUpperCase()} ${u}`:c.label||"",m=c.content?T(c.content.children,n):void 0;l+=` - ${N({title:d,description:m?m.slice(0,200):void 0,slug:J(c.link),siteUrl:o.seo?.siteUrl})}`}return{llmstxt:e+l,aiSearch:e}}function Tn(t,o){const s=[],n=r=>{for(const i of r)if(i.nodeType===h.SECURITY){const e=i;for(const l of e.requirements)for(const c of l.schemes)c[O]||c.name&&!s.includes(c.name)&&s.push(c.name)}else(i.nodeType===h.CONTAINER||i.nodeType===h.OVERVIEW_SECTION_WRAPPER)&&n(i.children)};if(n(t),s.length)return s.join(", ");if(o?.length){const r=o.flatMap(i=>Object.keys(i));if(r.length)return[...new Set(r)].join(", ")}}function xn(t){const o={};for(const n of t){const r=`${n.place}${n.mediaType?` (${n.mediaType})`:""}`;o[r]||(o[r]=[]),o[r].push(n)}return Object.entries(o).map(([n,r])=>{const i=r.map(e=>{const l=[...e.path||[],e.name],c=Array.isArray(e.description)?e.description.join(" "):e.description;let f=` - \`${l.join(".")}\` (${e.type}${e.required?", required":""})
93
93
  `;return c&&(f+=` ${c.trim()}
94
94
  `),e.enum?f+=` Enum: ${e.enum.map(a=>JSON.stringify(a)).join(", ")}
95
95
  `:e.example&&(f+=` Example: ${e.example}
@@ -97,9 +97,9 @@ ${JSON.stringify(o.outputSchema,null,2)}
97
97
 
98
98
  ${i.join(`
99
99
  `)}`}).join(`
100
- `)}function xn(t){let r="";const s=n=>{for(const o of n)if(o.nodeType===h.ITEM){const i=o;i.graphqlSchema&&(r+=Ln(i.graphqlSchema,i.variant))}else(o.nodeType===h.CONTAINER||o.nodeType===h.OVERVIEW_SECTION_WRAPPER)&&s(o.children)};return s(t),r}function Ln(t,r){let n=`
101
- ## ${K(r==="return-type"?"Return type":r==="graphql-args"||r==="arguments"?"Arguments":r==="graphql-fields"?"Fields":r)}:
100
+ `)}function Cn(t){let o="";const s=n=>{for(const r of n)if(r.nodeType===h.ITEM){const i=r;i.graphqlSchema&&(o+=Ln(i.graphqlSchema,i.variant))}else(r.nodeType===h.CONTAINER||r.nodeType===h.OVERVIEW_SECTION_WRAPPER)&&s(r.children)};return s(t),o}function Ln(t,o){let n=`
101
+ ## ${K(o==="return-type"?"Return type":o==="graphql-args"||o==="arguments"?"Arguments":o==="graphql-fields"?"Fields":o)}:
102
102
 
103
- `;const o=i=>{const e=i.description?N(Array.isArray(i.description)?i.description:[i.description]).trim():"";return` - \`${i.name}\` (${i.type})${e?`: ${e}`:""}
104
- `};if(!Array.isArray(t)){const i=t.description?N(Array.isArray(t.description)?t.description:[t.description]).trim():"";n+=` Type: ${t.type}`,i&&(n+=` - ${i}`),n+=`
105
- `;for(const e of t.fields??[])n+=o(e);return n}if(!t.length)return"";for(const i of t)n+=o(i);return n}function T(t,r){const s=[],n=i=>{for(const e of i)if(e.nodeType===h.MARKDOC){const l=e.content,c=Array.isArray(l)?l:[l],f=N(c,{renderTag:r}).trim();f&&s.push(f)}else(e.nodeType===h.CONTAINER||e.nodeType===h.OVERVIEW_SECTION_WRAPPER)&&n(e.children)};return n(t),s.join(" ").trim()||void 0}function Rn(t){return(Array.isArray(t)?t.join(" "):t)||void 0}function K(t){return t.charAt(0).toUpperCase()+t.slice(1)}function U(t,r){return r.access?.requiresLogin?!0:cn({slug:t.link||"",[O]:t[O]},r)}export{Qn as getAiDocumentsStore};
103
+ `;const r=i=>{const e=i.description?v(Array.isArray(i.description)?i.description:[i.description]).trim():"";return` - \`${i.name}\` (${i.type})${e?`: ${e}`:""}
104
+ `};if(!Array.isArray(t)){const i=t.description?v(Array.isArray(t.description)?t.description:[t.description]).trim():"";n+=` Type: ${t.type}`,i&&(n+=` - ${i}`),n+=`
105
+ `;for(const e of t.fields??[])n+=r(e);return n}if(!t.length)return"";for(const i of t)n+=r(i);return n}function T(t,o){const s=[],n=i=>{for(const e of i)if(e.nodeType===h.MARKDOC){const l=e.content,c=Array.isArray(l)?l:[l],f=v(c,{renderTag:o}).trim();f&&s.push(f)}else(e.nodeType===h.CONTAINER||e.nodeType===h.OVERVIEW_SECTION_WRAPPER)&&n(e.children)};return n(t),s.join(" ").trim()||void 0}function Rn(t){return(Array.isArray(t)?t.join(" "):t)||void 0}function K(t){return t.charAt(0).toUpperCase()+t.slice(1)}function w(t,o){return o.access?.requiresLogin?!0:cn({slug:t.link||"",[O]:t[O]},o)}export{Qn as getAiDocumentsStore};
@@ -1,4 +1,5 @@
1
- import{getCallableApis as n,isFetchCapable as o}from"../../../gateway-mcp/callable-apis.js";import{FETCH_TOOL_NAME as i}from"../../constants.js";const c=["```ts","/**"," * Call a documented API. Only the callable APIs' documented hosts are reachable."," * Responses cap at 1 MiB and redirects are not followed."," */","declare function fetch(url: string | URL, init?: {"," method?: string;"," /** `content-type` is set automatically for URLSearchParams/FormData unless you set one. */"," headers?: Record<string, string>;"," /** string \xB7 URLSearchParams (\u2192 application/x-www-form-urlencoded) \xB7 FormData (\u2192 multipart/form-data) */"," body?: string | URLSearchParams | FormData;"," /** Security scheme name (from the operation's `security` or `getSecuritySchemes`) whose credential to send. Omit to let the server choose. */"," securityScheme?: string;","}): Promise<{"," status: number;"," statusText: string;"," ok: boolean;"," headers: { get(name: string): string | null };"," json(): Promise<unknown>;"," text(): Promise<string>;","}>;","```"].join(`
2
- `),l=["Example - list the paid invoices of a billing API:","","```ts","const { items } = await tools.listApis({ filter: 'billing' });","const [api] = items;",`if (!api) return { error: 'no API matches "billing"' };`,"const { endpoints } = await tools.getEndpoints({ name: api.name });","const ep = endpoints.find((e) => e.method === 'GET' && e.path.includes('invoices'));","const info = await tools.getEndpointInfo({ name: api.name, path: ep.path, method: ep.method });","const url = new URL((info.servers?.[0]?.url ?? '') + ep.path);","// Every name below comes from `info.endpoint.parameters` - read them first, never guess them.","url.searchParams.set('filter', 'status:paid');","url.searchParams.set('sort', '-createdTime');","url.searchParams.set('limit', '100');","try {"," const res = await fetch(url, { method: ep.method });"," return res.ok ? await res.json() : { status: res.status, error: await res.text() };","} catch (error) {"," return { error: error instanceof Error ? error.message : String(error), endpointId: info };","}","```"].join(`
3
- `);function m(s){const t=new Map;for(const{name:e,version:r}of s){if(!e)continue;const a=t.get(e)??[];r&&a.push(r),t.set(e,a)}return[...t.entries()].map(([e,r])=>r.length>1?`${e} (${r.map(a=>`v${a}`).join(", ")})`:e).join(", ")}const p={id:i,purpose:"Call the documented APIs over HTTP",isActive:o,annotations:{readOnlyHint:!1,destructiveHint:!0,openWorldHint:!0},renderSection(s){const t=m(n(s));return["## `fetch` \u2014 call the documented APIs","",c,"","Always call `getEndpointInfo` before `fetch` for the exact URL, required parameters, and body shape. Put filtering, sorting, and paging in the query parameters, and keep sandbox JS for what the endpoint cannot express. Never guess.","","When an operation accepts more than one security scheme, pass `securityScheme` with the scheme name the user holds a credential for; without it the server picks one, and a mismatched credential fails upstream.","",`Callable APIs (their documented hosts are reachable via \`fetch\`): ${t}`,"",l].join(`
4
- `)}};export{c as FETCH_DECLARATION,p as fetchCapability};
1
+ import{getCallableApis as n,isFetchCapable as o}from"../../../gateway-mcp/callable-apis.js";import{FETCH_TOOL_NAME as i}from"../../constants.js";const l=["```ts","/**"," * Call a documented API. Only the callable APIs' documented hosts are reachable."," * Responses cap at 1 MiB and redirects are not followed."," */","declare function fetch(url: string | URL, init?: {"," method?: string;"," /** `content-type` is set automatically for URLSearchParams/FormData unless you set one. */"," headers?: Record<string, string>;"," /** string \xB7 URLSearchParams (\u2192 application/x-www-form-urlencoded) \xB7 FormData (\u2192 multipart/form-data) */"," body?: string | URLSearchParams | FormData;"," /** Security scheme name (from the operation's `security` or `getSecuritySchemes`) whose credential to send. Omit to let the server choose. */"," securityScheme?: string;","}): Promise<{"," status: number;"," statusText: string;"," ok: boolean;"," headers: { get(name: string): string | null };"," json(): Promise<unknown>;"," text(): Promise<string>;","}>;","```"].join(`
2
+ `),c=["listApis","getEndpoints","getEndpointInfo"],h=["Example - list the paid invoices of a billing API:","","```ts","const { items } = await tools.listApis({ filter: 'billing' });","const [api] = items;",`if (!api) return { error: 'no API matches "billing"' };`,"const { endpoints } = await tools.getEndpoints({ name: api.name });","const ep = endpoints.find((e) => e.method === 'GET' && e.path.includes('invoices'));","const info = await tools.getEndpointInfo({ name: api.name, path: ep.path, method: ep.method });","// Replace every `{placeholder}` first.","const url = new URL((info.servers?.[0]?.url ?? '') + ep.path);","// Every name below comes from `info.endpoint.parameters` - read them first, never guess them.","url.searchParams.set('filter', 'status:paid');","url.searchParams.set('sort', '-createdTime');","url.searchParams.set('limit', '100');","try {"," const res = await fetch(url, { method: ep.method });"," return res.ok ? await res.json() : { status: res.status, error: await res.text() };","} catch (error) {"," return { error: error instanceof Error ? error.message : String(error), endpointId: info };","}","```"].join(`
3
+ `),p=["Example - call an endpoint you already read:","","```ts","// Call `getEndpointInfo` first for the server URL, the path, and the parameter names.","// Replace every `{placeholder}` first.","const url = new URL('https://api.example.com/invoices');","url.searchParams.set('filter', 'status:paid');","try {"," const res = await fetch(url, { method: 'GET' });"," return res.ok ? await res.json() : { status: res.status, error: await res.text() };","} catch (error) {"," return { error: error instanceof Error ? error.message : String(error) };","}","```"].join(`
4
+ `);function m(r){return c.every(t=>r.includes(t))?h:p}function d(r){const t=new Map;for(const{name:e,version:a}of r){if(!e)continue;const s=t.get(e)??[];a&&s.push(a),t.set(e,s)}return[...t.entries()].map(([e,a])=>a.length>1?`${e} (${a.map(s=>`v${s}`).join(", ")})`:e).join(", ")}const g={id:i,purpose:"Call the documented APIs over HTTP",isActive:o,annotations:{readOnlyHint:!1,destructiveHint:!0,openWorldHint:!0},renderSection(r,t){const e=d(n(r));return["## `fetch` \u2014 call the documented APIs","",l,"","Always call `getEndpointInfo` before `fetch` for the exact URL, required parameters, and body shape. Put filtering, sorting, and paging in the query parameters, and keep sandbox JS for what the endpoint cannot express. Never guess.","","A `servers[].url` or an endpoint path can hold `{placeholders}`. Replace every one before you call `fetch`. Use the server variable `default`. Ask the user when the `default` only repeats the variable name, such as `{organizationId}`.","","When an operation accepts more than one security scheme, pass `securityScheme` with the scheme name the user holds a credential for; without it the server picks one, and a mismatched credential fails upstream.","",`Callable APIs (their documented hosts are reachable via \`fetch\`): ${e}`,"",m(t)].join(`
5
+ `)}};export{l as FETCH_DECLARATION,g as fetchCapability};
@@ -8,7 +8,10 @@ export type SandboxCapability = {
8
8
  isActive(context: McpToolContext): boolean;
9
9
  /** How this capability changes `execute`'s MCP annotations when active. */
10
10
  annotations: Partial<ToolAnnotations>;
11
- /** The self-contained `describe-tools` section for this capability: heading, TS declaration, guidance, and example. */
12
- renderSection(context: McpToolContext): string;
11
+ /**
12
+ * The self-contained `describe-tools` section for this capability: heading, TS declaration,
13
+ * guidance, and an example built only from `describedToolNames`.
14
+ */
15
+ renderSection(context: McpToolContext, describedToolNames: string[]): string;
13
16
  };
14
17
  //# sourceMappingURL=types.d.ts.map
@@ -1,7 +1,7 @@
1
- import{buildToolTypeDeclarations as i}from"../build-tool-type-declarations.js";import{EXECUTE_BASE_ANNOTATIONS as E}from"../tools/execute-schema.js";import{EXECUTE_ARGS_NOTE as p,PLAIN_EXECUTE_EXAMPLE as s,USAGE_NOTES as u}from"../prompts.js";import{FETCH_TOOL_NAME as c}from"../constants.js";import{ALL_CAPABILITIES as A}from"./registry.js";function S(o){return A.filter(n=>n.isActive(o))}function l(o){return o.reduce((n,e)=>({...n,...e.annotations}),{...E})}function N(o,n,e){const t=[];o.length>0&&t.push(`## Sandbox tools
1
+ import{buildToolTypeDeclarations as c,sanitizeToolName as p}from"../build-tool-type-declarations.js";import{EXECUTE_BASE_ANNOTATIONS as u}from"../tools/execute-schema.js";import{buildExecuteExample as m,EXECUTE_ARGS_NOTE as a,USAGE_NOTES as E}from"../prompts.js";import{FETCH_TOOL_NAME as f}from"../constants.js";import{ALL_CAPABILITIES as A}from"./registry.js";function S(n){return A.filter(e=>e.isActive(n))}function _(n){return n.reduce((e,i)=>({...e,...i.annotations}),{...u})}function x(n,e,i){const r=n.map(o=>p(o.name)),t=[];if(n.length>0){const o=c(n),s=o.includes("OpenApi")?`
2
2
 
3
- ${i(o)}
3
+ ${E}`:"";t.push(`## Sandbox tools
4
4
 
5
- ${u}`),t.push(p),o.length>0&&!n.some(r=>r.id===c)&&t.push(s);for(const r of n)t.push(r.renderSection(e));return t.join(`
5
+ ${o}${s}`)}t.push(a),n.length>0&&!e.some(o=>o.id===f)&&t.push(m(r));for(const o of e)t.push(o.renderSection(i,r));return t.join(`
6
6
 
7
- `)}export{l as composeExecuteAnnotations,S as getActiveCapabilities,N as renderDescribeToolsOutput};
7
+ `)}export{_ as composeExecuteAnnotations,S as getActiveCapabilities,x as renderDescribeToolsOutput};
@@ -4,6 +4,6 @@ export declare const EXECUTE_ARGS_NOTE = "Both `execute` arguments are required:
4
4
  export declare function buildExecuteDescription(hasFetch: boolean, toolList?: ToolListEntry[]): string;
5
5
  export declare const DESCRIBE_TOOLS_DESCRIPTION: string;
6
6
  export declare function buildCodeModeInstructions(hasFetch: boolean, toolList?: ToolListEntry[]): string;
7
- export declare const PLAIN_EXECUTE_EXAMPLE: string;
7
+ export declare function buildExecuteExample(toolNames: string[]): string;
8
8
  export declare const USAGE_NOTES: string;
9
9
  //# sourceMappingURL=prompts.d.ts.map
@@ -1,7 +1,8 @@
1
- import{buildToolList as i}from"./build-tool-list.js";const l=2048,c="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).",n="Available tools (exact signatures come from `describe-tools`):";function a(e,t){if(t.length===0)return e;const o=l-e.length-n.length-3,s=i(t,o);return s?[e,"",n,s].join(`
1
+ import{buildToolList as i}from"./build-tool-list.js";const r=2048,d="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).",n="Available tools (exact signatures come from `describe-tools`):";function a(e,t){if(t.length===0)return e;const o=r-e.length-n.length-3,s=i(t,o);return s?[e,"",n,s].join(`
2
2
  `):e}function h(e,t=[]){const o=["Run JavaScript in a sandbox against the documentation tools on the global `tools` object.",e?"The extra globals are `tools`, `fetch`, `URL`, `URLSearchParams`, and `FormData` - there is no `console`, `setTimeout`, `require`, or Node.js API; all other I/O goes through `tools`.":"The only extra global is `tools` - there is no `fetch`, `console`, `setTimeout`, `require`, or Node.js API; all I/O goes through `tools`.","","Workflow - minimize round-trips; one `describe-tools` call plus one `execute` call covers most requests:","1. Analyze the request and decide which sandbox tools it needs.","2. Call `describe-tools` with those names to get their exact TypeScript signatures - inputs, result shapes, and a worked example. NEVER call `execute` with guessed method names, parameter names, enum values, or result field names: read fields off the declared return types, not from assumptions.","3. Batch everything into a SINGLE script: chain tool calls, pass one call's output into the next, process results in plain JavaScript, and `return` only what the request needs."].join(`
3
- `);return a(o,t)}const d=["Get the exact TypeScript signatures of the sandbox tools available to `execute`.","Analyze the user request first, then pass `tools` with only the tool names the request needs (every name is listed in this input schema / description); omit `tools` only when you cannot tell which tools apply.","Always call this before your first `execute` and never guess signatures. Request every tool the task may need in ONE call instead of calling this repeatedly."].join(`
4
- `);function u(e,t=[]){const o=["This server exposes documentation tools (API discovery, endpoint details, security schemes, full-text search) through two tools:","- `describe-tools` returns the exact TypeScript signatures of the sandbox tools.","- `execute` runs JavaScript that calls those tools on the global `tools` object.","Workflow: analyze the request, call `describe-tools` once with only the tool names it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess tool signatures.",...e?["The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `describe-tools` call to get its contract and the list of callable APIs."]:[]].join(`
5
- `);return a(o,t)}const p=["Example - list the write endpoints of an API:","","```ts","const { items } = await tools.listApis({ filter: 'billing' });","const [api] = items;",`if (!api) return { error: 'no API matches "billing"' };`,"const { endpoints } = await tools.getEndpoints({ name: api.name });","const writes = endpoints.filter((e) => e.method !== 'GET');","return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
6
- `),m=["Types named `OpenApi\u2026` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
7
- `);export{d as DESCRIBE_TOOLS_DESCRIPTION,l as DESCRIPTION_CHAR_LIMIT,c as EXECUTE_ARGS_NOTE,p as PLAIN_EXECUTE_EXAMPLE,m as USAGE_NOTES,u as buildCodeModeInstructions,h as buildExecuteDescription};
3
+ `);return a(o,t)}const p=["Get the exact TypeScript signatures of the sandbox tools available to `execute`.","Analyze the user request first, then pass `tools` with only the tool names the request needs (every name is listed in this input schema / description); omit `tools` only when you cannot tell which tools apply.","Always call this before your first `execute` and never guess signatures. Request every tool the task may need in ONE call instead of calling this repeatedly."].join(`
4
+ `);function m(e,t=[]){const o=["This server exposes documentation tools (API discovery, endpoint details, security schemes, full-text search) through two tools:","- `describe-tools` returns the exact TypeScript signatures of the sandbox tools.","- `execute` runs JavaScript that calls those tools on the global `tools` object.","Workflow: analyze the request, call `describe-tools` once with only the tool names it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess tool signatures.",...e?["The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `describe-tools` call to get its contract and the list of callable APIs."]:[]].join(`
5
+ `);return a(o,t)}const l=["listApis","getEndpoints"],c=["Example - list the write endpoints of an API:","","```ts","const { items } = await tools.listApis({ filter: 'billing' });","const [api] = items;",`if (!api) return { error: 'no API matches "billing"' };`,"const { endpoints } = await tools.getEndpoints({ name: api.name });","const writes = endpoints.filter((e) => e.method !== 'GET');","return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
6
+ `);function g(e){if(l.every(o=>e.includes(o)))return c;const[t]=e;return t?[`Example - call \`${t}\` and return what the request needs:`,"","```ts",`const result = await tools.${t}({ /* the input its signature above declares */ });`,"return result;","```"].join(`
7
+ `):""}const b=["Types named `OpenApi\u2026` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
8
+ `);export{p as DESCRIBE_TOOLS_DESCRIPTION,r as DESCRIPTION_CHAR_LIMIT,d as EXECUTE_ARGS_NOTE,b as USAGE_NOTES,m as buildCodeModeInstructions,h as buildExecuteDescription,g as buildExecuteExample};
@@ -3,8 +3,8 @@ import type { SandboxFetch, SandboxTool } from '../types.js';
3
3
  /**
4
4
  * Builds the `setupContext` that shapes the shared sandbox (`~/server/sandbox`) for code
5
5
  * mode: the given tools — and, when provided, host fetch — become host-function rails, each
6
- * capped and bound by the run's budget, and the prelude installs the code-mode guest surface
7
- * over them.
6
+ * capped and bound by the run's budget, and the fetch prelude installs the guest `fetch`
7
+ * surface over its rail.
8
8
  */
9
9
  export declare function createSandboxSetup(tools: Record<string, SandboxTool>, hostFetch?: SandboxFetch): SetupSandboxContext;
10
10
  //# sourceMappingURL=create-sandbox-setup.d.ts.map
@@ -1,11 +1 @@
1
- import{setupHostFunctions as a}from"../../../../sandbox/utils/setup-host-functions.js";import{evalGuestCode as p}from"../../../../sandbox/utils/eval-guest-code.js";import{SANDBOX_FETCH_SETUP as i}from"./polyfills/index.js";import{FETCH_BRIDGE_FUNCTION_NAME as u,FETCH_BRIDGE_GLOBAL_NAME as c,TOOLS_BRIDGE_GLOBAL_NAME as n}from"../constants.js";const m=100,f=50;function T(r,t){return(e,l)=>{const s=[a(e,r,{globalName:n,budget:l,maxCalls:m,messages:{outputTooLarge:o=>`Tool output is too large (${o} bytes); request narrower data instead`,callLimitExceeded:o=>`Exceeded the limit of ${o} tool calls`}})];return t&&s.push(a(e,{[u]:o=>t(o)},{globalName:c,budget:l,maxCalls:f,messages:{outputTooLarge:o=>`Response is too large (${o} bytes); request less data`,callLimitExceeded:o=>`Exceeded the limit of ${o} fetch calls`}})),p(e,E(!!t)),()=>{for(const o of s)o()}}}function E(r){const t=r?i:"",e=`globalThis[${JSON.stringify(n)}]`;return`(() => {${t}
2
- const tools = ${e};
3
- ${e} = new Proxy(tools, {
4
- get(target, prop) {
5
- if (typeof prop !== 'string' || prop in target || prop === 'then' || prop === 'toJSON') {
6
- return target[prop];
7
- }
8
- throw new TypeError('Unknown tool "' + prop + '". Available tools: ' + Object.keys(target).join(', '));
9
- },
10
- });
11
- })();`}export{T as createSandboxSetup};
1
+ import{setupHostFunctions as l}from"../../../../sandbox/utils/setup-host-functions.js";import{evalGuestCode as r}from"../../../../sandbox/utils/eval-guest-code.js";import{CONSOLE_STUB as u,SANDBOX_FETCH_SETUP as _}from"./polyfills/index.js";import{FETCH_BRIDGE_FUNCTION_NAME as i,FETCH_BRIDGE_GLOBAL_NAME as E,TOOLS_BRIDGE_GLOBAL_NAME as L}from"../constants.js";const T=1e3,c=50,p=8*1024*1024;function A(m,t){return(o,s)=>{r(o,`(() => {${u}})();`);const a=[l(o,m,{globalName:L,budget:s,maxCalls:T,maxOutputBytes:p,messages:{outputTooLarge:e=>`Tool output is too large (${e} bytes); request narrower data instead`,callLimitExceeded:e=>`Exceeded the limit of ${e} tool calls`}})];return t&&(a.push(l(o,{[i]:e=>t(e)},{globalName:E,budget:s,maxCalls:c,messages:{outputTooLarge:e=>`Response is too large (${e} bytes); request less data`,callLimitExceeded:e=>`Exceeded the limit of ${e} fetch calls`}})),r(o,`(() => {${_}})();`)),()=>{for(const e of a)e()}}}export{A as createSandboxSetup};
@@ -0,0 +1,2 @@
1
+ export declare const CONSOLE_STUB = "\nglobalThis.console = Object.freeze({\n log() {}, info() {}, warn() {}, error() {}, debug() {}, trace() {}, table() {}, dir() {},\n});\n";
2
+ //# sourceMappingURL=console.d.ts.map
@@ -0,0 +1,5 @@
1
+ const e=`
2
+ globalThis.console = Object.freeze({
3
+ log() {}, info() {}, warn() {}, error() {}, debug() {}, trace() {}, table() {}, dir() {},
4
+ });
5
+ `;export{e as CONSOLE_STUB};
@@ -1,3 +1,4 @@
1
1
  /** The guest prelude installed when the gateway fetch capability is on */
2
2
  export declare const SANDBOX_FETCH_SETUP: string;
3
+ export { CONSOLE_STUB } from './console.js';
3
4
  //# sourceMappingURL=index.d.ts.map
@@ -1,2 +1,2 @@
1
- import{FETCH_SHIM as o}from"./fetch-shim.js";import{FORM_DATA_POLYFILL as L}from"./form-data.js";import{URL_POLYFILL as r}from"./url.js";import{URL_SEARCH_PARAMS_POLYFILL as _}from"./url-search-params.js";const i=[_,r,L,o].join(`
2
- `);export{i as SANDBOX_FETCH_SETUP};
1
+ import{FETCH_SHIM as o}from"./fetch-shim.js";import{FORM_DATA_POLYFILL as L}from"./form-data.js";import{URL_POLYFILL as r}from"./url.js";import{URL_SEARCH_PARAMS_POLYFILL as _}from"./url-search-params.js";const p=[_,r,L,o].join(`
2
+ `);import{CONSOLE_STUB as f}from"./console.js";export{f as CONSOLE_STUB,p as SANDBOX_FETCH_SETUP};
@@ -0,0 +1,5 @@
1
+ type ToolInputValidator = (input: unknown) => string | undefined;
2
+ /** Validates a sandbox tool call against the tool's MCP input schema before the handler runs. */
3
+ export declare function createToolInputValidator(sandboxName: string, schema: Record<string, unknown>): ToolInputValidator;
4
+ export {};
5
+ //# sourceMappingURL=tool-input-validator.d.ts.map
@@ -0,0 +1 @@
1
+ import s from"@redocly/ajv";const c=new s({allErrors:!0}),n=new Map;function f(t,r){const e=d(r);if(!e)return()=>{};const o=Object.keys(r.properties??{});return i=>{if(e(i??{}))return;const a=p(e.errors??[]);return`Invalid input for tools.${t}: ${a.join("; ")}. Accepted properties: ${o.join(", ")}. Call describe-tools for the exact signature.`}}function d(t){const r=JSON.stringify(t);if(n.has(r))return n.get(r);let e;try{e=c.compile(t)}catch{e=void 0}return n.set(r,e),e}function p(t){const r=new Set;for(const e of t)switch(e.keyword){case"additionalProperties":r.add(`unknown property "${e.params.additionalProperty}"`);break;case"required":r.add(`missing required property "${e.params.missingProperty}"`);break;default:r.add(`${u(e.instancePath)} ${e.message}`)}return[...r]}function u(t){return t?`"${t.replace(/^\//,"").replace(/\//g,".")}"`:"input"}export{f as createToolInputValidator};
@@ -0,0 +1,8 @@
1
+ import type { GuestPosition } from '../../../../sandbox/types.js';
2
+ /**
3
+ * Turns a guest error into the message the model reads. A call on a tool the sandbox does not
4
+ * hold names that tool and lists the available ones; every other error keeps its message and
5
+ * gains the line it was thrown on.
6
+ */
7
+ export declare function describeGuestError(code: string, message: string, position: GuestPosition | undefined, availableTools: string[]): string;
8
+ //# sourceMappingURL=unknown-tool-hint.d.ts.map
@@ -0,0 +1,2 @@
1
+ import{TOOLS_BRIDGE_GLOBAL_NAME as c}from"../constants.js";const i="not a function",d=new RegExp(`(?:^|[^\\w$.])${c}\\s*(?:(?:\\?\\.|\\.)\\s*([A-Za-z_$][\\w$]*)|(?:\\?\\.)?\\s*\\[\\s*(['"])([^'"]*)\\2\\s*\\])\\s*(?:\\?\\.)?\\s*$`);function $(o,t,n,e){const u=n&&E(o,n);if(!n||u===void 0)return t;const f=t===i?l(o.slice(0,u),e):void 0;return f===void 0?`${t} (line ${n.line})`:`Unknown tool "${f}". Available tools: ${e.join(", ")}`}function l(o,t){const n=d.exec(o),e=n?.[1]??n?.[3];return e!==void 0&&!t.includes(e)?e:void 0}function E(o,{line:t,column:n}){const e=o.split(`
2
+ `);if(t>e.length)return;const f=e.slice(0,t-1).reduce((r,s)=>r+s.length+1,0)+n-1;return f<=o.length?f:void 0}export{$ as describeGuestError};
@@ -1 +1,3 @@
1
- import{renderDescribeToolsOutput as S}from"../capabilities/index.js";import{McpServerType as y}from"../../constants.js";import{reportMcpToolCalled as v,reportMcpToolError as O}from"../../workers/mcp-tool-telemetry.js";import{DESCRIBE_TOOLS_TOOL_NAME as p}from"../constants.js";import{DESCRIBE_TOOLS_DESCRIPTION as k}from"../prompts.js";import{sanitizeToolName as s}from"../build-tool-type-declarations.js";import{UnknownToolError as w}from"./tool-errors.js";function x(i,l){const r=[...new Set([...i.map(n=>s(n.name)),...l.map(n=>s(n.id))])];return{name:p,title:"Describe tools",description:k,schema:{type:"object",required:[],additionalProperties:!1,properties:{tools:{type:"array",description:`Tool names to describe: ${r.join(", ")}. Omit to describe everything.`,items:r.length>0?{type:"string",enum:r}:{type:"string"},nullable:!0}}}}}function P(i,l,r,n){const c=new Map(i.map(t=>[s(t.name),t])),m=new Map(r.map(t=>[s(t.id),t]));return async t=>{const d=performance.now(),f=n.mcpMode??"code";try{const o=[...new Set((t.tools??[]).map(s))],a=o.length===0,u=o.filter(e=>!c.has(e)&&!m.has(e));if(u.length>0){const e=[...c.keys(),...m.keys()];throw new w(`Unknown tool(s): ${u.join(", ")}. Valid tools: ${e.join(", ")}.`)}const g=a?r:r.filter(e=>o.includes(s(e.id))),T=a?i:o.filter(e=>c.has(e)).map(e=>c.get(e)),M=await Promise.all(T.map(e=>l(e.name))),E=T.filter((e,b)=>M[b]),h=S(E,g,n);return v({tool:p,mode:f,serverType:y.Docs,durationMs:Math.round(performance.now()-d),outputLength:h.length}),{content:[{type:"text",text:h}]}}catch(o){const a=o instanceof w;throw O({tool:p,mode:f,serverType:y.Docs,durationMs:Math.round(performance.now()-d),message:o instanceof Error?o.message:String(o),stack:!a&&o instanceof Error&&o.stack||"",errorClass:a?"tool_error":"server_error"}),o}}}export{P as describeTools,x as describeToolsSchema};
1
+ import{renderDescribeToolsOutput as O}from"../capabilities/index.js";import{McpServerType as M}from"../../constants.js";import{reportMcpToolCalled as _,reportMcpToolError as k}from"../../workers/mcp-tool-telemetry.js";import{DESCRIBE_TOOLS_TOOL_NAME as d}from"../constants.js";import{DESCRIBE_TOOLS_DESCRIPTION as D}from"../prompts.js";import{sanitizeToolName as n}from"../build-tool-type-declarations.js";import{UnknownToolError as v}from"./tool-errors.js";function x(i,c){const t=[...new Set([...i.map(s=>n(s.name)),...c.map(s=>n(s.id))])];return{name:d,title:"Describe tools",description:D,schema:{type:"object",required:[],additionalProperties:!1,properties:{tools:{type:"array",description:`Tool names to describe: ${t.join(", ")}. Omit to describe everything.`,items:t.length>0?{type:"string",enum:t}:{type:"string"},nullable:!0}}}}}function P(i,c,t,s){const l=new Map(i.map(r=>[n(r.name),r])),f=new Map(t.map(r=>[n(r.id),r]));return async r=>{const u=performance.now(),h=s.mcpMode??"code";try{const o=[...new Set((r.tools??[]).map(n))],a=o.length===0,T=o.filter(e=>!l.has(e)&&!f.has(e));if(T.length>0){const e=[...l.keys(),...f.keys()];throw new v(`Unknown tool(s): ${T.join(", ")}. Valid tools: ${e.join(", ")}.`)}const E=a?t:t.filter(e=>o.includes(n(e.id))),p=a?i:o.filter(e=>l.has(e)).map(e=>l.get(e)),y=await Promise.all(p.map(e=>c(e.name))),S=p.filter((e,m)=>y[m]),w=p.filter((e,m)=>!y[m]),g=[O(S,E,s)];w.length>0&&g.push(`Not available for this request: ${w.map(e=>n(e.name)).join(", ")}`);const b=g.join(`
2
+
3
+ `);return _({tool:d,mode:h,serverType:M.Docs,durationMs:Math.round(performance.now()-u),outputLength:b.length}),{content:[{type:"text",text:b}]}}catch(o){const a=o instanceof v;throw k({tool:d,mode:h,serverType:M.Docs,durationMs:Math.round(performance.now()-u),message:o instanceof Error?o.message:String(o),stack:!a&&o instanceof Error&&o.stack||"",errorClass:a?"tool_error":"server_error"}),o}}}export{P as describeTools,x as describeToolsSchema};
@@ -1 +1 @@
1
- import{runInSandbox as p}from"../../../../sandbox/sandbox.js";import{isMcpToolAvailable as h}from"../../workers/execute-mcp-tool.js";import{importMcpToolHandlers as E}from"../../workers/import-mcp-tool-handlers.js";import{isFetchCapable as b}from"../../gateway-mcp/callable-apis.js";import{buildExecuteHostFetch as w}from"../../gateway-mcp/fetch-capability.js";import{withAuthRequiredMeta as C}from"../../gateway-mcp/upstream-auth.js";import{CODE_MODE_TOOL_NAMES as O,EXECUTE_TOOL_NAME as y}from"../constants.js";import{sanitizeToolName as T}from"../build-tool-type-declarations.js";import{invokeTool as M}from"../invoke-tool.js";import{createSandboxSetup as A}from"../sandbox/create-sandbox-setup.js";import{auditCode as F}from"../code-audit.js";import{reportCodeExecuted as S}from"../code-execution-telemetry.js";import{logCodeExecutionAudit as _}from"../code-execution-audit.js";const x=async(t,o,d)=>{const r=new Set,a=await N(o,d,r),n=[],e=b(o)?await w(o,l=>n.push(l)):void 0;let c=0;const u=e?l=>(c+=1,e(l)):void 0,i=F(t.code);_({audit:i,code:t.code,description:t.description,sessionHandle:t.sessionHandle,toolNames:Object.keys(a),fetchBudget:o.gatewayFetchBudgetPerExec,fetchCapable:e!==void 0});const m=Date.now(),{result:f,error:s}=await p(t.code,{setupContext:A(a,u)});return S({audit:i,fetchCount:c,outcome:s===void 0?"ok":"error",durationMs:Date.now()-m,client:o.client,clientVersion:o.clientVersion}),C({content:[{type:"text",text:JSON.stringify({result:f,error:s})}],isError:s!==void 0,...s!==void 0&&r.has(s)?{errorClass:"tool_error"}:{}},n)};async function N(t,o,d){const r=Object.keys(await E()).filter(e=>!O.has(e)),a=await Promise.all(r.map(e=>h({toolName:e,context:t}).catch(()=>!1))),n={};return r.forEach((e,c)=>{a[c]&&(n[T(e)]=u=>M(e,u,t,o).catch(i=>{throw i instanceof Error&&d.add(i.message),i}))}),n}var J={[y]:x};export{J as default};
1
+ import{runInSandbox as b}from"../../../../sandbox/sandbox.js";import{returnLastExpression as w}from"../../../../sandbox/utils/return-last-expression.js";import{isMcpToolAvailable as C}from"../../workers/execute-mcp-tool.js";import{importMcpToolHandlers as O}from"../../workers/import-mcp-tool-handlers.js";import{isFetchCapable as T}from"../../gateway-mcp/callable-apis.js";import{buildExecuteHostFetch as y}from"../../gateway-mcp/fetch-capability.js";import{withAuthRequiredMeta as x}from"../../gateway-mcp/upstream-auth.js";import{CODE_MODE_TOOL_NAMES as M,EXECUTE_TOOL_NAME as S}from"../constants.js";import{sanitizeToolName as v}from"../build-tool-type-declarations.js";import{invokeTool as A}from"../invoke-tool.js";import{createSandboxSetup as _}from"../sandbox/create-sandbox-setup.js";import{createToolInputValidator as k}from"../sandbox/tool-input-validator.js";import{describeGuestError as F}from"../sandbox/unknown-tool-hint.js";import{auditCode as N}from"../code-audit.js";import{reportCodeExecuted as g}from"../code-execution-telemetry.js";import{logCodeExecutionAudit as j}from"../code-execution-audit.js";const D=async(t,r,m)=>{const i=new Set,n=await H(r,m,i),s=[],e=T(r)?await y(r,p=>s.push(p)):void 0;let u=0;const f=e?p=>(u+=1,e(p)):void 0,a=N(t.code);j({audit:a,code:t.code,description:t.description,sessionHandle:t.sessionHandle,toolNames:Object.keys(n),fetchBudget:r.gatewayFetchBudgetPerExec,fetchCapable:e!==void 0});const l=Date.now(),d=w(t.code),{result:c,error:o,errorPosition:h}=await b(d,{setupContext:_(n,f)});g({audit:a,fetchCount:u,outcome:o===void 0?"ok":"error",durationMs:Date.now()-l,client:r.client,clientVersion:r.clientVersion});const E=o===void 0?void 0:F(d,o,h,Object.keys(n));return x({content:[{type:"text",text:JSON.stringify({result:c,error:E})}],isError:o!==void 0,...o!==void 0&&i.has(o)?{errorClass:"tool_error"}:{}},s)};async function H(t,r,m){const i=Object.keys(await O()).filter(e=>!M.has(e)),n=await Promise.all(i.map(e=>C({toolName:e,context:t}).catch(()=>!1))),s={};return i.forEach((e,u)=>{if(!n[u])return;const f=v(e),a=t.sandboxToolSchemas?.[e],l=a?k(f,a):void 0;s[f]=d=>{const c=l?.(d);return c?(m.add(c),Promise.reject(new Error(c))):A(e,d,t,r).catch(o=>{throw o instanceof Error&&m.add(o.message),o})}}),s}var Z={[S]:D};export{Z as default};
@@ -1,2 +1,2 @@
1
- import{MANAGE_API_CREDENTIALS_TOOL_NAME as v}from"../../constants.js";import{buildUpstreamCredentialFallback as y,buildUpstreamCredentialInputRequired as b,schemeLabelOf as P}from"../../gateway-mcp/elicitation.js";import{getCallableApis as m,isFetchCapable as S}from"../../gateway-mcp/callable-apis.js";import{secretStore as I}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as w,resolveSecretSubject as k}from"../../gateway-mcp/subject.js";import{resolveUpstreamApiAuth as j}from"../../gateway-mcp/upstream-auth-scheme.js";function H(e){return!!e.elicitationEnabled&&S(e)}function U(e){const t=m(e).map(n=>n.relativePath);return{name:v,title:"Manage API credentials",description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","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,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for.${t.length>0?` One of: ${t.join(", ")}.`:""}`,minLength:1,...t.length>0?{enum:t}:{}},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:{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 _(e,c){return async t=>{const n=k(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(n.kind==="invalid")return l(n.message);if(n.kind==="anonymous")return l(w);const{subject:u}=n,h=typeof t.api=="string"?t.api:"",s=m(e).find(o=>o.relativePath===h||o.name===h);if(!s){const o=m(e).map(g=>g.relativePath).join(", ");return l(`Unknown api "${h}". Credentials can only be managed for the APIs this server can call: ${o||"none"}.`)}const r=await j(e,s.relativePath),a=typeof t.scheme=="string"?t.scheme:void 0,A=Object.keys(r.schemes);if(a&&!r.schemes[a])return l(`Unknown scheme "${a}" for api "${s.relativePath}". The security schemes this server can store credentials for are: ${A.join(", ")}.`);const i=a??r.defaultScheme,p=P(r.schemes,i),d=await c.getKv(),f={subject:u,baseUrl:e.baseUrl??"",target:{api:s.relativePath,name:s.name,scheme:i,...p?{schemeLabel:p}:{}},auth:r.schemes[i],apiAuth:r,kv:d,hasExistingSecret:await I.hasSecret(d,u,s.relativePath,i),reason:{kind:"requested"}};return c.getClientCapabilities()?.elicitation?.url?await b(f):{content:[{type:"text",text:await y(f)}],isError:!1}}}function l(e){return{content:[{type:"text",text:e}],isError:!0}}export{H as isManageApiCredentialsToolAvailable,_ as manageApiCredentials,U as manageApiCredentialsSchema};
1
+ import{MANAGE_API_CREDENTIALS_TOOL_NAME as y}from"../../constants.js";import{buildUpstreamCredentialFallback as v,buildUpstreamCredentialInputRequired as b,schemeLabelOf as P}from"../../gateway-mcp/elicitation.js";import{getCallableApis as u,isFetchCapable as I}from"../../gateway-mcp/callable-apis.js";import{secretStore as S}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as w,resolveSecretSubject as k}from"../../gateway-mcp/subject.js";import{resolveUpstreamApiAuth as j}from"../../gateway-mcp/upstream-auth-scheme.js";import{apiTitleKey as C,countApiTitles as E}from"../../docs-mcp/utils/api-titles.js";function $(e){return!!e.elicitationEnabled&&I(e)}function M(e){const n=u(e),t=n.map(i=>i.relativePath),s=[...t,...T(n)];return{name:y,title:"Manage API credentials",description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","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,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for: its \`filePath\` or the \`name\` from \`listApis\`.${t.length>0?` The file paths are: ${t.join(", ")}.`:""}`,minLength:1,...s.length>0?{enum:s}:{}},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:{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 T(e){const n=E(e);return e.map(t=>t.name).filter(t=>n.get(C(t))===1)}function R(e,n){return async t=>{const s=k(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(s.kind==="invalid")return h(s.message);if(s.kind==="anonymous")return h(w);const{subject:i}=s,m=typeof t.api=="string"?t.api:"",r=u(e).find(c=>c.relativePath===m||c.name===m);if(!r){const c=u(e).map(g=>g.relativePath).join(", ");return h(`Unknown api "${m}". Credentials can only be managed for the APIs this server can call: ${c||"none"}.`)}const a=await j(e,r.relativePath),o=typeof t.scheme=="string"?t.scheme:void 0,A=Object.keys(a.schemes);if(o&&!a.schemes[o])return h(`Unknown scheme "${o}" for api "${r.relativePath}". The security schemes this server can store credentials for are: ${A.join(", ")}.`);const l=o??a.defaultScheme,p=P(a.schemes,l),d=await n.getKv(),f={subject:i,baseUrl:e.baseUrl??"",target:{api:r.relativePath,name:r.name,scheme:l,...p?{schemeLabel:p}:{}},auth:a.schemes[l],apiAuth:a,kv:d,hasExistingSecret:await S.hasSecret(d,i,r.relativePath,l),reason:{kind:"requested"}};return n.getClientCapabilities()?.elicitation?.url?await b(f):{content:[{type:"text",text:await v(f)}],isError:!1}}}function h(e){return{content:[{type:"text",text:e}],isError:!0}}export{$ as isManageApiCredentialsToolAvailable,R as manageApiCredentials,M as manageApiCredentialsSchema};