import{fileURLToPath as b}from"node:url";import{dirname as A,join as a}from"node:path";import{logger as g}from"../../tools/notifiers/logger.js";import{reporter as O}from"../../tools/notifiers/reporter.js";import{isDefined as _}from"../../../utils/guards/is-defined.js";import{buildGraphqlDescriptions as w,filterIgnoredApiDescriptions as h,getCleanedUpApiDescriptions as R,isMcpInRedirects as q}from"./utils.js";import{isMcpCodeModeEnabled as L}from"./mode.js";import{getDefaultToolSchemas as j,EXECUTE_TOOL_SCHEMA as N}from"./docs-mcp/tool-schemas.js";import{telemetryTraceStep as G}from"../../../cli/telemetry/helpers/trace-step.js";import{MCP_NOT_ALLOWED_TEMPLATE_ID as H}from"./constants.js";const D="mcp-docs-server-handler",p=A(b(import.meta.url));async function I(){let i=!1;return{id:"mcp",async processContent(e,r){i||await G("build.plugin.mcp",async c=>{const t=await e.loadOpenApiDefinitions(r),d=await e.loadGraphqlDefinitions(r),s=await r.getConfig(),{mcp:n,redirects:v}=s;if(c?.setAttribute("config",JSON.stringify(n||{})),!(n?.hide||n?.docs?.hide)&&(q(v)&&await O.panicOnBuildContentError('The reserved route "/mcp" cannot be used in redirect configuration. Please remove any redirects involving "/mcp" from your redocly.yaml config.'),e.createTemplate(H,"@redocly/theme/layouts/McpNotAllowed"),!n?.docs?.hide)){g.info("Configuring MCP servers...");const M=a(p,"./handlers/docs-mcp-handler.js"),C=R(h(t,n?.docs?.ignore||[])),l=new Map;for(const o of C){const f=o.definition.info?.title||"",u=o.definition.info?.version||"";l.set(`${f.toLowerCase()}@${u}`,{name:f,description:o.definition.info?.description||"",version:u,servers:o.definition.servers||[],relativePath:o.relativePath})}const m=w(h(d,n?.docs?.ignore||[])),P=Object.values(s.products||{}).map(o=>o?.name).filter(_),y=s.l10n?.locales?.map(o=>o.code)??r.fs.localeFolders,E=!!s?.access?.requiresLogin,S=s?.access?.rbac||{},T=j({products:P,locales:y,requiresLogin:E,rbac:S,hasGraphqlApis:m.length>0});e.addMcpTools(a(p,"./docs-mcp/tools/index.js"),T),L()&&e.addMcpTools(a(p,"./docs-mcp/tools/execute.js"),[N]),await U({actions:e,handlerPath:M,apiDescriptionsMap:Object.fromEntries(l),graphqlDescriptions:m,mcpConfig:n}),i=!0}})},async afterRoutesCreated(e,r){const c=await r.getConfig(),{mcp:t}=c;e.setGlobalData({mcpData:{docs:{enabled:!t?.hide&&!t?.docs?.hide,name:t?.docs?.name}}})}}}var K=I;async function U({actions:i,handlerPath:e,apiDescriptionsMap:r,graphqlDescriptions:c,mcpConfig:t}){i.createRequestHandler(D,e),i.addApiRoute({slug:"/mcp",requestHandlerId:D,httpMethod:"all",getStaticData:async()=>({props:{config:{apiDescriptionsMap:r,graphqlDescriptions:c,mcpDocsServerName:t?.docs?.name||"Docs MCP Server"},serverOutDir:i.serverOutDir,tools:i.getMcpTools().map(({importPath:d,...s})=>s)}})}),g.info("Registered Docs MCP Server endpoint at /mcp")}export{D as MCP_DOCS_SERVER_HANDLER_ID,K as default,I as mcpServerPlugin};
