@redocly/realm 0.137.0-next.9 → 0.137.0

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.
Files changed (105) hide show
  1. package/CHANGELOG.md +213 -1
  2. package/dist/cli/build/index.js +1 -1
  3. package/dist/client/app/Sidebar/useActions.js +1 -1
  4. package/dist/client/app/Sidebar/useSidebarItems.js +1 -1
  5. package/dist/client/app/hooks/catalog/useCatalogClassic.js +1 -1
  6. package/dist/client/app/hooks/catalog/useCatalogFilter.js +1 -1
  7. package/dist/client/app/search/useFacets.js +1 -1
  8. package/dist/client/app/seo/SeoTags.js +1 -1
  9. package/dist/client/app/utils/loadAndNavigate.js +1 -1
  10. package/dist/server/config/env-config.d.ts +2 -0
  11. package/dist/server/config/env-schema.d.ts +5 -0
  12. package/dist/server/config/env-schemas/feature-flags.d.ts +4 -0
  13. package/dist/server/config/env-schemas/feature-flags.js +1 -1
  14. package/dist/server/constants/plugins/search.js +1 -1
  15. package/dist/server/esbuild/esbuild-logger.d.ts +2 -2
  16. package/dist/server/esbuild/esbuild-logger.js +3 -3
  17. package/dist/server/plugins/api-docs/options.js +1 -1
  18. package/dist/server/plugins/api-docs/search/create-indexer.d.ts +5 -0
  19. package/dist/server/plugins/api-docs/search/create-indexer.js +1 -0
  20. package/dist/server/plugins/api-docs/search/get-ai-search-documents.d.ts +1 -1
  21. package/dist/server/plugins/api-docs/search/get-ai-search-documents.js +41 -41
  22. package/dist/server/plugins/api-docs/search/search-resolver.js +1 -1
  23. package/dist/server/plugins/catalog-entities/database/repositories/common/revision-repository.js +1 -1
  24. package/dist/server/plugins/catalog-entities/database/repositories/common/version-repository.js +1 -1
  25. package/dist/server/plugins/catalog-entities/database/repositories/utils/normalize-revision-flags.js +1 -1
  26. package/dist/server/plugins/config-parser/loaders/content-slugs-loader.js +1 -1
  27. package/dist/server/plugins/config-parser/loaders/versions-config-loader.js +1 -1
  28. package/dist/server/plugins/dev-onboarding/template/components/EditAppDescriptionDialog.js +1 -1
  29. package/dist/server/plugins/dev-onboarding/template/components/EditAppDialog.js +1 -1
  30. package/dist/server/plugins/dev-onboarding/template/components/EditCallbackUrlDialog.js +1 -1
  31. package/dist/server/plugins/markdown/is-partial.js +1 -1
  32. package/dist/server/plugins/mcp/codemode/capabilities/fetch/index.js +5 -4
  33. package/dist/server/plugins/mcp/codemode/capabilities/types.d.ts +5 -2
  34. package/dist/server/plugins/mcp/codemode/capabilities/utils.js +4 -4
  35. package/dist/server/plugins/mcp/codemode/code-execution-audit.js +1 -1
  36. package/dist/server/plugins/mcp/codemode/prompts.d.ts +1 -1
  37. package/dist/server/plugins/mcp/codemode/prompts.js +7 -6
  38. package/dist/server/plugins/mcp/codemode/sandbox/create-sandbox-setup.d.ts +2 -2
  39. package/dist/server/plugins/mcp/codemode/sandbox/create-sandbox-setup.js +1 -11
  40. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/console.d.ts +2 -0
  41. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/console.js +7 -0
  42. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/index.d.ts +1 -0
  43. package/dist/server/plugins/mcp/codemode/sandbox/polyfills/index.js +2 -2
  44. package/dist/server/plugins/mcp/codemode/sandbox/tool-input-validator.d.ts +5 -0
  45. package/dist/server/plugins/mcp/codemode/sandbox/tool-input-validator.js +1 -0
  46. package/dist/server/plugins/mcp/codemode/sandbox/unknown-tool-hint.d.ts +8 -0
  47. package/dist/server/plugins/mcp/codemode/sandbox/unknown-tool-hint.js +2 -0
  48. package/dist/server/plugins/mcp/codemode/tools/describe-tools.js +3 -1
  49. package/dist/server/plugins/mcp/codemode/tools/execute.js +1 -1
  50. package/dist/server/plugins/mcp/codemode/tools/manage-credentials.d.ts +2 -2
  51. package/dist/server/plugins/mcp/codemode/tools/manage-credentials.js +2 -2
  52. package/dist/server/plugins/mcp/docs-mcp/tool-schemas.js +1 -1
  53. package/dist/server/plugins/mcp/docs-mcp/tools/core/create-anonymous-session.js +1 -1
  54. package/dist/server/plugins/mcp/docs-mcp/tools/core/search.js +2 -2
  55. package/dist/server/plugins/mcp/docs-mcp/tools/core/types.d.ts +2 -2
  56. package/dist/server/plugins/mcp/docs-mcp/tools/graphql/get-graphql-type.js +5 -5
  57. package/dist/server/plugins/mcp/docs-mcp/tools/graphql/types.d.ts +2 -1
  58. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/list-apis.js +1 -1
  59. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/load-api-description.d.ts +4 -2
  60. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/load-api-description.js +1 -1
  61. package/dist/server/plugins/mcp/docs-mcp/tools/openapi/types.d.ts +6 -2
  62. package/dist/server/plugins/mcp/docs-mcp/utils/api-titles.d.ts +6 -0
  63. package/dist/server/plugins/mcp/docs-mcp/utils/api-titles.js +1 -0
  64. package/dist/server/plugins/mcp/gateway-mcp/elicitation.d.ts +11 -0
  65. package/dist/server/plugins/mcp/gateway-mcp/elicitation.js +5 -5
  66. package/dist/server/plugins/mcp/gateway-mcp/fetch/ssrf-guard.js +1 -1
  67. package/dist/server/plugins/mcp/gateway-mcp/fetch/url-placeholders.d.ts +5 -0
  68. package/dist/server/plugins/mcp/gateway-mcp/fetch/url-placeholders.js +1 -0
  69. package/dist/server/plugins/mcp/servers/docs-server.js +1 -1
  70. package/dist/server/plugins/mcp/servers/mcp-server.js +3 -3
  71. package/dist/server/plugins/mcp/types.d.ts +1 -0
  72. package/dist/server/plugins/mcp/utils/available-sandbox-tools.js +1 -1
  73. package/dist/server/plugins/mcp/workers/execute-mcp-tool.js +1 -1
  74. package/dist/server/plugins/search/ai-indexer/prepare-semantic-documents.js +1 -1
  75. package/dist/server/plugins/search/engines/flexsearch/index.js +1 -1
  76. package/dist/server/plugins/search/engines/flexsearch/search-index.d.ts +8 -4
  77. package/dist/server/plugins/search/engines/flexsearch/search-index.js +1 -1
  78. package/dist/server/plugins/search/llmstxt/create-llms-txt-generator.js +1 -1
  79. package/dist/server/plugins/search/llmstxt/index.d.ts +3 -1
  80. package/dist/server/plugins/search/llmstxt/index.js +9 -9
  81. package/dist/server/sandbox/sandbox.js +2 -2
  82. package/dist/server/sandbox/types.d.ts +9 -0
  83. package/dist/server/sandbox/utils/execution-budget.js +1 -1
  84. package/dist/server/sandbox/utils/return-last-expression.d.ts +6 -0
  85. package/dist/server/sandbox/utils/return-last-expression.js +1 -0
  86. package/dist/server/sandbox/utils/returns-from-top-level.d.ts +1 -2
  87. package/dist/server/sandbox/utils/returns-from-top-level.js +1 -1
  88. package/dist/server/sandbox/utils/setup-host-functions.d.ts +1 -0
  89. package/dist/server/sandbox/utils/setup-host-functions.js +2 -2
  90. package/dist/server/ssr/render.js +1 -1
  91. package/dist/server/store.js +1 -1
  92. package/dist/server/types/plugins/search.d.ts +7 -2
  93. package/dist/server/utils/globs.d.ts +4 -0
  94. package/dist/server/utils/globs.js +1 -1
  95. package/dist/server/utils/search/highlight-text-for-search.js +1 -1
  96. package/dist/server/web-server/middleware/ensureSearchData.js +1 -1
  97. package/dist/server/web-server/routes/dynamic-route.js +1 -1
  98. package/dist/server/web-server/routes/mcp-routes/mcp-oauth.js +1 -1
  99. package/dist/server/web-server/routes/mcp-routes/mcp-server-card.js +1 -1
  100. package/dist/{server/plugins/catalog-entities/utils/version-compare.d.ts → utils/version/compare-versions.d.ts} +1 -16
  101. package/dist/utils/version/compare-versions.js +1 -0
  102. package/package.json +11 -10
  103. package/dist/server/plugins/api-docs/search/search-indexer.d.ts +0 -9
  104. package/dist/server/plugins/api-docs/search/search-indexer.js +0 -1
  105. package/dist/server/plugins/catalog-entities/utils/version-compare.js +0 -1
@@ -1,4 +1,4 @@
1
- import type { CallToolResult, InputRequiredResult } from '@modelcontextprotocol/server';
1
+ import type { CallToolResult, InputRequiredResult, ServerContext } from '@modelcontextprotocol/server';
2
2
  import type { McpToolSchema } from '../../../../types';
3
3
  import type { McpToolContext } from '../../types.js';
4
4
  import type { KvService } from '@redocly/config';
@@ -16,5 +16,5 @@ export declare function manageApiCredentials(context: McpToolContext, deps: Mana
16
16
  api?: unknown;
17
17
  scheme?: unknown;
18
18
  sessionHandle?: unknown;
19
- }) => Promise<CallToolResult | InputRequiredResult>;
19
+ }, ctx: ServerContext) => Promise<CallToolResult | InputRequiredResult>;
20
20
  //# sourceMappingURL=manage-credentials.d.ts.map
@@ -1,2 +1,2 @@
1
- import{MANAGE_API_CREDENTIALS_TOOL_NAME as v}from"../../constants.js";import{buildUpstreamCredentialFallback as y,buildUpstreamCredentialInputRequired as b,schemeLabelOf as P}from"../../gateway-mcp/elicitation.js";import{getCallableApis as m,isFetchCapable as S}from"../../gateway-mcp/callable-apis.js";import{secretStore as I}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as w,resolveSecretSubject as k}from"../../gateway-mcp/subject.js";import{resolveUpstreamApiAuth as j}from"../../gateway-mcp/upstream-auth-scheme.js";function H(e){return!!e.elicitationEnabled&&S(e)}function U(e){const t=m(e).map(n=>n.relativePath);return{name:v,title:"Manage API credentials",description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.","The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.","It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument."].join(`
2
- `),annotations:{readOnlyHint:!1,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for.${t.length>0?` One of: ${t.join(", ")}.`:""}`,minLength:1,...t.length>0?{enum:t}:{}},scheme:{type:"string",description:"Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.",minLength:1},sessionHandle:{type:"string",description:"Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1}}}}}function _(e,c){return async t=>{const n=k(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(n.kind==="invalid")return l(n.message);if(n.kind==="anonymous")return l(w);const{subject:u}=n,h=typeof t.api=="string"?t.api:"",s=m(e).find(o=>o.relativePath===h||o.name===h);if(!s){const o=m(e).map(g=>g.relativePath).join(", ");return l(`Unknown api "${h}". Credentials can only be managed for the APIs this server can call: ${o||"none"}.`)}const r=await j(e,s.relativePath),a=typeof t.scheme=="string"?t.scheme:void 0,A=Object.keys(r.schemes);if(a&&!r.schemes[a])return l(`Unknown scheme "${a}" for api "${s.relativePath}". The security schemes this server can store credentials for are: ${A.join(", ")}.`);const i=a??r.defaultScheme,p=P(r.schemes,i),d=await c.getKv(),f={subject:u,baseUrl:e.baseUrl??"",target:{api:s.relativePath,name:s.name,scheme:i,...p?{schemeLabel:p}:{}},auth:r.schemes[i],apiAuth:r,kv:d,hasExistingSecret:await I.hasSecret(d,u,s.relativePath,i),reason:{kind:"requested"}};return c.getClientCapabilities()?.elicitation?.url?await b(f):{content:[{type:"text",text:await y(f)}],isError:!1}}}function l(e){return{content:[{type:"text",text:e}],isError:!0}}export{H as isManageApiCredentialsToolAvailable,_ as manageApiCredentials,U as manageApiCredentialsSchema};
1
+ import{MANAGE_API_CREDENTIALS_TOOL_NAME as P}from"../../constants.js";import{buildUpstreamCredentialFallback as b,buildUpstreamCredentialInputRequired as I,dedupeElicitation as S,isCredentialElicitationDeclined as k,isStatelessRequest as E,schemeLabelOf as w,supportsUrlElicitation as C}from"../../gateway-mcp/elicitation.js";import{getCallableApis as u,isFetchCapable as j}from"../../gateway-mcp/callable-apis.js";import{secretStore as T}from"../../gateway-mcp/secret-store.js";import{MISSING_SESSION_HANDLE_MESSAGE as q,resolveSecretSubject as $}from"../../gateway-mcp/subject.js";import{upstreamAuthKey as R}from"../../gateway-mcp/upstream-auth.js";import{resolveUpstreamApiAuth as L}from"../../gateway-mcp/upstream-auth-scheme.js";import{apiTitleKey as N,countApiTitles as O}from"../../docs-mcp/utils/api-titles.js";function W(e){return!!e.elicitationEnabled&&j(e)}function z(e){const s=u(e),t=s.map(r=>r.relativePath),a=[...t,...U(s)];return{name:P,title:"Manage API credentials",description:["Get a secure link where the user sets, replaces, or removes the credentials this server sends to a documented API.","Call it when the user wants to change or clear an API key, or when a tool result tells you the stored credentials were rejected.","The link covers every credential the API accepts, so scheme is optional - pass it only when a tool result names the scheme that was rejected.","It returns a link for the user to open - never ask for the secret in the conversation and never pass it as an argument."].join(`
2
+ `),annotations:{readOnlyHint:!1,openWorldHint:!1},schema:{type:"object",required:["api"],additionalProperties:!1,properties:{api:{type:"string",description:`The API to manage credentials for: its \`filePath\` or the \`name\` from \`listApis\`.${t.length>0?` The file paths are: ${t.join(", ")}.`:""}`,minLength:1,...a.length>0?{enum:a}:{}},scheme:{type:"string",description:"Name of the security scheme to manage the credential for, as named in the API description (a tool result that reports a rejected credential names it). Omit it to let the link cover every scheme the API accepts.",minLength:1},sessionHandle:{type:"string",description:"Handle returned by createAnonymousSession. Required while the caller is anonymous, so the credentials are stored against the same subject the API calls use.",minLength:1}}}}}function U(e){const s=O(e);return e.map(t=>t.name).filter(t=>s.get(N(t))===1)}function J(e,s){return async(t,a)=>{const r=$(e.user,typeof t.sessionHandle=="string"?t.sessionHandle:void 0);if(r.kind==="invalid")return h(r.message);if(r.kind==="anonymous")return h(q);const{subject:m}=r,p=typeof t.api=="string"?t.api:"",n=u(e).find(c=>c.relativePath===p||c.name===p);if(!n){const c=u(e).map(v=>v.relativePath).join(", ");return h(`Unknown api "${p}". Credentials can only be managed for the APIs this server can call: ${c||"none"}.`)}if(k(a.mcpReq.inputResponses))return{content:[{type:"text",text:`The user declined the credentials prompt for the "${n.name}" API, so this call minted no link.`}],isError:!1};const i=await L(e,n.relativePath),l=typeof t.scheme=="string"?t.scheme:void 0,y=Object.keys(i.schemes);if(l&&!i.schemes[l])return h(`Unknown scheme "${l}" for api "${n.relativePath}". The security schemes this server can store credentials for are: ${y.join(", ")}.`);const o=l??i.defaultScheme,d=w(i.schemes,o),f=await s.getKv(),A={subject:m,baseUrl:e.baseUrl??"",target:{api:n.relativePath,name:n.name,scheme:o,...d?{schemeLabel:d}:{}},auth:i.schemes[o],apiAuth:i,kv:f,hasExistingSecret:await T.hasSecret(f,m,n.relativePath,o),reason:{kind:"requested"}};if(E(a.mcpReq)&&C(s.getClientCapabilities()))return await I(A);const g=R({api:n.relativePath,scheme:o});return{content:[{type:"text",text:await S(`${m}:${g}`,()=>b(A))}],isError:!1}}}function h(e){return{content:[{type:"text",text:e}],isError:!0}}export{W as isManageApiCredentialsToolAvailable,J as manageApiCredentials,z as manageApiCredentialsSchema};
@@ -1 +1 @@
1
- import{shouldHandleMcpAuth as d}from"../../../utils/rbac/should-handle-mcp-auth.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as m}from"../constants.js";import{GRAPHQL_TYPE_KINDS as o,GRAPHQL_LIST_SCOPES as h}from"./tools/graphql/constants.js";import{OPERATION_METHODS as p}from"./tools/openapi/constants.js";const i={type:"string",nullable:!0},n={limit:{type:"number"},total:{type:"number"},page:{type:"number"},totalPages:{type:"number"}},r={codemodeType:"OpenApiServer[]"},s={codemodeType:"OpenApiSecurityRequirement[]"},l={codemodeType:"Record<string, OpenApiSecurityScheme>"},y={codemodeType:"OpenApiDocument"},f={codemodeType:"OpenApiOperation & { path: string; method: string }"},g={type:"object",additionalProperties:!1,required:[],properties:{filter:{type:"string",description:"Matches part of an API name, or of a description when no name matches",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of APIs per page. Default is 300",minimum:1,default:300,nullable:!0}}},a={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it",minLength:1},version:{type:"string",description:"API version",nullable:!0},filePath:{type:"string",description:"API definition file path",nullable:!0}}},b={type:"object",required:["name","path","method"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it",minLength:1},path:{type:"string",description:"Endpoint path (e.g. /api/v1/users)",minLength:1},method:{type:"string",description:"HTTP method (GET, POST, PUT, DELETE, etc.)",enum:[...p.map(e=>e.toUpperCase()),...p],minLength:1},version:{type:"string",description:"API version (required when multiple APIs share the same name but differ by version)",nullable:!0},filePath:{type:"string",description:"API definition file path",nullable:!0}}},S={type:"object",required:[],additionalProperties:!1,properties:{}},v={type:"object",required:[],additionalProperties:!1,properties:{}};function H(e){const t=[{name:"list-apis",title:"List APIs",description:"Lists the APIs documented in this project",schema:g,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i,version:i,servers:r,filePath:{type:"string",description:"API definition file path"},...e.hasCallableApis?{callable:{type:"boolean",description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}}:{}}}},...n}}},{name:"get-endpoints",title:"Get endpoints",description:"Get all endpoints for a specific API",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoints:{type:"array",items:{type:"object",properties:{path:{type:"string"},method:{type:"string"},summary:i,description:i,security:s}}}}}},{name:"get-endpoint-info",title:"Get endpoint info",description:"Get comprehensive information about specific endpoint including parameters, security, and examples",schema:b,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoint:f,globalSecurity:s,securitySchemes:l}}},{name:"get-security-schemes",title:"Get security schemes",description:"Get the security schemes for a specific API",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:i,version:i,securitySchemes:l,security:s}}},{name:"get-full-api-description",title:"Get full API description",description:"Get the complete OpenAPI description",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},definition:y}}},T(e.products,e.locales)];return d(e.requiresLogin,e.rbac)&&t.push({name:"whoami",title:"Who am I",description:"Get information about the currently authenticated user",schema:S,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{email:{type:"string"},name:{type:"string"},subject:{type:"string"},clientId:{type:"string"},scope:{type:"string"},issuedAt:{type:"string"},expiresAt:{type:"string"}}}}),e.hasGraphqlApis&&t.push(...O()),e.elicitationEnabled&&t.push({name:m,title:"Create anonymous session",description:"Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.",schema:v,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"object",required:["sessionHandle"],properties:{sessionHandle:{type:"string"}}}}),t}const A={type:"object",required:[],additionalProperties:!1,properties:{filter:{type:"string",description:"GraphQL schema name (or part of it)",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},P={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},kind:{type:"string",description:'Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).',enum:[...o],nullable:!0},scope:{type:"string",description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions \u2014 combine with `filter` to search nested fields anywhere in the schema.',enum:[...h],nullable:!0},filter:{type:"string",description:'Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")',minLength:1,nullable:!0},referencesType:{type:"string",description:'Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it \u2014 e.g. referencesType "Book" surfaces a search query returning a union that includes Book.',minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},L={type:"object",required:["name","type"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},type:{type:"string",description:"Name of the type, operation, or directive",minLength:1},includeReferencedTypes:{type:"boolean",description:"Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.",default:!1,nullable:!0}}},q={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1}}};function O(){return[{name:"list-graphql-apis",title:"List GraphQL APIs",description:"Lists available GraphQL schemas with their context and purpose",schema:A,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i}}},...n}}},{name:"get-graphql-type-list",title:"Get GraphQL type list",description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, \u2026) and carries a one-line description; operations also include their return type and argument signature \u2014 use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields \u2014 not just type names \u2014 set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',schema:P,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:{type:"string"},items:{type:"array",items:{type:"object",properties:{kind:{type:"string",enum:o},name:{type:"string"},description:i,type:{type:"string"},args:{type:"string"},directives:{type:"string"}}}},...n}}},{name:"get-graphql-type",title:"Get GraphQL type",description:'Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type\'s field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively \u2014 the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call get-graphql-type-list with `referencesType`.',schema:L,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}},{name:"get-graphql-schema",title:"Get GraphQL schema",description:"Get the complete GraphQL schema as SDL \u2014 the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer get-graphql-type-list (filter/paginate) plus targeted get-graphql-type calls, and reach for this only for small schemas or when you truly need the full SDL.",schema:q,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}}]}function T(e,t){const c=e&&e.length>0,u=t&&t.length>0;return{name:"search",title:"Search documentation",description:"Search across the documentation to fetch relevant content for a given query",schema:{type:"object",required:["query"],additionalProperties:!1,properties:{query:{type:"string",description:"Search query. Should be a single word or that phrase that is presented in a documentation.",minLength:1},...c?{product:{type:"string",description:"Optional product name to filter search results by specific product.",enum:e,nullable:!0}}:{},...u?{locale:{type:"string",description:"Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the project's default locale.",enum:t,nullable:!0}}:{}}},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"string"}}}const E=new Set(H({requiresLogin:!0,hasGraphqlApis:!0,elicitationEnabled:!0}).map(e=>e.name));export{E as ALL_DEFAULT_TOOL_NAMES,H as getDefaultToolSchemas};
1
+ import{SEMANTIC_SEARCH_API_URL as m}from"../../../constants/common.js";import{shouldHandleMcpAuth as h}from"../../../utils/rbac/should-handle-mcp-auth.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as y}from"../constants.js";import{GRAPHQL_TYPE_KINDS as o,GRAPHQL_LIST_SCOPES as f}from"./tools/graphql/constants.js";import{OPERATION_METHODS as p}from"./tools/openapi/constants.js";const i={type:"string",nullable:!0},n={limit:{type:"number"},total:{type:"number"},page:{type:"number"},totalPages:{type:"number"}},r={codemodeType:"OpenApiServer[]"},s={codemodeType:"OpenApiSecurityRequirement[]"},l={codemodeType:"Record<string, OpenApiSecurityScheme>"},g={codemodeType:"OpenApiDocument"},b={codemodeType:"OpenApiOperation & { path: string; method: string }"},v={type:"object",additionalProperties:!1,required:[],properties:{filter:{type:"string",description:"Matches part of an API name, or of a description when no name matches",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of APIs per page. Default is 300",minimum:1,default:300,nullable:!0}}},a={type:"object",required:[],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it. Omit when `filePath` is given.",minLength:1,nullable:!0},apiName:{type:"string",description:"Alias of `name`",nullable:!0},api:{type:"string",description:"Alias of `name`",nullable:!0},version:{type:"string",description:"API version",nullable:!0},filePath:{type:"string",description:"API definition file path, as returned by `listApis`",nullable:!0}}},S={type:"object",required:["path","method"],additionalProperties:!1,properties:{name:{type:"string",description:"API name, or a unique part of it. Omit when `filePath` is given.",minLength:1,nullable:!0},apiName:{type:"string",description:"Alias of `name`",nullable:!0},api:{type:"string",description:"Alias of `name`",nullable:!0},path:{type:"string",description:"Endpoint path (e.g. /api/v1/users)",minLength:1},method:{type:"string",description:"HTTP method (GET, POST, PUT, DELETE, etc.)",enum:[...p.map(e=>e.toUpperCase()),...p],minLength:1},version:{type:"string",description:"API version (required when multiple APIs share the same name but differ by version)",nullable:!0},filePath:{type:"string",description:"API definition file path, as returned by `listApis`",nullable:!0}}},A={type:"object",required:[],additionalProperties:!1,properties:{}},H={type:"object",required:[],additionalProperties:!1,properties:{}};function P(e){const t=[{name:"list-apis",title:"List APIs",description:"Lists the APIs documented in this project",schema:v,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i,version:i,servers:r,filePath:{type:"string",description:"API definition file path"},ambiguousTitle:{type:"boolean",description:"true = another API shares this title; pass `filePath`, or `version` when the copies differ by version"},...e.hasCallableApis?{callable:{type:"boolean",description:"true = the documented hosts of this API are reachable via `fetch`; false = documentation only"}}:{}}}},...n}}},{name:"get-endpoints",title:"Get endpoints",description:"Get all endpoints for a specific API",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoints:{type:"array",items:{type:"object",properties:{path:{type:"string"},method:{type:"string"},summary:i,description:i,security:s}}}}}},{name:"get-endpoint-info",title:"Get endpoint info",description:"Get comprehensive information about specific endpoint including parameters, security, and examples",schema:S,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},servers:r,endpoint:b,globalSecurity:s,securitySchemes:l}}},{name:"get-security-schemes",title:"Get security schemes",description:"Get the security schemes for a specific API",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:i,version:i,securitySchemes:l,security:s}}},{name:"get-full-api-description",title:"Get full API description",description:"Get the complete OpenAPI description",schema:a,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{api:{type:"string"},version:{type:"string"},definition:g}}},...m?[c(e.products,e.locales)]:[]];return h(e.requiresLogin,e.rbac)&&t.push({name:"whoami",title:"Who am I",description:"Get information about the currently authenticated user",schema:A,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{email:{type:"string"},name:{type:"string"},subject:{type:"string"},clientId:{type:"string"},scope:{type:"string"},issuedAt:{type:"string"},expiresAt:{type:"string"}}}}),e.hasGraphqlApis&&t.push(...G()),e.elicitationEnabled&&e.hasCallableApis&&t.push({name:y,title:"Create anonymous session",description:"Create an anonymous session handle for storing upstream API credentials. Pass the returned sessionHandle to execute when an API needs credentials and the caller is not signed in. Treat it as a secret and reuse it across calls.",schema:H,annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"object",required:["sessionHandle"],properties:{sessionHandle:{type:"string"}}}}),t}const L={type:"object",required:[],additionalProperties:!1,properties:{filter:{type:"string",description:"GraphQL schema name (or part of it)",minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},O={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},kind:{type:"string",description:'Optional: return only a single category of schema members. With scope "fields", restricts to the fields of that parent category ("objects", "interfaces", or "inputs" only).',enum:[...o,null],nullable:!0},scope:{type:"string",description:'Optional: what each list item is. "members" (default) lists top-level types and operations. "fields" flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions \u2014 combine with `filter` to search nested fields anywhere in the schema.',enum:[...f,null],nullable:!0},filter:{type:"string",description:'Optional: only members whose name or description contains this substring, case-insensitive (e.g. "custom tags")',minLength:1,nullable:!0},referencesType:{type:"string",description:'Optional: only members that reference this type directly or transitively (via return, field, argument, union-member or input-field types). Finds cross-cutting members that never name it \u2014 e.g. referencesType "Book" surfaces a search query returning a union that includes Book.',minLength:1,nullable:!0},page:{type:"number",description:"Page number",minimum:1,default:1,nullable:!0},limit:{type:"number",description:"Number of results per page. Default is 300",minimum:1,default:300,nullable:!0}}},T={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1},type:{type:"string",description:"Name of the type, operation, or directive",minLength:1,nullable:!0},typeName:{type:"string",description:"Alias of `type`",nullable:!0},includeReferencedTypes:{type:"boolean",description:"Also include the SDL of every type referenced transitively. Gives the whole subgraph at once, but can be large for highly-connected types.",default:!1,nullable:!0}}},q={type:"object",required:["name"],additionalProperties:!1,properties:{name:{type:"string",description:"GraphQL schema name",minLength:1}}};function G(){return[{name:"list-graphql-apis",title:"List GraphQL APIs",description:"Lists available GraphQL schemas with their context and purpose",schema:L,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{name:{type:"string"},description:i}}},...n}}},{name:"get-graphql-type-list",title:"Get GraphQL type list",description:'List all operations and types in a GraphQL schema as a flat, paginated list. Each item is tagged with its kind (query, object, enum, \u2026) and carries a one-line description; operations also include their return type and argument signature \u2014 use it to decide which members to fetch in detail. Narrow the result with `kind` (one category), `filter` (case-insensitive substring of the member name or description, e.g. "book"), or `referencesType` (only members that use a given type, directly or transitively) to explore a domain cheaply instead of pulling the full schema. To search nested fields \u2014 not just type names \u2014 set scope "fields": it flattens every field of every object/interface/input type into "ParentType.fieldName" entries with their descriptions, so `filter` finds things like an input field whose docstring mentions your keyword.',schema:O,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"object",properties:{name:{type:"string"},items:{type:"array",items:{type:"object",properties:{kind:{type:"string",enum:o},name:{type:"string"},description:i,type:{type:"string"},args:{type:"string"},directives:{type:"string"}}}},...n}}},{name:"get-graphql-type",title:"Get GraphQL type",description:'Get the SDL for a single GraphQL type, operation (query/mutation/subscription field), or directive. Without includeReferencedTypes, the SDL is followed by a one-level manifest of every directly referenced type\'s field names (e.g. "input ActionOperationInput { addTags, removeTags }"), so you can see what nested types contain before fetching them. Set includeReferencedTypes to instead pull in the full SDL of every type it references transitively \u2014 the whole structural subgraph in one call, ideal for complete exploration of an entity (e.g. Book and all the types it touches). That traversal only follows what the target depends on; to go the other direction and find the members that use a type, call get-graphql-type-list with `referencesType`.',schema:T,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}},{name:"get-graphql-schema",title:"Get GraphQL schema",description:"Get the complete GraphQL schema as SDL \u2014 the whole type graph in one call. Returns everything, so it can be very large and token-expensive for big schemas; prefer get-graphql-type-list (filter/paginate) plus targeted get-graphql-type calls, and reach for this only for small schemas or when you truly need the full SDL.",schema:q,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1},outputSchema:{type:"string"}}]}function c(e,t){const u=e&&e.length>0,d=t&&t.length>0;return{name:"search",title:"Search documentation",description:"Search across the documentation to fetch relevant content for a given query",schema:{type:"object",required:["query"],additionalProperties:!1,properties:{query:{type:"string",description:"Search query. Should be a single word or that phrase that is presented in a documentation.",minLength:1},...u?{product:{type:"string",description:"Optional product name to filter search results by specific product.",enum:[...e,null],nullable:!0}}:{},...d?{locale:{type:"string",description:"Optional locale code to filter search results by documentation language (e.g. 'en', 'ja'). Use the locale matching the language of the user's request. Defaults to the project's default locale.",enum:[...t,null],nullable:!0}}:{}}},annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!1,openWorldHint:!1},outputSchema:{type:"string"}}}const D=new Set([...P({requiresLogin:!0,hasGraphqlApis:!0,elicitationEnabled:!0,hasCallableApis:!0}).map(e=>e.name),c().name]);export{D as ALL_DEFAULT_TOOL_NAMES,P as getDefaultToolSchemas};
@@ -1 +1 @@
1
- import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as t}from"../../../constants.js";import{createSessionHandle as n}from"../../../gateway-mcp/subject.js";const o=async()=>({content:[{type:"text",text:JSON.stringify({sessionHandle:n()})}],isError:!1});function i(e){return!!e.elicitationEnabled&&!e.user?.isAuthenticated}var a={[t]:{execute:o,isAvailable:i}};export{a as default,i as isAnonymousSessionToolAvailable};
1
+ import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as o}from"../../../constants.js";import{isFetchCapable as i}from"../../../gateway-mcp/callable-apis.js";import{createSessionHandle as t}from"../../../gateway-mcp/subject.js";const r=async()=>({content:[{type:"text",text:JSON.stringify({sessionHandle:t()})}],isError:!1});function s(e){return!!e.elicitationEnabled&&e.mcpMode==="code"&&i(e)&&!e.user?.isAuthenticated}var c={[o]:{execute:r,isAvailable:s}};export{c as default,s as isAnonymousSessionToolAvailable};
@@ -1,6 +1,6 @@
1
- import{removeTrailingSlash as g,withPathPrefix as y,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as S}from"../../../../../../constants/common.js";const w=async(n,t)=>{const{query:e,product:c,locale:l}=n,u=t.config.l10n?.defaultLocale||S,h=JSON.stringify({query:e,product:c,locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${y(L.SEMANTIC_SEARCH)}`,o=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const s=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...o?{Cookie:o}:{}},body:h});if(!s.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await s.json(),d=new Set(t.searchIgnoredRoutes??[]),a=(p||[]).filter(r=>!R(r.url,d));if(a.length===0)return{content:[{type:"text",text:"No results found."}]};const m=r=>{try{return new URL(r,t.baseUrl).toString()}catch{return r}},i=a.map(r=>`### [${r.title}](${m(r.url)})
1
+ import{removeTrailingSlash as g,withPathPrefix as y,withoutPathPrefix as E}from"@redocly/theme/core/utils";import{ServerRoutes as L}from"../../../../../../constants/api.js";import{DEFAULT_LOCALE_PLACEHOLDER as S}from"../../../../../../constants/common.js";const w=async(n,t)=>{const{query:e,product:o,locale:l}=n,u=t.config.l10n?.defaultLocale||S,h=JSON.stringify({query:e,...o?{product:o}:{},locale:l||u}),f=`${t.internalBaseUrl||t.baseUrl}${y(L.SEMANTIC_SEARCH)}`,s=t.accessToken?`authorization=${String(t.accessToken).replace(/^Bearer /,"")}`:"";try{const a=await fetch(f,{method:"POST",credentials:"include",headers:{"Content-Type":"application/json",...s?{Cookie:s}:{}},body:h});if(!a.ok)return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0};const p=await a.json(),d=new Set(t.searchIgnoredRoutes??[]),i=(p||[]).filter(r=>!R(r.url,d));if(i.length===0)return{content:[{type:"text",text:"No results found."}]};const m=r=>{try{return new URL(r,t.baseUrl).toString()}catch{return r}},c=i.map(r=>`### [${r.title}](${m(r.url)})
2
2
 
3
3
  ${r.content}
4
4
  `).join(`
5
5
 
6
- `).trim();return{content:[{type:"text",text:i.length?i:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=g(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var v={search:w};export{v as default};
6
+ `).trim();return{content:[{type:"text",text:c.length?c:"No results found."}]}}catch{return{content:[{type:"text",text:"Error retrieving search results."}],isError:!0}}};function R(n,t){if(t.size===0)return!1;let e;try{e=new URL(n,"https://relative.invalid").pathname}catch{return!1}e=g(E(e));try{e=decodeURI(e)}catch{}return t.has(e)}var v={search:w};export{v as default};
@@ -1,7 +1,7 @@
1
1
  export type SearchArgs = {
2
2
  query: string;
3
- product?: string;
4
- locale?: string;
3
+ product?: string | null;
4
+ locale?: string | null;
5
5
  };
6
6
  export type WhoamiArgs = Record<string, never>;
7
7
  //# sourceMappingURL=types.d.ts.map
@@ -1,10 +1,10 @@
1
- import{respondWithGraphqlSchema as d}from"./tool-helpers.js";import{printTypeOrField as y,printTypeOrFieldWithReferences as a,referencedTypeManifest as $}from"./utils.js";const m=(r,c)=>d(r.name,c,({name:p,schema:n})=>{const{type:e,includeReferencedTypes:l}=r;if(l){const{sdl:t,referencedCount:s}=a(n,e);return`# Schema: ${p}
2
- # Type: ${e} (+ ${s} referenced types)
1
+ import{respondWithGraphqlSchema as s}from"./tool-helpers.js";import{printTypeOrField as d,printTypeOrFieldWithReferences as a,referencedTypeManifest as m}from"./utils.js";const h=(n,i)=>s(n.name,i,({name:p,schema:t})=>{const{includeReferencedTypes:c}=n,e=n.type??n.typeName;if(!e)throw new Error("Pass `type`: the name of the type, operation, or directive.");if(c){const{sdl:r,referencedCount:l}=a(t,e);return`# Schema: ${p}
2
+ # Type: ${e} (+ ${l} referenced types)
3
3
 
4
- ${t}`}const o=`# Schema: ${p}
4
+ ${r}`}const o=`# Schema: ${p}
5
5
  # Type: ${e}
6
6
 
7
- ${y(n,e)}`,f=$(n,e);if(f.length===0)return o;const i=["# Referenced types (one level, names only; fetch a type or set includeReferencedTypes for full SDL):",...f.map(t=>`# ${t}`)].join(`
7
+ ${d(t,e)}`,f=m(t,e);if(f.length===0)return o;const y=["# Referenced types (one level, names only; fetch a type or set includeReferencedTypes for full SDL):",...f.map(r=>`# ${r}`)].join(`
8
8
  `);return`${o}
9
9
 
10
- ${i}`});var h={"get-graphql-type":m};export{h as default};
10
+ ${y}`});var T={"get-graphql-type":h};export{T as default};
@@ -28,7 +28,8 @@ export type GetGraphqlTypeListArgs = {
28
28
  };
29
29
  export type GetGraphqlTypeArgs = {
30
30
  name: string;
31
- type: string;
31
+ type?: string;
32
+ typeName?: string;
32
33
  includeReferencedTypes?: boolean;
33
34
  };
34
35
  export type GetGraphqlSchemaArgs = {
@@ -1 +1 @@
1
- import{isFetchCapable as d}from"../../../gateway-mcp/callable-apis.js";import{filterApiDescriptionsByName as g}from"../../utils/api-name-matching.js";const h=async(n,i)=>{const{filter:s,page:l=1,limit:e=300}=n,o=d(i);let t=Object.values(i.apiDescriptionsMap);s&&(t=g(t,s));const a=(l-1)*e,c=a+e,p=Math.ceil(t.length/e),r=t.length;return t=t.slice(a,c),{content:[{type:"text",text:JSON.stringify({items:t.map(({relativePath:f,fetchEligible:m,...u})=>({filePath:f,...u,...o?{callable:m===!0}:{}})),limit:e,total:r,page:l,totalPages:p})}]}};var y={"list-apis":h};export{y as default};
1
+ import{isFetchCapable as d}from"../../../gateway-mcp/callable-apis.js";import{filterApiDescriptionsByName as h}from"../../utils/api-name-matching.js";import{apiTitleKey as y,countApiTitles as x}from"../../utils/api-titles.js";const A=async(c,i)=>{const{filter:s,page:l=1,limit:e=300}=c,p=d(i),n=Object.values(i.apiDescriptionsMap),r=x(n);let t=n;s&&(t=h(t,s));const a=(l-1)*e,m=a+e,u=Math.ceil(t.length/e),f=t.length;return t=t.slice(a,m),{content:[{type:"text",text:JSON.stringify({items:t.map(({relativePath:g,fetchEligible:b,...o})=>({filePath:g,...o,...(r.get(y(o.name))??0)>1?{ambiguousTitle:!0}:{},...p?{callable:b===!0}:{}})),limit:e,total:f,page:l,totalPages:u})}]}};var I={"list-apis":A};export{I as default};
@@ -1,7 +1,9 @@
1
1
  import type { OpenAPIDefinition } from '@redocly/api-docs';
2
2
  import type { McpToolContext } from '../../../types.js';
3
- export declare function loadApiDescription({ name, version, filePath }: {
4
- name: string;
3
+ export declare function loadApiDescription(args: {
4
+ name?: string;
5
+ apiName?: string;
6
+ api?: string;
5
7
  version?: string;
6
8
  filePath?: string;
7
9
  }, context: McpToolContext): Promise<OpenAPIDefinition>;
@@ -1 +1 @@
1
- import{describeAvailableApis as c,findApiDescriptionByNameAndVersion as u}from"../../utils/api-name-matching.js";import{getApiDescriptionFromFs as d}from"./utils.js";async function l({name:r,version:n,filePath:o},i){const e=o?Object.values(i.apiDescriptionsMap).find(s=>s.relativePath===o):u(i.apiDescriptionsMap,r,n);if(!e){if(o)throw new Error(`No API found with filePath "${o}". File paths are returned by the list-apis tool.`);const s=c(i.apiDescriptionsMap,r);throw new Error(s?`No API found matching "${r}". Available APIs: ${s}.`:`No API found matching "${r}".`)}const t=!!i?.config?.access?.requiresLogin,p=i?.config?.access?.rbac||{},a=await d({relativePath:e.relativePath||"",outdir:i.outdir||"",user:i.user,rbac:p,requiresLogin:t});if(!a)throw new Error(`No API found matching "${o||r}".`);return a}export{l as loadApiDescription};
1
+ import{describeAvailableApis as l,findApiDescriptionByNameAndVersion as h}from"../../utils/api-name-matching.js";import{getApiDescriptionFromFs as u}from"./utils.js";async function P(o,i){const{version:p,filePath:e}=o,r=o.name??o.apiName??o.api;if(!e&&!r)throw new Error("Pass `name` (the API title, or a unique part of it) or `filePath` from list-apis.");const t=Object.values(i.apiDescriptionsMap),n=e?t.find(a=>a.relativePath===e):t.find(a=>a.relativePath===r)??h(i.apiDescriptionsMap,r??"",p);if(!n){if(e)throw new Error(`No API found with filePath "${e}". File paths are returned by the list-apis tool.`);const a=l(i.apiDescriptionsMap,r??"");throw new Error(a?`No API found matching "${r}". Available APIs: ${a}.`:`No API found matching "${r}".`)}const c=!!i?.config?.access?.requiresLogin,f=i?.config?.access?.rbac||{},s=await u({relativePath:n.relativePath||"",outdir:i.outdir||"",user:i.user,rbac:f,requiresLogin:c});if(!s)throw new Error(`No API found matching "${e||r}".`);return s}export{P as loadApiDescription};
@@ -4,12 +4,16 @@ export type ListApisArgs = {
4
4
  limit?: number;
5
5
  };
6
6
  export type ApiNameVersionArgs = {
7
- name: string;
7
+ name?: string;
8
+ apiName?: string;
9
+ api?: string;
8
10
  version?: string;
9
11
  filePath?: string;
10
12
  };
11
13
  export type GetEndpointInfoArgs = {
12
- name: string;
14
+ name?: string;
15
+ apiName?: string;
16
+ api?: string;
13
17
  path: string;
14
18
  method: string;
15
19
  version?: string;
@@ -0,0 +1,6 @@
1
+ import type { ApiDescriptionInfo } from '../../types.js';
2
+ /** The form the API lookup compares titles in, so a collision here is a collision there. */
3
+ export declare function apiTitleKey(name: string): string;
4
+ /** How many APIs carry each title, keyed by `apiTitleKey`, so a shared title is detectable. */
5
+ export declare function countApiTitles(apis: ApiDescriptionInfo[]): Map<string, number>;
6
+ //# sourceMappingURL=api-titles.d.ts.map
@@ -0,0 +1 @@
1
+ function r(t){return t.trim().toLowerCase()}function c(t){const e=new Map;for(const{name:o}of t){const n=r(o);e.set(n,(e.get(n)??0)+1)}return e}export{r as apiTitleKey,c as countApiTitles};
@@ -31,6 +31,17 @@ type CredentialElicitationRequest = {
31
31
  hasExistingSecret: boolean;
32
32
  reason: CredentialElicitationReason;
33
33
  };
34
+ /** Concurrent prompts for one subject and scheme share the link the first one mints. */
35
+ export declare function dedupeElicitation(key: string, run: () => Promise<string>): Promise<string>;
36
+ export declare function supportsUrlElicitation(capabilities: {
37
+ elicitation?: {
38
+ url?: unknown;
39
+ };
40
+ } | undefined): boolean;
41
+ /** Only a 2026-07-28-era request carries `_meta` envelope keys, and it needs no session. */
42
+ export declare function isStatelessRequest(mcpReq: {
43
+ envelope?: unknown;
44
+ }): boolean;
34
45
  export declare function isCredentialElicitationDeclined(inputResponses: Record<string, unknown> | undefined): boolean;
35
46
  export declare function schemeLabelOf(schemes: Record<string, unknown>, scheme: string): string | undefined;
36
47
  /**
@@ -1,5 +1,5 @@
1
- import{inputRequired as h,inputResponse as w}from"@modelcontextprotocol/server";import{MANAGE_API_CREDENTIALS_TOOL_NAME as l}from"../constants.js";import{secretStore as d,ELICITATION_TTL_MS as y}from"./secret-store.js";import{operationsForScheme as I,orderedSchemesOf as A}from"./upstream-auth-scheme.js";import{ANONYMOUS_SUBJECT_PREFIX as u}from"./subject.js";const m="credentials";function R(e){const t=w(e,m);return t.kind==="elicit"&&(t.action==="decline"||t.action==="cancel")}function x(e,t){return Object.keys(e).length>1?t:void 0}async function F(e){const{url:t}=await f(e);return h({inputRequests:{[m]:h.elicitUrl({message:b(e),url:t})}})}async function L(e){const{url:t}=await f(e);return C(e,t,P(e.subject))}function U(e,t){const r=p(e);if(e.status===401&&!e.sentScheme){const[a,o]=e.callerHeader?[`Your code set the "${e.callerHeader}" header itself, so the stored credential was not sent.`,"Remove that header from the request and retry. Do not replace the stored credentials."]:["No stored credential was sent with this request, so this result says nothing about the stored credentials.","Do not replace them. Check whether this operation needs a different kind of credential or a different route."];return[`The "${e.name}" API returned ${r}. ${a}`,"",o].join(`
2
- `)}const n=e.status===401?`The "${e.name}" API rejected the stored ${t?`"${t}" `:""}credential (${r}).`:`The "${e.name}" API rejected the request with ${r}.`,i=t?`api: "${e.api}" and scheme: "${t}"`:`api: "${e.api}"`;return[n,"",`Do not retry the same call. Call \`${l}\` with ${i} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
3
- `)}function p({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}function H(e,t){const r=t.map(({name:n,label:i,description:a})=>`- ${n} \u2014 ${i}${a?`: ${a}`:""}`);return[`The "${e.name}" API rejected the request with ${p(e)} and this operation accepts more than one kind of credential:`,"",...r,"","Ask the user which one of these they have, and wait for the answer. Never guess and never reuse a value meant for another kind.",`Then call \`${l}\` with api: "${e.api}" and scheme set to the name they picked to get a link where they enter it.`].join(`
4
- `)}async function f({kv:e,subject:t,baseUrl:r,target:n,auth:i,apiAuth:a,hasExistingSecret:o}){const s=a?await k(e,t,n.api,a):[],c=await d.createElicitation(e,{subject:t,api:n.api,name:n.name,scheme:n.scheme,...n.schemeLabel?{schemeLabel:n.schemeLabel}:{},auth:i,hasExistingSecret:o,...s.length>1?{schemes:s}:{}});return{token:c,url:E(r,c)}}async function k(e,t,r,n){const a=(await d.getSecretsForSubject(e,t))[r]??{};return A(n.schemes).map(o=>{const s=I(n,o),c=n.descriptions?.[o];return{name:o,...c?{label:c}:{},auth:n.schemes[o],hasExistingSecret:!!a[o],...s.length>0?{operations:s}:{}}})}function P(e){return e.startsWith(u)?e.slice(u.length):void 0}function b({target:e,hasExistingSecret:t,reason:r}){const n=`The link works for ${$()} minutes.`,i=S(e),a=r.kind==="authFailure"&&r.detail?` The API answered: ${r.detail}.`:"";return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They go straight to the API and never enter the chat. ${n}`:`${g(i)} needs credentials.${a} Open this page in a browser to paste them - they go straight to the API and never enter the chat. ${n}`}function S({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function g(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $(){return Math.round(y/6e4)}function E(e,t){if(!e)return`/mcp/credentials?token=${t}`;try{const r=new URL("/mcp/credentials",e);return r.searchParams.set("token",t),r.toString()}catch{return`${e}/mcp/credentials?token=${t}`}}function C({target:e,reason:t,hasExistingSecret:r},n,i){const o=[`**Stop and show the user this link. They have to open it in a browser to ${r?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,"",n,"",`The link is valid ${$()} minutes and opens a form on this site. Credentials go straight to the API from there: never ask for them in the conversation and never pass them as a tool argument.`,"",t.kind==="authFailure"?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:""} and needs credentials.`:r?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, call this tool again with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:"Once the user confirms they saved them, call this tool again - the credentials are applied server-side and never appear in the conversation."],s=t.kind==="authFailure"?t.otherApiNames??[]:[];if(s.length>0){const c=s.map(T=>`"${T}"`).join(", ");o.push("",`The remaining APIs (${c}) will prompt for credentials on subsequent calls.`)}return o.join(`
5
- `)}export{m as CREDENTIALS_INPUT_REQUEST_KEY,U as buildCredentialsToolHint,H as buildSchemeChoiceHint,L as buildUpstreamCredentialFallback,F as buildUpstreamCredentialInputRequired,R as isCredentialElicitationDeclined,x as schemeLabelOf};
1
+ import{inputRequired as l,inputResponse as I}from"@modelcontextprotocol/server";import{MANAGE_API_CREDENTIALS_TOOL_NAME as d}from"../constants.js";import{secretStore as u,ELICITATION_TTL_MS as y}from"./secret-store.js";import{operationsForScheme as A,orderedSchemesOf as P}from"./upstream-auth-scheme.js";import{ANONYMOUS_SUBJECT_PREFIX as p}from"./subject.js";const m="credentials",h=new Map;function j(e,t){const r=h.get(e);if(r)return r;const n=t().finally(()=>{h.delete(e)});return h.set(e,n),n}function U(e){return!!e?.elicitation?.url}function F(e){return e.envelope!==void 0}function L(e){const t=I(e,m);return t.kind==="elicit"&&(t.action==="decline"||t.action==="cancel")}function M(e,t){return Object.keys(e).length>1?t:void 0}async function H(e){const{url:t}=await $(e);return l({inputRequests:{[m]:l.elicitUrl({message:k(e),url:t})}})}async function q(e){const{url:t}=await $(e);return v(e,t,g(e.subject))}function D(e,t){const r=f(e);if(e.status===401&&!e.sentScheme){const[o,s]=e.callerHeader?[`Your code set the "${e.callerHeader}" header itself, so the stored credential was not sent.`,"Remove that header from the request and retry. Do not replace the stored credentials."]:["No stored credential was sent with this request, so this result says nothing about the stored credentials.","Do not replace them. Check whether this operation needs a different kind of credential or a different route."];return[`The "${e.name}" API returned ${r}. ${o}`,"",s].join(`
2
+ `)}const n=e.status===401?`The "${e.name}" API rejected the stored ${t?`"${t}" `:""}credential (${r}).`:`The "${e.name}" API rejected the request with ${r}.`,i=t?`api: "${e.api}" and scheme: "${t}"`:`api: "${e.api}"`;return[n,"",`Do not retry the same call. Call \`${d}\` with ${i} to get a link the user has to open in a browser to replace or remove the stored credentials, then retry once they confirm they saved them.`].join(`
3
+ `)}function f({status:e,detail:t}){return t?`HTTP ${e}: ${t}`:`HTTP ${e}`}function B(e,t){const r=t.map(({name:n,label:i,description:o})=>`- ${n} \u2014 ${i}${o?`: ${o}`:""}`);return[`The "${e.name}" API rejected the request with ${f(e)} and this operation accepts more than one kind of credential:`,"",...r,"","Ask the user which one of these they have, and wait for the answer. Never guess and never reuse a value meant for another kind.",`Then call \`${d}\` with api: "${e.api}" and scheme set to the name they picked to get a link where they enter it.`].join(`
4
+ `)}async function $({kv:e,subject:t,baseUrl:r,target:n,auth:i,apiAuth:o,hasExistingSecret:s}){const a=o?await b(e,t,n.api,o):[],c=await u.createElicitation(e,{subject:t,api:n.api,name:n.name,scheme:n.scheme,...n.schemeLabel?{schemeLabel:n.schemeLabel}:{},auth:i,hasExistingSecret:s,...a.length>1?{schemes:a}:{}});return{token:c,url:C(r,c)}}async function b(e,t,r,n){const o=(await u.getSecretsForSubject(e,t))[r]??{};return P(n.schemes).map(s=>{const a=A(n,s),c=n.descriptions?.[s];return{name:s,...c?{label:c}:{},auth:n.schemes[s],hasExistingSecret:!!o[s],...a.length>0?{operations:a}:{}}})}function g(e){return e.startsWith(p)?e.slice(p.length):void 0}function k({target:e,hasExistingSecret:t,reason:r}){const n=`The link works for ${T()} minutes.`,i=E(e),o=r.kind==="authFailure"&&r.detail?` The API answered: ${r.detail}.`:"";return t?`Open this page in a browser to replace or remove the stored credentials for ${i}. They go straight to the API and never enter the chat. ${n}`:`${S(i)} needs credentials.${o} Open this page in a browser to paste them - they go straight to the API and never enter the chat. ${n}`}function E({name:e,schemeLabel:t}){return t?`the "${t}" scheme of the "${e}" API`:`the "${e}" API`}function S(e){return e.charAt(0).toUpperCase()+e.slice(1)}function T(){return Math.round(y/6e4)}function C(e,t){if(!e)return`/mcp/credentials?token=${t}`;try{const r=new URL("/mcp/credentials",e);return r.searchParams.set("token",t),r.toString()}catch{return`${e}/mcp/credentials?token=${t}`}}function v({target:e,reason:t,hasExistingSecret:r},n,i){const s=[`**Stop and show the user this link. They have to open it in a browser to ${r?`replace or remove the stored credentials for the "${e.name}" API`:`add credentials for the "${e.name}" API`} - nothing continues until they do.**`,"",n,"",`The link is valid ${T()} minutes and opens a form on this site. Credentials go straight to the API from there: never ask for them in the conversation and never pass them as a tool argument.`,"",t.kind==="authFailure"?`The upstream API "${e.name}" returned ${t.status}${t.detail?` (${t.detail})`:""} and needs credentials.`:r?`Credentials are already stored for the "${e.name}" API; the link lets the user replace or remove them.`:`The "${e.name}" API needs credentials.`,...e.schemeLabel?[`The operation authenticates with its "${e.schemeLabel}" security scheme.`]:[],i?`Once the user confirms they saved them, call this tool again with sessionHandle: "${i}" - the credentials are stored against that handle, applied server-side, and never appear in the conversation.`:"Once the user confirms they saved them, call this tool again - the credentials are applied server-side and never appear in the conversation."],a=t.kind==="authFailure"?t.otherApiNames??[]:[];if(a.length>0){const c=a.map(w=>`"${w}"`).join(", ");s.push("",`The remaining APIs (${c}) will prompt for credentials on subsequent calls.`)}return s.join(`
5
+ `)}export{m as CREDENTIALS_INPUT_REQUEST_KEY,D as buildCredentialsToolHint,B as buildSchemeChoiceHint,q as buildUpstreamCredentialFallback,H as buildUpstreamCredentialInputRequired,j as dedupeElicitation,L as isCredentialElicitationDeclined,F as isStatelessRequest,M as schemeLabelOf,U as supportsUrlElicitation};
@@ -1 +1 @@
1
- import{isIP as l}from"node:net";import{isHostAllowed as i}from"./allowed-hosts.js";import{isBlockedIp as a}from"./ssrf-blocklist.js";import{GatewayFetchBlockedError as c,GatewayFetchUserError as s}from"./fetch-errors.js";function m(o,r){let t;try{t=new URL(o)}catch{throw new s(`Invalid URL: ${o}`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new s(`Only http(s) URLs are allowed, got ${t.protocol}`);if(t.username||t.password)throw new s("URLs must not contain embedded credentials");const e=n(t.hostname);if(d(e)||!i(e,r))throw new c(`Host "${e}" is not allowed`,e);return t}function d(o){const r=n(o.toLowerCase()).split("%")[0];return r==="localhost"||r.endsWith(".localhost")?!0:l(r)!==0?a(r):!1}function n(o){return o.replace(/^\[|\]$/g,"")}export{m as assertUrlAllowed,d as isBlockedAddress};
1
+ import{isIP as d}from"node:net";import{isHostAllowed as h}from"./allowed-hosts.js";import{isBlockedIp as w}from"./ssrf-blocklist.js";import{GatewayFetchBlockedError as p,GatewayFetchUserError as r}from"./fetch-errors.js";import{findUnresolvedPlaceholders as a,unresolvedPlaceholderMessage as i}from"./url-placeholders.js";function v(o,t){let e;try{e=new URL(o)}catch{throw new r(`Invalid URL: ${o}`)}if(e.protocol!=="http:"&&e.protocol!=="https:")throw new r(`Only http(s) URLs are allowed, got ${e.protocol}`);if(e.username||e.password)throw new r("URLs must not contain embedded credentials");const n=a(e.hostname);if(n.length>0)throw new r(i(n));const s=c(e.hostname);if(f(s)||!h(s,t))throw new p(`Host "${s}" is not allowed`,s);const l=a(e.pathname);if(l.length>0)throw new r(i(l));return e}function f(o){const t=c(o.toLowerCase()).split("%")[0];return t==="localhost"||t.endsWith(".localhost")?!0:d(t)!==0?w(t):!1}function c(o){return o.replace(/^\[|\]$/g,"")}export{v as assertUrlAllowed,f as isBlockedAddress};
@@ -0,0 +1,5 @@
1
+ /** Collect the placeholder names one part of a URL still carries. */
2
+ export declare function findUnresolvedPlaceholders(urlPart: string): string[];
3
+ /** The refusal a caller reads when it left a placeholder in the URL. */
4
+ export declare function unresolvedPlaceholderMessage(names: readonly string[]): string;
5
+ //# sourceMappingURL=url-placeholders.d.ts.map
@@ -0,0 +1 @@
1
+ const o=/\{([^}/]+)\}/g,t=/^[A-Za-z_][A-Za-z0-9_]*$/;function n(e){const a=e.replace(/%7B/gi,"{").replace(/%7D/gi,"}"),l=new Set;for(const[,r]of a.matchAll(o))t.test(r)&&l.add(r);return[...l]}function s(e){const a=e.length>1?"placeholders":"placeholder",l=e.map(r=>`"${r}"`).join(", ");return`Unresolved ${a} ${l} in the URL. This is not a credentials problem. Replace every placeholder with a real value. Use the server variable default, or ask the user.`}export{n as findUnresolvedPlaceholders,s as unresolvedPlaceholderMessage};
@@ -1 +1 @@
1
- import{logger as S}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as M,MCP_TOOL_IS_AVAILABLE_KEY as v}from"../../../workers/mcp-tool-worker-pool.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as k}from"../constants.js";import{isAnonymousSessionToolAvailable as C}from"../docs-mcp/tools/core/create-anonymous-session.js";import{isManageApiCredentialsToolAvailable as L,manageApiCredentials as y,manageApiCredentialsSchema as D}from"../codemode/tools/manage-credentials.js";import{EXECUTE_TOOL_SCHEMA as A}from"../codemode/tools/execute-schema.js";import{EXECUTE_TOOL_NAME as w,CODE_MODE_TOOL_NAMES as N,FETCH_TOOL_NAME as x}from"../codemode/constants.js";import{buildCodeModeInstructions as H,buildExecuteDescription as I}from"../codemode/prompts.js";import{toToolListEntries as U}from"../codemode/build-tool-list.js";import{composeExecuteAnnotations as F,getActiveCapabilities as P}from"../codemode/capabilities/index.js";import{describeToolsSchema as R,describeTools as z}from"../codemode/tools/describe-tools.js";import{availableSandboxTools as W}from"../utils/available-sandbox-tools.js";import{toRegisterToolConfig as _}from"../utils/tool-registration.js";import{createMcpServer as X,createToolDispatch as Y,extractSerializableContext as $}from"./mcp-server.js";function g(c,r){const o=r.schema;if(C(c))return o;const{sessionHandle:f,...m}=o.properties;return{...o,properties:m}}async function ae({name:c,tools:r,context:o,skills:f=[],getKv:m}){const l=$(o),a=o.mcpMode==="code",s=a?P(o):[],T=s.some(e=>e.id===x),p=a?await W(r.filter(e=>!N.has(e.name)),l):[],b=U(p,s),O=a&&L(o),n=X(c,a?H(T,b):void 0),E={getClientCapabilities:()=>n.server.getClientCapabilities(),getKv:m},d=Y(l,E),u=async e=>{try{return await M.exec(v,[{toolName:e,context:l}],{timeout:1e4})}catch(i){return S.error(`Failed to check MCP tool availability for "${e}": ${i instanceof Error?i.message:String(i)}`),!1}};if(a){const e=[{tool:{...A,description:I(T,b),schema:g(o,A),annotations:F(s)},callback:d(w)},{tool:R(p,s),callback:z(p,u,s,o)}],i=r.find(t=>t.name===k);if(i&&C(o)&&e.push({tool:i,callback:d(i.name)}),O){const t=D(o);e.push({tool:{...t,schema:g(o,t)},callback:y(l,E)})}for(const{tool:t,callback:h}of e)n.registerTool(t.name,_(t),h)}else await Promise.all(r.map(async e=>{const i=n.registerTool(e.name,_(e),d(e.name));await u(e.name)||i.disable()}));for(const e of f)n.registerResource(e.slug,e.uri,{title:e.name,description:e.description,mimeType:"text/markdown"},async()=>({contents:[{uri:e.uri,mimeType:"text/markdown",text:e.content}]}));return n}export{ae as createDocsMcpServer};
1
+ import{logger as g}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as M,MCP_TOOL_IS_AVAILABLE_KEY as v}from"../../../workers/mcp-tool-worker-pool.js";import{CREATE_ANONYMOUS_SESSION_TOOL_NAME as k}from"../constants.js";import{isAnonymousSessionToolAvailable as C}from"../docs-mcp/tools/core/create-anonymous-session.js";import{isManageApiCredentialsToolAvailable as L,manageApiCredentials as y,manageApiCredentialsSchema as x}from"../codemode/tools/manage-credentials.js";import{EXECUTE_TOOL_SCHEMA as h}from"../codemode/tools/execute-schema.js";import{EXECUTE_TOOL_NAME as D,CODE_MODE_TOOL_NAMES as w,FETCH_TOOL_NAME as N}from"../codemode/constants.js";import{buildCodeModeInstructions as H,buildExecuteDescription as I}from"../codemode/prompts.js";import{toToolListEntries as U}from"../codemode/build-tool-list.js";import{composeExecuteAnnotations as F,getActiveCapabilities as P}from"../codemode/capabilities/index.js";import{describeToolsSchema as R,describeTools as z}from"../codemode/tools/describe-tools.js";import{availableSandboxTools as W}from"../utils/available-sandbox-tools.js";import{toRegisterToolConfig as A}from"../utils/tool-registration.js";import{createMcpServer as X,createToolDispatch as Y,extractSerializableContext as $}from"./mcp-server.js";function S(s,t){const o=t.schema;if(C(s))return o;const{sessionHandle:f,...p}=o.properties;return{...o,properties:p}}function j(s){return Object.fromEntries(s.map(t=>[t.name,t.schema]))}async function se({name:s,tools:t,context:o,skills:f=[],getKv:p}){const n=$(o),r=o.mcpMode==="code",c=r?P(o):[],T=c.some(e=>e.id===N),m=r?await W(t.filter(e=>!w.has(e.name)),n):[],b=U(m,c),O=r&&L(o),l=X(s,r?H(T,b):void 0),E={getClientCapabilities:()=>l.server.getClientCapabilities(),getKv:p},d=Y(r?{...n,sandboxToolSchemas:j(m)}:n,E),u=async e=>{try{return await M.exec(v,[{toolName:e,context:n}],{timeout:1e4})}catch(i){return g.error(`Failed to check MCP tool availability for "${e}": ${i instanceof Error?i.message:String(i)}`),!1}};if(r){const e=[{tool:{...h,description:I(T,b),schema:S(o,h),annotations:F(c)},callback:d(D)},{tool:R(m,c),callback:z(m,u,c,o)}],i=t.find(a=>a.name===k);if(i&&C(o)&&e.push({tool:i,callback:d(i.name)}),O){const a=x(o);e.push({tool:{...a,schema:S(o,a)},callback:y(n,E)})}for(const{tool:a,callback:_}of e)l.registerTool(a.name,A(a),_)}else await Promise.all(t.map(async e=>{const i=l.registerTool(e.name,A(e),d(e.name));await u(e.name)||i.disable()}));for(const e of f)l.registerResource(e.slug,e.uri,{title:e.name,description:e.description,mimeType:"text/markdown"},async()=>({contents:[{uri:e.uri,mimeType:"text/markdown",text:e.content}]}));return l}export{se as createDocsMcpServer};
@@ -1,5 +1,5 @@
1
- import{McpServer as j}from"@modelcontextprotocol/server";import{logger as b}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as D,MCP_TOOL_WORKER_KEY as F}from"../../../workers/mcp-tool-worker-pool.js";import{secretStore as K}from"../gateway-mcp/secret-store.js";import{readAuthRequiredMeta as L,stripAuthRequiredMeta as M,upstreamAuthKey as S}from"../gateway-mcp/upstream-auth.js";import{buildCredentialsToolHint as H,buildSchemeChoiceHint as B,buildUpstreamCredentialFallback as q,buildUpstreamCredentialInputRequired as P,isCredentialElicitationDeclined as $,schemeLabelOf as x}from"../gateway-mcp/elicitation.js";import{DEFAULT_SCHEME_NAME as T,resolveUpstreamApiAuth as N,schemeChoicesOf as v}from"../gateway-mcp/upstream-auth-scheme.js";import{MISSING_SESSION_HANDLE_MESSAGE as G,resolveSecretSubject as V}from"../gateway-mcp/subject.js";const W=6e4,E=new Map;function Y(e,t){const r=E.get(e);if(r)return r;const n=t().finally(()=>{E.delete(e)});return E.set(e,n),n}function pe(e,t){return new j({name:e,version:new Date().toISOString().slice(0,10)},{capabilities:{logging:{}},...t?{instructions:t}:{}})}function de(e,t){return r=>async(n,s)=>{b.info(`MCP tool called: ${r}`);const i=e.elicitationEnabled??!1,c=s.mcpReq.envelope!==void 0,a=i?V(e.user,n.sessionHandle):{kind:"anonymous"},o=a.kind==="resolved"?a.subject:void 0;if(a.kind==="invalid")return{content:[{type:"text",text:a.message}],isError:!0};const p=async()=>{if(!(!i||!o||!t?.getKv))try{const m=await t.getKv();return await K.getSecretsForSubject(m,o)}catch(m){b.warn(`gateway mcp secret store error, continuing unauthenticated: ${String(m)}`);return}};let u;const l=async()=>{u=await p();const m={toolName:r,args:n,context:{...e,upstreamSecrets:u},extra:re(s)};return await D.exec(F,[m],{timeout:W})};let d=await l();const f=L(d);if(f.length>0&&i&&!o)return M({...d,content:[{type:"text",text:G}],isError:!0});if(f.length>0&&i&&o&&t?.getKv){b.info(`gateway mcp credentials prompt: era=${c?"2026-07-28":"2025"} clientElicitation=${Q(t)}`);const m=await t.getKv(),h=await X(e,f),k=f.map(_=>Z(_,h)),y=z(u),g=c?await ee(e,s,k,o,m,y,h,t):await te(e,k,o,m,y,h);switch(g.kind){case"inputRequired":return g.result;case"retry":d=await l();break;case"prependText":d={...d,content:[{type:"text",text:g.text},...d.content],isError:!0};break;case"none":break}}return M(d)}}function J(e){return!!e?.getClientCapabilities()?.elicitation?.url}function Q(e){const t=e?.getClientCapabilities()?.elicitation;if(!t)return"none";const r=[t.form?"form":void 0,t.url?"url":void 0].filter(Boolean);return r.length>0?r.join("+"):"none"}async function X(e,t){const r=new Map;for(const n of new Set(t.map(s=>s.api)))r.set(n,await N(e,n));return r}function Z(e,t){const r=t.get(e.api);if(!r)return{...e,scheme:e.scheme??T};const n=e.scheme&&r.schemes[e.scheme]?e.scheme:r.defaultScheme;return{...e,scheme:n}}function z(e){const t=new Set;for(const[r,n]of Object.entries(e??{}))for(const s of Object.keys(n))t.add(S({api:r,scheme:s}));return t}function R(e,t){return e.status===401&&!t.has(S(e))}function A(e,t){const r=t.get(e.api),n=e.sentScheme??e.scheme;return r&&n?x(r.schemes,n):void 0}function I(e,t){const r=t.get(e.api);return!r||!e.schemes?.length?[]:v(r,e.schemes)}function C(e,t){return I(e,t).length>1}function w(e,t){return e.map(r=>H(r,A(r,t))).join(`
1
+ import{McpServer as _}from"@modelcontextprotocol/server";import{logger as S}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as j,MCP_TOOL_WORKER_KEY as D}from"../../../workers/mcp-tool-worker-pool.js";import{secretStore as F}from"../gateway-mcp/secret-store.js";import{readAuthRequiredMeta as K,stripAuthRequiredMeta as y,upstreamAuthKey as b}from"../gateway-mcp/upstream-auth.js";import{buildCredentialsToolHint as L,buildSchemeChoiceHint as H,buildUpstreamCredentialFallback as T,buildUpstreamCredentialInputRequired as P,dedupeElicitation as $,isCredentialElicitationDeclined as B,isStatelessRequest as x,schemeLabelOf as N,supportsUrlElicitation as v}from"../gateway-mcp/elicitation.js";import{DEFAULT_SCHEME_NAME as q,resolveUpstreamApiAuth as G,schemeChoicesOf as V}from"../gateway-mcp/upstream-auth-scheme.js";import{MISSING_SESSION_HANDLE_MESSAGE as W,resolveSecretSubject as Y}from"../gateway-mcp/subject.js";const J=6e4;function pe(e,t){return new _({name:e,version:new Date().toISOString().slice(0,10)},{capabilities:{logging:{}},...t?{instructions:t}:{}})}function de(e,t){return r=>async(n,s)=>{S.info(`MCP tool called: ${r}`);const i=e.elicitationEnabled??!1,c=x(s.mcpReq),a=i?Y(e.user,n.sessionHandle):{kind:"anonymous"},o=a.kind==="resolved"?a.subject:void 0;if(a.kind==="invalid")return{content:[{type:"text",text:a.message}],isError:!0};const p=async()=>{if(!(!i||!o||!t?.getKv))try{const m=await t.getKv();return await F.getSecretsForSubject(m,o)}catch(m){S.warn(`gateway mcp secret store error, continuing unauthenticated: ${String(m)}`);return}};let u;const l=async()=>{u=await p();const m={toolName:r,args:n,context:{...e,upstreamSecrets:u},extra:re(s)};return await j.exec(D,[m],{timeout:J})};let d=await l();const f=K(d);if(f.length>0&&i&&!o)return y({...d,content:[{type:"text",text:W}],isError:!0});if(f.length>0&&i&&o&&t?.getKv){S.info(`gateway mcp credentials prompt: era=${c?"2026-07-28":"2025"} clientElicitation=${Q(t)}`);const m=await t.getKv(),h=await X(e,f),w=f.map(O=>Z(O,h)),E=z(u),g=c?await ee(e,s,w,o,m,E,h,t):await te(e,w,o,m,E,h);switch(g.kind){case"inputRequired":return g.result;case"retry":d=await l();break;case"prependText":d={...d,content:[{type:"text",text:g.text},...d.content],isError:!0};break;case"none":break}}return y(d)}}function Q(e){const t=e?.getClientCapabilities()?.elicitation;if(!t)return"none";const r=[t.form?"form":void 0,t.url?"url":void 0].filter(Boolean);return r.length>0?r.join("+"):"none"}async function X(e,t){const r=new Map;for(const n of new Set(t.map(s=>s.api)))r.set(n,await G(e,n));return r}function Z(e,t){const r=t.get(e.api);if(!r)return{...e,scheme:e.scheme??q};const n=e.scheme&&r.schemes[e.scheme]?e.scheme:r.defaultScheme;return{...e,scheme:n}}function z(e){const t=new Set;for(const[r,n]of Object.entries(e??{}))for(const s of Object.keys(n))t.add(b({api:r,scheme:s}));return t}function R(e,t){return e.status===401&&!t.has(b(e))}function M(e,t){const r=t.get(e.api),n=e.sentScheme??e.scheme;return r&&n?N(r.schemes,n):void 0}function A(e,t){const r=t.get(e.api);return!r||!e.schemes?.length?[]:V(r,e.schemes)}function I(e,t){return A(e,t).length>1}function k(e,t){return e.map(r=>L(r,M(r,t))).join(`
2
2
 
3
- `)}function U(e,t,r){const n=e.map(s=>B(s,I(s,r)));return t.length>0&&n.push(w(t,r)),n.join(`
3
+ `)}function C(e,t,r){const n=e.map(s=>H(s,A(s,r)));return t.length>0&&n.push(k(t,r)),n.join(`
4
4
 
5
- `)}function O(e,t,r,n,s){const[i,...c]=t,a=s.get(i.api),o=i.scheme??a?.defaultScheme??T,p=A(i,s);return{subject:r,baseUrl:e.baseUrl??"",target:{api:i.api,name:i.name,scheme:o,...p?{schemeLabel:p}:{}},auth:a?.schemes[o]??{kind:"raw"},...a?{apiAuth:a}:{},kv:n,hasExistingSecret:!1,reason:{kind:"authFailure",status:i.status,...i.detail?{detail:i.detail}:{},otherApiNames:c.map(u=>u.name)}}}async function ee(e,t,r,n,s,i,c,a){if($(t.mcpReq.inputResponses))return{kind:"none"};const o=r.filter(l=>R(l,i));if(o.length===0)return{kind:"prependText",text:w(r,c)};const p=o.filter(l=>C(l,c));if(p.length>0){const l=r.filter(d=>!p.includes(d));return{kind:"prependText",text:U(p,l,c)}}const u=O(e,o,n,s,c);return J(a)?{kind:"inputRequired",result:await P(u)}:{kind:"prependText",text:await q(u)}}async function te(e,t,r,n,s,i){const c=t.filter(u=>R(u,s));if(c.length===0)return{kind:"prependText",text:w(t,i)};const a=c.filter(u=>C(u,i));if(a.length>0){const u=t.filter(l=>!a.includes(l));return{kind:"prependText",text:U(a,u,i)}}const o=O(e,c,r,n,i);return{kind:"prependText",text:await Y(`${r}:${S(c[0])}`,()=>q(o))}}function re(e){return{sessionId:e.sessionId,authInfo:e.http?.authInfo,requestId:e.mcpReq.id,_meta:e.mcpReq._meta}}function me(e){return{user:e.user,config:e.config,outdir:e.outdir,baseUrl:e.baseUrl,params:e.params,query:e.query,cookies:e.cookies,apiDescriptionsMap:e.apiDescriptionsMap,graphqlDescriptions:e.graphqlDescriptions,products:e.products,accessToken:e.accessToken,metadata:e.metadata,upstreamAuthorization:e.upstreamAuthorization,mcpMode:e.mcpMode,elicitationEnabled:e.elicitationEnabled,gatewayFetchBudgetPerExec:e.gatewayFetchBudgetPerExec,clientIp:e.clientIp,client:e.client,clientVersion:e.clientVersion,upstreamSecrets:e.upstreamSecrets,searchIgnoredRoutes:e.searchIgnoredRoutes,internalBaseUrl:e.internalBaseUrl,fs:void 0}}export{pe as createMcpServer,de as createToolDispatch,me as extractSerializableContext};
5
+ `)}function U(e,t,r,n,s){const[i,...c]=t,a=s.get(i.api),o=i.scheme??a?.defaultScheme??q,p=M(i,s);return{subject:r,baseUrl:e.baseUrl??"",target:{api:i.api,name:i.name,scheme:o,...p?{schemeLabel:p}:{}},auth:a?.schemes[o]??{kind:"raw"},...a?{apiAuth:a}:{},kv:n,hasExistingSecret:!1,reason:{kind:"authFailure",status:i.status,...i.detail?{detail:i.detail}:{},otherApiNames:c.map(u=>u.name)}}}async function ee(e,t,r,n,s,i,c,a){if(B(t.mcpReq.inputResponses))return{kind:"none"};const o=r.filter(l=>R(l,i));if(o.length===0)return{kind:"prependText",text:k(r,c)};const p=o.filter(l=>I(l,c));if(p.length>0){const l=r.filter(d=>!p.includes(d));return{kind:"prependText",text:C(p,l,c)}}const u=U(e,o,n,s,c);return v(a?.getClientCapabilities())?{kind:"inputRequired",result:await P(u)}:{kind:"prependText",text:await T(u)}}async function te(e,t,r,n,s,i){const c=t.filter(u=>R(u,s));if(c.length===0)return{kind:"prependText",text:k(t,i)};const a=c.filter(u=>I(u,i));if(a.length>0){const u=t.filter(l=>!a.includes(l));return{kind:"prependText",text:C(a,u,i)}}const o=U(e,c,r,n,i);return{kind:"prependText",text:await $(`${r}:${b(c[0])}`,()=>T(o))}}function re(e){return{sessionId:e.sessionId,authInfo:e.http?.authInfo,requestId:e.mcpReq.id,_meta:e.mcpReq._meta}}function me(e){return{user:e.user,config:e.config,outdir:e.outdir,baseUrl:e.baseUrl,params:e.params,query:e.query,cookies:e.cookies,apiDescriptionsMap:e.apiDescriptionsMap,graphqlDescriptions:e.graphqlDescriptions,products:e.products,accessToken:e.accessToken,metadata:e.metadata,upstreamAuthorization:e.upstreamAuthorization,mcpMode:e.mcpMode,elicitationEnabled:e.elicitationEnabled,gatewayFetchBudgetPerExec:e.gatewayFetchBudgetPerExec,clientIp:e.clientIp,client:e.client,clientVersion:e.clientVersion,upstreamSecrets:e.upstreamSecrets,searchIgnoredRoutes:e.searchIgnoredRoutes,internalBaseUrl:e.internalBaseUrl,sandboxToolSchemas:e.sandboxToolSchemas,fs:void 0}}export{pe as createMcpServer,de as createToolDispatch,me as extractSerializableContext};
@@ -107,6 +107,7 @@ export type McpToolContext = Omit<ApiFunctionsContext, 'telemetry' | 'getKv' | k
107
107
  upstreamSecrets?: UpstreamSecrets;
108
108
  searchIgnoredRoutes?: string[];
109
109
  internalBaseUrl?: string;
110
+ sandboxToolSchemas?: Record<string, Record<string, unknown>>;
110
111
  fs?: McpToolFileSystem;
111
112
  };
112
113
  export type McpToolHandler<TArgs extends ToolArgs = ToolArgs> = (args: TArgs, context: McpToolContext, extra: McpToolExtra) => Promise<McpToolWorkerResponse | McpToolJsonValue>;
@@ -1 +1 @@
1
- import{logger as i}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as a,MCP_TOOL_AVAILABILITY_KEY as m}from"../../../workers/mcp-tool-worker-pool.js";async function p(o,t){if(o.length===0)return o;const l=o.map(r=>r.name);let e;try{e=await a.exec(m,[{toolNames:l,context:t}],{timeout:1e4})}catch(r){return i.error(`Failed to resolve MCP tool availability: ${r instanceof Error?r.message:String(r)}`),o}return!e||typeof e!="object"?o:o.filter(r=>e[r.name]!==!1)}export{p as availableSandboxTools};
1
+ import{logger as a}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as n,MCP_TOOL_AVAILABILITY_KEY as m}from"../../../workers/mcp-tool-worker-pool.js";async function p(t,l){if(t.length===0)return t;const e=t.map(o=>o.name);let r;try{r=await n.exec(m,[{toolNames:e,context:l}],{timeout:1e4})}catch(o){return i(t,o instanceof Error?o.message:String(o))}return!r||typeof r!="object"?i(t,"the worker returned no availability map"):t.filter(o=>r[o.name]!==!1)}function i(t,l){const e=t.filter(r=>r.hasAvailabilityGate);return e.length===0?t:(a.warn(`MCP tool availability is unknown (${l}); the sandbox tool list drops the gated tools: ${e.map(r=>r.name).join(", ")}.`),t.filter(r=>!r.hasAvailabilityGate))}export{p as availableSandboxTools};
@@ -1 +1 @@
1
- import{telemetry as h}from"../../../telemetry/index.js";import{McpServerType as c}from"../constants.js";import{EXECUTE_TOOL_NAME as w}from"../codemode/constants.js";import{isPlainObject as f}from"../../../../utils/guards/is-plain-object.js";import{logMcpToolCallAudit as g,reportMcpToolCalled as _,reportMcpToolError as u}from"./mcp-tool-telemetry.js";import{attachToolFileSystem as E}from"./tool-file-system.js";import{importMcpToolHandlers as S}from"./import-mcp-tool-handlers.js";function A(e){return e.content.map(t=>t.type==="text"?t.text:"")}async function J(e){h.initialize();const{toolName:t,args:o,extra:s}=e,r=E(e.context),n=r?.mcpMode??"tools",a={client:r?.client,clientVersion:r?.clientVersion},d=performance.now();try{const i=await M(t);if(!i)throw new Error(`MCP tool "${t}" is not registered or its module does not export a handler for "${t}". Expected \`export default { '${t}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`);const C=typeof i=="function"?i:i.execute,l=P(t,await C(o,r,s),n),m=Math.round(performance.now()-d),{errorClass:y}=l;delete l.errorClass;const p=l.isError?y??(t===w?"sandbox_error":"tool_error"):void 0,v=t===w&&y==="tool_error",x=A(l),T=x.join("");return g({tool:t,mode:n,serverType:c.Docs,args:o,result:T,errorClass:p,...a}),p?v||u({tool:t,message:x.join(" "),mode:n,serverType:c.Docs,durationMs:m,errorClass:p,...a}):_({tool:t,mode:n,serverType:c.Docs,durationMs:m,outputLength:T.length,...a}),l}catch(i){throw g({tool:t,mode:n,serverType:c.Docs,args:o,errorClass:"server_error",...a}),u({tool:t,message:i instanceof Error?i.message:String(i),mode:n,serverType:c.Docs,durationMs:Math.round(performance.now()-d),stack:i instanceof Error&&i.stack||"",errorClass:"server_error",...a}),i}}function b(e){return"execute"in e&&typeof e.execute=="function"&&"description"in e&&typeof e.description=="string"}async function M(e){const t=(await S())[e];if(!t)return;const{default:o}=await t();return O(o,e)}function O(e,t){return b(e)?e:e[t]}function P(e,t,o){if(L(t))return t;if(typeof t=="string")return{content:[{type:"text",text:t}]};let s;try{s=JSON.stringify(t)}catch(n){throw new Error(`MCP tool "${e}" returned a value that cannot be serialized to JSON: `+(n instanceof Error?n.message:String(n)))}if(s===void 0)throw new Error(`MCP tool "${e}" returned an invalid result.`);const r=o==="code"?JSON.parse(s):void 0;return f(r)?{content:[{type:"text",text:s}],structuredContent:r}:{content:[{type:"text",text:s}]}}const k=new Set(["text","image","audio","resource","resource_link"]);function L(e){if(!f(e))return!1;const{content:t}=e;return Array.isArray(t)&&t.every(o=>f(o)&&k.has(o.type))}async function j(e){h.initialize();const{toolName:t}=e,o=E(e.context),s=performance.now();try{const r=await M(t);return r?typeof r=="object"&&typeof r.isAvailable=="function"?await r.isAvailable(o):!0:!1}catch(r){throw u({tool:t,message:"Failed to check if MCP tool is available: "+(r instanceof Error?r.message:String(r)),mode:o?.mcpMode??"tools",serverType:c.Docs,durationMs:Math.round(performance.now()-s),stack:r instanceof Error&&r.stack||"",errorClass:"server_error",client:o?.client,clientVersion:o?.clientVersion}),r}}async function F(e){const{toolNames:t,context:o}=e,s=await Promise.all(t.map(r=>j({toolName:r,context:o}).catch(()=>!1)));return Object.fromEntries(t.map((r,n)=>[r,s[n]]))}export{J as executeMcpTool,j as isMcpToolAvailable,F as mcpToolAvailability,O as resolveToolHandler};
1
+ import{telemetry as h}from"../../../telemetry/index.js";import{McpServerType as c}from"../constants.js";import{EXECUTE_TOOL_NAME as w}from"../codemode/constants.js";import{isPlainObject as p}from"../../../../utils/guards/is-plain-object.js";import{logMcpToolCallAudit as g,reportMcpToolCalled as _,reportMcpToolError as u}from"./mcp-tool-telemetry.js";import{attachToolFileSystem as E}from"./tool-file-system.js";import{importMcpToolHandlers as b}from"./import-mcp-tool-handlers.js";function A(t){return t.content.map(e=>e.type==="text"?e.text:"")}async function D(t){h.initialize();const{toolName:e,args:o,extra:s}=t,r=E(t.context),n=r?.mcpMode??"tools",a={client:r?.client,clientVersion:r?.clientVersion},d=performance.now();try{const i=await M(e);if(!i)throw new Error(`MCP tool "${e}" is not registered or its module does not export a handler for "${e}". Expected \`export default { '${e}': handler }\` or a single tool definition with \`description\` and \`execute\` as the default export.`);const C=typeof i=="function"?i:i.execute,l=P(e,await C(o,r,s),n),m=Math.round(performance.now()-d),{errorClass:y}=l;delete l.errorClass;const f=l.isError?y??(e===w?"sandbox_error":"tool_error"):void 0,v=e===w&&y==="tool_error",x=A(l),T=x.join("");return g({tool:e,mode:n,serverType:c.Docs,args:o,result:T,errorClass:f,...a}),f?v||u({tool:e,message:x.join(" "),mode:n,serverType:c.Docs,durationMs:m,errorClass:f,...a}):_({tool:e,mode:n,serverType:c.Docs,durationMs:m,outputLength:T.length,...a}),l}catch(i){throw g({tool:e,mode:n,serverType:c.Docs,args:o,errorClass:"server_error",...a}),u({tool:e,message:i instanceof Error?i.message:String(i),mode:n,serverType:c.Docs,durationMs:Math.round(performance.now()-d),stack:i instanceof Error&&i.stack||"",errorClass:"server_error",...a}),i}}function S(t){return"execute"in t&&typeof t.execute=="function"&&"description"in t&&typeof t.description=="string"}async function M(t){const e=(await b())[t];if(!e)return;const{default:o}=await e();return O(o,t)}function O(t,e){return S(t)?t:t[e]}function P(t,e,o){if(L(e))return e;if(typeof e=="string")return{content:[{type:"text",text:e}]};let s;try{s=JSON.stringify(e)}catch(n){throw new Error(`MCP tool "${t}" returned a value that cannot be serialized to JSON: `+(n instanceof Error?n.message:String(n)))}if(s===void 0)throw new Error(`MCP tool "${t}" returned an invalid result.`);const r=o==="code"?JSON.parse(s):void 0;return p(r)?{content:[{type:"text",text:s}],structuredContent:r}:{content:[{type:"text",text:s}]}}const k=new Set(["text","image","audio","resource","resource_link"]);function L(t){if(!p(t))return!1;const{content:e}=t;return Array.isArray(e)&&e.every(o=>p(o)&&k.has(o.type))}async function j(t){h.initialize();const{toolName:e}=t;if(N(e,t.context.metadata))return!1;const o=E(t.context),s=performance.now();try{const r=await M(e);return r?typeof r=="object"&&typeof r.isAvailable=="function"?await r.isAvailable(o):!0:!1}catch(r){throw u({tool:e,message:"Failed to check if MCP tool is available: "+(r instanceof Error?r.message:String(r)),mode:o?.mcpMode??"tools",serverType:c.Docs,durationMs:Math.round(performance.now()-s),stack:r instanceof Error&&r.stack||"",errorClass:"server_error",client:o?.client,clientVersion:o?.clientVersion}),r}}function N(t,e){const o=e?.disabledTools;return Array.isArray(o)&&o.includes(t)}async function F(t){const{toolNames:e,context:o}=t,s=await Promise.all(e.map(r=>j({toolName:r,context:o}).catch(()=>!1)));return Object.fromEntries(e.map((r,n)=>[r,s[n]]))}export{D as executeMcpTool,j as isMcpToolAvailable,F as mcpToolAvailability,O as resolveToolHandler};
@@ -1 +1 @@
1
- import p from"node:path";import{existsSync as O}from"node:fs";import{writeFile as h,access as y,rm as v,constants as b}from"fs/promises";import{REDOCLY_TEAMS_RBAC as N}from"@redocly/config";import{DEFAULT_LOCALE_PLACEHOLDER as P}from"../../../../constants/common.js";import{AI_INDEX_EXPORT_FOLDER as X}from"../../../constants/plugins/search.js";import{LLMS_TXT_FILE_NAME as $}from"../../../constants/common.js";import{envConfig as j}from"../../../config/env-config.js";import{logger as n}from"../../../tools/notifiers/logger.js";import{shaHexShort as B}from"../../../utils/crypto/sha-hex-short.js";import{promiseMapLimit as D}from"../../../utils/async/promise-map-limit.js";import{getLlmsTxtMdPathBySlug as G}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{validateLLMsTxtConfig as H,generateLLMsTxt as k}from"../llmstxt/index.js";import{buildPageLlmsTxtMd as J}from"../llmstxt/build-page-llms-txt-md.js";import{getLlmsTxtExcludeMatcher as K}from"../llmstxt/get-llms-txt-exclude-matcher.js";import{isIncludedInLlmsTxt as U}from"../llmstxt/is-included-in-llms-txt.js";import{getRouteStaticData as V}from"../../../utils/get-route-static-data.js";import{getRouteAiDocumentsStore as W}from"../../../utils/get-route-ai-documents-store.js";import{ensureDir as R}from"../../../utils/fs.js";import{extractTeamsFromScopeItems as Y,getRbacTeamsListForResource as q}from"../../../utils/rbac.js";const _=20,S="llms.txt:";async function ht(t,m,{embeddingsEnabled:e,writeLlmstxtFiles:l}){const c=p.join(t.outdir,$);if(!l){try{await y(c,b.W_OK),await v(c)}catch{}if(!e)return}e&&n.info("Preparing semantic documents..."),l&&n.info(`${S} Generating llms.txt files...`);const g=n.startTiming(),r=n.startTiming(),s=t.getGlobalConfig("seo"),f=s?.llmstxt,T=p.resolve(t.outdir,X),u=t.getConfig(),A=u.access?.rbac??{},M=t.getAllRoutes(),C=u?.l10n?.defaultLocale||u?.i18n?.defaultLocale||P,E=K(s),L=[];if(await D(M,_,async o=>{if(o.excludeFromSearch)return;const w=await V(o,t),x=await W(o,w,m,t);if(x){if(l)for(const i of await x.getLLMsTxts()){if(E(i.fsPath))continue;const d=G(i.slug),a=p.join(t.outdir,d);R(a),await h(a,J(i,s)),U(i,o,u)&&L.push(i)}if(e&&j.isBuildMode){const i=await x.getSearchDocuments();if(!i.length)return;const d=z(o,A),a=o.versions?.find(({active:F})=>F),I=a&&{folder:a.folderId,label:a.label,default:a.default};await Q(i,o.fsPath,d,T,C,I)}}}),e&&n.infoTime(r,"Semantic search documents prepared"),L.length)try{H(f);const o=await k(L,f,{title:s?.title,description:s?.description},m);R(c),await h(c,o),n.infoTime(g,`${S} files generated`)}catch(o){n.error(`${S} Failed to generate llms.txt file. ${o.message}`)}}function z(t,m){const e=Y(t?.[N]);return e?.length?e:q(t,m)}async function Q(t,m,e,l,c,g){await D(t,_,async r=>{const s=`${B(m+r.content)}.json`,f=R(p.join(l,s)),T=r.locale===P?c:r.locale;O(f)||await h(f,JSON.stringify({...r,rbacTeams:r.rbacTeams??e??[],version:g,locale:T}),"utf-8")})}export{ht as prepareSemanticDocuments};
1
+ import p from"node:path";import{existsSync as O}from"node:fs";import{writeFile as h,access as y,rm as v,constants as b}from"fs/promises";import{REDOCLY_TEAMS_RBAC as N}from"@redocly/config";import{DEFAULT_LOCALE_PLACEHOLDER as P}from"../../../../constants/common.js";import{AI_INDEX_EXPORT_FOLDER as X}from"../../../constants/plugins/search.js";import{LLMS_TXT_FILE_NAME as $}from"../../../constants/common.js";import{envConfig as j}from"../../../config/env-config.js";import{logger as n}from"../../../tools/notifiers/logger.js";import{shaHexShort as B}from"../../../utils/crypto/sha-hex-short.js";import{promiseMapLimit as D}from"../../../utils/async/promise-map-limit.js";import{getLlmsTxtMdPathBySlug as G}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{validateLLMsTxtConfig as U,generateLLMsTxt as H}from"../llmstxt/index.js";import{buildPageLlmsTxtMd as k}from"../llmstxt/build-page-llms-txt-md.js";import{getLlmsTxtExcludeMatcher as J}from"../llmstxt/get-llms-txt-exclude-matcher.js";import{isIncludedInLlmsTxt as K}from"../llmstxt/is-included-in-llms-txt.js";import{getRouteStaticData as V}from"../../../utils/get-route-static-data.js";import{getRouteAiDocumentsStore as W}from"../../../utils/get-route-ai-documents-store.js";import{ensureDir as R}from"../../../utils/fs.js";import{extractTeamsFromScopeItems as Y,getRbacTeamsListForResource as q}from"../../../utils/rbac.js";const _=20,S="llms.txt:";async function ht(t,m,{embeddingsEnabled:e,writeLlmstxtFiles:l}){const c=p.join(t.outdir,$);if(!l){try{await y(c,b.W_OK),await v(c)}catch{}if(!e)return}e&&n.info("Preparing semantic documents..."),l&&n.info(`${S} Generating llms.txt files...`);const g=n.startTiming(),s=n.startTiming(),i=t.getGlobalConfig("seo"),f=i?.llmstxt,T=p.resolve(t.outdir,X),u=t.getConfig(),A=u.access?.rbac??{},M=t.getAllRoutes(),C=u?.l10n?.defaultLocale||u?.i18n?.defaultLocale||P,E=J(i),L=[];if(await D(M,_,async o=>{if(o.excludeFromSearch)return;const w=await V(o,t),x=await W(o,w,m,t);if(x){if(l)for(const r of await x.getLLMsTxts()){if(E(r.fsPath))continue;const d=G(r.slug),a=p.join(t.outdir,d);R(a),await h(a,k(r,i)),K(r,o,u)&&L.push(r)}if(e&&j.isBuildMode){const r=await x.getSearchDocuments();if(!r.length)return;const d=z(o,A),a=o.versions?.find(({active:F})=>F),I=a&&{folder:a.folderId,label:a.label,default:a.default};await Q(r,o.fsPath,d,T,C,I)}}}),e&&n.infoTime(s,"Semantic search documents prepared"),L.length)try{U(f);const o=await H(L,f,{title:i?.title,description:i?.description,siteUrl:i?.siteUrl},m);R(c),await h(c,o),n.infoTime(g,`${S} files generated`)}catch(o){n.error(`${S} Failed to generate llms.txt file. ${o.message}`)}}function z(t,m){const e=Y(t?.[N]);return e?.length?e:q(t,m)}async function Q(t,m,e,l,c,g){await D(t,_,async s=>{const i=`${B(m+s.content)}.json`,f=R(p.join(l,i)),T=s.locale===P?c:s.locale;O(f)||await h(f,JSON.stringify({...s,rbacTeams:s.rbacTeams??e??[],version:g,locale:T}),"utf-8")})}export{ht as prepareSemanticDocuments};
@@ -1 +1 @@
1
- import{readFile as R,readdir as E,appendFile as F}from"node:fs/promises";import m from"node:path";import{existsSync as I}from"node:fs";import{SEARCH_GROUP_FACET_FIELD as S,SEARCH_PRODUCT_FIELD as w,SEARCH_VERSION_FIELD as C}from"../../../../../constants/common.js";import{SEARCH_INDEX_FIELDS as $,SEARCH_DATA_EXPORT_FOLDER as g,SEARCH_MAX_INMEMORY_DOCUMENTS_COUNT as O}from"../../../../constants/plugins/search.js";import{telemetryTraceStep as v}from"../../../../telemetry/helpers/trace-step.js";import{envConfig as j}from"../../../../config/env-config.js";import{ensureDir as h}from"../../../../utils/index.js";import{FlexSearchIndex as N}from"./search-index.js";class B{#e=new Map;#s;#t=0;async initIndexSchema(e){this.#s={document:{id:"id",tag:"tags",index:$},worker:!1,tokenize:"forward",context:{depth:2,resolution:9}}}#o(e,o){const i=this.#e.get(e);if(i)return i.find(t=>t.id===o)}#i(e,o){let i=this.#o(e,o);return i||(i=new N(o,this.#s),this.#e.set(e,[...this.#e.get(e)??[],i])),i}async addDocuments(e,o){if(e.length){const{group:i,locale:t,outDir:c}=o,n=this.#i(t,i);for(const r of e)n.add(r),j.isBuildMode&&(this.#t++,this.#t>=O&&await this.exportDocuments(c))}}getIndexesSize(){return this.#e.size}async search(e,o,i){return await v("com.redocly.search.performed",async t=>{t?.setAttribute("id","searchQueryId"),t?.setAttribute("object","searchQuery"),t?.setAttribute("uri","urn:redocly:realm:api:searchQuery:searchQueryId");const{query:c,locale:n,filter:r,loadMore:a}=e,l=this.#e.get(n)??[];let f=[],d="",x=["v:default"];if(t?.setAttribute("locale",n),r)for(const s of r)s.field===S?f=[...f,...s.values]:s.field===w?d=`p:${s.values[0]}`:s.field===C&&s.values.length&&s.values.length===2&&(x=[...x,`v:${s.values[0]}:${s.values[1]}`]);const D={auth:o,query:c,offset:0,SEARCH_GROUP_FACET_FIELD:S,product:d,versions:x},p=[];let u={facets:{},documents:{}};if(a){const s=this.#o(n,a.groupKey);s&&p.push(s.search({...D,offset:a.offset}))}else for(const s of l)f&&f.length?f.includes(s.id)&&p.push(s.search(D)):p.push(s.search(D));const A=await Promise.all(p);for(const s of A){u.documents={...u.documents,...s.documents};for(const[y,_]of Object.entries(s.facets))u.facets[y]?u.facets[y]=[...u.facets[y],..._]:u.facets[y]=_}return u})}async exportDocuments(e){const o='{"documents":[',i=h(m.join(e,g));for(const[t,c]of this.#e){const n=h(m.join(i,t));for(const r of c){const a=Array.from(r.documents);if(a.length===0)continue;const l=h(m.join(n,`${r.id}.json`)),f=!I(l),d=JSON.stringify(a).substring(1).slice(0,-1),x=f?o+d:","+d;await F(l,x,{encoding:"utf8"}),r.clearDocuments()}}this.#t=0}async exportIndexes(e){const o=h(m.join(e,g));for(const[i,t]of this.#e){const c=h(m.join(o,i));for(const n of t){const r=h(m.join(c,`${n.id}.json`)),a={};await n.export((f,d)=>{a[f]=d});const l=`],"index":${JSON.stringify(a)}}`;await F(r,l,{encoding:"utf8"})}}this.#e.clear()}async import(e){const o=`${e}/${g}`;if(!I(o))return;const i=await E(o);for(const t of i){const c=await E(`${o}/${t}`);for(const n of c){const r=`${o}/${t}/${n}`,a=JSON.parse(await R(r,"utf-8")),l=m.parse(n).name;await this.#i(t,l).import(a)}}}countFacets(e,o,i){const t={};for(const[c,n]of i)t[c]=n.values.map(r=>({value:r,count:0,isCounterVisible:!1}));return t}cleanupFacetValues(e){}}export{B as FlexSearch};
1
+ import{readFile as R,readdir as F,appendFile as I}from"node:fs/promises";import h from"node:path";import{existsSync as C}from"node:fs";import{SEARCH_GROUP_FACET_FIELD as S,SEARCH_PRODUCT_FIELD as v,SEARCH_VERSION_FIELD as w}from"../../../../../constants/common.js";import{SEARCH_INDEX_FIELDS as $,SEARCH_DATA_EXPORT_FOLDER as D,SEARCH_MAX_INMEMORY_DOCUMENTS_COUNT as O}from"../../../../constants/plugins/search.js";import{telemetryTraceStep as j}from"../../../../telemetry/helpers/trace-step.js";import{envConfig as N}from"../../../../config/env-config.js";import{ensureDir as m}from"../../../../utils/index.js";import{FlexSearchIndex as b}from"./search-index.js";class J{#e=new Map;#s;#t=0;async initIndexSchema(t){this.#s={document:{id:"id",tag:"tags",index:$},worker:!1,tokenize:"forward",context:{depth:2,resolution:9}}}#o(t,o){const i=this.#e.get(t);if(i)return i.find(s=>s.id===o)}#i(t,o){let i=this.#o(t,o);return i||(i=new b(o,this.#s),this.#e.set(t,[...this.#e.get(t)??[],i])),i}async addDocuments(t,o){if(t.length){const{group:i,locale:s,outDir:c}=o,n=this.#i(s,i);for(const r of t)n.add(r),N.isBuildMode&&(this.#t++,this.#t>=O&&await this.exportDocuments(c))}}getIndexesSize(){return this.#e.size}async search(t,o,i){return await j("com.redocly.search.performed",async s=>{s?.setAttribute("id","searchQueryId"),s?.setAttribute("object","searchQuery"),s?.setAttribute("uri","urn:redocly:realm:api:searchQuery:searchQueryId");const{query:c,locale:n,filter:r,loadMore:a}=t,l=this.#e.get(n)??[];let f=[],d="",x=["v:default"];if(s?.setAttribute("locale",n),r)for(const e of r)e.field===S?f=[...f,...e.values]:e.field===v?d=`p:${e.values[0]}`:e.field===w&&e.values.length&&e.values.length===2&&(x=[...x,`v:${e.values[0]}:${e.values[1]}`]);const g={auth:o,query:c,offset:0,SEARCH_GROUP_FACET_FIELD:S,product:d,versions:x},p=[];let u={facets:{},documents:{}};if(a){const e=this.#o(n,a.groupKey);e&&p.push(e.search({...g,offset:a.offset}))}else for(const e of l)f&&f.length?f.includes(e.id)&&p.push(e.search(g)):p.push(e.search(g));const _=await Promise.all(p),A=_.some(e=>e.hasCoveringHit);for(const e of _)if(!(A&&!e.hasCoveringHit)){u.documents={...u.documents,...e.documents};for(const[y,E]of Object.entries(e.facets))u.facets[y]?u.facets[y]=[...u.facets[y],...E]:u.facets[y]=E}return u})}async exportDocuments(t){const o='{"documents":[',i=m(h.join(t,D));for(const[s,c]of this.#e){const n=m(h.join(i,s));for(const r of c){const a=Array.from(r.documents);if(a.length===0)continue;const l=m(h.join(n,`${r.id}.json`)),f=!C(l),d=JSON.stringify(a).substring(1).slice(0,-1),x=f?o+d:","+d;await I(l,x,{encoding:"utf8"}),r.clearDocuments()}}this.#t=0}async exportIndexes(t){const o=m(h.join(t,D));for(const[i,s]of this.#e){const c=m(h.join(o,i));for(const n of s){const r=m(h.join(c,`${n.id}.json`)),a={};await n.export((f,d)=>{a[f]=d});const l=`],"index":${JSON.stringify(a)}}`;await I(r,l,{encoding:"utf8"})}}this.#e.clear()}async import(t){const o=`${t}/${D}`;if(!C(o))return;const i=await F(o);for(const s of i){const c=await F(`${o}/${s}`);for(const n of c){const r=`${o}/${s}/${n}`,a=JSON.parse(await R(r,"utf-8")),l=h.parse(n).name;await this.#i(s,l).import(a)}}}countFacets(t,o,i){const s={};for(const[c,n]of i)s[c]=n.values.map(r=>({value:r,count:0,isCounterVisible:!1}));return s}cleanupFacetValues(t){}}export{J as FlexSearch};
@@ -1,16 +1,20 @@
1
1
  import type { ExportHandler, IndexOptionsForDocumentSearch } from 'flexsearch';
2
- import type { FlexSearchData, SearchIndex, SearchParameters, SearchDocument } from '../../../../types';
2
+ import type { FlexSearchData, IndexedSearchDocument, SearchIndex, SearchParameters, SearchDocument } from '../../../../types';
3
3
  import type { SearchResponse } from '../../../../../types/index.js';
4
+ /** One group's results plus whether any of them holds every query word in a single value. */
5
+ export type IndexSearchResponse = SearchResponse & {
6
+ hasCoveringHit: boolean;
7
+ };
4
8
  export declare class FlexSearchIndex implements SearchIndex {
5
9
  #private;
6
10
  id: string;
7
11
  constructor(id: string, indexConfig: IndexOptionsForDocumentSearch<string>);
8
- get documents(): MapIterator<[number, SearchDocument]>;
12
+ get documents(): MapIterator<[number, IndexedSearchDocument]>;
9
13
  get documentsCount(): number;
10
14
  clearDocuments(): void;
11
- export(handler: ExportHandler<string | SearchDocument>): Promise<void>;
15
+ export(handler: ExportHandler<string | IndexedSearchDocument>): Promise<void>;
12
16
  import(searchData: FlexSearchData): Promise<void>;
13
17
  add(document: SearchDocument): void;
14
- search(params: SearchParameters): Promise<SearchResponse>;
18
+ search(params: SearchParameters): Promise<IndexSearchResponse>;
15
19
  }
16
20
  //# sourceMappingURL=search-index.d.ts.map
@@ -1 +1 @@
1
- import S from"flexsearch";import{REDOCLY_TEAMS_RBAC as I}from"@redocly/config";import{DISABLE_DEEP_LINK_IF_FIELDS_EXIST as w,SEARCH_LIMIT as y}from"../../../../constants/plugins/search.js";import{telemetryTraceStep as A}from"../../../../telemetry/helpers/trace-step.js";import{highlightTextForSearch as u}from"../../../../utils/search/highlight-text-for-search.js";class C{#e;#t=new Map;#s=1;id;constructor(e,t){this.id=e,this.#e=new S.Document(t)}get documents(){return this.#t.entries()}get documentsCount(){return this.#s}clearDocuments(){this.#t.clear()}async export(e){await this.#e.export(e)}async import(e){const{documents:t,index:s}=e;this.#t.clear();for(const[r,i]of t)this.#t.set(r,i);for(const[r,i]of Object.entries(s))await this.#e.import(r,i)}add(e){e.tags||(e.tags=[]),this.#t.set(this.#s,e[I]?e:{...e,[I]:void 0}),this.#e.add(this.#s,e),this.#s++}async search(e){return await A("com.redocly.search.performed",async t=>{t?.setAttribute("id","searchQueryId"),t?.setAttribute("object","searchQuery"),t?.setAttribute("uri","urn:redocly:realm:api:searchQuery:searchQueryId");const{query:s,offset:r,auth:i,product:o,versions:a}=e,n=[],c=i.teams,l={limit:y,offset:r};let m=new Map,d=await this.#e.searchAsync(s,{...l,tag:c});if(o){const h=await this.#e.searchAsync(s,{...l,tag:o});d=this.#i(d,h),t?.setAttribute("product",o)}if(a&&a.length){const h=await this.#e.searchAsync(s,{...l,tag:a});d=this.#i(d,h),t?.setAttribute("versions",a.join(","))}for(const h of d)for(const p of h.result){const f=m.get(p)?.fields||[];m.set(p,{fields:h.field?[...f,h.field]:[...f]})}let g=0;for(const[h,p]of m.entries()){if(g>=y)break;const f=this.#t.get(h);f&&!this.#n(f,a)&&(n.push({document:this.#o(f,s,p.fields),highlight:this.#a(f,s,p.fields)}),g++)}return{documents:{[this.id]:n},facets:{}}})}#o(e,t,s){return this.#c(e,t,s)}#a(e,t,s){const r={};let i=!1;for(const o of s)if(o==="path")r.path=e.path?e.path.map(a=>u(t,a)):[];else if(o.includes("parameters")){if(!i){const a=o.split(":")[1],n=e.parameters?.find(c=>{const l=c[a];return this.#r(t,typeof l=="boolean"?l.toString():l)});n&&(r.parameters=[{name:u(t,n.name),description:u(t,n.description),place:u(t,n.place),path:n.path?n.path.map(c=>u(t,c)):[]}],i=!0)}}else r[o]=u(t,e[o]);return r}#r=(e,t)=>{if(t){const s=e.split(/\s+/g);return Array.isArray(t)?t.some(r=>s.some(i=>r.toLowerCase().includes(i.toLowerCase()))):s.some(r=>t.toLowerCase().includes(r.toLowerCase()))}else return!1};#i(e,t){const s=[];for(const r of e){const i=[];for(const o of t)for(const a of r.result){const n=o.result.find(c=>c===a);n&&i.push(n)}i.length&&s.push({result:i,field:r.field})}return s}#n(e,t){return!!(t&&t.length&&e.isDefaultVersion&&e.versionFolderId&&e.version&&t.some(s=>s.includes(e.versionFolderId??""))&&!t.some(s=>s.includes(e.version??"")))}#c(e,t,s){for(const i of w)if(s.some(o=>o===i))return e;let r;for(const i of s)if(i.includes("parameters")){const o=i.split(":")[1],a=e.parameters?.find(n=>{const c=n[o];return this.#r(t,typeof c=="boolean"?c.toString():c)});if(a){r=a.deepLink;break}}if(r){const i=r.split("#")[1];return{...e,url:`${e.url}#${i}`}}return e}}export{C as FlexSearchIndex};
1
+ import L from"flexsearch";import{REDOCLY_TEAMS_RBAC as A}from"@redocly/config";import{DISABLE_DEEP_LINK_IF_FIELDS_EXIST as R,SEARCH_LIMIT as D}from"../../../../constants/plugins/search.js";import{telemetryTraceStep as b}from"../../../../telemetry/helpers/trace-step.js";import{highlightTextForSearch as u}from"../../../../utils/search/highlight-text-for-search.js";function v(S){const{name:e,description:t,place:r,path:o,deepLink:s}=S,i=s?.indexOf("#")??-1;return{name:e,description:t,place:r,...o&&{path:o},...s&&{deepLink:i>=0?s.slice(i+1):s}}}class C{#e;#t=new Map;#s=1;id;constructor(e,t){this.id=e,this.#e=new L.Document(t)}get documents(){return this.#t.entries()}get documentsCount(){return this.#s}clearDocuments(){this.#t.clear()}async export(e){await this.#e.export(e)}async import(e){const{documents:t,index:r}=e;this.#t.clear();for(const[o,s]of t)this.#t.set(o,s);for(const[o,s]of Object.entries(r))await this.#e.import(o,s)}add(e){const t={...e,tags:e.tags??[],[A]:e[A],...e.parameters&&{parameters:e.parameters.map(v)}};this.#t.set(this.#s,t),this.#e.add(this.#s,t),this.#s++}async search(e){return await b("com.redocly.search.performed",async t=>{t?.setAttribute("id","searchQueryId"),t?.setAttribute("object","searchQuery"),t?.setAttribute("uri","urn:redocly:realm:api:searchQuery:searchQueryId");const{query:r,offset:o,auth:s,product:i,versions:n}=e,c=[],l=s.teams,p={limit:D,offset:o};let h=new Map,m=await this.#e.searchAsync(r,{...p,tag:l});if(i){const a=await this.#e.searchAsync(r,{...p,tag:i});m=this.#a(m,a),t?.setAttribute("product",i)}if(n&&n.length){const a=await this.#e.searchAsync(r,{...p,tag:n});m=this.#a(m,a),t?.setAttribute("versions",n.join(","))}for(const a of m)for(const d of a.result){const f=h.get(d)?.fields||[];h.set(d,{fields:a.field?[...f,a.field]:[...f]})}const x=this.#r(r),g=[];for(const[a,d]of h.entries()){const f=this.#t.get(a);f&&!this.#h(f,n)&&g.push({document:f,fields:d.fields,score:this.#l(x,f)})}const I=g.filter(a=>a.score>=x.length),y=I.length?I:g;y.sort((a,d)=>d.score-a.score);for(const a of y.slice(0,D))c.push({document:this.#n(a.document,r,a.fields),highlight:this.#c(a.document,r,a.fields)});return{documents:{[this.id]:c},facets:{},hasCoveringHit:I.length>0}})}#n(e,t,r){return this.#f(e,t,r)}#c(e,t,r){const o={};let s=!1;for(const i of r)if(i==="path")o.path=e.path?e.path.map(n=>u(t,n)):[];else if(i.includes("parameters")){if(!s){const n=i.split(":")[1],c=this.#o(t,n,e.parameters);c&&(o.parameters=[{name:u(t,c.name),description:u(t,c.description),place:u(t,c.place),path:c.path?c.path.map(l=>u(t,l)):[]}],s=!0)}}else o[i]=u(t,e[i]);return o}#r(e){return[...new Set(e.toLowerCase().split(/\s+/g).filter(Boolean))]}#i(e,t){const r=t.toLowerCase().replace(/\s+/g," "),o=e.filter(i=>r.includes(i)).length;let s=0;for(let i=1;i<e.length;i++)r.includes(`${e[i-1]} ${e[i]}`)&&s++;return o+s/e.length}#l(e,t){let r=0;const o=s=>{if(s==null)return;const i=this.#i(e,String(s));i>r&&(r=i)};o(t.title),o(t.text),o(t.httpPath),o(t.path?.join(" "));for(const s of t.parameters??[])o([s.name,s.description,s.place].filter(Boolean).join(" "));return r}#o(e,t,r){const o=this.#r(e);let s,i=0;for(const n of r??[]){const c=n[t],l=(Array.isArray(c)?c:[c]).filter(h=>h!=null).map(h=>String(h)).join(" "),p=this.#i(o,l);p>i&&(i=p,s=n)}return s}#a(e,t){const r=[];for(const o of e){const s=[];for(const i of t)for(const n of o.result){const c=i.result.find(l=>l===n);c&&s.push(c)}s.length&&r.push({result:s,field:o.field})}return r}#h(e,t){return!!(t&&t.length&&e.isDefaultVersion&&e.versionFolderId&&e.version&&t.some(r=>r.includes(e.versionFolderId??""))&&!t.some(r=>r.includes(e.version??"")))}#f(e,t,r){for(const s of R)if(r.some(i=>i===s))return e;let o;for(const s of r)if(s.includes("parameters")){const i=s.split(":")[1],n=this.#o(t,i,e.parameters);if(n){o=n.deepLink;break}}return o?{...e,url:`${e.url}#${o}`}:e}}export{C as FlexSearchIndex};
@@ -1 +1 @@
1
- import p from"node:path";import{logger as f}from"../../../tools/notifiers/logger.js";import{promiseMapLimit as x}from"../../../utils/async/promise-map-limit.js";import{getLlmsTxtMdPathBySlug as L}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{getRouteStaticData as T}from"../../../utils/get-route-static-data.js";import{getRouteAiDocumentsStore as w}from"../../../utils/get-route-ai-documents-store.js";import{generateLLMsTxt as h,validateLLMsTxtConfig as M}from"./index.js";import{buildPageLlmsTxtMd as S}from"./build-page-llms-txt-md.js";import{getLlmsTxtExcludeMatcher as m}from"./get-llms-txt-exclude-matcher.js";import{isIncludedInLlmsTxt as R}from"./is-included-in-llms-txt.js";import{EntitlementsProvider as C}from"../../../entitlements/entitlements-provider.js";const A=20;function v(i,c){const a=new WeakMap,l=()=>{const t=i.getGlobalConfig("seo");return C.instance().canAccessFeature("seo")===!0&&t?.llmstxt?.hide!==!0},d=async t=>{if(t.excludeFromSearch)return[];const e=i,n=await T(t,e);return await(await w(t,n,c,e))?.getLLMsTxts()??[]},u=t=>{const e=a.get(t);if(e)return e;const n=d(t).catch(o=>(a.delete(t),f.warn(`Failed to generate Markdown for LLMs of "${t.slug}". ${o}`),[]));return a.set(t,n),n},g=t=>{const e=t==="/index.html.md"?"/":t.replace(/\.md$/,"");for(let n=e;n.startsWith("/");){const o=i.getRouteBySlug(n,{followRedirect:!1});if(o?.getAiDocumentsStore)return o;const r=p.posix.dirname(n);if(r===n)return;n=r}};return{async getPageMarkdown(t){if(!l())return;const e=g(t);if(!e)return;const n=i.getGlobalConfig("seo"),o=m(n),r=(await u(e)).find(s=>L(s.slug)===t&&!o(s.fsPath));if(r)return{route:e,content:S(r,n)}},async getLlmsTxt(){if(!l())return;const t=i.getConfig(),e=i.getGlobalConfig("seo"),n=m(e),o=[];if(await x(i.getAllRoutes(),A,async r=>{for(const s of await u(r))!n(s.fsPath)&&R(s,r,t)&&o.push(s)}),!!o.length)try{return M(e?.llmstxt),await h(o,e?.llmstxt,{title:e?.title,description:e?.description},c)}catch(r){f.error(`Failed to generate llms.txt. ${r}`);return}}}}export{v as createLlmsTxtGenerator};
1
+ import p from"node:path";import{logger as f}from"../../../tools/notifiers/logger.js";import{promiseMapLimit as x}from"../../../utils/async/promise-map-limit.js";import{getLlmsTxtMdPathBySlug as L}from"../../../utils/llmstxt/get-llms-txt-md-path-by-slug.js";import{getRouteStaticData as T}from"../../../utils/get-route-static-data.js";import{getRouteAiDocumentsStore as w}from"../../../utils/get-route-ai-documents-store.js";import{generateLLMsTxt as h,validateLLMsTxtConfig as M}from"./index.js";import{buildPageLlmsTxtMd as S}from"./build-page-llms-txt-md.js";import{getLlmsTxtExcludeMatcher as m}from"./get-llms-txt-exclude-matcher.js";import{isIncludedInLlmsTxt as R}from"./is-included-in-llms-txt.js";import{EntitlementsProvider as C}from"../../../entitlements/entitlements-provider.js";const A=20;function v(i,c){const a=new WeakMap,l=()=>{const t=i.getGlobalConfig("seo");return C.instance().canAccessFeature("seo")===!0&&t?.llmstxt?.hide!==!0},d=async t=>{if(t.excludeFromSearch)return[];const e=i,n=await T(t,e);return await(await w(t,n,c,e))?.getLLMsTxts()??[]},u=t=>{const e=a.get(t);if(e)return e;const n=d(t).catch(o=>(a.delete(t),f.warn(`Failed to generate Markdown for LLMs of "${t.slug}". ${o}`),[]));return a.set(t,n),n},g=t=>{const e=t==="/index.html.md"?"/":t.replace(/\.md$/,"");for(let n=e;n.startsWith("/");){const o=i.getRouteBySlug(n,{followRedirect:!1});if(o?.getAiDocumentsStore)return o;const r=p.posix.dirname(n);if(r===n)return;n=r}};return{async getPageMarkdown(t){if(!l())return;const e=g(t);if(!e)return;const n=i.getGlobalConfig("seo"),o=m(n),r=(await u(e)).find(s=>L(s.slug)===t&&!o(s.fsPath));if(r)return{route:e,content:S(r,n)}},async getLlmsTxt(){if(!l())return;const t=i.getConfig(),e=i.getGlobalConfig("seo"),n=m(e),o=[];if(await x(i.getAllRoutes(),A,async r=>{for(const s of await u(r))!n(s.fsPath)&&R(s,r,t)&&o.push(s)}),!!o.length)try{return M(e?.llmstxt),await h(o,e?.llmstxt,{title:e?.title,description:e?.description,siteUrl:e?.siteUrl},c)}catch(r){f.error(`Failed to generate llms.txt. ${r}`);return}}}}export{v as createLlmsTxtGenerator};
@@ -4,11 +4,13 @@ import type { LLMsTxt } from './types';
4
4
  export declare function generateLLMsTxt(llmstxts: LLMsTxt[], llmstxtConfig: SeoConfig['llmstxt'] | undefined, fallbackConfig: {
5
5
  title?: string;
6
6
  description?: string;
7
+ siteUrl: string | undefined;
7
8
  } | undefined, context: LifecycleContext): Promise<string>;
8
- export declare function llmsTxtLink({ title, description, slug, }: {
9
+ export declare function llmsTxtLink({ title, description, slug, siteUrl, }: {
9
10
  title: LLMsTxt['title'];
10
11
  description: LLMsTxt['description'];
11
12
  slug: LLMsTxt['slug'];
13
+ siteUrl?: string;
12
14
  }): string;
13
15
  export declare function validateLLMsTxtConfig(llmstxtConfig: SeoConfig['llmstxt']): void;
14
16
  //# sourceMappingURL=index.d.ts.map