@redocly/framework 1.0.0-next.1 → 1.0.0-next.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundler/build/dependency-pack.js +1 -1
- package/dist/bundler/build/output-metadata.js +1 -1
- package/dist/bundler/build/run.js +1 -1
- package/dist/bundler/build/theme-global-style-compiler.js +1 -0
- package/dist/bundler/build/theme-global-stylesheets.js +1 -0
- package/dist/bundler/build/vite-config.js +2 -2
- package/dist/bundler/dev/dev-content-build.js +1 -0
- package/dist/bundler/dev/dev-problems.js +1 -1
- package/dist/bundler/dev/dev-reporter.js +1 -1
- package/dist/bundler/dev/routes/dev-content-build-route.js +1 -0
- package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
- package/dist/bundler/dev/routes/source-sync-route.js +1 -1
- package/dist/bundler/dev/run.js +1 -1
- package/dist/bundler/dev/runtime-app.js +1 -1
- package/dist/bundler/dev/vite-chunk-url.js +1 -1
- package/dist/bundler/dev/vite-config.js +1 -1
- package/dist/bundler/node-bundle.js +1 -0
- package/dist/bundler/runtime-files.js +1 -1
- package/dist/bundler/user-markdoc-schema.js +1 -1
- package/dist/bundler/vite-config.base.js +12 -12
- package/dist/cli/api-docs-build-event.js +1 -0
- package/dist/cli/args.js +1 -1
- package/dist/cli/commands/build.js +1 -1
- package/dist/cli/commands/dev.js +1 -1
- package/dist/cli/commands/ingest.js +1 -1
- package/dist/cli/commands/translate.js +1 -1
- package/dist/cli/dev-console/{sweep.js → content-build.js} +1 -1
- package/dist/cli/dev-console/index.js +1 -1
- package/dist/cli/dev-console/lines.js +2 -2
- package/dist/cli/dev-console/plain.js +1 -1
- package/dist/cli/dev-console/tui.js +2 -2
- package/dist/cli/output.js +12 -12
- package/dist/cli/problems-output.js +3 -3
- package/dist/cli/validate-react-pages.js +1 -1
- package/dist/client/ApiAccess.js +3 -0
- package/dist/client/NavigationProgress.js +1 -1
- package/dist/client/ProductsProvider.js +1 -1
- package/dist/client/RouteErrorBoundary.js +1 -1
- package/dist/client/RuntimeLink.js +1 -0
- package/dist/client/ThemeGlobalStyle.js +1 -0
- package/dist/client/UnversionedVersionButton.js +1 -1
- package/dist/client/ai-search/citations.js +3 -3
- package/dist/client/ai-search/use-ai-search.js +1 -1
- package/dist/client/analytics-page-view.js +1 -1
- package/dist/client/app.js +2 -7
- package/dist/client/classic-webview-sync.js +1 -0
- package/dist/client/client-entry.js +1 -1
- package/dist/client/contexts.js +1 -1
- package/dist/client/dev-problems/ProblemsBar.js +75 -15
- package/dist/client/dev-problems/ProblemsModal.js +15 -15
- package/dist/client/dev-problems/build-segment.js +1 -0
- package/dist/client/dev-problems/index.js +1 -1
- package/dist/client/dev-problems/use-dev-problems.js +1 -1
- package/dist/client/experiments/runtime.js +1 -1
- package/dist/client/feedback.js +1 -1
- package/dist/client/history-mount.js +1 -0
- package/dist/client/l10n/ssr-l10n.js +1 -1
- package/dist/client/l10n/use-l10n-config.js +1 -1
- package/dist/client/l10n/use-l10n-href.js +1 -1
- package/dist/client/l10n/use-translate.js +1 -1
- package/dist/client/page-sync.js +1 -0
- package/dist/client/products.js +1 -1
- package/dist/client/review/ReviewBar.js +163 -69
- package/dist/client/review/login-url.js +1 -0
- package/dist/client/review/use-review.js +1 -1
- package/dist/client/revisions-history.js +1 -1
- package/dist/client/sidebar/PoweredByRedocly.js +2 -2
- package/dist/client/sidebar/SidebarDataProvider.js +1 -1
- package/dist/client/sidebar/drilldown.js +1 -1
- package/dist/client/ssr.js +1 -1
- package/dist/client/telemetry/config.js +1 -1
- package/dist/client/telemetry/report-preload-failure.js +1 -0
- package/dist/client/templates/dev-login.js +4 -4
- package/dist/client/templates/unauthorized.js +5 -5
- package/dist/client/theme-global-css.js +1 -0
- package/dist/client/theme-logo.js +1 -1
- package/dist/client/use-banner.js +1 -1
- package/dist/client/use-bar-position.js +1 -0
- package/dist/client/use-entity-revisions.js +1 -1
- package/dist/client/use-page-versions.js +1 -1
- package/dist/client/use-router-for-local-links.js +1 -1
- package/dist/client/use-search.js +1 -1
- package/dist/client/utils/routes/is-router-path.js +1 -0
- package/dist/client/webmcp/tools/shared.js +1 -1
- package/dist/client/webmcp/tools/site-tools.js +1 -1
- package/dist/client/webmcp/use-webmcp-tools.js +1 -1
- package/dist/content-layer/allowed-packages.js +1 -1
- package/dist/content-layer/api-outputs.js +1 -1
- package/dist/content-layer/config-schema.d.ts +12 -3
- package/dist/content-layer/config-schema.js +1 -1
- package/dist/content-layer/config.d.ts +30 -12
- package/dist/content-layer/config.js +1 -1
- package/dist/content-layer/context-state.js +1 -1
- package/dist/content-layer/context.d.ts +2 -0
- package/dist/content-layer/context.js +1 -1
- package/dist/content-layer/database/adapters/node-sqlite-client.js +1 -1
- package/dist/content-layer/database/assets.js +1 -1
- package/dist/content-layer/database/connection.js +1 -1
- package/dist/content-layer/database/entity-store.d.ts +24 -3
- package/dist/content-layer/database/entity-store.js +1 -1
- package/dist/content-layer/database/invalidation.d.ts +6 -0
- package/dist/content-layer/database/invalidation.js +26 -26
- package/dist/content-layer/database/origins.d.ts +2 -4
- package/dist/content-layer/database/origins.js +1 -1
- package/dist/content-layer/database/problems.d.ts +2 -0
- package/dist/content-layer/database/problems.js +1 -1
- package/dist/content-layer/database/reset.js +1 -1
- package/dist/content-layer/database/schema.d.ts +50 -0
- package/dist/content-layer/database/schema.js +1 -1
- package/dist/content-layer/database/site-config.d.ts +23 -0
- package/dist/content-layer/database/site-config.js +1 -1
- package/dist/content-layer/ingest/extract-all-phase.js +1 -1
- package/dist/content-layer/ingest/finalize-phase.js +1 -1
- package/dist/content-layer/ingest/git-last-modified.js +3 -3
- package/dist/content-layer/ingest/hash.js +1 -1
- package/dist/content-layer/ingest/hook-inputs.js +1 -1
- package/dist/content-layer/ingest/markdoc-schema-problem.js +1 -0
- package/dist/content-layer/ingest/normalize-artifacts.js +1 -1
- package/dist/content-layer/ingest/rbac-teams.js +1 -1
- package/dist/content-layer/ingest/run.js +1 -1
- package/dist/content-layer/ingest/scan.d.ts +1 -1
- package/dist/content-layer/ingest/scan.js +1 -1
- package/dist/content-layer/ingest/search-sync.js +1 -1
- package/dist/content-layer/ingest/slugger/resolve-final-slugs.js +1 -1
- package/dist/content-layer/ingest/sync.js +1 -1
- package/dist/content-layer/link-checker/config-links.js +1 -1
- package/dist/content-layer/link-checker/delta.js +1 -1
- package/dist/content-layer/link-checker/fingerprint.js +1 -1
- package/dist/content-layer/link-checker/load-view.js +1 -1
- package/dist/content-layer/link-checker/node-ref.js +1 -1
- package/dist/content-layer/link-checker/run-build.js +1 -1
- package/dist/content-layer/link-checker/validate.js +1 -1
- package/dist/content-layer/link-checker/view.js +1 -1
- package/dist/content-layer/loaders/context.js +1 -1
- package/dist/content-layer/loaders/define.d.ts +3 -0
- package/dist/content-layer/markdown/client/JsonSchemaTag.js +1 -1
- package/dist/content-layer/markdown/client/OpenapiTagComponents.js +2 -2
- package/dist/content-layer/markdown/client/code-highlight-notation.js +3 -3
- package/dist/content-layer/markdown/client/dynamic-components.js +1 -1
- package/dist/content-layer/markdown/client/markdoc-components.js +2 -2
- package/dist/content-layer/markdown/client/markdown-text.js +1 -1
- package/dist/content-layer/markdown/constants/builtin-tags.js +1 -1
- package/dist/content-layer/markdown/constants/markdown-text-tag-set.js +1 -1
- package/dist/content-layer/markdown/constants/tag-sets.d.ts +20 -5
- package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
- package/dist/content-layer/markdown/nodes/heading.js +1 -1
- package/dist/content-layer/markdown/nodes/table.js +1 -1
- package/dist/content-layer/markdown/resolve/ast.js +1 -1
- package/dist/content-layer/markdown/resolve/attribute-resolver-key.d.ts +8 -1
- package/dist/content-layer/markdown/resolve/attribute-resolver-key.js +1 -1
- package/dist/content-layer/markdown/resolve/audience-tag.d.ts +2 -6
- package/dist/content-layer/markdown/resolve/audience-tag.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/code-snippet.js +5 -4
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/code-walkthrough/filesets.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/diagram-file.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/file-reference.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.d.ts +2 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/json-schema.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.d.ts +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/svg-content.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc.d.ts +2 -1
- package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
- package/dist/content-layer/markdown/resolve/raw-partials.d.ts +2 -1
- package/dist/content-layer/markdown/resolve/raw-partials.js +1 -1
- package/dist/content-layer/markdown/resolve/references.d.ts +3 -1
- package/dist/content-layer/markdown/resolve/references.js +1 -1
- package/dist/content-layer/markdown/resolve/render-diagrams.d.ts +8 -1
- package/dist/content-layer/markdown/resolve/render-diagrams.js +1 -1
- package/dist/content-layer/markdown/search/to-sections.d.ts +8 -3
- package/dist/content-layer/markdown/search/to-sections.js +1 -1
- package/dist/content-layer/markdown/search/to-text.d.ts +4 -1
- package/dist/content-layer/markdown/search/to-text.js +5 -5
- package/dist/content-layer/markdown/server/render.d.ts +4 -2
- package/dist/content-layer/markdown/server/render.js +1 -1
- package/dist/content-layer/markdown/service.js +1 -1
- package/dist/content-layer/markdown/tags/html.d.ts +5 -2
- package/dist/content-layer/markdown/tags/html.js +1 -1
- package/dist/content-layer/markdown/tags/markdoc-error.d.ts +8 -0
- package/dist/content-layer/markdown/tags/markdoc-error.js +1 -1
- package/dist/content-layer/markdown/tags/openapi.d.ts +1 -1
- package/dist/content-layer/markdown/tags/openapi.js +1 -1
- package/dist/content-layer/markdown/tags/partial.d.ts +9 -3
- package/dist/content-layer/markdown/tags/partial.js +1 -1
- package/dist/content-layer/markdown/tags/variant.d.ts +6 -0
- package/dist/content-layer/markdown/tags/variant.js +1 -0
- package/dist/content-layer/markdown/types/service.d.ts +6 -0
- package/dist/content-layer/markdown/utils/collect-anchors.js +1 -1
- package/dist/content-layer/markdown/utils/collect-headings.d.ts +3 -1
- package/dist/content-layer/markdown/utils/collect-headings.js +1 -1
- package/dist/content-layer/markdown/utils/first-heading.js +1 -1
- package/dist/content-layer/markdown/utils/heading-slugger.d.ts +8 -0
- package/dist/content-layer/markdown/utils/heading-slugger.js +1 -1
- package/dist/content-layer/markdown/utils/node-source-range.d.ts +3 -3
- package/dist/content-layer/markdown/utils/node-source-range.js +1 -1
- package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
- package/dist/content-layer/markdown/utils/reparse-example-fences.d.ts +4 -1
- package/dist/content-layer/markdown/utils/reparse-example-fences.js +1 -1
- package/dist/content-layer/markdown/utils/substitute-variables.js +1 -1
- package/dist/content-layer/markdown/utils/walk-markdoc-ast.d.ts +2 -2
- package/dist/content-layer/markdown/utils/walk-markdoc-ast.js +1 -1
- package/dist/content-layer/materialization/asset-reconcile.js +1 -1
- package/dist/content-layer/materialization/entity.js +1 -1
- package/dist/content-layer/materialization/materializer.js +1 -0
- package/dist/content-layer/materialization/static-files.js +1 -1
- package/dist/content-layer/plan-gates.d.ts +3 -2
- package/dist/content-layer/plan-gates.js +1 -1
- package/dist/content-layer/plugins/execute.js +1 -1
- package/dist/content-layer/plugins/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/event-handlers.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/rebase-item-links.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/client/template.js +12 -4
- package/dist/content-layer/plugins/internal/api-docs/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/build-definition.d.ts +28 -13
- package/dist/content-layer/plugins/internal/api-docs/server/build-definition.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/build-sidebar.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/declares-proto-service.d.ts +2 -0
- package/dist/content-layer/plugins/internal/api-docs/server/declares-proto-service.js +3 -0
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-copy.d.ts +14 -0
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-copy.js +23 -0
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-decorator.d.ts +1 -4
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-decorator.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/options.d.ts +4 -2
- package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/search-documents.d.ts +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/search-documents.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/spec-download.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/index.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/access.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/api-function-telemetry.js +1 -0
- package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/banner.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.d.ts +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/logo.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/products.d.ts +2 -0
- package/dist/content-layer/plugins/internal/app-data/products.js +1 -1
- package/dist/content-layer/plugins/internal/assets/index.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/client/catalog-filtering.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/resolve-items.d.ts +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/resolve-items.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/sidebars.d.ts +1 -1
- package/dist/content-layer/plugins/internal/index.js +1 -1
- package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/server/shared.d.ts +1 -1
- package/dist/content-layer/plugins/internal/mcp/app-data.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/constants.d.ts +20 -0
- package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/content-tools.d.ts +4 -1
- package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/agent-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/audit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/auth.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/code-credentials.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/codemode/capabilities.js +6 -6
- package/dist/content-layer/plugins/internal/mcp/server/codemode/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/discover.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/execute-schema.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/codemode/prompts.js +8 -8
- package/dist/content-layer/plugins/internal/mcp/server/config-gate.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/custom-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/allowed-http-methods.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/api-call-operations.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/call-api.js +2 -0
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-handler.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js +10 -10
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/outcome-pages.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/elicitation.js +6 -5
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/allowed-hosts.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-bridge.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/fetch-errors.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/ssrf-guard.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/fetch/upstream-detail.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/index.js +3 -3
- package/dist/content-layer/plugins/internal/mcp/server/gateway/secret-store.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/gateway/tool-list.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/gateway/tools.js +4 -4
- package/dist/content-layer/plugins/internal/mcp/server/gateway/upstream-auth-scheme.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/mcp-server.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/mcp-telemetry.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/authorize.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/callback.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/error-reporting.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/register.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/token.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/rate-limit.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-card.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/server-info.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/skills-resources.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/graphql-catalog.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-catalog.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-document.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-refs.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/tools/schemas.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/search.js +2 -2
- package/dist/content-layer/plugins/internal/mcp/server/workflows/catalog.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/document-resolver.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/operations-subset.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/resolve-workflows.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/run-workflow.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/schemas.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/tools.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/types.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/server/workflows/workflow-references.js +1 -0
- package/dist/content-layer/plugins/internal/mcp/setup-page.js +1 -1
- package/dist/content-layer/plugins/internal/mock/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/react-page/index.d.ts +3 -2
- package/dist/content-layer/plugins/internal/react-page/index.js +1 -1
- package/dist/content-layer/plugins/internal/scorecard-classic/client/Grid.js +11 -11
- package/dist/content-layer/plugins/internal/scorecard-classic/client/ScorecardViews.js +1 -1
- package/dist/content-layer/plugins/internal/scorecard-classic/client/ScorecardWidgets.js +7 -7
- package/dist/content-layer/plugins/internal/scorecard-classic/client/template.js +2 -2
- package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/bundle.d.ts +18 -17
- package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/index.d.ts +5 -3
- package/dist/content-layer/plugins/internal/sidebar/index.js +2 -2
- package/dist/content-layer/plugins/internal/sidebar/subtree.js +1 -1
- package/dist/content-layer/plugins/internal/skills/index.js +1 -1
- package/dist/content-layer/plugins/internal/skills/server/routes.js +1 -1
- package/dist/content-layer/plugins/internal/versions/index.js +1 -1
- package/dist/content-layer/plugins/io.js +1 -1
- package/dist/content-layer/plugins/project/load.js +2 -2
- package/dist/content-layer/plugins/registry.js +1 -1
- package/dist/content-layer/plugins/request-context.d.ts +5 -0
- package/dist/content-layer/plugins/source-file.js +1 -1
- package/dist/content-layer/plugins/types/api-entity.d.ts +2 -6
- package/dist/content-layer/plugins/types/api-entity.js +1 -1
- package/dist/content-layer/plugins/types/markdoc.d.ts +2 -0
- package/dist/content-layer/plugins/types/plugin.d.ts +13 -0
- package/dist/content-layer/plugins/types/search.d.ts +14 -3
- package/dist/content-layer/plugins/utils/link-access.d.ts +2 -0
- package/dist/content-layer/plugins/utils/link-access.js +1 -1
- package/dist/content-layer/plugins/utils/route-index.d.ts +1 -1
- package/dist/content-layer/plugins/utils/route-index.js +1 -1
- package/dist/content-layer/plugins/utils/sidebar-label.d.ts +4 -1
- package/dist/content-layer/plugins/utils/sidebar-label.js +1 -1
- package/dist/content-layer/plugins/utils/version-path.js +1 -1
- package/dist/content-layer/plugins/work-time.js +1 -0
- package/dist/content-layer/problems/codes.d.ts +10 -0
- package/dist/content-layer/problems/codes.js +1 -1
- package/dist/content-layer/revisions/config.js +1 -1
- package/dist/content-layer/revisions/read.js +1 -1
- package/dist/content-layer/search/engine/core/content-parser.js +1 -1
- package/dist/content-layer/search/facet-rows.js +1 -1
- package/dist/content-layer/search/keywords.d.ts +18 -0
- package/dist/content-layer/search/keywords.js +1 -0
- package/dist/content-layer/search/postings/fragment-field.d.ts +2 -0
- package/dist/content-layer/search/postings/fragment-field.js +1 -1
- package/dist/content-layer/search/postings/postings-store.d.ts +14 -0
- package/dist/content-layer/search/postings/postings-store.js +1 -1
- package/dist/content-layer/search/store.d.ts +14 -1
- package/dist/content-layer/server/context.js +1 -1
- package/dist/content-layer/server/database.js +1 -1
- package/dist/content-layer/server/materialize.js +1 -1
- package/dist/content-layer/static/audience.js +1 -1
- package/dist/content-layer/static/registry.js +1 -1
- package/dist/content-layer/versions/group-info.d.ts +22 -0
- package/dist/content-layer/versions/group-info.js +1 -0
- package/dist/content-layer/versions/redirect.d.ts +24 -17
- package/dist/content-layer/versions/redirect.js +1 -1
- package/dist/content-layer/versions/resolve.d.ts +1 -21
- package/dist/content-layer/versions/resolve.js +1 -1
- package/dist/content-layer/versions/version-groups.d.ts +5 -1
- package/dist/content-layer/versions/version-groups.js +1 -1
- package/dist/plugin-api.d.ts +3 -0
- package/dist/plugin-api.js +1 -1
- package/dist/server/analytics-tags.js +1 -1
- package/dist/server/app.js +3 -3
- package/dist/server/ask-ai/feature-gate.js +1 -1
- package/dist/server/ask-ai/route.js +1 -1
- package/dist/server/auth/access-config.js +1 -1
- package/dist/server/auth/gate.js +1 -1
- package/dist/server/auth/middleware.js +1 -1
- package/dist/server/auth/oidc.js +1 -1
- package/dist/server/auth/request.js +1 -1
- package/dist/server/auth/routes.js +1 -1
- package/dist/server/auth/runtime.js +1 -1
- package/dist/server/content-assets/access.js +1 -1
- package/dist/server/content.js +15 -14
- package/dist/server/cors-proxy/handler.js +1 -1
- package/dist/server/feedback/route.js +1 -1
- package/dist/server/html-tags.js +2 -1
- package/dist/server/lambda-entry.js +1 -1
- package/dist/server/llms-txt.js +1 -1
- package/dist/server/manifest-assets.js +5 -5
- package/dist/server/metrics/request-metrics.js +1 -1
- package/dist/server/node-entry.js +1 -1
- package/dist/server/page-handlers.js +1 -1
- package/dist/server/plugin-context.js +1 -1
- package/dist/server/plugin-routes.js +1 -1
- package/dist/server/public-url.js +1 -0
- package/dist/server/rbac/content-asset-access.js +1 -1
- package/dist/server/redirects.js +1 -1
- package/dist/server/replay-oauth2/route.js +1 -1
- package/dist/server/review/route.js +1 -1
- package/dist/server/runtime-config.js +1 -1
- package/dist/server/search/cache.js +1 -0
- package/dist/server/search/route.js +1 -1
- package/dist/server/search/search-telemetry.js +1 -0
- package/dist/server/seo-tags.js +2 -2
- package/dist/server/sitemap.js +1 -1
- package/dist/server/ssrf/ssrf-blocklist.js +1 -1
- package/dist/server/static-files/serve.js +1 -1
- package/dist/server/subprocess/child-entry.js +1 -1
- package/dist/server/subprocess/runner.js +1 -1
- package/dist/server/telemetry/mock-server-events.js +1 -0
- package/dist/server/telemetry/redirect-event.js +1 -0
- package/dist/server/telemetry/route.js +1 -1
- package/dist/server/telemetry/sender.js +1 -1
- package/dist/server/telemetry/server-events.js +1 -1
- package/dist/server/template-ids.js +1 -1
- package/dist/server/wait-until.js +1 -0
- package/dist/shared/constants/api-spec-kinds.d.ts +7 -0
- package/dist/shared/constants/api-spec-kinds.js +1 -0
- package/dist/shared/constants/content-update.js +1 -1
- package/dist/shared/constants/dependency-pack.js +1 -1
- package/dist/shared/constants/dev-content-build.js +1 -0
- package/dist/shared/constants/dev-problems.js +1 -1
- package/dist/shared/constants/dev-source-sync.js +1 -1
- package/dist/shared/constants/l10n/langs/ar.js +1 -1
- package/dist/shared/constants/l10n/langs/de.js +1 -1
- package/dist/shared/constants/l10n/langs/en.js +1 -1
- package/dist/shared/constants/l10n/langs/es.js +1 -1
- package/dist/shared/constants/l10n/langs/fr.js +1 -1
- package/dist/shared/constants/l10n/langs/hi.js +1 -1
- package/dist/shared/constants/l10n/langs/it.js +1 -1
- package/dist/shared/constants/l10n/langs/ja.js +1 -1
- package/dist/shared/constants/l10n/langs/ko.js +1 -1
- package/dist/shared/constants/l10n/langs/pl.js +1 -1
- package/dist/shared/constants/l10n/langs/pt-br.js +1 -1
- package/dist/shared/constants/l10n/langs/pt.js +1 -1
- package/dist/shared/constants/l10n/langs/ru.js +1 -1
- package/dist/shared/constants/l10n/langs/uk.js +1 -1
- package/dist/shared/constants/l10n/langs/zh.js +1 -1
- package/dist/shared/constants/manifest-version.d.ts +3 -1
- package/dist/shared/constants/openapi-operation-methods.d.ts +2 -0
- package/dist/shared/constants/openapi-operation-methods.js +1 -0
- package/dist/shared/constants/review.d.ts +7 -0
- package/dist/shared/constants/review.js +1 -1
- package/dist/{server → shared}/constants/system-routes.d.ts +2 -2
- package/dist/shared/constants/system-routes.js +1 -0
- package/dist/shared/constants/versions.d.ts +2 -0
- package/dist/shared/constants/versions.js +1 -1
- package/dist/shared/experiments.js +1 -1
- package/dist/shared/load-dot-env.js +1 -1
- package/dist/shared/plan-gates.d.ts +9 -3
- package/dist/shared/plan-gates.js +1 -1
- package/dist/shared/products.js +1 -1
- package/dist/shared/project-env.d.ts +12 -0
- package/dist/shared/project-env.js +1 -0
- package/dist/shared/public-env.d.ts +9 -0
- package/dist/shared/public-env.js +1 -1
- package/dist/{server → shared}/rbac/api-docs.d.ts +3 -2
- package/dist/shared/rbac/api-docs.js +1 -0
- package/dist/{server → shared}/rbac/engine.d.ts +13 -10
- package/dist/shared/rbac/engine.js +0 -0
- package/dist/{server → shared}/rbac/filter.d.ts +2 -0
- package/dist/shared/rbac/filter.js +1 -0
- package/dist/{server → shared}/rbac/l10n-rules.d.ts +1 -1
- package/dist/shared/rbac/l10n-rules.js +1 -0
- package/dist/{server → shared}/rbac/route-scope.d.ts +1 -1
- package/dist/shared/rbac/route-scope.js +1 -0
- package/dist/{server → shared}/rbac/team-templates.d.ts +6 -2
- package/dist/shared/rbac/team-templates.js +1 -0
- package/dist/{server → shared}/rbac/teams.d.ts +1 -1
- package/dist/shared/rbac/types.js +1 -0
- package/dist/shared/search/facets.d.ts +5 -0
- package/dist/shared/search/facets.js +1 -1
- package/dist/shared/types/auth.d.ts +1 -0
- package/dist/shared/types/config.d.ts +5 -0
- package/dist/shared/types/search.d.ts +8 -2
- package/dist/shared/types/sidebar.d.ts +1 -0
- package/dist/shared/utils/redirect-match.js +1 -0
- package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
- package/dist/shared/utils/routes/markdown-copy-url.js +1 -0
- package/drizzle/20261103061150_site_config_effective_hash/migration.sql +1 -0
- package/drizzle/20261105151816_search_http_path_tokens/migration.sql +1 -0
- package/drizzle/20261111152552_page_markdown_rbac_scope/migration.sql +1 -0
- package/package.json +37 -13
- package/dist/bundler/dev/__tests__/reset-content-update-state.js +0 -1
- package/dist/bundler/dev/materialization-sweeper.js +0 -1
- package/dist/client/dev-problems/sweep-segment.js +0 -1
- package/dist/client/review/use-bar-position.js +0 -1
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.d.ts +0 -5
- package/dist/content-layer/plugins/internal/api-docs/server/markdown-docs.js +0 -26
- package/dist/content-layer/plugins/internal/mcp/server/gateway/__tests__/fake-kv.js +0 -1
- package/dist/content-layer/server/config.js +0 -1
- package/dist/server/__tests__/rbac-fixture.js +0 -1
- package/dist/server/__tests__/test-session.js +0 -1
- package/dist/server/constants/system-routes.js +0 -1
- package/dist/server/rbac/api-docs.js +0 -1
- package/dist/server/rbac/engine.js +0 -0
- package/dist/server/rbac/filter.js +0 -1
- package/dist/server/rbac/l10n-rules.js +0 -1
- package/dist/server/rbac/route-scope.js +0 -1
- package/dist/server/rbac/team-templates.js +0 -1
- package/dist/server/rbac/types.js +0 -1
- package/dist/shared/utils/routes/markdown-path.js +0 -1
- /package/dist/{server → shared}/rbac/entity-scope.js +0 -0
- /package/dist/{server → shared}/rbac/teams.js +0 -0
- /package/dist/{server → shared}/rbac/types.d.ts +0 -0
- /package/dist/{content-layer/markdown → shared}/utils/packed-ast.d.ts +0 -0
- /package/dist/{content-layer/markdown → shared}/utils/packed-ast.js +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`),
|
|
3
|
-
`),
|
|
4
|
-
`);function
|
|
5
|
-
`)}},
|
|
1
|
+
import{CALL_API_WRITE_TOOL_NAME as e,READ_ONLY_ANNOTATIONS as t}from"../../constants.js";import{FETCH_TOOL_NAME as n}from"./constants.js";import{buildToolTypeDeclarations as r,sanitizeToolName as i}from"./tool-declarations.js";import{callableApis as a}from"../gateway/eligibility.js";import{getOfferedWriteHttpMethods as o,getSafeHttpMethods as s}from"../gateway/allowed-http-methods.js";import{EXECUTE_ARGS_NOTE as c,PLAIN_JAVASCRIPT_RULE as l,USAGE_NOTES as u,buildExecuteExample as d}from"./prompts.js";const f=["```ts",`/**`,` * Call a documented operation of a callable API. Undocumented paths and methods are refused.`,` * Responses cap at 1 MiB and redirects are not followed.`,` */`,`declare function fetch(url: string | URL, init?: {`,` method?: string;`," /** `content-type` is set automatically for URLSearchParams/FormData unless you set one. */",` headers?: Record<string, string>;`,` /** string · URLSearchParams (→ application/x-www-form-urlencoded) · FormData (→ multipart/form-data) */`,` body?: string | URLSearchParams | FormData;`," /** Security scheme name (from the operation's `security` or `getSecuritySchemes`) whose credential to send. Omit to let the server choose. */",` securityScheme?: string;`,`}): Promise<{`,` status: number;`,` statusText: string;`,` ok: boolean;`,` headers: { get(name: string): string | null };`,` json(): Promise<unknown>;`,` text(): Promise<string>;`,`}>;`,"```"].join(`
|
|
2
|
+
`),p=[`listApis`,`getEndpoints`,`getEndpointInfo`],m=[`Example - list the paid invoices of a billing API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const ep = endpoints.find((e) => e.method === 'GET' && e.path.includes('invoices'));`,`const info = await site.getEndpointInfo({ name: api.name, path: ep.path, method: ep.method });`,"// Replace every `{placeholder}` first.",`const url = new URL((info.servers?.[0]?.url ?? '') + ep.path);`,"// Every name below comes from `info.endpoint.parameters` - read them first, never guess them.",`url.searchParams.set('filter', 'status:paid');`,`url.searchParams.set('sort', '-createdTime');`,`url.searchParams.set('limit', '100');`,`try {`,` const res = await fetch(url, { method: ep.method });`,` return res.ok ? await res.json() : { status: res.status, error: await res.text() };`,`} catch (error) {`,` return { error: error instanceof Error ? error.message : String(error), endpointId: info };`,`}`,"```"].join(`
|
|
3
|
+
`),h=[`Example - call an endpoint you already read:`,``,"```js","// Call `getEndpointInfo` first for the server URL, the path, and the parameter names.","// Replace every `{placeholder}` first.",`const url = new URL('https://api.example.com/invoices');`,`url.searchParams.set('filter', 'status:paid');`,`try {`,` const res = await fetch(url, { method: 'GET' });`,` return res.ok ? await res.json() : { status: res.status, error: await res.text() };`,`} catch (error) {`,` return { error: error instanceof Error ? error.message : String(error) };`,`}`,"```"].join(`
|
|
4
|
+
`);function g(e){return p.every(t=>e.includes(t))?m:h}function _(e){let t=/* @__PURE__ */ new Map;for(let{name:n,version:r}of e){if(!n)continue;let e=t.get(n)??[];r&&e.push(r),t.set(n,e)}return[...t.entries()].map(([e,t])=>t.length>1?`${e} (${t.map(e=>`v${e}`).join(`, `)})`:e).join(`, `)}function v(t){let n=s(t.config.mcp),r=n.length>0?`\`fetch\` sends only ${n.join(`, `)} requests.`:"`fetch` sends no request on this project.",i=o(t);return i.length>0?`${r} Send a ${i.join(`, `)} request with the \`${e}\` tool.`:`${r} Explain any other call to the user instead of making it.`}const y={id:n,purpose:`Call the documented APIs over HTTP`,isActive:async e=>(await a(e)).length>0,annotations:{...t,openWorldHint:!0},async renderSection(e,t){let n=_(await a(e));return["## `fetch` — call the documented APIs",``,f,``,"Always call `getEndpointInfo` before `fetch` for the exact URL, required parameters, and body shape. Put filtering, sorting, and paging in the query parameters, and keep sandbox JS for what the endpoint cannot express. Never guess.",``,"An endpoint path can hold `{placeholders}`. Fill each one from `endpoint.parameters` before you call `fetch`. Server URLs come with their variable defaults filled in. A `{placeholder}` left in a server URL has no usable default, so ask the user for its value.",``,v(e),``,`Callable APIs (their documented hosts are reachable via \`fetch\`): ${n}`,``,g(t)].join(`
|
|
5
|
+
`)}},b=[y];async function x(e){let t=await Promise.all(b.map(t=>t.isActive(e)));return b.filter((e,n)=>t[n])}function S(e,n){let r=[...e.map(e=>e.annotations??{}),...n.map(e=>e.annotations)],i=r.filter(e=>e.readOnlyHint!==!0),a=r.some(e=>e.openWorldHint!==!1);return i.length===0?{...t,openWorldHint:a}:{readOnlyHint:!1,destructiveHint:i.some(e=>e.destructiveHint!==!1),idempotentHint:i.every(e=>e.idempotentHint===!0),openWorldHint:a}}async function C(e,t,n){let a=e.map(e=>i(e.name)),o=[];if(e.length>0){let t=r(e),n=t.includes(`OpenApi`)?`\n\n${u}`:``;o.push(`## Sandbox functions\n\nThe signatures are TypeScript declarations. ${l}\n\n${t}${n}`)}o.push(c),e.length>0&&!t.some(e=>e.id===`fetch`)&&o.push(d(a));for(let e of t)o.push(await e.renderSection(n,a));return o.join(`
|
|
6
6
|
|
|
7
|
-
`)}export{
|
|
7
|
+
`)}export{b as ALL_CAPABILITIES,f as FETCH_DECLARATION,S as composeExecuteAnnotations,y as fetchCapability,x as getActiveCapabilities,C as renderDiscoverOutput};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{CALL_API_WRITE_TOOL_NAME as e,CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r,MANAGE_API_CREDENTIALS_TOOL_NAME as i,REMOVE_API_CREDENTIALS_TOOL_NAME as a,SUBMIT_FEEDBACK_TOOL_NAME as o}from"../../constants.js";const s=`fetch`,c=/* @__PURE__ */ new Set([r,n,t,i,a,o,e]),l=`site`,u=`tools`,d=`__fetchBridge`,f=`fetch`,p=1e4,m=45e3,h=5e4,g=1e3,_=50,v=50,y={ratePerMin:600,quotaPerDay:1e5},b=8388608,x=1048576,S=1048576,C=262144,w=67108864,T=134217728,E=16777216,D=65536,O=2,k=4,A=5e3,j=`The sandbox failed to run this code. The cause was logged on the server.`,M=`HostFunctionError`,N=`HostOutputTooLargeError`,P={NoReturn:`no_return`,OutputTooLarge:`output_too_large`,Timeout:`timeout`,MemoryLimit:`memory_limit`,SyntaxError:`syntax_error`,HostError:`host_error`,RuntimeError:`runtime_error`};export{A as ACQUIRE_TIMEOUT_MS,c as CODE_MODE_TOOL_NAMES,m as DEFAULT_MAX_LIFETIME_MS,p as DEFAULT_TIMEOUT_MS,h as EXECUTE_DEADLINE_MS,f as FETCH_BRIDGE_FUNCTION_NAME,d as FETCH_BRIDGE_GLOBAL_NAME,s as FETCH_TOOL_NAME,v as GATEWAY_FETCH_BUDGET_PER_EXEC,y as GATEWAY_FETCH_LIMITS,M as HOST_FUNCTION_ERROR_NAME,N as HOST_OUTPUT_TOO_LARGE_ERROR_NAME,E as INITIAL_TOTAL_MEMORY_BYTES,j as INTERNAL_ERROR_MESSAGE,w as MAX_ALLOCATION_BYTES,O as MAX_CONCURRENT_RUNS,_ as MAX_FETCH_CALLS,x as MAX_FETCH_OUTPUT_BYTES,k as MAX_QUEUED_RUNS,S as MAX_RESULT_BYTES,C as MAX_STACK_SIZE_BYTES,g as MAX_TOOL_CALLS,b as MAX_TOOL_OUTPUT_BYTES,T as MAX_TOTAL_MEMORY_BYTES,P as SANDBOX_FAILURE,l as SITE_GLOBAL_NAME,u as TOOLS_GLOBAL_ALIAS,D as WASM_PAGE_BYTES};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{DISCOVER_TOOL_NAME as e}from"../../constants.js";import{UnknownToolError as
|
|
1
|
+
import{DISCOVER_TOOL_NAME as e,READ_ONLY_ANNOTATIONS as t}from"../../constants.js";import{UnknownToolError as n}from"../tool-errors.js";import{sanitizeToolName as r}from"./tool-declarations.js";import{buildDiscoverDescription as i}from"./prompts.js";import{renderDiscoverOutput as a}from"./capabilities.js";function o(n,a,o=!0){let s=[.../* @__PURE__ */ new Set([...n.map(e=>r(e.name)),...a.map(e=>r(e.id))])];return{name:e,title:`Get docs function signatures`,description:i(o),annotations:t,schema:{type:`object`,required:[],additionalProperties:!1,properties:{names:{type:`array`,description:o?`Names of the sandbox functions to discover: ${s.join(`, `)}. Omit to discover all of them.`:`Names of the sandbox functions to discover. Omit to discover all of them.`,items:s.length>0?{type:`string`,enum:s}:{type:`string`},nullable:!0}}}}}function s(e,t,i,o){let s=new Map(e.map(e=>[r(e.name),e])),c=new Set(i.map(e=>r(e.id)));return async l=>{let u=[...new Set((l.names??[]).map(r))],d=u.filter(e=>!s.has(e)&&!c.has(e));if(d.length>0){let e=[...s.keys(),...c];throw new n(`Unknown function name(s): ${d.join(`, `)}. Valid names: ${e.join(`, `)}.`)}let f=u.length===0?i:i.filter(e=>u.includes(r(e.id))),p=u.length===0?e:u.filter(e=>s.has(e)).map(e=>s.get(e)),m=await Promise.all(p.map(e=>t(e.name))),h=p.filter((e,t)=>m[t]),g=p.filter((e,t)=>!m[t]),_=[await a(h,f,o)];return g.length>0&&_.push(`Not available for this request: ${g.map(e=>r(e.name)).join(`, `)}`),{content:[{type:`text`,text:_.join(`
|
|
2
2
|
|
|
3
3
|
`)}]}}}export{s as discover,o as discoverSchema};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{EXECUTE_TOOL_NAME as e}from"../../constants.js";import{buildExecuteDescription as t}from"./prompts.js";const n=`Execute code`;function r(e){return e.readOnlyHint?`Query the docs with code`:n}const i={name:e,title:n,description:t(!1),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}}},
|
|
1
|
+
import{EXECUTE_TOOL_NAME as e}from"../../constants.js";import{buildExecuteDescription as t}from"./prompts.js";const n=`Execute code`;function r(e){return e.readOnlyHint?`Query the docs with code`:n}const i={name:e,title:n,description:t(!1),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}}}},a={result:{description:`The value the code returned, as JSON`},error:{type:`string`,description:`Why the code failed. Set only on a failed call`}},o={type:`array`,description:"Every `fetch` request that reached an API before the failure, with its status; running the code again sends them again. Set only on a failed call",items:{type:`object`,properties:{method:{type:`string`},url:{type:`string`},status:{type:`number`,description:`Unset when no response arrived`}}}};function s(e){return{type:`object`,properties:e?{...a,sentFetches:o}:a}}export{i as EXECUTE_TOOL_SCHEMA,s as executeOutputSchema,r as executeToolTitle};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{formatError as t,innerToolErrorClass as n}from"../tool-errors.js";import{auditCode as r,callAttribution as i,logCodeExecutionAudit as a,logMcpToolCallAudit as o,toolOutputText as s,toolResultText as c}from"../audit.js";import{CODE_MODE_TOOL_NAMES as l,INTERNAL_ERROR_MESSAGE as u,SANDBOX_FAILURE as d}from"./constants.js";import{availableTools as f}from"../tool-registry.js";import{sanitizeToolName as p}from"./tool-declarations.js";import{SandboxBusyError as m,sandboxAdmission as h}from"./admission.js";import{authoredPosition as g,returnLastExpression as _}from"./return-last-expression.js";import{createSandboxSetup as v}from"./sandbox-setup.js";import{createToolInputValidator as y}from"./tool-input-validator.js";import{describeGuestError as b}from"./unknown-tool-hint.js";import{isCallToolResult as x}from"@modelcontextprotocol/server";async function S(e){let{code:n,registry:o,ctx:s,timeoutMs:c}=e,y=await f(o,s),x=s.telemetry?.trackCodeExecution(n,e.hostFetch),S=x?.hostFetch??e.hostFetch,w=Object.create(null);for(let e of y){if(l.has(e.schema.name))continue;let t=p(e.schema.name);w[t]=C(e,t,s,x)}let T=Object.keys(w);a(s.logger,{audit:r(n),code:n,description:e.description??``,sessionHandle:e.sessionHandle,toolNames:T,fetchBudget:e.fetchBudget,fetchCapable:S!==void 0,...i(s)});let E=_(n),D;try{let{runInSandbox:e}=await import(`./sandbox.js`);D=await h.run(()=>e(E.code,{setupContext:v(w,S),authoredCode:n,timeoutMs:c,deadline:s.executeDeadline,logger:s.logger}))}catch(e){e instanceof m?D={error:e.message}:(s.logger?.error(`MCP code mode failed before a result: ${t(e)}`),D={error:u,failure:d.RuntimeError})}let O=D.error===void 0?void 0:b(n,D.error,D.errorPosition&&g(E,D.errorPosition),T,D.failure),k=O===void 0?{result:D.result}:{error:O.message},A={content:[{type:`text`,text:JSON.stringify(k)}],structuredContent:k,isError:O!==void 0};return x?.finish(D,A,O?.unknownTool),A}function C(e,r,a,l){let{name:
|
|
1
|
+
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{formatError as t,innerToolErrorClass as n}from"../tool-errors.js";import{auditCode as r,callAttribution as i,logCodeExecutionAudit as a,logMcpToolCallAudit as o,toolOutputText as s,toolResultText as c}from"../audit.js";import{CODE_MODE_TOOL_NAMES as l,INTERNAL_ERROR_MESSAGE as u,SANDBOX_FAILURE as d}from"./constants.js";import{availableTools as f}from"../tool-registry.js";import{sanitizeToolName as p}from"./tool-declarations.js";import{SandboxBusyError as m,sandboxAdmission as h}from"./admission.js";import{authoredPosition as g,returnLastExpression as _}from"./return-last-expression.js";import{createSandboxSetup as v}from"./sandbox-setup.js";import{createToolInputValidator as y}from"./tool-input-validator.js";import{describeGuestError as b}from"./unknown-tool-hint.js";import{isCallToolResult as x}from"@modelcontextprotocol/server";async function S(e){let{code:n,registry:o,ctx:s,timeoutMs:c}=e,y=await f(o,s),x=s.telemetry?.trackCodeExecution(n,e.hostFetch),S=x?.hostFetch??e.hostFetch,w=Object.create(null);for(let e of y){if(l.has(e.schema.name))continue;let t=p(e.schema.name);w[t]=C(e,t,s,x,{gatewayFetch:S})}let T=Object.keys(w);a(s.logger,{audit:r(n),code:n,description:e.description??``,sessionHandle:e.sessionHandle,toolNames:T,fetchBudget:e.fetchBudget,fetchCapable:S!==void 0,...i(s)});let E=_(n),D;try{let{runInSandbox:e}=await import(`./sandbox.js`);D=await h.run(()=>e(E.code,{setupContext:v(w,S),authoredCode:n,timeoutMs:c,deadline:s.executeDeadline,logger:s.logger}))}catch(e){e instanceof m?D={error:e.message}:(s.logger?.error(`MCP code mode failed before a result: ${t(e)}`),D={error:u,failure:d.RuntimeError})}let O=D.error===void 0?void 0:b(n,D.error,D.errorPosition&&g(E,D.errorPosition),T,D.failure),k=O===void 0?{result:D.result}:{error:O.message},A={content:[{type:`text`,text:JSON.stringify(k)}],structuredContent:k,isError:O!==void 0};return x?.finish(D,A,O?.unknownTool),A}function C(e,r,a,l,u){let{name:d}=e.schema,f=y(r,e.schema.schema),p={tool:d,mode:`code`,...i(a)},m=async r=>{let i=w(r,e.inputAliases),l=f(i);if(l)throw Error(l);let m;try{m=await e.execute(i,a,u)}catch(e){throw a.logger?.warn(`MCP tool "${d}" failed in code mode: ${t(e)}`),o(a.logger,{...p,args:r,errorClass:n(e)}),e}let h=x(m)&&m.isError===!0?m:void 0;if(o(a.logger,{...p,args:r,result:s(m),errorClass:h?`tool_error`:void 0}),h)throw Error(c(h));return m};return async e=>T(await(l?l.innerToolCall(d,()=>m(e)):m(e)))}function w(t,n){if(!n||!e(t))return t;let r={...t};for(let[e,t]of Object.entries(n))e in r&&(r[t]??=r[e],delete r[e]);return r}function T(e){if(!x(e))return e;if(e.structuredContent!==void 0)return e.structuredContent;let t=c(e);try{return JSON.parse(t)}catch{return t}}export{S as runCodeMode};
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`):
|
|
3
|
-
`)}function
|
|
4
|
-
`)}function
|
|
5
|
-
`)}function
|
|
6
|
-
`);function
|
|
7
|
-
`):``}const
|
|
8
|
-
`);export{
|
|
1
|
+
import{CALL_API_WRITE_TOOL_NAME as e}from"../../constants.js";import{buildToolList as t}from"./tool-list.js";const n=2048,r="Both `execute` arguments are required: `code` (the JavaScript to run; return a value to receive it) and `description` (a short human-readable summary of what the code does).",i="Write plain JavaScript: no type annotations, interfaces or `as` casts.";function a(e,r){if(r.length===0)return e;let i=n-e.length-66-3,a=t(r,i);return a?[e,``,"Functions for `execute` scripts (signatures come from `discover`):",a].join(`
|
|
2
|
+
`):e}function o(e,t){return[t?`Run plain JavaScript (no TypeScript syntax) in a sandbox against the documentation at ${t}. The script calls the sandbox functions on the global \`site\` object.`:"Run plain JavaScript (no TypeScript syntax) in a sandbox against this documentation site. The script calls the sandbox functions on the global `site` object.",e?"The extra globals are `site`, `fetch`, `URL`, `URLSearchParams`, and `FormData` - there is no `console`, `setTimeout`, `require`, or Node.js API; all other I/O goes through `site`.":"The only extra global is `site` - there is no `fetch`, `console`, `setTimeout`, `require`, or Node.js API; all I/O goes through `site`.",``,"Workflow - minimize round-trips; one `discover` call plus one `execute` call covers most requests:",`1. Analyze the request and decide which sandbox functions it needs.`,"2. Call `discover` with those names to get their exact TypeScript signatures - inputs, result shapes, and a worked example. NEVER call `execute` with guessed function names, parameter names, enum values, or result field names: read fields off the declared return types, not from assumptions.","3. Batch everything into a SINGLE script: chain function calls, pass one call's output into the next, process results in plain JavaScript, and `return` only what the request needs."].join(`
|
|
3
|
+
`)}function s(e,t){let r=e&&t(e);return r&&r.length<=n?r:t()}function c(e,t=[],n){return a(s(n,t=>o(e,t)),t)}function l(e){return e?`Tools for the documentation at ${e}.`:`Tools for this documentation site.`}function u(e){return`${l(e)} Use them to answer questions about the content of these docs.`}function d(e){return s(e,u)}function f(e){return["Get the exact TypeScript signatures of the sandbox functions that `execute` scripts can call.",`Analyze the user request first, then pass \`names\` with only the functions the request needs (${e?`every name is listed in this input schema / description`:`every name is in the enum of this input schema`}); omit \`names\` only when you cannot tell which functions apply.`,"Always call this before your first `execute` and never guess signatures. Request every function the task may need in ONE call instead of calling this repeatedly."].join(`
|
|
4
|
+
`)}function p({hasFetch:t,hasCallApiWrite:n,hasWorkflows:r,docsUrl:i}){let a=[u(i),"- `discover` returns the exact TypeScript signatures of the sandbox functions.","- `execute` runs a JavaScript script that calls those functions on the global `site` object.","Workflow: analyze the request, call `discover` once with `names` set to only the functions it needs, then batch everything into a single `execute` script. Minimize round-trips and never guess function signatures."];return t&&a.push("The sandbox also has a global `fetch` that can call the documented APIs (allow-listed hosts only). Include `fetch` in your `discover` call to get its contract and the list of callable APIs."),n&&a.push(`\`fetch\` sends only safe methods. Send one write request to a documented API with the \`${e}\` tool.`),r&&a.push("This project also ships ready-made multi-step API workflows. When a task needs several API calls, call `listWorkflows` first and run a matching workflow with `runWorkflow` instead of chaining `fetch` calls."),a.join(`
|
|
5
|
+
`)}function m(e){return a(s(e.docsUrl,t=>p({...e,docsUrl:t})),e.toolList??[])}const h=[`listApis`,`getEndpoints`],g=[`Example - list the write endpoints of an API:`,``,"```js",`const { items } = await site.listApis({ filter: 'billing' });`,`const [api] = items;`,`if (!api) return { error: 'no API matches "billing"' };`,`const { endpoints } = await site.getEndpoints({ name: api.name });`,`const writes = endpoints.filter((e) => e.method !== 'GET');`,"return { api: api.name, writes: writes.map((e) => `${e.method} ${e.path}`) };","```"].join(`
|
|
6
|
+
`);function _(e){if(h.every(t=>e.includes(t)))return g;let[t]=e;return t?[`Example - call \`${t}\` and return what the request needs:`,``,"```js",`const result = await site.${t}({ /* the input its signature above declares */ });`,`return result;`,"```"].join(`
|
|
7
|
+
`):``}const v=["Types named `OpenApi…` are the standard OpenAPI Specification objects.","Payload samples live on a media type object (`requestBody.content[mediaType]`, `responses[code].content[mediaType]`): `.example` holds a single value, `.examples[name].value` a named map, and some descriptions only set `.schema.example`. Read each before concluding a sample is absent."].join(`
|
|
8
|
+
`);export{r as EXECUTE_ARGS_NOTE,i as PLAIN_JAVASCRIPT_RULE,v as USAGE_NOTES,m as buildCodeModeInstructions,f as buildDiscoverDescription,c as buildExecuteDescription,_ as buildExecuteExample,d as buildToolsModeInstructions,l as docsSiteSentence};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{ANONYMOUS_VIEWER as e}from"../../../../../shared/types/auth.js";import{RBAC_TEAM_ANONYMOUS as t}from"../../../../../shared/rbac/types.js";import{canView as n,parseRbacScope as r,resolveRole as i}from"../../../../../shared/rbac/engine.js";import{resolveViewerTeams as a}from"../../../../../shared/rbac/teams.js";function o(e){return!!e.mcp?.hide}function s(e){return e!==void 0&&(Object.keys(e),!0)}function c(e){if(!e||typeof e!=`object`||Object.keys(e).length===0)return!1;let a=r(e,`rbac`,()=>{});return!n(i(a,[t]))}function l(e){let t=e.access?.rbac;return{requiresLogin:e.access?.requiresLogin===!0,rbacConfigured:s(t),rbacDeniesAnonymous:Object.values(t?.content??{}).some(c)||c(t?.features?.mcp),featureScope:t?.features?.mcp}}function u(e){return e.requiresLogin||e.rbacDeniesAnonymous}function d(t,n){return!!t.mcp?.publicEndpoint&&u(n)&&p(n,a(e),!1)}function f(e){return d(e,l(e))}function p(e,t,a,o=()=>{}){return e.rbacConfigured?e.featureScope===void 0||n(i(r(e.featureScope,`features.mcp`,o),t)):!e.requiresLogin||a}export{p as canAccessMcpFeature,u as isMcpContentProtected,o as isMcpHidden,d as isPublicEndpointServed,f as isPublicEndpointServedFromConfig,l as resolveMcpAccess};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{publicOrigin as e}from"../../../utils/request-origin.js";import{errorMessage as t}from"../../../../../shared/utils/error-message.js";import{isSubprocessError as n}from"../../../../../server/subprocess/runner.js";import{MCP_TOOLS_ENTITY_TYPE as r}from"../constants.js";import{ToolHandlerError as i}from"./tool-errors.js";import{fileURLToPath as a}from"node:url";import{parse as o}from"hono/utils/cookie";const s=a(import.meta.url);function c(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function l(e){return`MCP tool "${e}" is not registered or its module does not export a handler for "${e}". Expected \`export default { '${e}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`}function u(e,t){if(c(e))return typeof e.execute==`function`&&typeof e.description==`string`?e:e[t]}const d=/* @__PURE__ */ new Set([`text`,`image`,`audio`,`resource`,`resource_link`]);function f(e){return c(e)&&Array.isArray(e.content)&&e.content.every(e=>c(e)&&d.has(e.type))}function p(e,t){if(f(t))return t;if(typeof t==`string`)return{content:[{type:`text`,text:t}]};let n;try{n=JSON.stringify(t)}catch(t){throw Error(`MCP tool "${e}" returned a value that cannot be serialized to JSON: ${S(t)}`)}if(n===void 0)throw Error(`MCP tool "${e}" returned an invalid result.`);return{content:[{type:`text`,text:n}]}}const m={readFile:async()=>{throw Error(`Project files are not available in this environment.`)}};async function h(e,n){let r=u((await n.loadModule(e.handlerModulePath)).default,e.toolName),i=typeof r==`function`?r:r?.execute;if(typeof i!=`function`)return{ok:!1,code:`no-handler-export`,message:l(e.toolName)};let a={...e.context,fs:m};try{if(e.mode===`isAvailable`){let e=typeof r==`function`?void 0:r?.isAvailable;return{ok:!0,output:!e||await e(a)}}let t=await i(e.args,a,e.extra);return{ok:!0,output:p(e.toolName,t)}}catch(e){return{ok:!1,code:`handler-error`,message:t(e),stack:e instanceof Error?e.stack:void 0}}}function g(t){let n=t.request.viewer;return{user:{teams:t.request.teams,claims:t.claims??{...n},email:n?.email,idpAccessToken:void 0,idpId:void 0,isAuthenticated:n?.isAuthenticated??!1},config:t.config,baseUrl:e(t.request),params:{},query:Object.fromEntries(new URL(t.request.url).searchParams),cookies:o(t.request.headers.cookie??``),products:Object.values(t.config.products??{}).map(e=>e.name),accessToken:t.accessToken,metadata:t.metadata}}function _(e,t,n){if(!c(e)||e.type!==`object`)return null;let r=`Invalid arguments for tool "${n}":`;if(!c(t))return`${r} expected an object.`;let i=Array.isArray(e.required)?e.required:[];for(let e of i)if(typeof e==`string`&&!(e in t))return`${r} missing required field "${e}".`;let a=c(e.properties)?e.properties:{};for(let[e,n]of Object.entries(t)){let t=a[e];if(c(t)){if(typeof t.type==`string`&&!v(n,t.type))return`${r} field "${e}" must be ${t.type}.`;if(Array.isArray(t.enum)&&!t.enum.includes(n))return`${r} field "${e}" must be one of ${JSON.stringify(t.enum)}.`}}return null}function v(e,t){switch(t){case`string`:return typeof e==`string`;case`number`:return typeof e==`number`&&Number.isFinite(e);case`integer`:return typeof e==`number`&&Number.isInteger(e);case`boolean`:return typeof e==`boolean`;case`object`:return c(e);case`array`:return Array.isArray(e);case`null`:return e===null;default:return!0}}function y(e,t,n,r,i){if(!t.subprocess)throw Error(`MCP tool "${e.toolName}" cannot run on this host: no subprocess.`);return t.subprocess.run({modulePath:s,exportName:`invokeCustomTool`,input:{handlerModulePath:t.subprocess.resolveContentModule(e.handlerFilePath),toolName:e.toolName,mode:n,args:r,context:g(t),extra:{sessionId:i?.sessionId,requestId:i?.mcpReq.id??t.requestId,_meta:i?.mcpReq._meta}},reuse:!import.meta.env.DEV,timeoutMs:3e4})}function b(e,t){return{schema:e,isAvailable:t.hasAvailabilityGate?async n=>{if(!n.subprocess)return!1;let r=n.isAvailableMemo?.get(e.name);if(r)return r;let i=(async()=>{try{let e=await y(t,n,`isAvailable`);return e.ok&&e.output===!0}catch(t){return n.logger?.warn(`MCP tool "${e.name}" isAvailable failed: ${S(t)}`),!1}})();return n.isAvailableMemo?.set(e.name,i),i}:void 0,async execute(n,r,a){let o=_(t.argsSchema,n,e.name);if(o)throw Error(o);let s=await y(t,r,`execute`,n,a?.serverContext);if(!s.ok){let e=new i(s.message);throw e.stack=s.stack??e.stack,e}return s.output}}}function x(e){let{declaration:t}=e;return b({name:t.name,title:t.title,description:t.description,schema:t.schema,outputSchema:t.outputSchema,annotations:t.annotations},{toolName:t.name,handlerFilePath:e.handler.filePath,argsSchema:t.schema,hasAvailabilityGate:!0})}function S(e){return n(e)?`${e.code}: ${e.message}`:t(e)}function C(e,t){if(!c(t))return{ok:!1,errors:["the default export must be an object with `description` and `execute` properties. Move shared helper code outside the `@mcp` folder."]};let{description:n,inputSchema:r,outputSchema:i,annotations:a,isAvailable:o,execute:s}=t,l=[];return(typeof n!=`string`||n.trim()===``)&&l.push("`description` must be a non-empty string."),typeof s!=`function`&&l.push("`execute` must be a function."),r!==void 0&&(c(r)?r.type!==void 0&&r.type!==`object`&&l.push('`inputSchema.type` must be "object" because MCP tool arguments are named.'):l.push("`inputSchema` must be a JSON Schema object.")),i!==void 0&&!c(i)&&l.push("`outputSchema` must be a JSON Schema object."),a!==void 0&&!c(a)&&l.push("`annotations` must be an object."),o!==void 0&&typeof o!=`function`&&l.push("`isAvailable` must be a function."),l.length>0||typeof n!=`string`?{ok:!1,errors:l}:{ok:!0,schema:{name:e,description:n,schema:Object.assign({type:`object`},r??{properties:{}}),outputSchema:i,annotations:a},hasAvailabilityGate:typeof o==`function`}}async function w(e){let t=[],n=[];for(let i of await e.entities.list({type:r})){let{name:r,sourcePath:a}=i.metadata,o=e=>n.push(`Invalid MCP tool file "${a}": ${e}`);if(e.reservedNames.has(r)){o(`the tool name "${r}" is already used by a built-in MCP tool. Rename the file.`);continue}let s;try{s=(await e.loadContentModule(a)).default}catch(e){o(`the file failed to load: ${S(e)}. Tool files must not have module-level side effects.`);continue}let c=C(r,s);if(!c.ok){o(c.errors.join(` `));continue}t.push({schema:c.schema,sourcePath:a,hasAvailabilityGate:c.hasAvailabilityGate})}return{tools:t,errors:n}}function T(e){return`MCP tool "${e.schema.name}" in ${e.sourcePath} declares no \`outputSchema\`. Add one that describes the returned value.`}const E=/* @__PURE__ */ new Set;function D(e,t){e&&!E.has(t)&&(E.add(t),e.warn(t))}async function O(e){let{loadContentModule:t,logger:n}=e;if(!t)return[];let{tools:r,errors:i}=await w({entities:e.entities,loadContentModule:t,reservedNames:e.reservedNames});for(let e of i)D(n,e);for(let e of r)e.schema.outputSchema===void 0&&D(n,T(e));return r.map(e=>b(e.schema,{toolName:e.schema.name,handlerFilePath:e.sourcePath,argsSchema:e.schema.schema,hasAvailabilityGate:e.hasAvailabilityGate}))}export{O as buildMcpFileTools,x as createCustomTool,h as invokeCustomTool,w as loadMcpFileTools,T as missingOutputSchemaWarning,C as validateToolDefinition};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const
|
|
1
|
+
import"../../constants.js";import{isToolDisabledByCaller as e}from"../disabled-tools.js";const t=[`GET`,`HEAD`,`OPTIONS`],n=/* @__PURE__ */ new Set([`GET`,`HEAD`,`OPTIONS`,`QUERY`]);function r(e){return(e?.apiCalls?.allowedHttpMethods??t).map(e=>e.toUpperCase())}function i(e){return n.has(e)}function a(e){return r(e).filter(e=>n.has(e))}function o(e){return r(e).filter(e=>!n.has(e))}function s(t){return e(`call-api_write`,t.metadata)?[]:o(t.config.mcp)}export{r as getAllowedHttpMethods,s as getOfferedWriteHttpMethods,a as getSafeHttpMethods,o as getWriteHttpMethods,i as isSafeHttpMethod};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{OPERATION_METHODS as e
|
|
1
|
+
import{OPERATION_METHODS as e}from"../../../../../../shared/constants/openapi-operation-methods.js";import{isEndpointHidden as t}from"../tools/openapi-document.js";import{basePathPrefix as n,operationHttpMethod as r,pathPattern as i,pathTemplateKey as a,pathVariableCount as o}from"./route-pattern.js";const s=new Set(e);function c(e){return t(e,`apiCalls`)||t(e,`docs`)}function l(e,t,a,l=[]){let d=n(a),f=new Set(l.map(({method:e,path:t})=>u(e&&r(e),t))),p=[];for(let[n,a]of Object.entries(e.paths??{})){if(!a||typeof a!=`object`)continue;let e=i(d,n);if(!e)continue;let l=c(a)||f.has(u(void 0,n)),m=t.paths?.[n],h=o(n);for(let[t,i]of Object.entries(a)){if(!s.has(t.toLowerCase())||!i||typeof i!=`object`)continue;let a=r(t);p.push({path:n,pattern:e,method:a,callable:!l&&!c(i)&&!f.has(u(a,n)),visible:!!m?.[t],variables:h})}}return p}function u(e,t){return`${e??`*`} ${a(t)}`}function d(e,t,n){return e.filter(e=>e.method===n&&e.pattern.test(t))}export{l as apiCallOperationsOf,d as matchingApiCallOperations};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{SsrfBlockedError as e}from"../../../../../../server/ssrf/ssrf-blocklist.js";import{CALL_API_WRITE_TOOL_NAME as t,REQUIRES_USER_INTERACTION_META as n,WRITE_TOOL_ANNOTATIONS as r}from"../../constants.js";import{callableApis as i}from"./eligibility.js";import{getOfferedWriteHttpMethods as a}from"./allowed-http-methods.js";import{GatewayFetchSystemError as o,GatewayFetchUserError as s}from"./fetch/fetch-errors.js";import{runExecuteWithGateway as c}from"./index.js";import{SESSION_HANDLE_PROPERTY as l}from"./tools.js";const u=[`content-type`,`location`],d=/[/+]json\b/i;function f(e){return{name:t,title:`Call a documented API`,description:[`Send one request with a write method to one documented operation of a callable API.`,"Read the operation with `execute` first: the server URL, the path parameters, and the body shape. Pass the same `url`, `method`, `headers` and `body` you would pass to `fetch` in a script.",`Send only the operation the user asked for. When its method or operation is not allowed, tell the user and stop. Do not substitute another operation.`].join(`
|
|
2
|
+
`),annotations:r,_meta:n,schema:{type:`object`,required:[`url`,`method`],additionalProperties:!1,properties:{url:{type:`string`,minLength:1,description:"The full URL: a documented server URL of the API plus the operation path, with every `{placeholder}` filled and the query parameters included."},method:e.length>0?{type:`string`,enum:e}:{type:`string`},headers:{type:`object`,additionalProperties:{type:`string`},description:`The request headers. The stored credential is added by the server.`},body:{description:"The request body: a JSON value, sent as `application/json`, or a string, sent as is with the `content-type` header you pass."},securityScheme:{type:`string`,minLength:1,description:`The security scheme whose stored credential to send. Omit it to let the server choose.`},sessionHandle:l}},outputSchema:{type:`object`,required:[`status`,`headers`],properties:{status:{type:`number`},headers:{type:`object`,additionalProperties:{type:`string`}},body:{description:`The response body: parsed JSON for a JSON response, else text.`}}}}}function p(e,t){return Object.keys(e).some(e=>e.toLowerCase()===t)}function m({url:e,method:t,headers:n={},body:r,securityScheme:i}){return r===void 0||typeof r==`string`?{url:e,method:t,headers:n,body:r,securityScheme:i}:{url:e,method:t,headers:p(n,`content-type`)?n:{...n,"content-type":`application/json`},body:JSON.stringify(r),securityScheme:i}}function h({headers:e,bodyText:t}){if(!d.test(e[`content-type`]??``))return t;try{return JSON.parse(t)}catch{return t}}async function g(t,n){try{let e=await n(m(t)),r=Object.fromEntries(u.flatMap(t=>e.headers[t]===void 0?[]:[[t,e.headers[t]]])),i={status:e.status,headers:r,body:h(e)};return{content:[{type:`text`,text:JSON.stringify(i)}],structuredContent:i}}catch(t){if(!(t instanceof s||t instanceof o||t instanceof e))throw t;return{content:[{type:`text`,text:t.message}],isError:!0}}}async function _(e){return(await i(e)).length>0}const v={schema:f([]),schemaFor:e=>f(a(e)),isAvailable:async e=>a(e).length>0&&await _(e),execute(e,n,r){let i=e,o=r?.serverContext;if(!o)throw Error(`\`${t}\` runs only as a top-level tool call.`);return c({ctx:n,sessionHandle:i.sessionHandle,serverContext:o,allowedHttpMethods:a(n),run:e=>g(i,e)})}};export{v as callApiWriteTool};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{notFoundResponse as e}from"../../../../../../server/plugin-context.js";import{isMcpHidden as t}from"../config-gate.js";import{resolveMcpMode as n}from"../mode.js";import{isGatewayEnabled as r}from"./env.js";async function i(i,a){if(!r(a.config)||n()!==`code`||t(a.config))return e();let{serveCredentials:o}=await import(`./credentials.js`);return o(i,a)}export{i as mcpCredentials};
|
package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{withPathPrefix as e}from"../../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../../constants.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../../shared/path-prefix.js";import{MCP_CREDENTIALS_ROUTE as t}from"../../../constants.js";import{FORM_ACTIONS as n}from"./constants.js";import{secretTtlSeconds as r}from"../subject.js";import{ELICITATION_TTL_MS as i}from"../secret-store.js";import{credentialSchemesOf as a,schemeFieldName as o}from"./form-contract.js";import{ICONS as s,code as c,escapeHtml as l,siteHeader as u,targetTitle as d}from"./layout.js";const f=`form-error`,p=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),m={bearer:{title:`API token`,noun:`API token`,placeholder:`Paste your API token`},apiKey:{title:`API key`,noun:`API key`,placeholder:`Paste your API key`},cookie:{title:`Cookie`,noun:`cookie value`,placeholder:`Paste the cookie value`},oauth2ClientCredentials:{title:`OAuth2`,noun:`access token`,placeholder:`Paste an access token`},raw:{title:`Authorization header`,noun:`header value`,placeholder:`Bearer <token>`}};function h(r){let{site:o,target:c,token:p,error:m}=r,h=e(t),y=a(c),b=y.length>1,x=g(r,y),S=x.some(e=>e.isStored),C=b&&S,w=x.map(e=>b?v(e):_(e)).join(``),O=C?`<button class="text-danger" type="submit" form="remove-all">Remove all credentials</button>`:``,k=m?`<div class="banner" role="alert" id="${f}">${s.alert}<p>${l(m.message)}</p></div>`:``,j=c.subject.startsWith(`anon:`)?`<div class="banner warning">${s.warning}<p>This link is not tied to an account. The person who sent it to you can use the credentials that you save here. Continue only if you asked your AI client for this link at ${A(c.expiresAt-i)} UTC.</p></div>`:``;return{title:`Credentials for ${d(c)}`,body:`<div class="page">
|
|
2
2
|
<main class="card">
|
|
3
|
-
${u(
|
|
3
|
+
${u(o)}
|
|
4
4
|
<h1>${S?`Update`:`Add`} credentials for ${l(d(c))}</h1>
|
|
5
5
|
<p class="lede">${b?`This API accepts more than one kind of credential. Fill in the one that you have.`:`This API needs one credential to authenticate your calls.`}</p>
|
|
6
6
|
${j}
|
|
@@ -15,7 +15,7 @@ ${D(p,n.save)}
|
|
|
15
15
|
</form>
|
|
16
16
|
${E(h,p,x,C)}
|
|
17
17
|
</main>
|
|
18
|
-
${T(c,
|
|
18
|
+
${T(c,o.host)}
|
|
19
19
|
</div>`}}function g(e,t){let{target:n,stored:i,error:a,clientIds:o}=e,s=n.acceptedSchemes??[n.scheme],c=a?.schemeIndex??Math.max(0,t.findIndex(({name:e})=>s.includes(e))),l=t.length>1;return t.map((e,t)=>{let u=i[e.name],d=a?.schemeIndex===t?a:void 0;return{scheme:e,index:t,isMulti:l,title:l?e.name:m[e.auth.kind].title,savedAt:u?.savedAt,deletedAt:u?.savedAt===void 0?void 0:u.savedAt+r(n.subject)*1e3,isStored:u!==void 0,isOpen:t===c||s.includes(e.name)||u!==void 0,error:d,clientId:o?.[t]??``,autofocusField:t===c?d?.field??`secret`:void 0}})}function _(e){return`<section class="scheme" aria-labelledby="scheme-${e.index}-title">
|
|
20
20
|
<div class="scheme-body">
|
|
21
21
|
<div class="scheme-head">
|
|
@@ -40,20 +40,20 @@ ${y(e)}
|
|
|
40
40
|
<div class="field-row">
|
|
41
41
|
${C({view:e,field:`client_id`,type:`text`,label:`Client ID`,placeholder:`Enter the client ID`,value:e.clientId})}
|
|
42
42
|
${C({view:e,field:`client_secret`,type:`password`,label:`Client secret`,placeholder:`Enter the client secret`})}
|
|
43
|
-
</div>`}function C({view:e,field:t,type:n,label:r,placeholder:i,hint:
|
|
43
|
+
</div>`}function C({view:e,field:t,type:n,label:r,placeholder:i,hint:a,value:s,isRequired:c}){let u=o(t,e.index),d=e.error!==void 0&&e.error.field===t,p=`${u}-hint`,m=[a?p:``,d?f:``].filter(Boolean).join(` `),h=[`type="${n}"`,`id="${u}"`,`name="${u}"`,`placeholder="${l(i)}"`,`autocomplete="off"`,`autocapitalize="off"`,`spellcheck="false"`,s?`value="${l(s)}"`:``,m?`aria-describedby="${m}"`:``,d?`aria-invalid="true"`:``,c?`required`:``,e.autofocusField===t?`autofocus`:``].filter(Boolean);return`<div class="field">
|
|
44
44
|
<label for="${u}">${l(r)}</label>
|
|
45
45
|
<input ${h.join(` `)}>
|
|
46
|
-
${
|
|
47
|
-
</div>`}function w(e){if(!e||e.length===0)return``;let t=e.slice(0,10).map(e=>`<li>${c(e)}</li>`).join(``),n=e.length-10;return`<details class="operations"><summary>Which operations use it</summary><ul>${t}${n>0?`<li class="muted">and ${n} more</li>`:``}</ul></details>`}function T({name:e,subject:t,expiresAt:n},
|
|
48
|
-
<li>Sent straight to ${l(
|
|
46
|
+
${a?`<p class="muted small" id="${p}">${a}</p>`:``}
|
|
47
|
+
</div>`}function w(e){if(!e||e.length===0)return``;let t=e.slice(0,10).map(e=>`<li>${c(e)}</li>`).join(``),n=e.length-10;return`<details class="operations"><summary>Which operations use it</summary><ul>${t}${n>0?`<li class="muted">and ${n} more</li>`:``}</ul></details>`}function T({name:e,subject:t,expiresAt:n},a){let o=`${s.shield}What happens to your credentials`,c=`<ol class="steps">
|
|
48
|
+
<li>Sent straight to ${l(a)}, never through your AI client</li>
|
|
49
49
|
<li>Stored encrypted and never shown again</li>
|
|
50
50
|
<li>Added only to calls to ${l(e)} from the AI client that asked for this link</li>
|
|
51
51
|
<li>You can delete them anytime</li>
|
|
52
52
|
</ol>`;return`<aside class="panel" aria-labelledby="panel-title">
|
|
53
|
-
<div class="panel-steps"><h2 id="panel-title">${
|
|
54
|
-
<details class="panel-steps-toggle"><summary><h2>${
|
|
53
|
+
<div class="panel-steps"><h2 id="panel-title">${o}</h2>${c}</div>
|
|
54
|
+
<details class="panel-steps-toggle"><summary><h2>${o}</h2></summary>${c}</details>
|
|
55
55
|
<div class="link-facts">
|
|
56
|
-
<p>Link requested at ${A(n-
|
|
56
|
+
<p>Link requested at ${A(n-i)} UTC</p>
|
|
57
57
|
<span class="pill">Open until ${A(n)} UTC</span>
|
|
58
58
|
<p>This link works one time.</p>
|
|
59
59
|
<p>Kept for ${j(r(t))} after you save them.</p>
|
package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/outcome-pages.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{credentialSchemesOf as e}from"./form-contract.js";import
|
|
1
|
+
import"../secret-store.js";import{credentialSchemesOf as e}from"./form-contract.js";import{ICONS as t,code as n,escapeHtml as r,targetTitle as i}from"./layout.js";const a={success:t.check,danger:t.cross,neutral:t.cross,warning:t.clock};function o(t,{action:n,schemes:a,stored:o}){let s=n===`saved`,c=e(t).length>1,l=r(t.name),u=o.filter(e=>!a.includes(e)),d=c?`We ${n} ${p(a)} for ${l}.`:`We ${n} your credentials for ${r(i(t))}.`,m=o.length===0?`Calls to ${l} now go without credentials.`:u.length>0?`${s?`Also stored`:`Still stored`}: ${p(u)}.`:``;return f(s?`success`:`danger`,s?`Credentials saved`:`Credentials removed`,[d,m,s?`Go back to your AI client and tell it that you saved them.`:``])}function s(){return f(`neutral`,`Link declined`,[`We saved nothing, and this link no longer works.`,`If you did not ask for this link, tell your AI client to stop.`])}function c(){return f(`warning`,`This link no longer works`,[`The link is not valid, was already used, or is older than 15 minutes.`,`Ask your AI client for a new link.`])}const l=`If someone sent you this link, do not save credentials through it.`;function u(e,t){return f(`warning`,`Sign in to continue`,[`This link saves credentials for a signed-in user. If you asked your AI client for this link, sign in to ${r(e)} with the account that your AI client uses.`,`<a href="${r(t)}" target="_blank" rel="noopener">Sign in</a> in a new tab, then reload this page.`,l])}function d(e){return f(`danger`,`This link is for another account`,[e?`You are signed in as ${n(e)}. We saved nothing.`:`We saved nothing.`,`If you asked your AI client for this link, sign in with the account that your AI client uses, then reload this page.`,l])}function f(e,t,n){let i=n.filter(Boolean).map(e=>`<p>${e}</p>`).join(`
|
|
2
2
|
`),o=e===`warning`?``:`<p class="muted small">You can close this tab.</p>`;return{title:t,body:`<div class="page narrow">
|
|
3
3
|
<main class="card outcome">
|
|
4
4
|
<span class="status-icon ${e}">${a[e]}</span>
|
package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/site-branding.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{
|
|
1
|
+
import{APP_DATA_ENTITY_KEY as e}from"../../../../../../../shared/constants/app-data.js";import{toAppData as t}from"../../../../../../../shared/utils/app-data.js";import{parseSrcSet as n}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as r}from"../../../../../../../shared/constants/mcp.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(n){let a=t(await n.entities.load(e)),s=o({seo:n.config.seo,logo:a.theme?.logo,colorMode:n.config.colorMode}),c=await n.entities.get(`mcp:credentials-theme`)?await n.entities.load(r):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(n.request)).host}}function o({seo:e,logo:t,colorMode:r}){let i={},a=e?.title||e?.projectTitle||t?.altText;a&&(i.name=a);let o=new Map((t?.srcSet?n(t.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??t?.image),u=c(o.get(`dark`));l&&(i.logo=u?{light:l,dark:u}:{light:l});let d=s(r);return d&&(i.colorScheme=d),i}function s(e){if(e?.hide)return`light`;if(e?.ignoreDetection)return e.modes?.[0]===`dark`?`dark`:`light`}function c(e){return e?.startsWith(`/`)&&!e.startsWith(`//`)?e:void 0}export{a as loadPageSite,o as resolveSiteBranding};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{SystemRoute as t}from"../../../../../../shared/constants/system-routes.js";import{FORM_ACTIONS as n}from"./credentials-page/constants.js";import{userSubject as r}from"./subject.js";import{rejectCredential as i}from"./credential-validation.js";import{SecretStore as a}from"./secret-store.js";import{buildAllowedOriginMatchers as o}from"./fetch/allowed-hosts.js";import{assertUrlAllowed as s}from"./fetch/ssrf-guard.js";import{getDefaultAgent as c,readCappedBody as l}from"./fetch/fetch-bridge.js";import{credentialSchemesOf as u,schemeFieldName as d}from"./credentials-page/form-contract.js";import{htmlDocument as f}from"./credentials-page/layout.js";import{formPage as p}from"./credentials-page/form-page.js";import{declinedPage as m,expiredPage as h,otherAccountPage as g,outcomePage as _,signInPage as v}from"./credentials-page/outcome-pages.js";import{loadPageSite as y}from"./credentials-page/site-branding.js";const b={"Content-Type":`text/html; charset=utf-8`,"Cache-Control":`no-store`,"X-Frame-Options":`DENY`,"Referrer-Policy":`no-referrer`,"Content-Security-Policy":`default-src 'none'; style-src 'unsafe-inline'; img-src 'self'; form-action 'self'; frame-ancestors 'none'; base-uri 'none'`},x=/^bearer\s+/i,S=/^\d+$/;async function C(e,t){let{kv:r}=t,i=new a(t.gatewaySecretSeed);if(e.req.method===`GET`){let n=await y(t),a=e.req.query(`token`)??``,o=await i.peekElicitation(r,a);return o?R(o,t,n)??M({secretStore:i,kv:r,site:n,token:a,target:o},{},200):L(n)}if(e.req.method===`POST`){let a=await y(t),o=await e.req.formData(),s=F(o,`token`),c=await i.peekElicitation(r,s);if(!c)return L(a);let l=R(c,t,a);if(l)return l;let d={secretStore:i,kv:r,site:a,token:s,target:c,form:o,ctx:t};switch(F(o,`action`)){case n.remove:return O(d,k(c,F(o,`scheme`)));case n.removeAll:return O(d,u(c));case n.decline:return A(d);default:return w(d)}}return new Response(`Method Not Allowed`,{status:405,headers:{Allow:`GET, POST`}})}async function w(e){let{target:t,form:n,ctx:r}=e,i=u(t),a=i.map((e,t)=>F(n,d(`client_id`,t)).trim()),o=t=>M(e,{error:t,clientIds:a},400),s=T(i,n);if(`error`in s)return o(s.error);if(s.writes.length===0)return o(E(i));let c=[];for(let e of s.writes){if(e.kind!==`exchange`){c.push(e);continue}let n=await N(e.auth,e.clientId,e.clientSecret);if(!n.ok)return r.logger?.warn(`gateway oauth2 client_credentials exchange failed for ${t.api}: ${n.reason}`),o(D(i,e.schemeIndex,`client_id`,`We could not exchange those client credentials for a token. Check the client ID and secret, then try again.`));c.push({kind:`set`,scheme:e.scheme,secret:n.secret})}return j(e,c)}function T(e,t){let n=[];for(let[r,a]of e.entries()){let o=F(t,d(`secret`,r)).trim();if(o){let t=i(a.auth,o);if(t)return{error:D(e,r,`secret`,t)};n.push({kind:`set`,scheme:a.name,secret:z(a.auth,o)});continue}if(a.auth.kind!==`oauth2ClientCredentials`)continue;let s=F(t,d(`client_id`,r)).trim(),c=F(t,d(`client_secret`,r)).trim();if(s&&c)n.push({kind:`exchange`,scheme:a.name,schemeIndex:r,auth:a.auth,clientId:s,clientSecret:c});else if(s||c)return{error:D(e,r,s?`client_secret`:`client_id`,`Enter both the client ID and the client secret, or leave both blank.`)}}return{writes:n}}function E(e){return e.length>1?{message:`Fill in at least one credential before saving.`}:{message:e[0].auth.kind===`oauth2ClientCredentials`?`Enter an access token, or the client ID and the client secret, before saving.`:`Enter a value before saving.`,schemeIndex:0,field:`secret`}}function D(e,t,n,r){return{message:e.length>1?`${e[t].name}: ${r}`:r,schemeIndex:t,field:n}}async function O(e,t){let{secretStore:n,kv:r,target:i}=e,a=await n.getStoredSchemes(r,i.subject,i.api),o=t.filter(e=>a[e.name]).map(e=>({kind:`remove`,scheme:e.name}));return o.length===0?M(e,{error:{message:`No credential is stored there, so there is nothing to remove.`}},400):j(e,o)}function k(e,t){let n=S.test(t)?u(e)[Number(t)]:void 0;return n?[n]:[]}async function A({secretStore:e,kv:t,site:n,token:r}){return await e.consumeElicitation(t,r)?I(n,m(),200):L(n)}async function j({secretStore:e,kv:t,site:n,token:r},i){let a=await e.consumeElicitation(t,r);if(!a)return L(n);for(let n of i)n.kind===`remove`?await e.deleteSecret(t,a.subject,a.api,n.scheme):await e.setSecret(t,a.subject,a.api,n.scheme,n.secret);let o=await e.getStoredSchemes(t,a.subject,a.api),s={action:i.some(e=>e.kind===`set`)?`saved`:`removed`,schemes:i.map(e=>e.scheme),stored:Object.keys(o).sort()};return I(n,_(a,s),200)}async function M({secretStore:e,kv:t,site:n,token:r,target:i},a,o){let s=await e.getStoredSchemes(t,i.subject,i.api);return I(n,p({site:n,target:i,token:r,stored:s,...a}),o)}async function N(e,t,n){try{let r=o([{url:e.tokenUrl}]),a=s(e.tokenUrl,r),u=new AbortController,d=setTimeout(()=>u.abort(),3e4),f;try{f=await fetch(a,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams({grant_type:`client_credentials`,client_id:t,client_secret:n}),redirect:`manual`,signal:u.signal,dispatcher:c()})}finally{clearTimeout(d)}if(!f.ok)return P(`token endpoint returned ${f.status}`);let p;try{p=await l(f,65536)}catch{return P(`token response exceeded the size cap`)}let m;try{m=JSON.parse(p)}catch{return P(`token response was not valid JSON`)}let h=typeof m==`object`&&m&&`access_token`in m?m.access_token:void 0,g=typeof h==`string`?h.trim():``;return g?i(e,g)?P(`token response had an access_token that cannot be sent in a header`):{ok:!0,secret:{header:`Authorization`,value:`Bearer ${g}`}}:P(`token response had no access_token`)}catch(e){return P(e instanceof Error?e.message:String(e))}}function P(e){return{ok:!1,reason:e}}function F(e,t){let n=e.get(t);return typeof n==`string`?n:``}function I(e,t,n){return new Response(f(t,e),{status:n,headers:b})}function L(e){return I(e,h(),404)}function R(n,i,a){if(!n.subject.startsWith(`user:`))return;let{viewer:o}=i.request,s=r(o);if(s===n.subject)return;if(s)return I(a,g(o?.email),403);let c=`${e(t.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,v(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t,MCP_CREDENTIALS_ROUTE as n}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import
|
|
2
|
-
`)}async function
|
|
1
|
+
import{withPathPrefix as e}from"../../../../../../shared/path-prefix.js";import{MANAGE_API_CREDENTIALS_TOOL_NAME as t,MCP_CREDENTIALS_ROUTE as n}from"../../constants.js";import{ANONYMOUS_SUBJECT_PREFIX as r}from"./subject.js";import"./secret-store.js";import{operationsForScheme as i,orderedSchemesOf as a}from"./upstream-auth-scheme.js";import{CLIENT_CAPABILITIES_META_KEY as o,inputRequired as s,inputResponse as c}from"@modelcontextprotocol/server";const l=`credentials`,u=/* @__PURE__ */ new Map;function d(e,t){let n=u.get(e);if(n)return n;let r=t().finally(()=>{u.delete(e)});return u.set(e,r),r}function f(e){return!!(e.envelope?.[o])?.elicitation?.url}function p(e){return e.envelope!==void 0}function m(e){let t=c(e,l);if(t.kind===`elicit`)return t.action===`accept`?`accepted`:`declined`}function h(e,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${e}" API.`,...n?[`The credentials page:`,n]:[],``,r?`Wait until the user says they saved the credentials, then retry the call that needed them. Do not call \`${t}\` again unless the user asks for a new link.`:`Wait until the user says they saved the credentials, then retry the call that needed them.`].join(`
|
|
2
|
+
`)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:N(i,e)}}function _(e,t){return Object.keys(e).length>1?t:void 0}async function v(e){let{token:t,url:n}=await C(e);return s({inputRequests:{[l]:s.elicitUrl({message:E(e),url:n})},requestState:t})}async function y(e){let{url:t}=await C(e);return P(e,t,T(e.subject))}function b(e,{schemeLabel:n,canManageCredentials:r}){let i=S(e);if(!e.sentScheme&&(e.status===401||!e.schemes))return[`The "${e.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,e.unsupportedSchemes?`Do not replace them. This operation accepts only ${e.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Use a different route.`:`Do not replace them. Check whether this operation needs a different kind of credential or a different route.`].join(`
|
|
3
|
+
`);if(e.status===403&&e.sentScheme)return[`The "${e.name}" API refused this operation with the stored ${n?`"${n}" `:``}credential (${i}). Usually the credential lacks a permission or role for it.`,``,`Tell the user what the API answered and that they need a credential with access to this operation.`,...r?[``,...x(e),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${t}\` with api: "${e.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
|
|
3
4
|
`);let a=e.status===401?`The "${e.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${e.name}" API rejected the request with ${i}.`;if(!r)return[a,``,e.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
|
|
4
|
-
`);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"
|
|
5
|
-
`)}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({
|
|
6
|
-
`)}export{
|
|
5
|
+
`);let o=n?`api: "${e.api}" and scheme: "${n}"`:`api: "${e.api}"`;return[a,``,...x(e),`Do not retry the same call. Call \`${t}\` with ${o} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
|
|
6
|
+
`)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:N(r,c)}}function w(e){return a(e.schemes).map(t=>{let n=i(e,t);return{name:t,label:e.descriptions?.[t],auth:e.schemes[t],operations:n.length>0?n:void 0}})}function T(e){return e.startsWith(`anon:`)?e.slice(r.length):void 0}function E({target:e,hasExistingSecret:t,reason:n}){let r=`The link works for 15 minutes.`,i=D(e),a=n.kind===`authFailure`&&n.detail?` The API answered: ${n.detail}.`:``,o=k(A(n)),s=o?j(n)?` The AI agent asked for this scheme, so the stored credentials (${o}) were not sent.`:` This operation does not take the stored credentials (${o}).`:``;return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They stay out of the chat. ${r}`:`${O(i)} needs credentials.${a}${s} Open this page in a browser to paste them - they stay out of the chat. ${r}`}function D({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function O(e){return e.charAt(0).toUpperCase()+e.slice(1)}function k(e,t=`, `){return e.map(e=>`"${e}"`).join(t)}function A(e){return e.kind===`authFailure`?e.unsentStoredSchemes??[]:[]}function j(e){return e.kind===`authFailure`&&e.isSchemeRequested===!0}function M(e,t){let n=k(A(t));if(!n)return[];let r=k(e.acceptedSchemes??[e.scheme],` or `);return j(t)?[`The stored credentials of this API (${n}) were not sent: the call set securityScheme to ${r}.`,`Without securityScheme, the server sends a stored credential when the operation takes one.`]:[`The stored credentials of this API (${n}) were not sent: this operation takes only ${r}.`,`If the user has no credential for ${r}, tell them that this operation does not take the stored credentials, and do not retry it.`]}function N(t,r){let i=new URL(e(n),t);return i.searchParams.set(`token`,r),i.toString()}function P({target:e,reason:t,hasExistingSecret:n},r,i){let a=n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`,o=A(t).length>0?`Once the user confirms they saved a credential for ${k(e.acceptedSchemes??[e.scheme],` or `)}, retry the call that needed it`:`Once the user confirms they saved them, retry the call that needed them`,s=[`**Stop and show the user this link. They have to open it in a browser to ${a} - nothing continues until they do.**`,``,r,``,`The link is valid 15 minutes and opens a form on this site. The site stores the credentials and adds them to API calls: never ask for them in the conversation and never pass them as a tool argument.`,``,t.kind===`authFailure`?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:``} and needs credentials.`:n?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],...M(e,t),i?`${o} with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`${o} - the credentials are applied server-side and never appear in the conversation.`],c=t.kind===`authFailure`?t.otherApiNames??[]:[];if(c.length>0){let e=c.map(e=>`"${e}"`).join(`, `);s.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return s.join(`
|
|
7
|
+
`)}export{l as CREDENTIALS_INPUT_REQUEST_KEY,g as acceptedCredentialsLink,h as buildCredentialsAcceptedHint,b as buildCredentialsToolHint,y as buildUpstreamCredentialFallback,v as buildUpstreamCredentialInputRequired,m as credentialElicitationAnswer,d as dedupeElicitation,p as isStatelessRequest,_ as schemeLabelOf,f as supportsUrlElicitation};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=/\{(?<!\{[^}]*?\{)([^}]+)\}/g;function
|
|
1
|
+
const e=/\{(?<!\{[^}]*?\{)([^}]+)\}/g,t=/^([a-z][a-z0-9+.-]*):\/\//i,n=/[/?#]/,r=/:(\d+|\{[^}]+\})$/,i=/^\{([^}]+)\}$/,a=/^\d+$/,o={"http:":80,"https:":443};function s(e=[]){let t=[];for(let n of e)t.push(...l(n));return t}function c(e,t){return e.protocol===t.protocol&&e.ports.includes(t.port)&&e.hostname.test(t.hostname)}function l(e){let t=h(e.url);if(!t)return[];let n=u(t.host,e.variables),r=f(t,e.variables);if(!n||r.length===0)return[];let i=[{protocol:t.protocol,hostname:n,ports:r}];return t.protocol===`http:`&&r.includes(``)&&i.push({protocol:`https:`,hostname:n,ports:[``]}),i}function u(t,n){let r=``,i=0,a=!1;for(let o of t.matchAll(e)){let[e,s]=o,c=t.slice(i,o.index);c.includes(`.`)&&(a=!0),r+=g(c);let l=d(n?.[s]);l.guaranteesDot&&(a=!0),r+=l.pattern,i=o.index+e.length}let o=t.slice(i);return o.includes(`.`)&&(a=!0),r+=g(o),a?RegExp(`^${r}$`,`i`):null}function d(e){let t=e?.enum?.filter(Boolean);if(t&&t.length>0)return{pattern:`(?:${t.map(g).join(`|`)})`,guaranteesDot:t.every(e=>e.includes(`.`))};let n=e?.default?.split(`.`).slice(1).join(`.`);return n?{pattern:`[^.]+\\.${g(n)}`,guaranteesDot:!0}:{pattern:`[^.]+`,guaranteesDot:!1}}function f({protocol:e,port:t},n){let r=i.exec(t)?.[1],a=r?p(n?.[r]):[t];return[...new Set(a.flatMap(t=>m(e,t)))]}function p(e){let t=e?.enum?.filter(Boolean).map(String);return t&&t.length>0?t:e?.default?[String(e.default)]:[]}function m(e,t){if(t===``)return[``];if(!a.test(t))return[];let n=Number(t);return[n===o[e]?``:String(n)]}function h(e){if(!e)return null;let i=(t.exec(e)?.[1]??`https`).toLowerCase();if(i!==`http`&&i!==`https`)return null;let a=e.replace(t,``).split(n,1)[0];if(!a)return null;let o=a.includes(`@`)?a.slice(a.lastIndexOf(`@`)+1):a,s=r.exec(o),c=s?o.slice(0,s.index):o;return c?{protocol:`${i}:`,host:c,port:s?.[1]??``}:null}function g(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}export{s as buildAllowedOriginMatchers,c as matchesOrigin};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as ee}from"../api-call-operations.js";import{GatewayFetchBlockedError as l,GatewayFetchSystemError as u,GatewayFetchUserError as d}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as f}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as p}from"undici";const m=`x-forwarded-for`,re=/%2f|%5c/i,h=/* @__PURE__ */ new Set([401,403,407]),g=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let _;function v(e){if(!_){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),_=new p({connect:{lookup:t({allowLoopback:n})}})}return _}function y({apis:e,onAuthRequired:t,sent:f,runEnded:p,logger:m,telemetry:g,fetchImpl:_=fetch,dispatcher:y=v(m),timeoutMs:b=3e4,deadline:T=1/0,maxResponseBytes:E=1048576,maxFetchesPerExec:D,beforeSend:ge,caller:O,allowedHttpMethods:k}){let A=e.flatMap(e=>e.matchers),_e=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),j=e.flatMap(e=>Object.values(e.secrets??{})),M=j.flatMap(a),ve=j.map(e=>e.header),N=e.flatMap(e=>e.credentialQueryParams??[]),P=0,F=!1;return async a=>{let v=c(a.method??`GET`),j=Date.now(),I,L,R,z={},B,V,H,U;try{if(D!==void 0){let e=Math.max(0,D);if(P+=1,P>e)throw new d(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(k&&!k.includes(v))throw new l(`${v} is not allowed: this project permits only ${k.join(`, `)} API calls`,ae(a.url));let o=ie(a.url,A,_e);if(I=o.hostname,L=te(o.pathname),re.test(o.pathname))throw new l(`${v} ${o.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,o.hostname);let c=e.filter(e=>e.matchers.some(e=>e.test(o.hostname))),u=c.flatMap(e=>e.operations?ee(e.operations,o.pathname,v).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),x=Math.min(...u.map(e=>e.variables)),C=u.filter(e=>e.variables===x);if(c.length>0&&(u.length===0||C.some(e=>!e.visible)))throw new l(`${v} ${o.pathname} is not a documented operation of ${c.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,o.hostname);let w=C.find(e=>!e.callable);if(w)throw new l(`${v} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let W=new Set(C.map(e=>e.api)).size===1?C[0].api:void 0;R=W?.slug;let G=de(a.securityScheme,W),K=G?[G]:W?le(W,o.pathname,v):void 0,q=W&&K?ue(W,K):void 0,J=q?W?.secrets?.[q]:void 0;z=me({callerHeaders:a.headers,secret:J,clientIp:O?.clientIp});let Y=fe(a.headers,o,c,J);if(Y&&(J||F))throw new d(pe(Y,!!J));if(T-Date.now()<=0)throw new d(`The execute time limit ended before this request was sent`);await ge?.(),F||=!!J,B=J?q:void 0;let X=new AbortController,ye=T-Date.now();if(U=ye<b?setTimeout(()=>X.abort(new d(`The request did not finish before the execute time limit`)),ye):setTimeout(()=>X.abort(),b),p?.aborted)throw new d(`The execute call had already answered, so this request was not sent`);H={method:v,url:i(o.origin+o.pathname,M)},f?.push(H);let Z=await _(o,{method:v,headers:z,body:a.body,redirect:`manual`,signal:X.signal,dispatcher:y});V=Z.status,H.status=Z.status;let Q=``;try{Q=await ce(Z,E)}finally{if(h.has(Z.status)&&W&&t){let e={api:W.slug,name:W.name,status:Z.status};q&&(e.scheme=q),K?.length&&(e.schemes=[...K]),B&&(e.sentScheme=B);let n=ne(Q,Z.headers.get(`content-type`),M);n&&(e.detail=n),t(e)}}let $=r(he(Z.headers),M);if(oe(Z.status)){$=n($,ve);let{location:e}=$;e&&!se(e,o,A)&&delete $.location}let be=S(Z.status);return g?.gatewayFetchPerformed({host:o.hostname,method:v,outcome:be,durationMs:Date.now()-j,path:L,api:R,status:Z.status,bytes:Buffer.byteLength(Q,`utf8`),injectedScheme:B}),s(m,{rawUrl:o.href,method:v,host:o.hostname,outcome:be,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:L,api:R,status:Z.status,injectedScheme:B,requestHeaders:z,requestBody:a.body,responseHeaders:$,responseBody:Q,caller:O}),{status:Z.status,statusText:i(Z.statusText,M),ok:Z.ok,headers:$,bodyText:i(Q,M)}}catch(e){H&&f&&x(e)&&f.splice(f.indexOf(H),1);let{outcome:t,userSafe:n}=C(e,V),r=I??(n instanceof l?n.host:void 0)??ae(a.url)??`invalid-url`;throw g?.gatewayFetchPerformed({host:r,method:v,outcome:t,durationMs:Date.now()-j,path:L,api:R,status:V,injectedScheme:B}),s(m,{rawUrl:a.url,method:v,host:r,outcome:t,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:L,api:R,status:V,injectedScheme:B,requestHeaders:z,requestBody:a.body,caller:O}),n||(m?.error(`Gateway MCP fetch failed [${v} ${r}]: ${i(w(e),M)} headers=${o(z)}`),new u(`Upstream fetch failed due to an internal error`))}finally{U!==void 0&&clearTimeout(U)}}}function b(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof d||n instanceof e)return n;n=n.cause}}function x(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function S(e){return h.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function C(t,n){let r=b(t),i=n===void 0?void 0:S(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof l||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function ie(e,t,n){try{return f(e,t)}catch(e){throw e instanceof l&&n?new l(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function ae(e){try{return new URL(e).hostname||void 0}catch{return}}function oe(e){return e>=300&&e<400}function se(e,t,n){try{return!!f(new URL(e,t).href,n)}catch{return!1}}function w(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function ce(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw T(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw T(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function T(e,t){return new d(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function le(e,t,n){let r=e.routes?.find(e=>e.method===n&&e.pattern.test(t));return r?r.schemes:E(e)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new d(`securityScheme must be a security scheme name (a string)`);if(!t)throw new d(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new d(`Unknown securityScheme "${e}" for ${t.name}; valid values: ${n.join(`, `)}`);return e}function E(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function fe(e,t,n,r){let i=D([...g,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=D(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function D(e){return new Set(e.map(e=>e.toLowerCase()))}function pe({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function me({callerHeaders:e,secret:t,clientIp:n}){let r={};for(let[t,n]of Object.entries(e??{})){let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==m&&(r[t]=n)}return n&&(r[m]=n),t&&(r[t.header]=t.value),r}function he(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{y as buildFetchBridge,v as getDefaultAgent,ce as readCappedBody};
|
|
1
|
+
import{SsrfBlockedError as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{createSsrfSafeLookup as t}from"../../../../../../../server/ssrf/ssrf-safe-lookup.js";import{redactHeaders as n,redactSecretValuesFromHeaders as r,redactSecretsFromString as i,secretEchoForms as a}from"./redact.js";import{auditHeaderNames as o,logGatewayFetchAudit as s}from"../../audit.js";import{operationHttpMethod as c}from"../route-pattern.js";import{matchingApiCallOperations as l}from"../api-call-operations.js";import{GatewayFetchBlockedError as u,GatewayFetchHostNotAllowedError as d,GatewayFetchSystemError as f,GatewayFetchUserError as p}from"./fetch-errors.js";import{matchesOrigin as ee}from"./allowed-hosts.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as m}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as h}from"undici";const g=`x-forwarded-for`,re=/%2f|%5c/i,_=/* @__PURE__ */ new Set([401,403,407]),ie=[`authorization`,`proxy-authorization`,`cookie`,`x-api-key`];let v;function y(e){if(!v){let n=process.env.NODE_ENV!==`production`;n&&e?.warn(`Gateway MCP SSRF guard: loopback upstreams are ALLOWED (develop mode only, never in runtime).`),v=new h({connect:{lookup:t({allowLoopback:n})}})}return v}function b({apis:e,onAuthRequired:t,sent:d,runEnded:m,logger:h,telemetry:g,fetchImpl:ie=fetch,dispatcher:v=y(h),timeoutMs:b=3e4,deadline:S=1/0,maxResponseBytes:D=1048576,maxFetchesPerExec:O,beforeSend:be,caller:k,refuseMethod:xe}){let A=e.flatMap(e=>e.matchers),Se=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),j=e.flatMap(e=>Object.values(e.secrets??{})),M=j.flatMap(a),Ce=j.map(e=>e.header),N=e.flatMap(e=>e.credentialQueryParams??[]),P=0,we=!1;return async a=>{let y=c(a.method??`GET`),j=Date.now(),Te,F,I,L={},R,z,B,V,Ee=!1;try{if(O!==void 0){let e=Math.max(0,O);if(P+=1,P>e)throw new p(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}let o=xe?.(y);if(o)throw new u(o,oe(a.url));let c=ae(a.url,A,Se);if(Te=c.hostname,F=te(c.pathname),re.test(c.pathname))throw new u(`${y} ${c.pathname} is refused: the path holds an encoded path separator (%2F or %5C), which could reach an operation other than the documented one`,c.hostname);let f=e.filter(e=>e.matchers.some(e=>ee(e,c))),x=f.flatMap(e=>e.operations?l(e.operations,c.pathname,y).map(t=>({api:e,callable:t.callable,visible:t.visible,variables:t.variables})):[{api:e,callable:!0,visible:!0,variables:1/0}]),C=Math.min(...x.map(e=>e.variables)),T=x.filter(e=>e.variables===C);if(f.length>0&&(x.length===0||T.some(e=>!e.visible)))throw new u(`${y} ${c.pathname} is not a documented operation of ${f.map(e=>e.name).join(`, `)}; \`fetch\` calls only the operations the API description documents`,c.hostname);let E=T.find(e=>!e.callable);if(E)throw new u(`${y} ${c.pathname} is not callable: this operation of ${E.api.name} is excluded from agent calls`,c.hostname);let H=[...new Set(T.map(e=>e.api))];if(H.length>1&&H.some(e=>me(e,y,c.pathname)))throw new u(he(H,`${y} ${c.pathname}`),c.hostname);let U=H.length===1?H[0]:void 0;I=U?.slug;let W=U&&pe(U,y,c.pathname);if(W?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${y} ${c.pathname} accepts only ${W.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Call it without securityScheme, and do not replace the stored credentials.`);let G=de(a.securityScheme,U),K=G?[G]:U?W?.schemes??fe(U):void 0,q=U&&K?ue(U,K):void 0,J=q?U?.secrets?.[q]:void 0;if((y===`GET`||y===`HEAD`)&&a.body!==void 0)throw new p(`A ${y} request cannot have a body; remove \`body\``);L=ve({callerHeaders:a.headers,secret:J,clientIp:k?.clientIp});let De=ge(a.headers,c,f,J);if(De&&(J||we))throw new p(_e(De,!!J));if(S-Date.now()<=0)throw new p(`The execute time limit ended before this request was sent`);await be?.(),we||=!!J,R=J?q:void 0;let Y=new AbortController,Oe=S-Date.now();if(V=Oe<b?setTimeout(()=>Y.abort(new p(`The request did not finish before the execute time limit`)),Oe):setTimeout(()=>{Ee=!0,Y.abort()},b),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);B={method:y,url:i(c.origin+c.pathname,M)},d?.push(B);let X=await ie(c,{method:y,headers:L,body:a.body,redirect:`manual`,signal:Y.signal,dispatcher:v});z=X.status,B.status=X.status;let Z=``;try{Z=await le(X,D)}finally{if(_.has(X.status)&&U&&t){let e={api:U.slug,name:U.name,status:X.status};q&&(e.scheme=q),K?.length&&(e.schemes=[...K]),G&&(e.isSchemeRequested=!0),R&&(e.sentScheme=R),W?.unsupportedSchemes&&(e.unsupportedSchemes=[...W.unsupportedSchemes]);let n=ne(Z,X.headers.get(`content-type`),M);n&&(e.detail=n),t(e)}}let Q=r(ye(X.headers),M);if(se(X.status)){Q=n(Q,Ce);let{location:e}=Q;e&&!ce(e,c,A)&&delete Q.location}let $=w(X.status);return g?.gatewayFetchPerformed({host:c.hostname,method:y,outcome:$,durationMs:Date.now()-j,path:F,api:I,status:X.status,bytes:Buffer.byteLength(Z,`utf8`),injectedScheme:R}),s(h,{rawUrl:c.href,method:y,host:c.hostname,outcome:$,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:F,api:I,status:X.status,injectedScheme:R,requestHeaders:L,requestBody:a.body,responseHeaders:Q,responseBody:Z,caller:k}),{status:X.status,statusText:i(X.statusText,M),ok:X.ok,headers:Q,bodyText:i(Z,M)}}catch(e){let t=B!==void 0&&C(e);t&&B&&d&&d.splice(d.indexOf(B),1);let{outcome:n,userSafe:r}=T(e,z),c=Te??(r instanceof u?r.host:void 0)??oe(a.url)??`invalid-url`;if(g?.gatewayFetchPerformed({host:c,method:y,outcome:n,durationMs:Date.now()-j,path:F,api:I,status:z,injectedScheme:R}),s(h,{rawUrl:a.url,method:y,host:c,outcome:n,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:F,api:I,status:z,injectedScheme:R,requestHeaders:L,requestBody:a.body,caller:k}),r)throw r;let l=Ee?{reason:`timeout after ${b} ms`,message:z===void 0?`The API did not answer within ${b/1e3} s`:`The API did not finish its answer within ${b/1e3} s`}:t?{reason:`connect failure ${x(e)??`without a code`}`,message:`Could not connect to ${c}`}:{reason:E(e),message:`Upstream fetch failed due to an internal error`};throw h?.error(`Gateway MCP fetch failed [${y} ${c}]: ${i(l.reason,M)} headers=${o(L)}`),new f(l.message)}finally{V!==void 0&&clearTimeout(V)}}}function x(e){let t=e;for(let e=0;e<5&&t instanceof Error;e++){if(`code`in t&&typeof t.code==`string`)return t.code;if(t instanceof AggregateError)return t.errors.map(x).find(e=>e!==void 0);t=t.cause}}function S(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof p||n instanceof e)return n;n=n.cause}}function C(t){let n=t;for(let t=0;t<5&&n instanceof Error;t++){if(n instanceof e)return!0;if(n instanceof AggregateError)return n.errors.some(C);let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function w(e){return _.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function T(t,n){let r=S(t),i=n===void 0?void 0:w(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof u||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function ae(e,t,n){try{return m(e,t)}catch(e){throw e instanceof d&&n?new u(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function oe(e){try{return new URL(e).hostname||void 0}catch{return}}function se(e){return e>=300&&e<400}function ce(e,t,n){try{return!!m(new URL(e,t).href,n)}catch{return!1}}function E(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function le(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw D(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw D(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function D(e,t){return new p(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new p(`securityScheme must be a security scheme name (a string)`);if(!t)throw new p(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new p(`This site cannot send securityScheme "${e}" to ${t.name}; valid values: ${n.join(`, `)}`);return e}function fe(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function pe(e,t,n){return e.routes?.find(e=>e.method===t&&e.pattern.test(n))}function me(e,t,n){return(pe(e,t,n)?.schemes??fe(e)).length>0}function he(e,t){return`${t} is documented by several callable APIs: ${e.map(e=>`"${e.name}" (${e.slug})`).join(`, `)}. This site cannot tell whose stored credential to send, so it does not call the operation. The site owner can keep all but one of these files out of API calls with \`mcp.apiCalls.excludeFiles\`.`}function ge(e,t,n,r){let i=O([...ie,...n.flatMap(e=>e.credentialHeaders??[]),...r?[r.header]:[]]),a=Object.keys(e??{}).find(e=>i.has(e.toLowerCase()));if(a)return{kind:`header`,name:a};let o=O(n.flatMap(e=>e.credentialQueryParams??[])),s=[...t.searchParams.keys()].find(e=>o.has(e.toLowerCase()));return s?{kind:`query parameter`,name:s}:void 0}function O(e){return new Set(e.map(e=>e.toLowerCase()))}function _e({kind:e,name:t},n){return n?`Remove the "${t}" ${e}: this request already sends the stored credential.`:`Remove the "${t}" ${e}: this script already sent a stored credential, so it cannot also send its own.`}function ve({callerHeaders:e,secret:t,clientIp:n}){let r={},i=new Headers;for(let[t,n]of Object.entries(e??{})){try{i.append(t,n)}catch{throw new p(`The "${t}" header is invalid: a header name must be a token and a value must hold no line breaks or characters above U+00FF`)}let e=t.toLowerCase();e!==`host`&&e!==`content-length`&&e!==g&&(r[t]=n)}return n&&(r[g]=n),t&&(r[t.header]=t.value),r}function ye(e){let t={};return e.forEach((e,n)=>{t[n.toLowerCase()]=e}),t}export{b as buildFetchBridge,y as getDefaultAgent,le as readCappedBody};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class extends Error{constructor(e){super(e),this.name=`GatewayFetchUserError`}},t=class extends e{host;constructor(e,t){super(e),this.name=`GatewayFetchBlockedError`,this.host=t}},n=class extends Error{constructor(e){super(e),this.name=`GatewayFetchSystemError`}};export{t as GatewayFetchBlockedError,n as GatewayFetchSystemError,e as GatewayFetchUserError};
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=`GatewayFetchUserError`}},t=class extends e{host;constructor(e,t){super(e),this.name=`GatewayFetchBlockedError`,this.host=t}},n=class extends t{constructor(e){super(`Host "${e}" is not allowed`,e),this.name=`GatewayFetchHostNotAllowedError`}},r=class extends Error{constructor(e){super(e),this.name=`GatewayFetchSystemError`}};export{t as GatewayFetchBlockedError,n as GatewayFetchHostNotAllowedError,r as GatewayFetchSystemError,e as GatewayFetchUserError};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isBlockedIp as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{
|
|
1
|
+
import{isBlockedIp as e}from"../../../../../../../server/ssrf/ssrf-blocklist.js";import{GatewayFetchBlockedError as t,GatewayFetchHostNotAllowedError as n,GatewayFetchUserError as r}from"./fetch-errors.js";import{matchesOrigin as i}from"./allowed-hosts.js";import{findUnresolvedPlaceholders as a,unresolvedPlaceholderMessage as o}from"./url-placeholders.js";import{isIP as s}from"node:net";function c(e,s){let c;try{c=new URL(e)}catch{throw new r(`Invalid URL: ${e}`)}if(c.protocol!==`http:`&&c.protocol!==`https:`)throw new r(`Only http(s) URLs are allowed, got ${c.protocol}`);if(c.username||c.password)throw new r(`URLs must not contain embedded credentials`);let f=a(c.hostname);if(f.length>0)throw new r(o(f));let p=d(c.hostname),m=l(p)?[]:s.filter(e=>e.hostname.test(p));if(m.length===0)throw new n(p);if(!m.some(e=>i(e,c))){let e=u(c.hostname,m);throw new t(`Origin "${c.origin}" is not allowed; use the documented ${e.length===1?`origin`:`origins`} of ${p}: ${e.join(`, `)}`,p)}let h=a(c.pathname);if(h.length>0)throw new r(o(h));return c}function l(t){let n=d(t.toLowerCase()).split(`%`)[0];return n===`localhost`||n.endsWith(`.localhost`)?!0:s(n)!==0&&e(n)}function u(e,t){let n=t.flatMap(({protocol:t,ports:n})=>n.map(n=>`${t}//${e}${n?`:${n}`:``}`));return[...new Set(n)]}function d(e){return e.replace(/^\[|\]$/g,``)}export{c as assertUrlAllowed,l as isBlockedAddress};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{redactSecretsFromString as e}from"./redact.js";function t(t,i,a){let o=n(i)?r(t):t;if(!o)return;let s=e(o.replace(/\s+/g,` `).trim(),a);if(s)return s.length>200?`${s.slice(0,199)}…`:s}function n(e){return/[/+]json\b/i.test(e??``)}function r(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t||Array.isArray(t))return;let n=[t.title,t.detail].filter(
|
|
1
|
+
import{redactSecretsFromString as e}from"./redact.js";function t(t,i,a){let o=n(i)?r(t):t;if(!o)return;let s=e(o.replace(/\s+/g,` `).trim(),a);if(s)return s.length>200?`${s.slice(0,199)}…`:s}function n(e){return/[/+]json\b/i.test(e??``)}function r(e){let t;try{t=JSON.parse(e)}catch{return}if(typeof t!=`object`||!t||Array.isArray(t))return;let n=[];for(let e of[t.title,t.detail,t.message,t.error]){if(!i(e)||n.some(t=>t.includes(e)))continue;let t=n.findIndex(t=>e.includes(t));n=n.filter(t=>!e.includes(t)),n.splice(t===-1?n.length:t,0,e)}return n.length>0?n.join(`: `):void 0}function i(e){return typeof e==`string`&&e.trim()!==``}export{t as extractUpstreamDetail};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{
|
|
1
|
+
import{isObject as e}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as t}from"../../../../utils/request-origin.js";import{CALL_API_WRITE_TOOL_NAME as n,MANAGE_API_CREDENTIALS_TOOL_NAME as r}from"../../constants.js";import{formatError as i}from"../tool-errors.js";import{callAttribution as a}from"../audit.js";import{isToolDisabledByCaller as o}from"../disabled-tools.js";import{GATEWAY_FETCH_LIMITS as s}from"../codemode/constants.js";import{resolveSecretSubject as c}from"./subject.js";import{ipRateLimitKey as l}from"../rate-limit.js";import{callableApis as u,excludedOperations as d}from"./eligibility.js";import{getOfferedWriteHttpMethods as f,getSafeHttpMethods as p,getWriteHttpMethods as m}from"./allowed-http-methods.js";import{apiCallOperationsOf as h}from"./api-call-operations.js";import{GatewayFetchUserError as g}from"./fetch/fetch-errors.js";import{SecretStore as _}from"./secret-store.js";import{credentialHeadersOf as v,orderedSchemesOf as y,resolveUpstreamApiAuth as b}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as x,buildCredentialsAcceptedHint as S,buildCredentialsToolHint as C,buildUpstreamCredentialFallback as w,buildUpstreamCredentialInputRequired as T,credentialElicitationAnswer as E,dedupeElicitation as D,isStatelessRequest as O,schemeLabelOf as k,supportsUrlElicitation as A}from"./elicitation.js";import{buildAllowedOriginMatchers as j}from"./fetch/allowed-hosts.js";import{buildFetchBridge as M}from"./fetch/fetch-bridge.js";import{applyFetchCount as N}from"./fetch/fetch-limit.js";import{dedupeAuthEvents as P,upstreamAuthKey as F}from"./upstream-auth.js";import{isInputRequiredResult as I}from"@modelcontextprotocol/server";function L(e){return new Map(e.map(e=>[e.relativePath,b(e)]))}function R(e,t,n,r,i,o,s,c){return M({apis:t.map(t=>{let i=n.get(t.relativePath);return{slug:t.relativePath,name:t.name,matchers:j(t.servers),secrets:r?.[t.relativePath],defaultScheme:i.defaultScheme,routes:i.routes,credentialHeaders:v(i.schemes),credentialQueryParams:i.credentialQueryParams,schemePriority:y(i.schemes),operations:h(t.fullDefinition,t.definition,t.servers,d(e,t.relativePath))}}),onAuthRequired:i,sent:o,runEnded:s,logger:e.logger,telemetry:e.telemetry,maxFetchesPerExec:50,deadline:e.executeDeadline,beforeSend:B(e),caller:a(e),refuseMethod:t=>z(e,c,t)})}function z(e,t,r){if(!t.includes(r))return f(e).includes(r)?`fetch sends safe methods only. Use the \`${n}\` tool for ${r} requests.`:`${r} is not allowed: ${m(e.config.mcp).includes(r)?`this client cannot send write requests`:`this call sends only ${t.join(`, `)} requests`}. Explain the call to the user instead of making it.`}function B(e){let{callerSubject:t,clientIp:n}=a(e),r={subject:t,ip:n&&l(n)};return async()=>{let t=await N(e.kv,r,s,Date.now(),e.logger);if(t)throw e.telemetry?.gatewayFetchRateLimited(t),new g(t.message)}}async function V(e,t){if(t)try{return await new _(e.gatewaySecretSeed).getSecretsForSubject(e.kv,t)}catch(t){e.logger?.warn(`gateway mcp secret store error, continuing unauthenticated: ${i(t)}`);return}}async function H(e){let t=[],n=await U(e,t);return I(n)?n:G(n,t)}async function U({ctx:e,sessionHandle:t,serverContext:n,allowedHttpMethods:i,run:a},s){let l=c(e,t);if(l.kind===`invalid`)return{content:[{type:`text`,text:l.message}],isError:!0};let d=l.kind===`resolved`?l.subject:void 0,[f,m]=await Promise.all([u(e),V(e,d)]),h=L(f),g=[],_=new AbortController,v=await a(R(e,f,h,m,e=>g.push(e),s,_.signal,i??p(e.config.mcp))).finally(()=>_.abort());if(g.length===0)return v;let y=P(g).map(e=>q(e,h));if(l.kind===`anonymous`)return y.some(e=>e.schemes)?K(v,[{type:`text`,text:l.message}]):K(v,[{type:`text`,text:Z(y,{plans:h,canManageCredentials:!1})},...v.content]);let b=O(n.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${b?`2026-07-28`:`2025`} urlElicitation=${A(n.mcpReq)}`);let x={ctx:e,serverContext:n,subject:l.subject,stored:J(m),plans:h,canManageCredentials:!o(r,e.metadata)},S=b?await $(x,y,!s.some(W)):await ee(x,y);switch(S.kind){case`inputRequired`:return S.result;case`prependText`:return K(v,[{type:`text`,text:S.text},...v.content]);case`none`:return v}}function W(e){return e.status===void 0||e.status<400||e.status>=500}function G(t,n){if(!t.isError||n.length===0)return t;let r=n.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
|
|
2
2
|
`+r.map(e=>`${e.method} ${e.url} -> ${e.status??`no response`}`).join(`
|
|
3
|
-
`);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(
|
|
3
|
+
`);return{...t,content:[...t.content.slice(0,-1),{type:`text`,text:i},...t.content.slice(-1)],structuredContent:{...e(t.structuredContent)?t.structuredContent:{},sentFetches:r}}}function K(e,t){let{structuredContent:n,...r}=e;return{...r,content:t,isError:!0}}function q(e,t){let n=t.get(e.api),r=e.scheme&&n.schemes[e.scheme]?e.scheme:n.defaultScheme;return{...e,scheme:r}}function J(e){let t=/* @__PURE__ */ new Set;for(let[n,r]of Object.entries(e??{}))for(let e of Object.keys(r))t.add(F({api:n,scheme:e}));return t}function Y(e,t){return e.status===401&&!!e.schemes&&!t.has(F(e))}function X(e,t){let n=t.get(e.api),r=e.sentScheme??e.scheme;return n&&r?k(n.schemes,r):void 0}function Z(e,{plans:t,canManageCredentials:n}){return e.map(e=>C(e,{schemeLabel:X(e,t),canManageCredentials:n})).join(`
|
|
4
4
|
|
|
5
|
-
`)}function Q({ctx:e,subject:
|
|
5
|
+
`)}function Q({ctx:e,subject:n,plans:r,stored:i},a){let[o,...s]=a,c=r.get(o.api),l=o.scheme??c.defaultScheme,u=o.schemes&&o.schemes.length>1?o.schemes:void 0;return{subject:n,baseUrl:t(e.request),target:{api:o.api,name:o.name,scheme:l,schemeLabel:u?void 0:X(o,r),acceptedSchemes:u},auth:c.schemes[l]??{kind:`raw`},apiAuth:c,secretStore:new _(e.gatewaySecretSeed),kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:o.status,detail:o.detail,otherApiNames:s.map(e=>e.name),unsentStoredSchemes:Object.keys(c.schemes).filter(e=>i.has(F({api:o.api,scheme:e}))),isSchemeRequested:o.isSchemeRequested}}}async function $(e,n,r){let{ctx:i,serverContext:a,subject:o,stored:s,canManageCredentials:c}=e,l=E(a.mcpReq.inputResponses);if(l===`declined`)return{kind:`none`};let u=n.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(n,e)};if(l===`accepted`){let e=await x(a.mcpReq.requestState(),{secretStore:new _(i.gatewaySecretSeed),kv:i.kv,subject:o,baseUrl:t(i.request),apis:u.map(e=>e.api)}),n=e?.apiName??u[0].name;return{kind:`prependText`,text:S(n,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!r||!A(a.mcpReq)?{kind:`prependText`,text:await w(d)}:{kind:`inputRequired`,result:await T(d)}}async function ee(e,t){let n=t.filter(t=>Y(t,e.stored));if(n.length===0)return{kind:`prependText`,text:Z(t,e)};let r=Q(e,n);return{kind:`prependText`,text:await D(`${e.subject}:${F(n[0])}`,()=>w(r))}}export{H as runExecuteWithGateway};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{secretTtlSeconds as e}from"./subject.js";import{assertHeaderSafe as t}from"./credential-validation.js";import{createCipheriv as n,createDecipheriv as r,createHash as i,hkdfSync as a,randomBytes as o,randomUUID as s}from"node:crypto";const c=15,l=9e5;var u=class{#e;constructor(e){this.#e=e}async setSecret(n,r,i,a,o){t(o.header,o.value);let s={...o,savedAt:Date.now()},c={api:i,scheme:a,...this.#d(this.#c(r),s,this.#a(i,a))};await n.set(this.#i(r,i,a),c,{ttlInSeconds:e(r)})}async getSecretsForSubject(e,t){return this.#t(e,t,this.#r(t))}async getStoredSchemes(e,t,n){let r=[...this.#r(t),n],i=(await this.#t(e,t,r))[n]??{};return Object.fromEntries(Object.entries(i).map(([e,{savedAt:t}])=>[e,{savedAt:t}]))}async#t(e,t,n){let r=this.#c(t),i=await this.#n(e,n),a={};for(let e of i){if(!e.value?.scheme)continue;let{api:t,scheme:n}=e.value;try{let i=this.#f(r,e.value,this.#a(t,n));a[t]={...a[t],[n]:i}}catch{continue}}return a}async hasSecret(e,t,n,r){return!!await e.get(this.#i(t,n,r))}async deleteSecret(e,t,n,r){await e.delete(this.#i(t,n,r))}async deleteSecrets(e,t,n){let r=n?[...this.#r(t),n]:this.#r(t),i=(await this.#n(e,r)).flatMap(({key:e,value:t})=>t?.scheme?[{key:e,api:t.api,scheme:t.scheme}]:[]);return await Promise.all(i.map(({key:t})=>e.delete(t))),i.map(({api:e,scheme:t})=>({api:e,scheme:t}))}async createElicitation(e,t){let n=s(),r={...t,expiresAt:Date.now()+l};return await e.set(this.#o(n),this.#d(this.#l(),r),{ttlInSeconds:l/1e3}),n}async peekElicitation(e,t){let n=await e.get(this.#o(t));if(n)try{return this.#f(this.#l(),n)}catch{return}}async consumeElicitation(e,t){let n=this.#o(t),r=await e.transaction(async e=>{let t=await e.get(n);return t&&await e.delete(n),t});if(r)try{return this.#f(this.#l(),r)}catch{return}}async#n(e,t){let n=[],r;do{let i=await e.list({prefix:t},{cursor:r});n.push(...i.items),r=i.cursor??void 0}while(r);return n}#r(e){return[`mcp`,`secrets`,this.#s(e)]}#i(e,t,n){return[`mcp`,`secrets`,this.#s(e),t,n]}#a(e,t){return`${e}\x00${t}`}#o(e){return[`mcp`,`elicitation`,e]}#s(e){return i(`sha256`).update(e).digest(`hex`)}#c(e){return Buffer.from(a(`sha256`,this.#u(),e,`mcp-upstream-secrets`,32))}#l(){return Buffer.from(a(`sha256`,this.#u(),`mcp-elicitation`,`mcp-elicitation`,32))}#u(){if(!this.#e)throw Error(`REALM_AUTH_KEY_SEED is required to store MCP gateway credentials. Set it to a long random string.`);return this.#e}#d(e,t,r){let i=o(12),a=n(`aes-256-gcm`,e,i);r&&a.setAAD(Buffer.from(r,`utf8`));let s=Buffer.concat([a.update(JSON.stringify(t),`utf8`),a.final()]);return{iv:i.toString(`base64`),tag:a.getAuthTag().toString(`base64`),data:s.toString(`base64`)}}#f(e,t,n){let i=r(`aes-256-gcm`,e,Buffer.from(t.iv,`base64`));n&&i.setAAD(Buffer.from(n,`utf8`)),i.setAuthTag(Buffer.from(t.tag,`base64`));let a=Buffer.concat([i.update(Buffer.from(t.data,`base64`)),i.final()]).toString(`utf8`);return JSON.parse(a)}};export{c as ELICITATION_TTL_MINUTES,l as ELICITATION_TTL_MS,u as SecretStore};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{createAnonymousSessionTool as e,manageApiCredentialsTool as t,removeApiCredentialsTool as n}from"./tools.js";import{callApiWriteTool as r}from"./call-api.js";import{workflowTools as i}from"../workflows/tools.js";function a(){return[e,t,n,r,...i()]}export{a as gatewayTools};
|