@decaf-ts/mcp-server 1.5.15 → 1.5.16

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 +3 -6
  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 +0 -0
  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 +0 -0
  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 +1 -2
  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,6 +1,3 @@
1
- DCAF1���b"���-��-0����#v��@�� ��+�w����o����]�|#� ͣC��x��
2
- ^�V����?�ȠF� � Uj9���
3
- SD`Z
4
- 8z��y3���[5&�s�����_�t�*t�9��m��t%$$J��F��y�'Zoig�q�zd���=�>��ri䣶�4��e��S����0�9�s�s9o��D��!�N����[Cn���U
5
- ,~��#�f(&�x"WS��J�^���ؓ� ����H
6
- Lk�ы�5�l&x6g�W���
1
+ DCAF1�D��3W�j��Bh��Y��`�c̍�9czBi��Ц^s����[��Do�"*;(/�3>|T�u\9=�#�}� ����-qPzVf�����IjXx0A�4����e"ò��(`
2
+ ��ѧ�#.c�I�xd�iBt5�BU���E�diu{�g�&�KX�g��[�
3
+ ����'Kb'H�D�gu��d)��,1iP�Ӣ����Ѐ��mTe�-#jN8.+�y% ��rd[^29�Ҧ�i���nb, ��x��Ħ�|0ג��;�����ʊ�ۑ�usr��S�h�mM�o�@�����L�r>U;�2�Q�Q�-�#�t��ǜ�{����4�B�� ��c
Binary file
Binary file
Binary file
@@ -1,2 +1 @@
1
- DCAF1LLT ���>�8�{�!#�����9)7�I���u�`�(��~�?�n��I�j�^���r���%0�+3}5pb'�hi�N$ghSY���2������=��y��x)e>z��T;�����d2rV�g(݅���V��J*�A4��}:.uY��V]p�S����y��� �S�1ѻd���ld���eC��]~���ӧ�݀`m/(�� Ggw��%fv6�$u����� ���
2
- �b �14�>g:J�b�̯�-����z�F�
1
+ DCAF1e�o.VUP���']������t��(��(}���紌=H4������kW�?$B�y��\'_���� ��ۡX�`L��
@@ -1 +1 @@
1
- DCAF1���ۉ�7@�5:|O9�+�2 VS�,5���d�¢��(�3��r5�/t/縵���Ð�
1
+ DCAF1!���qn##,'ZoGJ�����DG^�\N)�Xp��]OIqMs=$���!�B�ؤ��P��
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var e,t;e=this,t=function(e,t,r,s,i,n,o,a,c,d,p,u,l,m,h,f,y,g,b,w,v,I,S){"use strict";function j(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var k=j(t),x=j(c);class T extends r.MiniLogger{constructor(e,t,r){super(e,t,r)}log(e,t,s,i){const n=this.config("level");r.NumericLogLevels[n],r.NumericLogLevels[e]}}const _=(e,t,...r)=>{const s=(e=>{if("string"==typeof e)return e;if(!e)return"unknown";if("function"==typeof e)return e.name||"unknown";if("object"==typeof e&&"constructor"in e){const t=e.constructor;if(t&&t.name)return t.name}return"unknown"})(e);return new T(s,t)};var A,E,z,O,J;(e=>{e[e.NONE=0]="NONE",e[e.BASIC=1]="BASIC",e[e.ADVANCED=2]="ADVANCED",e[e.HIGH=3]="HIGH"})(A||(A={})),(e=>{e[e.NONE=0]="NONE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(E||(E={})),(e=>{e[e.FREE=0]="FREE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(z||(z={}));class C extends i.Model{get log(){return this._log||(this._log=r.Logging.for(this)),this._log}constructor(e){super(e)}logFor(e){const{sessionId:t,requestId:r,authInfo:s}=e||{};let i="string"==typeof t&&t.length>0?this.log.for(t):this.log;return s&&s.clientId&&(i=i.for(s.clientId)),r&&(i=i.for(r.toString())),i}setDescription(e){return this.description=e,this}getDescription(){return this.description}setName(e){return this.name=e,this}getName(){return this.name}setTitle(e){return this.title=e,this}}s.__decorate([i.required(),s.__metadata("design:type",String)],C.prototype,"description",void 0),s.__decorate([i.required(),s.__metadata("design:type",String)],C.prototype,"name",void 0),s.__decorate([i.required(),s.__metadata("design:type",String)],C.prototype,"title",void 0);class H extends C{constructor(e){super(e),this.reasoning=A.NONE,this.effort=E.NONE,this.cost=z.FREE}setReasoning(e){return this.reasoning=e,this}setEffort(e){return this.effort=e,this}setCost(e){return this.cost=e,this}}function N(e){if(!e)return;let t=e,r=t&&t._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)t=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)t=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)t=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)t=r.innerType;else{if(!r.schema)return;t=r.schema}r=t&&t._def}return r&&"ZodObject"===r.typeName?r:void 0}function q(e,t="schema"){if(N(e))return e;if(e&&"object"==typeof e){const t=e.def&&"object"==typeof e.def?e.def:void 0,r=t&&(t.shape||"object"===t.type)&&t.shape||("object"===e.type?e.shape:void 0)||(t&&"object"===t.type?{}:void 0);if(t||"object"===e.type||r){const e={};if(r&&"object"==typeof r)for(const[t,s]of Object.entries(r))e[t]=D(s)?s:n.z.any();return n.z.object(e)}}throw Error(`Registration error: provided a non-canonical ${t}. Export a ZodObject (z.object(...)).`)}function P(e){if(!e)return;if(e&&"object"==typeof e&&!e._def)return e.def&&"object"==typeof e.def&&e.def.shape?e.def.shape:e;const t=N(e);return t?"function"==typeof t.shape?t.shape():t.shape||void 0:void 0}function D(e){return!(!e||"object"!=typeof e||!e._def)}s.__decorate([i.required(),s.__metadata("design:type",Number)],H.prototype,"reasoning",void 0),s.__decorate([i.required(),s.__metadata("design:type",Number)],H.prototype,"effort",void 0),s.__decorate([i.required(),s.__metadata("design:type",Number)],H.prototype,"cost",void 0),(e=>{e.ASSETS="assets"})(O||(O={})),(e=>{e.PROMPT="prompts",e.DOCUMENTATION="documentation",e.CODE="code"})(J||(J={}));const R=Buffer.from("DCAF1","ascii");function $(e){let r=c.resolve(e);for(;;){if(t.existsSync(c.join(r,"package.json")))return r;const e=c.dirname(r);if(e===r)break;r=e}}const L=process.argv?.[1]?$(c.dirname(c.resolve(process.argv[1]))):void 0,M=(()=>{const e=Error().stack;if(!e)return;const t=e.split(/\r?\n/).slice(1);for(const e of t){const t=e.match(/\(?([^()]+?):\d+:\d+\)?/);if(!t)continue;let r=t[1];if(r.startsWith("file://"))try{r=l.fileURLToPath(r)}catch{continue}if(!r.includes("node:internal"))return c.dirname(r)}})(),U=M?$(M):void 0,B=L??U??process.cwd();function F(...e){return c.join(B,...e)}function W(e){let t=e;for(;;){const e=x.join(t,"lib","assets");if(k.existsSync(e))return e;const r=x.join(t,"src","assets");if(k.existsSync(r))return r;const s=x.join(t,"assets");if(k.existsSync(s))return s;const i=x.dirname(t);if(i===t)break;t=i}}function K(){const e=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(e&&k.existsSync(e))return e;const t=W(__dirname);if(t)return t;const r=process.argv?.[1];if(r){const e=W(x.dirname(r));if(e)return e}const s=[B,process.env.INIT_CWD].filter(Boolean);for(const e of s){const t=W(e);if(t)return t}return F("assets")}let Y=class extends r.LoggedClass{constructor(e){super(),this.basePath=e||K()}listAssets(...e){const t=x.join(this.basePath,...e);return k.readdirSync(t)}listPrompts(){return this.listAssets(J.PROMPT)}getAsset(e,t="md",...r){const s=x.join(this.basePath,...r),i=(e,t=!1)=>{try{return t?(e=>{if(e.length<R.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!e.subarray(0,R.length).equals(R))throw Error("Invalid prompt payload (bad magic)");const t=process.env.ENCRYPTION_KEY||"";if(!t)throw Error("Missing encryption key. Set ENCRYPTION_KEY to load obfuscated assets.");let r=R.length;const s=e.subarray(r,r+16);r+=16;const i=e.subarray(r,r+12);r+=12;const n=e.subarray(r,r+16);r+=16;const o=e.subarray(r),a=((e,t)=>p.scryptSync(e,t,32))(t,s),c=p.createDecipheriv("aes-256-gcm",a,i);c.setAuthTag(n);const d=Buffer.concat([c.update(o),c.final()]);return u.gunzipSync(d)})(k.readFileSync(e)).toString("utf-8"):k.readFileSync(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}},n=i(x.join(s,`${e}.${t}`),"enc"===t);if(null!==n)return n;const o=i(x.join(s,e+".enc"),!0);if(null!==o)return o;throw Error("Asset not found: "+x.join(s,`${e}.${t}`))}getAllAssets(e,...t){return this.listAssets(e,...t).reduce((r,s)=>{const i=x.extname(s),n=x.basename(s,i),o=i.replace(/^\./,"")||void 0;return r[n]=this.getAsset(n,o??void 0,e,...t),r},{})}toPromptDef(e){const t=e=>"number"==typeof e?e:"string"==typeof e?(e=>{switch(e){case"none":return A.NONE;case"basic":return A.BASIC;case"advanced":return A.ADVANCED;case"high":return A.HIGH;case"medium":return E.MEDIUM;case"low":return z.LOW;case"free":return z.FREE;default:throw new d.InternalError("Cannon convert unknown level "+e)}})(e.toLowerCase()):A.NONE;return e.effort=t(e.effort),e.reasoning=t(e.reasoning),e.cost=t(e.cost),e}getPrompt(e,...t){const s=this.getAsset(r.toSnakeCase(e),"json",J.PROMPT,...t);let i;try{i=JSON.parse(s)}catch(r){throw new d.SerializationError(`Failed to parse prompt ${e} in categories ${t}: ${r}`)}return this.toPromptDef(i)}getAllPrompts(...e){const t=this.getAllAssets(J.PROMPT,...e);return Object.entries(t).reduce((t,[r,s])=>{try{t[r]=JSON.parse(s)}catch(t){throw new d.SerializationError(`Failed to parse prompt ${r} in categories ${e}: ${t}`)}return t},t)}};Y=s.__decorate([o.injectable(),s.__metadata("design:paramtypes",[String])],Y);class X extends H{constructor(e){super(e)}setCb(e){return this.cb=e,this}setArgsSchema(e){return this.argsSchema=e,this}static get builder(){return new X}static patchPrompt(e,t,s,i){const n=(t=Array.isArray(t)?t:Object.keys(t)).filter(e=>!Object.prototype.hasOwnProperty.call(s,e));if(n.length)throw new d.ValidationError("Missing replacements for placeholders: "+n.join(", "));i&&(i.verbose("Patching prompt with placeholders: "+JSON.stringify(t)),i.debug("Values: "+JSON.stringify(s)));const o=t.reduce((e,t)=>(e[t]=s[t],e),{});return r.sf(e,o)}patchPrompt(e,t,r,s){return X.patchPrompt(e,t,r,s||this.log.for(this.patchPrompt))}build(e,t){const r=this.log.for(this.build),s=this.hasErrors();if(s)throw new d.ValidationError(s.toString());try{this.argsSchema&&q(this.argsSchema,"argsSchema");const r=P(this.argsSchema);return e.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(e,r)=>{const s=this.logFor(r);e=Object.assign({},t,e||{}),s.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(e)}`),e._meta=Object.assign(e._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const i=await Promise.resolve(this.cb(e,r));return s.verbose(`Prompt ${this.name} executed successfully.`),s.debug("Prompt execution meta: "+JSON.stringify(i._meta)),i})}catch(e){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),e),e}}}s.__decorate([o.inject(Y),s.__metadata("design:type",Y)],X.prototype,"assets",void 0),s.__decorate([i.required(),s.__metadata("design:type",Object)],X.prototype,"cb",void 0),s.__decorate([i.required(),s.__metadata("design:type",n.ZodObject)],X.prototype,"argsSchema",void 0),s.__decorate([a.prop(),s.__metadata("design:type",Object)],X.prototype,"placeholders",void 0);class G extends X{setCategory(e){return this.promptCategory=e,this}addPrefix(e){return this.prefixes=this.prefixes||[],this.prefixes.push(e),this}addSuffix(e){return this.suffixes=this.suffixes||[],this.suffixes.push(e),this}constructor(e){super(e)}build(e){const t=this.assets.getPrompt(this.name,this.promptCategory);i.Model.fromObject(this,t);const r=new Set((a.Metadata.properties(G)||[]).filter(e=>!["assets","promptCategory","prefixes","suffixes"].includes(e)));["cb","argsSchema"].forEach(e=>r.add(e));const s=this.hasErrors(...Array.from(r));if(s)throw new d.ValidationError(s.toString());const o=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),c=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),p=[...new Set([...t.placeholders,...o.map(e=>e.placeholders||[]),...c.map(e=>e.placeholders||[])].flat())].reduce((e,t)=>(e[t]=n.z.string().describe("The description for "+t),e),{});return this.setArgsSchema(n.z.object(p)),this.setCb((e,t)=>{const r=this.logFor(t).for(G).for(this.promptCategory).for(this.name);function s(e=[]){return Array.isArray(e)?e:Object.keys(e)}const i=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),n=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...i.map(e=>s(e.placeholders)).flat(),...n.map(e=>s(e.placeholders)).flat(),...s(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...i.map(e=>e.prompt),o.prompt,...n.map(e=>e.prompt)].join("\n\n"),a,e,r)}}],_meta:{}}}),super.build(e)}setReasoning(e){throw new d.InternalError("Named prompt builders don't require callback")}setEffort(e){throw new d.InternalError("Named prompt builders don't require callback")}setCost(e){throw new d.InternalError("Named prompt builders don't require callback")}setDescription(e){throw new d.InternalError("Named prompt builders don't require callback")}setTitle(e){throw new d.InternalError("Named prompt builders don't require callback")}static get builder(){return new G}}s.__decorate([i.required(),s.__metadata("design:type",String)],G.prototype,"promptCategory",void 0),s.__decorate([i.list(String),i.minlength(1),s.__metadata("design:type",Array)],G.prototype,"prefixes",void 0),s.__decorate([i.minlength(1),i.list(String),s.__metadata("design:type",Array)],G.prototype,"suffixes",void 0);const V=X.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(n.z.object({message:n.z.string().optional()})).setCb(async e=>{const t=e.message??"default";return{messages:[{role:"assistant",content:{type:"text",text:t}}],content:[],structuredContent:{message:t},result:{message:t}}}),Z=X.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc prompt").setDescription("Interactive prompt for jogging JSDoc helpers").setArgsSchema(n.z.object({gist:n.z.string().optional()})).setCb(async e=>{const t=e.gist??"interactive jsdoc response";return{messages:[{role:"assistant",content:{type:"text",text:t}}],content:[],structuredContent:{message:t},result:{message:t}}}),Q=Object.assign(Z,{name:Z.getName()});var ee;function te(e,t=[],r=[]){const s=G.builder.setCategory(ee.DOCS).setName(e);return["prefix",...t].forEach(e=>s.addPrefix(e)),["suffix",...r].forEach(e=>s.addSuffix(e)),s}(e=>{e.DOCS="documentation",e.CODE="code"})(ee||(ee={}));const re=[te("class"),te("constant"),te("decorator"),te("function"),te("module"),te("file"),te("repo",[],["iterate"])],se=n.z.object({className:n.z.string().describe("the class name to turn into a builder")}),ie=[V,Q,...re,X.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(se).setReasoning(A.BASIC).setCb((e,t)=>(e.className=r.toPascalCase(e.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 ${e.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 ${e.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<${e.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[]): ${e.className}Builder | Promise<${e.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(): ${e.className}Builder {\n return new ${e.className}Builder(); // static method to get a new builder instance\n }\n \n static from<K extends keyof ${e.className}Builder>(obj: K, ${e.className}Builder[K]): ${e.className}Builder {\n return new ${e.className}Builder(); // static method to create a builder from an object\n }\n}\n\`\`\` \n\n`}}],_meta:{}}))];class ne extends H{setAnnotations(e){return this.annotations=Object.assign(this.annotations,e),this}setCb(e){return this.cb=e,this}setInputSchema(e){return this.inputSchema=e,this}setOutputSchema(e){return this.outputSchema=e,this}constructor(e){super(e),this.annotations={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}static get builder(){return new ne}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{this.inputSchema&&q(this.inputSchema,"inputSchema"),this.outputSchema&&q(this.outputSchema,"outputSchema");const t=P(this.inputSchema),r=P(this.outputSchema);return e.registerTool(this.name,{title:this.title,description:this.description,inputSchema:t,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(e,t)=>{const r=this.logFor(t);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(e)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(e,t));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(s._meta)),s})}catch(e){const t=e?.message||e+"";if("string"==typeof t&&t.includes("already registered"))return r.Logging.for(this).warn(`Tool ${this.name} already registered - skipping duplicate registration`),{name:this.name};throw r.Logging.for(this).error("Error building tool",e),e}}}s.__decorate([i.required(),s.__metadata("design:type",Object)],ne.prototype,"annotations",void 0),s.__decorate([i.required(),s.__metadata("design:type",Object)],ne.prototype,"cb",void 0),s.__decorate([i.required(),s.__metadata("design:type",Function)],ne.prototype,"inputSchema",void 0);const oe=ne.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(n.z.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(oe,{name:oe.getName()});const ae=ne.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(n.z.object({filePath:n.z.string().optional()})).setCb(async()=>({content:[{type:"text",text:"file summary stub"}],result:{summary:"file summary stub"}}));function ce(){try{let e=process.argv[1]?c.dirname(c.resolve(process.argv[1])):process.cwd();for(;;){const r=c.join(e,"package.json");if(t.existsSync(r))return JSON.parse(t.readFileSync(r,"utf-8"));const s=c.dirname(e);if(s===e)break;e=s}}catch{}return{}}Object.assign(ae,{name:ae.getName()});const de=ce().version??"0.0.0",pe=ce().name??"unknown";a.Metadata.registerLibrary(pe,de);const ue={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:de,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:B,assetDir:K(),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,timeout:process.env.JIRA__TIMEOUT?parseInt(process.env.JIRA__TIMEOUT):1e3,rateLimitRetryDelayMs:process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS?parseInt(process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS):3e3},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:r.LogLevel.error},le=r.LoggedEnvironment.accumulate(ue);function me(){const{host:e,email:t,apiKey:r,projectKey:s,issueType:i}=le.jira;return{host:e?.trim(),email:t?.trim(),apiKey:r?.trim(),projectKey:s?.trim(),issueType:i?.trim(),parentIssue:le.jira.parentIssue?.trim()}}function he(){const e=me();return[{name:"JIRA__HOST",required:!0,description:"Atlassian host (e.g. decaf-ts.atlassian.net) where your Jira instance is hosted.",value:e.host},{name:"JIRA__EMAIL",required:!0,description:"Email address of the Jira account that has API access.",value:e.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:e.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:e.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:e.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:e.parentIssue}]}function fe(e){const t=e.value?((e,t)=>{if(e)return t?"<configured>":e})(e.value,e.sensitive):"not set",r=e.required?"(required)":"(optional)";return`\u2022 ${e.name} ${r}: ${e.description} Current state: ${t}.`}r.Logging.setConfig(le);class ye extends Error{constructor(e){const t=he(),r=(e=>{const t=he();return`${e.length?`Missing Jira credentials: ${e.map(e=>e.name).join(", ")}.`:"Jira credentials are configured."}\n\nThis setup uses the following environment variables:\n${t.map(fe).join("\n")}`})(e);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=t,this.missing=e,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,ye)}}const ge=r.Logging.for("jira.client"),be=/(authorization|cookie)/i;function we(e){if(!e)return;const t=e.baseURL??"",r=e.url??"";return t&&r?`${t.endsWith("/")?t.slice(0,-1):t}/${r.startsWith("/")?r.slice(1):r}`:r||t||void 0}function ve(e){if(void 0!==e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch(t){return m.inspect(e,{depth:null})}}}function Ie(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,r])=>{t[e]=be.test(e)&&r?"[REDACTED]":r}),t}function Se(e){let t;try{const e=require("jira.js");t=e?.Version3Client||e.default?.Version3Client||e.default||e}catch(e){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+e)}const{host:r,email:s,apiKey:i}=(()=>{const e=me(),t=he().filter(e=>e.required&&!e.value);if(t.length>0)throw new ye(t);return{host:e.host,email:e.email,apiKey:e.apiKey}})(),n=new t({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:s,apiToken:i}},baseRequestConfig:{headers:{Accept:"application/json","Content-Type":"application/json"}}});return(e=>{if(!e)return;const t="__jiraLoggingAttached";e[t]||(e[t]=!0,e.interceptors.request.use(e=>{e.headers=(e=>{const t={...e||{}};return Object.keys(t).some(e=>"accept"===e.toLowerCase())||(t.Accept="application/json"),Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),t})(e.headers);const t=(e.method??"GET").toString().toUpperCase(),r=we(e);return ge.info("jira.request",{method:t,url:r,headers:Ie(e.headers),params:e.params,data:ve(e.data)}),e},e=>(ge.error("jira.request.error",{message:e.message}),Promise.reject(e))),e.interceptors.response.use(e=>{const t=(e.config?.method??"GET").toString().toUpperCase(),r=we(e.config);return ge.info("jira.response",{method:t,url:r,status:e.status,headers:Ie(e.headers),data:ve(e.data)}),e},e=>{const t=e.config,r=e.response,s=(t?.method??"GET").toString().toUpperCase(),i=we(t);return ge.error("jira.response.error",{method:s,url:i,status:r?.status,headers:Ie(r?.headers),data:ve(r?.data),message:e.message}),Promise.reject(e)}))})(n.instance),n}const je=n.z.object({name:n.z.string().min(1).optional().describe("Optional template name that pre-populates additional fields"),content:n.z.string().min(1).describe("Markdown template content to apply when constructing the description"),placeholders:n.z.record(n.z.string()).optional().describe("Map of placeholder replacements used by the template")}).describe("Template metadata used to adjust the created description"),ke=n.z.object({template:je.optional().describe("Optional template settings for this create request")}).describe("Additional template controls available when creating an issue"),xe=n.z.union([n.z.object({fields:n.z.record(n.z.any()).describe("Full raw field map that gets delivered to Jira")}).merge(ke).describe("Create argument that supplies every field explicitly"),n.z.object({summary:n.z.string().min(1).describe("Title or summary of the new issue"),projectKey:n.z.string().min(1).describe("Project key where the issue is created"),issueType:n.z.string().min(1).describe("Type name for the new issue (story, task, etc.)"),description:n.z.string().optional().describe("Optional textual description for the issue")}).merge(ke).describe("Create argument with minimal required identifiers plus optional description")]).describe("Union describing how to create an issue either via raw fields or shorthand properties");function Te(e,t,r){const s=((e.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!s)return null;const i=s[2],n=r.resolveAttachment?.(i);return n?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:n.id,collection:n.collection??"attachments"}}]}}:null}function _e(e,t){if(!e)return[];if(!t.enableAtMentions&&!t.enableEmojiShortcodes)return[{type:"text",text:e}];let r=0;const s=[],i=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,n=/:([a-z0-9_+-]{1,64}):/gi;for(;r<e.length;){const o=Ee(t.enableAtMentions?Ae(i,e,r):null,t.enableEmojiShortcodes?Ae(n,e,r):null);if(!o){s.push({type:"text",text:e.slice(r)});break}if(o.index>r&&s.push({type:"text",text:e.slice(r,o.index)}),"mention"===o.kind){const{full:e,groups:i}=o,n=i[0]??"",a=i[1]??"";n&&s.push({type:"text",text:n});const c=t.resolveMention?.(a);c?s.push({type:"mention",attrs:{id:c.id,text:c.text}}):s.push({type:"text",text:"@"+a}),r=o.index+e.length;continue}if("emoji"===o.kind){const{full:e,groups:i}=o,n=`:${i[0]}:`,a=t.resolveEmoji?.(n);s.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:n}}),r=o.index+e.length;continue}}return(e=>{const t=[];for(const r of e){const e=t[t.length-1];"text"!==r.type||"text"!==e?.type||e.marks||r.marks?t.push(r):e.text=(e.text??"")+(r.text??"")}return t})(s)}function Ae(e,t,r){e.lastIndex=r;const s=e.exec(t);if(!s)return null;const i=e.source.includes("@")?"mention":"emoji";return{index:s.index,full:s[0],groups:s.slice(1),kind:i}}function Ee(e,t){return e?t&&e.index>t.index?t:e:t}function ze(e){const t=(e.children??[])[0];return"text"===t?.type?(t.value??"")+"":"paragraph"===t?.type?((t.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("")||"")+"":""}function Oe(e){const t=((e??"")+"").toLowerCase().trim();return t?"info"===t||"note"===t||"success"===t||"warning"===t||"error"===t?t:"danger"===t?"error":null:null}function Je(e){const t=((e??"")+"").toLowerCase().trim();return!t||"neutral"!==t&&"green"!==t&&"yellow"!==t&&"red"!==t&&"blue"!==t&&"purple"!==t?null:t}function Ce(e,t){const r=[];for(const s of e??[])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 e=(s.url??"")+"",i=Ne(s.children??[],e),n=Te(s,0,t);if(n){"inline"===n.type?r.push(n.node):r.push({type:"text",text:i,marks:[{type:"link",attrs:{href:e}}]});continue}if(t.enableSmartCards&&qe(i,e)){r.push({type:"inlineCard",attrs:{url:e}});continue}r.push({type:"text",text:i,marks:[{type:"link",attrs:{href:e}}]});continue}if("textDirective"===s.type&&"status"===s.name){const e=ze(s)||"Status",t=Je(s.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:e,color:t}});continue}if("textDirective"===s.type&&"emoji"===s.name){const e=Pe(s);r.push(De(e,t));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(s.value??"")+"",marks:[{type:"code"}]});else r.push(...He(Ce(s.children??[],t),{type:"strike"}));else r.push(...He(Ce(s.children??[],t),{type:"em"}));else r.push(...He(Ce(s.children??[],t),{type:"strong"}));else r.push(..._e((s.value??"")+"",t));return r.filter(e=>!("text"===e.type&&""===(e.text??"")))}function He(e,t){return e.map(e=>{if("text"!==e.type)return e;const r=e.marks?[...e.marks,t]:[t];return{...e,marks:r}})}function Ne(e,t){const r=[];for(const t of e??[])"text"===t.type||"inlineCode"===t.type?r.push((t.value??"")+""):"emphasis"!==t.type&&"strong"!==t.type&&"delete"!==t.type||r.push(Ne(t.children??[],""));return r.join("")||t}function qe(e,t){const r=(e??"").trim(),s=(t??"").trim();return r===s&&/^https?:\/\//i.test(s)}function Pe(e){return(e.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("").trim()||""}function De(e,t){const r=e.startsWith(":")?e:`:${e}:`,s=t.resolveEmoji?.(r);return s?{type:"emoji",attrs:{shortName:s.shortName,text:s.text}}:{type:"emoji",attrs:{shortName:r}}}function Re(e){return e?"string"==typeof e?e:"text"===e.type||"inlineCode"===e.type?(e.value??"")+"":Array.isArray(e.children)?e.children.map(Re).join(""):"":""}function $e(e,t){if(!e?.type)return null;if((e=>"containerDirective"===e?.type&&"panel"===e?.name)(e))return((e,t)=>{const r=e.attributes??{},s=Oe(r.type)??"info",i="string"==typeof r.title?r.title:void 0,n=(e.children??[]).map(e=>$e(e,t)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:s,...i?{panelType:s,title:i}:{panelType:s}},content:n.length?n:[{type:"paragraph",content:[]}]}})(e,t);switch(e.type){case"heading":return{type:"heading",attrs:{level:Me(e.depth??1,1,6)},content:Ce(e.children??[],t)};case"paragraph":{const r=(e=>{const t=e.children??[];if(1!==t.length)return null;const r=t[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})(e);return r||{type:"paragraph",content:Ce(e.children??[],t)}}case"blockquote":return{type:"blockquote",content:(e.children??[]).map(e=>$e(e,t)).flat().filter(Boolean)};case"list":return((e,t)=>t.enableTaskLists&&(e.children??[]).some(e=>"boolean"==typeof e.checked)?((e,t)=>{const r=[];let s=0;for(const i of e.children??[]){if("boolean"!=typeof i.checked)continue;s+=1;const e=(i.children??[]).map(e=>$e(e,t)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+s,state:i.checked?"DONE":"TODO"},content:e.length?e:[{type:"paragraph",content:[]}]})}return{type:"taskList",content:r}})(e,t):{type:e.ordered?"orderedList":"bulletList",content:(e.children??[]).map(e=>((e,t)=>{const r=(e.children??[]).map(e=>$e(e,t)).flat().filter(Boolean);return{type:"listItem",content:r.length?r:[{type:"paragraph",content:[]}]}})(e,t))})(e,t);case"code":{const r=((e,t)=>{const r=(e??"").toString().trim().toLowerCase();return r?t.enableMermaid&&"mermaid"===r?"mermaid":(e=>{const t=e.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"}[t]??t})(r):null})(e.lang,t);return{type:"codeBlock",attrs:{language:r},content:[{type:"text",text:(e.value??"")+""}]}}case"thematicBreak":return{type:"rule"};case"table":return((e,t)=>({type:"table",content:(e.children??[]).map((e,r)=>({type:"tableRow",content:(e.children??[]).map(e=>({type:0===r?"tableHeader":"tableCell",content:[{type:"paragraph",content:Ce(e.children??[],t)}]}))}))}))(e,t);case"leafDirective":return"status"===e.name?(e=>{const t=Je((e.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:ze(e)||"Status",color:t}}]}})(e):"panel"===e.name?((e,t)=>{const r=e.attributes??{},s=Oe(r.type)??"info",i="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:s,...i?{title:i}:{}},content:[{type:"paragraph",content:Ce([{type:"text",value:ze(e)}],t)}]}})(e,t):Le(e,t);default:return Le(e,t)}}function Le(e,t){if("drop"===t.unknownNodeStrategy)return null;const r=Re(e);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function Me(e,t,r){const s=Number.isFinite(e)?Math.trunc(e):t;return Math.max(t,Math.min(r,s))}const Ue={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function Be(e,t={}){const r={...Ue,...t},s=e??"",i=h.unified().use(g).use(f).use(y),n=i.parse(s),o=i.runSync(n);return Fe(o),((e,t)=>{const r=[];for(const s of e.children??[]){const e=$e(s,t);e&&(Array.isArray(e)?r.push(...e):r.push(e))}return((e,t)=>{if(!t.enableSmartCards)return e;const r=e.content.map(e=>(e=>{if("paragraph"!==e.type)return e;const t=e.content??[];if(1!==t.length)return e;const r=t[0];if("inlineCard"!==r?.type)return e;const s=r.attrs?.url;return s?[{type:"blockCard",attrs:{url:s}}]:e})(e)).flat();return{...e,content:r}})({version:1,type:"doc",content:r},t)})(o,r)}function Fe(e){if(!e||!Array.isArray(e.children))return;const t=[];for(const r of e.children)"definition"!==r?.type&&("html"!==r?.type?(Fe(r),t.push(r)):t.push({type:"text",value:(r.value??"")+""}));e.children=t}function We(e){return e.flatMap(e=>"panel"===e.type?We(e.content??[]):[Ke(e)])}function Ke(e){return e.content?{...e,content:We(e.content)}:{...e}}const Ye=/\{\{\s*([^\}]+)\s*\}\}/g;function Xe(e){if(!e||0>=Object.keys(e).length)return[];const t=(e=>{if(null==e)return"";try{return JSON.stringify(e,null,2)}catch{return m.inspect(e,{depth:null})}})(e);return t?[{type:"text",text:t}]:[]}function Ge(e={},t=[]){const r=(e=>e&&"object"==typeof e?Array.isArray(e)?{items:e}:e:"string"==typeof e?{message:e}:null==e?{}:{value:e})(e);return{content:t.length?t:Xe(r),result:r,structuredContent:r}}const Ve={name:"jira-issue-create",inputSchema:xe,runTool:async(e,t)=>Ge(await(async(e,t)=>{let r;const s=e=>e&&e.trim()?e.trim():void 0,i=s(le.jira.projectKey),n=s(le.jira.issueType),o=t&&"object"==typeof t&&!Array.isArray(t)?t:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??i,issueType:o.issueType??n};try{r=xe.parse(a)}catch(e){const t=Error("validation error");throw t.code="validation_error",t}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=((e,t)=>{if(!t||!t.content)return e;const r=(s=t.content,i=t.placeholders,s?s.replace(Ye,(e,t)=>{const r=t.trim();if(!r)return"";if(i&&Object.prototype.hasOwnProperty.call(i,r)){const e=i[r];return null==e?"":e+""}return e}):"");var s,i;if(!r.trim())return e;const n=Be(r),o=(a=e.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?Be(a).content:[]:[];var a;return e.description={type:"doc",version:1,content:[...o,...n.content]},e})(c,r.template);const d=e?.issues?.create??e?.issues?.createIssue;if("function"!=typeof d)throw Error("Jira client missing create function");const p=await d.call(e.issues,{fields:c}),u=p&&p.data||p;return{id:u?.id??null,key:u?.key??null}})(e,t))};class Ze extends Error{constructor({code:e,message:t,details:r}){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=e,this.details=r}}const Qe=r.Logging.for("jira.errors");function et(e){if(!e)return new Ze({code:"jira_error",message:"Unknown Jira error",details:{raw:e}});const t=e?.status??e?.statusCode??e?.response?.status??e?.response?.statusCode,r="number"==typeof t?t:Number(t)||void 0,s=e?.response?.data??e?.data??e?.response?.body??e?.body,i=[];"string"==typeof e?.message&&i.push(e.message),((e,t)=>{e&&(Array.isArray(e.errorMessages)&&e.errorMessages.forEach(e=>"string"==typeof e&&t.push(e)),"string"==typeof e.errorMessage&&t.push(e.errorMessage),e.errorCollection&&Array.isArray(e.errorCollection.errors)&&e.errorCollection.errors.forEach(e=>{"string"==typeof e?t.push(e):e&&"string"==typeof e.message&&t.push(e.message)}),e?.errors&&"object"==typeof e.errors&&Object.values(e.errors).forEach(e=>{"string"==typeof e?t.push(e):"string"==typeof e?.message&&t.push(e.message)}))})(s,i);const n=r?`Jira API error (${r})`:"Jira API error",o=i.length>0?i.join(" | "):n,a=r?"jira_"+r:e?.code??"jira_error",c=e?.config,d=c?{method:c.method?c.method.toString().toUpperCase():void 0,url:c.url,headers:Ie(c.headers),data:ve(c.data)}:void 0;return Qe.error("jira.error",{code:a,message:o,httpStatus:r,request:d,body:ve(s)??s}),new Ze({code:a,message:o,details:{httpStatus:r,body:s,request:d,raw:e}})}const tt=n.z.object({issueId:n.z.string().min(1),deleteSubtasks:n.z.boolean().optional().default(!0)}),rt={name:"jira-issue-delete",inputSchema:tt,runTool:async(e,t)=>{try{const r=tt.parse(t),s=e.issues??e.issue??e,i=s?.delete??s?.deleteIssue;if("function"!=typeof i)throw Error("jira client delete endpoint is not available");return await i.call(s,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),Ge({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(e){throw et(e)}}},st=n.z.object({projectKey:n.z.string().trim().min(1).optional().describe("Project key used to scope the issue search"),issueType:n.z.string().trim().min(1).optional().describe("Issue type name used to filter the results"),parentIssueId:n.z.string().trim().min(1).optional().describe("Optional parent issue key/ID to limit results to a subtree"),name:n.z.string().trim().min(1).optional().describe("Issue summary to match exactly"),reference:n.z.string().trim().min(1).optional().describe("External reference or custom identifier to filter by"),jql:n.z.string().trim().min(1).optional().describe("Free-form JQL query to drive the search"),startAt:n.z.number().int().min(0).optional().describe("Index for paging through the search results"),maxResults:n.z.number().int().min(1).optional().describe("Maximum number of issues to return"),fields:n.z.array(n.z.string()).optional().describe("List of issue fields to include in the response"),expand:n.z.string().optional().describe("Optional expansion clause for the results"),orderBy:n.z.string().trim().min(1).optional().describe("Field or clause used to order the returned issues")}).describe("Parameters describing how to search for Jira issues");function it(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const nt={name:"jira-issue-list",inputSchema:st,runTool:async(e,t)=>{try{const r=st.parse(t),s=r.startAt??0,i=r.maxResults??50;let n=r.jql?.trim();if(n){if(r.orderBy){const e=r.orderBy.trim();e&&(n=/\border\s+by\b/i.test(n)?`${n}, ${e}`:`${n} ORDER BY ${e}`)}}else n=(e=>{const t=[];if(e.projectKey&&t.push(`project = "${it(e.projectKey)}"`),e.issueType&&t.push(`issuetype = "${it(e.issueType)}"`),e.parentIssueId&&t.push(`parent = "${it(e.parentIssueId)}"`),e.name&&t.push(`summary ~ "${it(e.name)}"`),e.reference){const r=it(e.reference);t.push(`(key ~ "${r}" OR summary ~ "${r}" OR text ~ "${r}")`)}if(0===t.length){const e=Error("Provide a jql query or at least one filter (project, name, reference, parent, issue type, etc.).");throw e.code="validation_error",e}let r=t.join(" AND ");if(e.orderBy){const t=e.orderBy.trim();t&&(r=/\border\s+by\b/i.test(r)?`${r}, ${t}`:`${r} ORDER BY ${t}`)}return r})(r);const o={jql:n,startAt:s,maxResults:i};r.fields&&(o.fields=r.fields),r.expand&&(o.expand=r.expand);const a=e.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 d=await c.call(a,o),p=d?.data??d,u="object"==typeof p&&null!==p?{...p}:{};return void 0===u.startAt&&(u.startAt=s),void 0===u.maxResults&&(u.maxResults=i),Ge(u)}catch(e){throw et(e)}}},ot=n.z.object({issueId:n.z.string().min(1),expand:n.z.string().optional(),fields:n.z.array(n.z.string()).optional(),properties:n.z.array(n.z.string()).optional()}),at={name:"jira-issue-read",inputSchema:ot,runTool:async(e,t)=>{try{const r=ot.parse(t),s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand),r.fields&&(s.fields=r.fields),r.properties&&(s.properties=r.properties);const i=await e.issues.getIssue(s);return Ge(i?.data??i)}catch(e){throw et(e)}}},ct=n.z.object({issueId:n.z.string().min(1).describe("Target issue key or ID to transition"),transitionId:n.z.union([n.z.string(),n.z.number()]).describe("Identifier for the transition to execute"),fields:n.z.record(n.z.any()).optional().describe("Optional field updates to apply during the transition"),update:n.z.record(n.z.array(n.z.object({set:n.z.any().optional().describe("Set operation for the transition update"),add:n.z.any().optional().describe("Add operation for the transition update"),remove:n.z.any().optional().describe("Remove operation for the transition update")}))).optional().describe("Structured update operations to send alongside the transition"),comment:n.z.string().optional().describe("Optional comment to attach during the transition")}).describe("Inputs needed to transition a Jira issue"),dt={name:"jira-issue-transition",inputSchema:ct,runTool:async(e,t)=>{try{const r=ct.parse(t),s={id:r.transitionId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.comment&&(s.comment={body:Be(r.comment)});const i=await e.issues.transition({issueIdOrKey:r.issueId,transition:s});return Ge(i?.data??i)}catch(e){throw et(e)}}},pt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID for which to list transitions"),expand:n.z.string().optional().describe("Optional expand parameter for the transition response")}).describe("Inputs used to fetch available transitions for an issue"),ut={name:"jira-transition-list",inputSchema:pt,runTool:async(e,t)=>{try{const r=pt.parse(t),s=e.issues;if(!s||"function"!=typeof s.getTransitions)throw Error("Jira transitions API is unavailable on the client");const i={issueIdOrKey:r.issueId};r.expand&&(i.expand=r.expand);const n=await s.getTransitions(i);return Ge(n?.data??n)}catch(e){throw et(e)}}},lt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID to update"),fields:n.z.record(n.z.any()).optional().describe("Direct field map to apply to the issue (e.g., description, labels)"),update:n.z.record(n.z.array(n.z.object({set:n.z.any().optional().describe("Set operation alongside the update key"),add:n.z.any().optional().describe("Add operation alongside the update key"),remove:n.z.any().optional().describe("Remove operation alongside the update key"),edit:n.z.any().optional().describe("Edit operation alongside the update key")}))).optional().describe("Structured update operations for array/set fields"),properties:n.z.array(n.z.any()).optional().describe("Property payloads to attach to the issue"),notifyUsers:n.z.boolean().optional().default(!0).describe("Whether to notify watchers when the issue is updated"),issueTemplateId:n.z.string().optional().describe("Optional template ID to render issue descriptions"),overrideScreenSecurity:n.z.boolean().optional().default(!1).describe("Temporarily bypass screen security restrictions"),overrideEditableFlag:n.z.boolean().optional().default(!1).describe("Temporarily bypass the editable flag on the screen")}).describe("Arguments used to update existing Jira issues"),mt=r.Logging.for("jira.rate-limit"),ht=le.jira.rateLimitRetryDelayMs??3e3;let ft=!1;const yt="jira-issue-update",gt=lt,bt={name:yt,inputSchema:gt,runTool:async(e,t)=>{try{const r=gt.parse(t),s={issueIdOrKey:r.issueId};r.fields&&(s.fields=(e=>{const t={...e},r=t.description;var s;return(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"doc"===t.type&&1===t.version&&Array.isArray(t.content)})(r)&&(t.description=(s=r,{...s,content:We(s.content??[])})),t})(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 i=await(async(e,t)=>{try{return await t()}catch(s){if((e=>{const t=(e=>e?.status??e?.statusCode??e?.response?.status??e?.response?.statusCode??void 0)(e);if(403!==t)return!1;const r=(e=>{const t=e?.response?.data??e?.data??e?.response?.body??e,r=[];return"string"==typeof t&&r.push(t),"string"==typeof t?.message&&r.push(t.message),"string"==typeof t?.errorMessage&&r.push(t.errorMessage),Array.isArray(t?.errorMessages)&&r.push(...t.errorMessages.filter(e=>"string"==typeof e)),"string"==typeof t?.details?.message&&r.push(t.details.message),r.join(" ")||""})(e);return/rate\s?limit/i.test(r)})(s))return ft||(mt.warn(`Jira rate limit detected for ${e}; waiting ${ht}ms before retrying.`,{retryDelayMs:ht}),ft=!0),ht>0&&await(r=ht,new Promise(e=>setTimeout(e,r))),t();throw s}var r})(yt,()=>e.issues.editIssue(s));return Ge(i?.data??i)}catch(e){throw et(e)}}},wt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID for the assignment change"),assignee:n.z.union([n.z.string().describe("Username or account name of the new assignee"),n.z.object({accountId:n.z.string().min(1).describe("Account ID of the assignee")}),n.z.object({accountType:n.z.string().min(1).describe("Account type filter (e.g., user, app)")})]).describe("How the new assignee is specified")}).describe("Arguments required to assign a Jira issue to someone"),vt={name:"jira-assign-issue",inputSchema:wt,runTool:async(e,t)=>{try{const r=wt.parse(t);let s;s="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const i=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:s});return Ge(i?.data??i)}catch(e){throw et(e)}}},It=n.z.object({issueId:n.z.string().min(1)}),St={name:"jira-unassign-issue",inputSchema:It,runTool:async(e,t)=>{try{const r=It.parse(t),s=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return Ge(s?.data??s)}catch(e){throw et(e)}}},jt=n.z.object({issueId:n.z.string().min(1).describe("The Jira issue key or numeric ID receiving the comment"),body:n.z.string().min(1).describe("The markdown-compatible text of the comment"),visibility:n.z.object({type:n.z.enum(["role","group"]).describe("Visibility type that restricts the comment to a role or group"),value:n.z.string().min(1).describe("The name of the role or group granted visibility")}).optional().describe("Optional visibility override controlling who can read the comment")}).describe("Arguments for adding a comment to a Jira issue"),kt={name:"jira-comment-add",inputSchema:jt,runTool:async(e,t)=>{try{const r=jt.parse(t),s=e.issueComments;if(!s||"function"!=typeof s.addComment)throw Error("Jira issueComments API is unavailable on the client");const i={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(i.visibility=r.visibility);const n=await s.addComment(i);return Ge(n?.data??n)}catch(e){throw et(e)}}},xt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID whose comments should be retrieved"),start:n.z.number().optional().default(0).describe("Zero-based index to start pagination from"),maxResults:n.z.number().optional().default(50).describe("Maximum number of comments to return"),orderBy:n.z.string().optional().describe("Field name to order the returned comments by"),expand:n.z.string().optional().describe("Optional expansion clause for the comment response")}).describe("Parameters for fetching comments on a Jira issue"),Tt={name:"jira-comment-list",inputSchema:xt,runTool:async(e,t)=>{try{const r=xt.parse(t),s=e.issueComments;if(!s||"function"!=typeof s.getComments)throw Error("Jira issueComments API is unavailable on the client");const i=await s.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return Ge(i?.data??i)}catch(e){throw et(e)}}},_t=n.z.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"]).describe("The named relationship (Blocks, Relates to, etc.) that describes the link type"),At=n.z.object({id:n.z.string().optional().describe("Numeric Jira ID used when referencing an issue"),key:n.z.string().optional().describe("Human-readable key of the linked issue")}).describe("An issue reference (ID or key) used when building a link payload"),Et=n.z.object({type:n.z.enum(["role","group"]).describe("Visibility scope type attached to the comment"),value:n.z.string().min(1).describe("Name of the role or group granted visibility to the comment")}).describe("Optional visibility settings applied to the comment"),zt=n.z.object({body:n.z.string().optional().describe("Markdown text to include as a linked-comment"),visibility:Et.optional().describe("Optional ACL for the comment")}).describe("Optional comment applied at the time the link is created or updated"),Ot=n.z.object({link:n.z.object({relationship:_t,inwardIssue:At,outwardIssue:At,comment:zt.optional()}).describe("Definition of the link that should be created between two issues")}).describe("Arguments required to create a Jira issue link");let Jt=[];function Ct(e){return(e||"").trim().toLowerCase()}async function Ht(e,t){if(!t)throw Error("Link relationship is required");0===Jt.length&&(Jt=await(async e=>{const t=e.issueLinkTypes;if(!t||"function"!=typeof t.getIssueLinkTypes)throw Error("Jira issueLinkTypes API is unavailable on the client");const r=await t.getIssueLinkTypes(),s=r?.issueLinkTypes??r?.values??r;return Array.isArray(s)?s:[]})(e));const r=Ct(t),s=Jt.find(e=>[e.name,e.inward,e.outward].some(e=>Ct(e)===r));if(!s)throw Error(`No issue link type matching '${t}' found.`);return s}function Nt(e){if(!e)throw Error("Linked issue must include an id or key");if(e.id)return{id:e.id};if(e.key)return{key:e.key};throw Error("Linked issue must include an id or key")}function qt(e){if(!e)return;const t={};return e.body&&(t.body=Be(e.body)),e.visibility&&(t.visibility=e.visibility),Object.keys(t).length>0?t:void 0}const Pt=Ot,Dt={name:"jira-link-create",inputSchema:Pt,runTool:async(e,t)=>{try{const r=Pt.parse(t).link,s={inwardIssue:Nt(r.inwardIssue),outwardIssue:Nt(r.outwardIssue)},i=qt(r.comment);i&&(s.comment=i);const n=e.issueLinks;if(!n||"function"!=typeof n.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const o=await Ht(e,r.relationship);s.type={id:o.id};const a=await n.linkIssues(s);return Ge(a?.data??a)}catch(e){throw et(e)}}},Rt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID receiving the attachment"),file:n.z.string().min(1).describe("Base64 or path to the file contents to upload"),mimeType:n.z.string().optional().describe("Optional MIME type override for the attachment"),comment:n.z.string().optional().describe("Optional comment to associate with the attachment")}).describe("Inputs needed to attach a file to a Jira issue"),$t={name:"jira-attach",inputSchema:Rt,runTool:async(e,r)=>{try{const s=Rt.parse(r),i=c.resolve(s.file),n=await t.promises.readFile(i),o=c.basename(i),a=new FormData;a.append("file",new Blob([n],{type:s.mimeType??"application/octet-stream"}),o);const d=e?.config??null,p=d?.host,u=d?.authentication?.basic??d?.authentication??d?.auth??null,l=u?.email,m=u?.apiToken??u?.apiKey;if(!p||!l||!m)throw Error("Jira client authentication configuration is unavailable for attachments");const h=await fetch(`${p}/rest/api/3/issue/${s.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${l}:${m}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:a});if(!h.ok){const e=await h.text();throw Error(`Jira attachment upload failed (${h.status}): ${e}`)}const f=await h.json();if(s.comment){const t=e.issueComments;if(!t||"function"!=typeof t.addComment)throw Error("Jira issueComments API is unavailable on the client");await t.addComment({issueIdOrKey:s.issueId,comment:Be(s.comment)})}return Ge(f)}catch(e){if(e&&e.code&&"string"==typeof e.code&&["ENOENT","EACCES"].includes(e.code))throw Error("Attachment file error: "+e.message);throw et(e)}}},Lt=n.z.object({issueId:n.z.string().min(1)}),Mt={name:"jira-attachment-list",inputSchema:Lt,runTool:async(e,t)=>{try{const r=Lt.parse(t),s=e.issues;if(!s||"function"!=typeof s.getIssue)throw Error("Jira issues API is unavailable on the client");const i=await s.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),n=i?.data??i;return Ge({attachments:n?.fields?.attachment??[]})}catch(e){throw et(e)}}},Ut=n.z.object({issueId:n.z.string().min(1),attachmentId:n.z.string().min(1)}),Bt={name:"jira-attachment-delete",inputSchema:Ut,runTool:async(e,t)=>{try{const r=Ut.parse(t),s=e.issueAttachments;if(!s||"function"!=typeof s.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await s.removeAttachment({id:r.attachmentId}),Ge({success:!0,message:`Attachment ${t.attachmentId} deleted successfully`})}catch(e){throw et(e)}}},Ft=n.z.object({issueId:n.z.string().min(1).describe("Target issue key or ID for the worklog entry"),timeSpent:n.z.string().min(1).describe('Time spent text (e.g., "1h 30m")'),comment:n.z.string().optional().describe("Optional worklog comment in markdown"),author:n.z.object({accountId:n.z.string().min(1).describe("Account ID of the user logging the work")}).optional().describe("Optional author override for the worklog entry"),startingOn:n.z.string().optional().describe("Optional timestamp for when the work started (ISO)"),artifact:n.z.string().optional().describe("Optional identifier linking the worklog to another artifact")}).describe("Arguments required to add a worklog entry to a Jira issue"),Wt={name:"jira-worklog-add",inputSchema:Ft,runTool:async(e,t)=>{try{const r=Ft.parse(t),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 i=e.issueWorklogs;if(!i||"function"!=typeof i.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const n=await i.addWorklog({issueIdOrKey:r.issueId,...s});return Ge(n?.data??n)}catch(e){throw et(e)}}},Kt=r.Logging.for("jira.xray");class Yt{constructor(){this.clientId=le.orThrow().xray.apiUser,this.clientSecret=le.orThrow().xray.apiSecret,this.baseUrl=le.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 e=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})}),t=await e.text();return this.token=t.replace(/"/g,""),this.token}async graphql(e,t){this.token||await this.authenticate();const r={query:e,variables:t};Kt.info("xray.graphql.request",{payload:ve(r)});try{const e=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify(r)}),t=await e.json();if(Kt.info("xray.graphql.response",{status:e.status,headers:e.headers?.get?e.headers.get("content-type"):void 0,body:ve(t)}),t.errors)throw Kt.error("xray.graphql.errors",{errors:ve(t.errors)}),Error(JSON.stringify(t.errors,null,2));return t.data}catch(e){throw Kt.error("xray.graphql.failure",{error:e+""}),e}}async getTest(e){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:e})).getTest}async addStep(e,t){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:e,step:t})).addTestStep}async updateStep(e,t){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:e,step:t})).updateTestStep}async deleteStep(e){return(await this.graphql("\n mutation RemoveTestStep($stepId: String!) {\n removeTestStep(stepId: $stepId)\n }\n ",{stepId:e})).removeTestStep}async addSteps(e,t){return Promise.all(t.map(t=>this.addStep(e,t)))}async updateSteps(e){return Promise.all(e.map(e=>this.updateStep(e.stepId,e.step)))}async deleteSteps(e){return Promise.all(e.map(e=>this.deleteStep(e)))}async syncSteps(e,t){const r=(await this.getTest(e)).steps||[],s=[],i=[],n=[];for(let e=0;e<t.length;e++){const n=t[e],o=r[e];o?o.action===n.action&&o.data===n.data&&o.result===n.result||s.push({stepId:o.id,step:n}):i.push(n)}if(r.length>t.length)for(let e=t.length;e<r.length;e++)n.push(r[e].id);await this.addSteps(e,i),await this.updateSteps(s),await this.deleteSteps(n)}}let Xt=null;const Gt=new Map;function Vt(e){const t=e?.fields,r=e?.action??t?.Action??t?.action;if(!r||"string"!=typeof r)throw Error("Xray step action is required");const s=e.data??e.fields?.Data??e.fields?.data??void 0,i=e.result??e.fields?.Result??e.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof s?s:void 0,result:"string"==typeof i?i:void 0}}async function Zt(e,t){if(!t)throw Error("Issue reference is required when interacting with Xray steps");if(Gt.has(t))return Gt.get(t);if(/^[0-9]+$/.test(t))return Gt.set(t,t),t;const r=e?.issues??e?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const s=await r.getIssue({issueIdOrKey:t,fields:["id"]}),i=s?.id;if(!i)throw Error("Unable to resolve Jira issue ID for "+t);return Gt.set(t,i),i}async function Qt(e){if(e?.test?.step)return e.test.step;const t=await(async()=>{if(Xt)return Xt;const e=le.orThrow().xray.apiUser?.trim(),t=le.orThrow().xray.apiSecret?.trim();if(!e||!t)throw Error("Xray credentials are missing (XRAY__API_USER, XRAY__API_SECRET). Please configure them before using Xray tools.");const r=Se(),s=new Yt;return Xt={test:{step:{async createStep(e,t){const i=await Zt(r,e),n=await s.addStep(i,Vt(t));return{step:n,id:n?.id}},async updateStep(e,t,i){await Zt(r,e);const n=Vt(i),o=await s.updateStep(t.toString(),n);return{step:o,id:o?.id}},deleteStep:async(e,t)=>(await Zt(r,e),{success:!0===await s.deleteStep(t.toString())}),async getSteps(e){const t=await Zt(r,e),i=await s.getTest(t);return{steps:i?.steps??[]}}}}},Xt})();if(!t?.test?.step)throw Error("Xray step API is unavailable on the client");return t.test.step}const er=n.z.object({issueId:n.z.string().min(1),action:n.z.string().min(1),data:n.z.string().optional(),result:n.z.string().optional()}),tr={name:"jira-xray-step-add",inputSchema:er,runTool:async(e,t)=>{try{const r=er.parse(t),s=await Qt(e),i={action:r.action,data:r.data,result:r.result};return Ge(await s.createStep(r.issueId,i))}catch(e){throw et(e)}}},rr=n.z.object({issueId:n.z.string().min(1),stepId:n.z.union([n.z.string(),n.z.number()]),action:n.z.string().min(1),data:n.z.string().optional(),result:n.z.string().optional()}),sr={name:"jira-xray-step-update",inputSchema:rr,runTool:async(e,t)=>{try{const r=rr.parse(t),s=await Qt(e),i=r.stepId+"",n={action:r.action,data:r.data,result:r.result};return Ge(await s.updateStep(r.issueId,i,n))}catch(e){throw et(e)}}},ir=n.z.object({issueId:n.z.string().min(1),stepId:n.z.union([n.z.string(),n.z.number()])}),nr={name:"jira-xray-step-delete",inputSchema:ir,runTool:async(e,t)=>{try{const r=ir.parse(t),s=await Qt(e);return await s.deleteStep(r.issueId,r.stepId.toString()),Ge({success:!0})}catch(e){throw et(e)}}},or=n.z.object({issueId:n.z.string().min(1)}),ar={name:"jira-xray-step-list",inputSchema:or,runTool:async(e,t)=>{try{const r=or.parse(t),s=await Qt(e);return Ge(await s.getSteps(r.issueId))}catch(e){throw et(e)}}},cr=n.z.object({linkId:n.z.string().min(1)}),dr={name:"jira-link-delete",inputSchema:cr,runTool:async(e,t)=>{try{const r=cr.parse(t),s=e.issueLinks;if(!s||"function"!=typeof s.deleteIssueLink)throw Error("Jira issueLinks API is unavailable on the client");return await s.deleteIssueLink({linkId:r.linkId}),Ge({success:!0,message:`Issue link ${r.linkId} deleted successfully`})}catch(e){throw et(e)}}},pr=n.z.object({linkId:n.z.string().min(1).describe("ID of the existing issue link to change"),relationship:_t,comment:zt.optional().describe("Optional comment to attach while recreating the link")}).describe("Inputs required to update (recreate) a Jira issue link"),ur={name:"jira-link-update",inputSchema:pr,runTool:async(e,t)=>{try{const r=pr.parse(t),s=e.issueLinks;if(!s||"function"!=typeof s.getIssueLink||"function"!=typeof s.deleteIssueLink||"function"!=typeof s.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const i=await s.getIssueLink({linkId:r.linkId}),n=i?.data??i;if(!n)throw Error(`Issue link ${r.linkId} not found`);const o=n.inwardIssue,a=n.outwardIssue;if(!o||!a)throw Error("Issue link payload is missing linked issues");const c=await Ht(e,r.relationship);await s.deleteIssueLink({linkId:r.linkId});const d={inwardIssue:Nt(o),outwardIssue:Nt(a),type:{id:c.id}},p=qt(r.comment);return p&&(d.comment=p),await s.linkIssues(d),Ge({success:!0,message:`Issue link ${r.linkId} updated to ${r.relationship}`})}catch(e){throw et(e)}}},lr={[Ve.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[at.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[nt.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}},[bt.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}},[rt.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[dt.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ut.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[vt.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[St.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[kt.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}},[Tt.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Dt.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ur.name]:{title:"Jira Link Update",description:"Change the relationship type for an existing issue link",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[dr.name]:{title:"Jira Link Delete",description:"Delete an issue link from Jira",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[$t.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Mt.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Bt.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Wt.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[tr.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[sr.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[nr.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[ar.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 mr(e){const t=r.Logging.for(mr);let s,i=null;try{s=Se()}catch(e){if(!(e instanceof ye))return void t.warn("Skipping Jira tool registration; unable to create Jira client",{error:e});i=e,t.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:e})}const n=[Ve,at,nt,bt,rt,dt,ut,vt,St,kt,Tt,Dt,ur,dr,$t,Mt,Bt,Wt,tr,sr,nr,ar];for(const r of n){const n=lr[r.name];if(n)try{await e.registerTool(r.name,{title:n.title,description:n.description,inputSchema:r.inputSchema,annotations:n.annotations},async e=>{if(!s)throw i??Error("Jira client unavailable because credentials could not be loaded.");return r.runTool(s,e)}),t.info("Registered Jira tool "+r.name)}catch(e){t.error("Failed to register Jira tool "+r.name,{error:e})}}}async function hr(e){await(async e=>{e.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 e=ie.map(e=>e.getName()).sort();return{content:[{type:"text",text:["Name: "+le.name,"Title: "+le.title,"Version: "+le.version,"Prompts: "+(e.join(", ")||"<none>")].join("\n")}]}})})(e);const t=r.Logging.for(hr);try{await mr(e)}catch(e){t.error("Failed to register Jira tools",e)}}class fr extends C{setCb(e){return this.cb=e,this}setConfig(e){return this.config=e,this}setUriOtTemplate(e){return this.uriOrTemplate=e,this}constructor(e){super(e)}static get builder(){return new fr}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{const t="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new w.ResourceTemplate(new b.UriTemplate(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),s=async(e,t)=>{const r=this.logFor(t);r.verbose(`Requesting resource ${this.name} from ${e.toString()}`);const s=await Promise.resolve(this.cb(e,t));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(s._meta)),s};return e.resource(this.name,t,r,s)}catch(e){throw r.Logging.for(this).error("Error registering resource "+this.name,e),e}}}s.__decorate([i.required(),s.__metadata("design:type",String)],fr.prototype,"uriOrTemplate",void 0),s.__decorate([i.required(),s.__metadata("design:type",Function)],fr.prototype,"cb",void 0),s.__decorate([i.required(),s.__metadata("design:type",Object)],fr.prototype,"config",void 0);const yr=K()??x.join(__dirname,"..","assets"),gr=x.join(yr,"templates"),br=x.join(yr,"prompts"),wr=new WeakMap;class vr extends r.LoggedClass{get client(){const e=wr.get(this);if(!e)throw Error("Mcp server requires Mcp client");return e}constructor(){super()}async load(){const e=this.log.for(this.load);for(const t of ie)try{e.info("loading prompt "+t.getName());const r=t.build(this.client);e.verbose(`Loaded prompt ${r.title} from ${t.getName()} definition`)}catch(r){e.error("Failed to load prompt "+t.getName(),r)}try{await hr(this.client),e.verbose("Registered built-in tools")}catch(e){}try{await(async(e,t)=>{t.info("Registering agent templates as resources...");const r=k.readdirSync(gr).filter(e=>e.endsWith(".md"));for(const s of r){const r=x.basename(s,".md"),i=x.join(gr,s),n=fr.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+r}).setCb(async e=>{const t=k.readFileSync(e.pathname,"utf8");return{contents:[{uri:e.toString(),text:t,mimeType:"text/markdown"}],_meta:{}}});try{n.build(e),t.info("Registered template: "+r)}catch(e){t.error(`Failed to register template ${r}:`,e)}}t.info("Registering agent prompts...");const s=k.readdirSync(br).filter(e=>e.endsWith(".md"));for(const r of s){const s=x.basename(r,".md"),i=x.join(br,r),o=k.readFileSync(i,"utf8"),a=X.builder.setName(s).setTitle("Prompt: "+s).setDescription("Dynamic prompt for "+s).setArgsSchema(n.z.object({})).setCb(async e=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(e),t.info("Registered prompt: "+s)}catch(e){t.error(`Failed to register prompt ${s}:`,e)}}})(this.client,e)}catch(e){}}async boot(e="stdio"){"stdio"===e&&r.Logging.setFactory(_),r.Logging.for(this.constructor.name);const t=((Array.isArray(le.icons)?le.icons:[le.icons])||[]).map(e=>{const t="string"==typeof e?.src?e.src:(e?.src??"")+"",r="string"==typeof e?.mimeType?e.mimeType:(e?.mimeType??"")+"";let s=[];return Array.isArray(e?.sizes)?s=e.sizes.map(e=>e+""):"string"==typeof e?.sizes&&(s=(e.sizes+"").split(",").map(e=>e.trim())),{src:t,mimeType:r,sizes:s}}),s={name:le.name,title:le.title,websiteUrl:le.websiteUrl,version:le.version,icons:t},i=new w.McpServer(s,{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(((e,t)=>{wr.set(e,t)})(this,i),i.onerror=e=>{this.log.error("MCP instance onerror",e)},e){case"stdio":e=new I.StdioServerTransport;break;case"http":e=new S.StreamableHTTPServerTransport({sessionIdGenerator:()=>v.v4(),onsessioninitialized:e=>{},onsessionclosed:e=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(n=e)||"object"!=typeof n||"function"!=typeof n.send&&"function"!=typeof n.close&&"function"!=typeof n.on)throw new d.InternalError("Invalid transport type: "+e)}var n;try{await this.load()}catch(e){throw e}await this.client.connect(e)}}const Ir=(new e.Command).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async e=>{const r=F("package.json"),s=JSON.parse(t.readFileSync(r,"utf-8")),i=s.version,{transport:n}=e,o=(new T).for("mcp-server");if("stdio"!==n)throw Error("Unsupported transport mode: "+n);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(e)} for ${s.name} version ${i}`),(new vr).boot(n)});(new e.Command).command("md-to-ast").description("pipes markdown to jira ast: `cat file.md` | npx decaf-mcp md-to-ast > ast.json").action(async e=>{const s=F("package.json"),i=JSON.parse(t.readFileSync(s,"utf-8")),n=i.version;r.Logging.for("md-to-ast").debug(`running with options: ${JSON.stringify(e)} for ${i.name} version ${n}`);const o=Be(await(async()=>{const e=[];for await(const t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")})(),{resolveMention:e=>({id:e,text:"@"+e}),resolveAttachment:e=>({id:e,collection:"attachments"})});process.stdout.write(JSON.stringify(o,null,2)+"\n")});const Sr=(new e.Command).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");Sr.addCommand(Ir),Sr.parse(process.argv)},"object"==typeof exports&&"undefined"!=typeof module?t(require("commander"),require("fs"),require("@decaf-ts/logging"),require("tslib"),require("@decaf-ts/decorator-validation"),require("zod"),require("@decaf-ts/injectable-decorators"),require("@decaf-ts/decoration"),require("path"),require("@decaf-ts/db-decorators"),require("crypto"),require("zlib"),require("url"),require("node:util"),require("unified"),require("remark-directive"),require("remark-gfm"),require("remark-parse"),require("@modelcontextprotocol/sdk/shared/uriTemplate.js"),require("@modelcontextprotocol/sdk/server/mcp.js"),require("uuid"),require("@modelcontextprotocol/sdk/server/stdio.js"),require("@modelcontextprotocol/sdk/server/streamableHttp.js")):"function"==typeof define&&define.amd?define(["commander","fs","@decaf-ts/logging","tslib","@decaf-ts/decorator-validation","zod","@decaf-ts/injectable-decorators","@decaf-ts/decoration","path","@decaf-ts/db-decorators","crypto","zlib","url","node:util","unified","remark-directive","remark-gfm","remark-parse","@modelcontextprotocol/sdk/shared/uriTemplate.js","@modelcontextprotocol/sdk/server/mcp.js","uuid","@modelcontextprotocol/sdk/server/stdio.js","@modelcontextprotocol/sdk/server/streamableHttp.js"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).commander,e.fs,e.decafTsLogging,e.tslib,e.decafTsDecoratorValidation,e.zod,e.decafTsInjectableDecorators,e.decafTsDecoration,e.path,e.decafTsDbDecorators,e.crypto,e.zlib,e.url,e.node_util,e.unified,e.remarkDirective,e.remarkGfm,e.remarkParse,e.uriTemplate_js,e.mcp_js,e.uuid,e.stdio_js,e.streamableHttp_js);
2
+ var e,t;e=this,t=function(e,t,r,s,i,n,o,a,c,d,u,p,l,m,h,f,y,g,b,w,v,I,S){"use strict";function j(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var k=j(t),x=j(c);class T extends r.MiniLogger{constructor(e,t,r){super(e,t,r)}log(e,t,s,i){const n=this.config("level");r.NumericLogLevels[n],r.NumericLogLevels[e]}}const _=(e,t,...r)=>{const s=(e=>{if("string"==typeof e)return e;if(!e)return"unknown";if("function"==typeof e)return e.name||"unknown";if("object"==typeof e&&"constructor"in e){const t=e.constructor;if(t&&t.name)return t.name}return"unknown"})(e);return new T(s,t)};var A,E,z,O,J;(e=>{e[e.NONE=0]="NONE",e[e.BASIC=1]="BASIC",e[e.ADVANCED=2]="ADVANCED",e[e.HIGH=3]="HIGH"})(A||(A={})),(e=>{e[e.NONE=0]="NONE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(E||(E={})),(e=>{e[e.FREE=0]="FREE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(z||(z={}));class C extends i.Model{get log(){return this._log||(this._log=r.Logging.for(this)),this._log}constructor(e){super(e)}logFor(e){const{sessionId:t,requestId:r,authInfo:s}=e||{};let i="string"==typeof t&&t.length>0?this.log.for(t):this.log;return s&&s.clientId&&(i=i.for(s.clientId)),r&&(i=i.for(r.toString())),i}setDescription(e){return this.description=e,this}getDescription(){return this.description}setName(e){return this.name=e,this}getName(){return this.name}setTitle(e){return this.title=e,this}}s.__decorate([i.required(),s.__metadata("design:type",String)],C.prototype,"description",void 0),s.__decorate([i.required(),s.__metadata("design:type",String)],C.prototype,"name",void 0),s.__decorate([i.required(),s.__metadata("design:type",String)],C.prototype,"title",void 0);class H extends C{constructor(e){super(e),this.reasoning=A.NONE,this.effort=E.NONE,this.cost=z.FREE}setReasoning(e){return this.reasoning=e,this}setEffort(e){return this.effort=e,this}setCost(e){return this.cost=e,this}}function N(e){if(!e)return;let t=e,r=t&&t._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)t=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)t=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)t=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)t=r.innerType;else{if(!r.schema)return;t=r.schema}r=t&&t._def}return r&&"ZodObject"===r.typeName?r:void 0}function q(e,t="schema"){if(N(e))return e;if(e&&"object"==typeof e){const t=e.def&&"object"==typeof e.def?e.def:void 0,r=t&&(t.shape||"object"===t.type)&&t.shape||("object"===e.type?e.shape:void 0)||(t&&"object"===t.type?{}:void 0);if(t||"object"===e.type||r){const e={};if(r&&"object"==typeof r)for(const[t,s]of Object.entries(r))e[t]=P(s)?s:n.z.any();return n.z.object(e)}}throw Error(`Registration error: provided a non-canonical ${t}. Export a ZodObject (z.object(...)).`)}function D(e){if(!e)return;if(e&&"object"==typeof e&&!e._def)return e.def&&"object"==typeof e.def&&e.def.shape?e.def.shape:e;const t=N(e);return t?"function"==typeof t.shape?t.shape():t.shape||void 0:void 0}function P(e){return!(!e||"object"!=typeof e||!e._def)}s.__decorate([i.required(),s.__metadata("design:type",Number)],H.prototype,"reasoning",void 0),s.__decorate([i.required(),s.__metadata("design:type",Number)],H.prototype,"effort",void 0),s.__decorate([i.required(),s.__metadata("design:type",Number)],H.prototype,"cost",void 0),(e=>{e.ASSETS="assets"})(O||(O={})),(e=>{e.PROMPT="prompts",e.DOCUMENTATION="documentation",e.CODE="code"})(J||(J={}));const R=Buffer.from("DCAF1","ascii");function $(e){let r=c.resolve(e);for(;;){if(t.existsSync(c.join(r,"package.json")))return r;const e=c.dirname(r);if(e===r)break;r=e}}const L=process.argv?.[1]?$(c.dirname(c.resolve(process.argv[1]))):void 0,M=(()=>{const e=Error().stack;if(!e)return;const t=e.split(/\r?\n/).slice(1);for(const e of t){const t=e.match(/\(?([^()]+?):\d+:\d+\)?/);if(!t)continue;let r=t[1];if(r.startsWith("file://"))try{r=l.fileURLToPath(r)}catch{continue}if(!r.includes("node:internal"))return c.dirname(r)}})(),U=M?$(M):void 0,F=L??U??process.cwd();function B(...e){return c.join(F,...e)}function W(e){let t=e;for(;;){const e=x.join(t,"lib","assets");if(k.existsSync(e))return e;const r=x.join(t,"src","assets");if(k.existsSync(r))return r;const s=x.join(t,"assets");if(k.existsSync(s))return s;const i=x.dirname(t);if(i===t)break;t=i}}function K(){const e=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(e&&k.existsSync(e))return e;const t=W(__dirname);if(t)return t;const r=process.argv?.[1];if(r){const e=W(x.dirname(r));if(e)return e}const s=[F,process.env.INIT_CWD].filter(Boolean);for(const e of s){const t=W(e);if(t)return t}return B("assets")}let X=class extends r.LoggedClass{constructor(e){super(),this.basePath=e||K()}listAssets(...e){const t=x.join(this.basePath,...e);return k.readdirSync(t)}listPrompts(){return this.listAssets(J.PROMPT)}getAsset(e,t="md",...r){const s=x.join(this.basePath,...r),i=(e,t=!1)=>{try{return t?(e=>{if(e.length<R.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!e.subarray(0,R.length).equals(R))throw Error("Invalid prompt payload (bad magic)");const t=process.env.ENCRYPTION_KEY||"";if(!t)throw Error("Missing encryption key. Set ENCRYPTION_KEY to load obfuscated assets.");let r=R.length;const s=e.subarray(r,r+16);r+=16;const i=e.subarray(r,r+12);r+=12;const n=e.subarray(r,r+16);r+=16;const o=e.subarray(r),a=((e,t)=>u.scryptSync(e,t,32))(t,s),c=u.createDecipheriv("aes-256-gcm",a,i);c.setAuthTag(n);const d=Buffer.concat([c.update(o),c.final()]);return p.gunzipSync(d)})(k.readFileSync(e)).toString("utf-8"):k.readFileSync(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}},n=i(x.join(s,`${e}.${t}`),"enc"===t);if(null!==n)return n;const o=i(x.join(s,e+".enc"),!0);if(null!==o)return o;throw Error("Asset not found: "+x.join(s,`${e}.${t}`))}getAllAssets(e,...t){return this.listAssets(e,...t).reduce((r,s)=>{const i=x.extname(s),n=x.basename(s,i),o=i.replace(/^\./,"")||void 0;return r[n]=this.getAsset(n,o??void 0,e,...t),r},{})}toPromptDef(e){const t=e=>"number"==typeof e?e:"string"==typeof e?(e=>{switch(e){case"none":return A.NONE;case"basic":return A.BASIC;case"advanced":return A.ADVANCED;case"high":return A.HIGH;case"medium":return E.MEDIUM;case"low":return z.LOW;case"free":return z.FREE;default:throw new d.InternalError("Cannon convert unknown level "+e)}})(e.toLowerCase()):A.NONE;return e.effort=t(e.effort),e.reasoning=t(e.reasoning),e.cost=t(e.cost),e}getPrompt(e,...t){const s=this.getAsset(r.toSnakeCase(e),"json",J.PROMPT,...t);let i;try{i=JSON.parse(s)}catch(r){throw new d.SerializationError(`Failed to parse prompt ${e} in categories ${t}: ${r}`)}return this.toPromptDef(i)}getAllPrompts(...e){const t=this.getAllAssets(J.PROMPT,...e);return Object.entries(t).reduce((t,[r,s])=>{try{t[r]=JSON.parse(s)}catch(t){throw new d.SerializationError(`Failed to parse prompt ${r} in categories ${e}: ${t}`)}return t},t)}};X=s.__decorate([o.injectable(),s.__metadata("design:paramtypes",[String])],X);class Y extends H{constructor(e){super(e)}setCb(e){return this.cb=e,this}setArgsSchema(e){return this.argsSchema=e,this}static get builder(){return new Y}static patchPrompt(e,t,s,i){const n=(t=Array.isArray(t)?t:Object.keys(t)).filter(e=>!Object.prototype.hasOwnProperty.call(s,e));if(n.length)throw new d.ValidationError("Missing replacements for placeholders: "+n.join(", "));i&&(i.verbose("Patching prompt with placeholders: "+JSON.stringify(t)),i.debug("Values: "+JSON.stringify(s)));const o=t.reduce((e,t)=>(e[t]=s[t],e),{});return r.sf(e,o)}patchPrompt(e,t,r,s){return Y.patchPrompt(e,t,r,s||this.log.for(this.patchPrompt))}build(e,t){const r=this.log.for(this.build),s=this.hasErrors();if(s)throw new d.ValidationError(s.toString());try{this.argsSchema&&q(this.argsSchema,"argsSchema");const r=D(this.argsSchema);return e.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(e,r)=>{const s=this.logFor(r);e=Object.assign({},t,e||{}),s.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(e)}`),e._meta=Object.assign(e._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const i=await Promise.resolve(this.cb(e,r));return s.verbose(`Prompt ${this.name} executed successfully.`),s.debug("Prompt execution meta: "+JSON.stringify(i._meta)),i})}catch(e){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),e),e}}}s.__decorate([o.inject(X),s.__metadata("design:type",X)],Y.prototype,"assets",void 0),s.__decorate([i.required(),s.__metadata("design:type",Object)],Y.prototype,"cb",void 0),s.__decorate([i.required(),s.__metadata("design:type",n.ZodObject)],Y.prototype,"argsSchema",void 0),s.__decorate([a.prop(),s.__metadata("design:type",Object)],Y.prototype,"placeholders",void 0);class G extends Y{setCategory(e){return this.promptCategory=e,this}addPrefix(e){return this.prefixes=this.prefixes||[],this.prefixes.push(e),this}addSuffix(e){return this.suffixes=this.suffixes||[],this.suffixes.push(e),this}constructor(e){super(e)}build(e){const t=this.assets.getPrompt(this.name,this.promptCategory);i.Model.fromObject(this,t);const r=new Set((a.Metadata.properties(G)||[]).filter(e=>!["assets","promptCategory","prefixes","suffixes"].includes(e)));["cb","argsSchema"].forEach(e=>r.add(e));const s=this.hasErrors(...Array.from(r));if(s)throw new d.ValidationError(s.toString());const o=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),c=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),u=[...new Set([...t.placeholders,...o.map(e=>e.placeholders||[]),...c.map(e=>e.placeholders||[])].flat())].reduce((e,t)=>(e[t]=n.z.string().describe("The description for "+t),e),{});return this.setArgsSchema(n.z.object(u)),this.setCb((e,t)=>{const r=this.logFor(t).for(G).for(this.promptCategory).for(this.name);function s(e=[]){return Array.isArray(e)?e:Object.keys(e)}const i=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),n=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...i.map(e=>s(e.placeholders)).flat(),...n.map(e=>s(e.placeholders)).flat(),...s(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...i.map(e=>e.prompt),o.prompt,...n.map(e=>e.prompt)].join("\n\n"),a,e,r)}}],_meta:{}}}),super.build(e)}setReasoning(e){throw new d.InternalError("Named prompt builders don't require callback")}setEffort(e){throw new d.InternalError("Named prompt builders don't require callback")}setCost(e){throw new d.InternalError("Named prompt builders don't require callback")}setDescription(e){throw new d.InternalError("Named prompt builders don't require callback")}setTitle(e){throw new d.InternalError("Named prompt builders don't require callback")}static get builder(){return new G}}s.__decorate([i.required(),s.__metadata("design:type",String)],G.prototype,"promptCategory",void 0),s.__decorate([i.list(String),i.minlength(1),s.__metadata("design:type",Array)],G.prototype,"prefixes",void 0),s.__decorate([i.minlength(1),i.list(String),s.__metadata("design:type",Array)],G.prototype,"suffixes",void 0);const V=Y.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(n.z.object({message:n.z.string().optional()})).setCb(async e=>{const t=e.message??"default";return{messages:[{role:"assistant",content:{type:"text",text:t}}],content:[],structuredContent:{message:t},result:{message:t}}}),Z=Y.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc prompt").setDescription("Interactive prompt for jogging JSDoc helpers").setArgsSchema(n.z.object({gist:n.z.string().optional()})).setCb(async e=>{const t=e.gist??"interactive jsdoc response";return{messages:[{role:"assistant",content:{type:"text",text:t}}],content:[],structuredContent:{message:t},result:{message:t}}}),Q=Object.assign(Z,{name:Z.getName()});var ee;function te(e,t=[],r=[]){const s=G.builder.setCategory(ee.DOCS).setName(e);return["prefix",...t].forEach(e=>s.addPrefix(e)),["suffix",...r].forEach(e=>s.addSuffix(e)),s}(e=>{e.DOCS="documentation",e.CODE="code"})(ee||(ee={}));const re=[te("class"),te("constant"),te("decorator"),te("function"),te("module"),te("file"),te("repo",[],["iterate"])],se=n.z.object({className:n.z.string().describe("the class name to turn into a builder")}),ie=[V,Q,...re,Y.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(se).setReasoning(A.BASIC).setCb((e,t)=>(e.className=r.toPascalCase(e.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 ${e.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 ${e.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<${e.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[]): ${e.className}Builder | Promise<${e.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(): ${e.className}Builder {\n return new ${e.className}Builder(); // static method to get a new builder instance\n }\n \n static from<K extends keyof ${e.className}Builder>(obj: K, ${e.className}Builder[K]): ${e.className}Builder {\n return new ${e.className}Builder(); // static method to create a builder from an object\n }\n}\n\`\`\` \n\n`}}],_meta:{}}))];class ne extends H{setAnnotations(e){return this.annotations=Object.assign(this.annotations,e),this}setCb(e){return this.cb=e,this}setInputSchema(e){return this.inputSchema=e,this}setOutputSchema(e){return this.outputSchema=e,this}constructor(e){super(e),this.annotations={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}}static get builder(){return new ne}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{this.inputSchema&&q(this.inputSchema,"inputSchema"),this.outputSchema&&q(this.outputSchema,"outputSchema");const t=D(this.inputSchema),r=D(this.outputSchema);return e.registerTool(this.name,{title:this.title,description:this.description,inputSchema:t,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(e,t)=>{const r=this.logFor(t);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(e)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(e,t));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(s._meta)),s})}catch(e){const t=e?.message||e+"";if("string"==typeof t&&t.includes("already registered"))return r.Logging.for(this).warn(`Tool ${this.name} already registered - skipping duplicate registration`),{name:this.name};throw r.Logging.for(this).error("Error building tool",e),e}}}s.__decorate([i.required(),s.__metadata("design:type",Object)],ne.prototype,"annotations",void 0),s.__decorate([i.required(),s.__metadata("design:type",Object)],ne.prototype,"cb",void 0),s.__decorate([i.required(),s.__metadata("design:type",Function)],ne.prototype,"inputSchema",void 0);const oe=ne.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(n.z.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(oe,{name:oe.getName()});const ae=ne.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(n.z.object({filePath:n.z.string().optional()})).setCb(async()=>({content:[{type:"text",text:"file summary stub"}],result:{summary:"file summary stub"}}));function ce(){try{let e=process.argv[1]?c.dirname(c.resolve(process.argv[1])):process.cwd();for(;;){const r=c.join(e,"package.json");if(t.existsSync(r))return JSON.parse(t.readFileSync(r,"utf-8"));const s=c.dirname(e);if(s===e)break;e=s}}catch{}return{}}Object.assign(ae,{name:ae.getName()});const de=ce().version??"0.0.0",ue=ce().name??"unknown";a.Metadata.registerLibrary(ue,de);const pe={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:de,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:F,assetDir:K(),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,timeout:process.env.JIRA__TIMEOUT?parseInt(process.env.JIRA__TIMEOUT):1e3,rateLimitRetryDelayMs:process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS?parseInt(process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS):3e3},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:r.LogLevel.error},le=r.LoggedEnvironment.accumulate(pe);function me(){const{host:e,email:t,apiKey:r,projectKey:s,issueType:i}=le.jira;return{host:e?.trim(),email:t?.trim(),apiKey:r?.trim(),projectKey:s?.trim(),issueType:i?.trim(),parentIssue:le.jira.parentIssue?.trim()}}function he(){const e=me();return[{name:"JIRA__HOST",required:!0,description:"Atlassian host (e.g. decaf-ts.atlassian.net) where your Jira instance is hosted.",value:e.host},{name:"JIRA__EMAIL",required:!0,description:"Email address of the Jira account that has API access.",value:e.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:e.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:e.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:e.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:e.parentIssue}]}function fe(e){const t=e.value?((e,t)=>{if(e)return t?"<configured>":e})(e.value,e.sensitive):"not set",r=e.required?"(required)":"(optional)";return`\u2022 ${e.name} ${r}: ${e.description} Current state: ${t}.`}r.Logging.setConfig(le);class ye extends Error{constructor(e){const t=he(),r=(e=>{const t=he();return`${e.length?`Missing Jira credentials: ${e.map(e=>e.name).join(", ")}.`:"Jira credentials are configured."}\n\nThis setup uses the following environment variables:\n${t.map(fe).join("\n")}`})(e);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=t,this.missing=e,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,ye)}}const ge=r.Logging.for("jira.client"),be=/(authorization|cookie)/i;function we(e){if(!e)return;const t=e.baseURL??"",r=e.url??"";return t&&r?`${t.endsWith("/")?t.slice(0,-1):t}/${r.startsWith("/")?r.slice(1):r}`:r||t||void 0}function ve(e){if(void 0!==e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch(t){return m.inspect(e,{depth:null})}}}function Ie(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,r])=>{t[e]=be.test(e)&&r?"[REDACTED]":r}),t}function Se(e){let t;try{const e=require("jira.js");t=e?.Version3Client||e.default?.Version3Client||e.default||e}catch(e){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+e)}const{host:r,email:s,apiKey:i}=(()=>{const e=me(),t=he().filter(e=>e.required&&!e.value);if(t.length>0)throw new ye(t);return{host:e.host,email:e.email,apiKey:e.apiKey}})(),n=new t({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:s,apiToken:i}},baseRequestConfig:{headers:{Accept:"application/json","Content-Type":"application/json"}}});return(e=>{if(!e)return;const t="__jiraLoggingAttached";e[t]||(e[t]=!0,e.interceptors.request.use(e=>{e.headers=(e=>{const t={...e||{}};return Object.keys(t).some(e=>"accept"===e.toLowerCase())||(t.Accept="application/json"),Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),t})(e.headers);const t=(e.method??"GET").toString().toUpperCase(),r=we(e);return ge.info("jira.request",{method:t,url:r,headers:Ie(e.headers),params:e.params,data:ve(e.data)}),e},e=>(ge.error("jira.request.error",{message:e.message}),Promise.reject(e))),e.interceptors.response.use(e=>{const t=(e.config?.method??"GET").toString().toUpperCase(),r=we(e.config);return ge.info("jira.response",{method:t,url:r,status:e.status,headers:Ie(e.headers),data:ve(e.data)}),e},e=>{const t=e.config,r=e.response,s=(t?.method??"GET").toString().toUpperCase(),i=we(t);return ge.error("jira.response.error",{method:s,url:i,status:r?.status,headers:Ie(r?.headers),data:ve(r?.data),message:e.message}),Promise.reject(e)}))})(n.instance),n}const je=n.z.object({name:n.z.string().min(1).optional().describe("Optional template name that pre-populates additional fields"),content:n.z.string().min(1).describe("Markdown template content to apply when constructing the description"),placeholders:n.z.record(n.z.string()).optional().describe("Map of placeholder replacements used by the template")}).describe("Template metadata used to adjust the created description"),ke=n.z.object({template:je.optional().describe("Optional template settings for this create request")}).describe("Additional template controls available when creating an issue"),xe=n.z.union([n.z.object({fields:n.z.record(n.z.any()).describe("Full raw field map that gets delivered to Jira")}).merge(ke).describe("Create argument that supplies every field explicitly"),n.z.object({summary:n.z.string().min(1).describe("Title or summary of the new issue"),projectKey:n.z.string().min(1).describe("Project key where the issue is created"),issueType:n.z.string().min(1).describe("Type name for the new issue (story, task, etc.)"),description:n.z.string().optional().describe("Optional textual description for the issue")}).merge(ke).describe("Create argument with minimal required identifiers plus optional description")]).describe("Union describing how to create an issue either via raw fields or shorthand properties");function Te(e,t,r){const s=((e.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!s)return null;const i=s[2],n=r.resolveAttachment?.(i);return n?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:n.id,collection:n.collection??"attachments"}}]}}:null}function _e(e,t){if(!e)return[];if(!t.enableAtMentions&&!t.enableEmojiShortcodes)return[{type:"text",text:e}];let r=0;const s=[],i=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,n=/:([a-z0-9_+-]{1,64}):/gi;for(;r<e.length;){const o=Ee(t.enableAtMentions?Ae(i,e,r):null,t.enableEmojiShortcodes?Ae(n,e,r):null);if(!o){s.push({type:"text",text:e.slice(r)});break}if(o.index>r&&s.push({type:"text",text:e.slice(r,o.index)}),"mention"===o.kind){const{full:e,groups:i}=o,n=i[0]??"",a=i[1]??"";n&&s.push({type:"text",text:n});const c=t.resolveMention?.(a);c?s.push({type:"mention",attrs:{id:c.id,text:c.text}}):s.push({type:"text",text:"@"+a}),r=o.index+e.length;continue}if("emoji"===o.kind){const{full:e,groups:i}=o,n=`:${i[0]}:`,a=t.resolveEmoji?.(n);s.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:n}}),r=o.index+e.length;continue}}return(e=>{const t=[];for(const r of e){const e=t[t.length-1];"text"!==r.type||"text"!==e?.type||e.marks||r.marks?t.push(r):e.text=(e.text??"")+(r.text??"")}return t})(s)}function Ae(e,t,r){e.lastIndex=r;const s=e.exec(t);if(!s)return null;const i=e.source.includes("@")?"mention":"emoji";return{index:s.index,full:s[0],groups:s.slice(1),kind:i}}function Ee(e,t){return e?t&&e.index>t.index?t:e:t}function ze(e){const t=(e.children??[])[0];return"text"===t?.type?(t.value??"")+"":"paragraph"===t?.type?((t.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("")||"")+"":""}function Oe(e){const t=((e??"")+"").toLowerCase().trim();return t?"info"===t||"note"===t||"success"===t||"warning"===t||"error"===t?t:"danger"===t?"error":null:null}function Je(e){const t=((e??"")+"").toLowerCase().trim();return!t||"neutral"!==t&&"green"!==t&&"yellow"!==t&&"red"!==t&&"blue"!==t&&"purple"!==t?null:t}function Ce(e,t){const r=[];for(const s of e??[])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 e=(s.url??"")+"",i=Ne(s.children??[],e),n=Te(s,0,t);if(n){"inline"===n.type?r.push(n.node):r.push({type:"text",text:i,marks:[{type:"link",attrs:{href:e}}]});continue}if(t.enableSmartCards&&qe(i,e)){r.push({type:"inlineCard",attrs:{url:e}});continue}r.push({type:"text",text:i,marks:[{type:"link",attrs:{href:e}}]});continue}if("textDirective"===s.type&&"status"===s.name){const e=ze(s)||"Status",t=Je(s.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:e,color:t}});continue}if("textDirective"===s.type&&"emoji"===s.name){const e=De(s);r.push(Pe(e,t));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(s.value??"")+"",marks:[{type:"code"}]});else r.push(...He(Ce(s.children??[],t),{type:"strike"}));else r.push(...He(Ce(s.children??[],t),{type:"em"}));else r.push(...He(Ce(s.children??[],t),{type:"strong"}));else r.push(..._e((s.value??"")+"",t));return r.filter(e=>!("text"===e.type&&""===(e.text??"")))}function He(e,t){return e.map(e=>{if("text"!==e.type)return e;const r=e.marks?[...e.marks,t]:[t];return{...e,marks:r}})}function Ne(e,t){const r=[];for(const t of e??[])"text"===t.type||"inlineCode"===t.type?r.push((t.value??"")+""):"emphasis"!==t.type&&"strong"!==t.type&&"delete"!==t.type||r.push(Ne(t.children??[],""));return r.join("")||t}function qe(e,t){const r=(e??"").trim(),s=(t??"").trim();return r===s&&/^https?:\/\//i.test(s)}function De(e){return(e.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("").trim()||""}function Pe(e,t){const r=e.startsWith(":")?e:`:${e}:`,s=t.resolveEmoji?.(r);return s?{type:"emoji",attrs:{shortName:s.shortName,text:s.text}}:{type:"emoji",attrs:{shortName:r}}}function Re(e){return e?"string"==typeof e?e:"text"===e.type||"inlineCode"===e.type?(e.value??"")+"":Array.isArray(e.children)?e.children.map(Re).join(""):"":""}function $e(e,t){if(!e?.type)return null;if((e=>"containerDirective"===e?.type&&"panel"===e?.name)(e))return((e,t)=>{const r=e.attributes??{},s=Oe(r.type)??"info",i="string"==typeof r.title?r.title:void 0,n=(e.children??[]).map(e=>$e(e,t)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:s,...i?{panelType:s,title:i}:{panelType:s}},content:n.length?n:[{type:"paragraph",content:[]}]}})(e,t);switch(e.type){case"heading":return{type:"heading",attrs:{level:Me(e.depth??1,1,6)},content:Ce(e.children??[],t)};case"paragraph":{const r=(e=>{const t=e.children??[];if(1!==t.length)return null;const r=t[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})(e);return r||{type:"paragraph",content:Ce(e.children??[],t)}}case"blockquote":return{type:"blockquote",content:(e.children??[]).map(e=>$e(e,t)).flat().filter(Boolean)};case"list":return((e,t)=>t.enableTaskLists&&(e.children??[]).some(e=>"boolean"==typeof e.checked)?((e,t)=>{const r=[];let s=0;for(const i of e.children??[]){if("boolean"!=typeof i.checked)continue;s+=1;const e=(i.children??[]).map(e=>$e(e,t)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+s,state:i.checked?"DONE":"TODO"},content:e.length?e:[{type:"paragraph",content:[]}]})}return{type:"taskList",content:r}})(e,t):{type:e.ordered?"orderedList":"bulletList",content:(e.children??[]).map(e=>((e,t)=>{const r=(e.children??[]).map(e=>$e(e,t)).flat().filter(Boolean);return{type:"listItem",content:r.length?r:[{type:"paragraph",content:[]}]}})(e,t))})(e,t);case"code":{const r=((e,t)=>{const r=(e??"").toString().trim().toLowerCase();return r?t.enableMermaid&&"mermaid"===r?"mermaid":(e=>{const t=e.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"}[t]??t})(r):null})(e.lang,t);return{type:"codeBlock",attrs:{language:r},content:[{type:"text",text:(e.value??"")+""}]}}case"thematicBreak":return{type:"rule"};case"table":return((e,t)=>({type:"table",content:(e.children??[]).map((e,r)=>({type:"tableRow",content:(e.children??[]).map(e=>({type:0===r?"tableHeader":"tableCell",content:[{type:"paragraph",content:Ce(e.children??[],t)}]}))}))}))(e,t);case"leafDirective":return"status"===e.name?(e=>{const t=Je((e.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:ze(e)||"Status",color:t}}]}})(e):"panel"===e.name?((e,t)=>{const r=e.attributes??{},s=Oe(r.type)??"info",i="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:s,...i?{title:i}:{}},content:[{type:"paragraph",content:Ce([{type:"text",value:ze(e)}],t)}]}})(e,t):Le(e,t);default:return Le(e,t)}}function Le(e,t){if("drop"===t.unknownNodeStrategy)return null;const r=Re(e);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function Me(e,t,r){const s=Number.isFinite(e)?Math.trunc(e):t;return Math.max(t,Math.min(r,s))}const Ue={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function Fe(e,t={}){const r={...Ue,...t},s=e??"",i=h.unified().use(g).use(f).use(y),n=i.parse(s),o=i.runSync(n);return Be(o),((e,t)=>{const r=[];for(const s of e.children??[]){const e=$e(s,t);e&&(Array.isArray(e)?r.push(...e):r.push(e))}return((e,t)=>{if(!t.enableSmartCards)return e;const r=e.content.map(e=>(e=>{if("paragraph"!==e.type)return e;const t=e.content??[];if(1!==t.length)return e;const r=t[0];if("inlineCard"!==r?.type)return e;const s=r.attrs?.url;return s?[{type:"blockCard",attrs:{url:s}}]:e})(e)).flat();return{...e,content:r}})({version:1,type:"doc",content:r},t)})(o,r)}function Be(e){if(!e||!Array.isArray(e.children))return;const t=[];for(const r of e.children)"definition"!==r?.type&&("html"!==r?.type?(Be(r),t.push(r)):t.push({type:"text",value:(r.value??"")+""}));e.children=t}function We(e){return e.flatMap(e=>"panel"===e.type?We(e.content??[]):[Ke(e)])}function Ke(e){return e.content?{...e,content:We(e.content)}:{...e}}const Xe=/\{\{\s*([^\}]+)\s*\}\}/g;function Ye(e){if(!e||0>=Object.keys(e).length)return[];const t=(e=>{if(null==e)return"";try{return JSON.stringify(e,null,2)}catch{return m.inspect(e,{depth:null})}})(e);return t?[{type:"text",text:t}]:[]}function Ge(e={},t=[]){const r=(e=>e&&"object"==typeof e?Array.isArray(e)?{items:e}:e:"string"==typeof e?{message:e}:null==e?{}:{value:e})(e);return{content:t.length?t:Ye(r),result:r,structuredContent:r}}const Ve={name:"jira-issue-create",inputSchema:xe,runTool:async(e,t)=>Ge(await(async(e,t)=>{let r;const s=e=>e&&e.trim()?e.trim():void 0,i=s(le.jira.projectKey),n=s(le.jira.issueType),o=t&&"object"==typeof t&&!Array.isArray(t)?t:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??i,issueType:o.issueType??n};try{r=xe.parse(a)}catch(e){const t=Error("validation error");throw t.code="validation_error",t}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=((e,t)=>{if(!t||!t.content)return e;const r=(s=t.content,i=t.placeholders,s?s.replace(Xe,(e,t)=>{const r=t.trim();if(!r)return"";if(i&&Object.prototype.hasOwnProperty.call(i,r)){const e=i[r];return null==e?"":e+""}return e}):"");var s,i;if(!r.trim())return e;const n=Fe(r),o=(a=e.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?Fe(a).content:[]:[];var a;return e.description={type:"doc",version:1,content:[...o,...n.content]},e})(c,r.template);const d=e?.issues?.create??e?.issues?.createIssue;if("function"!=typeof d)throw Error("Jira client missing create function");const u=await d.call(e.issues,{fields:c}),p=u&&u.data||u;return{id:p?.id??null,key:p?.key??null}})(e,t))};class Ze extends Error{constructor({code:e,message:t,details:r}){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=e,this.details=r}}const Qe=r.Logging.for("jira.errors");function et(e){if(!e)return new Ze({code:"jira_error",message:"Unknown Jira error",details:{raw:e}});const t=e?.status??e?.statusCode??e?.response?.status??e?.response?.statusCode,r="number"==typeof t?t:Number(t)||void 0,s=e?.response?.data??e?.data??e?.response?.body??e?.body,i=[];"string"==typeof e?.message&&i.push(e.message),((e,t)=>{e&&(Array.isArray(e.errorMessages)&&e.errorMessages.forEach(e=>"string"==typeof e&&t.push(e)),"string"==typeof e.errorMessage&&t.push(e.errorMessage),e.errorCollection&&Array.isArray(e.errorCollection.errors)&&e.errorCollection.errors.forEach(e=>{"string"==typeof e?t.push(e):e&&"string"==typeof e.message&&t.push(e.message)}),e?.errors&&"object"==typeof e.errors&&Object.values(e.errors).forEach(e=>{"string"==typeof e?t.push(e):"string"==typeof e?.message&&t.push(e.message)}))})(s,i);const n=r?`Jira API error (${r})`:"Jira API error",o=i.length>0?i.join(" | "):n,a=r?"jira_"+r:e?.code??"jira_error",c=e?.config,d=c?{method:c.method?c.method.toString().toUpperCase():void 0,url:c.url,headers:Ie(c.headers),data:ve(c.data)}:void 0;return Qe.error("jira.error",{code:a,message:o,httpStatus:r,request:d,body:ve(s)??s}),new Ze({code:a,message:o,details:{httpStatus:r,body:s,request:d,raw:e}})}const tt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID to delete"),deleteSubtasks:n.z.boolean().optional().default(!0).describe("Whether to delete the subtasks alongside this issue")}).describe("Arguments used to delete a Jira issue (with optional subtasks)"),rt={name:"jira-issue-delete",inputSchema:tt,runTool:async(e,t)=>{try{const r=tt.parse(t),s=e.issues??e.issue??e,i=s?.delete??s?.deleteIssue;if("function"!=typeof i)throw Error("jira client delete endpoint is not available");return await i.call(s,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),Ge({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(e){throw et(e)}}},st=n.z.object({projectKey:n.z.string().trim().min(1).optional().describe("Project key used to scope the issue search"),issueType:n.z.string().trim().min(1).optional().describe("Issue type name used to filter the results"),parentIssueId:n.z.string().trim().min(1).optional().describe("Optional parent issue key/ID to limit results to a subtree"),name:n.z.string().trim().min(1).optional().describe("Issue summary to match exactly"),reference:n.z.string().trim().min(1).optional().describe("External reference or custom identifier to filter by"),jql:n.z.string().trim().min(1).optional().describe("Free-form JQL query to drive the search"),startAt:n.z.number().int().min(0).optional().describe("Index for paging through the search results"),maxResults:n.z.number().int().min(1).optional().describe("Maximum number of issues to return"),fields:n.z.array(n.z.string()).optional().describe("List of issue fields to include in the response"),expand:n.z.string().optional().describe("Optional expansion clause for the results"),orderBy:n.z.string().trim().min(1).optional().describe("Field or clause used to order the returned issues")}).describe("Parameters describing how to search for Jira issues");function it(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const nt={name:"jira-issue-list",inputSchema:st,runTool:async(e,t)=>{try{const r=st.parse(t),s=r.startAt??0,i=r.maxResults??50;let n=r.jql?.trim();if(n){if(r.orderBy){const e=r.orderBy.trim();e&&(n=/\border\s+by\b/i.test(n)?`${n}, ${e}`:`${n} ORDER BY ${e}`)}}else n=(e=>{const t=[];if(e.projectKey&&t.push(`project = "${it(e.projectKey)}"`),e.issueType&&t.push(`issuetype = "${it(e.issueType)}"`),e.parentIssueId&&t.push(`parent = "${it(e.parentIssueId)}"`),e.name&&t.push(`summary ~ "${it(e.name)}"`),e.reference){const r=it(e.reference);t.push(`(key ~ "${r}" OR summary ~ "${r}" OR text ~ "${r}")`)}if(0===t.length){const e=Error("Provide a jql query or at least one filter (project, name, reference, parent, issue type, etc.).");throw e.code="validation_error",e}let r=t.join(" AND ");if(e.orderBy){const t=e.orderBy.trim();t&&(r=/\border\s+by\b/i.test(r)?`${r}, ${t}`:`${r} ORDER BY ${t}`)}return r})(r);const o={jql:n,startAt:s,maxResults:i};r.fields&&(o.fields=r.fields),r.expand&&(o.expand=r.expand);const a=e.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 d=await c.call(a,o),u=d?.data??d,p="object"==typeof u&&null!==u?{...u}:{};return void 0===p.startAt&&(p.startAt=s),void 0===p.maxResults&&(p.maxResults=i),Ge(p)}catch(e){throw et(e)}}},ot=n.z.object({issueId:n.z.string().min(1).describe("Jira issue key or numeric ID to read"),expand:n.z.string().optional().describe("Optional expand clause for nested fields or changelog"),fields:n.z.array(n.z.string()).optional().describe("Explicit list of issue fields to return"),properties:n.z.array(n.z.string()).optional().describe("Specific issue properties to include in the response")}).describe("Arguments required to read a Jira issue"),at={name:"jira-issue-read",inputSchema:ot,runTool:async(e,t)=>{try{const r=ot.parse(t),s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand),r.fields&&(s.fields=r.fields),r.properties&&(s.properties=r.properties);const i=await e.issues.getIssue(s);return Ge(i?.data??i)}catch(e){throw et(e)}}},ct=n.z.object({issueId:n.z.string().min(1).describe("Target issue key or ID to transition"),transitionId:n.z.union([n.z.string(),n.z.number()]).describe("Identifier for the transition to execute"),fields:n.z.record(n.z.any()).optional().describe("Optional field updates to apply during the transition"),update:n.z.record(n.z.array(n.z.object({set:n.z.any().optional().describe("Set operation for the transition update"),add:n.z.any().optional().describe("Add operation for the transition update"),remove:n.z.any().optional().describe("Remove operation for the transition update")}))).optional().describe("Structured update operations to send alongside the transition"),comment:n.z.string().optional().describe("Optional comment to attach during the transition")}).describe("Inputs needed to transition a Jira issue"),dt={name:"jira-issue-transition",inputSchema:ct,runTool:async(e,t)=>{try{const r=ct.parse(t),s={id:r.transitionId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.comment&&(s.comment={body:Fe(r.comment)});const i=await e.issues.transition({issueIdOrKey:r.issueId,transition:s});return Ge(i?.data??i)}catch(e){throw et(e)}}},ut=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID for which to list transitions"),expand:n.z.string().optional().describe("Optional expand parameter for the transition response")}).describe("Inputs used to fetch available transitions for an issue"),pt={name:"jira-transition-list",inputSchema:ut,runTool:async(e,t)=>{try{const r=ut.parse(t),s=e.issues;if(!s||"function"!=typeof s.getTransitions)throw Error("Jira transitions API is unavailable on the client");const i={issueIdOrKey:r.issueId};r.expand&&(i.expand=r.expand);const n=await s.getTransitions(i);return Ge(n?.data??n)}catch(e){throw et(e)}}},lt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID to update"),fields:n.z.record(n.z.any()).optional().describe("Direct field map to apply to the issue (e.g., description, labels)"),update:n.z.record(n.z.array(n.z.object({set:n.z.any().optional().describe("Set operation alongside the update key"),add:n.z.any().optional().describe("Add operation alongside the update key"),remove:n.z.any().optional().describe("Remove operation alongside the update key"),edit:n.z.any().optional().describe("Edit operation alongside the update key")}))).optional().describe("Structured update operations for array/set fields"),properties:n.z.array(n.z.any()).optional().describe("Property payloads to attach to the issue"),notifyUsers:n.z.boolean().optional().default(!0).describe("Whether to notify watchers when the issue is updated"),issueTemplateId:n.z.string().optional().describe("Optional template ID to render issue descriptions"),overrideScreenSecurity:n.z.boolean().optional().default(!1).describe("Temporarily bypass screen security restrictions"),overrideEditableFlag:n.z.boolean().optional().default(!1).describe("Temporarily bypass the editable flag on the screen")}).describe("Arguments used to update existing Jira issues"),mt=r.Logging.for("jira.rate-limit"),ht=le.jira.rateLimitRetryDelayMs??3e3;let ft=!1;const yt="jira-issue-update",gt=lt,bt={name:yt,inputSchema:gt,runTool:async(e,t)=>{try{const r=gt.parse(t),s={issueIdOrKey:r.issueId};r.fields&&(s.fields=(e=>{const t={...e},r=t.description;var s;return(e=>{if(!e||"object"!=typeof e)return!1;const t=e;return"doc"===t.type&&1===t.version&&Array.isArray(t.content)})(r)&&(t.description=(s=r,{...s,content:We(s.content??[])})),t})(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 i=await(async(e,t)=>{try{return await t()}catch(s){if((e=>{const t=(e=>e?.status??e?.statusCode??e?.response?.status??e?.response?.statusCode??void 0)(e);if(403!==t)return!1;const r=(e=>{const t=e?.response?.data??e?.data??e?.response?.body??e,r=[];return"string"==typeof t&&r.push(t),"string"==typeof t?.message&&r.push(t.message),"string"==typeof t?.errorMessage&&r.push(t.errorMessage),Array.isArray(t?.errorMessages)&&r.push(...t.errorMessages.filter(e=>"string"==typeof e)),"string"==typeof t?.details?.message&&r.push(t.details.message),r.join(" ")||""})(e);return/rate\s?limit/i.test(r)})(s))return ft||(mt.warn(`Jira rate limit detected for ${e}; waiting ${ht}ms before retrying.`,{retryDelayMs:ht}),ft=!0),ht>0&&await(r=ht,new Promise(e=>setTimeout(e,r))),t();throw s}var r})(yt,()=>e.issues.editIssue(s));return Ge(i?.data??i)}catch(e){throw et(e)}}},wt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID for the assignment change"),assignee:n.z.union([n.z.string().describe("Username or account name of the new assignee"),n.z.object({accountId:n.z.string().min(1).describe("Account ID of the assignee")}),n.z.object({accountType:n.z.string().min(1).describe("Account type filter (e.g., user, app)")})]).describe("How the new assignee is specified")}).describe("Arguments required to assign a Jira issue to someone"),vt={name:"jira-assign-issue",inputSchema:wt,runTool:async(e,t)=>{try{const r=wt.parse(t);let s;s="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const i=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:s});return Ge(i?.data??i)}catch(e){throw et(e)}}},It=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID to remove the assignee from")}).describe("Inputs required to unassign a Jira issue"),St={name:"jira-unassign-issue",inputSchema:It,runTool:async(e,t)=>{try{const r=It.parse(t),s=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return Ge(s?.data??s)}catch(e){throw et(e)}}},jt=n.z.object({issueId:n.z.string().min(1).describe("The Jira issue key or numeric ID receiving the comment"),body:n.z.string().min(1).describe("The markdown-compatible text of the comment"),visibility:n.z.object({type:n.z.enum(["role","group"]).describe("Visibility type that restricts the comment to a role or group"),value:n.z.string().min(1).describe("The name of the role or group granted visibility")}).optional().describe("Optional visibility override controlling who can read the comment")}).describe("Arguments for adding a comment to a Jira issue"),kt={name:"jira-comment-add",inputSchema:jt,runTool:async(e,t)=>{try{const r=jt.parse(t),s=e.issueComments;if(!s||"function"!=typeof s.addComment)throw Error("Jira issueComments API is unavailable on the client");const i={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(i.visibility=r.visibility);const n=await s.addComment(i);return Ge(n?.data??n)}catch(e){throw et(e)}}},xt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID whose comments should be retrieved"),start:n.z.number().optional().default(0).describe("Zero-based index to start pagination from"),maxResults:n.z.number().optional().default(50).describe("Maximum number of comments to return"),orderBy:n.z.string().optional().describe("Field name to order the returned comments by"),expand:n.z.string().optional().describe("Optional expansion clause for the comment response")}).describe("Parameters for fetching comments on a Jira issue"),Tt={name:"jira-comment-list",inputSchema:xt,runTool:async(e,t)=>{try{const r=xt.parse(t),s=e.issueComments;if(!s||"function"!=typeof s.getComments)throw Error("Jira issueComments API is unavailable on the client");const i=await s.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return Ge(i?.data??i)}catch(e){throw et(e)}}},_t=n.z.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"]).describe("The named relationship (Blocks, Relates to, etc.) that describes the link type"),At=n.z.object({id:n.z.string().optional().describe("Numeric Jira ID used when referencing an issue"),key:n.z.string().optional().describe("Human-readable key of the linked issue")}).describe("An issue reference (ID or key) used when building a link payload"),Et=n.z.object({type:n.z.enum(["role","group"]).describe("Visibility scope type attached to the comment"),value:n.z.string().min(1).describe("Name of the role or group granted visibility to the comment")}).describe("Optional visibility settings applied to the comment"),zt=n.z.object({body:n.z.string().optional().describe("Markdown text to include as a linked-comment"),visibility:Et.optional().describe("Optional ACL for the comment")}).describe("Optional comment applied at the time the link is created or updated"),Ot=n.z.object({link:n.z.object({relationship:_t,inwardIssue:At,outwardIssue:At,comment:zt.optional()}).describe("Definition of the link that should be created between two issues")}).describe("Arguments required to create a Jira issue link");let Jt=[];function Ct(e){return(e||"").trim().toLowerCase()}async function Ht(e,t){if(!t)throw Error("Link relationship is required");0===Jt.length&&(Jt=await(async e=>{const t=e.issueLinkTypes;if(!t||"function"!=typeof t.getIssueLinkTypes)throw Error("Jira issueLinkTypes API is unavailable on the client");const r=await t.getIssueLinkTypes(),s=r?.issueLinkTypes??r?.values??r;return Array.isArray(s)?s:[]})(e));const r=Ct(t),s=Jt.find(e=>[e.name,e.inward,e.outward].some(e=>Ct(e)===r));if(!s)throw Error(`No issue link type matching '${t}' found.`);return s}function Nt(e){if(!e)throw Error("Linked issue must include an id or key");if(e.id)return{id:e.id};if(e.key)return{key:e.key};throw Error("Linked issue must include an id or key")}function qt(e){if(!e)return;const t={};return e.body&&(t.body=Fe(e.body)),e.visibility&&(t.visibility=e.visibility),Object.keys(t).length>0?t:void 0}const Dt=Ot,Pt={name:"jira-link-create",inputSchema:Dt,runTool:async(e,t)=>{try{const r=Dt.parse(t).link,s={inwardIssue:Nt(r.inwardIssue),outwardIssue:Nt(r.outwardIssue)},i=qt(r.comment);i&&(s.comment=i);const n=e.issueLinks;if(!n||"function"!=typeof n.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const o=await Ht(e,r.relationship);s.type={id:o.id};const a=await n.linkIssues(s);return Ge(a?.data??a)}catch(e){throw et(e)}}},Rt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID receiving the attachment"),file:n.z.string().min(1).describe("Base64 or path to the file contents to upload"),mimeType:n.z.string().optional().describe("Optional MIME type override for the attachment"),comment:n.z.string().optional().describe("Optional comment to associate with the attachment")}).describe("Inputs needed to attach a file to a Jira issue"),$t={name:"jira-attach",inputSchema:Rt,runTool:async(e,r)=>{try{const s=Rt.parse(r),i=c.resolve(s.file),n=await t.promises.readFile(i),o=c.basename(i),a=new FormData;a.append("file",new Blob([n],{type:s.mimeType??"application/octet-stream"}),o);const d=e?.config??null,u=d?.host,p=d?.authentication?.basic??d?.authentication??d?.auth??null,l=p?.email,m=p?.apiToken??p?.apiKey;if(!u||!l||!m)throw Error("Jira client authentication configuration is unavailable for attachments");const h=await fetch(`${u}/rest/api/3/issue/${s.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${l}:${m}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:a});if(!h.ok){const e=await h.text();throw Error(`Jira attachment upload failed (${h.status}): ${e}`)}const f=await h.json();if(s.comment){const t=e.issueComments;if(!t||"function"!=typeof t.addComment)throw Error("Jira issueComments API is unavailable on the client");await t.addComment({issueIdOrKey:s.issueId,comment:Fe(s.comment)})}return Ge(f)}catch(e){if(e&&e.code&&"string"==typeof e.code&&["ENOENT","EACCES"].includes(e.code))throw Error("Attachment file error: "+e.message);throw et(e)}}},Lt=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID whose attachments should be listed")}).describe("Arguments used to fetch attachments for a Jira issue"),Mt={name:"jira-attachment-list",inputSchema:Lt,runTool:async(e,t)=>{try{const r=Lt.parse(t),s=e.issues;if(!s||"function"!=typeof s.getIssue)throw Error("Jira issues API is unavailable on the client");const i=await s.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),n=i?.data??i;return Ge({attachments:n?.fields?.attachment??[]})}catch(e){throw et(e)}}},Ut=n.z.object({issueId:n.z.string().min(1).describe("Issue key or ID owning the attachment"),attachmentId:n.z.string().min(1).describe("ID of the attachment to delete")}).describe("Arguments required to remove an attachment from Jira"),Ft={name:"jira-attachment-delete",inputSchema:Ut,runTool:async(e,t)=>{try{const r=Ut.parse(t),s=e.issueAttachments;if(!s||"function"!=typeof s.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await s.removeAttachment({id:r.attachmentId}),Ge({success:!0,message:`Attachment ${t.attachmentId} deleted successfully`})}catch(e){throw et(e)}}},Bt=n.z.object({issueId:n.z.string().min(1).describe("Target issue key or ID for the worklog entry"),timeSpent:n.z.string().min(1).describe('Time spent text (e.g., "1h 30m")'),comment:n.z.string().optional().describe("Optional worklog comment in markdown"),author:n.z.object({accountId:n.z.string().min(1).describe("Account ID of the user logging the work")}).optional().describe("Optional author override for the worklog entry"),startingOn:n.z.string().optional().describe("Optional timestamp for when the work started (ISO)"),artifact:n.z.string().optional().describe("Optional identifier linking the worklog to another artifact")}).describe("Arguments required to add a worklog entry to a Jira issue"),Wt={name:"jira-worklog-add",inputSchema:Bt,runTool:async(e,t)=>{try{const r=Bt.parse(t),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 i=e.issueWorklogs;if(!i||"function"!=typeof i.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const n=await i.addWorklog({issueIdOrKey:r.issueId,...s});return Ge(n?.data??n)}catch(e){throw et(e)}}},Kt=r.Logging.for("jira.xray");class Xt{constructor(){this.clientId=le.orThrow().xray.apiUser,this.clientSecret=le.orThrow().xray.apiSecret,this.baseUrl=le.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 e=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})}),t=await e.text();return this.token=t.replace(/"/g,""),this.token}async graphql(e,t){this.token||await this.authenticate();const r={query:e,variables:t};Kt.info("xray.graphql.request",{payload:ve(r)});try{const e=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify(r)}),t=await e.json();if(Kt.info("xray.graphql.response",{status:e.status,headers:e.headers?.get?e.headers.get("content-type"):void 0,body:ve(t)}),t.errors)throw Kt.error("xray.graphql.errors",{errors:ve(t.errors)}),Error(JSON.stringify(t.errors,null,2));return t.data}catch(e){throw Kt.error("xray.graphql.failure",{error:e+""}),e}}async getTest(e){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:e})).getTest}async addStep(e,t){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:e,step:t})).addTestStep}async updateStep(e,t){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:e,step:t})).updateTestStep}async deleteStep(e){return(await this.graphql("\n mutation RemoveTestStep($stepId: String!) {\n removeTestStep(stepId: $stepId)\n }\n ",{stepId:e})).removeTestStep}async addSteps(e,t){return Promise.all(t.map(t=>this.addStep(e,t)))}async updateSteps(e){return Promise.all(e.map(e=>this.updateStep(e.stepId,e.step)))}async deleteSteps(e){return Promise.all(e.map(e=>this.deleteStep(e)))}async syncSteps(e,t){const r=(await this.getTest(e)).steps||[],s=[],i=[],n=[];for(let e=0;e<t.length;e++){const n=t[e],o=r[e];o?o.action===n.action&&o.data===n.data&&o.result===n.result||s.push({stepId:o.id,step:n}):i.push(n)}if(r.length>t.length)for(let e=t.length;e<r.length;e++)n.push(r[e].id);await this.addSteps(e,i),await this.updateSteps(s),await this.deleteSteps(n)}}let Yt=null;const Gt=new Map;function Vt(e){const t=e?.fields,r=e?.action??t?.Action??t?.action;if(!r||"string"!=typeof r)throw Error("Xray step action is required");const s=e.data??e.fields?.Data??e.fields?.data??void 0,i=e.result??e.fields?.Result??e.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof s?s:void 0,result:"string"==typeof i?i:void 0}}async function Zt(e,t){if(!t)throw Error("Issue reference is required when interacting with Xray steps");if(Gt.has(t))return Gt.get(t);if(/^[0-9]+$/.test(t))return Gt.set(t,t),t;const r=e?.issues??e?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const s=await r.getIssue({issueIdOrKey:t,fields:["id"]}),i=s?.id;if(!i)throw Error("Unable to resolve Jira issue ID for "+t);return Gt.set(t,i),i}async function Qt(e){if(e?.test?.step)return e.test.step;const t=await(async()=>{if(Yt)return Yt;const e=le.orThrow().xray.apiUser?.trim(),t=le.orThrow().xray.apiSecret?.trim();if(!e||!t)throw Error("Xray credentials are missing (XRAY__API_USER, XRAY__API_SECRET). Please configure them before using Xray tools.");const r=Se(),s=new Xt;return Yt={test:{step:{async createStep(e,t){const i=await Zt(r,e),n=await s.addStep(i,Vt(t));return{step:n,id:n?.id}},async updateStep(e,t,i){await Zt(r,e);const n=Vt(i),o=await s.updateStep(t.toString(),n);return{step:o,id:o?.id}},deleteStep:async(e,t)=>(await Zt(r,e),{success:!0===await s.deleteStep(t.toString())}),async getSteps(e){const t=await Zt(r,e),i=await s.getTest(t);return{steps:i?.steps??[]}}}}},Yt})();if(!t?.test?.step)throw Error("Xray step API is unavailable on the client");return t.test.step}const er=n.z.object({issueId:n.z.string().min(1).describe("Xray test case key or ID that owns the step"),action:n.z.string().min(1).describe("Action description for the new Xray step"),data:n.z.string().optional().describe("Optional data or context used by this step"),result:n.z.string().optional().describe("Optional expected result for the step")}).describe("Inputs for adding a step to an Xray test case"),tr={name:"jira-xray-step-add",inputSchema:er,runTool:async(e,t)=>{try{const r=er.parse(t),s=await Qt(e),i={action:r.action,data:r.data,result:r.result};return Ge(await s.createStep(r.issueId,i))}catch(e){throw et(e)}}},rr=n.z.object({issueId:n.z.string().min(1).describe("Xray test case key or ID that owns the step"),stepId:n.z.union([n.z.string(),n.z.number()]).describe("Identifier for the step that should be updated"),action:n.z.string().min(1).describe("New action text for the step"),data:n.z.string().optional().describe("Updated data/context for the step"),result:n.z.string().optional().describe("Updated expected result for the step")}).describe("Inputs required to modify an Xray test step"),sr={name:"jira-xray-step-update",inputSchema:rr,runTool:async(e,t)=>{try{const r=rr.parse(t),s=await Qt(e),i=r.stepId+"",n={action:r.action,data:r.data,result:r.result};return Ge(await s.updateStep(r.issueId,i,n))}catch(e){throw et(e)}}},ir=n.z.object({issueId:n.z.string().min(1).describe("Xray test case key or ID owning the step"),stepId:n.z.union([n.z.string(),n.z.number()]).describe("Identifier of the step to delete")}).describe("Arguments used to remove an Xray test step"),nr={name:"jira-xray-step-delete",inputSchema:ir,runTool:async(e,t)=>{try{const r=ir.parse(t),s=await Qt(e);return await s.deleteStep(r.issueId,r.stepId.toString()),Ge({success:!0})}catch(e){throw et(e)}}},or=n.z.object({issueId:n.z.string().min(1).describe("Xray test case key or ID whose steps should be returned")}).describe("Inputs required to list steps on an Xray test case"),ar={name:"jira-xray-step-list",inputSchema:or,runTool:async(e,t)=>{try{const r=or.parse(t),s=await Qt(e);return Ge(await s.getSteps(r.issueId))}catch(e){throw et(e)}}},cr=n.z.object({linkId:n.z.string().min(1).describe("Identifier for the Jira issue link to remove")}).describe("Inputs required to delete an existing Jira issue link"),dr={name:"jira-link-delete",inputSchema:cr,runTool:async(e,t)=>{try{const r=cr.parse(t),s=e.issueLinks;if(!s||"function"!=typeof s.deleteIssueLink)throw Error("Jira issueLinks API is unavailable on the client");return await s.deleteIssueLink({linkId:r.linkId}),Ge({success:!0,message:`Issue link ${r.linkId} deleted successfully`})}catch(e){throw et(e)}}},ur=n.z.object({linkId:n.z.string().min(1).describe("ID of the existing issue link to change"),relationship:_t,comment:zt.optional().describe("Optional comment to attach while recreating the link")}).describe("Inputs required to update (recreate) a Jira issue link"),pr={name:"jira-link-update",inputSchema:ur,runTool:async(e,t)=>{try{const r=ur.parse(t),s=e.issueLinks;if(!s||"function"!=typeof s.getIssueLink||"function"!=typeof s.deleteIssueLink||"function"!=typeof s.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const i=await s.getIssueLink({linkId:r.linkId}),n=i?.data??i;if(!n)throw Error(`Issue link ${r.linkId} not found`);const o=n.inwardIssue,a=n.outwardIssue;if(!o||!a)throw Error("Issue link payload is missing linked issues");const c=await Ht(e,r.relationship);await s.deleteIssueLink({linkId:r.linkId});const d={inwardIssue:Nt(o),outwardIssue:Nt(a),type:{id:c.id}},u=qt(r.comment);return u&&(d.comment=u),await s.linkIssues(d),Ge({success:!0,message:`Issue link ${r.linkId} updated to ${r.relationship}`})}catch(e){throw et(e)}}},lr={[Ve.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[at.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[nt.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}},[bt.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}},[rt.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[dt.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[pt.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[vt.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[St.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[kt.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}},[Tt.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Pt.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[pr.name]:{title:"Jira Link Update",description:"Change the relationship type for an existing issue link",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[dr.name]:{title:"Jira Link Delete",description:"Delete an issue link from Jira",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[$t.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Mt.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ft.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Wt.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[tr.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[sr.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[nr.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[ar.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 mr(e){const t=r.Logging.for(mr);let s,i=null;try{s=Se()}catch(e){if(!(e instanceof ye))return void t.warn("Skipping Jira tool registration; unable to create Jira client",{error:e});i=e,t.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:e})}const n=[Ve,at,nt,bt,rt,dt,pt,vt,St,kt,Tt,Pt,pr,dr,$t,Mt,Ft,Wt,tr,sr,nr,ar];for(const r of n){const n=lr[r.name];if(n)try{await e.registerTool(r.name,{title:n.title,description:n.description,inputSchema:r.inputSchema,annotations:n.annotations},async e=>{if(!s)throw i??Error("Jira client unavailable because credentials could not be loaded.");return r.runTool(s,e)}),t.info("Registered Jira tool "+r.name)}catch(e){t.error("Failed to register Jira tool "+r.name,{error:e})}}}async function hr(e){await(async e=>{e.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 e=ie.map(e=>e.getName()).sort();return{content:[{type:"text",text:["Name: "+le.name,"Title: "+le.title,"Version: "+le.version,"Prompts: "+(e.join(", ")||"<none>")].join("\n")}]}})})(e);const t=r.Logging.for(hr);try{await mr(e)}catch(e){t.error("Failed to register Jira tools",e)}}class fr extends C{setCb(e){return this.cb=e,this}setConfig(e){return this.config=e,this}setUriOtTemplate(e){return this.uriOrTemplate=e,this}constructor(e){super(e)}static get builder(){return new fr}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{const t="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new w.ResourceTemplate(new b.UriTemplate(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),s=async(e,t)=>{const r=this.logFor(t);r.verbose(`Requesting resource ${this.name} from ${e.toString()}`);const s=await Promise.resolve(this.cb(e,t));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(s._meta)),s};return e.resource(this.name,t,r,s)}catch(e){throw r.Logging.for(this).error("Error registering resource "+this.name,e),e}}}s.__decorate([i.required(),s.__metadata("design:type",String)],fr.prototype,"uriOrTemplate",void 0),s.__decorate([i.required(),s.__metadata("design:type",Function)],fr.prototype,"cb",void 0),s.__decorate([i.required(),s.__metadata("design:type",Object)],fr.prototype,"config",void 0);const yr=K()??x.join(__dirname,"..","assets"),gr=x.join(yr,"templates"),br=x.join(yr,"prompts"),wr=[{name:"example.resource",title:"Example Resource",description:"A tiny example payload for verifying resource listing.",uri:"resource://example.resource",cb:async()=>({contents:[{type:"text",text:"example"}],_meta:{}})},{name:"repo.metadata",title:"Repository Metadata",description:"Static metadata for the decaf-ts repository.",uri:"resource://repo.metadata",cb:async()=>({contents:[{type:"json",text:JSON.stringify({repo:"decaf-ts",version:"1.0.0"})}],_meta:{}})},{name:"decoration.schematics",title:"Decoration Schematics",description:"Metadata describing decoration schematics that ship with the project.",uri:"resource://decoration.schematics",cb:async()=>({content:{type:"json",data:JSON.stringify({collection:"decaf",files:["metadata/Metadata.ts"]})},_meta:{}})},{name:"golden.overrides",title:"Golden Overrides",description:"Stubbed golden override payload used for testing the resource API.",uri:"resource://golden.overrides",cb:async()=>({content:{type:"text",text:"golden overrides stub"},_meta:{}})}];async function vr(e){const t=r.Logging.for(vr);for(const r of wr){const{name:s,uri:i,title:n,description:o,cb:a}=r;if(!s||!i||"function"!=typeof a){t.warn("Skipping invalid resource registration: "+(s??"<unknown>"));continue}const c={title:n??s,description:o??"",_meta:{}};try{await e.resource(s,i,c,async(e,t)=>a(e,t)),t.info(`Registered resource ${s} @ ${i}`)}catch(e){t.error("Failed to register resource "+s,e)}}}const Ir=new WeakMap;class Sr extends r.LoggedClass{get client(){const e=Ir.get(this);if(!e)throw Error("Mcp server requires Mcp client");return e}constructor(){super()}async load(){const e=this.log.for(this.load);for(const t of ie)try{e.info("loading prompt "+t.getName());const r=t.build(this.client);e.verbose(`Loaded prompt ${r.title} from ${t.getName()} definition`)}catch(r){e.error("Failed to load prompt "+t.getName(),r)}try{await hr(this.client),e.verbose("Registered built-in tools")}catch(e){}try{await vr(this.client),e.verbose("Registered built-in resources")}catch(e){}try{await(async(e,t)=>{t.info("Registering agent templates as resources...");const r=k.readdirSync(gr).filter(e=>e.endsWith(".md"));for(const s of r){const r=x.basename(s,".md"),i=x.join(gr,s),n=fr.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+r}).setCb(async e=>{const t=k.readFileSync(e.pathname,"utf8");return{contents:[{uri:e.toString(),text:t,mimeType:"text/markdown"}],_meta:{}}});try{n.build(e),t.info("Registered template: "+r)}catch(e){t.error(`Failed to register template ${r}:`,e)}}t.info("Registering agent prompts...");const s=k.readdirSync(br).filter(e=>e.endsWith(".md"));for(const r of s){const s=x.basename(r,".md"),i=x.join(br,r),o=k.readFileSync(i,"utf8"),a=Y.builder.setName(s).setTitle("Prompt: "+s).setDescription("Dynamic prompt for "+s).setArgsSchema(n.z.object({})).setCb(async e=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(e),t.info("Registered prompt: "+s)}catch(e){t.error(`Failed to register prompt ${s}:`,e)}}})(this.client,e)}catch(e){}}async boot(e="stdio"){"stdio"===e&&r.Logging.setFactory(_),r.Logging.for(this.constructor.name);const t=((Array.isArray(le.icons)?le.icons:[le.icons])||[]).map(e=>{const t="string"==typeof e?.src?e.src:(e?.src??"")+"",r="string"==typeof e?.mimeType?e.mimeType:(e?.mimeType??"")+"";let s=[];return Array.isArray(e?.sizes)?s=e.sizes.map(e=>e+""):"string"==typeof e?.sizes&&(s=(e.sizes+"").split(",").map(e=>e.trim())),{src:t,mimeType:r,sizes:s}}),s={name:le.name,title:le.title,websiteUrl:le.websiteUrl,version:le.version,icons:t},i=new w.McpServer(s,{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(((e,t)=>{Ir.set(e,t)})(this,i),i.onerror=e=>{this.log.error("MCP instance onerror",e)},e){case"stdio":e=new I.StdioServerTransport;break;case"http":e=new S.StreamableHTTPServerTransport({sessionIdGenerator:()=>v.v4(),onsessioninitialized:e=>{},onsessionclosed:e=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(n=e)||"object"!=typeof n||"function"!=typeof n.send&&"function"!=typeof n.close&&"function"!=typeof n.on)throw new d.InternalError("Invalid transport type: "+e)}var n;try{await this.load()}catch(e){throw e}await this.client.connect(e)}}const jr=(new e.Command).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async e=>{const r=B("package.json"),s=JSON.parse(t.readFileSync(r,"utf-8")),i=s.version,{transport:n}=e,o=(new T).for("mcp-server");if("stdio"!==n)throw Error("Unsupported transport mode: "+n);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(e)} for ${s.name} version ${i}`),(new Sr).boot(n)});(new e.Command).command("md-to-ast").description("pipes markdown to jira ast: `cat file.md` | npx decaf-mcp md-to-ast > ast.json").action(async e=>{const s=B("package.json"),i=JSON.parse(t.readFileSync(s,"utf-8")),n=i.version;r.Logging.for("md-to-ast").debug(`running with options: ${JSON.stringify(e)} for ${i.name} version ${n}`);const o=Fe(await(async()=>{const e=[];for await(const t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")})(),{resolveMention:e=>({id:e,text:"@"+e}),resolveAttachment:e=>({id:e,collection:"attachments"})});process.stdout.write(JSON.stringify(o,null,2)+"\n")});const kr=(new e.Command).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");kr.addCommand(jr),kr.parse(process.argv)},"object"==typeof exports&&"undefined"!=typeof module?t(require("commander"),require("fs"),require("@decaf-ts/logging"),require("tslib"),require("@decaf-ts/decorator-validation"),require("zod"),require("@decaf-ts/injectable-decorators"),require("@decaf-ts/decoration"),require("path"),require("@decaf-ts/db-decorators"),require("crypto"),require("zlib"),require("url"),require("node:util"),require("unified"),require("remark-directive"),require("remark-gfm"),require("remark-parse"),require("@modelcontextprotocol/sdk/shared/uriTemplate.js"),require("@modelcontextprotocol/sdk/server/mcp.js"),require("uuid"),require("@modelcontextprotocol/sdk/server/stdio.js"),require("@modelcontextprotocol/sdk/server/streamableHttp.js")):"function"==typeof define&&define.amd?define(["commander","fs","@decaf-ts/logging","tslib","@decaf-ts/decorator-validation","zod","@decaf-ts/injectable-decorators","@decaf-ts/decoration","path","@decaf-ts/db-decorators","crypto","zlib","url","node:util","unified","remark-directive","remark-gfm","remark-parse","@modelcontextprotocol/sdk/shared/uriTemplate.js","@modelcontextprotocol/sdk/server/mcp.js","uuid","@modelcontextprotocol/sdk/server/stdio.js","@modelcontextprotocol/sdk/server/streamableHttp.js"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).commander,e.fs,e.decafTsLogging,e.tslib,e.decafTsDecoratorValidation,e.zod,e.decafTsInjectableDecorators,e.decafTsDecoration,e.path,e.decafTsDbDecorators,e.crypto,e.zlib,e.url,e.node_util,e.unified,e.remarkDirective,e.remarkGfm,e.remarkParse,e.uriTemplate_js,e.mcp_js,e.uuid,e.stdio_js,e.streamableHttp_js);
3
3
  //# sourceMappingURL=mcp-server.cjs.map