@redocly/framework 1.0.0-next.3 → 1.0.0-next.4
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.
- package/dist/bundler/build/output-metadata.js +1 -1
- package/dist/bundler/build/run.js +1 -1
- package/dist/bundler/build/vite-config.js +2 -2
- package/dist/bundler/dev/materialization-sweeper.js +1 -1
- package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
- package/dist/bundler/dev/routes/source-sync-route.js +1 -1
- package/dist/bundler/dev/run.js +1 -1
- package/dist/bundler/dev/runtime-app.js +1 -1
- package/dist/bundler/dev/vite-chunk-url.js +1 -1
- package/dist/bundler/user-markdoc-schema.js +1 -1
- package/dist/bundler/vite-config.base.js +3 -3
- package/dist/cli/commands/build.js +1 -1
- package/dist/cli/commands/dev.js +1 -1
- package/dist/cli/commands/ingest.js +1 -1
- package/dist/cli/commands/translate.js +2 -2
- package/dist/cli/dev-console/index.js +1 -1
- package/dist/cli/log-output/index.js +1 -1
- package/dist/cli/validate-react-pages.js +1 -1
- package/dist/client/RuntimeLink.js +1 -1
- package/dist/client/ai-search/use-ai-search.js +1 -1
- package/dist/client/analytics-page-view.js +1 -1
- package/dist/client/app.js +3 -3
- package/dist/client/client-entry.js +1 -1
- package/dist/client/contexts.js +1 -1
- package/dist/client/dev-problems/ProblemsBar.js +1 -1
- package/dist/client/feedback.js +1 -1
- package/dist/client/l10n/use-l10n-config.js +1 -1
- package/dist/client/products.js +1 -1
- package/dist/client/review/ReviewBar.js +50 -50
- package/dist/client/review/use-review.js +1 -1
- package/dist/client/sidebar/SidebarDataProvider.js +1 -1
- package/dist/client/sidebar/drilldown.js +1 -1
- package/dist/client/ssr.js +1 -1
- package/dist/client/telemetry/config.js +1 -1
- package/dist/client/use-entity-revisions.js +1 -1
- package/dist/client/use-page-versions.js +1 -1
- package/dist/client/use-search.js +1 -1
- package/dist/client/webmcp/tools/shared.js +1 -1
- package/dist/client/webmcp/tools/site-tools.js +1 -1
- package/dist/client/webmcp/use-webmcp-tools.js +1 -1
- package/dist/content-layer/config.js +1 -1
- package/dist/content-layer/database/invalidation.js +26 -26
- package/dist/content-layer/ingest/finalize-phase.js +1 -1
- package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
- package/dist/content-layer/ingest/run.js +1 -1
- package/dist/content-layer/ingest/search-sync.js +1 -1
- package/dist/content-layer/ingest/sync.js +1 -1
- package/dist/content-layer/link-checker/load-view.js +1 -1
- package/dist/content-layer/link-checker/validate.js +1 -1
- package/dist/content-layer/loaders/context.js +1 -1
- package/dist/content-layer/markdown/client/markdown-text.js +1 -1
- package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
- package/dist/content-layer/markdown/constants/markdown-text-tag-set.js +1 -1
- package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
- package/dist/content-layer/markdown/nodes/heading.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
- package/dist/content-layer/markdown/resolve/references.js +1 -1
- package/dist/content-layer/markdown/search/to-markdown.js +1 -1
- package/dist/content-layer/markdown/search/to-sections.js +1 -1
- package/dist/content-layer/markdown/server/render.js +1 -1
- package/dist/content-layer/markdown/tags/variant.js +1 -1
- package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
- package/dist/content-layer/plugins/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/rebase-item-links.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/template.js +2 -2
- package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.js +13 -13
- package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/banner.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/index.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/constants.d.ts +0 -6
- package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/capabilities.js +3 -3
- package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/discover.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
- package/dist/content-layer/plugins/internal/mcp/server/codemode/sandbox.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/tool-list.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/api-call-operations.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +6 -5
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/allowed-hosts.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-bridge.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-errors.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/ssrf-guard.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
- package/dist/content-layer/plugins/internal/mcp/server/gateway/subject.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
- package/dist/content-layer/plugins/internal/mcp/server/gateway/upstream-auth-scheme.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-document.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/graphql.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-catalog.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-document.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +3 -3
- package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/submit-feedback.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/whoami.js +1 -1
- package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
- package/dist/content-layer/plugins/internal/skills/index.js +1 -1
- package/dist/content-layer/plugins/project/load.js +2 -2
- package/dist/content-layer/plugins/utils/link-access.js +1 -1
- package/dist/content-layer/plugins/utils/route-index.js +1 -1
- package/dist/content-layer/versions/redirect.js +1 -1
- package/dist/content-layer/versions/resolve.js +1 -1
- package/dist/server/__tests__/rbac-fixture.js +1 -1
- package/dist/server/app.js +3 -3
- package/dist/server/ask-ai/route.js +1 -1
- package/dist/server/auth/middleware.js +1 -1
- package/dist/server/auth/request.js +1 -1
- package/dist/server/auth/routes.js +1 -1
- package/dist/server/constants/system-routes.js +1 -1
- package/dist/server/content.js +13 -13
- package/dist/server/cors-proxy/handler.js +1 -1
- package/dist/server/feedback/route.js +1 -1
- package/dist/server/lambda-entry.js +1 -1
- package/dist/server/llms-txt.js +1 -1
- package/dist/server/manifest-assets.js +4 -4
- package/dist/server/node-entry.js +1 -1
- package/dist/server/plugin-context.js +1 -1
- package/dist/server/public-url.js +1 -0
- package/dist/server/rbac/l10n-rules.js +1 -1
- package/dist/server/rbac/team-templates.js +1 -1
- package/dist/server/search/cache.js +1 -0
- package/dist/server/search/route.js +1 -1
- package/dist/server/seo-tags.js +2 -2
- package/dist/server/static-files/serve.js +1 -1
- package/dist/shared/constants/l10n/langs/ar.js +1 -1
- package/dist/shared/constants/l10n/langs/de.js +1 -1
- package/dist/shared/constants/l10n/langs/en.js +1 -1
- package/dist/shared/constants/l10n/langs/es.js +1 -1
- package/dist/shared/constants/l10n/langs/fr.js +1 -1
- package/dist/shared/constants/l10n/langs/hi.js +1 -1
- package/dist/shared/constants/l10n/langs/it.js +1 -1
- package/dist/shared/constants/l10n/langs/ja.js +1 -1
- package/dist/shared/constants/l10n/langs/ko.js +1 -1
- package/dist/shared/constants/l10n/langs/pl.js +1 -1
- package/dist/shared/constants/l10n/langs/pt-br.js +1 -1
- package/dist/shared/constants/l10n/langs/pt.js +1 -1
- package/dist/shared/constants/l10n/langs/ru.js +1 -1
- package/dist/shared/constants/l10n/langs/uk.js +1 -1
- package/dist/shared/constants/l10n/langs/zh.js +1 -1
- package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
- package/dist/shared/utils/routes/markdown-copy-url.js +1 -0
- package/package.json +6 -4
- package/dist/content-layer/plugins/internal/mcp/server/codemode/execution-budget.js +0 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/read-result.js +0 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/return-last-expression.js +0 -6
- package/dist/content-layer/plugins/internal/mcp/server/codemode/returns-from-top-level.js +0 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/tool-declarations.js +0 -4
- package/dist/content-layer/plugins/internal/mcp/server/codemode/unknown-tool-hint.js +0 -3
- package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-constants.js +0 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages-constants.js +0 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +0 -1
- package/dist/shared/utils/routes/markdown-path.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as ee}from"../api-call-operations.js";import{GatewayFetchBlockedError as l,GatewayFetchSystemError as u,GatewayFetchUserError as d}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as f}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as p}from"undici";const m=`x-forwarded-for`,re=/%2f|%5c/i,h=/* @__PURE__ */ new Set([401,403,407]),g=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let _;function v(e){if(!_){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),_=new p({connect:{lookup:t({allowLoopback:n})}})}return _}function y({apis:e,onAuthRequired:t,sent:f,runEnded:p,logger:m,telemetry:g,fetchImpl:_=fetch,dispatcher:y=v(m),timeoutMs:b=3e4,deadline:T=1/0,maxResponseBytes:E=1048576,maxFetchesPerExec:D,beforeSend:ge,caller:O,allowedHttpMethods:k}){let A=e.flatMap(e=>e.matchers),_e=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),j=e.flatMap(e=>Object.values(e.secrets??{})),M=j.flatMap(a),ve=j.map(e=>e.header),N=e.flatMap(e=>e.credentialQueryParams??[]),P=0,F=!1;return async a=>{let v=c(a.method??`GET`),j=Date.now(),I,L,R,z={},B,V,H,U;try{if(D!==void 0){let e=Math.max(0,D);if(P+=1,P>e)throw new d(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(k&&!k.includes(v))throw new l(`${v} is not allowed: this project permits only ${k.join(`, `)} API calls`,ae(a.url));let o=ie(a.url,A,_e);if(I=o.hostname,L=te(o.pathname),re.test(o.pathname))throw new l(`${v} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>e.test(o.hostname))),u=c.flatMap(e=>e.operations?ee(e.operations,o.pathname,v).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),x=Math.min(...u.map(e=>e.variables)),C=u.filter(e=>e.variables===x);if(c.length>0&&(u.length===0||C.some(e=>!e.visible)))throw new l(`${v} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=C.find(e=>!e.callable);if(w)throw new l(`${v} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let W=new Set(C.map(e=>e.api)).size===1?C[0].api:void 0;R=W?.slug;let G=de(a.securityScheme,W),K=G?[G]:W?le(W,o.pathname,v):void 0,q=W&&K?ue(W,K):void 0,J=q?W?.secrets?.[q]:void 0;z=me({callerHeaders:a.headers,secret:J,clientIp:O?.clientIp});let Y=fe(a.headers,o,c,J);if(Y&&(J||F))throw new d(pe(Y,!!J));if(T-Date.now()<=0)throw new d(`The execute time limit ended before this request was sent`);await ge?.(),F||=!!J,B=J?q:void 0;let X=new AbortController,ye=T-Date.now();if(U=ye<b?setTimeout(()=>X.abort(new d(`The request did not finish before the execute time limit`)),ye):setTimeout(()=>X.abort(),b),p?.aborted)throw new d(`The execute call had already answered, so this request was not sent`);H={method:v,url:i(o.origin+o.pathname,M)},f?.push(H);let Z=await _(o,{method:v,headers:z,body:a.body,redirect:`manual`,signal:X.signal,dispatcher:y});V=Z.status,H.status=Z.status;let Q=``;try{Q=await ce(Z,E)}finally{if(h.has(Z.status)&&W&&t){let e={api:W.slug,name:W.name,status:Z.status};q&&(e.scheme=q),K?.length&&(e.schemes=[...K]),B&&(e.sentScheme=B);let n=ne(Q,Z.headers.get(`content-type`),M);n&&(e.detail=n),t(e)}}let $=r(he(Z.headers),M);if(oe(Z.status)){$=n($,ve);let{location:e}=$;e&&!se(e,o,A)&&delete $.location}let be=S(Z.status);return g?.gatewayFetchPerformed({host:o.hostname,method:v,outcome:be,durationMs:Date.now()-j,path:L,api:R,status:Z.status,bytes:Buffer.byteLength(Q,`utf8`),injectedScheme:B}),s(m,{rawUrl:o.href,method:v,host:o.hostname,outcome:be,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:L,api:R,status:Z.status,injectedScheme:B,requestHeaders:z,requestBody:a.body,responseHeaders:$,responseBody:Q,caller:O}),{status:Z.status,statusText:i(Z.statusText,M),ok:Z.ok,headers:$,bodyText:i(Q,M)}}catch(e){H&&f&&x(e)&&f.splice(f.indexOf(H),1);let{outcome:t,userSafe:n}=C(e,V),r=I??(n instanceof l?n.host:void 0)??ae(a.url)??`invalid-url`;throw g?.gatewayFetchPerformed({host:r,method:v,outcome:t,durationMs:Date.now()-j,path:L,api:R,status:V,injectedScheme:B}),s(m,{rawUrl:a.url,method:v,host:r,outcome:t,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:L,api:R,status:V,injectedScheme:B,requestHeaders:z,requestBody:a.body,caller:O}),n||(m?.error(`Gateway MCP fetch failed [${v} ${r}]: ${i(w(e),M)} headers=${o(z)}`),new u(`Upstream fetch failed due to an internal error`))}finally{U!==void 0&&clearTimeout(U)}}}function b(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof d||n instanceof e)return n;n=n.cause}}function x(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function S(e){return h.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function C(t,n){let r=b(t),i=n===void 0?void 0:S(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof l||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function ie(e,t,n){try{return f(e,t)}catch(e){throw e instanceof l&&n?new l(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function ae(e){try{return new URL(e).hostname||void 0}catch{return}}function oe(e){return e>=300&&e<400}function se(e,t,n){try{return!!f(new URL(e,t).href,n)}catch{return!1}}function w(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function ce(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw T(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw T(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function T(e,t){return new d(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function le(e,t,n){let r=e.routes?.find(e=>e.method===n&&e.pattern.test(t));return r?r.schemes:E(e)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new d(`securityScheme must be a security scheme name (a string)`);if(!t)throw new d(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new d(`Unknown securityScheme "${e}" for ${t.name}; valid values: ${n.join(`, `)}`);return e}function E(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function fe(e,t,n,r){let i=D([...g,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=D(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function D(e){return new Set(e.map(e=>e.toLowerCase()))}function pe({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function me({callerHeaders:e,secret:t,clientIp:n}){let r={};for(let[t,n]of Object.entries(e??{})){let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==m&&(r[t]=n)}return n&&(r[m]=n),t&&(r[t.header]=t.value),r}function he(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{y as buildFetchBridge,v as getDefaultAgent,ce as readCappedBody};
|
|
1
|
+
import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as l}from"../api-call-operations.js";import{matchesOrigin as ee}from"./allowed-hosts.js";import{GatewayFetchBlockedError as u,GatewayFetchHostNotAllowedError as d,GatewayFetchSystemError as f,GatewayFetchUserError as p}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as m}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as h}from"undici";const g=`x-forwarded-for`,re=/%2f|%5c/i,_=/* @__PURE__ */ new Set([401,403,407]),ie=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let v;function y(e){if(!v){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),v=new h({connect:{lookup:t({allowLoopback:n})}})}return v}function b({apis:e,onAuthRequired:t,sent:d,runEnded:m,logger:h,telemetry:g,fetchImpl:ie=fetch,dispatcher:v=y(h),timeoutMs:b=3e4,deadline:S=1/0,maxResponseBytes:D=1048576,maxFetchesPerExec:O,beforeSend:_e,caller:k,allowedHttpMethods:A}){let j=e.flatMap(e=>e.matchers),ve=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),M=e.flatMap(e=>Object.values(e.secrets??{})),N=M.flatMap(a),ye=M.map(e=>e.header),P=e.flatMap(e=>e.credentialQueryParams??[]),F=0,I=!1;return async a=>{let y=c(a.method??`GET`),M=Date.now(),L,R,z,B={},V,H,U,W,G=!1;try{if(O!==void 0){let e=Math.max(0,O);if(F+=1,F>e)throw new p(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(A&&!A.includes(y))throw new u(`${y} is not allowed: this project permits only ${A.join(`, `)} API calls`,T(a.url));let o=oe(a.url,j,ve);if(L=o.hostname,R=te(o.pathname),re.test(o.pathname))throw new u(`${y} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>ee(e,o))),f=c.flatMap(e=>e.operations?l(e.operations,o.pathname,y).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),x=Math.min(...f.map(e=>e.variables)),C=f.filter(e=>e.variables===x);if(c.length>0&&(f.length===0||C.some(e=>!e.visible)))throw new u(`${y} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=C.find(e=>!e.callable);if(w)throw new u(`${y} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let E=new Set(C.map(e=>e.api)).size===1?C[0].api:void 0;z=E?.slug;let K=E?.routes?.find(e=>e.method===y&&e.pattern.test(o.pathname));if(K?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${y} ${o.pathname} accepts only ${K.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Call it without securityScheme, and do not replace the stored credentials.`);let be=de(a.securityScheme,E),q=be?[be]:E?K?.schemes??fe(E):void 0,J=E&&q?ue(E,q):void 0,Y=J?E?.secrets?.[J]:void 0;if((y===`GET`||y===`HEAD`)&&a.body!==void 0)throw new p(`A ${y} request cannot have a body; remove \`body\``);B=he({callerHeaders:a.headers,secret:Y,clientIp:k?.clientIp});let xe=pe(a.headers,o,c,Y);if(xe&&(Y||I))throw new p(me(xe,!!Y));if(S-Date.now()<=0)throw new p(`The execute time limit ended before this request was sent`);await _e?.(),I||=!!Y,V=Y?J:void 0;let X=new AbortController,Se=S-Date.now();if(W=Se<b?setTimeout(()=>X.abort(new p(`The request did not finish before the execute time limit`)),Se):setTimeout(()=>{G=!0,X.abort()},b),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);U={method:y,url:i(o.origin+o.pathname,N)},d?.push(U);let Z=await ie(o,{method:y,headers:B,body:a.body,redirect:`manual`,signal:X.signal,dispatcher:v});H=Z.status,U.status=Z.status;let Q=``;try{Q=await le(Z,D)}finally{if(_.has(Z.status)&&E&&t){let e={api:E.slug,name:E.name,status:Z.status};J&&(e.scheme=J),q?.length&&(e.schemes=[...q]),V&&(e.sentScheme=V),K?.unsupportedSchemes&&(e.unsupportedSchemes=[...K.unsupportedSchemes]);let n=ne(Q,Z.headers.get(`content-type`),N);n&&(e.detail=n),t(e)}}let $=r(ge(Z.headers),N);if(se(Z.status)){$=n($,ye);let{location:e}=$;e&&!ce(e,o,j)&&delete $.location}let Ce=ae(Z.status);return g?.gatewayFetchPerformed({host:o.hostname,method:y,outcome:Ce,durationMs:Date.now()-M,path:R,api:z,status:Z.status,bytes:Buffer.byteLength(Q,`utf8`),injectedScheme:V}),s(h,{rawUrl:o.href,method:y,host:o.hostname,outcome:Ce,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:R,api:z,status:Z.status,injectedScheme:V,requestHeaders:B,requestBody:a.body,responseHeaders:$,responseBody:Q,caller:k}),{status:Z.status,statusText:i(Z.statusText,N),ok:Z.ok,headers:$,bodyText:i(Q,N)}}catch(e){let t=U!==void 0&&C(e);t&&U&&d&&d.splice(d.indexOf(U),1);let{outcome:n,userSafe:r}=w(e,H),c=L??(r instanceof u?r.host:void 0)??T(a.url)??`invalid-url`;if(g?.gatewayFetchPerformed({host:c,method:y,outcome:n,durationMs:Date.now()-M,path:R,api:z,status:H,injectedScheme:V}),s(h,{rawUrl:a.url,method:y,host:c,outcome:n,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:R,api:z,status:H,injectedScheme:V,requestHeaders:B,requestBody:a.body,caller:k}),r)throw r;let l=G?{reason:`timeout after ${b} ms`,message:H===void 0?`The API did not answer within ${b/1e3} s`:`The API did not finish its answer within ${b/1e3} s`}:t?{reason:`connect failure ${x(e)??`without a code`}`,message:`Could not connect to ${c}`}:{reason:E(e),message:`Upstream fetch failed due to an internal error`};throw h?.error(`Gateway MCP fetch failed [${y} ${c}]: ${i(l.reason,N)} headers=${o(B)}`),new f(l.message)}finally{W!==void 0&&clearTimeout(W)}}}function x(e){let t=e;for(let e=0;e<5&&t instanceof Error;e++){if(`code`in t&&typeof t.code==`string`)return t.code;if(t instanceof AggregateError)return t.errors.map(x).find(e=>e!==void 0);t=t.cause}}function S(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof p||n instanceof e)return n;n=n.cause}}function C(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;if(n instanceof AggregateError)return n.errors.some(C);let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function ae(e){return _.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function w(t,n){let r=S(t),i=n===void 0?void 0:ae(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof u||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function oe(e,t,n){try{return m(e,t)}catch(e){throw e instanceof d&&n?new u(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function T(e){try{return new URL(e).hostname||void 0}catch{return}}function se(e){return e>=300&&e<400}function ce(e,t,n){try{return!!m(new URL(e,t).href,n)}catch{return!1}}function E(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function le(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw D(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw D(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function D(e,t){return new p(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new p(`securityScheme must be a security scheme name (a string)`);if(!t)throw new p(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new p(`This site cannot send securityScheme "${e}" to ${t.name}; valid values: ${n.join(`, `)}`);return e}function fe(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function pe(e,t,n,r){let i=O([...ie,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=O(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function O(e){return new Set(e.map(e=>e.toLowerCase()))}function me({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function he({callerHeaders:e,secret:t,clientIp:n}){let r={},i=new Headers;for(let[t,n]of Object.entries(e??{})){try{i.append(t,n)}catch{throw new p(`The "${t}" header is invalid: a header name must be a token and a value must hold no line breaks or characters above U+00FF`)}let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==g&&(r[t]=n)}return n&&(r[g]=n),t&&(r[t.header]=t.value),r}function ge(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{b as buildFetchBridge,y as getDefaultAgent,le as readCappedBody};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`GatewayFetchUserError`}},t=class extends e{host;constructor(e,t){super(e),this.name=`GatewayFetchBlockedError`,this.host=t}},n=class extends Error{constructor(e){super(e),this.name=`GatewayFetchSystemError`}};export{t as GatewayFetchBlockedError,n as GatewayFetchSystemError,e as GatewayFetchUserError};
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`GatewayFetchUserError`}},t=class extends e{host;constructor(e,t){super(e),this.name=`GatewayFetchBlockedError`,this.host=t}},n=class extends t{constructor(e){super(`Host "${e}" is not allowed`,e),this.name=`GatewayFetchHostNotAllowedError`}},r=class extends Error{constructor(e){super(e),this.name=`GatewayFetchSystemError`}};export{t as GatewayFetchBlockedError,n as GatewayFetchHostNotAllowedError,r as GatewayFetchSystemError,e as GatewayFetchUserError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isBlockedIp as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{
|
|
1
|
+
import{isBlockedIp as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{matchesOrigin as t}from"./allowed-hosts.js";import{GatewayFetchBlockedError as n,GatewayFetchHostNotAllowedError as r,GatewayFetchUserError as i}from"./fetch-errors.js";import{findUnresolvedPlaceholders as a,unresolvedPlaceholderMessage as o}from"./url-placeholders.js";import{isIP as s}from"node:net";function c(e,s){let c;try{c=new URL(e)}catch{throw new i(`Invalid URL: ${e}`)}if(c.protocol!==`http:`&&c.protocol!==`https:`)throw new i(`Only http(s) URLs are allowed, got ${c.protocol}`);if(c.username||c.password)throw new i(`URLs must not contain embedded credentials`);let f=a(c.hostname);if(f.length>0)throw new i(o(f));let p=d(c.hostname),m=l(p)?[]:s.filter(e=>e.hostname.test(p));if(m.length===0)throw new r(p);if(!m.some(e=>t(e,c))){let e=u(c.hostname,m);throw new n(`Origin "${c.origin}" is not allowed; use the documented ${e.length===1?`origin`:`origins`} of ${p}: ${e.join(`, `)}`,p)}let h=a(c.pathname);if(h.length>0)throw new i(o(h));return c}function l(t){let n=d(t.toLowerCase()).split(`%`)[0];return n===`localhost`||n.endsWith(`.localhost`)?!0:s(n)!==0&&e(n)}function u(e,t){let n=t.flatMap(({protocol:t,ports:n})=>n.map(n=>`${t}//${e}${n?`:${n}`:``}`));return[...new Set(n)]}function d(e){return e.replace(/^\[|\]$/g,``)}export{c as assertUrlAllowed,l as isBlockedAddress};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{
|
|
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:
|
|
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(
|
|
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(`
|
|
4
4
|
|
|
5
|
-
`)}function Q({ctx:e,subject:
|
|
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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,
|
|
3
|
-
`),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,
|
|
4
|
-
`)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await
|
|
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,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)[0].trim();a&&(n[r]=a.slice(0,120))}return n}function
|
|
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 +1 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{
|
|
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 +1 @@
|
|
|
1
|
-
import
|
|
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 +1 @@
|
|
|
1
|
-
import{
|
|
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 +1 @@
|
|
|
1
|
-
import{
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import{FIELD_SCOPE_KINDS as e,GRAPHQL_TYPE_KINDS as t}from"
|
|
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(`
|
|
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"
|
|
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 +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{
|
|
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 +1 @@
|
|
|
1
|
-
import{toolNameForMode as
|
|
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 +1 @@
|
|
|
1
|
-
import{
|
|
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 +1 @@
|
|
|
1
|
-
import{
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import{readIgnoredRouteSlugs as e}from"../../ignored-routes.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{recoveryToolNames as n}from"./openapi-document.js";import{
|
|
2
|
-
`)}}},
|
|
1
|
+
import{readIgnoredRouteSlugs as e}from"../../ignored-routes.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{recoveryToolNames as n}from"./openapi-document.js";import{collectNodeLinks as r,countPages as i,findSection as a,flattenSections as o,loadPageNavigation as s,loadVisiblePages as c,toPageSlug as l,toPublicUrl as u,toSectionId as d}from"./pages-navigation.js";import{DEFAULT_GREP_MATCHES as f,DEFAULT_PAGE_LINES as p,GET_PAGE_SCHEMA as m,GREP_PAGES_SCHEMA as h,LIST_PAGES_SCHEMA as g,MAX_GREP_MATCHES as _,MAX_PAGE_LINES as v,grepPagesToolSchema as y,listPagesToolSchema as b}from"@redocly/mcp";const x=/^(#{1,3}) +(\S.*)$/,S=/^\s*(```|~~~)/,C={schema:g,schemaFor:e=>b(e.mcpMode),async execute(e,n){let{section:r}=e??{},{sections:i}=await s(n),c=t(n.request);if(!r)return{sections:i.map(e=>({id:e.id,title:e.title,items:D(e.id,e.nodes,c)}))};let l=a(i,r,c);if(!l){let e=o(i).slice(0,50).map(({id:e})=>e);throw Error(`No section "${r}". Pass one of these section ids: ${e.join(`; `)}.`)}return{section:{id:l.id,title:l.title},items:D(l.id,l.nodes,c)}}},w={schema:m,async execute(e,r){let{url:i,startLine:a,lines:o}=e??{};if(typeof i!=`string`||i.trim()===``)throw Error(`The "url" parameter is required: a page URL or path.`);let s=t(r.request),c=l(i,s),d=c===null?null:await E(c,r);if(c===null||d===null)throw Error(`No page you can read is at "${i}": it does not exist, or your access does not include it. Do not describe it from other pages. Call ${n(r.mcpMode).listPages} to see the pages you can read.`);let f=A(d.text),m=Math.max(1,Math.floor(a??1));if(m>f.length)throw Error(`Line ${m} is past the end of "${d.title??c}", which has ${f.length} lines.`);let h=O(o,p,v),g=Math.min(f.length,m+h-1);return{url:u(c,s),title:d.title??c,totalLines:f.length,startLine:m,endLine:g,...g<f.length?{nextStartLine:g+1}:{},outline:j(f),content:f.slice(m-1,g).join(`
|
|
2
|
+
`)}}},T={schema:h,schemaFor:e=>y(e.mcpMode),async execute(e,i){let{query:o,section:l,maxMatches:d}=e??{};if(typeof o!=`string`||o===``)throw Error(`The "query" parameter is required: a text to find.`);let p=t(i.request),m,h;if(l){let{sections:e,pages:t}=await s(i),o=a(e,l,p);if(!o)throw Error(`No section "${l}". Call ${n(i.mcpMode).listPages} to see the sections.`);let c=new Set(r(o.nodes));o.link&&c.add(o.link),m=t.filter(e=>c.has(e.slug)),h=o.title}else m=(await c(i)).pages;let g=O(d,f,_),v=o.toLowerCase(),y=m.length,b=[];for(let e of m){let t=(await i.pageMarkdown.readPage(e.slug))?.text??``;if(t.toLowerCase().includes(v))for(let[n,r]of A(t).entries()){let t=r.toLowerCase().indexOf(v);if(t!==-1){if(b.length===g)return{matches:b,searchedPages:y,truncated:!0};b.push({url:u(e.slug,p),title:e.title,line:n+1,text:k(r,t)})}}}return b.length>0?{matches:b,searchedPages:y,truncated:!1}:{matches:b,searchedPages:y,truncated:!1,note:`No page you can read ${h?`in "${h}" contains "${o}". All ${y} pages there were searched.`:`contains "${o}". All ${y} pages were searched. API references are not searched: use ${n(i.mcpMode).listApis} for them.`}`}}};async function E(t,n){return(await e(n.entities)).has(t)?null:n.pageMarkdown.readPage(t)}function D(e,t,n){return t.map(t=>t.type===`page`?{type:`page`,title:t.label,url:u(t.link??``,n)}:{type:`section`,id:d(e,t.label),title:t.label,...t.link?{url:u(t.link,n)}:{},pageCount:i(t.items)})}function O(e,t,n){return Math.min(Math.max(1,Math.floor(e??t)),n)}function k(e,t){let n=Math.max(0,Math.min(t-80,e.length-200));return e.slice(n,n+200).trim()}function A(e){return(e.endsWith(`
|
|
3
3
|
`)?e.slice(0,-1):e).split(`
|
|
4
|
-
`)}function
|
|
4
|
+
`)}function j(e){let t=[],n=!1;return e.forEach((e,r)=>{if(S.test(e)){n=!n;return}let i=n?null:x.exec(e);i&&t.push({line:r+1,level:i[1].length,heading:i[2].trim()})}),t}const M=[C,w,T];export{M as pageTools};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{normalizeL10nConfig as e}from"../../../../../../shared/utils/l10n.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{SEARCH_SCHEMA as c,searchSchema as l}from"
|
|
1
|
+
import{normalizeL10nConfig as e}from"../../../../../../shared/utils/l10n.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import{readIgnoredRouteSlugs as n}from"../../ignored-routes.js";import{publicOrigin as r}from"../../../../utils/request-origin.js";import{resolveSemanticSearchUpstreamUrl as i}from"../../../../../../shared/ask-ai/upstream.js";import{SemanticSearchError as a,fetchSemanticSearchDocuments as o,filterSemanticSearchDocuments as s}from"../semantic-search.js";import{SEARCH_SCHEMA as c,searchSchema as l}from"@redocly/mcp";const u=`No results found.`;function d(e,n){let r=e=>{try{return new URL(t(e),n).toString()}catch{return e}};return e.map(e=>`### [${e.title}](${r(e.url)})\n\n${e.content}\n`).join(`
|
|
2
2
|
|
|
3
3
|
`).trim()}const f=[{schema:c,schemaFor:t=>l(Object.values(t.config.products??{}).map(e=>e.name),e(t.config.l10n).locales?.map(e=>e.code)??[]),isAvailable:()=>i()!==``,async execute(t,i){let{query:c,product:l,locale:f}=t??{},p;try{p=await o({query:c,product:l||void 0,locale:f||e(i.config.l10n).defaultLocale})}catch(e){throw e instanceof a?(i.logger?.warn(`MCP search: ${e.message} ${e.detail}`),Error(`The search service failed. Try the call again later.`)):e}let m=await n(i.entities),h=await s(p,async e=>!m.has(e)&&i.isSlugVisible(e)&&await i.hasRoute(e));return h.length===0?u:d(h,r(i.request))||u}}];export{f as searchTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{publicOrigin as e}from"../../../../utils/request-origin.js";import{submitFeedback as t}from"../../../../../../server/feedback/route.js";import{
|
|
1
|
+
import{publicOrigin as e}from"../../../../utils/request-origin.js";import{submitFeedback as t}from"../../../../../../server/feedback/route.js";import{toPageSlug as n,toPublicUrl as r}from"./pages-navigation.js";import{SUBMIT_FEEDBACK_SCHEMA as i}from"@redocly/mcp";function a(e){return{content:[{type:`text`,text:JSON.stringify(e)}],isError:!0}}function o(e){return e?.trim()||void 0}function s(e,t){let i=n(e,t);return i===null?void 0:new URL(r(i,t)).toString()}function c(e){return e.feedback?.hide!==!0}const l=[{schema:i,isAvailable:e=>c(e.config),async execute(n,r){let i=n??{},c=o(i.path),l=o(i.summary);if(!c||!l)return a({error:`Invalid arguments`,message:"`path` and `summary` are required."});let u=s(c,e(r.request));if(!u)return a({error:`Invalid arguments`,message:"`path` must be a page path or URL of this site."});let d=o(i.details),f=r.clientVersion?`${r.client}/${r.clientVersion}`:r.client,p;try{p=await t({body:{component:`comment`,path:u,comment:d?`${l}\n\n${d}`:l,agent:f,targetFeature:o(i.targetFeature),origin:`mcp`},request:r.request,isSlugVisible:e=>r.isSlugVisible(e)},{hasRoute:e=>r.hasRoute(e),logger:r.logger})}catch{return a({error:`Failed to submit feedback`,message:`The feedback endpoint could not be reached.`})}let{status:m,data:h}=p;return m===403?a({error:`Forbidden`,message:`You have no access to this page, so feedback for it is not accepted.`}):m===404?a({error:`Not found`,message:`No page exists at ${u}.`}):m===400?a({error:`Invalid feedback`,errors:Array.isArray(h.errors)?h.errors.filter(e=>typeof e==`string`):[]}):m<200||m>299?a({error:`Failed to submit feedback`,message:`The feedback endpoint answered ${m}.`}):{status:`received`,page:u,message:`Thanks for your feedback. The documentation team sees it on the Feedback page.`}}}];export{c as isFeedbackEnabled,l as submitFeedbackTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{WHOAMI_SCHEMA as e}from"
|
|
1
|
+
import{WHOAMI_SCHEMA as e}from"@redocly/mcp";function t(e){let t=typeof e==`number`?e:Number(e);return Number.isFinite(t)&&t>0?(/* @__PURE__ */ new Date(t*1e3)).toISOString():void 0}const n=[{schema:e,isAvailable:e=>e.isProtected,async execute(e,n){let r=n.request.viewer;if(!r?.isAuthenticated)return{authenticated:!1};let i=n.claims??{};return{authenticated:!0,email:r.email,name:r.name,subject:r.sub,clientId:i.client_id,scope:i.scope,issuedAt:t(i.iat),expiresAt:t(i.exp)}}}];export{n as whoamiTools};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{
|
|
1
|
+
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{stripPathPrefix as t}from"../../../../../shared/path-prefix.js";import{filePathToRouteSlug as n}from"../../../../../shared/utils/routes/file-path-to-route-slug.js";import{mockPathPrefix as r}from"../../../types/api-entity.js";import{isPlanFeatureGranted as i}from"../../../../../shared/plan-gates.js";import{notFoundResponse as a}from"../../../../../server/plugin-context.js";const o={"Cache-Control":`no-store`},s=/* @__PURE__ */ new Map;function c(t,n){let r=n.metadata?.mockServer;return{...t,...e(r)?r:{}}}function l(e,t){let{specType:n,routeSlug:i}=e.metadata??{};return n!==`openapi`||typeof i!=`string`||c(t,e).off===!0?null:r(i)}function u(e,t,n=void 0){let r=null,i=-1;for(let a of e){let e=l(a,n);e===null||e.length<=i||d(e,t)&&(r={api:a,path:t.slice(e.length)||`/`},i=e.length)}return r}function d(e,t){return t===e||t.startsWith(`${e}/`)}function f(e,t,{createMockServer:n}){let r=s.get(t.key);if(r&&r.dataHash===t.dataHash)return r.handler;let{strictExamples:i,errorIfForcedExampleNotFound:a}=c(e.config.mockServer,t),o=e.entities.load(t.key).then(e=>n(structuredClone(e),{strictExamples:i,errorIfForcedExampleNotFound:a}));return s.set(t.key,{dataHash:t.dataHash,handler:o}),o.catch(()=>s.delete(t.key)),o}async function p(e,t){let i=await e.entities.list({type:`api`}),a=i.filter(({metadata:e})=>e?.specType!==`openapi`||e.routeSlug!==void 0?!1:d(r(n(String(e.sourcePath))),t));return a.length===0?i:(await Promise.all(a.map(t=>e.entities.load(t.key))),e.entities.list({type:`api`}))}function m(e,t){let n=(e.req.header(`x-http-method-override`)??e.req.method).toUpperCase(),{search:r}=new URL(e.req.url),i;return{path:t,method:n,query:r===``?void 0:r,headers:Object.fromEntries(e.req.raw.headers),getBody:()=>i??=e.req.arrayBuffer().then(e=>e.byteLength>0?Buffer.from(e):void 0)}}function h(e){return(t(new URL(e.req.url).pathname)??``).slice(6)||`/`}async function g(e,t){if(!i(t.config,`mockServer`))return a();let n=h(e),r=u(await p(t,n),n,t.config.mockServer);if(!r||!t.isSlugVisible(String(r.api.metadata?.routeSlug)))return a();let s;try{s=await import(`@redocly/mock-server`)}catch{return new Response(`Mock server is not available on this host`,{status:501})}let c=await(await f(t,r.api,s))(m(e,r.path));return new Response(c.body?new Uint8Array(c.body):null,{status:c.statusCode,headers:{...c.headers,...o}})}export{u as matchMockApi,g as mock,m as toMockRequest};
|