@redocly/framework 1.0.0-next.7 → 1.0.0-next.9
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/vite-config.js +2 -2
- package/dist/bundler/dev/routes/dev-problems-route.js +1 -1
- package/dist/bundler/dev/routes/source-sync-route.js +1 -1
- package/dist/bundler/dev/run.js +1 -1
- package/dist/bundler/dev/runtime-app.js +1 -1
- package/dist/bundler/dev/vite-chunk-url.js +1 -1
- package/dist/bundler/dev/vite-config.js +1 -1
- package/dist/bundler/user-markdoc-schema.js +1 -1
- package/dist/bundler/vite-config.base.js +8 -8
- package/dist/cli/commands/build.js +1 -1
- package/dist/cli/commands/dev.js +1 -1
- package/dist/cli/commands/ingest.js +1 -1
- package/dist/cli/commands/translate.js +2 -2
- package/dist/cli/dev-console/index.js +1 -1
- package/dist/cli/dev-console/tui.js +1 -1
- package/dist/cli/log-output/index.js +1 -1
- package/dist/cli/output.js +12 -12
- package/dist/cli/validate-react-pages.js +1 -1
- package/dist/client/ai-search/use-ai-search.js +1 -1
- package/dist/client/analytics-page-view.js +1 -1
- package/dist/client/app.js +2 -7
- package/dist/client/client-entry.js +1 -1
- package/dist/client/contexts.js +1 -1
- package/dist/client/dev-problems/ProblemsBar.js +26 -16
- 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/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/SidebarDataProvider.js +1 -1
- package/dist/client/sidebar/drilldown.js +1 -1
- package/dist/client/ssr.js +1 -1
- package/dist/client/telemetry/config.js +1 -1
- package/dist/client/theme-logo.js +1 -1
- package/dist/client/use-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-search.js +1 -1
- package/dist/client/webmcp/tools/shared.js +1 -1
- package/dist/client/webmcp/tools/site-tools.js +1 -1
- package/dist/client/webmcp/use-webmcp-tools.js +1 -1
- package/dist/content-layer/api-outputs.js +1 -1
- package/dist/content-layer/config-schema.js +1 -1
- package/dist/content-layer/config.js +1 -1
- package/dist/content-layer/database/invalidation.js +26 -26
- 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 +17 -0
- package/dist/content-layer/database/schema.js +1 -1
- package/dist/content-layer/ingest/finalize-phase.js +1 -1
- package/dist/content-layer/ingest/hash.js +1 -1
- package/dist/content-layer/ingest/l10n-warnings.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/run.js +1 -1
- package/dist/content-layer/ingest/search-sync.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/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/code-highlight-notation.js +3 -3
- 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/tag-sets.d.ts +11 -2
- package/dist/content-layer/markdown/constants/tag-sets.js +1 -1
- package/dist/content-layer/markdown/nodes/fence.js +1 -1
- package/dist/content-layer/markdown/nodes/heading.js +1 -1
- package/dist/content-layer/markdown/nodes/table.js +1 -1
- package/dist/content-layer/markdown/resolve/audience-tag.d.ts +1 -5
- package/dist/content-layer/markdown/resolve/audience-tag.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.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/operation-samples.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/partial.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc-resolvers/svg-content.js +1 -1
- package/dist/content-layer/markdown/resolve/markdoc.js +1 -1
- package/dist/content-layer/markdown/resolve/references.d.ts +3 -1
- package/dist/content-layer/markdown/resolve/references.js +1 -1
- package/dist/content-layer/markdown/search/to-markdown.js +2 -2
- package/dist/content-layer/markdown/search/to-sections.d.ts +8 -3
- package/dist/content-layer/markdown/search/to-sections.js +1 -1
- package/dist/content-layer/markdown/search/to-text.js +5 -5
- package/dist/content-layer/markdown/server/render.js +1 -1
- package/dist/content-layer/markdown/service.js +1 -1
- package/dist/content-layer/markdown/tags/html.d.ts +2 -2
- package/dist/content-layer/markdown/tags/html.js +1 -1
- package/dist/content-layer/markdown/tags/openapi.js +1 -1
- package/dist/content-layer/markdown/tags/variant.js +1 -1
- package/dist/content-layer/markdown/types/service.d.ts +2 -0
- package/dist/content-layer/markdown/utils/first-heading.js +1 -1
- package/dist/content-layer/markdown/utils/parse-cache.js +1 -1
- package/dist/content-layer/materialization/static-files.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/template.js +11 -3
- 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 +21 -11
- 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/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/markdown-docs.js +8 -8
- package/dist/content-layer/plugins/internal/api-docs/server/options.js +1 -1
- package/dist/content-layer/plugins/internal/api-docs/server/search-documents.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/access.js +1 -1
- package/dist/content-layer/plugins/internal/api-functions/server/dispatch.js +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.d.ts +1 -1
- package/dist/content-layer/plugins/internal/app-data/index.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/client/use-catalog-classic.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/catalog-classic/resolve-items.js +1 -1
- package/dist/content-layer/plugins/internal/index.js +1 -1
- package/dist/content-layer/plugins/internal/l10n/index.js +1 -1
- package/dist/content-layer/plugins/internal/l10n/translations-loader.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/client/template.js +1 -1
- package/dist/content-layer/plugins/internal/markdoc/index.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/constants.d.ts +17 -0
- package/dist/content-layer/plugins/internal/mcp/constants.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/content-tools.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/ignored-routes.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/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/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/prompts.js +8 -8
- 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-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 -6
- 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/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/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 +1 -1
- 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/oauth/authorize.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/oauth/discovery.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/tools/openapi-catalog.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi-document.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/openapi.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages-navigation.js +1 -1
- package/dist/content-layer/plugins/internal/mcp/server/tools/pages.js +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/mock/server/handler.js +1 -1
- package/dist/content-layer/plugins/internal/react-page/index.js +1 -1
- package/dist/content-layer/plugins/internal/scorecard-classic/index.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/bundle.d.ts +15 -15
- package/dist/content-layer/plugins/internal/sidebar/bundle.js +1 -1
- package/dist/content-layer/plugins/internal/sidebar/index.d.ts +2 -1
- 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/versions/index.js +1 -1
- package/dist/content-layer/plugins/project/load.js +2 -2
- package/dist/content-layer/plugins/types/markdoc.d.ts +2 -0
- 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.js +1 -1
- package/dist/content-layer/problems/codes.js +1 -1
- 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.js +1 -1
- package/dist/content-layer/templates/template-set.js +1 -1
- package/dist/content-layer/versions/redirect.js +1 -1
- 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/server/app.js +3 -3
- 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/content.js +12 -12
- package/dist/server/cors-proxy/handler.js +1 -1
- package/dist/server/feedback/route.js +1 -1
- package/dist/server/lambda-entry.js +1 -1
- package/dist/server/manifest-assets.js +4 -4
- package/dist/server/node-entry.js +1 -1
- package/dist/server/plugin-context.js +1 -1
- package/dist/server/review/route.js +1 -1
- package/dist/server/search/route.js +1 -1
- package/dist/server/seo-tags.js +2 -2
- package/dist/server/sitemap.js +1 -1
- package/dist/server/static-files/serve.js +1 -1
- package/dist/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 +5 -0
- package/dist/shared/constants/review.js +1 -1
- package/dist/shared/constants/system-routes.js +1 -1
- package/dist/shared/constants/versions.d.ts +2 -0
- package/dist/shared/constants/versions.js +1 -1
- package/dist/shared/load-dot-env.js +1 -1
- package/dist/shared/rbac/api-docs.d.ts +2 -1
- package/dist/shared/rbac/api-docs.js +1 -1
- package/dist/shared/rbac/engine.d.ts +12 -9
- package/dist/shared/rbac/engine.js +0 -0
- package/dist/shared/rbac/filter.js +1 -1
- package/dist/shared/rbac/l10n-rules.js +1 -1
- package/dist/shared/rbac/route-scope.d.ts +1 -1
- package/dist/shared/rbac/team-templates.js +1 -1
- package/dist/shared/types/auth.d.ts +1 -0
- package/dist/shared/types/config.d.ts +1 -0
- package/dist/shared/utils/l10n.js +1 -1
- package/dist/shared/utils/routes/file-path-to-route-slug.js +1 -1
- package/drizzle/20261111152552_page_markdown_rbac_scope/migration.sql +1 -0
- package/package.json +11 -10
- package/dist/client/review/use-bar-position.js +0 -1
|
@@ -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,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(t,n,r){let i=[u(r),"- `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&&i.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&&i.push(`\`fetch\` sends only safe methods. Send one write request to a documented API with the \`${e}\` tool.`),i.join(`
|
|
5
|
+
`)}function m(e,t=[],n,r=!1){return a(s(n,t=>p(e,r,t)),t)}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
|
-
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 r(e).filter(e=>n.has(e))}function a(e){return r(e).filter(e=>!n.has(e))}function o(t){return e(`call-api_write`,t.metadata)?[]:a(t.config.mcp)}export{r as getAllowedHttpMethods,o as getOfferedWriteHttpMethods,i as getSafeHttpMethods,a as getWriteHttpMethods};
|
|
@@ -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({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{CALL_API_WRITE_TOOL_NAME as e,REQUIRES_USER_INTERACTION_META as t,WRITE_TOOL_ANNOTATIONS as n}from"../../constants.js";import{SsrfBlockedError as r}from"../../../../../../server/ssrf/ssrf-blocklist.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(r){return{name:e,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:n,_meta:t,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:r.length>0?{type:`string`,enum:r}:{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(e,t){try{let n=await t(m(e)),r=Object.fromEntries(u.flatMap(e=>n.headers[e]===void 0?[]:[[e,n.headers[e]]])),i={status:n.status,headers:r,body:h(n)};return{content:[{type:`text`,text:JSON.stringify(i)}],structuredContent:i}}catch(e){if(!(e instanceof s||e instanceof o||e instanceof r))throw e;return{content:[{type:`text`,text:e.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(t,n,r){let i=t;if(!r)throw Error(`\`${e}\` runs only as a top-level tool call.`);return c({ctx:n,sessionHandle:i.sessionHandle,serverContext:r,allowedHttpMethods:a(n),run:e=>g(i,e)})}};export{v as callApiWriteTool};
|
package/dist/content-layer/plugins/internal/mcp/server/gateway/credentials-page/form-page.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{MCP_CREDENTIALS_ROUTE as e}from"../../../constants.js";import{withPathPrefix as t}from"../../../../../../../shared/path-prefix.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=t(e),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{parseSrcSet as t}from"../../../../assets/srcset.js";import{MCP_CREDENTIALS_THEME_ENTITY_KEY as n}from"../../../../../../../shared/constants/mcp.js";import{toAppData as r}from"../../../../../../../shared/utils/app-data.js";import{publicOrigin as i}from"../../../../../utils/request-origin.js";async function a(t){let a=r(await t.entities.load(e)),s=o({seo:t.config.seo,logo:a.theme?.logo,colorMode:t.config.colorMode}),c=await t.entities.get(`mcp:credentials-theme`)?await t.entities.load(n):void 0;return{...s,...c?{theme:c}:{},host:new URL(i(t.request)).host}}function o({seo:e,logo:n,colorMode:r}){let i={},a=e?.title||e?.projectTitle||n?.altText;a&&(i.name=a);let o=new Map((n?.srcSet?t(n.srcSet)??[]:[]).map(({src:e,descriptor:t})=>[t.trim(),e])),l=c(o.get(`light`)??n?.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{SystemRoute as e}from"../../../../../../shared/constants/system-routes.js";import{withPathPrefix as t}from"../../../../../../shared/path-prefix.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=`${t(e.AuthIdpLogin)}?${new URLSearchParams({redirectTo:`/`})}`;return I(a,v(a.host,c),403)}function z(e,t){return e.kind===`apiKey`?{header:e.header,value:t}:e.kind===`cookie`?{header:`Cookie`,value:`${e.name}=${t}`}:e.kind===`bearer`||e.kind===`oauth2ClientCredentials`?{header:`Authorization`,value:B(t)}:{header:`Authorization`,value:t}}function B(e){return`Bearer ${e.replace(x,``)}`}export{C as serveCredentials};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import{
|
|
2
|
-
`)}async function g(e,{secretStore:t,kv:n,subject:r,baseUrl:i,apis:a}){if(typeof e!=`string`)return;let o=await t.peekElicitation(n,e);if(o?.subject===r&&a.includes(o.api))return{apiName:o.name,url:k(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 A(e,t,T(e.subject))}function b(
|
|
3
|
-
`);if(
|
|
4
|
-
`);let a=
|
|
5
|
-
`);let o=n?`api: "${
|
|
6
|
-
`)}function x(e){let t=e.sentScheme?(e.schemes??[]).filter(t=>t!==e.sentScheme):[];return t.length>0?[`This API also defines ${t.map(e=>`"${e}"`).join(`, `)}. Ask the user which credential they hold: if it is one of those, they can save it through the same link.`,``]:[]}function S({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}async function C({secretStore:e,kv:t,subject:n,baseUrl:r,target:i,auth:a,apiAuth:o}){let s=o?w(o):[],c=await e.createElicitation(t,{subject:n,api:i.api,name:i.name,scheme:i.scheme,schemeLabel:i.schemeLabel,auth:a,schemes:s.length>1?s:void 0,acceptedSchemes:s.length>1?i.acceptedSchemes:void 0});return{token:c,url:k(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}.`:``;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} 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(
|
|
1
|
+
import{MANAGE_API_CREDENTIALS_TOOL_NAME as e,MCP_CREDENTIALS_ROUTE as t}from"../../constants.js";import{withPathPrefix as n}from"../../../../../../shared/path-prefix.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(t,{url:n,canManageCredentials:r}){return[`The user accepted the prompt to add credentials for the "${t}" 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 \`${e}\` 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:k(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 A(e,t,T(e.subject))}function b(t,{schemeLabel:n,canManageCredentials:r}){let i=S(t);if(!t.sentScheme&&(t.status===401||!t.schemes))return[`The "${t.name}" API returned ${i}. No stored credential was sent with this request, so this result says nothing about the stored credentials.`,``,t.unsupportedSchemes?`Do not replace them. This operation accepts only ${t.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(t.status===403&&t.sentScheme)return[`The "${t.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(t),`If the user has a different credential, or the API answer says this one is invalid or expired, call \`${e}\` with api: "${t.api}" to get a link where they can save it.`]:[`This client cannot replace the stored credentials.`]].join(`
|
|
4
|
+
`);let a=t.status===401?`The "${t.name}" API rejected the stored ${n?`"${n}" `:``}credential (${i}).`:`The "${t.name}" API rejected the request with ${i}.`;if(!r)return[a,``,t.sentScheme?`Do not retry the same call. Tell the user what the API answered. This client cannot replace the stored credentials.`:`Do not retry the same call. Tell the user what the API answered.`].join(`
|
|
5
|
+
`);let o=n?`api: "${t.api}" and scheme: "${n}"`:`api: "${t.api}"`;return[a,``,...x(t),`Do not retry the same call. Call \`${e}\` 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:k(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}.`:``;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} 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,r){let i=new URL(n(t),e);return i.searchParams.set(`token`,r),i.toString()}function A({target:e,reason:t,hasExistingSecret:n},r,i){let a=[`**Stop and show the user this link. They have to open it in a browser to ${n?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - 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.`]:[],i?`Once the user confirms they saved them, retry the call that needed them with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:`Once the user confirms they saved them, retry the call that needed them - the credentials are applied server-side and never appear in the conversation.`],o=t.kind===`authFailure`?t.otherApiNames??[]:[];if(o.length>0){let e=o.map(e=>`"${e}"`).join(`, `);a.push(``,`The remaining APIs (${e}) will prompt for credentials on subsequent calls.`)}return a.join(`
|
|
7
7
|
`)}export{l as CREDENTIALS_INPUT_REQUEST_KEY,g as acceptedCredentialsLink,h as buildCredentialsAcceptedHint,b as buildCredentialsToolHint,y as buildUpstreamCredentialFallback,v as buildUpstreamCredentialInputRequired,m as credentialElicitationAnswer,d as dedupeElicitation,p as isStatelessRequest,_ as schemeLabelOf,f as supportsUrlElicitation};
|
|
@@ -1 +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 l}from"../api-call-operations.js";import{matchesOrigin as ee}from"./allowed-hosts.js";import{GatewayFetchBlockedError as u,GatewayFetchHostNotAllowedError as d,GatewayFetchSystemError as f,GatewayFetchUserError as p}from"./fetch-errors.js";import{normalizeFetchPath as te}from"./normalize-path.js";import{assertUrlAllowed as m}from"./ssrf-guard.js";import{extractUpstreamDetail as ne}from"./upstream-detail.js";import{Agent as h}from"undici";const g=`x-forwarded-for`,re=/%2f|%5c/i,ie=/* @__PURE__ */ new Set([401,403,407]),ae=[`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 h({connect:{lookup:t({allowLoopback:n})}})}return _}function y({apis:e,onAuthRequired:t,sent:d,runEnded:m,logger:h,telemetry:g,fetchImpl:ae=fetch,dispatcher:_=v(h),timeoutMs:y=3e4,deadline:x=1/0,maxResponseBytes:D=1048576,maxFetchesPerExec:O,beforeSend:be,caller:k,allowedHttpMethods:A}){let j=e.flatMap(e=>e.matchers),xe=[...new Set(e.map(e=>e.name).filter(Boolean))].join(`, `),M=e.flatMap(e=>Object.values(e.secrets??{})),N=M.flatMap(a),Se=M.map(e=>e.header),P=e.flatMap(e=>e.credentialQueryParams??[]),F=0,Ce=!1;return async a=>{let v=c(a.method??`GET`),M=Date.now(),we,I,L,R={},z,B,V,H,Te=!1;try{if(O!==void 0){let e=Math.max(0,O);if(F+=1,F>e)throw new p(`Outbound fetch budget exceeded (max ${e} fetches per execute); split the work across calls`)}if(A&&!A.includes(v))throw new u(`${v} is not allowed: this project permits only ${A.join(`, `)} API calls`,T(a.url));let o=oe(a.url,j,xe);if(we=o.hostname,I=te(o.pathname),re.test(o.pathname))throw new u(`${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=>ee(e,o))),f=c.flatMap(e=>e.operations?l(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}]),b=Math.min(...f.map(e=>e.variables)),S=f.filter(e=>e.variables===b);if(c.length>0&&(f.length===0||S.some(e=>!e.visible)))throw new u(`${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=S.find(e=>!e.callable);if(w)throw new u(`${v} ${o.pathname} is not callable: this operation of ${w.api.name} is excluded from agent calls`,o.hostname);let E=[...new Set(S.map(e=>e.api))];if(E.length>1&&E.some(e=>me(e,v,o.pathname)))throw new u(he(E,`${v} ${o.pathname}`),o.hostname);let U=E.length===1?E[0]:void 0;L=U?.slug;let W=U&&pe(U,v,o.pathname);if(W?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${v} ${o.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((v===`GET`||v===`HEAD`)&&a.body!==void 0)throw new p(`A ${v} request cannot have a body; remove \`body\``);R=ve({callerHeaders:a.headers,secret:J,clientIp:k?.clientIp});let Ee=ge(a.headers,o,c,J);if(Ee&&(J||Ce))throw new p(_e(Ee,!!J));if(x-Date.now()<=0)throw new p(`The execute time limit ended before this request was sent`);await be?.(),Ce||=!!J,z=J?q:void 0;let Y=new AbortController,De=x-Date.now();if(H=De<y?setTimeout(()=>Y.abort(new p(`The request did not finish before the execute time limit`)),De):setTimeout(()=>{Te=!0,Y.abort()},y),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);V={method:v,url:i(o.origin+o.pathname,N)},d?.push(V);let X=await ae(o,{method:v,headers:R,body:a.body,redirect:`manual`,signal:Y.signal,dispatcher:_});B=X.status,V.status=X.status;let Z=``;try{Z=await le(X,D)}finally{if(ie.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]),z&&(e.sentScheme=z),W?.unsupportedSchemes&&(e.unsupportedSchemes=[...W.unsupportedSchemes]);let n=ne(Z,X.headers.get(`content-type`),N);n&&(e.detail=n),t(e)}}let Q=r(ye(X.headers),N);if(se(X.status)){Q=n(Q,Se);let{location:e}=Q;e&&!ce(e,o,j)&&delete Q.location}let $=C(X.status);return g?.gatewayFetchPerformed({host:o.hostname,method:v,outcome:$,durationMs:Date.now()-M,path:I,api:L,status:X.status,bytes:Buffer.byteLength(Z,`utf8`),injectedScheme:z}),s(h,{rawUrl:o.href,method:v,host:o.hostname,outcome:$,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:I,api:L,status:X.status,injectedScheme:z,requestHeaders:R,requestBody:a.body,responseHeaders:Q,responseBody:Z,caller:k}),{status:X.status,statusText:i(X.statusText,N),ok:X.ok,headers:Q,bodyText:i(Z,N)}}catch(e){let t=V!==void 0&&S(e);t&&V&&d&&d.splice(d.indexOf(V),1);let{outcome:n,userSafe:r}=w(e,B),c=we??(r instanceof u?r.host:void 0)??T(a.url)??`invalid-url`;if(g?.gatewayFetchPerformed({host:c,method:v,outcome:n,durationMs:Date.now()-M,path:I,api:L,status:B,injectedScheme:z}),s(h,{rawUrl:a.url,method:v,host:c,outcome:n,durationMs:Date.now()-M,injectedSecretValues:N,credentialQueryParams:P,path:I,api:L,status:B,injectedScheme:z,requestHeaders:R,requestBody:a.body,caller:k}),r)throw r;let l=Te?{reason:`timeout after ${y} ms`,message:B===void 0?`The API did not answer within ${y/1e3} s`:`The API did not finish its answer within ${y/1e3} s`}:t?{reason:`connect failure ${b(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 [${v} ${c}]: ${i(l.reason,N)} headers=${o(R)}`),new f(l.message)}finally{H!==void 0&&clearTimeout(H)}}}function b(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(b).find(e=>e!==void 0);t=t.cause}}function x(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 S(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(S);let{code:t,syscall:r}=n;if(t===`UND_ERR_CONNECT_TIMEOUT`||r===`connect`||r===`getaddrinfo`)return!0;n=n.cause}return!1}function C(e){return ie.has(e)?`auth_failure`:e>=400?`upstream_error`:`success`}function w(t,n){let r=x(t),i=n===void 0?void 0:C(n);return{outcome:i!==void 0&&i!==`success`?i:r instanceof u||r instanceof e?`blocked`:r?`user_error`:`system_error`,userSafe:r}}function oe(e,t,n){try{return m(e,t)}catch(e){throw e instanceof d&&n?new u(`${e.message}. \`fetch\` reaches only the documented hosts of the callable APIs (${n}); other documented APIs can be read through the tools but not called.`,e.host):e}}function T(e){try{return new URL(e).hostname||void 0}catch{return}}function se(e){return e>=300&&e<400}function ce(e,t,n){try{return!!m(new URL(e,t).href,n)}catch{return!1}}function E(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error?`${e.message}: ${t.message}`:e.message}async function le(e,t){let n=Number(e.headers.get(`content-length`));if(Number.isFinite(n)&&n>t)throw D(t,n);if(!e.body)return``;let r=e.body.getReader(),i=new TextDecoder,a=0,o=``;try{for(;;){let{done:e,value:n}=await r.read();if(e)break;if(a+=n.byteLength,a>t)throw D(t,a);o+=i.decode(n,{stream:!0})}return o+i.decode()}finally{await r.cancel().catch(()=>{})}}function D(e,t){return new p(`Response is too large (over ${e} bytes, got ${t}); request less data`)}function ue(e,t){let n=t.filter(t=>e.secrets?.[t]);return n.length===0?t[0]:n.reduce((t,n)=>{let r=e.secrets?.[t]?.savedAt??0;return(e.secrets?.[n]?.savedAt??0)>r?n:t})}function de(e,t){if(e==null)return;if(typeof e!=`string`)throw new p(`securityScheme must be a security scheme name (a string)`);if(!t)throw new p(`securityScheme cannot be applied: the URL host does not identify exactly one callable API`);let n=t.schemePriority??[];if(n.length>0&&!n.includes(e))throw new p(`This site cannot send securityScheme "${e}" to ${t.name}; valid values: ${n.join(`, `)}`);return e}function fe(e){let t=Object.keys(e.secrets??{});if(t.length===0)return e.defaultScheme?[e.defaultScheme]:[];let n=(e.schemePriority??[]).filter(e=>t.includes(e));return[...n,...t.filter(e=>!n.includes(e))]}function pe(e,t,n){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([...ae,...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{y as buildFetchBridge,v as getDefaultAgent,le 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,F=!1;return async a=>{let y=c(a.method??`GET`),j=Date.now(),we,I,L,R={},z,B,V,H,Te=!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(we=c.hostname,I=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 U=[...new Set(T.map(e=>e.api))];if(U.length>1&&U.some(e=>me(e,y,c.pathname)))throw new u(he(U,`${y} ${c.pathname}`),c.hostname);let W=U.length===1?U[0]:void 0;L=W?.slug;let G=W&&pe(W,y,c.pathname);if(G?.unsupportedSchemes&&a.securityScheme!=null)throw new p(`${y} ${c.pathname} accepts only ${G.unsupportedSchemes.map(e=>`"${e}"`).join(`, `)}, which this site cannot send. Call it without securityScheme, and do not replace the stored credentials.`);let Ee=de(a.securityScheme,W),K=Ee?[Ee]:W?G?.schemes??fe(W):void 0,q=W&&K?ue(W,K):void 0,J=q?W?.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\``);R=ve({callerHeaders:a.headers,secret:J,clientIp:k?.clientIp});let De=ge(a.headers,c,f,J);if(De&&(J||F))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?.(),F||=!!J,z=J?q:void 0;let Y=new AbortController,Oe=S-Date.now();if(H=Oe<b?setTimeout(()=>Y.abort(new p(`The request did not finish before the execute time limit`)),Oe):setTimeout(()=>{Te=!0,Y.abort()},b),m?.aborted)throw new p(`The execute call had already answered, so this request was not sent`);V={method:y,url:i(c.origin+c.pathname,M)},d?.push(V);let X=await ie(c,{method:y,headers:R,body:a.body,redirect:`manual`,signal:Y.signal,dispatcher:v});B=X.status,V.status=X.status;let Z=``;try{Z=await le(X,D)}finally{if(_.has(X.status)&&W&&t){let e={api:W.slug,name:W.name,status:X.status};q&&(e.scheme=q),K?.length&&(e.schemes=[...K]),z&&(e.sentScheme=z),G?.unsupportedSchemes&&(e.unsupportedSchemes=[...G.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:I,api:L,status:X.status,bytes:Buffer.byteLength(Z,`utf8`),injectedScheme:z}),s(h,{rawUrl:c.href,method:y,host:c.hostname,outcome:$,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:I,api:L,status:X.status,injectedScheme:z,requestHeaders:R,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=V!==void 0&&C(e);t&&V&&d&&d.splice(d.indexOf(V),1);let{outcome:n,userSafe:r}=T(e,B),c=we??(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:I,api:L,status:B,injectedScheme:z}),s(h,{rawUrl:a.url,method:y,host:c,outcome:n,durationMs:Date.now()-j,injectedSecretValues:M,credentialQueryParams:N,path:I,api:L,status:B,injectedScheme:z,requestHeaders:R,requestBody:a.body,caller:k}),r)throw r;let l=Te?{reason:`timeout after ${b} ms`,message:B===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(R)}`),new f(l.message)}finally{H!==void 0&&clearTimeout(H)}}}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
|
-
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{
|
|
1
|
+
import{CALL_API_WRITE_TOOL_NAME as e,MANAGE_API_CREDENTIALS_TOOL_NAME as t}from"../../constants.js";import{isObject as n}from"../../../../../../shared/utils/is-object.js";import{publicOrigin as r}from"../../../../utils/request-origin.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(t,n,r){if(!n.includes(r))return f(t).includes(r)?`fetch sends safe methods only. Use the \`${e}\` tool for ${r} requests.`:`${r} is not allowed: ${m(t.config.mcp).includes(r)?`this client cannot send write requests`:`this call sends only ${n.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:n,serverContext:r,allowedHttpMethods:i,run:a},s){let l=c(e,n);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(r.mcpReq);e.logger?.info(`gateway mcp credentials prompt: era=${b?`2026-07-28`:`2025`} urlElicitation=${A(r.mcpReq)}`);let x={ctx:e,serverContext:r,subject:l.subject,stored:J(m),plans:h,canManageCredentials:!o(t,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(e,t){if(!e.isError||t.length===0)return e;let r=t.map(e=>({...e})),i=`These requests reached the API before the failure, and running the code again sends them again:
|
|
2
2
|
`+r.map(e=>`${e.method} ${e.url} -> ${e.status??`no response`}`).join(`
|
|
3
|
-
`);return{...
|
|
3
|
+
`);return{...e,content:[...e.content.slice(0,-1),{type:`text`,text:i},...e.content.slice(-1)],structuredContent:{...n(e.structuredContent)?e.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:t,plans:
|
|
5
|
+
`)}function Q({ctx:e,subject:t,plans:n},i){let[a,...o]=i,s=n.get(a.api),c=a.scheme??s.defaultScheme,l=a.schemes&&a.schemes.length>1?a.schemes:void 0;return{subject:t,baseUrl:r(e.request),target:{api:a.api,name:a.name,scheme:c,schemeLabel:l?void 0:X(a,n),acceptedSchemes:l},auth:s.schemes[c]??{kind:`raw`},apiAuth:s,secretStore:new _(e.gatewaySecretSeed),kv:e.kv,hasExistingSecret:!1,reason:{kind:`authFailure`,status:a.status,detail:a.detail,otherApiNames:o.map(e=>e.name)}}}async function $(e,t,n){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=t.filter(e=>Y(e,s));if(u.length===0)return{kind:`prependText`,text:Z(t,e)};if(l===`accepted`){let e=await x(a.mcpReq.requestState(),{secretStore:new _(i.gatewaySecretSeed),kv:i.kv,subject:o,baseUrl:r(i.request),apis:u.map(e=>e.api)}),t=e?.apiName??u[0].name;return{kind:`prependText`,text:S(t,{url:e?.url,canManageCredentials:c})}}let d=Q(e,u);return!n||!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};
|
|
@@ -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";function i(){return[e,t,n,r]}export{i as gatewayTools};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,MANAGE_API_CREDENTIALS_TOOL_NAME as t,REMOVE_API_CREDENTIALS_TOOL_NAME as
|
|
2
|
-
`),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,
|
|
3
|
-
`),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,
|
|
4
|
-
`)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!
|
|
1
|
+
import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as e,MANAGE_API_CREDENTIALS_TOOL_NAME as t,READ_ONLY_ANNOTATIONS as n,REMOVE_API_CREDENTIALS_TOOL_NAME as r}from"../../constants.js";import{publicOrigin as i}from"../../../../utils/request-origin.js";import{isToolDisabledByCaller as a}from"../disabled-tools.js";import{createSessionHandle as o,resolveSecretSubject as s}from"./subject.js";import{toolNameForMode as c}from"../codemode/tool-declarations.js";import{apiTitleKey as l,countApiTitles as u}from"../tools/api-titles.js";import{callableApis as d}from"./eligibility.js";import{SecretStore as f}from"./secret-store.js";import{resolveUpstreamApiAuth as p}from"./upstream-auth-scheme.js";import{acceptedCredentialsLink as m,buildCredentialsAcceptedHint as h,buildUpstreamCredentialFallback as g,buildUpstreamCredentialInputRequired as _,credentialElicitationAnswer as v,dedupeElicitation as y,isStatelessRequest as b,schemeLabelOf as x,supportsUrlElicitation as S}from"./elicitation.js";import{upstreamAuthKey as C}from"./upstream-auth.js";async function w(e){return(await d(e)).length>0}const T={schema:{name:e,title:`Create anonymous session`,description:`Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.`,schema:{type:`object`,required:[],additionalProperties:!1,properties:{}},annotations:n,outputSchema:{type:`object`,required:[`sessionHandle`],properties:{sessionHandle:{type:`string`}}}},isAvailable:async e=>!e.request.viewer?.isAuthenticated&&!a(`createAnonymousSession`,e.metadata)&&await w(e),execute:async()=>{let e={sessionHandle:o()};return{content:[{type:`text`,text:JSON.stringify(e)}],structuredContent:e}}};function E(e,t,n){let r=e.map(e=>e.relativePath),i=[...r,...k(e)],a={type:`string`,description:`${n}: its \`filePath\` or the \`name\` from \`${c(`list-apis`,t)}\`.${r.length>0?` The file paths are: ${r.join(`, `)}.`:``}`,minLength:1};return i.length>0&&(a.enum=i),a}const D={type:`string`,description:`Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.`,minLength:1};function O(e,n,i){return{name:t,title:`Manage API credentials`,description:[i?`Get a secure link where the user sets or replaces the credentials this server sends to a documented API.`:`Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.`,i?`Call it when the user wants to change an API key, or when a tool result tells you the stored credentials were rejected. To remove stored credentials, call \`${r}\` instead.`:`Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.`,`The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.`,`It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument.`].join(`
|
|
2
|
+
`),annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},schema:{type:`object`,required:[`api`],additionalProperties:!1,properties:{api:E(e,n,`The API to manage credentials for`),scheme:{type:`string`,description:`Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.`,minLength:1},sessionHandle:D}}}}function k(e){let t=u(e);return e.map(e=>e.name).filter(e=>t.get(l(e))===1)}function A(e,t){let n=e.find(e=>e.relativePath===t||e.name===t);if(n)return{api:n};let r=e.map(e=>e.relativePath).join(`, `);return{error:N(`Unknown API "${typeof t==`string`?t:``}". Credentials can only be managed for the APIs this server can call: ${r||`none`}.`)}}function j(e,t,n){return N(`Unknown scheme "${e}" for api "${t.relativePath}". The security schemes this server can store credentials for are: ${n.join(`, `)}.`)}async function M(e,t,n){let r=new f(t.gatewaySecretSeed),a=s(t,e.sessionHandle);if(a.kind!==`resolved`)return N(a.message);let{subject:o}=a,c=A(await d(t),e.api);if(`error`in c)return c.error;let{api:l}=c,u=i(t.request),w=v(n?.mcpReq.inputResponses);if(w===`accepted`){let e=await m(n?.mcpReq.requestState(),{secretStore:r,kv:t.kv,subject:o,baseUrl:u,apis:[l.relativePath]});return{content:[{type:`text`,text:h(l.name,{url:e?.url,canManageCredentials:!0})}],isError:!1}}if(w===`declined`)return{content:[{type:`text`,text:`The user declined the credentials prompt for the "${l.name}" API, so this call minted no link.`}],isError:!1};let T=p(l),E=typeof e.scheme==`string`?e.scheme:void 0,D=Object.keys(T.schemes);if(E&&!T.schemes[E])return j(E,l,D);let O=E??T.defaultScheme,k={subject:o,baseUrl:u,target:{api:l.relativePath,name:l.name,scheme:O,schemeLabel:E?x(T.schemes,E):void 0},auth:T.schemes[O],apiAuth:T,secretStore:r,kv:t.kv,hasExistingSecret:await r.hasSecret(t.kv,o,l.relativePath,O),reason:{kind:`requested`}};if(n&&b(n.mcpReq)&&S(n.mcpReq))return _(k);let M=C({api:l.relativePath,scheme:O});return{content:[{type:`text`,text:await y(`${o}:${M}`,()=>g(k))}],isError:!1}}function N(e){return{content:[{type:`text`,text:e}],isError:!0}}const P={schema:O([],`tools`,!0),schemaFor:async e=>O(await d(e),e.mcpMode,!a(r,e.metadata)),isAvailable:async e=>!a(`manageApiCredentials`,e.metadata)&&await w(e),execute:(e,t,n)=>M(e,t,n)};function F(e,n,i){return{name:r,title:`Remove API credentials`,description:[`Delete the credentials this server stores for the caller and sends to documented APIs. The user opens no link.`,`Call it only when the user asks to remove, clear, or forget their credentials.${i?` To replace a credential, call \`${t}\` instead.`:``}`,`Pass api to remove the credentials of one API, and add scheme to remove only one of them. To remove the credentials of every API, pass all: true instead of api.`].join(`
|
|
3
|
+
`),annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!0,openWorldHint:!1},schema:{type:`object`,required:[],additionalProperties:!1,properties:{api:E(e,n,`The API to remove credentials for`),scheme:{type:`string`,description:`Name of the security scheme to remove the credential for, as named in the API description. Needs api. Omit it to remove every credential of the API.`,minLength:1},all:{type:`boolean`,description:`Set to true, without api, to remove the credentials of every API. Use it only when the user asks to remove all their credentials.`},sessionHandle:D}}}}async function I(e,t){let n=new f(t.gatewaySecretSeed),r=s(t,e.sessionHandle);if(r.kind!==`resolved`)return N(r.message);let{subject:i}=r,a=await d(t),o=typeof e.scheme==`string`?e.scheme:void 0;if(e.api===void 0)return o===void 0?e.all===!0?L(await n.deleteSecrets(t.kv,i),a,`No credentials are stored for this caller, so nothing was removed.`):N(`Name the api to remove credentials for. To remove the credentials of every API, pass all: true instead.`):N(`Pass api together with scheme "${o}": a scheme belongs to one API.`);if(e.all===!0)return N(`Pass either api or all: true, not both.`);let c=A(a,e.api);if(`error`in c)return c.error;let{api:l}=c;if(o===void 0)return L(await n.deleteSecrets(t.kv,i,l.relativePath),a,`No credentials are stored for the "${l.name}" API, so nothing was removed.`);let u=Object.keys(p(l).schemes);if(!u.includes(o))return j(o,l,u);let m=`No credential is stored for the "${o}" scheme of the "${l.name}" API, so nothing was removed.`;return await n.hasSecret(t.kv,i,l.relativePath,o)?(await n.deleteSecret(t.kv,i,l.relativePath,o),L([{api:l.relativePath,scheme:o}],a,m)):L([],a,m)}function L(e,t,n){if(e.length===0)return{content:[{type:`text`,text:n}],isError:!1};let r=/* @__PURE__ */ new Map;for(let{api:t,scheme:n}of e)r.set(t,[...r.get(t)??[],n]);return{content:[{type:`text`,text:[`Removed the stored credentials:`,...[...r].map(([e,n])=>`- "${t.find(t=>t.relativePath===e)?.name??e}" (${e}): ${n.sort().join(`, `)}`),``,`This server no longer sends them. The next call that an API rejects with HTTP 401 asks the user for new credentials.`].join(`
|
|
4
|
+
`)}],isError:!1}}const R={schema:F([],`tools`,!0),schemaFor:async e=>F(await d(e),e.mcpMode,!a(t,e.metadata)),isAvailable:async e=>!a(`removeApiCredentials`,e.metadata)&&await w(e),execute:(e,t)=>I(e,t)};export{D as SESSION_HANDLE_PROPERTY,T as createAnonymousSessionTool,P as manageApiCredentialsTool,R as removeApiCredentialsTool};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{OPERATION_METHODS as e}from"
|
|
1
|
+
import{OPERATION_METHODS as e}from"../../../../../../shared/constants/openapi-operation-methods.js";import{basePathPrefix as t,operationHttpMethod as n,pathPattern as r,pathVariableCount as i}from"./route-pattern.js";const a=`default`,o={kind:`raw`},s=[`oauth2ClientCredentials`,`bearer`,`apiKey`,`cookie`,`raw`],c=new Set(e);function l(){return{schemes:{[a]:o},defaultScheme:a,routes:[],credentialQueryParams:[]}}function u(e){let{definition:t,servers:n}=e,r=_(t),i=Object.keys(r),a=d(t);if(i.length===0)return{...l(),credentialQueryParams:a};let o={schemes:r,defaultScheme:b(t.security,r)[0]??y(i,r)[0],routes:x(t,r,n),credentialQueryParams:a},s=g(t,i);return Object.keys(s).length>0&&(o.descriptions=s),o}function d(e){let t=/* @__PURE__ */ new Set;for(let n of Object.values(e.components?.securitySchemes??{}))S(n)&&n.type===`apiKey`&&n.in===`query`&&n.name&&t.add(n.name);return[...t]}function f(e){return[...new Set(Object.values(e).map(h))]}function p(e){return y(Object.keys(e),e)}function m(e,t){let n=/* @__PURE__ */ new Set;for(let r of e.routes)r.schemes?.includes(t)&&n.add(`${r.method} ${r.path}`);return[...n]}function h(e){return e.kind===`apiKey`?e.header:e.kind===`cookie`?`Cookie`:`Authorization`}function g(e,t){let n={};for(let r of t){let t=e.components?.securitySchemes?.[r],i=S(t)?t.description:void 0;if(typeof i!=`string`)continue;let a=i.split(`
|
|
2
2
|
`)[0].trim();a&&(n[r]=a.slice(0,120))}return n}function _(e){let t={};for(let[n,r]of Object.entries(e.components?.securitySchemes??{})){if(!S(r))continue;let e=v(r);e&&(t[n]=e)}return t}function v(e){if(e.type===`oauth2`){let t=e.flows?.clientCredentials;return t?{kind:`oauth2ClientCredentials`,tokenUrl:t.tokenUrl,scopes:Object.keys(t.scopes??{})}:{kind:`bearer`}}if(e.type===`openIdConnect`||e.type===`http`&&e.scheme?.toLowerCase()===`bearer`)return{kind:`bearer`};if(e.type===`apiKey`&&e.in===`header`)return{kind:`apiKey`,header:e.name||`X-Api-Key`};if(e.type===`apiKey`&&e.in===`cookie`&&e.name)return{kind:`cookie`,name:e.name}}function y(e,t){return[...e].sort((n,r)=>s.indexOf(t[n].kind)-s.indexOf(t[r].kind)||e.indexOf(n)-e.indexOf(r))}function b(e,t){let n=[];for(let r of e??[])for(let e of Object.keys(r))t[e]&&!n.includes(e)&&n.push(e);return n}function x(e,a,o){let s=t(o),l=[];for(let[t,i]of Object.entries(e.paths??{})){if(!i||typeof i!=`object`)continue;let o=r(s,t);if(o)for(let[r,s]of Object.entries(i)){if(!c.has(r.toLowerCase()))continue;let i=s?.security??e.security,u={pattern:o,path:t,method:n(r)};if(l.push(u),i===void 0)continue;let d=b(i,a);u.schemes=y(d,a);let f=i.map(e=>Object.keys(e)),p=d.length===0&&f.every(e=>e.length>0)?[...new Set(f.flat())]:[];p.length>0&&(u.unsupportedSchemes=p)}}return l.sort((e,t)=>i(e.path)-i(t.path))}function S(e){return typeof e==`object`&&!!e&&`type`in e}export{a as DEFAULT_SCHEME_NAME,f as credentialHeadersOf,m as operationsForScheme,p as orderedSchemesOf,u as resolveUpstreamApiAuth};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{AI_METADATA_HEADER as e}from"../constants.js";import{isMcpHidden as t,isPublicEndpointServed as n,resolveMcpAccess as r}from"./config-gate.js";import{notFoundResponse as i}from"../../../../../server/plugin-context.js";import{publicOrigin as a}from"../../../utils/request-origin.js";import{formatError as o,jsonRpcErrorResponse as s}from"./tool-errors.js";import{buildMcpFileTools as c,createCustomTool as l,invokeCustomTool as u}from"./custom-tools.js";import{authorizeMcpRequest as d}from"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p,resolveRequestInstructionsStyle as m,resolveRequestMcpMode as h}from"./mode.js";import{narrowMcpConfigForCaller as g}from"./gateway/caller-api-calls.js";import{isGatewayEnabled as _}from"./gateway/env.js";import{userSubject as v}from"./gateway/subject.js";import{parseUserAgent as y}from"./mcp-client.js";import{createMcpTelemetry as b}from"./mcp-telemetry.js";import{applyMcpRateLimit as x}from"./rate-limit.js";import{createToolRegistry as S}from"./tool-registry.js";import{mcpToolRegistry as C}from"./registry-instance.js";const w=`POST`;function T(e){return(e??``).split(`,`).some(e=>{let[t,...n]=e.split(`;`).map(e=>e.trim().toLowerCase());if(t!==`text/html`)return!1;let r=n.find(e=>e.startsWith(`q=`));return r===void 0||Number(r.slice(2))>0})}function E(){return s(405,`Method not allowed`,{Allow:w})}function D(e){let t={error:`Method Not Allowed`,message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${e}`};return new Response(JSON.stringify(t),{status:405,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,Allow:w}})}function O(){return s(501,`MCP transport is not available in this environment`)}function k(e){if(!e)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function A(t,n,r,i){let a=k(t.headers.get(e)),{userAgent:o}=n.request,{client:s,clientVersion:c}=y(o),l=h(t.url,p()),u=crypto.randomUUID(),d=v(n.request.viewer),f=n.request.ip??void 0;return{config:{...n.config,mcp:g(n.config.mcp,a)},entities:n.entities,hasRoute:e=>n.hasRoute(e),isSlugVisible:(e,t)=>n.isSlugVisible(e,t),kv:n.kv,gatewaySecretSeed:n.gatewaySecretSeed,logger:n.logger,pageMarkdown:n.pageMarkdown,search:n.search,request:n.request,metadata:a,mcpMode:l,instructionsStyle:m(t.url),requestId:u,executeDeadline:i,messageId:typeof a.messageId==`string`?a.messageId:void 0,callerSubject:d,client:s,clientVersion:c,accessToken:r.accessToken,isProtected:r.isProtected??!1,isAvailableMemo:/* @__PURE__ */ new Map,subprocess:n.subprocess,claims:r.claims,telemetry:b({userAgent:o,request:t,metadata:a,mode:l,requestId:u,callerSubject:d,clientIp:f,logger:n.logger})}}async function j(e){let t=_(e.config)?(await import(`./gateway/
|
|
1
|
+
import{AI_METADATA_HEADER as e}from"../constants.js";import{isMcpHidden as t,isPublicEndpointServed as n,resolveMcpAccess as r}from"./config-gate.js";import{notFoundResponse as i}from"../../../../../server/plugin-context.js";import{publicOrigin as a}from"../../../utils/request-origin.js";import{formatError as o,jsonRpcErrorResponse as s}from"./tool-errors.js";import{buildMcpFileTools as c,createCustomTool as l,invokeCustomTool as u}from"./custom-tools.js";import{authorizeMcpRequest as d}from"./auth.js";import{EXECUTE_DEADLINE_MS as f}from"./codemode/constants.js";import{resolveMcpMode as p,resolveRequestInstructionsStyle as m,resolveRequestMcpMode as h}from"./mode.js";import{narrowMcpConfigForCaller as g}from"./gateway/caller-api-calls.js";import{isGatewayEnabled as _}from"./gateway/env.js";import{userSubject as v}from"./gateway/subject.js";import{parseUserAgent as y}from"./mcp-client.js";import{createMcpTelemetry as b}from"./mcp-telemetry.js";import{applyMcpRateLimit as x}from"./rate-limit.js";import{createToolRegistry as S}from"./tool-registry.js";import{mcpToolRegistry as C}from"./registry-instance.js";const w=`POST`;function T(e){return(e??``).split(`,`).some(e=>{let[t,...n]=e.split(`;`).map(e=>e.trim().toLowerCase());if(t!==`text/html`)return!1;let r=n.find(e=>e.startsWith(`q=`));return r===void 0||Number(r.slice(2))>0})}function E(){return s(405,`Method not allowed`,{Allow:w})}function D(e){let t={error:`Method Not Allowed`,message:`In order to use this MCP server, you need to register it in your MCP client (VS Code, Cursor, Claude Code, etc.) using this URL: ${e}`};return new Response(JSON.stringify(t),{status:405,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`,Allow:w}})}function O(){return s(501,`MCP transport is not available in this environment`)}function k(e){if(!e)return{};try{let t=JSON.parse(e);return typeof t==`object`&&t&&!Array.isArray(t)?t:{}}catch{return{}}}function A(t,n,r,i){let a=k(t.headers.get(e)),{userAgent:o}=n.request,{client:s,clientVersion:c}=y(o),l=h(t.url,p()),u=crypto.randomUUID(),d=v(n.request.viewer),f=n.request.ip??void 0;return{config:{...n.config,mcp:g(n.config.mcp,a)},entities:n.entities,hasRoute:e=>n.hasRoute(e),isSlugVisible:(e,t)=>n.isSlugVisible(e,t),kv:n.kv,gatewaySecretSeed:n.gatewaySecretSeed,logger:n.logger,pageMarkdown:n.pageMarkdown,search:n.search,request:n.request,metadata:a,mcpMode:l,instructionsStyle:m(t.url),requestId:u,executeDeadline:i,messageId:typeof a.messageId==`string`?a.messageId:void 0,callerSubject:d,client:s,clientVersion:c,accessToken:r.accessToken,isProtected:r.isProtected??!1,isAvailableMemo:/* @__PURE__ */ new Map,subprocess:n.subprocess,claims:r.claims,telemetry:b({userAgent:o,request:t,metadata:a,mode:l,requestId:u,callerSubject:d,clientIp:f,logger:n.logger})}}async function j(e){let t=_(e.config)?(await import(`./gateway/tool-list.js`)).gatewayTools():[],n=e.subprocess?e.mcpToolEntries??[]:[],r=C.list(),i=/* @__PURE__ */ new Set([...r.map(e=>e.schema.name),...t.map(e=>e.schema.name),...n.map(e=>e.declaration.name)]),a=e.subprocess?await c({entities:e.entities,loadContentModule:e.loadContentModule,reservedNames:i,logger:e.logger}):[];if(t.length===0&&n.length===0&&a.length===0)return C;let o=S();for(let e of r)o.register(e);for(let e of t)o.register(e);for(let e of n)o.register(l(e));for(let e of a)o.register(e);return o}async function M(e,t,n,r={}){let i=await j(e),a;try{a=await import(`./mcp-server.js`)}catch(t){return e.logger?.error(`MCP transport failed to load: ${o(t)}`),async()=>O()}let s;return a.createMcpRequestHandler({registry:i,logger:e.logger,buildToolContext:r=>s??=A(r,e,t,n),onError:r.onError})}function N(e={}){return async(o,s,c)=>{let l=Date.now()+f;if(t(c.config)||e.publicEndpoint&&!n(c.config,r(c.config)))return i();if(o.req.method===`GET`&&T(o.req.header(`accept`)))return s();let u=await x({kv:c.kv,ip:c.request.ip,bucket:`mcp`,logger:c.logger});if(u)return u;let p=await d({c:o,ctx:c,forceAnonymous:e.forceAnonymous});return p.kind===`deny`?p.response:o.req.method===`GET`?D(`${a(c.request)}${new URL(c.request.url).pathname}`):o.req.method===`POST`?(await M(p.ctx,{isProtected:p.isProtected,accessToken:p.accessToken,claims:p.claims},l))(o.req.raw):E()}}const P=N(),F=N({forceAnonymous:!0,publicEndpoint:!0});export{A as buildToolContext,N as createMcpHandler,M as createServedMcpRequestHandler,u as invokeCustomTool,P as mcp,F as mcpPublic};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{CALL_API_WRITE_TOOL_NAME as e,CREATE_ANONYMOUS_SESSION_TOOL_NAME as t,DISCOVER_TOOL_NAME as n,EXECUTE_TOOL_NAME as r}from"../constants.js";import{isObject as i}from"../../../../../shared/utils/is-object.js";import{formatError as a}from"./tool-errors.js";import{auditToolCall as o,callAttribution as s}from"./audit.js";import{CODE_MODE_TOOL_NAMES as c,FETCH_TOOL_NAME as l}from"./codemode/constants.js";import{resolveMcpMode as u,resolveRequestMcpMode as d}from"./mode.js";import{sendMcpRequestError as f}from"./mcp-telemetry.js";import{availableTools as p,isToolAvailable as m,normalizeToolDisplayName as h}from"./tool-registry.js";import{mcpJsonSchemaValidator as g}from"./json-schema-validator.js";import{toToolListEntries as _}from"./codemode/tool-list.js";import{buildCodeModeInstructions as v,buildExecuteDescription as y,buildToolsModeInstructions as b}from"./codemode/prompts.js";import{composeExecuteAnnotations as x,getActiveCapabilities as S}from"./codemode/capabilities.js";import{discover as C,discoverSchema as w}from"./codemode/discover.js";import{EXECUTE_TOOL_SCHEMA as T,executeOutputSchema as E,executeToolTitle as D}from"./codemode/execute-schema.js";import{runCodeMode as O}from"./codemode/index.js";import{docsServerInfo as k}from"./server-info.js";import{loadSkillResources as A}from"./skills-resources.js";import{randomUUID as j}from"node:crypto";import{McpServer as M,createMcpHandler as N,fromJsonSchema as P,isCallToolResult as F,isInputRequiredResult as I}from"@modelcontextprotocol/server";const L=`text/markdown`,R={listChanged:!1};function z(e){let{title:t,description:n,schema:r,outputSchema:i,annotations:a,_meta:o}=h(e);return{title:t,description:n,inputSchema:P(r,g),outputSchema:i?P(i,g):void 0,annotations:a,_meta:o}}function B(e,t){if(e)return t;let n=t.schema,{sessionHandle:r,...i}=n.properties;return{...t,schema:{...n,properties:i}}}function V(e,t){if(F(e)||I(e))return e;let n=[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e)}];return t===`code`&&i(e)?{content:n,structuredContent:e}:{content:n}}function H(e,t){return(n,r)=>o(e,t.schema.name,n,async()=>V(await t.execute(n,e,r),e.mcpMode))}function U(e,t){return new M(e,{capabilities:{logging:{},tools:R},maxToolInputElements:1e4,instructions:t})}async function W(i,a,s){let[u,d]=await Promise.all([p(s,a),S(a)]),f=d.some(e=>e.id===l),h=u.some(({schema:t})=>t.name===e),g=u.filter(e=>!c.has(e.schema.name)).map(e=>e.schema),b=u.filter(({schema:e})=>c.has(e.name)&&e.name!==`execute`&&e.name!==`discover`),k=a.instructionsStyle!==`brief`,A=k?_(g,d):[],j=b.some(e=>e.schema.name===t),M=U(i,v(f,A,i.websiteUrl,h)),N=x(g,d);M.registerTool(r,z({...B(j,T),title:D(N),description:y(f,A,i.websiteUrl),outputSchema:E(f),annotations:N}),async(e,t)=>{let n=typeof e.sessionHandle==`string`?e.sessionHandle:void 0,i=t=>o(a,r,e,()=>O({code:e.code,description:e.description,sessionHandle:n,fetchBudget:50,registry:s,ctx:a,hostFetch:t}));if(!f)return i();let{runExecuteWithGateway:c}=await import(`./gateway/index.js`);return c({ctx:a,sessionHandle:n,serverContext:t,run:i})});let P=C(g,async e=>{let t=s.get(e);return t!==void 0&&await m(t,a)},d,a);M.registerTool(n,z(w(g,d,k)),e=>o(a,n,e,()=>P(e)));for(let e of b)M.registerTool(e.schema.name,z(B(j,e.schema)),H(a,e));return M}async function G(e,t,n){let r=new Map((await p(n,t)).map(e=>[e.schema.name,e])),i=U(e,b(e.websiteUrl));for(let e of n.list()){let n=r.get(e.schema.name)??e,a=i.registerTool(n.schema.name,z({...n.schema,outputSchema:void 0}),H(t,n));r.has(n.schema.name)||a.disable()}return i}async function K(e,t,n){let r=k(e.config,e.request),i=e.mcpMode===`code`?await W(r,e,t):await G(r,e,t);n.length>0&&i.server.registerCapabilities({resources:R});for(let e of n)i.registerResource(e.slug,e.uri,{title:e.title,description:e.description,mimeType:L},async()=>({contents:[{uri:e.uri,mimeType:L,text:await e.read()}]}));return i}function q(e){if(e.status!==200)return e;let t=new Headers(e.headers);return t.set(`Cache-Control`,`no-store`),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}function J(){return new Response(JSON.stringify({jsonrpc:`2.0`,error:{code:-32603,message:`Internal server error`,data:`internal error`},id:null}),{status:500,headers:{"Content-Type":`application/json`,"Cache-Control":`no-store`}})}function Y(e){return async t=>{let n;try{n=await e.buildToolContext(t);let r=await A(n),i=await K(n,e.registry,r),a=N(()=>i,{keepAliveMs:15e3,maxRequestBodySize:1048576,onerror:t=>e.logger?.warn(`MCP handler: ${t.message}`)}),o=await a.fetch(t);return t.headers.get(`mcp-method`)===`subscriptions/listen`&&await a.close(),q(o)}catch(r){if(e.onError)await e.onError(r);else{let i=n?s(n):{requestId:j()};e.logger?.error(`MCP request failed: ${a(r)}`,{request_id:i.requestId}),await f(r,d(t.url,u()),{logger:e.logger,caller:i})}return J()}}}export{Y as createMcpRequestHandler,z as toRegisterToolConfig};
|