@redocly/reef 0.137.0-next.5 → 0.137.0-next.7
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/CHANGELOG.md +41 -0
- package/dist/api-schemas/otel-traces.d.ts +1359 -0
- package/dist/api-schemas/otel-traces.js +1 -0
- package/dist/cli/stats/collectors/asyncapi/index.d.ts +3 -0
- package/dist/cli/stats/collectors/asyncapi/index.js +1 -0
- package/dist/cli/stats/collectors/extension-sampling.d.ts +44 -0
- package/dist/cli/stats/collectors/extension-sampling.js +1 -0
- package/dist/cli/stats/collectors/openapi/index.js +1 -1
- package/dist/cli/stats/collectors/prepare-stats-walk.d.ts +10 -0
- package/dist/cli/stats/collectors/prepare-stats-walk.js +1 -0
- package/dist/cli/stats/collectors/run-stats-collector.d.ts +24 -0
- package/dist/cli/stats/collectors/run-stats-collector.js +1 -0
- package/dist/cli/stats/index.js +1 -1
- package/dist/client/app/hooks/useMcpData.d.ts +1 -0
- package/dist/client/app/hooks/useMcpData.js +1 -1
- package/dist/client/app/markdoc/custom-components/openapi/replay-openapi.js +1 -1
- package/dist/client/providers/hooks.js +1 -1
- package/dist/client/providers/post-message/PostMessageProvider.js +1 -1
- package/dist/client/templates/api-docs/helpers.d.ts +4 -1
- package/dist/client/templates/api-docs/helpers.js +5 -1
- package/dist/client/templates/api-docs/template.js +1 -1
- package/dist/constants/l10n/langs/ar.js +1 -1
- package/dist/constants/l10n/langs/de.js +1 -1
- package/dist/constants/l10n/langs/en.js +1 -1
- package/dist/constants/l10n/langs/es.js +1 -1
- package/dist/constants/l10n/langs/fr.js +1 -1
- package/dist/constants/l10n/langs/hi.js +1 -1
- package/dist/constants/l10n/langs/it.js +1 -1
- package/dist/constants/l10n/langs/ja.js +1 -1
- package/dist/constants/l10n/langs/ko.js +1 -1
- package/dist/constants/l10n/langs/pl.js +1 -1
- package/dist/constants/l10n/langs/pt-BR.js +1 -1
- package/dist/constants/l10n/langs/pt.js +1 -1
- package/dist/constants/l10n/langs/ru.js +1 -1
- package/dist/constants/l10n/langs/uk.js +1 -1
- package/dist/constants/l10n/langs/zh.js +1 -1
- package/dist/server/config/env-config.d.ts +2 -0
- package/dist/server/config/env-schema.d.ts +5 -0
- package/dist/server/config/env-schemas/feature-flags.d.ts +4 -0
- package/dist/server/config/env-schemas/feature-flags.js +1 -1
- package/dist/server/constants/mcp.d.ts +5 -0
- package/dist/server/constants/mcp.js +1 -0
- package/dist/server/constants/rbac.d.ts +3 -0
- package/dist/server/constants/rbac.js +1 -0
- package/dist/server/esbuild/esbuild.js +3 -3
- package/dist/server/esbuild/plugins/mcp-tool-handlers-resolver.js +1 -1
- package/dist/server/plugins/api-docs/options.js +1 -1
- package/dist/server/plugins/api-docs/search/get-ai-search-documents.js +9 -9
- package/dist/server/plugins/api-docs/search/search-indexer.js +1 -1
- package/dist/server/plugins/{openapi-docs/is-openapi-doc.d.ts → api-docs/utils/is-api-doc.d.ts} +4 -2
- package/dist/server/plugins/api-docs/utils/is-api-doc.js +1 -0
- package/dist/server/plugins/arazzo-docs/arazzo-doc-loader.d.ts +1 -1
- package/dist/server/plugins/arazzo-docs/arazzo-doc-loader.js +1 -1
- package/dist/server/plugins/entitlements/index.js +1 -1
- package/dist/server/plugins/l10n/index.js +1 -1
- package/dist/server/plugins/lifecycle.js +2 -2
- package/dist/server/plugins/markdown/attribute-resolvers/resolve-link.js +1 -1
- package/dist/server/plugins/markdown/attribute-resolvers/resolve-open-api-ref.js +1 -1
- package/dist/server/plugins/mcp/auth/auth-handlers.d.ts +1 -2
- package/dist/server/plugins/mcp/auth/auth-handlers.js +1 -1
- package/dist/server/plugins/mcp/codemode/capabilities/fetch/index.js +4 -4
- package/dist/server/plugins/mcp/codemode/code-execution-telemetry.d.ts +3 -1
- package/dist/server/plugins/mcp/codemode/code-execution-telemetry.js +1 -1
- package/dist/server/plugins/mcp/codemode/invoke-tool.js +1 -1
- package/dist/server/plugins/mcp/codemode/prompts.js +1 -1
- package/dist/server/plugins/mcp/codemode/sandbox/polyfills/fetch-shim.d.ts +1 -1
- package/dist/server/plugins/mcp/codemode/sandbox/polyfills/fetch-shim.js +9 -3
- package/dist/server/plugins/mcp/codemode/tools/describe-tools.d.ts +1 -1
- package/dist/server/plugins/mcp/codemode/tools/describe-tools.js +1 -1
- package/dist/server/plugins/mcp/codemode/tools/execute-schema.js +1 -1
- package/dist/server/plugins/mcp/codemode/tools/execute.js +1 -1
- package/dist/server/plugins/mcp/codemode/tools/manage-credentials.js +2 -2
- package/dist/server/plugins/mcp/codemode/types.d.ts +1 -0
- package/dist/server/plugins/mcp/constants.d.ts +1 -1
- package/dist/server/plugins/mcp/constants.js +1 -1
- package/dist/server/plugins/mcp/custom-tools/extract-tool-definition.d.ts +13 -0
- package/dist/server/plugins/mcp/custom-tools/extract-tool-definition.js +1 -0
- package/dist/server/plugins/mcp/custom-tools/scan-custom-tools.d.ts +6 -0
- package/dist/server/plugins/mcp/custom-tools/scan-custom-tools.js +1 -0
- package/dist/server/plugins/mcp/custom-tools/validate-tool-definition.d.ts +3 -0
- package/dist/server/plugins/mcp/custom-tools/validate-tool-definition.js +1 -0
- package/dist/server/plugins/mcp/docs-mcp/tool-schemas.d.ts +2 -0
- package/dist/server/plugins/mcp/docs-mcp/tool-schemas.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/core/search.js +2 -2
- package/dist/server/plugins/mcp/docs-mcp/tools/openapi/get-endpoints.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/openapi/list-apis.js +1 -1
- package/dist/server/plugins/mcp/docs-mcp/tools/openapi/utils.js +1 -1
- package/dist/server/plugins/mcp/gateway-mcp/callable-apis.d.ts +10 -0
- package/dist/server/plugins/mcp/gateway-mcp/callable-apis.js +1 -0
- package/dist/server/plugins/mcp/gateway-mcp/elicitation.d.ts +3 -2
- package/dist/server/plugins/mcp/gateway-mcp/elicitation.js +5 -4
- package/dist/server/plugins/mcp/gateway-mcp/eligibility.js +1 -1
- package/dist/server/plugins/mcp/gateway-mcp/fetch/fetch-audit.d.ts +2 -1
- package/dist/server/plugins/mcp/gateway-mcp/fetch/fetch-audit.js +1 -1
- package/dist/server/plugins/mcp/gateway-mcp/fetch/fetch-bridge.js +1 -1
- package/dist/server/plugins/mcp/gateway-mcp/fetch/upstream-detail.d.ts +7 -0
- package/dist/server/plugins/mcp/gateway-mcp/fetch/upstream-detail.js +1 -0
- package/dist/server/plugins/mcp/gateway-mcp/fetch-capability.d.ts +1 -9
- package/dist/server/plugins/mcp/gateway-mcp/fetch-capability.js +1 -1
- package/dist/server/plugins/mcp/gateway-mcp/upstream-auth.d.ts +6 -0
- package/dist/server/plugins/mcp/gateway-mcp/upstream-auth.js +1 -1
- package/dist/server/plugins/mcp/handlers/docs-mcp-handler.js +1 -1
- package/dist/server/plugins/mcp/handlers/errors.d.ts +6 -1
- package/dist/server/plugins/mcp/handlers/errors.js +1 -1
- package/dist/server/plugins/mcp/handlers/handle-mcp-request.js +1 -1
- package/dist/server/plugins/mcp/handlers/mcp-credentials-handler.js +1 -1
- package/dist/server/plugins/mcp/handlers/mcp-credentials-page.d.ts +6 -0
- package/dist/server/plugins/mcp/handlers/mcp-credentials-page.js +50 -42
- package/dist/server/plugins/mcp/index.d.ts +0 -2
- package/dist/server/plugins/mcp/index.js +1 -1
- package/dist/server/plugins/mcp/servers/docs-server.js +1 -1
- package/dist/server/plugins/mcp/servers/mcp-server.js +3 -3
- package/dist/server/plugins/mcp/types.d.ts +30 -3
- package/dist/server/plugins/mcp/utils/available-sandbox-tools.d.ts +4 -0
- package/dist/server/plugins/mcp/utils/available-sandbox-tools.js +1 -0
- package/dist/server/plugins/mcp/utils/find-gated-tool-names.d.ts +2 -3
- package/dist/server/plugins/mcp/utils/find-gated-tool-names.js +1 -1
- package/dist/server/plugins/mcp/utils/mcp-client.d.ts +13 -0
- package/dist/server/plugins/mcp/utils/mcp-client.js +1 -0
- package/dist/server/plugins/mcp/utils/tool-registration.d.ts +17 -0
- package/dist/server/plugins/mcp/utils/tool-registration.js +1 -0
- package/dist/server/plugins/mcp/workers/execute-mcp-tool.d.ts +6 -1
- package/dist/server/plugins/mcp/workers/execute-mcp-tool.js +1 -1
- package/dist/server/plugins/mcp/workers/import-mcp-tool-handlers.d.ts +5 -0
- package/dist/server/plugins/mcp/workers/import-mcp-tool-handlers.js +1 -0
- package/dist/server/plugins/mcp/workers/mcp-tool-telemetry.d.ts +6 -11
- package/dist/server/plugins/mcp/workers/mcp-tool-telemetry.js +1 -1
- package/dist/server/plugins/mcp/workers/tool-file-system.d.ts +6 -0
- package/dist/server/plugins/mcp/workers/tool-file-system.js +1 -0
- package/dist/server/sandbox/sandbox.js +2 -2
- package/dist/server/sandbox/utils/returns-from-top-level.d.ts +4 -0
- package/dist/server/sandbox/utils/returns-from-top-level.js +1 -0
- package/dist/server/store.d.ts +1 -0
- package/dist/server/store.js +1 -1
- package/dist/server/types/plugins/common.d.ts +3 -1
- package/dist/server/utils/rbac/can-anonymous-access-mcp-feature.d.ts +3 -0
- package/dist/server/utils/rbac/can-anonymous-access-mcp-feature.js +1 -0
- package/dist/server/utils/rbac/should-handle-mcp-auth.d.ts +2 -0
- package/dist/server/utils/rbac/should-handle-mcp-auth.js +1 -0
- package/dist/server/utils/rbac.js +1 -1
- package/dist/server/web-server/auth.js +3 -3
- package/dist/server/web-server/handle-api-route-request.js +1 -1
- package/dist/server/web-server/routes/error.js +1 -1
- package/dist/server/web-server/routes/helpers/resolve-ui-locales-for-idp-login.js +1 -1
- package/dist/server/web-server/routes/index.js +1 -1
- package/dist/server/web-server/routes/mcp-routes/agent-card.js +1 -1
- package/dist/server/web-server/routes/mcp-routes/mcp-server-card.js +1 -1
- package/dist/server/web-server/routes/otel/otel.js +1 -1
- package/dist/server/web-server/routes/page-data.js +1 -1
- package/dist/server/web-server/routes/resolve-route.js +1 -1
- package/dist/server/web-server/utils/get-request-origin.d.ts +2 -0
- package/dist/server/web-server/utils/get-request-origin.js +1 -1
- package/dist/server/web-server/utils/prepare-list-response.d.ts +0 -4
- package/dist/server/web-server/utils/prepare-list-response.js +1 -1
- package/dist/server/web-server/utils.d.ts +1 -1
- package/dist/server/web-server/utils.js +1 -1
- package/dist/server/workers/mcp-tool-worker-pool.d.ts +1 -0
- package/dist/server/workers/mcp-tool-worker-pool.js +1 -1
- package/dist/server/workers/mcp-tool-worker.js +1 -1
- package/dist/server/workers/types.d.ts +9 -2
- package/dist/server/workers/worker-pool.d.ts +1 -0
- package/dist/server/workers/worker-pool.js +1 -1
- package/dist/types/global-data.d.ts +1 -0
- package/dist/utils/guards/is-plain-object.d.ts +19 -0
- package/dist/utils/guards/is-plain-object.js +1 -0
- package/package.json +6 -9
- package/dist/client/templates/asyncapi-docs/helpers.d.ts +0 -12
- package/dist/client/templates/asyncapi-docs/helpers.js +0 -1
- package/dist/client/templates/asyncapi-docs/template.d.ts +0 -15
- package/dist/client/templates/asyncapi-docs/template.js +0 -9
- package/dist/client/templates/openapi-docs/helpers.d.ts +0 -18
- package/dist/client/templates/openapi-docs/helpers.js +0 -5
- package/dist/client/templates/openapi-docs/template.d.ts +0 -6
- package/dist/client/templates/openapi-docs/template.js +0 -14
- package/dist/server/esbuild/plugins/api-docs-module-replacer/empty-check.d.ts +0 -9
- package/dist/server/esbuild/plugins/api-docs-module-replacer/empty-check.js +0 -1
- package/dist/server/esbuild/plugins/api-docs-module-replacer/empty-overlay.d.ts +0 -2
- package/dist/server/esbuild/plugins/api-docs-module-replacer/empty-overlay.js +0 -1
- package/dist/server/esbuild/plugins/api-docs-module-replacer/index.d.ts +0 -6
- package/dist/server/esbuild/plugins/api-docs-module-replacer/index.js +0 -1
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/empty-check.d.ts +0 -8
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/empty-check.js +0 -1
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/empty-overlay.d.ts +0 -2
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/empty-overlay.js +0 -1
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/empty-use-license-key.d.ts +0 -5
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/empty-use-license-key.js +0 -1
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/index.d.ts +0 -6
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/index.js +0 -1
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/loadAndBundleSpec.mock.d.ts +0 -3
- package/dist/server/esbuild/plugins/openapi-docs-module-replacer/loadAndBundleSpec.mock.js +0 -1
- package/dist/server/plugins/asyncapi-docs/asyncapi-doc-loader.d.ts +0 -18
- package/dist/server/plugins/asyncapi-docs/asyncapi-doc-loader.js +0 -5
- package/dist/server/plugins/asyncapi-docs/get-server-props.d.ts +0 -4
- package/dist/server/plugins/asyncapi-docs/get-server-props.js +0 -1
- package/dist/server/plugins/asyncapi-docs/get-template-path.d.ts +0 -2
- package/dist/server/plugins/asyncapi-docs/get-template-path.js +0 -1
- package/dist/server/plugins/asyncapi-docs/index.d.ts +0 -3
- package/dist/server/plugins/asyncapi-docs/index.js +0 -1
- package/dist/server/plugins/asyncapi-docs/is-asyncapi-doc.d.ts +0 -3
- package/dist/server/plugins/asyncapi-docs/is-asyncapi-doc.js +0 -1
- package/dist/server/plugins/asyncapi-docs/search/get-ai-search-documents.d.ts +0 -9
- package/dist/server/plugins/asyncapi-docs/search/get-ai-search-documents.js +0 -56
- package/dist/server/plugins/asyncapi-docs/search/schema-processor.d.ts +0 -8
- package/dist/server/plugins/asyncapi-docs/search/schema-processor.js +0 -1
- package/dist/server/plugins/asyncapi-docs/search/search-facets.d.ts +0 -8
- package/dist/server/plugins/asyncapi-docs/search/search-facets.js +0 -1
- package/dist/server/plugins/asyncapi-docs/search/search-resolver.d.ts +0 -5
- package/dist/server/plugins/asyncapi-docs/search/search-resolver.js +0 -1
- package/dist/server/plugins/asyncapi-docs/store-definition-bundles.d.ts +0 -4
- package/dist/server/plugins/asyncapi-docs/store-definition-bundles.js +0 -1
- package/dist/server/plugins/graphql-docs/constants.d.ts +0 -2
- package/dist/server/plugins/graphql-docs/constants.js +0 -1
- package/dist/server/plugins/graphql-docs/get-template-path.d.ts +0 -2
- package/dist/server/plugins/graphql-docs/get-template-path.js +0 -1
- package/dist/server/plugins/graphql-docs/graphql-doc-loader.d.ts +0 -17
- package/dist/server/plugins/graphql-docs/graphql-doc-loader.js +0 -1
- package/dist/server/plugins/graphql-docs/index.d.ts +0 -4
- package/dist/server/plugins/graphql-docs/index.js +0 -1
- package/dist/server/plugins/graphql-docs/is-graphql-doc.d.ts +0 -2
- package/dist/server/plugins/graphql-docs/is-graphql-doc.js +0 -1
- package/dist/server/plugins/graphql-docs/search/ai/get-ai-search-document.d.ts +0 -17
- package/dist/server/plugins/graphql-docs/search/ai/get-ai-search-document.js +0 -4
- package/dist/server/plugins/graphql-docs/search/ai/utils.d.ts +0 -14
- package/dist/server/plugins/graphql-docs/search/ai/utils.js +0 -36
- package/dist/server/plugins/graphql-docs/search/search-facets.d.ts +0 -8
- package/dist/server/plugins/graphql-docs/search/search-facets.js +0 -1
- package/dist/server/plugins/graphql-docs/search/search-resolver.d.ts +0 -5
- package/dist/server/plugins/graphql-docs/search/search-resolver.js +0 -1
- package/dist/server/plugins/graphql-docs/spec-download.api.d.ts +0 -3
- package/dist/server/plugins/graphql-docs/spec-download.api.js +0 -1
- package/dist/server/plugins/graphql-docs/template/GraphQLDocs.d.ts +0 -5
- package/dist/server/plugins/graphql-docs/template/GraphQLDocs.js +0 -4
- package/dist/server/plugins/graphql-docs/types.d.ts +0 -40
- package/dist/server/plugins/graphql-docs/types.js +0 -0
- package/dist/server/plugins/openapi-docs/ai-search-indexer.d.ts +0 -14
- package/dist/server/plugins/openapi-docs/ai-search-indexer.js +0 -1
- package/dist/server/plugins/openapi-docs/decorators.d.ts +0 -25
- package/dist/server/plugins/openapi-docs/decorators.js +0 -1
- package/dist/server/plugins/openapi-docs/format-bundle-error.d.ts +0 -6
- package/dist/server/plugins/openapi-docs/format-bundle-error.js +0 -5
- package/dist/server/plugins/openapi-docs/get-server-props.d.ts +0 -4
- package/dist/server/plugins/openapi-docs/get-server-props.js +0 -1
- package/dist/server/plugins/openapi-docs/get-template-path.d.ts +0 -2
- package/dist/server/plugins/openapi-docs/get-template-path.js +0 -1
- package/dist/server/plugins/openapi-docs/index.d.ts +0 -3
- package/dist/server/plugins/openapi-docs/index.js +0 -1
- package/dist/server/plugins/openapi-docs/is-openapi-doc.js +0 -1
- package/dist/server/plugins/openapi-docs/load-definition.d.ts +0 -31
- package/dist/server/plugins/openapi-docs/load-definition.js +0 -3
- package/dist/server/plugins/openapi-docs/openapi-search-builder.d.ts +0 -24
- package/dist/server/plugins/openapi-docs/openapi-search-builder.js +0 -1
- package/dist/server/plugins/openapi-docs/search/get-ai-search-documents.d.ts +0 -18
- package/dist/server/plugins/openapi-docs/search/get-ai-search-documents.js +0 -94
- package/dist/server/plugins/openapi-docs/search/search-facets.d.ts +0 -11
- package/dist/server/plugins/openapi-docs/search/search-facets.js +0 -1
- package/dist/server/plugins/openapi-docs/search/search-resolver.d.ts +0 -5
- package/dist/server/plugins/openapi-docs/search/search-resolver.js +0 -1
- package/dist/server/plugins/openapi-docs/search-indexer.d.ts +0 -17
- package/dist/server/plugins/openapi-docs/search-indexer.js +0 -1
- package/dist/server/plugins/openapi-docs/spec-download.api.d.ts +0 -4
- package/dist/server/plugins/openapi-docs/spec-download.api.js +0 -1
- package/dist/server/plugins/openapi-docs/store-definition-bundles.d.ts +0 -4
- package/dist/server/plugins/openapi-docs/store-definition-bundles.js +0 -1
- package/dist/server/plugins/openapi-docs/types.d.ts +0 -17
- package/dist/server/plugins/openapi-docs/types.js +0 -0
- package/dist/server/plugins/openapi-docs/utils.d.ts +0 -25
- package/dist/server/plugins/openapi-docs/utils.js +0 -1
- /package/dist/client/templates/{openapi-docs → api-docs}/mock-server-config.d.ts +0 -0
- /package/dist/client/templates/{openapi-docs → api-docs}/mock-server-config.js +0 -0
- /package/dist/{server/plugins → markdoc}/helpers/parse-partials.d.ts +0 -0
- /package/dist/{server/plugins → markdoc}/helpers/parse-partials.js +0 -0
- /package/dist/server/plugins/{openapi-docs → api-docs/utils}/ast-utils.d.ts +0 -0
- /package/dist/server/plugins/{openapi-docs → api-docs/utils}/ast-utils.js +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
import{renderDescribeToolsOutput as
|
|
1
|
+
import{renderDescribeToolsOutput as S}from"../capabilities/index.js";import{McpServerType as y}from"../../constants.js";import{reportMcpToolCalled as v,reportMcpToolError as O}from"../../workers/mcp-tool-telemetry.js";import{DESCRIBE_TOOLS_TOOL_NAME as p}from"../constants.js";import{DESCRIBE_TOOLS_DESCRIPTION as k}from"../prompts.js";import{sanitizeToolName as s}from"../build-tool-type-declarations.js";import{UnknownToolError as w}from"./tool-errors.js";function x(i,l){const r=[...new Set([...i.map(n=>s(n.name)),...l.map(n=>s(n.id))])];return{name:p,title:"Describe tools",description:k,schema:{type:"object",required:[],additionalProperties:!1,properties:{tools:{type:"array",description:`Tool names to describe: ${r.join(", ")}. Omit to describe everything.`,items:r.length>0?{type:"string",enum:r}:{type:"string"},nullable:!0}}}}}function P(i,l,r,n){const c=new Map(i.map(t=>[s(t.name),t])),m=new Map(r.map(t=>[s(t.id),t]));return async t=>{const d=performance.now(),f=n.mcpMode??"code";try{const o=[...new Set((t.tools??[]).map(s))],a=o.length===0,u=o.filter(e=>!c.has(e)&&!m.has(e));if(u.length>0){const e=[...c.keys(),...m.keys()];throw new w(`Unknown tool(s): ${u.join(", ")}. Valid tools: ${e.join(", ")}.`)}const g=a?r:r.filter(e=>o.includes(s(e.id))),T=a?i:o.filter(e=>c.has(e)).map(e=>c.get(e)),M=await Promise.all(T.map(e=>l(e.name))),E=T.filter((e,b)=>M[b]),h=S(E,g,n);return v({tool:p,mode:f,serverType:y.Docs,durationMs:Math.round(performance.now()-d),outputLength:h.length}),{content:[{type:"text",text:h}]}}catch(o){const a=o instanceof w;throw O({tool:p,mode:f,serverType:y.Docs,durationMs:Math.round(performance.now()-d),message:o instanceof Error?o.message:String(o),stack:!a&&o instanceof Error&&o.stack||"",errorClass:a?"tool_error":"server_error"}),o}}}export{P as describeTools,x as describeToolsSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EXECUTE_TOOL_NAME as e}from"../constants.js";import{buildExecuteDescription as t}from"../prompts.js";const n={
|
|
1
|
+
import{EXECUTE_TOOL_NAME as e}from"../constants.js";import{buildExecuteDescription as t}from"../prompts.js";const n={readOnlyHint:!0,openWorldHint:!1},r={name:e,title:"Execute code",description:t(!1),annotations:n,schema:{type:"object",required:["code","description"],additionalProperties:!1,properties:{code:{type:"string",description:"JavaScript to run in the sandbox. Return a value to receive it as the result.",minLength:1},description:{type:"string",description:"A short, human-readable summary of what this code does.",minLength:1},sessionHandle:{type:"string",description:"Handle returned by createAnonymousSession. Required when an API needs credentials. This parameter is only offered when createAnonymousSession is available, so pass it whenever you have called that tool.",minLength:1}}}};export{n as EXECUTE_BASE_ANNOTATIONS,r as EXECUTE_TOOL_SCHEMA};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{runInSandbox as p}from"../../../../sandbox/sandbox.js";import{isMcpToolAvailable as h}from"../../workers/execute-mcp-tool.js";import{importMcpToolHandlers as E}from"../../workers/import-mcp-tool-handlers.js";import{isFetchCapable as b}from"../../gateway-mcp/callable-apis.js";import{buildExecuteHostFetch as w}from"../../gateway-mcp/fetch-capability.js";import{withAuthRequiredMeta as C}from"../../gateway-mcp/upstream-auth.js";import{CODE_MODE_TOOL_NAMES as O,EXECUTE_TOOL_NAME as y}from"../constants.js";import{sanitizeToolName as T}from"../build-tool-type-declarations.js";import{invokeTool as M}from"../invoke-tool.js";import{createSandboxSetup as A}from"../sandbox/create-sandbox-setup.js";import{auditCode as F}from"../code-audit.js";import{reportCodeExecuted as S}from"../code-execution-telemetry.js";import{logCodeExecutionAudit as _}from"../code-execution-audit.js";const x=async(t,o,d)=>{const r=new Set,a=await N(o,d,r),n=[],e=b(o)?await w(o,l=>n.push(l)):void 0;let c=0;const u=e?l=>(c+=1,e(l)):void 0,i=F(t.code);_({audit:i,code:t.code,description:t.description,sessionHandle:t.sessionHandle,toolNames:Object.keys(a),fetchBudget:o.gatewayFetchBudgetPerExec,fetchCapable:e!==void 0});const m=Date.now(),{result:f,error:s}=await p(t.code,{setupContext:A(a,u)});return S({audit:i,fetchCount:c,outcome:s===void 0?"ok":"error",durationMs:Date.now()-m,client:o.client,clientVersion:o.clientVersion}),C({content:[{type:"text",text:JSON.stringify({result:f,error:s})}],isError:s!==void 0,...s!==void 0&&r.has(s)?{errorClass:"tool_error"}:{}},n)};async function N(t,o,d){const r=Object.keys(await E()).filter(e=>!O.has(e)),a=await Promise.all(r.map(e=>h({toolName:e,context:t}).catch(()=>!1))),n={};return r.forEach((e,c)=>{a[c]&&(n[T(e)]=u=>M(e,u,t,o).catch(i=>{throw i instanceof Error&&d.add(i.message),i}))}),n}var J={[y]:x};export{J as default};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{MANAGE_API_CREDENTIALS_TOOL_NAME as v}from"../../constants.js";import{buildUpstreamCredentialFallback as y,buildUpstreamCredentialInputRequired as b,schemeLabelOf as P}from"../../gateway-mcp/elicitation.js";import{getCallableApis as m,isFetchCapable as S}from"../../gateway-mcp/
|
|
2
|
-
`),annotations:{
|
|
1
|
+
import{MANAGE_API_CREDENTIALS_TOOL_NAME as v}from"../../constants.js";import{buildUpstreamCredentialFallback as y,buildUpstreamCredentialInputRequired as b,schemeLabelOf as P}from"../../gateway-mcp/elicitation.js";import{getCallableApis as m,isFetchCapable as S}from"../../gateway-mcp/callable-apis.js";import{secretStore as I}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as w,resolveSecretSubject as k}from"../../gateway-mcp/subject.js";import{resolveUpstreamApiAuth as j}from"../../gateway-mcp/upstream-auth-scheme.js";function H(e){return!!e.elicitationEnabled&&S(e)}function U(e){const t=m(e).map(n=>n.relativePath);return{name:v,title:"Manage API credentials",description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.","The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.","It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument."].join(`
|
|
2
|
+
`),annotations:{readOnlyHint:!1,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for.${t.length>0?` One of: ${t.join(", ")}.`:""}`,minLength:1,...t.length>0?{enum:t}:{}},scheme:{type:"string",description:"Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.",minLength:1},sessionHandle:{type:"string",description:"Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1}}}}}function _(e,c){return async t=>{const n=k(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(n.kind==="invalid")return l(n.message);if(n.kind==="anonymous")return l(w);const{subject:u}=n,h=typeof t.api=="string"?t.api:"",s=m(e).find(o=>o.relativePath===h||o.name===h);if(!s){const o=m(e).map(g=>g.relativePath).join(", ");return l(`Unknown api "${h}". Credentials can only be managed for the APIs this server can call: ${o||"none"}.`)}const r=await j(e,s.relativePath),a=typeof t.scheme=="string"?t.scheme:void 0,A=Object.keys(r.schemes);if(a&&!r.schemes[a])return l(`Unknown scheme "${a}" for api "${s.relativePath}". The security schemes this server can store credentials for are: ${A.join(", ")}.`);const i=a??r.defaultScheme,p=P(r.schemes,i),d=await c.getKv(),f={subject:u,baseUrl:e.baseUrl??"",target:{api:s.relativePath,name:s.name,scheme:i,...p?{schemeLabel:p}:{}},auth:r.schemes[i],apiAuth:r,kv:d,hasExistingSecret:await I.hasSecret(d,u,s.relativePath,i),reason:{kind:"requested"}};return c.getClientCapabilities()?.elicitation?.url?await b(f):{content:[{type:"text",text:await y(f)}],isError:!1}}}function l(e){return{content:[{type:"text",text:e}],isError:!0}}export{H as isManageApiCredentialsToolAvailable,_ as manageApiCredentials,U as manageApiCredentialsSchema};
|
|
@@ -12,9 +12,9 @@ export declare const MCP_PROTOCOL_VERSION = "2025-11-25";
|
|
|
12
12
|
export declare const DEFAULT_CONNECTION_TIMEOUT_MS = 30000;
|
|
13
13
|
export declare const SSE_KEEPALIVE_INTERVAL_MS = 15000;
|
|
14
14
|
export declare const MAX_DOCUMENTS_PER_CATEGORY = 3;
|
|
15
|
-
export declare const MCP_NOT_ALLOWED_TEMPLATE_ID = "mcp-not-allowed";
|
|
16
15
|
export declare const DEFAULT_DOCS_MCP_SERVER_NAME = "Docs MCP server";
|
|
17
16
|
export declare const SUPPORTED_MCP_SCOPES: readonly ['openid', 'profile', 'email', 'offline_access'];
|
|
18
17
|
export declare const CREATE_ANONYMOUS_SESSION_TOOL_NAME = "createAnonymousSession";
|
|
19
18
|
export declare const MANAGE_API_CREDENTIALS_TOOL_NAME = "manageApiCredentials";
|
|
19
|
+
export declare const CUSTOM_MCP_TOOLS_META_DIR = "custom-mcp-tools-meta";
|
|
20
20
|
//# sourceMappingURL=constants.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{LATEST_PROTOCOL_VERSION as o}from"@modelcontextprotocol/server";const
|
|
1
|
+
import{LATEST_PROTOCOL_VERSION as o}from"@modelcontextprotocol/server";const r={Docs:"docs"},t={InternalError:-32603,ServerError:-32e3,InvalidRequest:-32600,MethodNotFound:-32601,InvalidParams:-32602},E=o,_=3e4,s=15e3,O=3,n="Docs MCP server",S=["openid","profile","email","offline_access"],c="createAnonymousSession",T="manageApiCredentials",M="custom-mcp-tools-meta";export{c as CREATE_ANONYMOUS_SESSION_TOOL_NAME,M as CUSTOM_MCP_TOOLS_META_DIR,_ as DEFAULT_CONNECTION_TIMEOUT_MS,n as DEFAULT_DOCS_MCP_SERVER_NAME,T as MANAGE_API_CREDENTIALS_TOOL_NAME,O as MAX_DOCUMENTS_PER_CATEGORY,E as MCP_PROTOCOL_VERSION,t as McpErrorCodes,r as McpServerType,s as SSE_KEEPALIVE_INTERVAL_MS,S as SUPPORTED_MCP_SCOPES};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { ToolDefinitionValidationResult } from '../types.js';
|
|
2
|
+
export type ExtractToolDefinitionParams = {
|
|
3
|
+
toolName: string;
|
|
4
|
+
absoluteSourcePath: string;
|
|
5
|
+
contentDir: string;
|
|
6
|
+
serverOutDir: string;
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Reads a tool's schema by bundling the file with esbuild and importing the bundle
|
|
10
|
+
* once at build time; the source file itself only runs in the worker pool.
|
|
11
|
+
*/
|
|
12
|
+
export declare function extractToolDefinition(params: ExtractToolDefinitionParams): Promise<ToolDefinitionValidationResult>;
|
|
13
|
+
//# sourceMappingURL=extract-tool-definition.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{existsSync as p}from"node:fs";import{mkdir as b,rm as g,writeFile as w}from"node:fs/promises";import{dirname as y,join as f}from"node:path";import{pathToFileURL as T}from"node:url";import{build as v}from"esbuild";import{shaHex as x}from"../../../utils/crypto/sha-hex.js";import{CUSTOM_MCP_TOOLS_META_DIR as $}from"../constants.js";import{validateToolDefinition as D}from"./validate-tool-definition.js";const m=new Map;async function C(t){const{toolName:n,absoluteSourcePath:a,contentDir:d,serverOutDir:h}=t;let i;try{const e=f(d,"tsconfig.json");i=(await v({entryPoints:[a],write:!1,bundle:!0,format:"esm",platform:"node",mainFields:["module","main"],logLevel:"silent",...p(e)?{tsconfig:e}:{}})).outputFiles[0].text}catch(e){return{ok:!1,errors:[`the file cannot be bundled: ${u(e)}`]}}const s=x(i),l=`${n}:${a}:${s}`,c=m.get(l);if(c)return c;const o=f(h,$,`${s.slice(0,16)}.mjs`);let r;try{await b(y(o),{recursive:!0}),await w(o,i);const e=await import(T(o).href);r=D(n,e.default)}catch(e){r={ok:!1,errors:[`the file failed to load: ${u(e)}. Tool files must not have module-level side effects.`]}}finally{await g(o,{force:!0}).catch(()=>{})}return m.set(l,r),r}function u(t){return t instanceof Error?t.message:String(t)}export{C as extractToolDefinition};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { LifecycleContext, ProcessContentActions } from '../../../types';
|
|
2
|
+
import type { CustomMcpToolsState } from '../types.js';
|
|
3
|
+
/** Registers every file in an `@mcp` folder as one MCP tool, named after the file. */
|
|
4
|
+
export declare function scanCustomMcpTools(actions: ProcessContentActions, context: LifecycleContext, state: CustomMcpToolsState): Promise<number>;
|
|
5
|
+
export declare function resetCustomMcpTools(actions: Pick<ProcessContentActions, 'removeMcpTools'>, state: CustomMcpToolsState): void;
|
|
6
|
+
//# sourceMappingURL=scan-custom-tools.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{basename as f,join as d}from"node:path";import{envConfig as p}from"../../../config/env-config.js";import{reporter as i}from"../../../tools/notifiers/reporter.js";import{CODE_MODE_TOOL_NAMES as E}from"../codemode/constants.js";import{ALL_DEFAULT_TOOL_NAMES as O}from"../docs-mcp/tool-schemas.js";import{extractToolDefinition as h}from"./extract-tool-definition.js";const T=/(^|\/)@mcp\/.*\.(ts|js)$/,M=/^[a-zA-Z0-9_-]{1,64}$/,_=new Set([...E,...O]);async function S(o,r,a){if(!p.REDOCLY_EXP_MCP_CUSTOM_TOOLS_ENABLED)return 0;C(o,a);const u=new Set(o.getMcpTools().map(n=>n.name)),l=new Map;for(const n of r.fs.scan(T)){if(n.isVirtual||n.relativePath.endsWith(".d.ts"))continue;const{relativePath:t}=n,e=f(t).replace(/\.(ts|js)$/,"");if(!M.test(e)){await i.panicOnBuildContentError(`Invalid MCP tool file "${t}": the tool name "${e}" is derived from the file name and may only contain letters, numbers, hyphens, and underscores (max 64 characters). Rename the file.`);continue}const c=l.get(e);if(c){await i.panicOnBuildContentError(`Duplicate MCP tool name "${e}": defined by both "${c}" and "${t}". Tool names are file names, so each file name must be unique across @mcp folders.`);continue}if(_.has(e)||u.has(e)){await i.panicOnBuildContentError(`Invalid MCP tool file "${t}": the tool name "${e}" is already used by a built-in MCP tool. Rename the file.`);continue}l.set(e,t);const m=d(o.contentDir,t),s=await h({toolName:e,absoluteSourcePath:m,contentDir:o.contentDir,serverOutDir:o.serverOutDir});if(!s.ok){await i.panicOnBuildContentError(`Invalid MCP tool file "${t}": ${s.errors.join(" ")}`);continue}o.addMcpTools(m,[s.schema]),a.registeredToolNames.push(e)}return a.registeredToolNames.length}function C(o,r){o.removeMcpTools(r.registeredToolNames),r.registeredToolNames=[]}export{C as resetCustomMcpTools,S as scanCustomMcpTools};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import type { ToolDefinitionValidationResult, ToolFileDefaultExport } from '../types.js';
|
|
2
|
+
export declare function validateToolDefinition(toolName: string, moduleDefault: ToolFileDefaultExport): ToolDefinitionValidationResult;
|
|
3
|
+
//# sourceMappingURL=validate-tool-definition.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{isPlainObject as s}from"../../../../utils/guards/is-plain-object.js";function f(c,a){if(!s(a))return{ok:!1,errors:["the default export must be an object with `description` and `execute` properties. Move shared helper code outside the `@mcp` folder."]};const{description:i,inputSchema:t,outputSchema:n,annotations:o,isAvailable:u,execute:p}=a,e=[];return(typeof i!="string"||i.trim()==="")&&e.push("`description` must be a non-empty string."),typeof p!="function"&&e.push("`execute` must be a function."),t!==void 0&&(s(t)?t.type!==void 0&&t.type!=="object"&&e.push('`inputSchema.type` must be "object" because MCP tool arguments are named.'):e.push("`inputSchema` must be a JSON Schema object.")),n!==void 0&&!s(n)&&e.push("`outputSchema` must be a JSON Schema object."),o!==void 0&&!s(o)&&e.push("`annotations` must be an object."),u!==void 0&&typeof u!="function"&&e.push("`isAvailable` must be a function."),e.length>0||typeof i!="string"?{ok:!1,errors:e}:{ok:!0,schema:{name:c,description:i,schema:{type:"object",...t??{properties:{}}},...n?{outputSchema:n}:{},...o?{annotations:o}:{},hasAvailabilityGate:typeof u=="function"}}}export{f as validateToolDefinition};
|
|
@@ -6,5 +6,7 @@ export declare function getDefaultToolSchemas(config: {
|
|
|
6
6
|
rbac?: Record<string, unknown>;
|
|
7
7
|
hasGraphqlApis?: boolean;
|
|
8
8
|
elicitationEnabled?: boolean;
|
|
9
|
+
hasCallableApis?: boolean;
|
|
9
10
|
}): McpToolSchema[];
|
|
11
|
+
export declare const ALL_DEFAULT_TOOL_NAMES: ReadonlySet<string>;
|
|
10
12
|
//# sourceMappingURL=tool-schemas.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{shouldHandleMcpAuth as d}from"../auth/auth-handlers.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as m}from"../constants.js";import{GRAPHQL_TYPE_KINDS as o,GRAPHQL_LIST_SCOPES as h}from"./tools/graphql/constants.js";import{OPERATION_METHODS as p}from"./tools/openapi/constants.js";const i={type:"string",nullable:!0},n={limit:{type:"number"},total:{type:"number"},page:{type:"number"},totalPages:{type:"number"}},r={codemodeType:"OpenApiServer[]"},s={codemodeType:"OpenApiSecurityRequirement[]"},l={codemodeType:"Record<string, OpenApiSecurityScheme>"},y={codemodeType:"OpenApiDocument"},f={codemodeType:"OpenApiOperation & { path: string; method: string }"},g={type:"object",additionalProperties:!1,required:[],properties:{filter:{type:"string",description:"Matches part of an API name, or of a description when no name matches",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of APIs per page. Default is 300",minimum:1,default:300,nullable:!0}}},a={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it",minLength:1},version:{type:"string",description:"API version",nullable:!0},filePath:{type:"string",description:"API definition file path",nullable:!0}}},b={type:"object",required:["name","path","method"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it",minLength:1},path:{type:"string",description:"Endpoint path (e.g. /api/v1/users)",minLength:1},method:{type:"string",description:"HTTP method (GET, POST, PUT, DELETE, etc.)",enum:[...p.map(e=>e.toUpperCase()),...p],minLength:1},version:{type:"string",description:"API version (required when multiple APIs share the same name but differ by version)",nullable:!0},filePath:{type:"string",description:"API definition file path",nullable:!0}}},S={type:"object",required:[],additionalProperties:!1,properties:{}},v={type:"object",required:[],additionalProperties:!1,properties:{}};function I(e){const t=[{name:"list-apis",description:"Lists available APIs with their context and purpose",schema:g,annotations:{title:"List APIs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i,version:i,servers:r,filePath:{type:"string",description:"API definition file path"}}}},...n}}},{name:"get-endpoints",description:"Get all endpoints for a specific API",schema:a,annotations:{title:"Get Endpoints",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoints:{type:"array",items:{type:"object",properties:{path:{type:"string"},method:{type:"string"},summary:i,description:i,security:s}}}}}},{name:"get-endpoint-info",description:"Get comprehensive information about specific endpoint including parameters, security, and examples",schema:b,annotations:{title:"Get Endpoint Info",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoint:f,globalSecurity:s,securitySchemes:l}}},{name:"get-security-schemes",description:"Get the security schemes for a specific API",schema:a,annotations:{title:"Get Security Schemes",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:i,version:i,securitySchemes:l,security:s}}},{name:"get-full-api-description",description:"Get the complete OpenAPI description",schema:a,annotations:{title:"Get Full API Description",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},definition:y}}},q(e.products,e.locales)];return d(e.requiresLogin,e.rbac)&&t.push({name:"whoami",description:"Get information about the currently authenticated user",schema:S,annotations:{title:"Who Am I",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{email:{type:"string"},name:{type:"string"},subject:{type:"string"},clientId:{type:"string"},scope:{type:"string"},issuedAt:{type:"string"},expiresAt:{type:"string"}}}}),e.hasGraphqlApis&&t.push(...T()),e.elicitationEnabled&&t.push({name:m,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:v,annotations:{title:"Create anonymous session",readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"object",required:["sessionHandle"],properties:{sessionHandle:{type:"string"}}}}),t}const H={type:"object",required:[],additionalProperties:!1,properties:{filter:{type:"string",description:"GraphQL schema name (or part of it)",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},P={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},kind:{type:"string",description:'Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).',enum:[...o],nullable:!0},scope:{type:"string",description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions \u2014 combine with `filter` to search nested fields anywhere in the schema.',enum:[...h],nullable:!0},filter:{type:"string",description:'Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")',minLength:1,nullable:!0},referencesType:{type:"string",description:'Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it \u2014 e.g. referencesType "Book" surfaces a search query returning a union that includes Book.',minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},A={type:"object",required:["name","type"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},type:{type:"string",description:"Name of the type, operation, or directive",minLength:1},includeReferencedTypes:{type:"boolean",description:"Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.",default:!1,nullable:!0}}},L={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1}}};function T(){return[{name:"list-graphql-apis",description:"Lists available GraphQL schemas with their context and purpose",schema:H,annotations:{title:"List GraphQL APIs",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i}}},...n}}},{name:"get-graphql-type-list",description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, \u2026) and carries a one-line description; operations also include their return type and argument signature \u2014 use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields \u2014 not just type names \u2014 set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',schema:P,annotations:{title:"Get GraphQL Type List",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:{type:"string"},items:{type:"array",items:{type:"object",properties:{kind:{type:"string",enum:o},name:{type:"string"},description:i,type:{type:"string"},args:{type:"string"},directives:{type:"string"}}}},...n}}},{name:"get-graphql-type",description:'Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type\'s field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively \u2014 the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call get-graphql-type-list with `referencesType`.',schema:A,annotations:{title:"Get GraphQL Type",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}},{name:"get-graphql-schema",description:"Get the complete GraphQL schema as SDL \u2014 the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer get-graphql-type-list (filter/paginate) plus targeted get-graphql-type calls, and reach for this only for small schemas or when you truly need the full SDL.",schema:L,annotations:{title:"Get GraphQL Schema",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}}]}function q(e,t){const c=e&&e.length>0,u=t&&t.length>0;return{name:"search",description:"Search across the documentation to fetch relevant content for a given query",schema:{type:"object",required:["query"],additionalProperties:!1,properties:{query:{type:"string",description:"Search query. Should be a single word or that phrase that is presented in a documentation.",minLength:1},...c?{product:{type:"string",description:"Optional product name to filter search results by specific product.",enum:e,nullable:!0}}:{},...u?{locale:{type:"string",description:"Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the project's default locale.",enum:t,nullable:!0}}:{}}},annotations:{title:"Search Documentation",readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"string"}}}export{I as getDefaultToolSchemas};
|
|
1
|
+
import{shouldHandleMcpAuth as d}from"../../../utils/rbac/should-handle-mcp-auth.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as m}from"../constants.js";import{GRAPHQL_TYPE_KINDS as o,GRAPHQL_LIST_SCOPES as h}from"./tools/graphql/constants.js";import{OPERATION_METHODS as p}from"./tools/openapi/constants.js";const i={type:"string",nullable:!0},n={limit:{type:"number"},total:{type:"number"},page:{type:"number"},totalPages:{type:"number"}},r={codemodeType:"OpenApiServer[]"},s={codemodeType:"OpenApiSecurityRequirement[]"},l={codemodeType:"Record<string, OpenApiSecurityScheme>"},y={codemodeType:"OpenApiDocument"},f={codemodeType:"OpenApiOperation & { path: string; method: string }"},g={type:"object",additionalProperties:!1,required:[],properties:{filter:{type:"string",description:"Matches part of an API name, or of a description when no name matches",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of APIs per page. Default is 300",minimum:1,default:300,nullable:!0}}},a={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it",minLength:1},version:{type:"string",description:"API version",nullable:!0},filePath:{type:"string",description:"API definition file path",nullable:!0}}},b={type:"object",required:["name","path","method"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it",minLength:1},path:{type:"string",description:"Endpoint path (e.g. /api/v1/users)",minLength:1},method:{type:"string",description:"HTTP method (GET, POST, PUT, DELETE, etc.)",enum:[...p.map(e=>e.toUpperCase()),...p],minLength:1},version:{type:"string",description:"API version (required when multiple APIs share the same name but differ by version)",nullable:!0},filePath:{type:"string",description:"API definition file path",nullable:!0}}},S={type:"object",required:[],additionalProperties:!1,properties:{}},v={type:"object",required:[],additionalProperties:!1,properties:{}};function H(e){const t=[{name:"list-apis",title:"List APIs",description:"Lists the APIs documented in this project",schema:g,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i,version:i,servers:r,filePath:{type:"string",description:"API definition file path"},...e.hasCallableApis?{callable:{type:"boolean",description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}}:{}}}},...n}}},{name:"get-endpoints",title:"Get endpoints",description:"Get all endpoints for a specific API",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoints:{type:"array",items:{type:"object",properties:{path:{type:"string"},method:{type:"string"},summary:i,description:i,security:s}}}}}},{name:"get-endpoint-info",title:"Get endpoint info",description:"Get comprehensive information about specific endpoint including parameters, security, and examples",schema:b,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoint:f,globalSecurity:s,securitySchemes:l}}},{name:"get-security-schemes",title:"Get security schemes",description:"Get the security schemes for a specific API",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:i,version:i,securitySchemes:l,security:s}}},{name:"get-full-api-description",title:"Get full API description",description:"Get the complete OpenAPI description",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},definition:y}}},T(e.products,e.locales)];return d(e.requiresLogin,e.rbac)&&t.push({name:"whoami",title:"Who am I",description:"Get information about the currently authenticated user",schema:S,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{email:{type:"string"},name:{type:"string"},subject:{type:"string"},clientId:{type:"string"},scope:{type:"string"},issuedAt:{type:"string"},expiresAt:{type:"string"}}}}),e.hasGraphqlApis&&t.push(...O()),e.elicitationEnabled&&t.push({name:m,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:v,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"object",required:["sessionHandle"],properties:{sessionHandle:{type:"string"}}}}),t}const A={type:"object",required:[],additionalProperties:!1,properties:{filter:{type:"string",description:"GraphQL schema name (or part of it)",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},P={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},kind:{type:"string",description:'Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).',enum:[...o],nullable:!0},scope:{type:"string",description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions \u2014 combine with `filter` to search nested fields anywhere in the schema.',enum:[...h],nullable:!0},filter:{type:"string",description:'Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")',minLength:1,nullable:!0},referencesType:{type:"string",description:'Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it \u2014 e.g. referencesType "Book" surfaces a search query returning a union that includes Book.',minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},L={type:"object",required:["name","type"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},type:{type:"string",description:"Name of the type, operation, or directive",minLength:1},includeReferencedTypes:{type:"boolean",description:"Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.",default:!1,nullable:!0}}},q={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1}}};function O(){return[{name:"list-graphql-apis",title:"List GraphQL APIs",description:"Lists available GraphQL schemas with their context and purpose",schema:A,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i}}},...n}}},{name:"get-graphql-type-list",title:"Get GraphQL type list",description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, \u2026) and carries a one-line description; operations also include their return type and argument signature \u2014 use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields \u2014 not just type names \u2014 set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',schema:P,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:{type:"string"},items:{type:"array",items:{type:"object",properties:{kind:{type:"string",enum:o},name:{type:"string"},description:i,type:{type:"string"},args:{type:"string"},directives:{type:"string"}}}},...n}}},{name:"get-graphql-type",title:"Get GraphQL type",description:'Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type\'s field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively \u2014 the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call get-graphql-type-list with `referencesType`.',schema:L,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}},{name:"get-graphql-schema",title:"Get GraphQL schema",description:"Get the complete GraphQL schema as SDL \u2014 the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer get-graphql-type-list (filter/paginate) plus targeted get-graphql-type calls, and reach for this only for small schemas or when you truly need the full SDL.",schema:q,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}}]}function T(e,t){const c=e&&e.length>0,u=t&&t.length>0;return{name:"search",title:"Search documentation",description:"Search across the documentation to fetch relevant content for a given query",schema:{type:"object",required:["query"],additionalProperties:!1,properties:{query:{type:"string",description:"Search query. Should be a single word or that phrase that is presented in a documentation.",minLength:1},...c?{product:{type:"string",description:"Optional product name to filter search results by specific product.",enum:e,nullable:!0}}:{},...u?{locale:{type:"string",description:"Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the project's default locale.",enum:t,nullable:!0}}:{}}},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"string"}}}const E=new Set(H({requiresLogin:!0,hasGraphqlApis:!0,elicitationEnabled:!0}).map(e=>e.name));export{E as ALL_DEFAULT_TOOL_NAMES,H as getDefaultToolSchemas};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{removeTrailingSlash as
|
|
1
|
+
import{removeTrailingSlash as g,withPathPrefix as y,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as S}from"../../../../../../constants/common.js";const w=async(n,t)=>{const{query:e,product:c,locale:l}=n,u=t.config.l10n?.defaultLocale||S,h=JSON.stringify({query:e,product:c,locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${y(L.SEMANTIC_SEARCH)}`,o=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const s=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}},body:h});if(!s.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await s.json(),d=new Set(t.searchIgnoredRoutes??[]),a=(p||[]).filter(r=>!R(r.url,d));if(a.length===0)return{content:[{type:"text",text:"No results found."}]};const m=r=>{try{return new URL(r,t.baseUrl).toString()}catch{return r}},i=a.map(r=>`### [${r.title}](${m(r.url)})
|
|
2
2
|
|
|
3
3
|
${r.content}
|
|
4
4
|
`).join(`
|
|
5
5
|
|
|
6
|
-
`).trim();return{content:[{type:"text",text:
|
|
6
|
+
`).trim();return{content:[{type:"text",text:i.length?i:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=g(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var v={search:w};export{v as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{loadApiDescription as i}from"./load-api-description.js";import{getEndpointsFromPaths as s}from"./utils.js";const p=async(
|
|
1
|
+
import{loadApiDescription as i}from"./load-api-description.js";import{getEndpointsFromPaths as s}from"./utils.js";const p=async(e,r)=>{let t;try{t=await i(e,r)}catch(o){return{content:[{type:"text",text:o.message}],isError:!0}}const n=s(t);return{content:[{type:"text",text:JSON.stringify({api:t.info?.title||"",version:t.info?.version||"",servers:t.servers||[],endpoints:n},null,2)}]}};var d={"get-endpoints":p};export{d as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{filterApiDescriptionsByName as g}from"../../utils/api-name-matching.js";const h=async(
|
|
1
|
+
import{isFetchCapable as d}from"../../../gateway-mcp/callable-apis.js";import{filterApiDescriptionsByName as g}from"../../utils/api-name-matching.js";const h=async(n,i)=>{const{filter:s,page:l=1,limit:e=300}=n,o=d(i);let t=Object.values(i.apiDescriptionsMap);s&&(t=g(t,s));const a=(l-1)*e,c=a+e,p=Math.ceil(t.length/e),r=t.length;return t=t.slice(a,c),{content:[{type:"text",text:JSON.stringify({items:t.map(({relativePath:f,fetchEligible:m,...u})=>({filePath:f,...u,...o?{callable:m===!0}:{}})),limit:e,total:r,page:l,totalPages:p})}]}};var y={"list-apis":h};export{y as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import a from"node:path";import{existsSync as f}from"node:fs";import{readFile as d}from"node:fs/promises";import{replaceFileExtension as h}from"../../../../../plugins/
|
|
1
|
+
import a from"node:path";import{existsSync as f}from"node:fs";import{readFile as d}from"node:fs/promises";import{replaceFileExtension as h}from"../../../../../plugins/api-docs/utils/replace-file-extension.js";import{PUBLIC_API_DEFINITIONS_FOLDER as u}from"../../../../../constants/common.js";import{filterDataByAccessDeep as l}from"../../../../../utils/rbac.js";import{checkEndpointAndDeleteXMcp as c}from"../../../utils/xmcp-utils.js";import{HTTP_METHODS as y}from"./constants.js";function P(t){return typeof t=="object"&&t!==null&&"responses"in t&&typeof t.responses=="object"}function S(t){const{paths:n={}}=t,e=[];for(const[r,i]of Object.entries(n)){const s=!c(i,"docs");for(const[p,o]of Object.entries(i))y.has(p.toLowerCase())&&(s||!c(o,"docs")||e.push({path:r,method:p.toUpperCase(),summary:o.summary,description:o.description,security:o.security}))}return e}async function T({relativePath:t,outdir:n,user:e,rbac:r={},requiresLogin:i=!1}){const s=a.join(n||"",u,h(t,".json"));if(!f(s))return;const o=await d(s,"utf-8"),m=JSON.parse(o);return l(m,{isAuthenticated:e?.isAuthenticated,email:e?.email,teams:e?.teams},r,i)}export{T as getApiDescriptionFromFs,S as getEndpointsFromPaths,P as isMcpEndpoint};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ApiDescriptionInfo, McpToolContext } from '../types.js';
|
|
2
|
+
export declare function getCallableApis(context: McpToolContext): ApiDescriptionInfo[];
|
|
3
|
+
/**
|
|
4
|
+
* Fetch capability at request/worker time is derived purely from the build-time stamps:
|
|
5
|
+
* `fetchEligible` is stamped per API by the lifecycle plugin under `isGatewayCapabilityEnabled`
|
|
6
|
+
* (entitlement + hide checks), and the map arriving here is already RBAC-filtered.
|
|
7
|
+
* No EntitlementsProvider read — this code runs in graphs where the provider is uninitialized.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isFetchCapable(context: McpToolContext): boolean;
|
|
10
|
+
//# sourceMappingURL=callable-apis.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function i(e){return Object.values(e.apiDescriptionsMap??{}).filter(t=>t.fetchEligible)}function l(e){return i(e).length>0}export{i as getCallableApis,l as isFetchCapable};
|
|
@@ -16,6 +16,7 @@ export type CredentialTarget = {
|
|
|
16
16
|
export type CredentialElicitationReason = {
|
|
17
17
|
kind: 'authFailure';
|
|
18
18
|
status: number;
|
|
19
|
+
detail?: string;
|
|
19
20
|
otherApiNames?: string[];
|
|
20
21
|
} | {
|
|
21
22
|
kind: 'requested';
|
|
@@ -43,8 +44,8 @@ export declare function buildUpstreamCredentialInputRequired(request: Credential
|
|
|
43
44
|
export declare function buildUpstreamCredentialFallback(request: CredentialElicitationRequest): Promise<string>;
|
|
44
45
|
/**
|
|
45
46
|
* Text for an authorization failure we deliberately do NOT prompt for: a stored secret the
|
|
46
|
-
* upstream rejected,
|
|
47
|
-
*
|
|
47
|
+
* upstream rejected, a 401 that never carried a stored credential, or a 403/407 that is more
|
|
48
|
+
* likely a permissions problem than a missing key.
|
|
48
49
|
*/
|
|
49
50
|
export declare function buildCredentialsToolHint(event: UpstreamAuthRequiredEvent, schemeLabel?: string): string;
|
|
50
51
|
/**
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import{inputRequired as h,inputResponse as
|
|
2
|
-
`)}
|
|
3
|
-
`)}
|
|
4
|
-
`)}
|
|
1
|
+
import{inputRequired as h,inputResponse as w}from"@modelcontextprotocol/server";import{MANAGE_API_CREDENTIALS_TOOL_NAME as l}from"../constants.js";import{secretStore as d,ELICITATION_TTL_MS as y}from"./secret-store.js";import{operationsForScheme as I,orderedSchemesOf as A}from"./upstream-auth-scheme.js";import{ANONYMOUS_SUBJECT_PREFIX as u}from"./subject.js";const m="credentials";function R(e){const t=w(e,m);return t.kind==="elicit"&&(t.action==="decline"||t.action==="cancel")}function x(e,t){return Object.keys(e).length>1?t:void 0}async function F(e){const{url:t}=await f(e);return h({inputRequests:{[m]:h.elicitUrl({message:b(e),url:t})}})}async function L(e){const{url:t}=await f(e);return C(e,t,P(e.subject))}function U(e,t){const r=p(e);if(e.status===401&&!e.sentScheme){const[a,o]=e.callerHeader?[`Your code set the "${e.callerHeader}" header itself, so the stored credential was not sent.`,"Remove that header from the request and retry. Do not replace the stored credentials."]:["No stored credential was sent with this request, so this result says nothing about the stored credentials.","Do not replace them. Check whether this operation needs a different kind of credential or a different route."];return[`The "${e.name}" API returned ${r}. ${a}`,"",o].join(`
|
|
2
|
+
`)}const n=e.status===401?`The "${e.name}" API rejected the stored ${t?`"${t}" `:""}credential (${r}).`:`The "${e.name}" API rejected the request with ${r}.`,i=t?`api: "${e.api}" and scheme: "${t}"`:`api: "${e.api}"`;return[n,"",`Do not retry the same call. Call \`${l}\` with ${i} 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(`
|
|
3
|
+
`)}function p({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}function H(e,t){const r=t.map(({name:n,label:i,description:a})=>`- ${n} \u2014 ${i}${a?`: ${a}`:""}`);return[`The "${e.name}" API rejected the request with ${p(e)} and this operation accepts more than one kind of credential:`,"",...r,"","Ask the user which one of these they have, and wait for the answer. Never guess and never reuse a value meant for another kind.",`Then call \`${l}\` with api: "${e.api}" and scheme set to the name they picked to get a link where they enter it.`].join(`
|
|
4
|
+
`)}async function f({kv:e,subject:t,baseUrl:r,target:n,auth:i,apiAuth:a,hasExistingSecret:o}){const s=a?await k(e,t,n.api,a):[],c=await d.createElicitation(e,{subject:t,api:n.api,name:n.name,scheme:n.scheme,...n.schemeLabel?{schemeLabel:n.schemeLabel}:{},auth:i,hasExistingSecret:o,...s.length>1?{schemes:s}:{}});return{token:c,url:E(r,c)}}async function k(e,t,r,n){const a=(await d.getSecretsForSubject(e,t))[r]??{};return A(n.schemes).map(o=>{const s=I(n,o),c=n.descriptions?.[o];return{name:o,...c?{label:c}:{},auth:n.schemes[o],hasExistingSecret:!!a[o],...s.length>0?{operations:s}:{}}})}function P(e){return e.startsWith(u)?e.slice(u.length):void 0}function b({target:e,hasExistingSecret:t,reason:r}){const n=`The link works for ${$()} minutes.`,i=S(e),a=r.kind==="authFailure"&&r.detail?` The API answered: ${r.detail}.`:"";return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They go straight to the API and never enter the chat. ${n}`:`${g(i)} needs credentials.${a} Open this page in a browser to paste them - they go straight to the API and never enter the chat. ${n}`}function S({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function g(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $(){return Math.round(y/6e4)}function E(e,t){if(!e)return`/mcp/credentials?token=${t}`;try{const r=new URL("/mcp/credentials",e);return r.searchParams.set("token",t),r.toString()}catch{return`${e}/mcp/credentials?token=${t}`}}function C({target:e,reason:t,hasExistingSecret:r},n,i){const o=[`**Stop and show the user this link. They have to open it in a browser to ${r?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,"",n,"",`The link is valid ${$()} minutes and opens a form on this site. Credentials go straight to the API from there: 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.`:r?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, call this tool again with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:"Once the user confirms they saved them, call this tool again - the credentials are applied server-side and never appear in the conversation."],s=t.kind==="authFailure"?t.otherApiNames??[]:[];if(s.length>0){const c=s.map(T=>`"${T}"`).join(", ");o.push("",`The remaining APIs (${c}) will prompt for credentials on subsequent calls.`)}return o.join(`
|
|
5
|
+
`)}export{m as CREDENTIALS_INPUT_REQUEST_KEY,U as buildCredentialsToolHint,H as buildSchemeChoiceHint,L as buildUpstreamCredentialFallback,F as buildUpstreamCredentialInputRequired,R as isCredentialElicitationDeclined,x as schemeLabelOf};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{join as e}from"node:path";import{PUBLIC_API_DEFINITIONS_FOLDER as s}from"../../../constants/common.js";import{
|
|
1
|
+
import{join as e}from"node:path";import{PUBLIC_API_DEFINITIONS_FOLDER as s}from"../../../constants/common.js";import{ANONYMOUS_AUTH_DETAILS as n}from"../../../constants/rbac.js";import{canDownloadApiDefinition as a}from"../../../utils/rbac.js";import{MCP_PROTOCOL_VERSION as p}from"../constants.js";import{isApiIncludedInDocsMcp as c}from"../utils.js";import{isMcpGatewayEnabled as l}from"../utils/mode.js";import{isDefinitionHidden as m,hasGatewayConfig as f}from"../utils/xmcp-utils.js";function u(o){return l()&&!o?.hide&&!o?.docs?.hide}function d(o,r,i){return m(o,"gateway")?!1:a(e(s,r),i,!1,n)||f(o)}function _(o,r,i,t){return u(t)&&!o?.["x-mcp"]?.servers?.length&&d(o?.info,r,i)&&c(r,o,t)}function G(o){return{protocolVersion:p,capabilities:{tools:{}},servers:[{url:o}],tools:[],resources:[],prompts:[]}}export{G as buildGatewayXMcp,u as isGatewayCapabilityEnabled,d as isGatewayEligible,_ as shouldAdvertiseGatewayXMcp};
|
|
@@ -9,6 +9,7 @@ type GatewayFetchAuditRecord = {
|
|
|
9
9
|
path?: string;
|
|
10
10
|
api?: string;
|
|
11
11
|
status?: number;
|
|
12
|
+
injectedScheme?: string;
|
|
12
13
|
requestHeaders?: Record<string, string>;
|
|
13
14
|
requestBody?: string;
|
|
14
15
|
responseHeaders?: Record<string, string>;
|
|
@@ -19,6 +20,6 @@ type GatewayFetchAuditRecord = {
|
|
|
19
20
|
* telemetry event verbatim so a Grafana row joins onto this line; `url_sha256` identifies the
|
|
20
21
|
* request itself, since the telemetry event's `path` is deliberately normalized.
|
|
21
22
|
*/
|
|
22
|
-
export declare function logGatewayFetchAudit({ rawUrl, method, host, outcome, durationMs, injectedSecretValues, path, api, status, requestHeaders, requestBody, responseHeaders, responseBody, }: GatewayFetchAuditRecord): void;
|
|
23
|
+
export declare function logGatewayFetchAudit({ rawUrl, method, host, outcome, durationMs, injectedSecretValues, path, api, status, injectedScheme, requestHeaders, requestBody, responseHeaders, responseBody, }: GatewayFetchAuditRecord): void;
|
|
23
24
|
export {};
|
|
24
25
|
//# sourceMappingURL=fetch-audit.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{auditHeaderNames as
|
|
1
|
+
import{auditHeaderNames as n,auditInput as g,auditOutputDigest as b,auditSha256 as l,auditUrl as y,logAuditRecord as A}from"../../audit/audit-log.js";function R({rawUrl:e,method:u,host:i,outcome:r,durationMs:o,injectedSecretValues:t,path:_,api:h,status:f,injectedScheme:m,requestHeaders:p,requestBody:d,responseHeaders:c,responseBody:s}){const a=s===void 0?void 0:b(s);A("Record gateway fetch",{url_sha256:l(e),host:i,method:u,path:_,api:h,outcome:r,status:f,injected_scheme:m,duration_ms:o,url:y(e,t),request_header_names:n(p),request_body:d===void 0?void 0:g(d,t),response_header_names:n(c),response_sha256:a?.sha256,response_bytes:a?.bytes})}export{R as logGatewayFetchAudit};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Agent as
|
|
1
|
+
import{Agent as Q}from"undici";import{envConfig as Z}from"../../../../config/env-config.js";import{logger as N}from"../../../../tools/notifiers/logger.js";import{assertUrlAllowed as I}from"./ssrf-guard.js";import{createSsrfSafeLookup as q}from"./ssrf-safe-lookup.js";import{SsrfBlockedError as W}from"./ssrf-blocklist.js";import{GatewayFetchBlockedError as R,GatewayFetchSystemError as ee,GatewayFetchUserError as g}from"./fetch-errors.js";import{redactHeaders as J,redactSecretsFromString as te}from"./redact.js";import{extractUpstreamDetail as re}from"./upstream-detail.js";import{normalizeFetchPath as ne}from"./normalize-path.js";import{reportGatewayFetch as K}from"./fetch-telemetry.js";import{logGatewayFetchAudit as V}from"./fetch-audit.js";const X="x-forwarded-for",oe=3e4,se=1024*1024,ae=new Set([401,403,407]);let C;function ce(){if(!C){const e=Z.isDevelopMode;e&&N.warn("Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime)."),C=new Q({connect:{lookup:q({allowLoopback:e})}})}return C}function _e({allowedHosts:e,apis:t=[],authorization:r,onAuthRequired:n,fetchImpl:c=fetch,dispatcher:a=ce(),timeoutMs:h=oe,maxResponseBytes:l=se,maxFetchesPerExec:w,clientIp:k}){const f=[...e,...t.flatMap(o=>o.matchers)],$=[...new Set(t.map(o=>o.name).filter(Boolean))].join(", "),m=t.flatMap(o=>Object.values(o.secrets??{})),D=[r,...m.map(o=>o.value)].filter(o=>!!o),x=m.map(o=>o.header);let O=0;return async o=>{const y=o.method??"GET",T=Date.now();let B,b,A,E={},H,_,j;try{if(w!==void 0){const u=Math.max(0,w);if(O+=1,O>u)throw new g(`Outbound fetch budget exceeded (max ${u} fetches per execute); split the work across calls`)}const d=le(o.url,f,$);B=d.hostname,b=ne(d.pathname);const v=t.filter(u=>u.matchers.some(z=>z.test(d.hostname))),s=v.length===1?v[0]:void 0;A=s?.slug;const S=pe(o.securityScheme,s),F=S?[S]:s?ye(s,d.pathname,y):void 0,L=s&&F?Se(s,F):void 0,P=L?s?.secrets?.[L]:void 0,M=be({callerHeaders:o.headers,secret:P,authorization:r,clientIp:k,credentialHeaders:s?.credentialHeaders});E=M.headers,H=P&&!M.callerHeader?L:void 0;const G=new AbortController;j=setTimeout(()=>G.abort(),h);const i=await c(d,{method:y,headers:E,body:o.body,redirect:"manual",signal:G.signal,dispatcher:a});_=i.status;let U="";try{U=await we(i,l)}finally{if(ae.has(i.status)&&s&&n){const u=re(U,i.headers.get("content-type"),D);n({api:s.slug,name:s.name,status:i.status,...L?{scheme:L}:{},...F?.length?{schemes:[...F]}:{},...H?{sentScheme:H}:{},...M.callerHeader?{callerHeader:M.callerHeader}:{},...u?{detail:u}:{}})}}let p=Ae(i.headers);if(fe(i.status)){p=J(p,x);const{location:u}=p;u&&!he(u,d,f)&&delete p.location}return K({host:d.hostname,method:y,outcome:"success",durationMs:Date.now()-T,path:b,api:A,status:i.status,bytes:Buffer.byteLength(U,"utf8")}),V({rawUrl:d.href,method:y,host:d.hostname,outcome:"success",durationMs:Date.now()-T,injectedSecretValues:D,path:b,api:A,status:i.status,injectedScheme:H,requestHeaders:E,requestBody:o.body,responseHeaders:p,responseBody:U}),{status:i.status,statusText:i.statusText,ok:i.ok,headers:p,bodyText:U}}catch(d){const{outcome:v,userSafe:s}=ie(d),S=B??(s instanceof R?s.host:void 0)??ue(o.url)??"invalid-url";throw K({host:S,method:y,outcome:v,durationMs:Date.now()-T,path:b,api:A,status:_}),V({rawUrl:o.url,method:y,host:S,outcome:v,durationMs:Date.now()-T,injectedSecretValues:D,path:b,api:A,status:_,injectedScheme:H,requestHeaders:E,requestBody:o.body}),s||(N.error(`Gateway MCP fetch failed [${y} ${S}]: ${te(me(d),D)} headers=${JSON.stringify(J(E,x))}`),new ee("Upstream fetch failed due to an internal error"))}finally{j!==void 0&&clearTimeout(j)}}}function de(e){let t=e;for(let r=0;r<5&&t instanceof Error;r++){if(t instanceof g||t instanceof W)return t;t=t.cause}}function ie(e){const t=de(e);return{outcome:t instanceof R||t instanceof W?"blocked":t?"user_error":"system_error",userSafe:t}}function le(e,t,r){try{return I(e,t)}catch(n){throw n instanceof R&&r?new R(`${n.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${r}); other documented APIs can be read through the tools but not called.`,n.host):n}}function ue(e){try{return new URL(e).hostname||void 0}catch{return}}function fe(e){return e>=300&&e<400}function he(e,t,r){try{return!!I(new URL(e,t).href,r)}catch{return!1}}function me(e){if(!(e instanceof Error))return String(e);const t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function we(e,t){const r=Number(e.headers.get("content-length"));if(Number.isFinite(r)&&r>t)throw Y(t,r);if(!e.body)return"";const n=e.body.getReader(),c=new TextDecoder;let a=0,h="";try{for(;;){const{done:l,value:w}=await n.read();if(l)break;if(a+=w.byteLength,a>t)throw Y(t,a);h+=c.decode(w,{stream:!0})}return h+c.decode()}finally{await n.cancel().catch(()=>{})}}function Y(e,t){return new g(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ye(e,t,r){const n=e.routes?.find(c=>c.method===r&&c.pattern.test(t));return n?n.schemes:ge(e)}function Se(e,t){const r=t.filter(n=>e.secrets?.[n]);return r.length===0?t[0]:r.reduce((n,c)=>{const a=e.secrets?.[n]?.savedAt??0;return(e.secrets?.[c]?.savedAt??0)>a?c:n})}function pe(e,t){if(e==null)return;if(typeof e!="string")throw new g("securityScheme must be a security scheme name (a string)");if(!t)throw new g("securityScheme cannot be applied: the URL host does not identify exactly one callable API");const r=t.schemePriority??[];if(r.length>0&&!r.includes(e))throw new g(`Unknown securityScheme "${e}" for ${t.name}; valid values: ${r.join(", ")}`);return e}function ge(e){const t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];const r=(e.schemePriority??[]).filter(n=>t.includes(n));return[...r,...t.filter(n=>!r.includes(n))]}function be({callerHeaders:e,secret:t,authorization:r,clientIp:n,credentialHeaders:c}){const a={},h=new Set,l=t??(r?{header:"Authorization",value:r}:void 0),w=l?new Set((c??[]).map(f=>f.toLowerCase()).filter(f=>f!==l.header.toLowerCase())):new Set;for(const[f,$]of Object.entries(e??{})){const m=f.toLowerCase();m==="host"||m==="content-length"||m!==X&&(w.has(m)||(h.add(m),a[f]=$))}if(n&&(a[X]=n),!l)return{headers:a};const k=l.header.toLowerCase();return h.has(k)?{headers:a,callerHeader:k}:(a[l.header]=l.value,{headers:a})}function Ae(e){const t={};return e.forEach((r,n)=>{t[n.toLowerCase()]=r}),t}export{_e as buildFetchBridge,ce as getDefaultAgent,we as readCappedBody};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The upstream's own explanation of an auth failure: `title` and `detail` of a `problem+json`
|
|
3
|
+
* body, a `message`/`error` string of a plain JSON body, or a short text body. Whitespace is
|
|
4
|
+
* collapsed, injected secrets are redacted, and the result is capped so it fits in a hint.
|
|
5
|
+
*/
|
|
6
|
+
export declare function extractUpstreamDetail(bodyText: string, contentType: string | null, injectedSecretValues: readonly string[]): string | undefined;
|
|
7
|
+
//# sourceMappingURL=upstream-detail.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{redactSecretsFromString as c}from"./redact.js";const o=200;function l(t,e,r){const i=f(e)?u(t):t;if(!i)return;const n=c(i.replace(/\s+/g," ").trim(),r);if(n)return n.length>o?`${n.slice(0,o-1)}\u2026`:n}function f(t){return/[/+]json\b/i.test(t??"")}function u(t){let e;try{e=JSON.parse(t)}catch{return}if(typeof e!="object"||e===null||Array.isArray(e))return;const r=[e.title,e.detail].filter(s);return r.length>0?r.join(": "):[e.message,e.error].find(s)}function s(t){return typeof t=="string"&&t.trim()!==""}export{l as extractUpstreamDetail};
|
|
@@ -1,13 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { McpToolContext } from '../types.js';
|
|
2
2
|
import type { SandboxFetch } from '../codemode/types.js';
|
|
3
3
|
import type { UpstreamAuthRequiredEvent } from './upstream-auth.js';
|
|
4
|
-
export declare function getCallableApis(context: McpToolContext): ApiDescriptionInfo[];
|
|
5
|
-
/**
|
|
6
|
-
* Fetch capability at request/worker time is derived purely from the build-time stamps:
|
|
7
|
-
* `fetchEligible` is stamped per API by the lifecycle plugin under `isGatewayCapabilityEnabled`
|
|
8
|
-
* (entitlement + hide checks), and the map arriving here is already RBAC-filtered.
|
|
9
|
-
* No EntitlementsProvider read — this code runs in graphs where the provider is uninitialized.
|
|
10
|
-
*/
|
|
11
|
-
export declare function isFetchCapable(context: McpToolContext): boolean;
|
|
12
4
|
export declare function buildExecuteHostFetch(context: McpToolContext, onAuthRequired?: (event: UpstreamAuthRequiredEvent) => void): Promise<SandboxFetch>;
|
|
13
5
|
//# sourceMappingURL=fetch-capability.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildAllowedHostMatchers as
|
|
1
|
+
import{getCallableApis as l}from"./callable-apis.js";import{buildAllowedHostMatchers as a}from"./fetch/allowed-hosts.js";import{buildFetchBridge as m}from"./fetch/fetch-bridge.js";import{credentialHeadersOf as o,orderedSchemesOf as c,resolveUpstreamApiAuth as h}from"./upstream-auth-scheme.js";async function f(e,s){const i=await Promise.all(l(e).map(async r=>{const t=await h(e,r.relativePath);return{slug:r.relativePath,name:r.name,matchers:a(r.servers??[]),secrets:e.upstreamSecrets?.[r.relativePath],defaultScheme:t.defaultScheme,routes:t.routes,credentialHeaders:o(t.schemes),schemePriority:c(t.schemes)}}));return m({allowedHosts:a([]),apis:i,authorization:e.upstreamAuthorization,onAuthRequired:s,maxFetchesPerExec:e.gatewayFetchBudgetPerExec,clientIp:e.clientIp})}export{f as buildExecuteHostFetch};
|
|
@@ -6,6 +6,12 @@ export type UpstreamAuthRequiredEvent = {
|
|
|
6
6
|
status: number;
|
|
7
7
|
scheme?: string;
|
|
8
8
|
schemes?: string[];
|
|
9
|
+
/** Scheme whose stored credential the bridge actually sent; absent when nothing was injected. */
|
|
10
|
+
sentScheme?: string;
|
|
11
|
+
/** Lower-cased credential header the sandbox code set itself, which suppressed the injection. */
|
|
12
|
+
callerHeader?: string;
|
|
13
|
+
/** The upstream's own explanation of the failure, taken from the response body. */
|
|
14
|
+
detail?: string;
|
|
9
15
|
};
|
|
10
16
|
export declare function upstreamAuthKey(event: {
|
|
11
17
|
api: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const i="com.redocly/upstream-auth-required";function
|
|
1
|
+
const i="com.redocly/upstream-auth-required";function m(e){return`${e.api}\0${e.scheme??""}`}function h(e,n){const t=new Map;for(const o of n){const s=m(o),a=t.get(s);(!a||u(o)>u(a))&&t.set(s,o)}const r=[...t.values()];return r.length===0?e:{...e,_meta:{...e._meta,[i]:r}}}function u(e){return e.status!==401?0:e.sentScheme?2:1}function y(e){const n=e._meta?.[i];return Array.isArray(n)?n.filter(t=>typeof t?.api=="string"&&typeof t?.name=="string"&&typeof t?.status=="number").map(t=>{const r=Array.isArray(t.schemes)?t.schemes.filter(f=>typeof f=="string"):[],{schemes:o,sentScheme:s,callerHeader:a,detail:c,...p}=t;return{...p,...r.length>0?{schemes:r}:{},...typeof s=="string"?{sentScheme:s}:{},...typeof a=="string"?{callerHeader:a}:{},...typeof c=="string"?{detail:c}:{}}}):[]}function d(e){if(!e._meta||!(i in e._meta))return e;const{[i]:n,...t}=e._meta,r={...e};return Object.keys(t).length>0?r._meta=t:delete r._meta,r}export{i as UPSTREAM_AUTH_REQUIRED_META,y as readAuthRequiredMeta,d as stripAuthRequiredMeta,m as upstreamAuthKey,h as withAuthRequiredMeta};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{logger as
|
|
1
|
+
import{logger as E}from"../../../tools/notifiers/logger.js";import{getFeedbackClientIp as F}from"../../../web-server/utils/feedback-ip.js";import{getForwardedOrigin as g,getInternalOrigin as N}from"../../../web-server/utils/get-request-origin.js";import{GATEWAY_FETCH_LIMIT_DEFAULTS as v}from"../../../../constants/common.js";import{isObject as B}from"../../../../utils/guards/is-object.js";import{getAccessibleSkills as k}from"../../../utils/skills/get-accessible-skills.js";import{getSkillUrl as L}from"../../../utils/skills/get-skill-url.js";import{createDocsMcpServer as H}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as j,filterGraphqlDescriptionsByRbac as V}from"../utils.js";import{McpClientInputError as $,createMethodNotAllowedError as G,withErrorHandling as J}from"./errors.js";import{constructForbiddenResponse as Y,constructInvalidTokenResponse as z,constructUnauthorizedResponse as K,handleMcpAuth as W}from"../auth/auth-handlers.js";import{shouldHandleMcpAuth as X}from"../../../utils/rbac/should-handle-mcp-auth.js";import{canAnonymousAccessMcpFeature as Q}from"../../../utils/rbac/can-anonymous-access-mcp-feature.js";import{extractTokenFromAuthHeader as Z}from"../utils/jwt.js";import{resolveMcpClient as q}from"../utils/mcp-client.js";import{DEFAULT_DOCS_MCP_SERVER_NAME as x}from"../constants.js";import{withPathPrefix as ee}from"@redocly/theme/core/utils";import{PUBLIC_MCP_ROUTE as re}from"@redocly/theme/core/constants/mcp";import{canAccessFeature as oe}from"../../../utils/rbac.js";import{ANONYMOUS_AUTH_DETAILS as ne}from"../../../constants/rbac.js";import{DEFAULT_ANONYMOUS_VISITOR_TEAM as se,RbacFeatures as ie}from"../../../../constants/common.js";const h="X-Redocly-AI-Metadata";function te(r){if(r)try{const e=JSON.parse(r);if(B(e))return e;E.warn(`Ignoring ${h} header: not a JSON object.`)}catch{E.warn(`Ignoring ${h} header: invalid JSON.`)}}const ce=async(r,e,o)=>{const i=!!e?.config?.access?.requiresLogin,t=e?.config?.access?.rbac||{},A=o?.props?.config?.mcpMode??"tools",T=o?.props?.config?.gatewayFetchBudgetPerExec??v.budgetPerExec,b=o?.props?.config?.searchIgnoredRoutes??[],n=o,y=!!n?.props?.config?.isPublicEndpoint;let d;const M=r.headers.get("Authorization");if(y)e.user={...ne,email:"",idpAccessToken:void 0,idpId:void 0};else if(X(i,t)){const{isAuthenticated:l,isTokenValid:u,currentUser:p,accessToken:f}=await W(r,e);if(!l){const a=g(r),m=e.config.mcp?.docs?.publicEndpoint&&Q(t,i)?`${a}${ee(re)}`:void 0;return u===!1?z(a):K(a,m)}p&&(e.user=p),d=f}else M&&(d=Z(M||"")??void 0);const I={isAuthenticated:!!e.user?.isAuthenticated,teams:e.user?.teams||[se],claims:e.user?.claims??{}};if(!oe(ie.MCP,I,t,i))return Y();let c;return await J(async()=>{const l=o?.props?.config?.elicitationEnabled??!1;if(r.method==="GET")return new Response(JSON.stringify({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: ${r.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(r.method!=="POST")return G();const u=n?.props?.config?.apiDescriptionsMap||{},p=n?.props?.config?.graphqlDescriptions||[],f=n?.props?.config?.mcpDocsServerName||x,{config:{mcp:a={}}}=e,m=j(u,e.user,t,i),S=V(p,e.user,t,i),U=e.config.products?Object.values(e.config.products).map(s=>s?.name):[],w=a.docs?.name||f,R=te(r.headers.get(h)),C=n?.props?.tools||[],D=n?.props?.skillsBaseUrl||g(r),O=k(n?.props?.skills||[],e.user,t,i).map(s=>({slug:s.slug,name:s.name,description:s.description,content:s.content,uri:L(D,s.slug)})),_=await ae(r),P={name:w,tools:C,skills:O,context:{...e,accessToken:d,outdir:e.outdir||"",baseUrl:e.baseUrl||g(r),internalBaseUrl:N(r),apiDescriptionsMap:m,graphqlDescriptions:S,products:U,metadata:R,mcpMode:A,elicitationEnabled:l,gatewayFetchBudgetPerExec:T,searchIgnoredRoutes:b,clientIp:F(r),...q(r)}};return c=await H({...P,getKv:e.getKv}),await pe(r,c,_)},async()=>{c&&(await c.cleanup(),c=void 0)},A)};async function ae(r){try{return await r.json()}catch(e){throw new $(e instanceof Error?e.message:String(e),{cause:e})}}async function pe(r,e,o){return e.transport.handleRequest(r,o!==void 0?{parsedBody:o}:void 0)}var Pe=ce;export{Pe as default};
|
|
@@ -12,8 +12,13 @@ export declare class McpError extends Error {
|
|
|
12
12
|
constructor(code: McpErrorCodeTypes, message: string, data?: unknown, requestId?: string | number | null);
|
|
13
13
|
createErrorResponse(): Response;
|
|
14
14
|
}
|
|
15
|
+
export declare class McpClientInputError extends Error {
|
|
16
|
+
constructor(message: string, options?: {
|
|
17
|
+
cause?: unknown;
|
|
18
|
+
});
|
|
19
|
+
}
|
|
15
20
|
export declare function createMethodNotAllowedError(requestId?: string | number | null): Response;
|
|
16
|
-
export declare function createInternalServerError(error: Error | string, requestId?: string | number | null
|
|
21
|
+
export declare function createInternalServerError(error: Error | string, requestId?: string | number | null): Response;
|
|
17
22
|
export declare function createInvalidRequestError(message?: string, requestId?: string | number | null): Response;
|
|
18
23
|
export declare function createInvalidParamsError(message?: string, requestId?: string | number | null): Response;
|
|
19
24
|
export declare function withErrorHandling<T>(operation: () => Promise<T>, cleanup?: () => Promise<void>, mode?: McpMode): Promise<T | Response>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{telemetry as c}from"../../../telemetry/index.js";import{McpErrorCodes as
|
|
1
|
+
import{telemetry as c}from"../../../telemetry/index.js";import{McpErrorCodes as o,McpServerType as i}from"../constants.js";import{serverAttributes as d}from"../utils/telemetry-attributes.js";class n extends Error{code;data;requestId;constructor(e,t,s,a){super(t),this.name="McpError",this.code=e,this.data=s,this.requestId=a}createErrorResponse(){const e={jsonrpc:"2.0",error:{code:this.code,message:this.message,...this.data?{data:this.data}:{}},id:this.requestId??null},t=p(this.code);return new Response(JSON.stringify(e),{status:t,headers:{"Content-Type":"application/json"}})}}class u extends Error{constructor(e,t){super(e,t),this.name="McpClientInputError"}}function p(r){switch(r){case o.InvalidRequest:case o.InvalidParams:return 400;case o.MethodNotFound:return 404;case o.ServerError:return 405;case o.InternalError:default:return 500}}function f(r){return new n(o.ServerError,"Method not allowed",void 0,r).createErrorResponse()}function l(r,e){const t=r instanceof Error?r.message:String(r);return new n(o.InternalError,"Internal server error mcp",t,e).createErrorResponse()}function I(r="Invalid request",e){return new n(o.InvalidRequest,r,void 0,e).createErrorResponse()}function v(r="Invalid parameters",e){return new n(o.InvalidParams,r,void 0,e).createErrorResponse()}async function M(r,e,t="tools"){try{return await r()}catch(s){return c.sendMcpErrorMessage([{...d(i.Docs),message:s?.message||"",stack:s?.stack||"",error_class:s instanceof u?"client_error":"server_error",mode:t}]),e&&e(),l(s)}}export{u as McpClientInputError,n as McpError,l as createInternalServerError,v as createInvalidParamsError,I as createInvalidRequestError,f as createMethodNotAllowedError,M as withErrorHandling};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{withPathPrefix as g}from"@redocly/theme/core/utils";import{importApiRoutesHandler as D}from"../../../api-routes/import-api-routes-handlers.js";import{enhanceContext as h}from"../../../api-routes/helpers/enhance-context.js";import{telemetry as A}from"../../../telemetry/index.js";import{KvService as E}from"../../../persistence/kv/services/kv-service.js";import{envConfig as l}from"../../../config/env-config.js";import{acceptsHtml as R}from"../../../utils/ai-agent-detection.js";import{handleErrorPageRender as T}from"../../../web-server/utils.js";import{
|
|
1
|
+
import{withPathPrefix as g}from"@redocly/theme/core/utils";import{importApiRoutesHandler as D}from"../../../api-routes/import-api-routes-handlers.js";import{enhanceContext as h}from"../../../api-routes/helpers/enhance-context.js";import{telemetry as A}from"../../../telemetry/index.js";import{KvService as E}from"../../../persistence/kv/services/kv-service.js";import{envConfig as l}from"../../../config/env-config.js";import{acceptsHtml as R}from"../../../utils/ai-agent-detection.js";import{handleErrorPageRender as T}from"../../../web-server/utils.js";import{MCP_DOCS_SERVER_HANDLER_ID as _,MCP_NOT_ALLOWED_TEMPLATE_ID as w}from"../../../constants/mcp.js";import{resolvePublicBaseUrl as S}from"../../../web-server/utils/resolve-public-base-url.js";import{getForwardedOrigin as q}from"../../../web-server/utils/get-request-origin.js";import{applyEdgeRateLimit as O}from"../gateway-mcp/rate-limit/apply-edge-rate-limit.js";async function N(a,t,e){const n=t.req.raw;if(a.requestHandlerId===_&&n.method==="GET"&&R(n.headers.get("accept"))&&e.globalData.mcpData?.docs?.enabled)return T(t,e,{slug:a.slug},405,w);const r=t.get("auth"),s=await O(n,e);if(s)return s;const o=await e.resolveRouteStaticData(a)||{},m=g(a.slug),{requestHandlers:c}=await D(e.serverOutDir),p=c[a.requestHandlerId],d=(await p()).default,u=async()=>await E.getInstance({baseDbDir:e.serverOutDir,sqldRemoteDatabaseUrl:l.SQLD_REMOTE_DATABASE_URL,sqldRemoteDatabaseAuthToken:l.SQLD_REMOTE_DATABASE_AUTH_TOKEN}),f=h({honoCtx:t,ctx:{user:{teams:r.teams,email:r.claims.email,claims:r.claims,idpAccessToken:r.idpAccessToken,idpId:r.claims.idpId,isAuthenticated:r.isAuthenticated},config:e.config,outdir:e.outdir,baseUrl:q(t.req.raw)},telemetry:A,getKv:u}),i=await d(t.req.raw,f,{...o,props:{...o.props,routeSlug:m,outdir:e.outdir,skills:e.config.skills?.hide===!0?[]:e.getSkills(),skillsBaseUrl:S(e,t)}});return i instanceof Response?i:typeof i=="string"?new Response(i,{headers:{"Content-Type":"text/plain"}}):new Response(JSON.stringify(i),{headers:{"Content-Type":"application/json"}})}export{N as handleMcpRequest};
|