import{McpServer as _}from"@redocly/mcp-typescript-sdk/server/mcp.js";import{StreamableHTTPServerTransport as S}from"@redocly/mcp-typescript-sdk/server/streamableHttp.js";import{logger as p}from"../../../tools/notifiers/logger.js";import{mcpToolWorkers as u,MCP_TOOL_WORKER_KEY as b,MCP_TOOL_IS_AVAILABLE_KEY as y}from"../../../workers/mcp-tool-worker-pool.js";import{EXECUTE_TOOL_NAME as d,EXECUTE_TOOL_SCHEMA as f,DESCRIBE_TOOLS_TOOL_NAME as I,CODE_MODE_TOOL_NAMES as C}from"../docs-mcp/tool-schemas.js";import{buildToolTypeDeclarations as M,sanitizeToolName as E}from"../docs-mcp/codemode/build-tool-type-declarations.js";import{CODE_MODE_INSTRUCTIONS as D,DESCRIBE_TOOLS_DESCRIPTION as g,USAGE_NOTES as h}from"../docs-mcp/codemode/prompts.js";import{isMcpCodeModeEnabled as T}from"../mode.js";async function B({name:e,tools:o,context:n}){const a=new _({name:e,version:new Date().toISOString().slice(0,10)},{capabilities:{logging:{}},instructions:T()?D:void 0}),s=new S({sessionIdGenerator:void 0}),c=L(n),l=r=>async(t,m)=>{p.info(`MCP tool called: ${r}`);const O={toolName:r,args:t,context:c,extra:w(m)};return await u.exec(b,[O],{timeout:6e4})},i=async r=>{try{return await u.exec(y,[{toolName:r,context:c}],{timeout:1e4})}catch(t){return p.error(`Failed to check MCP tool availability for "${r}": ${t instanceof Error?t.message:String(t)}`),!1}};if(T()){const r=o.filter(t=>!C.has(t.name));a.tool(d,f.description,f.schema,l(d)),a.tool(I,g,q(r),v(r,i))}else await Promise.all(o.map(async r=>{const t=r.annotations||{title:r.name},m=a.tool(r.name,r.description,r.schema,t,l(r.name));await i(r.name)||m.disable()}));return await a.connect(s),{server:a,transport:s,cleanup:async()=>{s.close()}}}function q(e){const o=[...new Set(e.map(n=>E(n.name)))];return{type:"object",required:[],additionalProperties:!1,properties:{tools:{type:"array",description:"Tool names to describe. Omit to describe every tool.",items:{type:"string",enum:o},nullable:!0}}}}function v(e,o){return async n=>{const a=n.tools,s=a?.length?e.filter(i=>a.includes(E(i.name))):e,c=await Promise.all(s.map(i=>o(i.name))),l=s.filter((i,r)=>c[r]);return{content:[{type:"text",text:`${M(l)}

${h}`}]}}}function w(e){return{sessionId:e.sessionId,authInfo:e.authInfo,requestId:e.requestId,requestInfo:e.requestInfo,_meta:e._meta}}function L(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}}export{B as createDocsMcpServer};
