import{toFetchResponse as b,toReqRes as N}from"fetch-to-node";import{logger as m}from"../../../tools/notifiers/logger.js";import{isObject as k}from"../../../../utils/guards/is-object.js";import{createDocsMcpServer as O}from"../servers/docs-server.js";import{filterApiDescriptionsByRbac as U,filterGraphqlDescriptionsByRbac as E}from"../utils.js";import{createMethodNotAllowedError as H,withErrorHandling as I}from"./errors.js";import{attachSseKeepalive as j}from"./sse-keepalive.js";import{McpServerType as L}from"../constants.js";import{constructInvalidTokenResponse as J,constructUnauthorizedResponse as P,handleMcpAuth as q,shouldHandleMcpAuth as B}from"../auth/auth-handlers.js";import{extractTokenFromAuthHeader as G}from"../utils/jwt.js";const u="X-Redocly-AI-Metadata";function $(r){if(r)try{const e=JSON.parse(r);if(k(e))return e;m.warn(`Ignoring ${u} header: not a JSON object.`)}catch{m.warn(`Ignoring ${u} header: invalid JSON.`)}}const z=async(r,e,h)=>{const n=!!e?.config?.access?.requiresLogin,i=e?.config?.access?.rbac||{};let a;const f=r.headers.get("Authorization");if(B(n,i)){const{isAuthenticated:o,isTokenValid:c,currentUser:t,accessToken:p}=await q(r,e);if(!o)return P(new URL(r.url).origin);if(!c)return J();t&&(e.user=t),a=p}else f&&(a=G(f||"")??void 0);let s;const g=async()=>{s&&(await s.cleanup(),s=void 0)};return await I(async()=>{if(r.method==="GET")return new Response(JSON.stringify({error:"Method Not Allowed",message:`In order to use this MCP server, you need register it in your MCP Client (VS Code, Cursor, Claude Code, etc.) using that URL: ${r.url}`}),{status:405,headers:{"Content-Type":"application/json"}});if(r.method!=="POST")return H();const o=h,c=o?.props?.config?.apiDescriptionsMap||{},t=o?.props?.config?.graphqlDescriptions||[],p=o?.props?.config?.mcpDocsServerName||"Docs MCP server",{config:{mcp:D={}}}=e,M=U(c,e.user,i,n),R=E(t,e.user,i,n),y=e.config.products?Object.values(e.config.products).map(l=>l?.name):[],A=D.docs?.name||p,w=$(r.headers.get(u)),T=o?.props?.tools||[];s=await O({name:A,tools:T,context:{...e,accessToken:a,outdir:e.outdir||"",baseUrl:e.baseUrl||new URL(r.url).origin,apiDescriptionsMap:M,graphqlDescriptions:R,products:y,metadata:w}});const v=await r.json(),{req:C,res:d}=N(r),S=j(d);try{await s.transport.handleRequest(C,d,v)}catch(l){throw S.stop(),l}return b(d)},L.Docs,g)};var ee=z;export{ee as default};
