@redocly/framework 1.0.0-next.11 → 1.0.0-next.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundler/build/dependency-pack.js +1 -1
- package/dist/bundler/build/output-metadata.js +1 -1
- package/dist/bundler/build/run.js +1 -1
- package/dist/bundler/build/theme-global-stylesheets.js +1 -1
- package/dist/bundler/build/vite-config.js +2 -2
- package/dist/bundler/dev/dev-content-build.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/dev/vite-config.js +1 -1
- package/dist/bundler/user-markdoc-schema.js +1 -1
- package/dist/bundler/vite-config.base.js +5 -5
- package/dist/cli/api-docs-build-event.js +1 -1
- package/dist/cli/args.js +1 -1
- 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 +1 -1
- package/dist/cli/problems-output.js +3 -3
- package/dist/cli/validate-react-pages.js +1 -1
- package/dist/client/ai-search/citations.js +3 -3
- 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 +2 -2
- package/dist/client/classic-webview-sync.js +1 -0
- package/dist/client/client-entry.js +1 -1
- package/dist/client/contexts.js +1 -1
- package/dist/client/feedback.js +1 -1
- package/dist/client/l10n/ssr-l10n.js +1 -1
- package/dist/client/l10n/use-l10n-config.js +1 -1
- package/dist/client/page-sync.js +1 -0
- package/dist/client/products.js +1 -1
- package/dist/client/review/ReviewBar.js +3 -3
- package/dist/client/review/login-url.js +1 -1
- package/dist/client/review/use-review.js +1 -1
- package/dist/client/revisions-history.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/theme-logo.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/context-state.js +1 -1
- package/dist/content-layer/context.js +1 -1
- package/dist/content-layer/database/assets.js +1 -1
- package/dist/content-layer/database/blobs.js +1 -1
- package/dist/content-layer/database/entity-store.js +1 -1
- package/dist/content-layer/database/files.js +1 -1
- package/dist/content-layer/database/finalize.js +1 -1
- package/dist/content-layer/database/invalidation.js +26 -26
- package/dist/content-layer/database/link-refs.js +1 -1
- package/dist/content-layer/database/origins.js +1 -1
- package/dist/content-layer/database/problems.js +1 -1
- package/dist/content-layer/database/reset.js +1 -1
- package/dist/content-layer/database/route-query-deps.js +1 -1
- package/dist/content-layer/database/search-vocab.js +2 -2
- package/dist/content-layer/database/static-files.js +1 -1
- package/dist/content-layer/ingest/extract-all-phase.js +1 -1
- package/dist/content-layer/ingest/finalize-phase.js +1 -1
- package/dist/content-layer/ingest/hash.js +1 -1
- package/dist/content-layer/ingest/hook-inputs.js +1 -1
- package/dist/content-layer/ingest/l10n-warnings.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/scan.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/config-links.js +1 -1
- package/dist/content-layer/link-checker/delta.js +1 -1
- package/dist/content-layer/link-checker/fingerprint.js +1 -1
- package/dist/content-layer/link-checker/load-view.js +1 -1
- package/dist/content-layer/link-checker/node-ref.js +1 -1
- package/dist/content-layer/link-checker/run-build.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/JsonSchemaTag.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/nodes/fence.js +1 -1
- package/dist/content-layer/markdown/nodes/heading.js +1 -1
- package/dist/content-layer/markdown/nodes/table.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/file-reference.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/svg-content.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 +2 -2
- package/dist/content-layer/markdown/search/to-sections.js +1 -1
- package/dist/content-layer/markdown/search/to-text.js +5 -5
- package/dist/content-layer/markdown/server/render.js +1 -1
- package/dist/content-layer/markdown/service.js +1 -1
- package/dist/content-layer/markdown/tags/variant.js +1 -1
- package/dist/content-layer/markdown/utils/collect-anchors.js +1 -1
- package/dist/content-layer/markdown/utils/first-heading.js +1 -1
- package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
- package/dist/content-layer/materialization/asset-reconcile.js +1 -1
- package/dist/content-layer/materialization/entity.js +1 -1
- package/dist/content-layer/materialization/materializer.js +1 -1
- package/dist/content-layer/materialization/static-files.js +1 -1
- package/dist/content-layer/plugins/execute.js +1 -1
- package/dist/content-layer/plugins/index.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/build-definition.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-copy.js +5 -5
- package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/search-documents.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/spec-download.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.d.ts +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/logo.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/products.js +1 -1
- package/dist/content-layer/plugins/internal/assets/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/catalog-classic/resolve-items.js +1 -1
- package/dist/content-layer/plugins/internal/index.js +1 -1
- package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
- package/dist/content-layer/plugins/internal/l10n/translations-loader.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/app-data.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/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/config-gate.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/custom-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/call-api.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-handler.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.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 -6
- package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
- package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
- package/dist/content-layer/plugins/internal/mcp/server/handler.js +1 -1
- 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/oauth/callback.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/error-reporting.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/register.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/token.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/rate-limit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/skills-resources.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 +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/setup-page.js +1 -1
- package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/react-page/index.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/internal/skills/server/routes.js +1 -1
- package/dist/content-layer/plugins/internal/versions/index.js +1 -1
- package/dist/content-layer/plugins/io.js +1 -1
- package/dist/content-layer/plugins/project/load.js +2 -2
- package/dist/content-layer/plugins/source-file.js +1 -1
- 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/revisions/delete.js +1 -1
- package/dist/content-layer/revisions/read.js +1 -1
- package/dist/content-layer/search/engine/core/search-engine.js +1 -1
- package/dist/content-layer/search/postings/postings-store.js +1 -1
- package/dist/content-layer/server/database.js +1 -1
- package/dist/content-layer/static/registry.js +1 -1
- package/dist/content-layer/templates/template-set.js +1 -1
- package/dist/content-layer/versions/group-info.d.ts +2 -1
- package/dist/content-layer/versions/group-info.js +1 -1
- package/dist/content-layer/versions/redirect.js +1 -1
- package/dist/content-layer/versions/resolve.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/auth/runtime.js +1 -1
- package/dist/server/content.js +12 -12
- 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/manifest-assets.js +4 -4
- package/dist/server/node-entry.js +1 -1
- package/dist/server/plugin-context.js +1 -1
- package/dist/server/rbac/content-asset-access.js +1 -1
- package/dist/server/runtime-config.js +1 -1
- package/dist/server/search/route.js +1 -1
- package/dist/server/seo-tags.js +2 -2
- package/dist/server/sitemap.js +1 -1
- package/dist/server/static-files/serve.js +1 -1
- package/dist/server/subprocess/child-entry.js +1 -1
- package/dist/server/telemetry/mock-server-events.js +1 -1
- package/dist/server/telemetry/sender.js +1 -1
- package/dist/server/template-ids.js +1 -1
- package/dist/server/wait-until.js +1 -0
- package/dist/shared/constants/review.d.ts +2 -0
- package/dist/shared/constants/review.js +1 -1
- package/dist/shared/constants/system-routes.d.ts +1 -1
- package/dist/shared/constants/system-routes.js +1 -1
- package/dist/shared/rbac/engine.js +0 -0
- package/dist/shared/rbac/l10n-rules.js +1 -1
- package/dist/shared/rbac/route-scope.js +1 -1
- package/dist/shared/rbac/team-templates.js +1 -1
- package/dist/shared/utils/l10n.js +1 -1
- package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ANONYMOUS_VIEWER as e}from"../../../../../shared/types/auth.js";import{RBAC_TEAM_ANONYMOUS as t}from"../../../../../shared/rbac/types.js";import{canView as n,parseRbacScope as r,resolveRole as i}from"../../../../../shared/rbac/engine.js";import{resolveViewerTeams as a}from"../../../../../shared/rbac/teams.js";function o(e){return!!e.mcp?.hide}function s(e){return e!==void 0&&(Object.keys(e),!0)}function c(e){if(!e||typeof e!=`object`||Object.keys(e).length===0)return!1;let a=r(e,`rbac`,()=>{});return!n(i(a,[t]))}function l(e){let t=e.access?.rbac;return{requiresLogin:e.access?.requiresLogin===!0,rbacConfigured:s(t),rbacDeniesAnonymous:Object.values(t?.content??{}).some(c)||c(t?.features?.mcp),featureScope:t?.features?.mcp}}function u(e){return e.requiresLogin||e.rbacDeniesAnonymous}function d(t,n){return!!t.mcp?.publicEndpoint&&u(n)&&p(n,a(e),!1)}function f(e){return d(e,l(e))}function p(e,t,a,o=()=>{}){return e.rbacConfigured?e.featureScope===void 0||n(i(r(e.featureScope,`features.mcp`,o),t)):!e.requiresLogin||a}export{p as canAccessMcpFeature,u as isMcpContentProtected,o as isMcpHidden,d as isPublicEndpointServed,f as isPublicEndpointServedFromConfig,l as resolveMcpAccess};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{publicOrigin as e}from"../../../utils/request-origin.js";import{errorMessage as t}from"../../../../../shared/utils/error-message.js";import{isSubprocessError as n}from"../../../../../server/subprocess/runner.js";import{MCP_TOOLS_ENTITY_TYPE as r}from"../constants.js";import{ToolHandlerError as i}from"./tool-errors.js";import{fileURLToPath as a}from"node:url";import{parse as o}from"hono/utils/cookie";const s=a(import.meta.url);function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(e){return`MCP tool "${e}" is not registered or its module does not export a handler for "${e}". Expected \`export default { '${e}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`}function u(e,t){if(c(e))return typeof e.execute==`function`&&typeof e.description==`string`?e:e[t]}const d=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function f(e){return c(e)&&Array.isArray(e.content)&&e.content.every(e=>c(e)&&d.has(e.type))}function p(e,t){if(f(t))return t;if(typeof t==`string`)return{content:[{type:`text`,text:t}]};let n;try{n=JSON.stringify(t)}catch(t){throw Error(`MCP tool "${e}" returned a value that cannot be serialized to JSON: ${S(t)}`)}if(n===void 0)throw Error(`MCP tool "${e}" returned an invalid result.`);return{content:[{type:`text`,text:n}]}}const m={readFile:async()=>{throw Error(`Project files are not available in this environment.`)}};async function h(e,n){let r=u((await n.loadModule(e.handlerModulePath)).default,e.toolName),i=typeof r==`function`?r:r?.execute;if(typeof i!=`function`)return{ok:!1,code:`no-handler-export`,message:l(e.toolName)};let a={...e.context,fs:m};try{if(e.mode===`isAvailable`){let e=typeof r==`function`?void 0:r?.isAvailable;return{ok:!0,output:!e||await e(a)}}let t=await i(e.args,a,e.extra);return{ok:!0,output:p(e.toolName,t)}}catch(e){return{ok:!1,code:`handler-error`,message:t(e),stack:e instanceof Error?e.stack:void 0}}}function g(t){let n=t.request.viewer;return{user:{teams:t.request.teams,claims:t.claims??{...n},email:n?.email,idpAccessToken:void 0,idpId:void 0,isAuthenticated:n?.isAuthenticated??!1},config:t.config,baseUrl:e(t.request),params:{},query:Object.fromEntries(new URL(t.request.url).searchParams),cookies:o(t.request.headers.cookie??``),products:Object.values(t.config.products??{}).map(e=>e.name),accessToken:t.accessToken,metadata:t.metadata}}function _(e,t,n){if(!c(e)||e.type!==`object`)return null;let r=`Invalid arguments for tool "${n}":`;if(!c(t))return`${r} expected an object.`;let i=Array.isArray(e.required)?e.required:[];for(let e of i)if(typeof e==`string`&&!(e in t))return`${r} missing required field "${e}".`;let a=c(e.properties)?e.properties:{};for(let[e,n]of Object.entries(t)){let t=a[e];if(c(t)){if(typeof t.type==`string`&&!v(n,t.type))return`${r} field "${e}" must be ${t.type}.`;if(Array.isArray(t.enum)&&!t.enum.includes(n))return`${r} field "${e}" must be one of ${JSON.stringify(t.enum)}.`}}return null}function v(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&Number.isFinite(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`object`:return c(e);case`array`:return Array.isArray(e);case`null`:return e===null;default:return!0}}function y(e,t,n,r,i){if(!t.subprocess)throw Error(`MCP tool "${e.toolName}" cannot run on this host: no subprocess.`);return t.subprocess.run({modulePath:s,exportName:`invokeCustomTool`,input:{handlerModulePath:t.subprocess.resolveContentModule(e.handlerFilePath),toolName:e.toolName,mode:n,args:r,context:g(t),extra:{sessionId:i?.sessionId,requestId:i?.mcpReq.id??t.requestId,_meta:i?.mcpReq._meta}},reuse:!import.meta.env.DEV,timeoutMs:3e4})}function b(e,t){return{schema:e,isAvailable:t.hasAvailabilityGate?async n=>{if(!n.subprocess)return!1;let r=n.isAvailableMemo?.get(e.name);if(r)return r;let i=(async()=>{try{let e=await y(t,n,`isAvailable`);return e.ok&&e.output===!0}catch(t){return n.logger?.warn(`MCP tool "${e.name}" isAvailable failed: ${S(t)}`),!1}})();return n.isAvailableMemo?.set(e.name,i),i}:void 0,async execute(n,r,a){let o=_(t.argsSchema,n,e.name);if(o)throw Error(o);let s=await y(t,r,`execute`,n,a?.serverContext);if(!s.ok){let e=new i(s.message);throw e.stack=s.stack??e.stack,e}return s.output}}}function x(e){let{declaration:t}=e;return b({name:t.name,title:t.title,description:t.description,schema:t.schema,outputSchema:t.outputSchema,annotations:t.annotations},{toolName:t.name,handlerFilePath:e.handler.filePath,argsSchema:t.schema,hasAvailabilityGate:!0})}function S(e){return n(e)?`${e.code}: ${e.message}`:t(e)}function C(e,t){if(!c(t))return{ok:!1,errors:["the default export must be an object with `description` and `execute` properties. Move shared helper code outside the `@mcp` folder."]};let{description:n,inputSchema:r,outputSchema:i,annotations:a,isAvailable:o,execute:s}=t,l=[];return(typeof n!=`string`||n.trim()===``)&&l.push("`description` must be a non-empty string."),typeof s!=`function`&&l.push("`execute` must be a function."),r!==void 0&&(c(r)?r.type!==void 0&&r.type!==`object`&&l.push('`inputSchema.type` must be "object" because MCP tool arguments are named.'):l.push("`inputSchema` must be a JSON Schema object.")),i!==void 0&&!c(i)&&l.push("`outputSchema` must be a JSON Schema object."),a!==void 0&&!c(a)&&l.push("`annotations` must be an object."),o!==void 0&&typeof o!=`function`&&l.push("`isAvailable` must be a function."),l.length>0||typeof n!=`string`?{ok:!1,errors:l}:{ok:!0,schema:{name:e,description:n,schema:Object.assign({type:`object`},r??{properties:{}}),outputSchema:i,annotations:a},hasAvailabilityGate:typeof o==`function`}}async function w(e){let t=[],n=[];for(let i of await e.entities.list({type:r})){let{name:r,sourcePath:a}=i.metadata,o=e=>n.push(`Invalid MCP tool file "${a}": ${e}`);if(e.reservedNames.has(r)){o(`the tool name "${r}" is already used by a built-in MCP tool. Rename the file.`);continue}let s;try{s=(await e.loadContentModule(a)).default}catch(e){o(`the file failed to load: ${S(e)}. Tool files must not have module-level side effects.`);continue}let c=C(r,s);if(!c.ok){o(c.errors.join(` `));continue}t.push({schema:c.schema,sourcePath:a,hasAvailabilityGate:c.hasAvailabilityGate})}return{tools:t,errors:n}}function T(e){return`MCP tool "${e.schema.name}" in ${e.sourcePath} declares no \`outputSchema\`. Add one that describes the returned value.`}const E=/* @__PURE__ */ new Set;function D(e,t){e&&!E.has(t)&&(E.add(t),e.warn(t))}async function O(e){let{loadContentModule:t,logger:n}=e;if(!t)return[];let{tools:r,errors:i}=await w({entities:e.entities,loadContentModule:t,reservedNames:e.reservedNames});for(let e of i)D(n,e);for(let e of r)e.schema.outputSchema===void 0&&D(n,T(e));return r.map(e=>b(e.schema,{toolName:e.schema.name,handlerFilePath:e.sourcePath,argsSchema:e.schema.schema,hasAvailabilityGate:e.hasAvailabilityGate}))}export{O as buildMcpFileTools,x as createCustomTool,h as invokeCustomTool,w as loadMcpFileTools,T as missingOutputSchemaWarning,C as validateToolDefinition};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),annotations:
|
|
1
|
+
import{SsrfBlockedError as e}from"../../../../../../server/ssrf/ssrf-blocklist.js";import{CALL_API_WRITE_TOOL_NAME as t,REQUIRES_USER_INTERACTION_META as n,WRITE_TOOL_ANNOTATIONS as r}from"../../constants.js";import{callableApis as i}from"./eligibility.js";import{getOfferedWriteHttpMethods as a}from"./allowed-http-methods.js";import{GatewayFetchSystemError as o,GatewayFetchUserError as s}from"./fetch/fetch-errors.js";import{runExecuteWithGateway as c}from"./index.js";import{SESSION_HANDLE_PROPERTY as l}from"./tools.js";const u=[`content-type`,`location`],d=/[/+]json\b/i;function f(e){return{name:t,title:`Call a documented API`,description:[`Send one request with a write method to one documented operation of a callable API.`,"Read the operation with `execute` first: the server URL, the path parameters, and the body shape. Pass the same `url`, `method`, `headers` and `body` you would pass to `fetch` in a script.",`Send only the operation the user asked for. When its method or operation is not allowed, tell the user and stop. Do not substitute another operation.`].join(`
|
|
2
|
+
`),annotations:r,_meta:n,schema:{type:`object`,required:[`url`,`method`],additionalProperties:!1,properties:{url:{type:`string`,minLength:1,description:"The full URL: a documented server URL of the API plus the operation path, with every `{placeholder}` filled and the query parameters included."},method:e.length>0?{type:`string`,enum:e}:{type:`string`},headers:{type:`object`,additionalProperties:{type:`string`},description:`The request headers. The stored credential is added by the server.`},body:{description:"The request body: a JSON value, sent as `application/json`, or a string, sent as is with the `content-type` header you pass."},securityScheme:{type:`string`,minLength:1,description:`The security scheme whose stored credential to send. Omit it to let the server choose.`},sessionHandle:l}},outputSchema:{type:`object`,required:[`status`,`headers`],properties:{status:{type:`number`},headers:{type:`object`,additionalProperties:{type:`string`}},body:{description:`The response body: parsed JSON for a JSON response, else text.`}}}}}function p(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t)}function m({url:e,method:t,headers:n={},body:r,securityScheme:i}){return r===void 0||typeof r==`string`?{url:e,method:t,headers:n,body:r,securityScheme:i}:{url:e,method:t,headers:p(n,`content-type`)?n:{...n,"content-type":`application/json`},body:JSON.stringify(r),securityScheme:i}}function h({headers:e,bodyText:t}){if(!d.test(e[`content-type`]??``))return t;try{return JSON.parse(t)}catch{return t}}async function g(t,n){try{let e=await n(m(t)),r=Object.fromEntries(u.flatMap(t=>e.headers[t]===void 0?[]:[[t,e.headers[t]]])),i={status:e.status,headers:r,body:h(e)};return{content:[{type:`text`,text:JSON.stringify(i)}],structuredContent:i}}catch(t){if(!(t instanceof s||t instanceof o||t instanceof e))throw t;return{content:[{type:`text`,text:t.message}],isError:!0}}}async function _(e){return(await i(e)).length>0}const v={schema:f([]),schemaFor:e=>f(a(e)),isAvailable:async e=>a(e).length>0&&await _(e),execute(e,n,r){let i=e,o=r?.serverContext;if(!o)throw Error(`\`${t}\` runs only as a top-level tool call.`);return c({ctx:n,sessionHandle:i.sessionHandle,serverContext:o,allowedHttpMethods:a(n),run:e=>g(i,e)})}};export{v as callApiWriteTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{notFoundResponse as e}from"../../../../../../server/plugin-context.js";import{isMcpHidden as t}from"../config-gate.js";import{resolveMcpMode as n}from"../mode.js";import{isGatewayEnabled as r}from"./env.js";async function i(i,a){if(!r(a.config)||n()!==`code`||t(a.config))return e();let{serveCredentials:o}=await import(`./credentials.js`);return o(i,a)}export{i as mcpCredentials};
|
package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../../constants.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{ELICITATION_TTL_MS as i}from"../secret-store.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./form-contract.js";import{ICONS as s,code as c,escapeHtml as l,siteHeader as u,targetTitle as d}from"./layout.js";const f=`form-error`,p=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),m={bearer:{title:`API token`,noun:`API token`,placeholder:`Paste your API token`},apiKey:{title:`API key`,noun:`API key`,placeholder:`Paste your API key`},cookie:{title:`Cookie`,noun:`cookie value`,placeholder:`Paste the cookie value`},oauth2ClientCredentials:{title:`OAuth2`,noun:`access token`,placeholder:`Paste an access token`},raw:{title:`Authorization header`,noun:`header value`,placeholder:`Bearer <token>`}};function h(r){let{site:o,target:c,token:p,error:m}=r,h=e(t),y=a(c),b=y.length>1,x=g(r,y),S=x.some(e=>e.isStored),C=b&&S,w=x.map(e=>b?v(e):_(e)).join(``),O=C?`<button class="text-danger" type="submit" form="remove-all">Remove all credentials</button>`:``,k=m?`<div class="banner" role="alert" id="${f}">${s.alert}<p>${l(m.message)}</p></div>`:``,j=c.subject.startsWith(`anon:`)?`<div class="banner warning">${s.warning}<p>This link is not tied to an account. The person who sent it to you can use the credentials that you save here. Continue only if you asked your AI client for this link at ${A(c.expiresAt-i)} UTC.</p></div>`:``;return{title:`Credentials for ${d(c)}`,body:`<div class="page">
|
|
2
2
|
<main class="card">
|
|
3
3
|
${u(o)}
|
|
4
4
|
<h1>${S?`Update`:`Add`} credentials for ${l(d(c))}</h1>
|
package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{
|
|
1
|
+
import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{toAppData as t}from"../../../../../../../shared/utils/app-data.js";import{parseSrcSet as n}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as r}from"../../../../../../../shared/constants/mcp.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(n){let a=t(await n.entities.load(e)),s=o({seo:n.config.seo,logo:a.theme?.logo,colorMode:n.config.colorMode}),c=await n.entities.get(`mcp:credentials-theme`)?await n.entities.load(r):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(n.request)).host}}function o({seo:e,logo:t,colorMode:r}){let i={},a=e?.title||e?.projectTitle||t?.altText;a&&(i.name=a);let o=new Map((t?.srcSet?n(t.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??t?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{SecretStore as a}from"./secret-store.js";import{buildAllowedOriginMatchers as o}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as s}from"./fetch/ssrf-guard.js";import{getDefaultAgent as c,readCappedBody as l}from"./fetch/fetch-bridge.js";import{credentialSchemesOf as u,schemeFieldName as d}from"./credentials-page/form-contract.js";import{htmlDocument as f}from"./credentials-page/layout.js";import{formPage as p}from"./credentials-page/form-page.js";import{declinedPage as m,expiredPage as h,otherAccountPage as g,outcomePage as _,signInPage as v}from"./credentials-page/outcome-pages.js";import{loadPageSite as y}from"./credentials-page/site-branding.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t,i=new a(t.gatewaySecretSeed);if(e.req.method===`GET`){let n=await y(t),a=e.req.query(`token`)??``,o=await i.peekElicitation(r,a);return o?R(o,t,n)??M({secretStore:i,kv:r,site:n,token:a,target:o},{},200):L(n)}if(e.req.method===`POST`){let a=await y(t),o=await e.req.formData(),s=F(o,`token`),c=await i.peekElicitation(r,s);if(!c)return L(a);let l=R(c,t,a);if(l)return l;let d={secretStore:i,kv:r,site:a,token:s,target:c,form:o,ctx:t};switch(F(o,`action`)){case n.remove:return O(d,k(c,F(o,`scheme`)));case n.removeAll:return O(d,u(c));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=u(t),a=i.map((e,t)=>F(n,d(`client_id`,t)).trim()),o=t=>M(e,{error:t,clientIds:a},400),s=T(i,n);if(`error`in s)return o(s.error);if(s.writes.length===0)return o(E(i));let c=[];for(let e of s.writes){if(e.kind!==`exchange`){c.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),o(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));c.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,c)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let o=F(t,d(`secret`,r)).trim();if(o){let t=i(a.auth,o);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,o)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let s=F(t,d(`client_id`,r)).trim(),c=F(t,d(`client_secret`,r)).trim();if(s&&c)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:s,clientSecret:c});else if(s||c)return{error:D(e,r,s?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{secretStore:n,kv:r,target:i}=e,a=await n.getStoredSchemes(r,i.subject,i.api),o=t.filter(e=>a[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return o.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,o)}function k(e,t){let n=S.test(t)?u(e)[Number(t)]:void 0;return n?[n]:[]}async function A({secretStore:e,kv:t,site:n,token:r}){return await e.consumeElicitation(t,r)?I(n,m(),200):L(n)}async function j({secretStore:e,kv:t,site:n,token:r},i){let a=await e.consumeElicitation(t,r);if(!a)return L(n);for(let n of i)n.kind===`remove`?await e.deleteSecret(t,a.subject,a.api,n.scheme):await e.setSecret(t,a.subject,a.api,n.scheme,n.secret);let o=await e.getStoredSchemes(t,a.subject,a.api),s={action:i.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:i.map(e=>e.scheme),stored:Object.keys(o).sort()};return I(n,_(a,s),200)}async function M({secretStore:e,kv:t,site:n,token:r,target:i},a,o){let s=await e.getStoredSchemes(t,i.subject,i.api);return I(n,p({site:n,target:i,token:r,stored:s,...a}),o)}async function N(e,t,n){try{let r=o([{url:e.tokenUrl}]),a=s(e.tokenUrl,r),u=new AbortController,d=setTimeout(()=>u.abort(),3e4),f;try{f=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:u.signal,dispatcher:c()})}finally{clearTimeout(d)}if(!f.ok)return P(`token endpoint returned ${f.status}`);let p;try{p=await l(f,65536)}catch{return P(`token response exceeded the size cap`)}let m;try{m=JSON.parse(p)}catch{return P(`token response was not valid JSON`)}let h=typeof m==`object`&&m&&`access_token`in m?m.access_token:void 0,g=typeof h==`string`?h.trim():``;return g?i(e,g)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${g}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(f(t,e),{status:n,headers:b})}function L(e){return I(e,h(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,g(o?.email),403);let c=`${e(t.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,v(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:N(i,e)}}function _(e,t){return Object.keys(e).length>1?t:void 0}async function v(e){let{token:t,url:n}=await C(e);return s({inputRequests:{[l]:s.elicitUrl({message:E(e),url:n})},requestState:t})}async function y(e){let{url:t}=await C(e);return P(e,t,T(e.subject))}function b(
|
|
3
|
-
`);if(
|
|
4
|
-
`);let a=
|
|
5
|
-
`);let o=n?`api: "${
|
|
6
|
-
`)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:N(r,c)}}function w(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function T(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function E({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=D(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``,o=k(A(n)),s=o?j(n)?` The AI agent asked for this scheme, so the stored credentials (${o}) were not sent.`:` This operation does not take the stored credentials (${o}).`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${O(i)} needs credentials.${a}${s} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function D({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function O(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(e,t=`, `){return e.map(e=>`"${e}"`).join(t)}function A(e){return e.kind===`authFailure`?e.unsentStoredSchemes??[]:[]}function j(e){return e.kind===`authFailure`&&e.isSchemeRequested===!0}function M(e,t){let n=k(A(t));if(!n)return[];let r=k(e.acceptedSchemes??[e.scheme],` or `);return j(t)?[`The stored credentials of this API (${n}) were not sent: the call set securityScheme to ${r}.`,`Without securityScheme, the server sends a stored credential when the operation takes one.`]:[`The stored credentials of this API (${n}) were not sent: this operation takes only ${r}.`,`If the user has no credential for ${r}, tell them that this operation does not take the stored credentials, and do not retry it.`]}function N(
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t,MCP_CREDENTIALS_ROUTE as n}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as o,inputRequired as s,inputResponse as c}from"@modelcontextprotocol/server";const l=`credentials`,u=/* @__PURE__ */ new Map;function d(e,t){let n=u.get(e);if(n)return n;let r=t().finally(()=>{u.delete(e)});return u.set(e,r),r}function f(e){return!!(e.envelope?.[o])?.elicitation?.url}function p(e){return e.envelope!==void 0}function m(e){let t=c(e,l);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function h(e,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${t}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
|
|
2
|
+
`)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:N(i,e)}}function _(e,t){return Object.keys(e).length>1?t:void 0}async function v(e){let{token:t,url:n}=await C(e);return s({inputRequests:{[l]:s.elicitUrl({message:E(e),url:n})},requestState:t})}async function y(e){let{url:t}=await C(e);return P(e,t,T(e.subject))}function b(e,{schemeLabel:n,canManageCredentials:r}){let i=S(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
|
|
3
|
+
`);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...x(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${t}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
|
|
4
|
+
`);let a=e.status===401?`The "${e.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${e.name}" API rejected the request with ${i}.`;if(!r)return[a,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
|
|
5
|
+
`);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"`;return[a,``,...x(e),`Do not retry the same call. Call \`${t}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
|
|
6
|
+
`)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:N(r,c)}}function w(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function T(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function E({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=D(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``,o=k(A(n)),s=o?j(n)?` The AI agent asked for this scheme, so the stored credentials (${o}) were not sent.`:` This operation does not take the stored credentials (${o}).`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${O(i)} needs credentials.${a}${s} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function D({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function O(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(e,t=`, `){return e.map(e=>`"${e}"`).join(t)}function A(e){return e.kind===`authFailure`?e.unsentStoredSchemes??[]:[]}function j(e){return e.kind===`authFailure`&&e.isSchemeRequested===!0}function M(e,t){let n=k(A(t));if(!n)return[];let r=k(e.acceptedSchemes??[e.scheme],` or `);return j(t)?[`The stored credentials of this API (${n}) were not sent: the call set securityScheme to ${r}.`,`Without securityScheme, the server sends a stored credential when the operation takes one.`]:[`The stored credentials of this API (${n}) were not sent: this operation takes only ${r}.`,`If the user has no credential for ${r}, tell them that this operation does not take the stored credentials, and do not retry it.`]}function N(t,r){let i=new URL(e(n),t);return i.searchParams.set(`token`,r),i.toString()}function P({target:e,reason:t,hasExistingSecret:n},r,i){let a=n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`,o=A(t).length>0?`Once the user confirms they saved a credential for ${k(e.acceptedSchemes??[e.scheme],` or `)}, retry the call that needed it`:`Once the user confirms they saved them, retry the call that needed them`,s=[`**Stop and show the user this link. They have to open it in a browser to ${a} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],...M(e,t),i?`${o} with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`${o} - the credentials are applied server-side and never appear in the conversation.`],c=t.kind===`authFailure`?t.otherApiNames??[]:[];if(c.length>0){let e=c.map(e=>`"${e}"`).join(`, `);s.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return s.join(`
|
|
7
7
|
`)}export{l as CREDENTIALS_INPUT_REQUEST_KEY,g as acceptedCredentialsLink,h as buildCredentialsAcceptedHint,b as buildCredentialsToolHint,y as buildUpstreamCredentialFallback,v as buildUpstreamCredentialInputRequired,m as credentialElicitationAnswer,d as dedupeElicitation,p as isStatelessRequest,_ as schemeLabelOf,f as supportsUrlElicitation};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{CALL_API_WRITE_TOOL_NAME as n,MANAGE_API_CREDENTIALS_TOOL_NAME as r}from"../../constants.js";import{formatError as i}from"../tool-errors.js";import{callAttribution as a}from"../audit.js";import{isToolDisabledByCaller as o}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as s}from"../codemode/constants.js";import{resolveSecretSubject as c}from"./subject.js";import{ipRateLimitKey as l}from"../rate-limit.js";import{callableApis as u,excludedOperations as d}from"./eligibility.js";import{getOfferedWriteHttpMethods as f,getSafeHttpMethods as p,getWriteHttpMethods as m}from"./allowed-http-methods.js";import{apiCallOperationsOf as h}from"./api-call-operations.js";import{GatewayFetchUserError as g}from"./fetch/fetch-errors.js";import{SecretStore as _}from"./secret-store.js";import{credentialHeadersOf as v,orderedSchemesOf as y,resolveUpstreamApiAuth as b}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as x,buildCredentialsAcceptedHint as S,buildCredentialsToolHint as C,buildUpstreamCredentialFallback as w,buildUpstreamCredentialInputRequired as T,credentialElicitationAnswer as E,dedupeElicitation as D,isStatelessRequest as O,schemeLabelOf as k,supportsUrlElicitation as A}from"./elicitation.js";import{buildAllowedOriginMatchers as j}from"./fetch/allowed-hosts.js";import{buildFetchBridge as M}from"./fetch/fetch-bridge.js";import{applyFetchCount as N}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as P,upstreamAuthKey as F}from"./upstream-auth.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(e){return new Map(e.map(e=>[e.relativePath,b(e)]))}function R(e,t,n,r,i,o,s,c){return M({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:j(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:v(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:y(i.schemes),operations:h(t.fullDefinition,t.definition,t.servers,d(e,t.relativePath))}}),onAuthRequired:i,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:a(e),refuseMethod:t=>z(e,c,t)})}function z(e,t,r){if(!t.includes(r))return f(e).includes(r)?`fetch sends safe methods only. Use the \`${n}\` tool for ${r} requests.`:`${r} is not allowed: ${m(e.config.mcp).includes(r)?`this client cannot send write requests`:`this call sends only ${t.join(`, `)} requests`}. Explain the call to the user instead of making it.`}function B(e){let{callerSubject:t,clientIp:n}=a(e),r={subject:t,ip:n&&l(n)};return async()=>{let t=await N(e.kv,r,s,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new g(t.message)}}async function V(e,t){if(t)try{return await new _(e.gatewaySecretSeed).getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${i(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,allowedHttpMethods:i,run:a},s){let l=c(e,t);if(l.kind===`invalid`)return{content:[{type:`text`,text:l.message}],isError:!0};let d=l.kind===`resolved`?l.subject:void 0,[f,m]=await Promise.all([u(e),V(e,d)]),h=L(f),g=[],_=new AbortController,v=await a(R(e,f,h,m,e=>g.push(e),s,_.signal,i??p(e.config.mcp))).finally(()=>_.abort());if(g.length===0)return v;let y=P(g).map(e=>q(e,h));if(l.kind===`anonymous`)return y.some(e=>e.schemes)?K(v,[{type:`text`,text:l.message}]):K(v,[{type:`text`,text:Z(y,{plans:h,canManageCredentials:!1})},...v.content]);let b=O(n.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${b?`2026-07-28`:`2025`} urlElicitation=${A(n.mcpReq)}`);let x={ctx:e,serverContext:n,subject:l.subject,stored:J(m),plans:h,canManageCredentials:!o(r,e.metadata)},S=b?await $(x,y,!s.some(W)):await ee(x,y);switch(S.kind){case`inputRequired`:return S.result;case`prependText`:return K(v,[{type:`text`,text:S.text},...v.content]);case`none`:return v}}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{...
|
|
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(F({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(F(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?k(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>C(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,stored:i},a){let[o,...s]=a,c=r.get(o.api),l=o.scheme??c.defaultScheme,u=o.schemes&&o.schemes.length>1?o.schemes:void 0;return{subject:n,baseUrl:t(e.request),target:{api:o.api,name:o.name,scheme:l,schemeLabel:u?void 0:X(o,r),acceptedSchemes:u},auth:c.schemes[l]??{kind:`raw`},apiAuth:c,secretStore:new _(e.gatewaySecretSeed),kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:o.status,detail:o.detail,otherApiNames:s.map(e=>e.name),unsentStoredSchemes:Object.keys(c.schemes).filter(e=>i.has(F({api:o.api,scheme:e}))),isSchemeRequested:o.isSchemeRequested}}}async function $(e,n,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=E(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 x(a.mcpReq.requestState(),{secretStore:new _(i.gatewaySecretSeed),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:S(n,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!A(a.mcpReq)?{kind:`prependText`,text:await w(d)}:{kind:`inputRequired`,result:await T(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 D(`${e.subject}:${F(n[0])}`,()=>w(r))}}export{H as runExecuteWithGateway};
|
|
@@ -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 d(e),e.mcpMode,!a(
|
|
1
|
+
import{publicOrigin as e}from"../../../../utils/request-origin.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,MANAGE_API_CREDENTIALS_TOOL_NAME as n,READ_ONLY_ANNOTATIONS as r,REMOVE_API_CREDENTIALS_TOOL_NAME as i}from"../../constants.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{createSessionHandle as o,resolveSecretSubject as s}from"./subject.js";import{toolNameForMode as c}from"../codemode/tool-declarations.js";import{apiTitleKey as l,countApiTitles as u}from"../tools/api-titles.js";import{callableApis as d}from"./eligibility.js";import{SecretStore as f}from"./secret-store.js";import{resolveUpstreamApiAuth as p}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as m,buildCredentialsAcceptedHint as h,buildUpstreamCredentialFallback as g,buildUpstreamCredentialInputRequired as _,credentialElicitationAnswer as v,dedupeElicitation as y,isStatelessRequest as b,schemeLabelOf as x,supportsUrlElicitation as S}from"./elicitation.js";import{upstreamAuthKey as C}from"./upstream-auth.js";async function w(e){return(await d(e)).length>0}const T={schema:{name:t,title:`Create anonymous session`,description:`Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:r,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!a(`createAnonymousSession`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:o()};return{content:[{type:`text`,text:JSON.stringify(e)}],structuredContent:e}}};function E(e,t,n){let r=e.map(e=>e.relativePath),i=[...r,...k(e)],a={type:`string`,description:`${n}: its \`filePath\` or the \`name\` from \`${c(`list-apis`,t)}\`.${r.length>0?` The file paths are: ${r.join(`, `)}.`:``}`,minLength:1};return i.length>0&&(a.enum=i),a}const D={type:`string`,description:`Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.`,minLength:1};function O(e,t,r){return{name:n,title:`Manage API credentials`,description:[r?`Get a secure link where the user sets or replaces the credentials this server sends to a documented API.`:`Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.`,r?`Call it when the user wants to change an API key, or when a tool result tells you the stored credentials were rejected. To remove stored credentials, call \`${i}\` instead.`:`Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.`,`The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.`,`It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument.`].join(`
|
|
2
|
+
`),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,t,`The API to manage credentials for`),scheme:{type:`string`,description:`Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.`,minLength:1},sessionHandle:D}}}}function k(e){let t=u(e);return e.map(e=>e.name).filter(e=>t.get(l(e))===1)}function A(e,t){let n=e.find(e=>e.relativePath===t||e.name===t);if(n)return{api:n};let r=e.map(e=>e.relativePath).join(`, `);return{error:N(`Unknown API "${typeof t==`string`?t:``}". Credentials can only be managed for the APIs this server can call: ${r||`none`}.`)}}function j(e,t,n){return N(`Unknown scheme "${e}" for api "${t.relativePath}". The security schemes this server can store credentials for are: ${n.join(`, `)}.`)}async function M(t,n,r){let i=new f(n.gatewaySecretSeed),a=s(n,t.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:o}=a,c=A(await d(n),t.api);if(`error`in c)return c.error;let{api:l}=c,u=e(n.request),w=v(r?.mcpReq.inputResponses);if(w===`accepted`){let e=await m(r?.mcpReq.requestState(),{secretStore:i,kv:n.kv,subject:o,baseUrl:u,apis:[l.relativePath]});return{content:[{type:`text`,text:h(l.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(w===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${l.name}" API, so this call minted no link.`}],isError:!1};let T=p(l),E=typeof t.scheme==`string`?t.scheme:void 0,D=Object.keys(T.schemes);if(E&&!T.schemes[E])return j(E,l,D);let O=E??T.defaultScheme,k={subject:o,baseUrl:u,target:{api:l.relativePath,name:l.name,scheme:O,schemeLabel:E?x(T.schemes,E):void 0},auth:T.schemes[O],apiAuth:T,secretStore:i,kv:n.kv,hasExistingSecret:await i.hasSecret(n.kv,o,l.relativePath,O),reason:{kind:`requested`}};if(r&&b(r.mcpReq)&&S(r.mcpReq))return _(k);let M=C({api:l.relativePath,scheme:O});return{content:[{type:`text`,text:await y(`${o}:${M}`,()=>g(k))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await d(e),e.mcpMode,!a(i,e.metadata)),isAvailable:async e=>!a(`manageApiCredentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n?.serverContext)};function F(e,t,r){return{name:i,title:`Remove API credentials`,description:[`Delete the credentials this server stores for the caller and sends to documented APIs. The user opens no link.`,`Call it only when the user asks to remove, clear, or forget their credentials.${r?` To replace a credential, call \`${n}\` instead.`:``}`,`Pass api to remove the credentials of one API, and add scheme to remove only one of them. To remove the credentials of every API, pass all: true instead of api.`].join(`
|
|
3
|
+
`),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,t,`The API to remove credentials for`),scheme:{type:`string`,description:`Name of the security scheme to remove the credential for, as named in the API description. Needs api. Omit it to remove every credential of the API.`,minLength:1},all:{type:`boolean`,description:`Set to true, without api, to remove the credentials of every API. Use it only when the user asks to remove all their credentials.`},sessionHandle:D}}}}async function I(e,t){let n=new f(t.gatewaySecretSeed),r=s(t,e.sessionHandle);if(r.kind!==`resolved`)return N(r.message);let{subject:i}=r,a=await d(t),o=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return o===void 0?e.all===!0?L(await n.deleteSecrets(t.kv,i),a,`No credentials are stored for this caller, so nothing was removed.`):N(`Name the api to remove credentials for. To remove the credentials of every API, pass all: true instead.`):N(`Pass api together with scheme "${o}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let c=A(a,e.api);if(`error`in c)return c.error;let{api:l}=c;if(o===void 0)return L(await n.deleteSecrets(t.kv,i,l.relativePath),a,`No credentials are stored for the "${l.name}" API, so nothing was removed.`);let u=Object.keys(p(l).schemes);if(!u.includes(o))return j(o,l,u);let m=`No credential is stored for the "${o}" scheme of the "${l.name}" API, so nothing was removed.`;return await n.hasSecret(t.kv,i,l.relativePath,o)?(await n.deleteSecret(t.kv,i,l.relativePath,o),L([{api:l.relativePath,scheme:o}],a,m)):L([],a,m)}function L(e,t,n){if(e.length===0)return{content:[{type:`text`,text:n}],isError:!1};let r=/* @__PURE__ */ new Map;for(let{api:t,scheme:n}of e)r.set(t,[...r.get(t)??[],n]);return{content:[{type:`text`,text:[`Removed the stored credentials:`,...[...r].map(([e,n])=>`- "${t.find(t=>t.relativePath===e)?.name??e}" (${e}): ${n.sort().join(`, `)}`),``,`This server no longer sends them. The next call that an API rejects with HTTP 401 asks the user for new credentials.`].join(`
|
|
4
|
+
`)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!a(n,e.metadata)),isAvailable:async e=>!a(`removeApiCredentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{D as SESSION_HANDLE_PROPERTY,T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{notFoundResponse as e}from"../../../../../server/plugin-context.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{isMcpHidden as n,isPublicEndpointServed as r,resolveMcpAccess as i}from"./config-gate.js";import{AI_METADATA_HEADER as a}from"../constants.js";import{formatError as o,jsonRpcErrorResponse as s}from"./tool-errors.js";import{buildMcpFileTools as c,createCustomTool as l,invokeCustomTool as u}from"./custom-tools.js";import{authorizeMcpRequest as d}from"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p,resolveRequestInstructionsStyle as m,resolveRequestMcpMode as h}from"./mode.js";import{narrowMcpConfigForCaller as g}from"./gateway/caller-api-calls.js";import{isGatewayEnabled as _}from"./gateway/env.js";import{userSubject as v}from"./gateway/subject.js";import{parseUserAgent as y}from"./mcp-client.js";import{createMcpTelemetry as b}from"./mcp-telemetry.js";import{applyMcpRateLimit as x}from"./rate-limit.js";import{createToolRegistry as S}from"./tool-registry.js";import{mcpToolRegistry as C}from"./registry-instance.js";const w=`POST`;function T(e){return(e??``).split(`,`).some(e=>{let[t,...n]=e.split(`;`).map(e=>e.trim().toLowerCase());if(t!==`text/html`)return!1;let r=n.find(e=>e.startsWith(`q=`));return r===void 0||Number(r.slice(2))>0})}function E(){return s(405,`Method not allowed`,{Allow:w})}function D(e){let t={error:`Method Not Allowed`,message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${e}`};return new Response(JSON.stringify(t),{status:405,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,Allow:w}})}function O(){return s(501,`MCP transport is not available in this environment`)}function k(e){if(!e)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function A(e,t,n,r){let i=k(e.headers.get(a)),{userAgent:o}=t.request,{client:s,clientVersion:c}=y(o),l=h(e.url,p()),u=crypto.randomUUID(),d=v(t.request.viewer),f=t.request.ip??void 0;return{config:{...t.config,mcp:g(t.config.mcp,i)},entities:t.entities,hasRoute:e=>t.hasRoute(e),isSlugVisible:(e,n)=>t.isSlugVisible(e,n),kv:t.kv,gatewaySecretSeed:t.gatewaySecretSeed,logger:t.logger,pageMarkdown:t.pageMarkdown,search:t.search,request:t.request,metadata:i,mcpMode:l,instructionsStyle:m(e.url),requestId:u,executeDeadline:r,messageId:typeof i.messageId==`string`?i.messageId:void 0,callerSubject:d,client:s,clientVersion:c,accessToken:n.accessToken,isProtected:n.isProtected??!1,isAvailableMemo:/* @__PURE__ */ new Map,subprocess:t.subprocess,claims:n.claims,telemetry:b({userAgent:o,request:e,metadata:i,mode:l,requestId:u,callerSubject:d,clientIp:f,logger:t.logger})}}async function j(e){let t=_(e.config)?(await import(`./gateway/tool-list.js`)).gatewayTools():[],n=e.subprocess?e.mcpToolEntries??[]:[],r=C.list(),i=/* @__PURE__ */ new Set([...r.map(e=>e.schema.name),...t.map(e=>e.schema.name),...n.map(e=>e.declaration.name)]),a=e.subprocess?await c({entities:e.entities,loadContentModule:e.loadContentModule,reservedNames:i,logger:e.logger}):[];if(t.length===0&&n.length===0&&a.length===0)return C;let o=S();for(let e of r)o.register(e);for(let e of t)o.register(e);for(let e of n)o.register(l(e));for(let e of a)o.register(e);return o}async function M(e,t,n,r={}){let i=await j(e),a;try{a=await import(`./mcp-server.js`)}catch(t){return e.logger?.error(`MCP transport failed to load: ${o(t)}`),async()=>O()}let s;return a.createMcpRequestHandler({registry:i,logger:e.logger,buildToolContext:r=>s??=A(r,e,t,n),onError:r.onError})}function N(a={}){return async(o,s,c)=>{let l=Date.now()+f;if(n(c.config)||a.publicEndpoint&&!r(c.config,i(c.config)))return e();if(o.req.method===`GET`&&T(o.req.header(`accept`)))return s();let u=await x({kv:c.kv,ip:c.request.ip,bucket:`mcp`,logger:c.logger});if(u)return u;let p=await d({c:o,ctx:c,forceAnonymous:a.forceAnonymous});return p.kind===`deny`?p.response:o.req.method===`GET`?D(`${t(c.request)}${new URL(c.request.url).pathname}`):o.req.method===`POST`?(await M(p.ctx,{isProtected:p.isProtected,accessToken:p.accessToken,claims:p.claims},l))(o.req.raw):E()}}const P=N(),F=N({forceAnonymous:!0,publicEndpoint:!0});export{A as buildToolContext,N as createMcpHandler,M as createServedMcpRequestHandler,u as invokeCustomTool,P as mcp,F as mcpPublic};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{isObject as e}from"../../../../../shared/utils/is-object.js";import{CALL_API_WRITE_TOOL_NAME as t,CREATE_ANONYMOUS_SESSION_TOOL_NAME as n,DISCOVER_TOOL_NAME as r,EXECUTE_TOOL_NAME as i,LIST_WORKFLOWS_TOOL_NAME as a}from"../constants.js";import{formatError as o}from"./tool-errors.js";import{auditToolCall as s,callAttribution as c}from"./audit.js";import{CODE_MODE_TOOL_NAMES as l,FETCH_TOOL_NAME as u}from"./codemode/constants.js";import{resolveMcpMode as d,resolveRequestMcpMode as f}from"./mode.js";import{sendMcpRequestError as p}from"./mcp-telemetry.js";import{availableTools as m,isToolAvailable as h,normalizeToolDisplayName as g}from"./tool-registry.js";import{mcpJsonSchemaValidator as _}from"./json-schema-validator.js";import{toToolListEntries as v}from"./codemode/tool-list.js";import{buildCodeModeInstructions as y,buildExecuteDescription as b,buildToolsModeInstructions as x}from"./codemode/prompts.js";import{composeExecuteAnnotations as S,getActiveCapabilities as C}from"./codemode/capabilities.js";import{discover as w,discoverSchema as T}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as E,executeOutputSchema as D,executeToolTitle as O}from"./codemode/execute-schema.js";import{runCodeMode as k}from"./codemode/index.js";import{docsServerInfo as A}from"./server-info.js";import{loadSkillResources as j}from"./skills-resources.js";import{randomUUID as M}from"node:crypto";import{McpServer as N,createMcpHandler as P,fromJsonSchema as F,isCallToolResult as I,isInputRequiredResult as L}from"@modelcontextprotocol/server";const R=`text/markdown`,z={listChanged:!1};function B(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a,_meta:o}=g(e);return{title:t,description:n,inputSchema:F(r,_),outputSchema:i?F(i,_):void 0,annotations:a,_meta:o}}function V(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function H(t,n){if(I(t)||L(t))return t;let r=[{type:`text`,text:typeof t==`string`?t:JSON.stringify(t)}];return n===`code`&&e(t)?{content:r,structuredContent:t}:{content:r}}function U(e,t){return(n,r)=>s(e,t.schema.name,n,async()=>H(await t.execute(n,e,{serverContext:r}),e.mcpMode))}function W(e,t){return new N(e,{capabilities:{logging:{},tools:z},maxToolInputElements:1e4,instructions:t})}async function G(e,o,c){let[d,f]=await Promise.all([m(c,o),C(o)]),p=f.some(e=>e.id===u),g=d.some(({schema:e})=>e.name===t),_=d.some(({schema:e})=>e.name===a),x=d.filter(e=>!l.has(e.schema.name)).map(e=>e.schema),A=d.filter(({schema:e})=>l.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),j=o.instructionsStyle!==`brief`,M=j?v(x,f):[],N=A.some(e=>e.schema.name===n),P=W(e,y({hasFetch:p,toolList:M,docsUrl:e.websiteUrl,hasCallApiWrite:g,hasWorkflows:_})),F=S(x,f);P.registerTool(i,B({...V(N,E),title:O(F),description:b(p,M,e.websiteUrl),outputSchema:D(p),annotations:F}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,r=t=>s(o,i,e,()=>k({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:c,ctx:o,hostFetch:t}));if(!p)return r();let{runExecuteWithGateway:a}=await import(`./gateway/index.js`);return a({ctx:o,sessionHandle:n,serverContext:t,run:r})});let I=w(x,async e=>{let t=c.get(e);return t!==void 0&&await h(t,o)},f,o);P.registerTool(r,B(T(x,f,j)),e=>s(o,r,e,()=>I(e)));for(let e of A)P.registerTool(e.schema.name,B(V(N,e.schema)),U(o,e));return P}async function K(e,t,n){let r=new Map((await m(n,t)).map(e=>[e.schema.name,e])),i=W(e,x(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,B({...n.schema,outputSchema:void 0}),U(t,n));r.has(n.schema.name)||a.disable()}return i}async function q(e,t,n){let r=A(e.config,e.request),i=e.mcpMode===`code`?await G(r,e,t):await K(r,e,t);n.length>0&&i.server.registerCapabilities({resources:z});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:R},async()=>({contents:[{uri:e.uri,mimeType:R,text:await e.read()}]}));return i}function J(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function Y(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function X(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await j(n),i=await q(n,e.registry,r),a=P(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),J(o)}catch(r){if(e.onError)await e.onError(r);else{let i=n?c(n):{requestId:M()};e.logger?.error(`MCP request failed: ${o(r)}`,{request_id:i.requestId}),p(r,f(t.url,d()),{logger:e.logger,caller:i})}return Y()}}}export{X as createMcpRequestHandler,B as toRegisterToolConfig};
|
|
@@ -1 +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"../constants.js";import{innerToolErrorClass as i,thrownErrorClass as a}from"./tool-errors.js";import{auditCode as o,auditInput as s,auditSha256 as c,auditStack as l,isCallToolResult as u,toolOutputText as d,toolResultText as f}from"./audit.js";import{SANDBOX_FAILURE as p}from"./codemode/constants.js";import{parseUserAgent as m,readListingSource as h}from"./mcp-client.js";import{randomUUID as g}from"node:crypto";import{ulid as _}from"ulid";const v={id:`docs`,object:`mcpServer`,uri:`urn:redocly:realm:mcp:server:docs`};function y(e){if(e===void 0)return;let t=c(e);return{id:t,object:`user`,uri:`urn:redocly:realm:mcp:subject:${t}`}}function b(n){let{mode:c,requestId:g,callerSubject:_,clientIp:b,logger:x}=n,S=n.env??process.env,C=t(S),w=y(_),{client:T,clientVersion:E}=m(n.userAgent),D=n.metadata.messageId,O={client:T,client_version:E,message_id:typeof D==`string`?D:void 0,listing_source:h(n.request)},j=[],M=/* @__PURE__ */ new Set,N=/* @__PURE__ */ new WeakSet,P=(e,t)=>{j.push({type:e,data:[t],requestId:g,time:/* @__PURE__ */ new Date,actor:w,clientIp:b})},F=t=>{try{t()}catch(t){x?.warn(`MCP telemetry failed: ${e(t)}`)}},I=(e,t,n)=>P(`com.redocly.mcpServer.toolCalled`,{...v,tool:e,mode:c,output_length:n,duration_ms:t,...O}),L=(e,t,n)=>{n.stack&&x?.error(`MCP tool ${e} failed (${n.error_class})`,{request_id:g,stack:n.stack}),P(`com.redocly.mcpServer.error`,{...v,tool:e,mode:c,duration_ms:t,message:s(n.message),stack:l(n.stack),error_class:n.error_class,...O})},R=async(t,n,r)=>{let a=Date.now(),o;try{o=await n()}catch(n){let o=i(n),s=o===`server_error`;throw r.set(e(n),{tool:t,reason:s?`server_error`:`inner_tool_error`}),F(()=>L(t,Date.now()-a,{message:e(n),stack:s&&n instanceof Error?n.stack??``:``,error_class:o})),n}return F(()=>I(t,Date.now()-a,d(o).length)),o};return{toolReturned(e,t,n){F(()=>{if(!u(n)||n.isError!==!0){I(e,t,d(n).length);return}N.has(n)||L(e,t,{message:f(n,` `),stack:``,error_class:e===`execute`?`sandbox_error`:`tool_error`})})},toolThrew(t,n,r){F(()=>{let i=a(r);L(t,n,{message:e(r),stack:i===`server_error`&&r instanceof Error?r.stack??``:``,error_class:i})})},trackCodeExecution(t,n){let r=Date.now(),i=o(t),a=/* @__PURE__ */ new Map,s=0;return{hostFetch:n&&(t=>(s+=1,n(t).catch(t=>{throw a.set(e(t),{reason:`runtime_error`}),t}))),innerToolCall(e,t){let n=R(e,t,a),r=n.then(()=>void 0,()=>void 0);return M.add(r),r.then(()=>M.delete(r)),n},finish(e,t,n){let o=e.failure===p.HostError&&e.error!==void 0?a.get(e.error):void 0;o?.tool&&N.add(t);let c=e.error===void 0?`ok`:`error`,l=Date.now()-r,u=k(e.failure,o,n),d=o?.tool;F(()=>P(`com.redocly.mcpServer.codeExecuted`,{...v,code_sha256:i.sha256,code_length:i.length,fetch_count:s,outcome:c,flags:i.flags,duration_ms:l,failure_reason:u,failed_tool:d,...O})),x?.info(`Gateway MCP code executed [${i.sha256.slice(0,12)}] outcome=${c} codeLength=${i.length} fetchCount=${s}`+(i.flags?` flags=${i.flags}`:``)+` durationMs=${l}`+(u?` failureReason=${u}`:``)+(d?` failedTool=${d}`:``))}}},gatewayFetchPerformed({host:e,method:t,outcome:n,durationMs:r,path:i,api:a,status:o,bytes:s,injectedScheme:c}){F(()=>P(`com.redocly.mcpServer.gatewayFetchPerformed`,{...v,host:e,method:t,outcome:n,path:i,api:a,status:o,injected_scheme:c,bytes:s,duration_ms:r})),x?.info(`Gateway MCP fetch [${t} ${e}] outcome=${n}`+(i===void 0?``:` path=${i}`)+(a===void 0?``:` api=${a}`)+(o===void 0?``:` status=${o}`)+(c===void 0?``:` injectedScheme=${c}`)+(s===void 0?``:` bytes=${s}`)+` durationMs=${r}`)},gatewayFetchRateLimited({scope:e,limit:t,retryAfterSeconds:n}){F(()=>P(`com.redocly.mcpServer.gatewayFetchRateLimited`,{...v,scope:e,retry_after_seconds:n,limit:t}))},async flush(){if(!C){j=[];return}await A(M,300);let e=j;j=[],await r(e,{env:S,fetcher:n.fetcher,logger:x})}}}function x(e,t){let{requestId:r=g(),callerSubject:i,clientIp:a}=t.caller??{};return n({...e,requestId:r,actor:y(i),clientIp:a},t)}function S(e,t,n={}){return x({type:`com.redocly.mcpServer.error`,data:[{...v,message:s(e instanceof Error?e.message:``),stack:l(e instanceof Error?e.stack??``:``),error_class:`server_error`,mode:t}]},n)}function C({scope:e,retryAfterSeconds:t,limit:n},r={}){return x({type:`com.redocly.mcpServer.rateLimited`,data:[{...v,scope:e,retry_after_seconds:t,limit:n}]},r)}function w(e){let t=e||_(),n=t.startsWith(`mcp_`)?t:`mcp_${t}`;return{id:n,object:`mcpSession`,uri:`urn:redocly:realm:mcp:session:${n}`}}function T(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.started`,data:[{...w(e),redirect_uri:t}]},n)}function E(e,t,n={}){return x({type:`com.redocly.mcpServerAuthorization.completed`,data:[{...w(e),redirect_uri:t}]},n)}function D(e,t,n,r,i={}){return x({type:`com.redocly.mcpServerAuthorization.failed`,data:[{...w(e),error:n,error_details:r,error_class:t}]},i)}function O(e,t={}){return x({type:`com.redocly.mcpServerCard.served`,data:{id:`mcpServerCardId`,object:`mcpServerCard`,uri:`urn:redocly:realm:api:mcpServerCard:mcpServerCardId`,...e},signal:`trace`},t)}function k(e,t,n){return e===p.HostError?t?.reason??p.RuntimeError:e===p.RuntimeError&&n!==void 0?`unknown_tool`:e}async function A(e,t){if(e.size===0)return;let n;await Promise.race([Promise.allSettled(e),new Promise(e=>{n=setTimeout(e,t)})]),clearTimeout(n)}export{b as createMcpTelemetry,E as sendMcpAuthorizationCompleted,D as sendMcpAuthorizationFailed,T as sendMcpAuthorizationStarted,C as sendMcpRateLimited,S as sendMcpRequestError,O as sendMcpServerCardServed};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{getSessionIssuer as n}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as r}from"../../../../../../server/plugin-context.js";import{isMcpContentProtected as i,isMcpHidden as a,resolveMcpAccess as o}from"../config-gate.js";import{MCP_CALLBACK_ROUTE as s}from"../../constants.js";import{SUPPORTED_CODE_CHALLENGE_METHODS as c}from"./constants.js";import"../auth.js";import{sendMcpAuthorizationStarted as l}from"../mcp-telemetry.js";import{applyMcpRateLimit as u}from"../rate-limit.js";import{parseRedirectUri as d}from"./redirect-uri.js";import{fetchClientMetadataDocument as f,isClientMetadataDocumentUrl as p,isRedirectUriRegistered as m}from"./client-metadata.js";import{readMcpClient as h}from"./client-registry.js";import{reportMcpAuthorizationFailure as g,withMcpFailureReporting as _}from"./error-reporting.js";import{isSupportedCodeChallengeMethod as v,signMcpArtifact as y}from"./tokens.js";import{ulid as b}from"ulid";function x(e,t){return e.json({error:`invalid_request`,error_description:t},400)}async function S(e,t,n){if(p(t)){let r;try{r=await f(t)}catch(t){let n=`Unable to resolve client metadata document: ${t instanceof Error?t.message:String(t)}`;return await g(e,n),{ok:!1,error:n}}return{ok:!0,allowed:m(n,r.redirect_uris),clientName:r.client_name??null}}let r=(await h(e.kv,t))?.redirect_uris??[];return{ok:!0,allowed:r.length===0||m(n,r),clientName:null}}const C=_(w,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500));async function w(f,p){if(a(p.config)||!i(o(p.config)))return r();let m=n(f);if(!m)return r();let h=await u({kv:p.kv,ip:p.request.ip,bucket:`oauth`,logger:p.logger});if(h)return h;let g=new URL(f.req.url).searchParams,_=g.get(`redirect_uri`),C=g.get(`client_id`),w=g.get(`code_challenge`),T=g.get(`code_challenge_method`);if(!_||!d(_))return x(f,`redirect_uri must be an https URL, a loopback http URL, or a private-use scheme`);if(!C)return x(f,`client_id is required`);if(!w)return x(f,`code_challenge is required`);if(!T||!v(T))return x(f,`Unsupported code_challenge_method. Supported: ${c.join(`, `)}`);let E=await S(p,C,_);if(!E.ok)return f.json({error:`invalid_client`,error_description:E.error},400);if(!E.allowed)return x(f,`redirect_uri is not registered for this client`);let D=b(),O=await y({type:`mcp_context`,sessionId:D,redirectUri:_,clientId:C,clientName:E.clientName,state:g.get(`state`),codeChallenge:w,codeChallengeMethod:T},m.artifactSecret,Math.floor(Date.now()/1e3)+600);l(D,_,{logger:p.logger});let k=new URLSearchParams({redirectTo:`${s}/${O}`});return f.redirect(`${e(t.AuthIdpLogin)}?${k.toString()}`,302)}export{C as mcpAuthorize};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{REALM_SESSION_COOKIE as e}from"../../../../../../server/auth/constants.js";import{getBearerVerifier as t,getSessionIssuer as n}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as r}from"../../../../../../server/plugin-context.js";import{isMcpHidden as i}from"../config-gate.js";import{MCP_REFRESH_SESSION_LIFETIME_SEC as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import{auditInput as s}from"../audit.js";import{sendMcpAuthorizationCompleted as c}from"../mcp-telemetry.js";import{loadPageSite as l}from"../gateway/credentials-page/site-branding.js";import{isLoopbackRedirect as u,parseRedirectUri as d}from"./redirect-uri.js";import{isClientMetadataDocumentUrl as f}from"./client-metadata.js";import{reportMcpAuthorizationFailure as p,withMcpFailureReporting as m}from"./error-reporting.js";import{sessionClaimsFromSession as h,sha256Base64Url as g,signMcpArtifact as _,verifyMcpArtifact as v}from"./tokens.js";import{CONSENT_PAGE_HEADERS as y,consentInvalidPage as b,consentPage as x}from"./consent-page.js";import{hasConsent as S,saveConsent as C}from"./store.js";import{getCookie as w}from"hono/cookie";const T={"Cache-Control":`no-store`},E=`Missing context token`;function D(e){let t=e.searchParams.get(`context`);if(t)return t;let n=e.pathname.split(`/`).filter(Boolean).pop();return n&&n!==`callback`?n:null}async function O(n,r){let i=new URL(n.req.url),a=w(n,e),o=a?await t(n)?.(a):null;return{method:n.req.method,path:`${i.pathname}${i.search}`,referer:n.req.header(`referer`)??null,user_agent:r.request.userAgent,has_session_cookie:a!==void 0,has_user_session:!!o&&o?.claims.tokenUse!==`mcp_access_token`}}function k(a){return async(o,c)=>{if(i(c.config))return r();let l=n(o);if(!l)return r();let u=D(new URL(o.req.url));if(!u){let e=await O(o,c);return await p(c,E,{details:s(JSON.stringify(e)),logFields:e}),o.text(E,400,T)}let f,m,h;try{if(f=await v(u,l.artifactSecret,`mcp_context`),h=f.sessionId,o.set(`realmMcpSessionId`,h),m=d(f.redirectUri),!m)throw Error(`Invalid MCP context`)}catch(e){let t=await p(c,e,{sessionId:h,errorClass:`client_error`,logMessage:`MCP callback failed`});return o.text(`Invalid MCP callback: ${t}`,400,T)}let g=w(o,e),_=g?await t(o)?.(g):null;return!g||!_||_.claims.tokenUse===`mcp_access_token`?(await p(c,`Authentication required`,{sessionId:h}),o.text(`Authentication required`,401,T)):a(o,c,{issuer:l,contextToken:u,mcpContext:f,redirectUrl:m,sessionToken:g,session:_})}}async function A(e,t,{issuer:n,mcpContext:r,redirectUrl:i,session:o}){let s=Math.floor(Date.now()/1e3),l=await _({type:`mcp_auth_code`,sessionId:r.sessionId,clientId:r.clientId,redirectUri:r.redirectUri,claims:h(o),sessionExp:s+a,codeChallenge:r.codeChallenge,codeChallengeMethod:r.codeChallengeMethod},n.artifactSecret,s+600),u=new URL(i);return u.searchParams.set(`code`,l),r.state&&u.searchParams.set(`state`,r.state),c(r.sessionId,r.redirectUri,{logger:t.logger}),e.header(`Cache-Control`,`no-store`),e.redirect(u.toString(),302)}async function j(e,t,{mcpContext:n,redirectUrl:r}){let i=new URL(r);return i.searchParams.set(`error`,`access_denied`),n.state&&i.searchParams.set(`state`,n.state),await p(t,`access_denied`,{sessionId:n.sessionId}),e.header(`Cache-Control`,`no-store`),e.redirect(i.toString(),302)}function M({mcpContext:e,session:t}){return{idpId:t.claims.idpId,subject:t.viewer.sub,clientId:e.clientId,redirectUri:e.redirectUri}}function N({issuer:e,sessionToken:t,contextToken:n}){return _({type:`mcp_consent`,sessionHash:g(t),contextHash:g(n)},e.artifactSecret,Math.floor(Date.now()/1e3)+300)}async function P(e,{issuer:t,sessionToken:n,contextToken:r}){try{let i=await v(e,t.artifactSecret,`mcp_consent`);return i.sessionHash===g(n)&&i.contextHash===g(r)}catch{return!1}}const F=e=>e.text(`MCP authorization could not be completed`,500,T),I=m(k(async(e,t,n)=>{if(u(n.redirectUrl)||await S(t.kv,M(n)))return A(e,t,n);let{clientId:r,clientName:i}=n.mcpContext,{viewer:s}=n.session,c=x({site:await l(t),user:s.email||s.name||s.sub,clientName:i??void 0,clientIdHost:f(r)?new URL(r).host:void 0,redirectUrl:n.redirectUrl,scopes:o,accessLifetimeHours:a/3600,rememberDays:30,consentToken:await N(n)});return e.set(`realmCacheControlOwned`,!0),new Response(c,{status:200,headers:y})}),F),L=m(k(async(e,t,n)=>{let r=await e.req.formData().catch(()=>null),i=r?.get(`consent`);return typeof i!=`string`||!await P(i,n)?new Response(b(await l(t)),{status:403,headers:y}):r?.get(`decision`)===`allow`?(await C(t.kv,M(n)),A(e,t,n)):j(e,t,n)}),F);export{I as mcpCallback,L as mcpConsent};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{notFoundResponse as t}from"../../../../../../server/plugin-context.js";import{publicOrigin as n}from"../../../../utils/request-origin.js";import{isMcpContentProtected as r,isMcpHidden as i,resolveMcpAccess as a}from"../config-gate.js";import{MCP_AUTHORIZATION_SERVER_ROUTE as o,MCP_AUTHORIZE_ROUTE as s,MCP_REGISTER_ROUTE as c,MCP_ROUTE as l,MCP_TOKEN_ROUTE as u}from"../../constants.js";import{CORS_ANY_ORIGIN as d,SUPPORTED_MCP_GRANT_TYPES as f,SUPPORTED_MCP_SCOPES as p}from"./constants.js";import"../auth.js";function m(e){return!i(e.config)&&r(a(e.config))}function h(r,i){if(!m(i))return t();let a=n(i.request);return r.json({resource:`${a}${e(l)}`,authorization_servers:[a],bearer_methods_supported:[`header`],resource_documentation:`${a}${e(o)}`,scopes_supported:[...p],bearer_token_types_supported:[`Bearer`]},200,{...d})}function g(r,i){if(!m(i))return t();let a=n(i.request);return r.json({issuer:a,authorization_endpoint:`${a}${e(s)}`,token_endpoint:`${a}${e(u)}`,scopes_supported:[...p],registration_endpoint:`${a}${e(c)}`,response_types_supported:[`code`],grant_types_supported:[...f],subject_types_supported:[`public`],id_token_signing_alg_values_supported:[`RS256`],code_challenge_methods_supported:[`S256`],token_endpoint_auth_methods_supported:[`none`],client_id_metadata_document_supported:!0},200,{...d})}export{g as oauthAuthorizationServer,h as oauthProtectedResource};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{auditInput as e,auditStack as t}from"../audit.js";import{sendMcpAuthorizationFailed as n}from"../mcp-telemetry.js";import{randomUUID as r}from"node:crypto";function i(e){return e instanceof Error?e.name===`Error`?{message:e.message,details:e.stack?t(e.stack):null}:{message:e.name,details:null}:{message:String(e),details:null}}function a(n){if(!(n instanceof Error))return i(n);let r=e=>e.split(`
|
|
2
|
-
`,1)[0],a=n;for(;a.cause instanceof Error;)a=a.cause;let o=r(n.name===`Error`?n.message:`${n.name}: ${n.message}`),s=a===n?``:` (${r(a.message)})`;return{message:e(`${o}${s}`),details:n.stack?t(n.stack):null}}async function o(e,t,a={}){let{sessionId:o,logFields:s}=a,c=r(),l=typeof t==`string`?{message:t,details:null}:i(t),u=a.message??l.message,d=a.details===void 0?l.details:a.details,f=a.errorClass??(typeof t==`string`?`client_error`:`server_error`),p={request_id:c,mcp_session_id:o,...s};return typeof t==`string`?e.logger?.warn(a.logMessage??`MCP authorization refused`,{...p,error:u}):e.logger?.error(a.logMessage??`MCP authorization failed`,{...p,...d===null?{error:u}:{err:t}}),
|
|
2
|
+
`,1)[0],a=n;for(;a.cause instanceof Error;)a=a.cause;let o=r(n.name===`Error`?n.message:`${n.name}: ${n.message}`),s=a===n?``:` (${r(a.message)})`;return{message:e(`${o}${s}`),details:n.stack?t(n.stack):null}}async function o(e,t,a={}){let{sessionId:o,logFields:s}=a,c=r(),l=typeof t==`string`?{message:t,details:null}:i(t),u=a.message??l.message,d=a.details===void 0?l.details:a.details,f=a.errorClass??(typeof t==`string`?`client_error`:`server_error`),p={request_id:c,mcp_session_id:o,...s};return typeof t==`string`?e.logger?.warn(a.logMessage??`MCP authorization refused`,{...p,error:u}):e.logger?.error(a.logMessage??`MCP authorization failed`,{...p,...d===null?{error:u}:{err:t}}),n(o,f,u,d,{logger:e.logger,caller:{requestId:c,clientIp:e.request.ip??void 0}}),u}async function s(e,t,n,r,i){return await o(t,r,{sessionId:e.get(`realmMcpSessionId`),logMessage:i}),e.json({error:n,error_description:r},400)}function c(e,t){return async(n,r)=>{try{return await e(n,r)}catch(e){if(e instanceof Error&&`getResponse`in e)throw e;return await o(r,e,{...a(e),sessionId:n.get(`realmMcpSessionId`)}),t(n)}}}export{s as refuseMcpOAuth,o as reportMcpAuthorizationFailure,c as withMcpFailureReporting};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{notFoundResponse as e}from"../../../../../../server/plugin-context.js";import{isMcpContentProtected as t,isMcpHidden as n,resolveMcpAccess as r}from"../config-gate.js";import{CORS_ANY_ORIGIN as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o}from"./constants.js";import"../auth.js";import{applyMcpRateLimit as s}from"../rate-limit.js";import{writeMcpClient as c}from"./client-registry.js";import{withMcpFailureReporting as l}from"./error-reporting.js";import{ulid as u}from"ulid";function d(e){let t=e.client_name;if(typeof t==`string`&&Buffer.byteLength(t,`utf8`)>256)return{ok:!1,error:`client_name exceeds 256 bytes`};let n=e.redirect_uris;if(n!==void 0&&!Array.isArray(n))return{ok:!1,error:`redirect_uris must be an array`};if(Array.isArray(n)&&n.length>20)return{ok:!1,error:`redirect_uris must hold at most 20 entries`};let r=[];for(let e of Array.isArray(n)?n:[])if(typeof e==`string`&&e!==``){if(Buffer.byteLength(e,`utf8`)>512)return{ok:!1,error:`a redirect_uri exceeds 512 bytes`};r.push(e)}return{ok:!0,clientName:typeof t==`string`&&t?t:`MCP Client`,redirectUris:r}}const f=l(p,e=>e.json({error:`server_error`,error_description:`Unable to register client`},500,{...i}));async function p(l,f){if(n(f.config)||!t(r(f.config)))return e();let p=await s({kv:f.kv,ip:f.request.ip,bucket:`oauth`,logger:f.logger});if(p)return p;let m=await l.req.json().catch(()=>null);if(m!==null&&(typeof m!=`object`||Array.isArray(m)))return l.json({error:`invalid_request`,error_description:`Client metadata must be a JSON object`},400,{...i});let h=d(m??{});if(!h.ok)return l.json({error:`invalid_request`,error_description:h.error},400,{...i});let g=(/* @__PURE__ */ new Date()).toISOString(),_={client_id:`mcp_${u()}`,client_name:h.clientName,redirect_uris:h.redirectUris,grant_types:[...a],response_types:[`code`],scope:o.join(` `),subject_type:`public`,token_endpoint_auth_method:`none`,created_at:g,updated_at:g};return await c(f.kv,_),l.json(_,201,{...i})}export{f as mcpRegister};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{MCP_ACCESS_TOKEN_USE as e}from"../../../../../../server/auth/constants.js";import{getSessionIssuer as t}from"../../../../../../server/auth/middleware.js";import{notFoundResponse as n}from"../../../../../../server/plugin-context.js";import{isMcpHidden as r}from"../config-gate.js";import{MCP_ACCESS_TOKEN_TTL_SEC as i,SUPPORTED_MCP_GRANT_TYPES as a,SUPPORTED_MCP_SCOPES as o,TOKEN_RESPONSE_HEADERS as s}from"./constants.js";import{refuseMcpOAuth as c,withMcpFailureReporting as l}from"./error-reporting.js";import{signMcpArtifact as u,verifyMcpArtifact as d,verifyPkce as f}from"./tokens.js";import{redeemAuthorizationCode as p,redeemRefreshToken as m}from"./store.js";async function h(t,n,r,a){t.set(`realmCacheControlOwned`,!0);let l=Math.floor(Date.now()/1e3);if(l>=a.sessionExp)return c(t,n,`invalid_grant`,`Session has expired`);let d=Math.min(i,a.sessionExp-l),[f,p]=await Promise.all([r.mint({...a.claims,tokenUse:e},l+d),u({type:`mcp_refresh_token`,sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp},r.artifactSecret,a.sessionExp)]);return t.json({access_token:f,token_type:`Bearer`,expires_in:d,refresh_token:p,scope:o.join(` `)},200,{...s})}const g=l(_,e=>e.json({error:`server_error`,error_description:`The server could not complete the request`},500,{...s}));async function _(e,i){if(r(i.config))return n();let o=t(e);if(!o)return n();let s;try{s=await e.req.formData()}catch{return c(e,i,`invalid_request`,`Expected an application/x-www-form-urlencoded body`)}let l=s.get(`grant_type`);return typeof l!=`string`||!a.includes(l)?c(e,i,`invalid_request`,`Invalid grant type`):l===`refresh_token`?y(e,i,o,s):v(e,i,o,s)}async function v(e,t,n,r){let i=r.get(`code`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`Missing authorization code`);let a;try{a=await d(i,n.artifactSecret,`mcp_auth_code`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid authorization code`,`MCP token exchange failed`)}let o=r.get(`redirect_uri`);if(typeof o!=`string`||o!==a.redirectUri)return c(e,t,`invalid_grant`,`redirect_uri mismatch`);let s=r.get(`client_id`);if(typeof s!=`string`||s!==a.clientId)return c(e,t,`invalid_grant`,`Client mismatch`);let l=r.get(`code_verifier`);return typeof l!=`string`||l===``?c(e,t,`invalid_grant`,`code_verifier required`):f(a.codeChallenge,a.codeChallengeMethod,l)?await p(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Authorization code already used`):c(e,t,`invalid_grant`,`code_verifier mismatch`)}async function y(e,t,n,r){let i=r.get(`refresh_token`);if(typeof i!=`string`||i===``)return c(e,t,`invalid_request`,`refresh_token is required`);let a;try{a=await d(i,n.artifactSecret,`mcp_refresh_token`),e.set(`realmMcpSessionId`,a.sessionId)}catch{return c(e,t,`invalid_grant`,`Invalid refresh token`,`MCP refresh token rejected`)}let o=r.get(`client_id`);return typeof o!=`string`||o!==a.clientId?c(e,t,`invalid_grant`,`Client mismatch`):await m(t.kv,i,a.exp)?h(e,t,n,{sessionId:a.sessionId,clientId:a.clientId,claims:a.claims,sessionExp:a.sessionExp}):c(e,t,`invalid_grant`,`Refresh token already used`,`MCP refresh rejected: the refresh token was already used`)}export{g as mcpToken};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r=86400,i={ratePerMin:600,quotaPerDay:2e4},a={ratePerMin:60,quotaPerDay:2e3},o={ratePerMin:60,quotaPerDay:2e3};function s(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function c(e){return e===`oauth`?a:e===`card`?o:{ratePerMin:s(process.env.MCP_RATE_LIMIT_PER_MINUTE,i.ratePerMin),quotaPerDay:s(process.env.MCP_RATE_LIMIT_PER_DAY,i.quotaPerDay)}}const l={rate:`minute`,quota:`day`};function u(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}const d=[{scope:`rate`,seconds:60},{scope:`quota`,seconds:r}];function f(e,t){return e===`mcp`?[`mcp`,`request-rl`,t]:[`mcp`,`request-rl`,e,t]}async function p(e){let{kv:t,bucket:n}=e,i=e.limits??c(n),a=Math.floor((e.now??Date.now())/1e3),o=f(n,u(e.ip)),s=await t.get(o),l={};for(let{scope:e,seconds:t}of d){let n=Math.floor(a/t),r=s?.[e],o=r?.id===n?r.count:0;if(o>=(e===`rate`?i.ratePerMin:i.quotaPerDay))return{limited:!0,scope:e,retryAfterSeconds:Math.max(1,(n+1)*t-a)};l[e]={id:n,count:o+1}}return await t.set(o,l,{ttlInSeconds:r}),{limited:!1}}function m(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function h(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=c(n),a;try{a=await p({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${l[a.scope]})`),
|
|
1
|
+
import{extractMappedIpv4 as e}from"../../../../../server/ssrf/ssrf-blocklist.js";import{sendMcpRateLimited as t}from"./mcp-telemetry.js";import{isIP as n}from"node:net";const r=86400,i={ratePerMin:600,quotaPerDay:2e4},a={ratePerMin:60,quotaPerDay:2e3},o={ratePerMin:60,quotaPerDay:2e3};function s(e,t){return e!==void 0&&/^[1-9]\d*$/.test(e)?Number(e):t}function c(e){return e===`oauth`?a:e===`card`?o:{ratePerMin:s(process.env.MCP_RATE_LIMIT_PER_MINUTE,i.ratePerMin),quotaPerDay:s(process.env.MCP_RATE_LIMIT_PER_DAY,i.quotaPerDay)}}const l={rate:`minute`,quota:`day`};function u(t){if(n(t)!==6)return t;let r=e(t);if(r)return r;let[i,a=``]=t.split(`%`)[0].split(`::`),o=i?i.split(`:`):[],s=a?a.split(`:`):[],c=8-o.length-s.length;return`${[...o,...Array(Math.max(0,c)).fill(`0`),...s].slice(0,4).map(e=>parseInt(e||`0`,16).toString(16)).join(`:`)}::/64`}const d=[{scope:`rate`,seconds:60},{scope:`quota`,seconds:r}];function f(e,t){return e===`mcp`?[`mcp`,`request-rl`,t]:[`mcp`,`request-rl`,e,t]}async function p(e){let{kv:t,bucket:n}=e,i=e.limits??c(n),a=Math.floor((e.now??Date.now())/1e3),o=f(n,u(e.ip)),s=await t.get(o),l={};for(let{scope:e,seconds:t}of d){let n=Math.floor(a/t),r=s?.[e],o=r?.id===n?r.count:0;if(o>=(e===`rate`?i.ratePerMin:i.quotaPerDay))return{limited:!0,scope:e,retryAfterSeconds:Math.max(1,(n+1)*t-a)};l[e]={id:n,count:o+1}}return await t.set(o,l,{ttlInSeconds:r}),{limited:!1}}function m(e,t){let n={jsonrpc:`2.0`,error:{code:-32029,message:`Rate limit exceeded (${e.scope}); retry after ${e.retryAfterSeconds}s`},id:null};return new Response(JSON.stringify(n),{status:429,headers:{...t,"Content-Type":`application/json`,"Cache-Control":`no-store`,"Retry-After":String(e.retryAfterSeconds)}})}async function h(e){if(!e.ip)return;let{bucket:n,logger:r}=e,i=c(n),a;try{a=await p({kv:e.kv,ip:e.ip,bucket:n,now:e.now,limits:i})}catch(e){r?.warn(`MCP rate-limit store error, failing open: ${String(e)}`);return}if(a.limited)return r?.warn(`MCP rate limit exceeded (${n}, ${l[a.scope]})`),t({scope:a.scope,retryAfterSeconds:a.retryAfterSeconds,limit:a.scope===`rate`?i.ratePerMin:i.quotaPerDay},{logger:r,caller:{clientIp:e.ip}}),m(a,e.headers??{})}export{h as applyMcpRateLimit,p as checkMcpRateLimit,u as ipRateLimitKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{ANONYMOUS_VIEWER as t}from"../../../../../shared/types/auth.js";import{notFoundResponse as n}from"../../../../../server/plugin-context.js";import{publicBaseUrl as r,publicOrigin as i}from"../../../utils/request-origin.js";import{isMcpContentProtected as a,isMcpHidden as o,resolveMcpAccess as s}from"./config-gate.js";import{MCP_ROUTE as c}from"../constants.js";import{formatError as l}from"./tool-errors.js";import{CORS_ANY_ORIGIN as u,MCP_AUTH_SCHEMES as d}from"./oauth/constants.js";import"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p}from"./mode.js";import{sendMcpServerCardServed as m}from"./mcp-telemetry.js";import{applyMcpRateLimit as h}from"./rate-limit.js";import{createServedMcpRequestHandler as g}from"./handler.js";import{docsServerInfo as _}from"./server-info.js";import{CLIENT_CAPABILITIES_META_KEY as v,CLIENT_INFO_META_KEY as y,LATEST_PROTOCOL_VERSION as b,PROTOCOL_VERSION_META_KEY as x}from"@modelcontextprotocol/server";const S=`2026-07-28`,C=[`dynamic`],w={capabilities:{},tools:C};async function T(e,t,n){let r=await e(new Request(t,{method:`POST`,headers:{"content-type":`application/json`,accept:`application/json, text/event-stream`,"mcp-protocol-version":S,"mcp-method":n},body:JSON.stringify({jsonrpc:`2.0`,id:1,method:n,params:{_meta:{[x]:S,[y]:{name:`server-card`,version:`1.0`},[v]:{}}}})}));if(r.ok)return(await r.json()).result}function E(e,t){e.logger?.warn(`MCP server card lists dynamic tools: ${l(t)}`)}async function D(n,r){let a=await n.withViewer(t),o=await g(a,{isProtected:r},Date.now()+f,{onError:e=>E(n,e)}),s=new URL(e(c),i(n.request)).href,[l,u]=await Promise.all([T(o,s,`server/discover`),r?void 0:T(o,s,`tools/list`)]);if(!l)return;if(r)return{capabilities:l.capabilities,tools:C};if(!u)return;let d=u.tools.map(({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a})=>({name:e,title:t,description:n,inputSchema:r,annotations:i,_meta:a}));return{capabilities:l.capabilities,instructions:l.instructions,tools:d.length>0?d:C}}async function O(t,i){if(o(i.config))return n();t.set(`realmCacheControlOwned`,!0);let l=await h({kv:i.kv,ip:i.request.ip,bucket:`card`,headers:u,logger:i.logger});if(l)return l;let f=_(i.config,i.request),g=a(s(i.config)),v=await D(i,g).catch(e=>{E(i,e)}),{capabilities:y,instructions:x,tools:S}=v??w;return m({mode:p(),toolsCount:S===C?0:S.length,authRequired:g},{logger:i.logger}),t.json({$schema:`https://static.modelcontextprotocol.io/schemas/mcp-server-card/v1.json`,version:`1.0`,protocolVersion:b,serverInfo:{...f,title:f.name},description:f.description,documentationUrl:r(i.config,i.request),transport:{type:`streamable-http`,endpoint:e(c)},capabilities:y,authentication:g?{required:!0,schemes:[...d]}:void 0,instructions:x,tools:S},200,{...u,"Cache-Control":v?`public, max-age=3600`:`no-store`})}export{O as mcpServerCard};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{realmPlusVersion as e}from"../../../../../shared/realm-plus-version.js";import{publicOrigin as t}from"../../../utils/request-origin.js";import{PLACEHOLDER_MCP_SERVER_NAMES as n}from"../constants.js";import{resolveDocsSiteUrl as r}from"./docs-site-url.js";import{docsSiteSentence as i}from"./codemode/prompts.js";function a(e){let t=e.mcp?.name?.trim();return t&&!n.includes(t)?t:void 0}function o(n,o){let s=r(n.seo?.siteUrl,t(o));return{name:a(n)||new URL(s).host,version:e(),description:i(s),websiteUrl:s}}export{o as docsServerInfo};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../shared/path-prefix.js";import{skillMarkdownPath as t}from"../../../utils/skill-paths.js";import{isEntityScopeVisible as n}from"../../../../../shared/rbac/entity-scope.js";import{publicOrigin as r}from"../../../utils/request-origin.js";import{SKILL_ENTITY_TYPE as i}from"../../../types/skill-entity.js";async function a(a){if(a.config.skills?.hide===!0)return[];let o=await a.entities.list({type:i}),s=r(a.request),c=e=>n(e,a.request.teams,e=>a.logger?.warn(e));return o.flatMap(n=>{let{slug:r,title:i,description:o}=n.metadata??{};return typeof r!=`string`||!c(n)?[]:[{slug:r,title:i??r,description:o??``,uri:`${s}${e(t(r))}`,read:async()=>(await a.entities.load(n.key)).content}]})}export{a as loadSkillResources};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{stripPathPrefix as e,withPathPrefix as t}from"../../../../../../shared/path-prefix.js";import"../../../../../../shared/constants/app-data.js";import{toAppData as n}from"../../../../../../shared/utils/app-data.js";import{normalizeRouteSlug as r}from"../../../../../../shared/utils/routes/normalize-route-slug.js";import{normalizeRoutePath as i}from"../../../../../../shared/utils/routes/normalize-route-path.js";import{filterRbacAnnotatedValue as a}from"../../../../../../shared/rbac/filter.js";import{FOLDER_SIDEBAR_FILENAME_REGEX as o,SIDEBAR_AGGREGATOR_LOADER_ID as s,SIDEBAR_PLUGIN_ID as c,isTabbedSidebar as l}from"../../../sidebar/index.js";import{readIgnoredRouteSlugs as u}from"../../ignored-routes.js";import{posix as d}from"node:path";const f=/* @__PURE__ */ new Set,p=/(?:\/index(?:\.html\.md|\.html|\.md)|\.md|\.html)$/;async function m(e){let[t,n]=await Promise.all([u(e.entities),e.pageMarkdown.listPages()]);return{pages:n.filter(e=>!t.has(e.slug)),isVisible:n=>!t.has(n)&&e.isSlugVisible(n)}}async function h(e){let[{pages:t,isVisible:n},i,o]=await Promise.all([m(e),w(e),T(e)]),s=o.filter(e=>typeof e.link==`string`&&e.external!==!0&&n(r(e.link))),c=new Map(t.map(e=>[e.slug,e.title])),l=/* @__PURE__ */ new Set,u=[],d=g(i.map(({path:e})=>e)),p=i.map(({path:e,value:t},n)=>({path:e,value:t,id:d[n],links:M(k(t))})),h=D(p.flatMap(({links:e})=>e.slice(0,1)));for(let{path:t,value:r,id:i,links:o}of p){for(let e of o)l.add(e);let d=N(k(a(r,e.request.teams)),e=>n(e)&&c.has(e));if(d.length===0)continue;let p=i===`/`,m=p?e.config.seo?.title||`Documentation`:i,g=O(t,d,s,c,p?f:h)||m;u.push({id:i,title:g,nodes:d})}u.sort((e,t)=>Number(t.id===`/`)-Number(e.id===`/`));let _=t.filter(e=>!l.has(e.slug)).map(e=>({type:`page`,label:e.title,link:e.slug,items:[]}));return _.length>0&&u.push({id:`other-pages`,title:`Other pages`,nodes:_}),{sections:u,pages:t}}function g(e){let t=e.map(e=>{let t=d.dirname(e);return t===`.`?`/`:t}),n=/* @__PURE__ */ new Map;for(let e of t)n.set(e,(n.get(e)??0)+1);return e.map((e,r)=>{let i=t[r],a=!o.test(e),s=(n.get(i)??0)>1;return a&&s?e:i})}function _(e){let t=(e,n)=>n.flatMap(n=>{if(n.type!==`section`)return[];let r=v(e,n.label);return[{id:r,title:n.label,link:n.link,nodes:n.items},...t(r,n.items)]});return e.flatMap(e=>[e,...t(e.id,e.nodes)])}function v(e,t){return`${e} > ${t}`}function y(e,t,n){let r=_(e),i=t.trim().toLowerCase(),a=r.find(e=>e.id.toLowerCase()===i);if(a)return a;let o=C(t,n),s=r.find(e=>e.link!==void 0&&e.link===o);if(s)return s;let c=r.filter(e=>e.title.toLowerCase()===i);return c.find(e=>c.every(t=>t===e||t.id.startsWith(`${e.id} > `)))}function b(e){return e.flatMap(e=>[...e.link?[e.link]:[],...b(e.items)])}function x(e){return e.reduce((e,t)=>e+(t.type===`page`?1:x(t.items)),0)}function S(e,n){return`${n}${t(e)}`}function C(t,n){let r;try{r=new URL(t.trim(),n).pathname}catch{return null}let a=e(r)??r;return i(a.replace(p,``))}async function w(e){let t=(await e.entities.list({pluginId:c})).flatMap(e=>{let t=e.metadata?.sourcePath;return e.loaderId===s&&typeof t==`string`?[{path:t,key:e.key}]:[]});return t.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path)),Promise.all(t.map(async({path:t,key:n})=>({path:t,value:await e.entities.load(n)})))}async function T(e){if(!await e.entities.get(`app-data`))return[];let t=n(await e.entities.load(`app-data`)).theme?.navbar?.items??[];return E(a(t,e.request.teams)??[])}function E(e){return e.flatMap(e=>[e,...E(e.items??[])])}function D(e){let t=/* @__PURE__ */ new Map;for(let n of e)t.set(n,(t.get(n)??0)+1);return new Set([...t].filter(([,e])=>e>1).map(([e])=>e))}function O(e,t,n,r,i){let a=n.find(t=>Array.isArray(t.linkedSidebars)&&t.linkedSidebars.includes(e));if(typeof a?.label==`string`&&a.label!==``)return a.label;let o=t.find(e=>!e.link||!i.has(e.link));if(o)return o.link?r.get(o.link):o.label}function k(e){return e===null?[]:l(e)?e.tabs.map(A):e}function A(e){return{label:e.label,link:e.link,items:e.menu??e.items??[]}}function j(e){return e.link!==void 0&&e.external!==!0}function M(e){return e.flatMap(e=>[...j(e)&&e.link?[r(e.link)]:[],...M(e.items??[])])}function N(e,t){return e.flatMap(e=>{let n=j(e)&&e.link?r(e.link):void 0,i=n!==void 0&&t(n)?n:void 0;if(e.items){let n=N(e.items,t);return n.length===0&&!i?[]:[{type:`section`,label:e.label??``,...i?{link:i}:{},items:n}]}return i?[{type:`page`,label:e.label??i,link:i,items:[]}]:[]})}export{b as collectNodeLinks,x as countPages,y as findSection,_ as flattenSections,h as loadPageNavigation,m as loadVisiblePages,C as toPageSlug,S as toPublicUrl,v as toSectionId};
|