import{telemetry as c}from"../../../telemetry/index.js";import{McpErrorCodes as o,McpServerType as i}from"../constants.js";import{getMcpMode as d}from"../mode.js";class n extends Error{code;data;requestId;constructor(r,t,s,a){super(t),this.name="McpError",this.code=r,this.data=s,this.requestId=a}createErrorResponse(){const r={jsonrpc:"2.0",error:{code:this.code,message:this.message,...this.data?{data:this.data}:{}},id:this.requestId??null},t=u(this.code);return new Response(JSON.stringify(r),{status:t,headers:{"Content-Type":"application/json"}})}}function u(e){switch(e){case o.InvalidRequest:case o.InvalidParams:return 400;case o.MethodNotFound:return 404;case o.ServerError:return 405;case o.InternalError:default:return 500}}function h(e){return new n(o.ServerError,"Method not allowed",void 0,e).createErrorResponse()}function p(e,r=i.Docs,t){const s=e instanceof Error?e.message:String(e),a=e instanceof Error?e.stack:void 0;return c.sendMcpErrorMessage([{id:r,object:"mcpServer",uri:`urn:redocly:realm:mcp:server:${r}`,server_type:r,message:s,stack:a||"",mode:d()}]),new n(o.InternalError,"Internal server error mcp",s,t).createErrorResponse()}function v(e="Invalid request",r){return new n(o.InvalidRequest,e,void 0,r).createErrorResponse()}function I(e="Invalid parameters",r){return new n(o.InvalidParams,e,void 0,r).createErrorResponse()}async function M(e,r,t){try{return await e()}catch(s){return c.sendMcpErrorMessage([{id:r,object:"mcpServer",uri:`urn:redocly:realm:mcp:server:${r}`,server_type:r,message:s?.message||"",stack:s?.stack||"",mode:d()}]),t&&t(),p(s,r)}}export{n as McpError,p as createInternalServerError,I as createInvalidParamsError,v as createInvalidRequestError,h as createMethodNotAllowedError,M as withErrorHandling};
