@decaf-ts/mcp-server 1.5.11 → 1.5.13

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 (45) hide show
  1. package/dist/assets/code/patterns/builder.enc +0 -0
  2. package/dist/assets/prompts/agent/agent.enc +0 -0
  3. package/dist/assets/prompts/agent/init.enc +0 -0
  4. package/dist/assets/prompts/constitution_commands.enc +0 -0
  5. package/dist/assets/prompts/documentation/class.enc +0 -0
  6. package/dist/assets/prompts/documentation/constant.enc +0 -0
  7. package/dist/assets/prompts/documentation/decorator.enc +0 -0
  8. package/dist/assets/prompts/documentation/file.enc +3 -6
  9. package/dist/assets/prompts/documentation/function.enc +0 -0
  10. package/dist/assets/prompts/documentation/interface.enc +0 -0
  11. package/dist/assets/prompts/documentation/iterate.enc +1 -3
  12. package/dist/assets/prompts/documentation/module.enc +0 -0
  13. package/dist/assets/prompts/documentation/prefix.enc +0 -0
  14. package/dist/assets/prompts/documentation/repo.enc +0 -0
  15. package/dist/assets/prompts/documentation/suffix.enc +0 -0
  16. package/dist/assets/prompts/git_commands.enc +0 -0
  17. package/dist/assets/prompts/jira/operational_prompts.enc +0 -0
  18. package/dist/assets/prompts/jira/system_prompt.enc +0 -0
  19. package/dist/assets/prompts/mode_commands.enc +0 -0
  20. package/dist/assets/prompts/plan_commands.enc +0 -0
  21. package/dist/assets/prompts/repository/readme.enc +0 -0
  22. package/dist/assets/prompts/repository/release_notes.enc +0 -0
  23. package/dist/assets/prompts/repository/setup.enc +0 -0
  24. package/dist/assets/prompts/specification_commands.enc +0 -0
  25. package/dist/assets/prompts/startup_command.enc +0 -0
  26. package/dist/assets/prompts/task_commands.enc +0 -0
  27. package/dist/assets/prompts/tests/coverage.enc +0 -0
  28. package/dist/assets/templates/AGENTS.enc +0 -0
  29. package/dist/assets/templates/agents_template.enc +0 -0
  30. package/dist/assets/templates/constitution_template.enc +0 -0
  31. package/dist/assets/templates/decaf/context/logCtx.enc +0 -0
  32. package/dist/assets/templates/decaf/services/client_based_service.enc +0 -0
  33. package/dist/assets/templates/decaf/services/model_service.enc +0 -0
  34. package/dist/assets/templates/decaf/services/service.enc +0 -0
  35. package/dist/assets/templates/decaf_guidelines.enc +1 -1
  36. package/dist/assets/templates/instructions_template.enc +0 -0
  37. package/dist/assets/templates/jira_templates.enc +0 -0
  38. package/dist/assets/templates/plan_template.enc +0 -0
  39. package/dist/assets/templates/specification_template.enc +0 -0
  40. package/dist/assets/templates/task_template.enc +0 -0
  41. package/dist/mcp-server.cjs +1 -1
  42. package/dist/mcp-server.cjs.map +1 -1
  43. package/dist/mcp-server.js +1 -1
  44. package/dist/mcp-server.js.map +1 -1
  45. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- import{Command as t}from"commander";import*as e from"fs";import r,{promises as s}from"fs";import{MiniLogger as n,NumericLogLevels as i,Logging as o,LoggedClass as a,toSnakeCase as c,sf as p,toPascalCase as l,LogLevel as u,LoggedEnvironment as d}from"@decaf-ts/logging";import{__decorate as m,__metadata as h}from"tslib";import{required as f,Model as y,list as g,minlength as b}from"@decaf-ts/decorator-validation";import{z as v,ZodObject as w}from"zod";import{injectable as S,inject as I}from"@decaf-ts/injectable-decorators";import{prop as j,Metadata as x}from"@decaf-ts/decoration";import*as T from"path";import A from"path";import{InternalError as E,SerializationError as k,ValidationError as O}from"@decaf-ts/db-decorators";import N from"crypto";import C from"zlib";import{fileURLToPath as J}from"url";import{unified as H}from"unified";import _ from"remark-directive";import P from"remark-gfm";import $ from"remark-parse";import{inspect as R}from"node:util";import{UriTemplate as D}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";import{ResourceTemplate as q,McpServer as M}from"@modelcontextprotocol/sdk/server/mcp.js";import{v4 as B}from"uuid";import{StdioServerTransport as U}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as K}from"@modelcontextprotocol/sdk/server/streamableHttp.js";class F extends n{constructor(t,e,r){super(t,e,r)}log(t,e,r,s){const n=this.config("level");i[n],i[t]}}const L=(t,e,...r)=>{const s=(t=>{if("string"==typeof t)return t;if(!t)return"unknown";if("function"==typeof t)return t.name||"unknown";if("object"==typeof t&&"constructor"in t){const e=t.constructor;if(e&&e.name)return e.name}return"unknown"})(t);return new F(s,e)};var W,Y,X,z,G;(t=>{t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.ADVANCED=2]="ADVANCED",t[t.HIGH=3]="HIGH"})(W||(W={})),(t=>{t[t.NONE=0]="NONE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(Y||(Y={})),(t=>{t[t.FREE=0]="FREE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(X||(X={}));class Z extends y{get log(){return this._log||(this._log=o.for(this)),this._log}constructor(t){super(t)}logFor(t){const{sessionId:e,requestId:r,authInfo:s}=t||{};let n="string"==typeof e&&e.length>0?this.log.for(e):this.log;return s&&s.clientId&&(n=n.for(s.clientId)),r&&(n=n.for(r.toString())),n}setDescription(t){return this.description=t,this}getDescription(){return this.description}setName(t){return this.name=t,this}getName(){return this.name}setTitle(t){return this.title=t,this}}m([f(),h("design:type",String)],Z.prototype,"description",void 0),m([f(),h("design:type",String)],Z.prototype,"name",void 0),m([f(),h("design:type",String)],Z.prototype,"title",void 0);class V extends Z{constructor(t){super(t),this.reasoning=W.NONE,this.effort=Y.NONE,this.cost=X.FREE}setReasoning(t){return this.reasoning=t,this}setEffort(t){return this.effort=t,this}setCost(t){return this.cost=t,this}}function Q(t){if(!t)return;let e=t,r=e&&e._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)e=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)e=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)e=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)e=r.innerType;else{if(!r.schema)return;e=r.schema}r=e&&e._def}return r&&"ZodObject"===r.typeName?r:void 0}function tt(t,e="schema"){if(Q(t))return t;if(t&&"object"==typeof t){const e=t.def&&"object"==typeof t.def?t.def:void 0,r=e&&(e.shape||"object"===e.type)&&e.shape||("object"===t.type?t.shape:void 0)||(e&&"object"===e.type?{}:void 0);if(e||"object"===t.type||r){const t={};if(r&&"object"==typeof r)for(const[e,s]of Object.entries(r))t[e]=rt(s)?s:v.any();return v.object(t)}}throw Error(`Registration error: provided a non-canonical ${e}. Export a ZodObject (z.object(...)).`)}function et(t){if(!t)return;if(t&&"object"==typeof t&&!t._def)return t.def&&"object"==typeof t.def&&t.def.shape?t.def.shape:t;const e=Q(t);return e?"function"==typeof e.shape?e.shape():e.shape||void 0:void 0}function rt(t){return!(!t||"object"!=typeof t||!t._def)}m([f(),h("design:type",Number)],V.prototype,"reasoning",void 0),m([f(),h("design:type",Number)],V.prototype,"effort",void 0),m([f(),h("design:type",Number)],V.prototype,"cost",void 0),(t=>{t.ASSETS="assets"})(z||(z={})),(t=>{t.PROMPT="prompts",t.DOCUMENTATION="documentation",t.CODE="code"})(G||(G={}));const st=Buffer.from("DCAF1","ascii");function nt(t){let e=A.resolve(t);for(;;){if(r.existsSync(A.join(e,"package.json")))return e;const t=A.dirname(e);if(t===e)break;e=t}}const it=process.argv?.[1]?nt(A.dirname(A.resolve(process.argv[1]))):void 0,ot=(()=>{const t=Error().stack;if(!t)return;const e=t.split(/\r?\n/).slice(1);for(const t of e){const e=t.match(/\(?([^()]+?):\d+:\d+\)?/);if(!e)continue;let r=e[1];if(r.startsWith("file://"))try{r=J(r)}catch{continue}if(!r.includes("node:internal"))return A.dirname(r)}})(),at=ot?nt(ot):void 0,ct=it??at??process.cwd();function pt(...t){return A.join(ct,...t)}function lt(t){let r=t;for(;;){const t=T.join(r,"lib","assets");if(e.existsSync(t))return t;const s=T.join(r,"src","assets");if(e.existsSync(s))return s;const n=T.join(r,"assets");if(e.existsSync(n))return n;const i=T.dirname(r);if(i===r)break;r=i}}function ut(){const t=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(t&&e.existsSync(t))return t;const r=lt(__dirname);if(r)return r;const s=process.argv?.[1];if(s){const t=lt(T.dirname(s));if(t)return t}const n=[ct,process.env.INIT_CWD].filter(Boolean);for(const t of n){const e=lt(t);if(e)return e}return pt("assets")}let dt=class extends a{constructor(t){super(),this.basePath=t||ut()}listAssets(...t){const r=T.join(this.basePath,...t);return e.readdirSync(r)}listPrompts(){return this.listAssets(G.PROMPT)}getAsset(t,r="md",...s){const n=T.join(this.basePath,...s),i=(t,r=!1)=>{try{return r?(t=>{if(t.length<st.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!t.subarray(0,st.length).equals(st))throw Error("Invalid prompt payload (bad magic)");const e=process.env.ENCRYPTION_KEY||"";if(!e)throw Error("Missing encryption key. Set ENCRYPTION_KEY to load obfuscated assets.");let r=st.length;const s=t.subarray(r,r+16);r+=16;const n=t.subarray(r,r+12);r+=12;const i=t.subarray(r,r+16);r+=16;const o=t.subarray(r),a=((t,e)=>N.scryptSync(t,e,32))(e,s),c=N.createDecipheriv("aes-256-gcm",a,n);c.setAuthTag(i);const p=Buffer.concat([c.update(o),c.final()]);return C.gunzipSync(p)})(e.readFileSync(t)).toString("utf-8"):e.readFileSync(t,"utf-8")}catch(t){if("ENOENT"===t.code)return null;throw t}},o=i(T.join(n,`${t}.${r}`),"enc"===r);if(null!==o)return o;const a=i(T.join(n,t+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+T.join(n,`${t}.${r}`))}getAllAssets(t,...e){return this.listAssets(t,...e).reduce((r,s)=>{const n=T.extname(s),i=T.basename(s,n),o=n.replace(/^\./,"")||void 0;return r[i]=this.getAsset(i,o??void 0,t,...e),r},{})}toPromptDef(t){const e=t=>"number"==typeof t?t:"string"==typeof t?(t=>{switch(t){case"none":return W.NONE;case"basic":return W.BASIC;case"advanced":return W.ADVANCED;case"high":return W.HIGH;case"medium":return Y.MEDIUM;case"low":return X.LOW;case"free":return X.FREE;default:throw new E("Cannon convert unknown level "+t)}})(t.toLowerCase()):W.NONE;return t.effort=e(t.effort),t.reasoning=e(t.reasoning),t.cost=e(t.cost),t}getPrompt(t,...e){const r=this.getAsset(c(t),"json",G.PROMPT,...e);let s;try{s=JSON.parse(r)}catch(r){throw new k(`Failed to parse prompt ${t} in categories ${e}: ${r}`)}return this.toPromptDef(s)}getAllPrompts(...t){const e=this.getAllAssets(G.PROMPT,...t);return Object.entries(e).reduce((e,[r,s])=>{try{e[r]=JSON.parse(s)}catch(e){throw new k(`Failed to parse prompt ${r} in categories ${t}: ${e}`)}return e},e)}};dt=m([S(),h("design:paramtypes",[String])],dt);class mt extends V{constructor(t){super(t)}setCb(t){return this.cb=t,this}setArgsSchema(t){return this.argsSchema=t,this}static get builder(){return new mt}static patchPrompt(t,e,r,s){const n=(e=Array.isArray(e)?e:Object.keys(e)).filter(t=>!Object.prototype.hasOwnProperty.call(r,t));if(n.length)throw new O("Missing replacements for placeholders: "+n.join(", "));s&&(s.verbose("Patching prompt with placeholders: "+JSON.stringify(e)),s.debug("Values: "+JSON.stringify(r)));const i=e.reduce((t,e)=>(t[e]=r[e],t),{});return p(t,i)}patchPrompt(t,e,r,s){return mt.patchPrompt(t,e,r,s||this.log.for(this.patchPrompt))}build(t,e){const r=this.log.for(this.build),s=this.hasErrors();if(s)throw new O(s.toString());try{this.argsSchema&&tt(this.argsSchema,"argsSchema");const r=et(this.argsSchema);return t.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(t,r)=>{const s=this.logFor(r);t=Object.assign({},e,t||{}),s.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(t)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const n=await Promise.resolve(this.cb(t,r));return s.verbose(`Prompt ${this.name} executed successfully.`),s.debug("Prompt execution meta: "+JSON.stringify(n._meta)),n})}catch(t){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),t),t}}}m([I(dt),h("design:type",dt)],mt.prototype,"assets",void 0),m([f(),h("design:type",Object)],mt.prototype,"cb",void 0),m([f(),h("design:type",w)],mt.prototype,"argsSchema",void 0),m([j(),h("design:type",Object)],mt.prototype,"placeholders",void 0);class ht extends mt{setCategory(t){return this.promptCategory=t,this}addPrefix(t){return this.prefixes=this.prefixes||[],this.prefixes.push(t),this}addSuffix(t){return this.suffixes=this.suffixes||[],this.suffixes.push(t),this}constructor(t){super(t)}build(t){const e=this.assets.getPrompt(this.name,this.promptCategory);y.fromObject(this,e);const r=new Set((x.properties(ht)||[]).filter(t=>!["assets","promptCategory","prefixes","suffixes"].includes(t)));["cb","argsSchema"].forEach(t=>r.add(t));const s=this.hasErrors(...Array.from(r));if(s)throw new O(s.toString());const n=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=[...new Set([...e.placeholders,...n.map(t=>t.placeholders||[]),...i.map(t=>t.placeholders||[])].flat())].reduce((t,e)=>(t[e]=v.string().describe("The description for "+e),t),{});return this.setArgsSchema(v.object(o)),this.setCb((t,e)=>{const r=this.logFor(e).for(ht).for(this.promptCategory).for(this.name);function s(t=[]){return Array.isArray(t)?t:Object.keys(t)}const n=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...n.map(t=>s(t.placeholders)).flat(),...i.map(t=>s(t.placeholders)).flat(),...s(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...n.map(t=>t.prompt),o.prompt,...i.map(t=>t.prompt)].join("\n\n"),a,t,r)}}],_meta:{}}}),super.build(t)}setReasoning(t){throw new E("Named prompt builders don't require callback")}setEffort(t){throw new E("Named prompt builders don't require callback")}setCost(t){throw new E("Named prompt builders don't require callback")}setDescription(t){throw new E("Named prompt builders don't require callback")}setTitle(t){throw new E("Named prompt builders don't require callback")}static get builder(){return new ht}}m([f(),h("design:type",String)],ht.prototype,"promptCategory",void 0),m([g(String),b(1),h("design:type",Array)],ht.prototype,"prefixes",void 0),m([b(1),g(String),h("design:type",Array)],ht.prototype,"suffixes",void 0);const ft=mt.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(v.object({message:v.string().optional()})).setCb(async t=>{const e=t.message??"default";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),yt=mt.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc prompt").setDescription("Interactive prompt for jogging JSDoc helpers").setArgsSchema(v.object({gist:v.string().optional()})).setCb(async t=>{const e=t.gist??"interactive jsdoc response";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),gt=Object.assign(yt,{name:yt.getName()});var bt;function vt(t,e=[],r=[]){const s=ht.builder.setCategory(bt.DOCS).setName(t);return["prefix",...e].forEach(t=>s.addPrefix(t)),["suffix",...r].forEach(t=>s.addSuffix(t)),s}(t=>{t.DOCS="documentation",t.CODE="code"})(bt||(bt={}));const wt=[vt("class"),vt("constant"),vt("decorator"),vt("function"),vt("module"),vt("file"),vt("repo",[],["iterate"])],St=v.object({className:v.string().describe("the class name to turn into a builder")}),It=[ft,gt,...wt,mt.builder.setName("ts-code-dp-builder").setTitle("Typescript builder design patter prompt").setDescription("for a class, with a defined set of properties, scafold a builder design pattern").setArgsSchema(St).setReasoning(W.BASIC).setCb((t,e)=>(t.className=l(t.className),{messages:[{role:"user",content:{type:"text",text:`You're a senior TypeScript developer writing typescript code.You're a senior TypeScript developer writing typescript code.\nTransform the selected class into a builder design pattern implementation in Typescript.\nuse @decaf-ts validation decorators to enforce the validation of your builder.\n\n- must extend the Model Class from @decaf-ts/decorator-validation;\n- each property must be marked as protected;\n- each property must have a setter method that returns 'this' for chaining;\n- the build() method must validate the properties using hasErrors() method from Model class;\n- if validation fails, throw an error with the validation errors;\n- if validation passes, return an instance of the original class with the set properties;\n- optionally (but do so by default) add the static builder and from methods from the example;\n- if the clasee already follows the pattern but has properties without decoration or without setters, simple add them;\n\nexample:\n\noriginal class:\n\`\`\`typescript\nexport class ${t.className} {\n description!: string;\n name!: string = "default name";\n title!: string;\n age?: string;\n dateOfBirth!: Date;\n}}\n\`\`\` \n\nresulting builder pattern implementation:\n\`\`\`typescript\nexport class ${t.className}Builder extends Model {\n\n @minlength(10\n @required()\n protected description!: string;\n \n @required()\n protected name!: string = "default value;\n \n @required()\n protected title!: string;\n \n @min(18)\n protected age?: string;\n \n @date()\n protected dateOfBirth!: Date;\n\n protected constructor(arg?: ModelArg<${t.className}Builder>>) {\n super(arg);\n Model.fromModel(this, arg);\n }\n\n setDescription(value: string) {\n this.description = value;\n return this;\n }\n\n setName(value: string) {\n this.name = value;\n return this;\n }\n\n setTitle(value: string) {\n this.title = value;\n return this;\n }\n setAge(value: number) {\n this.age = value;\n return this;\n }\n setDate(value: Date) {\n this.age = value;\n return this;\n }\n \n build(...args: any[]): ${t.className}Builder | Promise<${t.className}Builder> {\n const errs = this.hasErrors();\n if (errs) throw new Error(errs.toString());\n \n return // code that builds OBJ here\n }\n \n static get builder(): ${t.className}Builder {\n return new ${t.className}Builder(); // static method to get a new builder instance\n }\n \n static from<K extends keyof ${t.className}Builder>(obj: K, ${t.className}Builder[K]): ${t.className}Builder {\n return new ${t.className}Builder(); // static method to create a builder from an object\n }\n}\n\`\`\` \n\n`}}],_meta:{}}))];class jt extends V{setAnnotations(t){return this.annotations=Object.assign(this.annotations,t),this}setCb(t){return this.cb=t,this}setInputSchema(t){return this.inputSchema=t,this}setOutputSchema(t){return this.outputSchema=t,this}constructor(t){super(t),this.annotations={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}static get builder(){return new jt}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{this.inputSchema&&tt(this.inputSchema,"inputSchema"),this.outputSchema&&tt(this.outputSchema,"outputSchema");const e=et(this.inputSchema),r=et(this.outputSchema);return t.registerTool(this.name,{title:this.title,description:this.description,inputSchema:e,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(t,e)=>{const r=this.logFor(e);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(t)}`),e._meta=Object.assign(e._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(t,e));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(s._meta)),s})}catch(t){const e=t?.message||t+"";if("string"==typeof e&&e.includes("already registered"))return o.for(this).warn(`Tool ${this.name} already registered - skipping duplicate registration`),{name:this.name};throw o.for(this).error("Error building tool",t),t}}}m([f(),h("design:type",Object)],jt.prototype,"annotations",void 0),m([f(),h("design:type",Object)],jt.prototype,"cb",void 0),m([f(),h("design:type",Function)],jt.prototype,"inputSchema",void 0);const xt=jt.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(v.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(xt,{name:xt.getName()});const Tt=jt.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(v.object({filePath:v.string().optional()})).setCb(async()=>({content:[{type:"text",text:"file summary stub"}],result:{summary:"file summary stub"}}));function At(){try{let t=process.argv[1]?A.dirname(A.resolve(process.argv[1])):process.cwd();for(;;){const e=A.join(t,"package.json");if(r.existsSync(e))return JSON.parse(r.readFileSync(e,"utf-8"));const s=A.dirname(t);if(s===t)break;t=s}}catch{}return{}}Object.assign(Tt,{name:Tt.getName()});const Et=At().version??"0.0.0",kt=At().name??"unknown";x.registerLibrary(kt,Et);const Ot={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:Et,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:ct,assetDir:ut(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0},xray:{host:process.env.XRAY__HOST||process.env.XRAY__API_HOST||"https://xray.cloud.getxray.app",apiUser:process.env.XRAY__API_USER||"",apiSecret:process.env.XRAY__API_SECRET||""},level:u.error},Nt=d.accumulate(Ot);function Ct(){const{host:t,email:e,apiKey:r,projectKey:s,issueType:n}=Nt.jira;return{host:t?.trim(),email:e?.trim(),apiKey:r?.trim(),projectKey:s?.trim(),issueType:n?.trim(),parentIssue:Nt.jira.parentIssue?.trim()}}function Jt(){const t=Ct();return[{name:"JIRA__HOST",required:!0,description:"Atlassian host (e.g. decaf-ts.atlassian.net) where your Jira instance is hosted.",value:t.host},{name:"JIRA__EMAIL",required:!0,description:"Email address of the Jira account that has API access.",value:t.email},{name:"JIRA__API_KEY",required:!0,description:"API token created in your Atlassian profile (a.k.a. APIKEY alias) for authenticating requests.",sensitive:!0,value:t.apiKey},{name:"JIRA__PROJECT_KEY",required:!1,description:"Default Jira project key (e.g. DECAF) used when an issue creation request omits a project.",value:t.projectKey},{name:"JIRA__ISSUE_TYPE",required:!1,description:"Default Jira issue type (e.g. Task, Bug) used when creating issues without an explicit type.",value:t.issueType},{name:"JIRA__PARENT_ISSUE",required:!1,description:"Default parent issue key (e.g. DECAF-123) applied when a child issue is created without an explicit parent.",value:t.parentIssue}]}function Ht(t){const e=t.value?((t,e)=>{if(t)return e?"<configured>":t})(t.value,t.sensitive):"not set",r=t.required?"(required)":"(optional)";return`\u2022 ${t.name} ${r}: ${t.description} Current state: ${e}.`}o.setConfig(Nt);class _t extends Error{constructor(t){const e=Jt(),r=(t=>{const e=Jt();return`${t.length?`Missing Jira credentials: ${t.map(t=>t.name).join(", ")}.`:"Jira credentials are configured."}\n\nThis setup uses the following environment variables:\n${e.map(Ht).join("\n")}`})(t);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=e,this.missing=t,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,_t)}}function Pt(t){let e;try{const t=require("jira.js");e=t?.Version3Client||t.default?.Version3Client||t.default||t}catch(t){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+t)}const{host:r,email:s,apiKey:n}=(()=>{const t=Ct(),e=Jt().filter(t=>t.required&&!t.value);if(e.length>0)throw new _t(e);return{host:t.host,email:t.email,apiKey:t.apiKey}})();return new e({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:s,apiToken:n}}})}const $t=v.object({name:v.string().min(1).optional(),content:v.string().min(1),placeholders:v.record(v.string()).optional()}),Rt=v.object({template:$t.optional()}),Dt=v.union([v.object({fields:v.record(v.any())}).merge(Rt),v.object({summary:v.string().min(1),projectKey:v.string().min(1),issueType:v.string().min(1),description:v.string().optional()}).merge(Rt)]);function qt(t,e,r){const s=((t.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!s)return null;const n=s[2],i=r.resolveAttachment?.(n);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Mt(t,e){if(!t)return[];if(!e.enableAtMentions&&!e.enableEmojiShortcodes)return[{type:"text",text:t}];let r=0;const s=[],n=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;r<t.length;){const o=Ut(e.enableAtMentions?Bt(n,t,r):null,e.enableEmojiShortcodes?Bt(i,t,r):null);if(!o){s.push({type:"text",text:t.slice(r)});break}if(o.index>r&&s.push({type:"text",text:t.slice(r,o.index)}),"mention"===o.kind){const{full:t,groups:n}=o,i=n[0]??"",a=n[1]??"";i&&s.push({type:"text",text:i});const c=e.resolveMention?.(a);c?s.push({type:"mention",attrs:{id:c.id,text:c.text}}):s.push({type:"text",text:"@"+a}),r=o.index+t.length;continue}if("emoji"===o.kind){const{full:t,groups:n}=o,i=`:${n[0]}:`,a=e.resolveEmoji?.(i);s.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:i}}),r=o.index+t.length;continue}}return(t=>{const e=[];for(const r of t){const t=e[e.length-1];"text"!==r.type||"text"!==t?.type||t.marks||r.marks?e.push(r):t.text=(t.text??"")+(r.text??"")}return e})(s)}function Bt(t,e,r){t.lastIndex=r;const s=t.exec(e);if(!s)return null;const n=t.source.includes("@")?"mention":"emoji";return{index:s.index,full:s[0],groups:s.slice(1),kind:n}}function Ut(t,e){return t?e&&t.index>e.index?e:t:e}function Kt(t){const e=(t.children??[])[0];return"text"===e?.type?(e.value??"")+"":"paragraph"===e?.type?((e.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("")||"")+"":""}function Ft(t){const e=((t??"")+"").toLowerCase().trim();return e?"info"===e||"note"===e||"success"===e||"warning"===e||"error"===e?e:"danger"===e?"error":null:null}function Lt(t){const e=((t??"")+"").toLowerCase().trim();return!e||"neutral"!==e&&"green"!==e&&"yellow"!==e&&"red"!==e&&"blue"!==e&&"purple"!==e?null:e}function Wt(t,e){const r=[];for(const s of t??[])if(s?.type)if("text"!==s.type)if("strong"!==s.type)if("emphasis"!==s.type)if("delete"!==s.type)if("inlineCode"!==s.type)if("break"!==s.type){if("link"===s.type){const t=(s.url??"")+"",n=Xt(s.children??[],t),i=qt(s,0,e);if(i){"inline"===i.type?r.push(i.node):r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:t}}]});continue}if(e.enableSmartCards&&zt(n,t)){r.push({type:"inlineCard",attrs:{url:t}});continue}r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:t}}]});continue}if("textDirective"===s.type&&"status"===s.name){const t=Kt(s)||"Status",e=Lt(s.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:t,color:e}});continue}if("textDirective"===s.type&&"emoji"===s.name){const t=Gt(s);r.push(Zt(t,e));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(s.value??"")+"",marks:[{type:"code"}]});else r.push(...Yt(Wt(s.children??[],e),{type:"strike"}));else r.push(...Yt(Wt(s.children??[],e),{type:"em"}));else r.push(...Yt(Wt(s.children??[],e),{type:"strong"}));else r.push(...Mt((s.value??"")+"",e));return r.filter(t=>!("text"===t.type&&""===(t.text??"")))}function Yt(t,e){return t.map(t=>{if("text"!==t.type)return t;const r=t.marks?[...t.marks,e]:[e];return{...t,marks:r}})}function Xt(t,e){const r=[];for(const e of t??[])"text"===e.type||"inlineCode"===e.type?r.push((e.value??"")+""):"emphasis"!==e.type&&"strong"!==e.type&&"delete"!==e.type||r.push(Xt(e.children??[],""));return r.join("")||e}function zt(t,e){const r=(t??"").trim(),s=(e??"").trim();return r===s&&/^https?:\/\//i.test(s)}function Gt(t){return(t.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("").trim()||""}function Zt(t,e){const r=t.startsWith(":")?t:`:${t}:`,s=e.resolveEmoji?.(r);return s?{type:"emoji",attrs:{shortName:s.shortName,text:s.text}}:{type:"emoji",attrs:{shortName:r}}}function Vt(t){return t?"string"==typeof t?t:"text"===t.type||"inlineCode"===t.type?(t.value??"")+"":Array.isArray(t.children)?t.children.map(Vt).join(""):"":""}function Qt(t,e){if(!t?.type)return null;if((t=>"containerDirective"===t?.type&&"panel"===t?.name)(t))return((t,e)=>{const r=t.attributes??{},s=Ft(r.type)??"info",n="string"==typeof r.title?r.title:void 0,i=(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:s,...n?{panelType:s,title:n}:{panelType:s}},content:i.length?i:[{type:"paragraph",content:[]}]}})(t,e);switch(t.type){case"heading":return{type:"heading",attrs:{level:ee(t.depth??1,1,6)},content:Wt(t.children??[],e)};case"paragraph":return(t=>{const e=t.children??[];if(1!==e.length)return null;const r=e[0];if("image"!==r?.type)return null;const s=(r.url??"")+"";return s?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:s}}]}:null})(t)||{type:"paragraph",content:Wt(t.children??[],e)};case"blockquote":return{type:"blockquote",content:(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean)};case"list":return((t,e)=>e.enableTaskLists&&(t.children??[]).some(t=>"boolean"==typeof t.checked)?((t,e)=>{const r=[];let s=0;for(const n of t.children??[]){if("boolean"!=typeof n.checked)continue;s+=1;const t=(n.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+s,state:n.checked?"DONE":"TODO"},content:t.length?t:[{type:"paragraph",content:[]}]})}return{type:"taskList",content:r}})(t,e):{type:t.ordered?"orderedList":"bulletList",content:(t.children??[]).map(t=>((t,e)=>{const r=(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);return{type:"listItem",content:r.length?r:[{type:"paragraph",content:[]}]}})(t,e))})(t,e);case"code":{const r=((t,e)=>{const r=(t??"").toString().trim().toLowerCase();return r?e.enableMermaid&&"mermaid"===r?"mermaid":(t=>{const e=t.trim().toLowerCase();return{js:"javascript",javascript:"javascript",jsx:"javascript",ts:"typescript",typescript:"typescript",tsx:"typescript",py:"python",python:"python",rb:"ruby",ruby:"ruby",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",yml:"yaml",yaml:"yaml",json:"json",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",sql:"sql",go:"go",rust:"rust",java:"java",c:"c",cpp:"cpp","c++":"cpp",cs:"csharp",csharp:"csharp",php:"php",kotlin:"kotlin",swift:"swift",md:"markdown",markdown:"markdown",graphql:"graphql",gql:"graphql",dockerfile:"docker",makefile:"make",ini:"ini"}[e]??e})(r):null})(t.lang,e);return{type:"codeBlock",attrs:{language:r},content:[{type:"text",text:(t.value??"")+""}]}}case"thematicBreak":return{type:"rule"};case"table":return((t,e)=>({type:"table",content:(t.children??[]).map((t,r)=>({type:"tableRow",content:(t.children??[]).map(t=>({type:0===r?"tableHeader":"tableCell",content:[{type:"paragraph",content:Wt(t.children??[],e)}]}))}))}))(t,e);case"leafDirective":return"status"===t.name?(t=>{const e=Lt((t.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:Kt(t)||"Status",color:e}}]}})(t):"panel"===t.name?((t,e)=>{const r=t.attributes??{},s=Ft(r.type)??"info",n="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:s,...n?{title:n}:{}},content:[{type:"paragraph",content:Wt([{type:"text",value:Kt(t)}],e)}]}})(t,e):te(t,e);default:return te(t,e)}}function te(t,e){if("drop"===e.unknownNodeStrategy)return null;const r=Vt(t);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function ee(t,e,r){const s=Number.isFinite(t)?Math.trunc(t):e;return Math.max(e,Math.min(r,s))}const re={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function se(t,e={}){const r={...re,...e},s=t??"",n=H().use($).use(P).use(_),i=n.parse(s),o=n.runSync(i);return ne(o),((t,e)=>{const r=[];for(const s of t.children??[]){const t=Qt(s,e);t&&(Array.isArray(t)?r.push(...t):r.push(t))}return((t,e)=>{if(!e.enableSmartCards)return t;const r=t.content.map(t=>(t=>{if("paragraph"!==t.type)return t;const e=t.content??[];if(1!==e.length)return t;const r=e[0];if("inlineCard"!==r?.type)return t;const s=r.attrs?.url;return s?[{type:"blockCard",attrs:{url:s}}]:t})(t)).flat();return{...t,content:r}})({version:1,type:"doc",content:r},e)})(o,r)}function ne(t){if(!t||!Array.isArray(t.children))return;const e=[];for(const r of t.children)"definition"!==r?.type&&("html"!==r?.type?(ne(r),e.push(r)):e.push({type:"text",value:(r.value??"")+""}));t.children=e}const ie=/\{\{\s*([^\}]+)\s*\}\}/g;function oe(t){if(!t||0>=Object.keys(t).length)return[];const e=(t=>{if(null==t)return"";try{return JSON.stringify(t,null,2)}catch{return R(t,{depth:null})}})(t);return e?[{type:"text",text:e}]:[]}function ae(t={},e=[]){const r=(t=>t&&"object"==typeof t?Array.isArray(t)?{items:t}:t:"string"==typeof t?{message:t}:null==t?{}:{value:t})(t);return{content:e.length?e:oe(r),result:r,structuredContent:r}}const ce={name:"jira-issue-create",inputSchema:Dt,runTool:async(t,e)=>ae(await(async(t,e)=>{let r;const s=t=>t&&t.trim()?t.trim():void 0,n=s(Nt.jira.projectKey),i=s(Nt.jira.issueType),o=e&&"object"==typeof e&&!Array.isArray(e)?e:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??n,issueType:o.issueType??i};try{r=Dt.parse(a)}catch(t){const e=Error("validation error");throw e.code="validation_error",e}let c;c=r&&"object"==typeof r&&"fields"in r&&r.fields?{...r.fields}:{summary:r.summary,project:{key:r.projectKey},issuetype:{name:r.issueType},...r.description?{description:r.description}:{}},c=((t,e)=>{if(!e||!e.content)return t;const r=(s=e.content,n=e.placeholders,s?s.replace(ie,(t,e)=>{const r=e.trim();if(!r)return"";if(n&&Object.prototype.hasOwnProperty.call(n,r)){const t=n[r];return null==t?"":t+""}return t}):"");var s,n;if(!r.trim())return t;const i=se(r),o=(a=t.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?se(a).content:[]:[];var a;return t.description={type:"doc",version:1,content:[...o,...i.content]},t})(c,r.template);const p=t?.issues?.create??t?.issues?.createIssue;if("function"!=typeof p)throw Error("Jira client missing create function");const l=await p.call(t.issues,{fields:c}),u=l&&l.data||l;return{id:u?.id??null,key:u?.key??null}})(t,e))};class pe extends Error{constructor({code:t,message:e,details:r}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=t,this.details=r}}function le(t){if(!t)return new pe({code:"jira_error",message:"Unknown Jira error",details:{raw:t}});const e=t?.status??t?.statusCode??t?.response?.status??t?.response?.statusCode,r="number"==typeof e?e:Number(e)||void 0,s=t?.response?.data??t?.data??t?.response?.body??t?.body,n=[];"string"==typeof t?.message&&n.push(t.message),((t,e)=>{t&&(Array.isArray(t.errorMessages)&&t.errorMessages.forEach(t=>"string"==typeof t&&e.push(t)),"string"==typeof t.errorMessage&&e.push(t.errorMessage),t.errorCollection&&Array.isArray(t.errorCollection.errors)&&t.errorCollection.errors.forEach(t=>{"string"==typeof t?e.push(t):t&&"string"==typeof t.message&&e.push(t.message)}),t?.errors&&"object"==typeof t.errors&&Object.values(t.errors).forEach(t=>{"string"==typeof t?e.push(t):"string"==typeof t?.message&&e.push(t.message)}))})(s,n);const i=r?`Jira API error (${r})`:"Jira API error",o=n.length>0?n.join(" | "):i;return new pe({code:r?"jira_"+r:t?.code??"jira_error",message:o,details:{httpStatus:r,body:s,raw:t}})}const ue=v.object({issueId:v.string().min(1),deleteSubtasks:v.boolean().optional().default(!0)}),de={name:"jira-issue-delete",inputSchema:ue,runTool:async(t,e)=>{try{const r=ue.parse(e),s=t.issues??t.issue??t,n=s?.delete??s?.deleteIssue;if("function"!=typeof n)throw Error("jira client delete endpoint is not available");return await n.call(s,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),ae({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(t){throw le(t)}}},me=v.object({projectKey:v.string().trim().min(1).optional(),issueType:v.string().trim().min(1).optional(),parentIssueId:v.string().trim().min(1).optional(),name:v.string().trim().min(1).optional(),reference:v.string().trim().min(1).optional(),jql:v.string().trim().min(1).optional(),startAt:v.number().int().min(0).optional(),maxResults:v.number().int().min(1).optional(),fields:v.array(v.string()).optional(),expand:v.string().optional(),orderBy:v.string().trim().min(1).optional()});function he(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const fe={name:"jira-issue-list",inputSchema:me,runTool:async(t,e)=>{try{const r=me.parse(e),s=r.startAt??0,n=r.maxResults??50;let i=r.jql?.trim();if(i){if(r.orderBy){const t=r.orderBy.trim();t&&(i=/\border\s+by\b/i.test(i)?`${i}, ${t}`:`${i} ORDER BY ${t}`)}}else i=(t=>{const e=[];if(t.projectKey&&e.push(`project = "${he(t.projectKey)}"`),t.issueType&&e.push(`issuetype = "${he(t.issueType)}"`),t.parentIssueId&&e.push(`parent = "${he(t.parentIssueId)}"`),t.name&&e.push(`summary ~ "${he(t.name)}"`),t.reference){const r=he(t.reference);e.push(`(key ~ "${r}" OR summary ~ "${r}" OR text ~ "${r}")`)}if(0===e.length){const t=Error("Provide a jql query or at least one filter (project, name, reference, parent, issue type, etc.).");throw t.code="validation_error",t}let r=e.join(" AND ");if(t.orderBy){const e=t.orderBy.trim();e&&(r=/\border\s+by\b/i.test(r)?`${r}, ${e}`:`${r} ORDER BY ${e}`)}return r})(r);const o={jql:i,startAt:s,maxResults:n};r.fields&&(o.fields=r.fields),r.expand&&(o.expand=r.expand);const a=t.issueSearch,c=a&&"function"==typeof a.searchForIssuesUsingJqlEnhancedSearch?a.searchForIssuesUsingJqlEnhancedSearch:a&&"function"==typeof a.searchForIssuesUsingJql?a.searchForIssuesUsingJql:void 0;if(!c)throw Error("Jira search API is unavailable on the client");const p=await c.call(a,o),l=p?.data??p,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=s),void 0===u.maxResults&&(u.maxResults=n),ae(u)}catch(t){throw le(t)}}},ye=v.object({issueId:v.string().min(1),expand:v.string().optional(),fields:v.array(v.string()).optional(),properties:v.array(v.string()).optional()}),ge={name:"jira-issue-read",inputSchema:ye,runTool:async(t,e)=>{try{const r=ye.parse(e),s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand),r.fields&&(s.fields=r.fields),r.properties&&(s.properties=r.properties);const n=await t.issues.getIssue(s);return ae(n?.data??n)}catch(t){throw le(t)}}},be=v.object({issueId:v.string().min(1),transitionId:v.union([v.string(),v.number()]),fields:v.record(v.any()).optional(),update:v.record(v.array(v.object({set:v.any().optional(),add:v.any().optional(),remove:v.any().optional()}))).optional(),comment:v.string().optional()}),ve={name:"jira-issue-transition",inputSchema:be,runTool:async(t,e)=>{try{const r=be.parse(e),s={id:r.transitionId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.comment&&(s.comment={body:se(r.comment)});const n=await t.issues.transition({issueIdOrKey:r.issueId,transition:s});return ae(n?.data??n)}catch(t){throw le(t)}}},we=v.object({issueId:v.string().min(1),expand:v.string().optional()}),Se={name:"jira-transition-list",inputSchema:we,runTool:async(t,e)=>{try{const r=we.parse(e),s=t.issues;if(!s||"function"!=typeof s.getTransitions)throw Error("Jira transitions API is unavailable on the client");const n={issueIdOrKey:r.issueId};r.expand&&(n.expand=r.expand);const i=await s.getTransitions(n);return ae(i?.data??i)}catch(t){throw le(t)}}},Ie=v.object({issueId:v.string().min(1),fields:v.record(v.any()).optional(),update:v.record(v.array(v.object({set:v.any().optional(),add:v.any().optional(),remove:v.any().optional(),edit:v.any().optional()}))).optional(),properties:v.array(v.any()).optional(),notifyUsers:v.boolean().optional().default(!0),issueTemplateId:v.string().optional(),overrideScreenSecurity:v.boolean().optional().default(!1),overrideEditableFlag:v.boolean().optional().default(!1)}),je={name:"jira-issue-update",inputSchema:Ie,runTool:async(t,e)=>{try{const r=Ie.parse(e),s={issueIdOrKey:r.issueId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.properties&&(s.properties=r.properties),void 0!==r.notifyUsers&&(s.notifyUsers=r.notifyUsers),r.issueTemplateId&&(s.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(s.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(s.overrideEditableFlag=r.overrideEditableFlag);const n=await t.issues.editIssue(s);return ae(n?.data??n)}catch(t){throw le(t)}}},xe=v.object({issueId:v.string().min(1),assignee:v.union([v.string(),v.object({accountId:v.string().min(1)}),v.object({accountType:v.string().min(1)})])}),Te={name:"jira-assign-issue",inputSchema:xe,runTool:async(t,e)=>{try{const r=xe.parse(e);let s;s="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const n=await t.issues.assignIssue({issueIdOrKey:r.issueId,assignee:s});return ae(n?.data??n)}catch(t){throw le(t)}}},Ae=v.object({issueId:v.string().min(1)}),Ee={name:"jira-unassign-issue",inputSchema:Ae,runTool:async(t,e)=>{try{const r=Ae.parse(e),s=await t.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return ae(s?.data??s)}catch(t){throw le(t)}}},ke=v.object({issueId:v.string().min(1),body:v.string().min(1),visibility:v.object({type:v.enum(["role","group"]),value:v.string().min(1)}).optional()}),Oe={name:"jira-comment-add",inputSchema:ke,runTool:async(t,e)=>{try{const r=ke.parse(e),s=t.issueComments;if(!s||"function"!=typeof s.addComment)throw Error("Jira issueComments API is unavailable on the client");const n={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(n.visibility=r.visibility);const i=await s.addComment(n);return ae(i?.data??i)}catch(t){throw le(t)}}},Ne=v.object({issueId:v.string().min(1),start:v.number().optional().default(0),maxResults:v.number().optional().default(50),orderBy:v.string().optional(),expand:v.string().optional()}),Ce={name:"jira-comment-list",inputSchema:Ne,runTool:async(t,e)=>{try{const r=Ne.parse(e),s=t.issueComments;if(!s||"function"!=typeof s.getComments)throw Error("Jira issueComments API is unavailable on the client");const n=await s.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return ae(n?.data??n)}catch(t){throw le(t)}}},Je=v.object({link:v.object({relationship:v.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]),inwardIssue:v.object({id:v.string().optional(),key:v.string().optional()}),outwardIssue:v.object({id:v.string().optional(),key:v.string().optional()}),comment:v.object({body:v.string().optional(),visibility:v.object({type:v.enum(["role","group"]),value:v.string().min(1)}).optional()}).optional()})});let He=[];function _e(t){return(t||"").trim().toLowerCase()}const Pe=Je;function $e(t){if(t.id)return{id:t.id};if(t.key)return{key:t.key};throw Error("Linked issue must include an id or key")}const Re={name:"jira-link-create",inputSchema:Pe,runTool:async(t,e)=>{try{const r=Pe.parse(e).link,s={inwardIssue:$e(r.inwardIssue),outwardIssue:$e(r.outwardIssue)};if(r.comment){const t={};r.comment.body&&(t.body=se(r.comment.body)),r.comment.visibility&&(t.visibility=r.comment.visibility),Object.keys(t).length>0&&(s.comment=t)}const n=t.issueLinks;if(!n||"function"!=typeof n.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const i=await(async(t,e)=>{if(!e)throw Error("Link relationship is required");if(0===He.length){const e=t.issueLinkTypes;if(!e||"function"!=typeof e.getIssueLinkTypes)throw Error("Jira issueLinkTypes API is unavailable on the client");const r=await e.getIssueLinkTypes();He=r?.issueLinkTypes??r?.values??[]}const r=_e(e),s=He.find(t=>[t.name,t.inward,t.outward].some(t=>_e(t)===r));if(!s)throw Error(`No issue link type matching '${e}' found.`);return s})(t,r.relationship);s.type={id:i.id};const o=await n.linkIssues(s);return ae(o?.data??o)}catch(t){throw le(t)}}},De=v.object({issueId:v.string().min(1),file:v.string().min(1),mimeType:v.string().optional(),comment:v.string().optional()}),qe={name:"jira-attach",inputSchema:De,runTool:async(t,e)=>{try{const r=De.parse(e),n=A.resolve(r.file),i=await s.readFile(n),o=A.basename(n),a=new FormData;a.append("file",new Blob([i],{type:r.mimeType??"application/octet-stream"}),o);const c=t?.config??null,p=c?.host,l=c?.authentication?.basic??c?.authentication??c?.auth??null,u=l?.email,d=l?.apiToken??l?.apiKey;if(!p||!u||!d)throw Error("Jira client authentication configuration is unavailable for attachments");const m=await fetch(`${p}/rest/api/3/issue/${r.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${u}:${d}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:a});if(!m.ok){const t=await m.text();throw Error(`Jira attachment upload failed (${m.status}): ${t}`)}const h=await m.json();if(r.comment){const e=t.issueComments;if(!e||"function"!=typeof e.addComment)throw Error("Jira issueComments API is unavailable on the client");await e.addComment({issueIdOrKey:r.issueId,comment:se(r.comment)})}return ae(h)}catch(t){if(t&&t.code&&"string"==typeof t.code&&["ENOENT","EACCES"].includes(t.code))throw Error("Attachment file error: "+t.message);throw le(t)}}},Me=v.object({issueId:v.string().min(1)}),Be={name:"jira-attachment-list",inputSchema:Me,runTool:async(t,e)=>{try{const r=Me.parse(e),s=t.issues;if(!s||"function"!=typeof s.getIssue)throw Error("Jira issues API is unavailable on the client");const n=await s.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),i=n?.data??n;return ae({attachments:i?.fields?.attachment??[]})}catch(t){throw le(t)}}},Ue=v.object({issueId:v.string().min(1),attachmentId:v.string().min(1)}),Ke={name:"jira-attachment-delete",inputSchema:Ue,runTool:async(t,e)=>{try{const r=Ue.parse(e),s=t.issueAttachments;if(!s||"function"!=typeof s.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await s.removeAttachment({id:r.attachmentId}),ae({success:!0,message:`Attachment ${e.attachmentId} deleted successfully`})}catch(t){throw le(t)}}},Fe=v.object({issueId:v.string().min(1),timeSpent:v.string().min(1),comment:v.string().optional(),author:v.object({accountId:v.string().min(1)}).optional(),startingOn:v.string().optional(),artifact:v.string().optional()}),Le={name:"jira-worklog-add",inputSchema:Fe,runTool:async(t,e)=>{try{const r=Fe.parse(e),s={timeSpent:r.timeSpent};r.comment&&(s.comment=r.comment),r.author&&(s.author=r.author),r.startingOn&&(s.started=r.startingOn),r.artifact&&(s.artifact=r.artifact);const n=t.issueWorklogs;if(!n||"function"!=typeof n.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const i=await n.addWorklog({issueIdOrKey:r.issueId,...s});return ae(i?.data??i)}catch(t){throw le(t)}}};class We{constructor(){this.clientId=Nt.orThrow().xray.apiUser,this.clientSecret=Nt.orThrow().xray.apiSecret,this.baseUrl=Nt.orThrow().xray.host||"https://eu.xray.cloud.getxray.app"}async authenticate(){if(!this.clientId||!this.clientSecret)throw Error("Xray API credentials are missing (XRAY__API_USER, XRAY__API_SECRET).");const t=await fetch(this.baseUrl+"/api/v2/authenticate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId,client_secret:this.clientSecret})}),e=await t.text();return this.token=e.replace(/"/g,""),this.token}async graphql(t,e){this.token||await this.authenticate();const r=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify({query:t,variables:e})}),s=await r.json();if(s.errors)throw Error(JSON.stringify(s.errors,null,2));return s.data}async getTest(t){return(await this.graphql('\n query GetTest($issueId: String!) {\n getTest(issueId: $issueId) {\n issueId\n jira(fields:["key"])\n steps {\n id\n action\n data\n result\n }\n }\n }\n ',{issueId:t})).getTest}async addStep(t,e){return(await this.graphql("\n mutation AddTestStep($issueId: String!, $step: CreateStepInput!) {\n addTestStep(issueId: $issueId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{issueId:t,step:e})).addTestStep}async updateStep(t,e){return(await this.graphql("\n mutation UpdateTestStep($stepId: String!, $step: UpdateStepInput!) {\n updateTestStep(stepId: $stepId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{stepId:t,step:e})).updateTestStep}async deleteStep(t){return(await this.graphql("\n mutation RemoveTestStep($stepId: String!) {\n removeTestStep(stepId: $stepId)\n }\n ",{stepId:t})).removeTestStep}async addSteps(t,e){return Promise.all(e.map(e=>this.addStep(t,e)))}async updateSteps(t){return Promise.all(t.map(t=>this.updateStep(t.stepId,t.step)))}async deleteSteps(t){return Promise.all(t.map(t=>this.deleteStep(t)))}async syncSteps(t,e){const r=(await this.getTest(t)).steps||[],s=[],n=[],i=[];for(let t=0;t<e.length;t++){const i=e[t],o=r[t];o?o.action===i.action&&o.data===i.data&&o.result===i.result||s.push({stepId:o.id,step:i}):n.push(i)}if(r.length>e.length)for(let t=e.length;t<r.length;t++)i.push(r[t].id);await this.addSteps(t,n),await this.updateSteps(s),await this.deleteSteps(i)}}let Ye=null;const Xe=new Map;function ze(t){const e=t?.fields,r=t?.action??e?.Action??e?.action;if(!r||"string"!=typeof r)throw Error("Xray step action is required");const s=t.data??t.fields?.Data??t.fields?.data??void 0,n=t.result??t.fields?.Result??t.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof s?s:void 0,result:"string"==typeof n?n:void 0}}async function Ge(t,e){if(!e)throw Error("Issue reference is required when interacting with Xray steps");if(Xe.has(e))return Xe.get(e);if(/^[0-9]+$/.test(e))return Xe.set(e,e),e;const r=t?.issues??t?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const s=await r.getIssue({issueIdOrKey:e,fields:["id"]}),n=s?.id;if(!n)throw Error("Unable to resolve Jira issue ID for "+e);return Xe.set(e,n),n}async function Ze(t){if(t?.test?.step)return t.test.step;const e=await(async()=>{if(Ye)return Ye;const t=Nt.orThrow().xray.apiUser?.trim(),e=Nt.orThrow().xray.apiSecret?.trim();if(!t||!e)throw Error("Xray credentials are missing (XRAY__API_USER, XRAY__API_SECRET). Please configure them before using Xray tools.");const r=Pt(),s=new We;return Ye={test:{step:{async createStep(t,e){const n=await Ge(r,t),i=await s.addStep(n,ze(e));return{step:i,id:i?.id}},async updateStep(t,e,n){await Ge(r,t);const i=ze(n),o=await s.updateStep(e.toString(),i);return{step:o,id:o?.id}},deleteStep:async(t,e)=>(await Ge(r,t),{success:!0===await s.deleteStep(e.toString())}),async getSteps(t){const e=await Ge(r,t),n=await s.getTest(e);return{steps:n?.steps??[]}}}}},Ye})();if(!e?.test?.step)throw Error("Xray step API is unavailable on the client");return e.test.step}const Ve=v.object({issueId:v.string().min(1),action:v.string().min(1),data:v.string().optional(),result:v.string().optional()}),Qe={name:"jira-xray-step-add",inputSchema:Ve,runTool:async(t,e)=>{try{const r=Ve.parse(e),s=await Ze(t),n={action:r.action,data:r.data,result:r.result};return ae(await s.createStep(r.issueId,n))}catch(t){throw le(t)}}},tr=v.object({issueId:v.string().min(1),stepId:v.union([v.string(),v.number()]),action:v.string().min(1),data:v.string().optional(),result:v.string().optional()}),er={name:"jira-xray-step-update",inputSchema:tr,runTool:async(t,e)=>{try{const r=tr.parse(e),s=await Ze(t),n=r.stepId+"",i={action:r.action,data:r.data,result:r.result};return ae(await s.updateStep(r.issueId,n,i))}catch(t){throw le(t)}}},rr=v.object({issueId:v.string().min(1),stepId:v.union([v.string(),v.number()])}),sr={name:"jira-xray-step-delete",inputSchema:rr,runTool:async(t,e)=>{try{const r=rr.parse(e),s=await Ze(t),n=Number(r.stepId);return await s.deleteStep(r.issueId,n),ae({success:!0})}catch(t){throw le(t)}}},nr=v.object({issueId:v.string().min(1)}),ir={name:"jira-xray-step-list",inputSchema:nr,runTool:async(t,e)=>{try{const r=nr.parse(e),s=await Ze(t);return ae(await s.getSteps(r.issueId))}catch(t){throw le(t)}}},or={[ce.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ge.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[fe.name]:{title:"Jira Issue List",description:"Search issues by summary, reference, parent, or JQL and list the matching tickets",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[je.name]:{title:"Jira Issue Update",description:"Update a Jira issue using fields, update ops, and property toggles",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[de.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[ve.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Se.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Te.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ee.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Oe.name]:{title:"Jira Comment Add",description:"Add a comment to a Jira issue with optional visibility",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ce.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Re.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[qe.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Be.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ke.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Le.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Qe.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[er.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[sr.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[ir.name]:{title:"Jira Xray Step List",description:"List steps for an Xray test case",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}};async function ar(t){const e=o.for(ar);let r,s=null;try{r=Pt()}catch(t){if(!(t instanceof _t))return void e.warn("Skipping Jira tool registration; unable to create Jira client",{error:t});s=t,e.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:t})}const n=[ce,ge,fe,je,de,ve,Se,Te,Ee,Oe,Ce,Re,qe,Be,Ke,Le,Qe,er,sr,ir];for(const i of n){const n=or[i.name];if(n)try{await t.registerTool(i.name,{title:n.title,description:n.description,inputSchema:i.inputSchema,annotations:n.annotations},async t=>{if(!r)throw s??Error("Jira client unavailable because credentials could not be loaded.");return i.runTool(r,t)}),e.info("Registered Jira tool "+i.name)}catch(t){e.error("Failed to register Jira tool "+i.name,{error:t})}}}async function cr(t){await(async t=>{t.registerTool("decaf-server-info",{title:"Decaf MCP Server Info",description:"Return server metadata, version, and registered prompt names for diagnostics.",inputSchema:{},outputSchema:void 0,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{const t=It.map(t=>t.getName()).sort();return{content:[{type:"text",text:["Name: "+Nt.name,"Title: "+Nt.title,"Version: "+Nt.version,"Prompts: "+(t.join(", ")||"<none>")].join("\n")}]}})})(t);const e=o.for(cr);try{await ar(t)}catch(t){e.error("Failed to register Jira tools",t)}}class pr extends Z{setCb(t){return this.cb=t,this}setConfig(t){return this.config=t,this}setUriOtTemplate(t){return this.uriOrTemplate=t,this}constructor(t){super(t)}static get builder(){return new pr}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{const e="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new q(new D(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),s=async(t,e)=>{const r=this.logFor(e);r.verbose(`Requesting resource ${this.name} from ${t.toString()}`);const s=await Promise.resolve(this.cb(t,e));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(s._meta)),s};return t.resource(this.name,e,r,s)}catch(t){throw o.for(this).error("Error registering resource "+this.name,t),t}}}m([f(),h("design:type",String)],pr.prototype,"uriOrTemplate",void 0),m([f(),h("design:type",Function)],pr.prototype,"cb",void 0),m([f(),h("design:type",Object)],pr.prototype,"config",void 0);const lr=ut()??T.join(__dirname,"..","assets"),ur=T.join(lr,"templates"),dr=T.join(lr,"prompts"),mr=new WeakMap;class hr extends a{get client(){const t=mr.get(this);if(!t)throw Error("Mcp server requires Mcp client");return t}constructor(){super()}async load(){const t=this.log.for(this.load);for(const e of It)try{t.info("loading prompt "+e.getName());const r=e.build(this.client);t.verbose(`Loaded prompt ${r.title} from ${e.getName()} definition`)}catch(r){t.error("Failed to load prompt "+e.getName(),r)}try{await cr(this.client),t.verbose("Registered built-in tools")}catch(t){}try{await(async(t,r)=>{r.info("Registering agent templates as resources...");const s=e.readdirSync(ur).filter(t=>t.endsWith(".md"));for(const n of s){const s=T.basename(n,".md"),i=T.join(ur,n),o=pr.builder.setName(s).setTitle("Template: "+s).setDescription("Resource template for "+s).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+s}).setCb(async t=>{const r=e.readFileSync(t.pathname,"utf8");return{contents:[{uri:t.toString(),text:r,mimeType:"text/markdown"}],_meta:{}}});try{o.build(t),r.info("Registered template: "+s)}catch(t){r.error(`Failed to register template ${s}:`,t)}}r.info("Registering agent prompts...");const n=e.readdirSync(dr).filter(t=>t.endsWith(".md"));for(const s of n){const n=T.basename(s,".md"),i=T.join(dr,s),o=e.readFileSync(i,"utf8"),a=mt.builder.setName(n).setTitle("Prompt: "+n).setDescription("Dynamic prompt for "+n).setArgsSchema(v.object({})).setCb(async t=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(t),r.info("Registered prompt: "+n)}catch(t){r.error(`Failed to register prompt ${n}:`,t)}}})(this.client,t)}catch(t){}}async boot(t="stdio"){"stdio"===t&&o.setFactory(L),o.for(this.constructor.name);const e=((Array.isArray(Nt.icons)?Nt.icons:[Nt.icons])||[]).map(t=>{const e="string"==typeof t?.src?t.src:(t?.src??"")+"",r="string"==typeof t?.mimeType?t.mimeType:(t?.mimeType??"")+"";let s=[];return Array.isArray(t?.sizes)?s=t.sizes.map(t=>t+""):"string"==typeof t?.sizes&&(s=(t.sizes+"").split(",").map(t=>t.trim())),{src:e,mimeType:r,sizes:s}}),r={name:Nt.name,title:Nt.title,websiteUrl:Nt.websiteUrl,version:Nt.version,icons:e},s=new M(r,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((t,e)=>{mr.set(t,e)})(this,s),s.onerror=t=>{this.log.error("MCP instance onerror",t)},t){case"stdio":t=new U;break;case"http":t=new K({sessionIdGenerator:()=>B(),onsessioninitialized:t=>{},onsessionclosed:t=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(n=t)||"object"!=typeof n||"function"!=typeof n.send&&"function"!=typeof n.close&&"function"!=typeof n.on)throw new E("Invalid transport type: "+t)}var n;try{await this.load()}catch(t){throw t}await this.client.connect(t)}}const fr=(new t).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async t=>{const e=pt("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version,{transport:i}=t,o=(new F).for("mcp-server");if("stdio"!==i)throw Error("Unsupported transport mode: "+i);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(t)} for ${s.name} version ${n}`),(new hr).boot(i)});(new t).command("md-to-ast").description("pipes markdown to jira ast: `cat file.md` | npx decaf-mcp md-to-ast > ast.json").action(async t=>{const e=pt("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version;o.for("md-to-ast").debug(`running with options: ${JSON.stringify(t)} for ${s.name} version ${n}`);const i=se(await(async()=>{const t=[];for await(const e of process.stdin)t.push(Buffer.from(e));return Buffer.concat(t).toString("utf8")})(),{resolveMention:t=>({id:t,text:"@"+t}),resolveAttachment:t=>({id:t,collection:"attachments"})});process.stdout.write(JSON.stringify(i,null,2)+"\n")});const yr=(new t).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");yr.addCommand(fr),yr.parse(process.argv);
1
+ import{Command as t}from"commander";import*as e from"fs";import n,{promises as r}from"fs";import{MiniLogger as s,NumericLogLevels as i,Logging as o,LoggedClass as a,toSnakeCase as c,sf as p,toPascalCase as l,LogLevel as u,LoggedEnvironment as d}from"@decaf-ts/logging";import{__decorate as m,__metadata as h}from"tslib";import{required as f,Model as y,list as g,minlength as b}from"@decaf-ts/decorator-validation";import{z as w,ZodObject as v}from"zod";import{injectable as I,inject as S}from"@decaf-ts/injectable-decorators";import{prop as j,Metadata as x}from"@decaf-ts/decoration";import*as k from"path";import A from"path";import{InternalError as T,SerializationError as E,ValidationError as O}from"@decaf-ts/db-decorators";import H from"crypto";import J from"zlib";import{fileURLToPath as N}from"url";import{unified as C}from"unified";import _ from"remark-directive";import P from"remark-gfm";import $ from"remark-parse";import{inspect as R}from"node:util";import{UriTemplate as D}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";import{ResourceTemplate as q,McpServer as L}from"@modelcontextprotocol/sdk/server/mcp.js";import{v4 as M}from"uuid";import{StdioServerTransport as U}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as B}from"@modelcontextprotocol/sdk/server/streamableHttp.js";class K extends s{constructor(t,e,n){super(t,e,n)}log(t,e,n,r){const s=this.config("level");i[s],i[t]}}const F=(t,e,...n)=>{const r=(t=>{if("string"==typeof t)return t;if(!t)return"unknown";if("function"==typeof t)return t.name||"unknown";if("object"==typeof t&&"constructor"in t){const e=t.constructor;if(e&&e.name)return e.name}return"unknown"})(t);return new K(r,e)};var W,Y,X,z,G;(t=>{t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.ADVANCED=2]="ADVANCED",t[t.HIGH=3]="HIGH"})(W||(W={})),(t=>{t[t.NONE=0]="NONE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(Y||(Y={})),(t=>{t[t.FREE=0]="FREE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(X||(X={}));class Z extends y{get log(){return this._log||(this._log=o.for(this)),this._log}constructor(t){super(t)}logFor(t){const{sessionId:e,requestId:n,authInfo:r}=t||{};let s="string"==typeof e&&e.length>0?this.log.for(e):this.log;return r&&r.clientId&&(s=s.for(r.clientId)),n&&(s=s.for(n.toString())),s}setDescription(t){return this.description=t,this}getDescription(){return this.description}setName(t){return this.name=t,this}getName(){return this.name}setTitle(t){return this.title=t,this}}m([f(),h("design:type",String)],Z.prototype,"description",void 0),m([f(),h("design:type",String)],Z.prototype,"name",void 0),m([f(),h("design:type",String)],Z.prototype,"title",void 0);class V extends Z{constructor(t){super(t),this.reasoning=W.NONE,this.effort=Y.NONE,this.cost=X.FREE}setReasoning(t){return this.reasoning=t,this}setEffort(t){return this.effort=t,this}setCost(t){return this.cost=t,this}}function Q(t){if(!t)return;let e=t,n=e&&e._def;for(;n&&"ZodObject"!==n.typeName;){if("ZodEffects"===n.typeName&&n.schema)e=n.schema;else if("ZodOptional"===n.typeName&&n.innerType)e=n.innerType;else if("ZodDefault"===n.typeName&&n.innerType)e=n.innerType;else if("ZodNullable"===n.typeName&&n.innerType)e=n.innerType;else{if(!n.schema)return;e=n.schema}n=e&&e._def}return n&&"ZodObject"===n.typeName?n:void 0}function tt(t,e="schema"){if(Q(t))return t;if(t&&"object"==typeof t){const e=t.def&&"object"==typeof t.def?t.def:void 0,n=e&&(e.shape||"object"===e.type)&&e.shape||("object"===t.type?t.shape:void 0)||(e&&"object"===e.type?{}:void 0);if(e||"object"===t.type||n){const t={};if(n&&"object"==typeof n)for(const[e,r]of Object.entries(n))t[e]=nt(r)?r:w.any();return w.object(t)}}throw Error(`Registration error: provided a non-canonical ${e}. Export a ZodObject (z.object(...)).`)}function et(t){if(!t)return;if(t&&"object"==typeof t&&!t._def)return t.def&&"object"==typeof t.def&&t.def.shape?t.def.shape:t;const e=Q(t);return e?"function"==typeof e.shape?e.shape():e.shape||void 0:void 0}function nt(t){return!(!t||"object"!=typeof t||!t._def)}m([f(),h("design:type",Number)],V.prototype,"reasoning",void 0),m([f(),h("design:type",Number)],V.prototype,"effort",void 0),m([f(),h("design:type",Number)],V.prototype,"cost",void 0),(t=>{t.ASSETS="assets"})(z||(z={})),(t=>{t.PROMPT="prompts",t.DOCUMENTATION="documentation",t.CODE="code"})(G||(G={}));const rt=Buffer.from("DCAF1","ascii");function st(t){let e=A.resolve(t);for(;;){if(n.existsSync(A.join(e,"package.json")))return e;const t=A.dirname(e);if(t===e)break;e=t}}const it=process.argv?.[1]?st(A.dirname(A.resolve(process.argv[1]))):void 0,ot=(()=>{const t=Error().stack;if(!t)return;const e=t.split(/\r?\n/).slice(1);for(const t of e){const e=t.match(/\(?([^()]+?):\d+:\d+\)?/);if(!e)continue;let n=e[1];if(n.startsWith("file://"))try{n=N(n)}catch{continue}if(!n.includes("node:internal"))return A.dirname(n)}})(),at=ot?st(ot):void 0,ct=it??at??process.cwd();function pt(...t){return A.join(ct,...t)}function lt(t){let n=t;for(;;){const t=k.join(n,"lib","assets");if(e.existsSync(t))return t;const r=k.join(n,"src","assets");if(e.existsSync(r))return r;const s=k.join(n,"assets");if(e.existsSync(s))return s;const i=k.dirname(n);if(i===n)break;n=i}}function ut(){const t=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(t&&e.existsSync(t))return t;const n=lt(__dirname);if(n)return n;const r=process.argv?.[1];if(r){const t=lt(k.dirname(r));if(t)return t}const s=[ct,process.env.INIT_CWD].filter(Boolean);for(const t of s){const e=lt(t);if(e)return e}return pt("assets")}let dt=class extends a{constructor(t){super(),this.basePath=t||ut()}listAssets(...t){const n=k.join(this.basePath,...t);return e.readdirSync(n)}listPrompts(){return this.listAssets(G.PROMPT)}getAsset(t,n="md",...r){const s=k.join(this.basePath,...r),i=(t,n=!1)=>{try{return n?(t=>{if(t.length<rt.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!t.subarray(0,rt.length).equals(rt))throw Error("Invalid prompt payload (bad magic)");const e=process.env.ENCRYPTION_KEY||"";if(!e)throw Error("Missing encryption key. Set ENCRYPTION_KEY to load obfuscated assets.");let n=rt.length;const r=t.subarray(n,n+16);n+=16;const s=t.subarray(n,n+12);n+=12;const i=t.subarray(n,n+16);n+=16;const o=t.subarray(n),a=((t,e)=>H.scryptSync(t,e,32))(e,r),c=H.createDecipheriv("aes-256-gcm",a,s);c.setAuthTag(i);const p=Buffer.concat([c.update(o),c.final()]);return J.gunzipSync(p)})(e.readFileSync(t)).toString("utf-8"):e.readFileSync(t,"utf-8")}catch(t){if("ENOENT"===t.code)return null;throw t}},o=i(k.join(s,`${t}.${n}`),"enc"===n);if(null!==o)return o;const a=i(k.join(s,t+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+k.join(s,`${t}.${n}`))}getAllAssets(t,...e){return this.listAssets(t,...e).reduce((n,r)=>{const s=k.extname(r),i=k.basename(r,s),o=s.replace(/^\./,"")||void 0;return n[i]=this.getAsset(i,o??void 0,t,...e),n},{})}toPromptDef(t){const e=t=>"number"==typeof t?t:"string"==typeof t?(t=>{switch(t){case"none":return W.NONE;case"basic":return W.BASIC;case"advanced":return W.ADVANCED;case"high":return W.HIGH;case"medium":return Y.MEDIUM;case"low":return X.LOW;case"free":return X.FREE;default:throw new T("Cannon convert unknown level "+t)}})(t.toLowerCase()):W.NONE;return t.effort=e(t.effort),t.reasoning=e(t.reasoning),t.cost=e(t.cost),t}getPrompt(t,...e){const n=this.getAsset(c(t),"json",G.PROMPT,...e);let r;try{r=JSON.parse(n)}catch(n){throw new E(`Failed to parse prompt ${t} in categories ${e}: ${n}`)}return this.toPromptDef(r)}getAllPrompts(...t){const e=this.getAllAssets(G.PROMPT,...t);return Object.entries(e).reduce((e,[n,r])=>{try{e[n]=JSON.parse(r)}catch(e){throw new E(`Failed to parse prompt ${n} in categories ${t}: ${e}`)}return e},e)}};dt=m([I(),h("design:paramtypes",[String])],dt);class mt extends V{constructor(t){super(t)}setCb(t){return this.cb=t,this}setArgsSchema(t){return this.argsSchema=t,this}static get builder(){return new mt}static patchPrompt(t,e,n,r){const s=(e=Array.isArray(e)?e:Object.keys(e)).filter(t=>!Object.prototype.hasOwnProperty.call(n,t));if(s.length)throw new O("Missing replacements for placeholders: "+s.join(", "));r&&(r.verbose("Patching prompt with placeholders: "+JSON.stringify(e)),r.debug("Values: "+JSON.stringify(n)));const i=e.reduce((t,e)=>(t[e]=n[e],t),{});return p(t,i)}patchPrompt(t,e,n,r){return mt.patchPrompt(t,e,n,r||this.log.for(this.patchPrompt))}build(t,e){const n=this.log.for(this.build),r=this.hasErrors();if(r)throw new O(r.toString());try{this.argsSchema&&tt(this.argsSchema,"argsSchema");const n=et(this.argsSchema);return t.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:n},async(t,n)=>{const r=this.logFor(n);t=Object.assign({},e,t||{}),r.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(t)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(t,n));return r.verbose(`Prompt ${this.name} executed successfully.`),r.debug("Prompt execution meta: "+JSON.stringify(s._meta)),s})}catch(t){throw n.error("Failed to register prompt "+(this.name||this.constructor.name),t),t}}}m([S(dt),h("design:type",dt)],mt.prototype,"assets",void 0),m([f(),h("design:type",Object)],mt.prototype,"cb",void 0),m([f(),h("design:type",v)],mt.prototype,"argsSchema",void 0),m([j(),h("design:type",Object)],mt.prototype,"placeholders",void 0);class ht extends mt{setCategory(t){return this.promptCategory=t,this}addPrefix(t){return this.prefixes=this.prefixes||[],this.prefixes.push(t),this}addSuffix(t){return this.suffixes=this.suffixes||[],this.suffixes.push(t),this}constructor(t){super(t)}build(t){const e=this.assets.getPrompt(this.name,this.promptCategory);y.fromObject(this,e);const n=new Set((x.properties(ht)||[]).filter(t=>!["assets","promptCategory","prefixes","suffixes"].includes(t)));["cb","argsSchema"].forEach(t=>n.add(t));const r=this.hasErrors(...Array.from(n));if(r)throw new O(r.toString());const s=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=[...new Set([...e.placeholders,...s.map(t=>t.placeholders||[]),...i.map(t=>t.placeholders||[])].flat())].reduce((t,e)=>(t[e]=w.string().describe("The description for "+e),t),{});return this.setArgsSchema(w.object(o)),this.setCb((t,e)=>{const n=this.logFor(e).for(ht).for(this.promptCategory).for(this.name);function r(t=[]){return Array.isArray(t)?t:Object.keys(t)}const s=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...s.map(t=>r(t.placeholders)).flat(),...i.map(t=>r(t.placeholders)).flat(),...r(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...s.map(t=>t.prompt),o.prompt,...i.map(t=>t.prompt)].join("\n\n"),a,t,n)}}],_meta:{}}}),super.build(t)}setReasoning(t){throw new T("Named prompt builders don't require callback")}setEffort(t){throw new T("Named prompt builders don't require callback")}setCost(t){throw new T("Named prompt builders don't require callback")}setDescription(t){throw new T("Named prompt builders don't require callback")}setTitle(t){throw new T("Named prompt builders don't require callback")}static get builder(){return new ht}}m([f(),h("design:type",String)],ht.prototype,"promptCategory",void 0),m([g(String),b(1),h("design:type",Array)],ht.prototype,"prefixes",void 0),m([b(1),g(String),h("design:type",Array)],ht.prototype,"suffixes",void 0);const ft=mt.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(w.object({message:w.string().optional()})).setCb(async t=>{const e=t.message??"default";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),yt=mt.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc prompt").setDescription("Interactive prompt for jogging JSDoc helpers").setArgsSchema(w.object({gist:w.string().optional()})).setCb(async t=>{const e=t.gist??"interactive jsdoc response";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),gt=Object.assign(yt,{name:yt.getName()});var bt;function wt(t,e=[],n=[]){const r=ht.builder.setCategory(bt.DOCS).setName(t);return["prefix",...e].forEach(t=>r.addPrefix(t)),["suffix",...n].forEach(t=>r.addSuffix(t)),r}(t=>{t.DOCS="documentation",t.CODE="code"})(bt||(bt={}));const vt=[wt("class"),wt("constant"),wt("decorator"),wt("function"),wt("module"),wt("file"),wt("repo",[],["iterate"])],It=w.object({className:w.string().describe("the class name to turn into a builder")}),St=[ft,gt,...vt,mt.builder.setName("ts-code-dp-builder").setTitle("Typescript builder design patter prompt").setDescription("for a class, with a defined set of properties, scafold a builder design pattern").setArgsSchema(It).setReasoning(W.BASIC).setCb((t,e)=>(t.className=l(t.className),{messages:[{role:"user",content:{type:"text",text:`You're a senior TypeScript developer writing typescript code.You're a senior TypeScript developer writing typescript code.\nTransform the selected class into a builder design pattern implementation in Typescript.\nuse @decaf-ts validation decorators to enforce the validation of your builder.\n\n- must extend the Model Class from @decaf-ts/decorator-validation;\n- each property must be marked as protected;\n- each property must have a setter method that returns 'this' for chaining;\n- the build() method must validate the properties using hasErrors() method from Model class;\n- if validation fails, throw an error with the validation errors;\n- if validation passes, return an instance of the original class with the set properties;\n- optionally (but do so by default) add the static builder and from methods from the example;\n- if the clasee already follows the pattern but has properties without decoration or without setters, simple add them;\n\nexample:\n\noriginal class:\n\`\`\`typescript\nexport class ${t.className} {\n description!: string;\n name!: string = "default name";\n title!: string;\n age?: string;\n dateOfBirth!: Date;\n}}\n\`\`\` \n\nresulting builder pattern implementation:\n\`\`\`typescript\nexport class ${t.className}Builder extends Model {\n\n @minlength(10\n @required()\n protected description!: string;\n \n @required()\n protected name!: string = "default value;\n \n @required()\n protected title!: string;\n \n @min(18)\n protected age?: string;\n \n @date()\n protected dateOfBirth!: Date;\n\n protected constructor(arg?: ModelArg<${t.className}Builder>>) {\n super(arg);\n Model.fromModel(this, arg);\n }\n\n setDescription(value: string) {\n this.description = value;\n return this;\n }\n\n setName(value: string) {\n this.name = value;\n return this;\n }\n\n setTitle(value: string) {\n this.title = value;\n return this;\n }\n setAge(value: number) {\n this.age = value;\n return this;\n }\n setDate(value: Date) {\n this.age = value;\n return this;\n }\n \n build(...args: any[]): ${t.className}Builder | Promise<${t.className}Builder> {\n const errs = this.hasErrors();\n if (errs) throw new Error(errs.toString());\n \n return // code that builds OBJ here\n }\n \n static get builder(): ${t.className}Builder {\n return new ${t.className}Builder(); // static method to get a new builder instance\n }\n \n static from<K extends keyof ${t.className}Builder>(obj: K, ${t.className}Builder[K]): ${t.className}Builder {\n return new ${t.className}Builder(); // static method to create a builder from an object\n }\n}\n\`\`\` \n\n`}}],_meta:{}}))];class jt extends V{setAnnotations(t){return this.annotations=Object.assign(this.annotations,t),this}setCb(t){return this.cb=t,this}setInputSchema(t){return this.inputSchema=t,this}setOutputSchema(t){return this.outputSchema=t,this}constructor(t){super(t),this.annotations={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}static get builder(){return new jt}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{this.inputSchema&&tt(this.inputSchema,"inputSchema"),this.outputSchema&&tt(this.outputSchema,"outputSchema");const e=et(this.inputSchema),n=et(this.outputSchema);return t.registerTool(this.name,{title:this.title,description:this.description,inputSchema:e,outputSchema:n,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(t,e)=>{const n=this.logFor(e);n.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(t)}`),e._meta=Object.assign(e._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const r=await Promise.resolve(this.cb(t,e));return n.verbose(`Tool ${this.name} executed successfully.`),n.debug("Tool execution meta: "+JSON.stringify(r._meta)),r})}catch(t){const e=t?.message||t+"";if("string"==typeof e&&e.includes("already registered"))return o.for(this).warn(`Tool ${this.name} already registered - skipping duplicate registration`),{name:this.name};throw o.for(this).error("Error building tool",t),t}}}m([f(),h("design:type",Object)],jt.prototype,"annotations",void 0),m([f(),h("design:type",Object)],jt.prototype,"cb",void 0),m([f(),h("design:type",Function)],jt.prototype,"inputSchema",void 0);const xt=jt.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(w.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(xt,{name:xt.getName()});const kt=jt.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(w.object({filePath:w.string().optional()})).setCb(async()=>({content:[{type:"text",text:"file summary stub"}],result:{summary:"file summary stub"}}));function At(){try{let t=process.argv[1]?A.dirname(A.resolve(process.argv[1])):process.cwd();for(;;){const e=A.join(t,"package.json");if(n.existsSync(e))return JSON.parse(n.readFileSync(e,"utf-8"));const r=A.dirname(t);if(r===t)break;t=r}}catch{}return{}}Object.assign(kt,{name:kt.getName()});const Tt=At().version??"0.0.0",Et=At().name??"unknown";x.registerLibrary(Et,Tt);const Ot={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:Tt,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:ct,assetDir:ut(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0},xray:{host:process.env.XRAY__HOST||process.env.XRAY__API_HOST||"https://xray.cloud.getxray.app",apiUser:process.env.XRAY__API_USER||"",apiSecret:process.env.XRAY__API_SECRET||""},level:u.error},Ht=d.accumulate(Ot);function Jt(){const{host:t,email:e,apiKey:n,projectKey:r,issueType:s}=Ht.jira;return{host:t?.trim(),email:e?.trim(),apiKey:n?.trim(),projectKey:r?.trim(),issueType:s?.trim(),parentIssue:Ht.jira.parentIssue?.trim()}}function Nt(){const t=Jt();return[{name:"JIRA__HOST",required:!0,description:"Atlassian host (e.g. decaf-ts.atlassian.net) where your Jira instance is hosted.",value:t.host},{name:"JIRA__EMAIL",required:!0,description:"Email address of the Jira account that has API access.",value:t.email},{name:"JIRA__API_KEY",required:!0,description:"API token created in your Atlassian profile (a.k.a. APIKEY alias) for authenticating requests.",sensitive:!0,value:t.apiKey},{name:"JIRA__PROJECT_KEY",required:!1,description:"Default Jira project key (e.g. DECAF) used when an issue creation request omits a project.",value:t.projectKey},{name:"JIRA__ISSUE_TYPE",required:!1,description:"Default Jira issue type (e.g. Task, Bug) used when creating issues without an explicit type.",value:t.issueType},{name:"JIRA__PARENT_ISSUE",required:!1,description:"Default parent issue key (e.g. DECAF-123) applied when a child issue is created without an explicit parent.",value:t.parentIssue}]}function Ct(t){const e=t.value?((t,e)=>{if(t)return e?"<configured>":t})(t.value,t.sensitive):"not set",n=t.required?"(required)":"(optional)";return`\u2022 ${t.name} ${n}: ${t.description} Current state: ${e}.`}o.setConfig(Ht);class _t extends Error{constructor(t){const e=Nt(),n=(t=>{const e=Nt();return`${t.length?`Missing Jira credentials: ${t.map(t=>t.name).join(", ")}.`:"Jira credentials are configured."}\n\nThis setup uses the following environment variables:\n${e.map(Ct).join("\n")}`})(t);super(n),this.name="MissingJiraEnvironmentError",this.descriptors=e,this.missing=t,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,_t)}}function Pt(t){let e;try{const t=require("jira.js");e=t?.Version3Client||t.default?.Version3Client||t.default||t}catch(t){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+t)}const{host:n,email:r,apiKey:s}=(()=>{const t=Jt(),e=Nt().filter(t=>t.required&&!t.value);if(e.length>0)throw new _t(e);return{host:t.host,email:t.email,apiKey:t.apiKey}})();return new e({host:n.startsWith("http://")||n.startsWith("https://")?n:"https://"+n,authentication:{basic:{email:r,apiToken:s}}})}const $t=w.object({name:w.string().min(1).optional(),content:w.string().min(1),placeholders:w.record(w.string()).optional()}),Rt=w.object({template:$t.optional()}),Dt=w.union([w.object({fields:w.record(w.any())}).merge(Rt),w.object({summary:w.string().min(1),projectKey:w.string().min(1),issueType:w.string().min(1),description:w.string().optional()}).merge(Rt)]);function qt(t,e,n){const r=((t.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!r)return null;const s=r[2],i=n.resolveAttachment?.(s);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Lt(t,e){if(!t)return[];if(!e.enableAtMentions&&!e.enableEmojiShortcodes)return[{type:"text",text:t}];let n=0;const r=[],s=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;n<t.length;){const o=Ut(e.enableAtMentions?Mt(s,t,n):null,e.enableEmojiShortcodes?Mt(i,t,n):null);if(!o){r.push({type:"text",text:t.slice(n)});break}if(o.index>n&&r.push({type:"text",text:t.slice(n,o.index)}),"mention"===o.kind){const{full:t,groups:s}=o,i=s[0]??"",a=s[1]??"";i&&r.push({type:"text",text:i});const c=e.resolveMention?.(a);c?r.push({type:"mention",attrs:{id:c.id,text:c.text}}):r.push({type:"text",text:"@"+a}),n=o.index+t.length;continue}if("emoji"===o.kind){const{full:t,groups:s}=o,i=`:${s[0]}:`,a=e.resolveEmoji?.(i);r.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:i}}),n=o.index+t.length;continue}}return(t=>{const e=[];for(const n of t){const t=e[e.length-1];"text"!==n.type||"text"!==t?.type||t.marks||n.marks?e.push(n):t.text=(t.text??"")+(n.text??"")}return e})(r)}function Mt(t,e,n){t.lastIndex=n;const r=t.exec(e);if(!r)return null;const s=t.source.includes("@")?"mention":"emoji";return{index:r.index,full:r[0],groups:r.slice(1),kind:s}}function Ut(t,e){return t?e&&t.index>e.index?e:t:e}function Bt(t){const e=(t.children??[])[0];return"text"===e?.type?(e.value??"")+"":"paragraph"===e?.type?((e.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("")||"")+"":""}function Kt(t){const e=((t??"")+"").toLowerCase().trim();return e?"info"===e||"note"===e||"success"===e||"warning"===e||"error"===e?e:"danger"===e?"error":null:null}function Ft(t){const e=((t??"")+"").toLowerCase().trim();return!e||"neutral"!==e&&"green"!==e&&"yellow"!==e&&"red"!==e&&"blue"!==e&&"purple"!==e?null:e}function Wt(t,e){const n=[];for(const r of t??[])if(r?.type)if("text"!==r.type)if("strong"!==r.type)if("emphasis"!==r.type)if("delete"!==r.type)if("inlineCode"!==r.type)if("break"!==r.type){if("link"===r.type){const t=(r.url??"")+"",s=Xt(r.children??[],t),i=qt(r,0,e);if(i){"inline"===i.type?n.push(i.node):n.push({type:"text",text:s,marks:[{type:"link",attrs:{href:t}}]});continue}if(e.enableSmartCards&&zt(s,t)){n.push({type:"inlineCard",attrs:{url:t}});continue}n.push({type:"text",text:s,marks:[{type:"link",attrs:{href:t}}]});continue}if("textDirective"===r.type&&"status"===r.name){const t=Bt(r)||"Status",e=Ft(r.attributes?.color)??"neutral";n.push({type:"status",attrs:{text:t,color:e}});continue}if("textDirective"===r.type&&"emoji"===r.name){const t=Gt(r);n.push(Zt(t,e));continue}}else n.push({type:"hardBreak"});else n.push({type:"text",text:(r.value??"")+"",marks:[{type:"code"}]});else n.push(...Yt(Wt(r.children??[],e),{type:"strike"}));else n.push(...Yt(Wt(r.children??[],e),{type:"em"}));else n.push(...Yt(Wt(r.children??[],e),{type:"strong"}));else n.push(...Lt((r.value??"")+"",e));return n.filter(t=>!("text"===t.type&&""===(t.text??"")))}function Yt(t,e){return t.map(t=>{if("text"!==t.type)return t;const n=t.marks?[...t.marks,e]:[e];return{...t,marks:n}})}function Xt(t,e){const n=[];for(const e of t??[])"text"===e.type||"inlineCode"===e.type?n.push((e.value??"")+""):"emphasis"!==e.type&&"strong"!==e.type&&"delete"!==e.type||n.push(Xt(e.children??[],""));return n.join("")||e}function zt(t,e){const n=(t??"").trim(),r=(e??"").trim();return n===r&&/^https?:\/\//i.test(r)}function Gt(t){return(t.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("").trim()||""}function Zt(t,e){const n=t.startsWith(":")?t:`:${t}:`,r=e.resolveEmoji?.(n);return r?{type:"emoji",attrs:{shortName:r.shortName,text:r.text}}:{type:"emoji",attrs:{shortName:n}}}function Vt(t){return t?"string"==typeof t?t:"text"===t.type||"inlineCode"===t.type?(t.value??"")+"":Array.isArray(t.children)?t.children.map(Vt).join(""):"":""}function Qt(t,e){if(!t?.type)return null;if((t=>"containerDirective"===t?.type&&"panel"===t?.name)(t))return((t,e)=>{const n=t.attributes??{},r=Kt(n.type)??"info",s="string"==typeof n.title?n.title:void 0,i=(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:r,...s?{panelType:r,title:s}:{panelType:r}},content:i.length?i:[{type:"paragraph",content:[]}]}})(t,e);switch(t.type){case"heading":return{type:"heading",attrs:{level:ee(t.depth??1,1,6)},content:Wt(t.children??[],e)};case"paragraph":return(t=>{const e=t.children??[];if(1!==e.length)return null;const n=e[0];if("image"!==n?.type)return null;const r=(n.url??"")+"";return r?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:r}}]}:null})(t)||{type:"paragraph",content:Wt(t.children??[],e)};case"blockquote":return{type:"blockquote",content:(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean)};case"list":return((t,e)=>e.enableTaskLists&&(t.children??[]).some(t=>"boolean"==typeof t.checked)?((t,e)=>{const n=[];let r=0;for(const s of t.children??[]){if("boolean"!=typeof s.checked)continue;r+=1;const t=(s.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);n.push({type:"taskItem",attrs:{localId:"task-"+r,state:s.checked?"DONE":"TODO"},content:t.length?t:[{type:"paragraph",content:[]}]})}return{type:"taskList",content:n}})(t,e):{type:t.ordered?"orderedList":"bulletList",content:(t.children??[]).map(t=>((t,e)=>{const n=(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);return{type:"listItem",content:n.length?n:[{type:"paragraph",content:[]}]}})(t,e))})(t,e);case"code":{const n=((t,e)=>{const n=(t??"").toString().trim().toLowerCase();return n?e.enableMermaid&&"mermaid"===n?"mermaid":(t=>{const e=t.trim().toLowerCase();return{js:"javascript",javascript:"javascript",jsx:"javascript",ts:"typescript",typescript:"typescript",tsx:"typescript",py:"python",python:"python",rb:"ruby",ruby:"ruby",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",yml:"yaml",yaml:"yaml",json:"json",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",sql:"sql",go:"go",rust:"rust",java:"java",c:"c",cpp:"cpp","c++":"cpp",cs:"csharp",csharp:"csharp",php:"php",kotlin:"kotlin",swift:"swift",md:"markdown",markdown:"markdown",graphql:"graphql",gql:"graphql",dockerfile:"docker",makefile:"make",ini:"ini"}[e]??e})(n):null})(t.lang,e);return{type:"codeBlock",attrs:{language:n},content:[{type:"text",text:(t.value??"")+""}]}}case"thematicBreak":return{type:"rule"};case"table":return((t,e)=>({type:"table",content:(t.children??[]).map((t,n)=>({type:"tableRow",content:(t.children??[]).map(t=>({type:0===n?"tableHeader":"tableCell",content:[{type:"paragraph",content:Wt(t.children??[],e)}]}))}))}))(t,e);case"leafDirective":return"status"===t.name?(t=>{const e=Ft((t.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:Bt(t)||"Status",color:e}}]}})(t):"panel"===t.name?((t,e)=>{const n=t.attributes??{},r=Kt(n.type)??"info",s="string"==typeof n.title?n.title:void 0;return{type:"panel",attrs:{panelType:r,...s?{title:s}:{}},content:[{type:"paragraph",content:Wt([{type:"text",value:Bt(t)}],e)}]}})(t,e):te(t,e);default:return te(t,e)}}function te(t,e){if("drop"===e.unknownNodeStrategy)return null;const n=Vt(t);return n?{type:"paragraph",content:[{type:"text",text:n}]}:null}function ee(t,e,n){const r=Number.isFinite(t)?Math.trunc(t):e;return Math.max(e,Math.min(n,r))}const ne={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function re(t,e={}){const n={...ne,...e},r=t??"",s=C().use($).use(_).use(P),i=s.parse(r),o=s.runSync(i);return se(o),((t,e)=>{const n=[];for(const r of t.children??[]){const t=Qt(r,e);t&&(Array.isArray(t)?n.push(...t):n.push(t))}return((t,e)=>{if(!e.enableSmartCards)return t;const n=t.content.map(t=>(t=>{if("paragraph"!==t.type)return t;const e=t.content??[];if(1!==e.length)return t;const n=e[0];if("inlineCard"!==n?.type)return t;const r=n.attrs?.url;return r?[{type:"blockCard",attrs:{url:r}}]:t})(t)).flat();return{...t,content:n}})({version:1,type:"doc",content:n},e)})(o,n)}function se(t){if(!t||!Array.isArray(t.children))return;const e=[];for(const n of t.children)"definition"!==n?.type&&("html"!==n?.type?(se(n),e.push(n)):e.push({type:"text",value:(n.value??"")+""}));t.children=e}function ie(t){return t.flatMap(t=>"panel"===t.type?ie(t.content??[]):[oe(t)])}function oe(t){return t.content?{...t,content:ie(t.content)}:{...t}}const ae=/\{\{\s*([^\}]+)\s*\}\}/g;function ce(t){if(!t||0>=Object.keys(t).length)return[];const e=(t=>{if(null==t)return"";try{return JSON.stringify(t,null,2)}catch{return R(t,{depth:null})}})(t);return e?[{type:"text",text:e}]:[]}function pe(t={},e=[]){const n=(t=>t&&"object"==typeof t?Array.isArray(t)?{items:t}:t:"string"==typeof t?{message:t}:null==t?{}:{value:t})(t);return{content:e.length?e:ce(n),result:n,structuredContent:n}}const le={name:"jira-issue-create",inputSchema:Dt,runTool:async(t,e)=>pe(await(async(t,e)=>{let n;const r=t=>t&&t.trim()?t.trim():void 0,s=r(Ht.jira.projectKey),i=r(Ht.jira.issueType),o=e&&"object"==typeof e&&!Array.isArray(e)?e:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??s,issueType:o.issueType??i};try{n=Dt.parse(a)}catch(t){const e=Error("validation error");throw e.code="validation_error",e}let c;c=n&&"object"==typeof n&&"fields"in n&&n.fields?{...n.fields}:{summary:n.summary,project:{key:n.projectKey},issuetype:{name:n.issueType},...n.description?{description:n.description}:{}},c=((t,e)=>{if(!e||!e.content)return t;const n=(r=e.content,s=e.placeholders,r?r.replace(ae,(t,e)=>{const n=e.trim();if(!n)return"";if(s&&Object.prototype.hasOwnProperty.call(s,n)){const t=s[n];return null==t?"":t+""}return t}):"");var r,s;if(!n.trim())return t;const i=re(n),o=(a=t.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?re(a).content:[]:[];var a;return t.description={type:"doc",version:1,content:[...o,...i.content]},t})(c,n.template);const p=t?.issues?.create??t?.issues?.createIssue;if("function"!=typeof p)throw Error("Jira client missing create function");const l=await p.call(t.issues,{fields:c}),u=l&&l.data||l;return{id:u?.id??null,key:u?.key??null}})(t,e))};class ue extends Error{constructor({code:t,message:e,details:n}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=t,this.details=n}}function de(t){if(!t)return new ue({code:"jira_error",message:"Unknown Jira error",details:{raw:t}});const e=t?.status??t?.statusCode??t?.response?.status??t?.response?.statusCode,n="number"==typeof e?e:Number(e)||void 0,r=t?.response?.data??t?.data??t?.response?.body??t?.body,s=[];"string"==typeof t?.message&&s.push(t.message),((t,e)=>{t&&(Array.isArray(t.errorMessages)&&t.errorMessages.forEach(t=>"string"==typeof t&&e.push(t)),"string"==typeof t.errorMessage&&e.push(t.errorMessage),t.errorCollection&&Array.isArray(t.errorCollection.errors)&&t.errorCollection.errors.forEach(t=>{"string"==typeof t?e.push(t):t&&"string"==typeof t.message&&e.push(t.message)}),t?.errors&&"object"==typeof t.errors&&Object.values(t.errors).forEach(t=>{"string"==typeof t?e.push(t):"string"==typeof t?.message&&e.push(t.message)}))})(r,s);const i=n?`Jira API error (${n})`:"Jira API error",o=s.length>0?s.join(" | "):i;return new ue({code:n?"jira_"+n:t?.code??"jira_error",message:o,details:{httpStatus:n,body:r,raw:t}})}const me=w.object({issueId:w.string().min(1),deleteSubtasks:w.boolean().optional().default(!0)}),he={name:"jira-issue-delete",inputSchema:me,runTool:async(t,e)=>{try{const n=me.parse(e),r=t.issues??t.issue??t,s=r?.delete??r?.deleteIssue;if("function"!=typeof s)throw Error("jira client delete endpoint is not available");return await s.call(r,{issueIdOrKey:n.issueId,deleteSubtasks:n.deleteSubtasks}),pe({success:!0,message:`Issue ${n.issueId} deleted successfully`})}catch(t){throw de(t)}}},fe=w.object({projectKey:w.string().trim().min(1).optional(),issueType:w.string().trim().min(1).optional(),parentIssueId:w.string().trim().min(1).optional(),name:w.string().trim().min(1).optional(),reference:w.string().trim().min(1).optional(),jql:w.string().trim().min(1).optional(),startAt:w.number().int().min(0).optional(),maxResults:w.number().int().min(1).optional(),fields:w.array(w.string()).optional(),expand:w.string().optional(),orderBy:w.string().trim().min(1).optional()});function ye(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const ge={name:"jira-issue-list",inputSchema:fe,runTool:async(t,e)=>{try{const n=fe.parse(e),r=n.startAt??0,s=n.maxResults??50;let i=n.jql?.trim();if(i){if(n.orderBy){const t=n.orderBy.trim();t&&(i=/\border\s+by\b/i.test(i)?`${i}, ${t}`:`${i} ORDER BY ${t}`)}}else i=(t=>{const e=[];if(t.projectKey&&e.push(`project = "${ye(t.projectKey)}"`),t.issueType&&e.push(`issuetype = "${ye(t.issueType)}"`),t.parentIssueId&&e.push(`parent = "${ye(t.parentIssueId)}"`),t.name&&e.push(`summary ~ "${ye(t.name)}"`),t.reference){const n=ye(t.reference);e.push(`(key ~ "${n}" OR summary ~ "${n}" OR text ~ "${n}")`)}if(0===e.length){const t=Error("Provide a jql query or at least one filter (project, name, reference, parent, issue type, etc.).");throw t.code="validation_error",t}let n=e.join(" AND ");if(t.orderBy){const e=t.orderBy.trim();e&&(n=/\border\s+by\b/i.test(n)?`${n}, ${e}`:`${n} ORDER BY ${e}`)}return n})(n);const o={jql:i,startAt:r,maxResults:s};n.fields&&(o.fields=n.fields),n.expand&&(o.expand=n.expand);const a=t.issueSearch,c=a&&"function"==typeof a.searchForIssuesUsingJqlEnhancedSearch?a.searchForIssuesUsingJqlEnhancedSearch:a&&"function"==typeof a.searchForIssuesUsingJql?a.searchForIssuesUsingJql:void 0;if(!c)throw Error("Jira search API is unavailable on the client");const p=await c.call(a,o),l=p?.data??p,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=r),void 0===u.maxResults&&(u.maxResults=s),pe(u)}catch(t){throw de(t)}}},be=w.object({issueId:w.string().min(1),expand:w.string().optional(),fields:w.array(w.string()).optional(),properties:w.array(w.string()).optional()}),we={name:"jira-issue-read",inputSchema:be,runTool:async(t,e)=>{try{const n=be.parse(e),r={issueIdOrKey:n.issueId};n.expand&&(r.expand=n.expand),n.fields&&(r.fields=n.fields),n.properties&&(r.properties=n.properties);const s=await t.issues.getIssue(r);return pe(s?.data??s)}catch(t){throw de(t)}}},ve=w.object({issueId:w.string().min(1),transitionId:w.union([w.string(),w.number()]),fields:w.record(w.any()).optional(),update:w.record(w.array(w.object({set:w.any().optional(),add:w.any().optional(),remove:w.any().optional()}))).optional(),comment:w.string().optional()}),Ie={name:"jira-issue-transition",inputSchema:ve,runTool:async(t,e)=>{try{const n=ve.parse(e),r={id:n.transitionId};n.fields&&(r.fields=n.fields),n.update&&(r.update=n.update),n.comment&&(r.comment={body:re(n.comment)});const s=await t.issues.transition({issueIdOrKey:n.issueId,transition:r});return pe(s?.data??s)}catch(t){throw de(t)}}},Se=w.object({issueId:w.string().min(1),expand:w.string().optional()}),je={name:"jira-transition-list",inputSchema:Se,runTool:async(t,e)=>{try{const n=Se.parse(e),r=t.issues;if(!r||"function"!=typeof r.getTransitions)throw Error("Jira transitions API is unavailable on the client");const s={issueIdOrKey:n.issueId};n.expand&&(s.expand=n.expand);const i=await r.getTransitions(s);return pe(i?.data??i)}catch(t){throw de(t)}}},xe=w.object({issueId:w.string().min(1),fields:w.record(w.any()).optional(),update:w.record(w.array(w.object({set:w.any().optional(),add:w.any().optional(),remove:w.any().optional(),edit:w.any().optional()}))).optional(),properties:w.array(w.any()).optional(),notifyUsers:w.boolean().optional().default(!0),issueTemplateId:w.string().optional(),overrideScreenSecurity:w.boolean().optional().default(!1),overrideEditableFlag:w.boolean().optional().default(!1)}),ke={name:"jira-issue-update",inputSchema:xe,runTool:async(t,e)=>{try{const n=xe.parse(e),r={issueIdOrKey:n.issueId};n.fields&&(r.fields=(t=>{const e={...t},n=e.description;var r;return(t=>{if(!t||"object"!=typeof t)return!1;const e=t;return"doc"===e.type&&1===e.version&&Array.isArray(e.content)})(n)&&(e.description=(r=n,{...r,content:ie(r.content??[])})),e})(n.fields)),n.update&&(r.update=n.update),n.properties&&(r.properties=n.properties),void 0!==n.notifyUsers&&(r.notifyUsers=n.notifyUsers),n.issueTemplateId&&(r.issueTemplateId=n.issueTemplateId),void 0!==n.overrideScreenSecurity&&(r.overrideScreenSecurity=n.overrideScreenSecurity),void 0!==n.overrideEditableFlag&&(r.overrideEditableFlag=n.overrideEditableFlag);const s=await t.issues.editIssue(r);return pe(s?.data??s)}catch(t){throw de(t)}}},Ae=w.object({issueId:w.string().min(1),assignee:w.union([w.string(),w.object({accountId:w.string().min(1)}),w.object({accountType:w.string().min(1)})])}),Te={name:"jira-assign-issue",inputSchema:Ae,runTool:async(t,e)=>{try{const n=Ae.parse(e);let r;r="string"==typeof n.assignee?{accountId:n.assignee}:n.assignee;const s=await t.issues.assignIssue({issueIdOrKey:n.issueId,assignee:r});return pe(s?.data??s)}catch(t){throw de(t)}}},Ee=w.object({issueId:w.string().min(1)}),Oe={name:"jira-unassign-issue",inputSchema:Ee,runTool:async(t,e)=>{try{const n=Ee.parse(e),r=await t.issues.assignIssue({issueIdOrKey:n.issueId,assignee:{accountId:"-1"}});return pe(r?.data??r)}catch(t){throw de(t)}}},He=w.object({issueId:w.string().min(1),body:w.string().min(1),visibility:w.object({type:w.enum(["role","group"]),value:w.string().min(1)}).optional()}),Je={name:"jira-comment-add",inputSchema:He,runTool:async(t,e)=>{try{const n=He.parse(e),r=t.issueComments;if(!r||"function"!=typeof r.addComment)throw Error("Jira issueComments API is unavailable on the client");const s={issueIdOrKey:n.issueId,comment:n.body};n.visibility&&(s.visibility=n.visibility);const i=await r.addComment(s);return pe(i?.data??i)}catch(t){throw de(t)}}},Ne=w.object({issueId:w.string().min(1),start:w.number().optional().default(0),maxResults:w.number().optional().default(50),orderBy:w.string().optional(),expand:w.string().optional()}),Ce={name:"jira-comment-list",inputSchema:Ne,runTool:async(t,e)=>{try{const n=Ne.parse(e),r=t.issueComments;if(!r||"function"!=typeof r.getComments)throw Error("Jira issueComments API is unavailable on the client");const s=await r.getComments({issueIdOrKey:n.issueId,startAt:n.start,maxResults:n.maxResults,orderBy:n.orderBy,expand:n.expand});return pe(s?.data??s)}catch(t){throw de(t)}}},_e=w.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","is tested by","tests","Is covered by","covered by","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]),Pe=w.object({id:w.string().optional(),key:w.string().optional()}),$e=w.object({type:w.enum(["role","group"]),value:w.string().min(1)}),Re=w.object({body:w.string().optional(),visibility:$e.optional()}),De=w.object({link:w.object({relationship:_e,inwardIssue:Pe,outwardIssue:Pe,comment:Re.optional()})});let qe=[];function Le(t){return(t||"").trim().toLowerCase()}async function Me(t,e){if(!e)throw Error("Link relationship is required");0===qe.length&&(qe=await(async t=>{const e=t.issueLinkTypes;if(!e||"function"!=typeof e.getIssueLinkTypes)throw Error("Jira issueLinkTypes API is unavailable on the client");const n=await e.getIssueLinkTypes(),r=n?.issueLinkTypes??n?.values??n;return Array.isArray(r)?r:[]})(t));const n=Le(e),r=qe.find(t=>[t.name,t.inward,t.outward].some(t=>Le(t)===n));if(!r)throw Error(`No issue link type matching '${e}' found.`);return r}function Ue(t){if(!t)throw Error("Linked issue must include an id or key");if(t.id)return{id:t.id};if(t.key)return{key:t.key};throw Error("Linked issue must include an id or key")}function Be(t){if(!t)return;const e={};return t.body&&(e.body=re(t.body)),t.visibility&&(e.visibility=t.visibility),Object.keys(e).length>0?e:void 0}const Ke=De,Fe={name:"jira-link-create",inputSchema:Ke,runTool:async(t,e)=>{try{const n=Ke.parse(e).link,r={inwardIssue:Ue(n.inwardIssue),outwardIssue:Ue(n.outwardIssue)},s=Be(n.comment);s&&(r.comment=s);const i=t.issueLinks;if(!i||"function"!=typeof i.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const o=await Me(t,n.relationship);r.type={id:o.id};const a=await i.linkIssues(r);return pe(a?.data??a)}catch(t){throw de(t)}}},We=w.object({issueId:w.string().min(1),file:w.string().min(1),mimeType:w.string().optional(),comment:w.string().optional()}),Ye={name:"jira-attach",inputSchema:We,runTool:async(t,e)=>{try{const n=We.parse(e),s=A.resolve(n.file),i=await r.readFile(s),o=A.basename(s),a=new FormData;a.append("file",new Blob([i],{type:n.mimeType??"application/octet-stream"}),o);const c=t?.config??null,p=c?.host,l=c?.authentication?.basic??c?.authentication??c?.auth??null,u=l?.email,d=l?.apiToken??l?.apiKey;if(!p||!u||!d)throw Error("Jira client authentication configuration is unavailable for attachments");const m=await fetch(`${p}/rest/api/3/issue/${n.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${u}:${d}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:a});if(!m.ok){const t=await m.text();throw Error(`Jira attachment upload failed (${m.status}): ${t}`)}const h=await m.json();if(n.comment){const e=t.issueComments;if(!e||"function"!=typeof e.addComment)throw Error("Jira issueComments API is unavailable on the client");await e.addComment({issueIdOrKey:n.issueId,comment:re(n.comment)})}return pe(h)}catch(t){if(t&&t.code&&"string"==typeof t.code&&["ENOENT","EACCES"].includes(t.code))throw Error("Attachment file error: "+t.message);throw de(t)}}},Xe=w.object({issueId:w.string().min(1)}),ze={name:"jira-attachment-list",inputSchema:Xe,runTool:async(t,e)=>{try{const n=Xe.parse(e),r=t.issues;if(!r||"function"!=typeof r.getIssue)throw Error("Jira issues API is unavailable on the client");const s=await r.getIssue({issueIdOrKey:n.issueId,fields:["attachment"]}),i=s?.data??s;return pe({attachments:i?.fields?.attachment??[]})}catch(t){throw de(t)}}},Ge=w.object({issueId:w.string().min(1),attachmentId:w.string().min(1)}),Ze={name:"jira-attachment-delete",inputSchema:Ge,runTool:async(t,e)=>{try{const n=Ge.parse(e),r=t.issueAttachments;if(!r||"function"!=typeof r.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await r.removeAttachment({id:n.attachmentId}),pe({success:!0,message:`Attachment ${e.attachmentId} deleted successfully`})}catch(t){throw de(t)}}},Ve=w.object({issueId:w.string().min(1),timeSpent:w.string().min(1),comment:w.string().optional(),author:w.object({accountId:w.string().min(1)}).optional(),startingOn:w.string().optional(),artifact:w.string().optional()}),Qe={name:"jira-worklog-add",inputSchema:Ve,runTool:async(t,e)=>{try{const n=Ve.parse(e),r={timeSpent:n.timeSpent};n.comment&&(r.comment=n.comment),n.author&&(r.author=n.author),n.startingOn&&(r.started=n.startingOn),n.artifact&&(r.artifact=n.artifact);const s=t.issueWorklogs;if(!s||"function"!=typeof s.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const i=await s.addWorklog({issueIdOrKey:n.issueId,...r});return pe(i?.data??i)}catch(t){throw de(t)}}};class tn{constructor(){this.clientId=Ht.orThrow().xray.apiUser,this.clientSecret=Ht.orThrow().xray.apiSecret,this.baseUrl=Ht.orThrow().xray.host||"https://eu.xray.cloud.getxray.app"}async authenticate(){if(!this.clientId||!this.clientSecret)throw Error("Xray API credentials are missing (XRAY__API_USER, XRAY__API_SECRET).");const t=await fetch(this.baseUrl+"/api/v2/authenticate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId,client_secret:this.clientSecret})}),e=await t.text();return this.token=e.replace(/"/g,""),this.token}async graphql(t,e){this.token||await this.authenticate();const n=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify({query:t,variables:e})}),r=await n.json();if(r.errors)throw Error(JSON.stringify(r.errors,null,2));return r.data}async getTest(t){return(await this.graphql('\n query GetTest($issueId: String!) {\n getTest(issueId: $issueId) {\n issueId\n jira(fields:["key"])\n steps {\n id\n action\n data\n result\n }\n }\n }\n ',{issueId:t})).getTest}async addStep(t,e){return(await this.graphql("\n mutation AddTestStep($issueId: String!, $step: CreateStepInput!) {\n addTestStep(issueId: $issueId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{issueId:t,step:e})).addTestStep}async updateStep(t,e){return(await this.graphql("\n mutation UpdateTestStep($stepId: String!, $step: UpdateStepInput!) {\n updateTestStep(stepId: $stepId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{stepId:t,step:e})).updateTestStep}async deleteStep(t){return(await this.graphql("\n mutation RemoveTestStep($stepId: String!) {\n removeTestStep(stepId: $stepId)\n }\n ",{stepId:t})).removeTestStep}async addSteps(t,e){return Promise.all(e.map(e=>this.addStep(t,e)))}async updateSteps(t){return Promise.all(t.map(t=>this.updateStep(t.stepId,t.step)))}async deleteSteps(t){return Promise.all(t.map(t=>this.deleteStep(t)))}async syncSteps(t,e){const n=(await this.getTest(t)).steps||[],r=[],s=[],i=[];for(let t=0;t<e.length;t++){const i=e[t],o=n[t];o?o.action===i.action&&o.data===i.data&&o.result===i.result||r.push({stepId:o.id,step:i}):s.push(i)}if(n.length>e.length)for(let t=e.length;t<n.length;t++)i.push(n[t].id);await this.addSteps(t,s),await this.updateSteps(r),await this.deleteSteps(i)}}let en=null;const nn=new Map;function rn(t){const e=t?.fields,n=t?.action??e?.Action??e?.action;if(!n||"string"!=typeof n)throw Error("Xray step action is required");const r=t.data??t.fields?.Data??t.fields?.data??void 0,s=t.result??t.fields?.Result??t.fields?.result??void 0;return{action:n.toString(),data:"string"==typeof r?r:void 0,result:"string"==typeof s?s:void 0}}async function sn(t,e){if(!e)throw Error("Issue reference is required when interacting with Xray steps");if(nn.has(e))return nn.get(e);if(/^[0-9]+$/.test(e))return nn.set(e,e),e;const n=t?.issues??t?.issue;if(!n?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const r=await n.getIssue({issueIdOrKey:e,fields:["id"]}),s=r?.id;if(!s)throw Error("Unable to resolve Jira issue ID for "+e);return nn.set(e,s),s}async function on(t){if(t?.test?.step)return t.test.step;const e=await(async()=>{if(en)return en;const t=Ht.orThrow().xray.apiUser?.trim(),e=Ht.orThrow().xray.apiSecret?.trim();if(!t||!e)throw Error("Xray credentials are missing (XRAY__API_USER, XRAY__API_SECRET). Please configure them before using Xray tools.");const n=Pt(),r=new tn;return en={test:{step:{async createStep(t,e){const s=await sn(n,t),i=await r.addStep(s,rn(e));return{step:i,id:i?.id}},async updateStep(t,e,s){await sn(n,t);const i=rn(s),o=await r.updateStep(e.toString(),i);return{step:o,id:o?.id}},deleteStep:async(t,e)=>(await sn(n,t),{success:!0===await r.deleteStep(e.toString())}),async getSteps(t){const e=await sn(n,t),s=await r.getTest(e);return{steps:s?.steps??[]}}}}},en})();if(!e?.test?.step)throw Error("Xray step API is unavailable on the client");return e.test.step}const an=w.object({issueId:w.string().min(1),action:w.string().min(1),data:w.string().optional(),result:w.string().optional()}),cn={name:"jira-xray-step-add",inputSchema:an,runTool:async(t,e)=>{try{const n=an.parse(e),r=await on(t),s={action:n.action,data:n.data,result:n.result};return pe(await r.createStep(n.issueId,s))}catch(t){throw de(t)}}},pn=w.object({issueId:w.string().min(1),stepId:w.union([w.string(),w.number()]),action:w.string().min(1),data:w.string().optional(),result:w.string().optional()}),ln={name:"jira-xray-step-update",inputSchema:pn,runTool:async(t,e)=>{try{const n=pn.parse(e),r=await on(t),s=n.stepId+"",i={action:n.action,data:n.data,result:n.result};return pe(await r.updateStep(n.issueId,s,i))}catch(t){throw de(t)}}},un=w.object({issueId:w.string().min(1),stepId:w.union([w.string(),w.number()])}),dn={name:"jira-xray-step-delete",inputSchema:un,runTool:async(t,e)=>{try{const n=un.parse(e),r=await on(t);return await r.deleteStep(n.issueId,n.stepId.toString()),pe({success:!0})}catch(t){throw de(t)}}},mn=w.object({issueId:w.string().min(1)}),hn={name:"jira-xray-step-list",inputSchema:mn,runTool:async(t,e)=>{try{const n=mn.parse(e),r=await on(t);return pe(await r.getSteps(n.issueId))}catch(t){throw de(t)}}},fn=w.object({linkId:w.string().min(1)}),yn={name:"jira-link-delete",inputSchema:fn,runTool:async(t,e)=>{try{const n=fn.parse(e),r=t.issueLinks;if(!r||"function"!=typeof r.deleteIssueLink)throw Error("Jira issueLinks API is unavailable on the client");return await r.deleteIssueLink({linkId:n.linkId}),pe({success:!0,message:`Issue link ${n.linkId} deleted successfully`})}catch(t){throw de(t)}}},gn=w.object({linkId:w.string().min(1),relationship:_e,comment:Re.optional()}),bn={name:"jira-link-update",inputSchema:gn,runTool:async(t,e)=>{try{const n=gn.parse(e),r=t.issueLinks;if(!r||"function"!=typeof r.getIssueLink||"function"!=typeof r.deleteIssueLink||"function"!=typeof r.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const s=await r.getIssueLink({linkId:n.linkId}),i=s?.data??s;if(!i)throw Error(`Issue link ${n.linkId} not found`);const o=i.inwardIssue,a=i.outwardIssue;if(!o||!a)throw Error("Issue link payload is missing linked issues");const c=await Me(t,n.relationship);await r.deleteIssueLink({linkId:n.linkId});const p={inwardIssue:Ue(o),outwardIssue:Ue(a),type:{id:c.id}},l=Be(n.comment);return l&&(p.comment=l),await r.linkIssues(p),pe({success:!0,message:`Issue link ${n.linkId} updated to ${n.relationship}`})}catch(t){throw de(t)}}},wn={[le.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[we.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[ge.name]:{title:"Jira Issue List",description:"Search issues by summary, reference, parent, or JQL and list the matching tickets",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[ke.name]:{title:"Jira Issue Update",description:"Update a Jira issue using fields, update ops, and property toggles",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[he.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Ie.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[je.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Te.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Oe.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Je.name]:{title:"Jira Comment Add",description:"Add a comment to a Jira issue with optional visibility",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ce.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Fe.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[bn.name]:{title:"Jira Link Update",description:"Change the relationship type for an existing issue link",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[yn.name]:{title:"Jira Link Delete",description:"Delete an issue link from Jira",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Ye.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ze.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ze.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Qe.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[cn.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ln.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[dn.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[hn.name]:{title:"Jira Xray Step List",description:"List steps for an Xray test case",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}};async function vn(t){const e=o.for(vn);let n,r=null;try{n=Pt()}catch(t){if(!(t instanceof _t))return void e.warn("Skipping Jira tool registration; unable to create Jira client",{error:t});r=t,e.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:t})}const s=[le,we,ge,ke,he,Ie,je,Te,Oe,Je,Ce,Fe,bn,yn,Ye,ze,Ze,Qe,cn,ln,dn,hn];for(const i of s){const s=wn[i.name];if(s)try{await t.registerTool(i.name,{title:s.title,description:s.description,inputSchema:i.inputSchema,annotations:s.annotations},async t=>{if(!n)throw r??Error("Jira client unavailable because credentials could not be loaded.");return i.runTool(n,t)}),e.info("Registered Jira tool "+i.name)}catch(t){e.error("Failed to register Jira tool "+i.name,{error:t})}}}async function In(t){await(async t=>{t.registerTool("decaf-server-info",{title:"Decaf MCP Server Info",description:"Return server metadata, version, and registered prompt names for diagnostics.",inputSchema:{},outputSchema:void 0,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{const t=St.map(t=>t.getName()).sort();return{content:[{type:"text",text:["Name: "+Ht.name,"Title: "+Ht.title,"Version: "+Ht.version,"Prompts: "+(t.join(", ")||"<none>")].join("\n")}]}})})(t);const e=o.for(In);try{await vn(t)}catch(t){e.error("Failed to register Jira tools",t)}}class Sn extends Z{setCb(t){return this.cb=t,this}setConfig(t){return this.config=t,this}setUriOtTemplate(t){return this.uriOrTemplate=t,this}constructor(t){super(t)}static get builder(){return new Sn}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{const e="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new q(new D(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,n=Object.assign(this.config,{_meta:{}}),r=async(t,e)=>{const n=this.logFor(e);n.verbose(`Requesting resource ${this.name} from ${t.toString()}`);const r=await Promise.resolve(this.cb(t,e));return n.verbose(`Resource ${this.name} retrieved successfully.`),n.debug("Resource retrieval meta: "+JSON.stringify(r._meta)),r};return t.resource(this.name,e,n,r)}catch(t){throw o.for(this).error("Error registering resource "+this.name,t),t}}}m([f(),h("design:type",String)],Sn.prototype,"uriOrTemplate",void 0),m([f(),h("design:type",Function)],Sn.prototype,"cb",void 0),m([f(),h("design:type",Object)],Sn.prototype,"config",void 0);const jn=ut()??k.join(__dirname,"..","assets"),xn=k.join(jn,"templates"),kn=k.join(jn,"prompts"),An=new WeakMap;class Tn extends a{get client(){const t=An.get(this);if(!t)throw Error("Mcp server requires Mcp client");return t}constructor(){super()}async load(){const t=this.log.for(this.load);for(const e of St)try{t.info("loading prompt "+e.getName());const n=e.build(this.client);t.verbose(`Loaded prompt ${n.title} from ${e.getName()} definition`)}catch(n){t.error("Failed to load prompt "+e.getName(),n)}try{await In(this.client),t.verbose("Registered built-in tools")}catch(t){}try{await(async(t,n)=>{n.info("Registering agent templates as resources...");const r=e.readdirSync(xn).filter(t=>t.endsWith(".md"));for(const s of r){const r=k.basename(s,".md"),i=k.join(xn,s),o=Sn.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+r}).setCb(async t=>{const n=e.readFileSync(t.pathname,"utf8");return{contents:[{uri:t.toString(),text:n,mimeType:"text/markdown"}],_meta:{}}});try{o.build(t),n.info("Registered template: "+r)}catch(t){n.error(`Failed to register template ${r}:`,t)}}n.info("Registering agent prompts...");const s=e.readdirSync(kn).filter(t=>t.endsWith(".md"));for(const r of s){const s=k.basename(r,".md"),i=k.join(kn,r),o=e.readFileSync(i,"utf8"),a=mt.builder.setName(s).setTitle("Prompt: "+s).setDescription("Dynamic prompt for "+s).setArgsSchema(w.object({})).setCb(async t=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(t),n.info("Registered prompt: "+s)}catch(t){n.error(`Failed to register prompt ${s}:`,t)}}})(this.client,t)}catch(t){}}async boot(t="stdio"){"stdio"===t&&o.setFactory(F),o.for(this.constructor.name);const e=((Array.isArray(Ht.icons)?Ht.icons:[Ht.icons])||[]).map(t=>{const e="string"==typeof t?.src?t.src:(t?.src??"")+"",n="string"==typeof t?.mimeType?t.mimeType:(t?.mimeType??"")+"";let r=[];return Array.isArray(t?.sizes)?r=t.sizes.map(t=>t+""):"string"==typeof t?.sizes&&(r=(t.sizes+"").split(",").map(t=>t.trim())),{src:e,mimeType:n,sizes:r}}),n={name:Ht.name,title:Ht.title,websiteUrl:Ht.websiteUrl,version:Ht.version,icons:e},r=new L(n,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((t,e)=>{An.set(t,e)})(this,r),r.onerror=t=>{this.log.error("MCP instance onerror",t)},t){case"stdio":t=new U;break;case"http":t=new B({sessionIdGenerator:()=>M(),onsessioninitialized:t=>{},onsessionclosed:t=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(s=t)||"object"!=typeof s||"function"!=typeof s.send&&"function"!=typeof s.close&&"function"!=typeof s.on)throw new T("Invalid transport type: "+t)}var s;try{await this.load()}catch(t){throw t}await this.client.connect(t)}}const En=(new t).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async t=>{const e=pt("package.json"),r=JSON.parse(n.readFileSync(e,"utf-8")),s=r.version,{transport:i}=t,o=(new K).for("mcp-server");if("stdio"!==i)throw Error("Unsupported transport mode: "+i);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(t)} for ${r.name} version ${s}`),(new Tn).boot(i)});(new t).command("md-to-ast").description("pipes markdown to jira ast: `cat file.md` | npx decaf-mcp md-to-ast > ast.json").action(async t=>{const e=pt("package.json"),r=JSON.parse(n.readFileSync(e,"utf-8")),s=r.version;o.for("md-to-ast").debug(`running with options: ${JSON.stringify(t)} for ${r.name} version ${s}`);const i=re(await(async()=>{const t=[];for await(const e of process.stdin)t.push(Buffer.from(e));return Buffer.concat(t).toString("utf8")})(),{resolveMention:t=>({id:t,text:"@"+t}),resolveAttachment:t=>({id:t,collection:"attachments"})});process.stdout.write(JSON.stringify(i,null,2)+"\n")});const On=(new t).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");On.addCommand(En),On.parse(process.argv);
2
2
  //# sourceMappingURL=mcp-server.js.map