@decaf-ts/mcp-server 1.5.11 → 1.5.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/assets/code/patterns/builder.enc +0 -0
  2. package/dist/assets/prompts/agent/agent.enc +0 -0
  3. package/dist/assets/prompts/agent/init.enc +0 -0
  4. package/dist/assets/prompts/constitution_commands.enc +0 -0
  5. package/dist/assets/prompts/documentation/class.enc +0 -0
  6. package/dist/assets/prompts/documentation/constant.enc +0 -0
  7. package/dist/assets/prompts/documentation/decorator.enc +0 -0
  8. package/dist/assets/prompts/documentation/file.enc +3 -6
  9. package/dist/assets/prompts/documentation/function.enc +0 -0
  10. package/dist/assets/prompts/documentation/interface.enc +0 -0
  11. package/dist/assets/prompts/documentation/iterate.enc +1 -3
  12. package/dist/assets/prompts/documentation/module.enc +0 -0
  13. package/dist/assets/prompts/documentation/prefix.enc +0 -0
  14. package/dist/assets/prompts/documentation/repo.enc +0 -0
  15. package/dist/assets/prompts/documentation/suffix.enc +0 -0
  16. package/dist/assets/prompts/git_commands.enc +0 -0
  17. package/dist/assets/prompts/jira/operational_prompts.enc +0 -0
  18. package/dist/assets/prompts/jira/system_prompt.enc +0 -0
  19. package/dist/assets/prompts/mode_commands.enc +0 -0
  20. package/dist/assets/prompts/plan_commands.enc +0 -0
  21. package/dist/assets/prompts/repository/readme.enc +0 -0
  22. package/dist/assets/prompts/repository/release_notes.enc +0 -0
  23. package/dist/assets/prompts/repository/setup.enc +0 -0
  24. package/dist/assets/prompts/specification_commands.enc +0 -0
  25. package/dist/assets/prompts/startup_command.enc +0 -0
  26. package/dist/assets/prompts/task_commands.enc +0 -0
  27. package/dist/assets/prompts/tests/coverage.enc +0 -0
  28. package/dist/assets/templates/AGENTS.enc +0 -0
  29. package/dist/assets/templates/agents_template.enc +0 -0
  30. package/dist/assets/templates/constitution_template.enc +0 -0
  31. package/dist/assets/templates/decaf/context/logCtx.enc +0 -0
  32. package/dist/assets/templates/decaf/services/client_based_service.enc +0 -0
  33. package/dist/assets/templates/decaf/services/model_service.enc +0 -0
  34. package/dist/assets/templates/decaf/services/service.enc +0 -0
  35. package/dist/assets/templates/decaf_guidelines.enc +1 -1
  36. package/dist/assets/templates/instructions_template.enc +0 -0
  37. package/dist/assets/templates/jira_templates.enc +0 -0
  38. package/dist/assets/templates/plan_template.enc +0 -0
  39. package/dist/assets/templates/specification_template.enc +0 -0
  40. package/dist/assets/templates/task_template.enc +0 -0
  41. package/dist/mcp-server.cjs +1 -1
  42. package/dist/mcp-server.cjs.map +1 -1
  43. package/dist/mcp-server.js +1 -1
  44. package/dist/mcp-server.js.map +1 -1
  45. package/package.json +1 -1
Binary file
Binary file
@@ -1,6 +1,3 @@
1
- DCAF183�������f|f(c����P�ۍ��� H�\1���z��'���L
2
- &�^q�@'9��Z+t���o#fq�?B�RNd�ܤ�����އ��@�ً���I������?� `j-� OX���9_)2�.9k�dZ�s�bq��=�v����ô|2+���˂��O�f��
3
- �<�n eE|����T`����'��S/9��C�K�? >�)-�X��Đ������f��NI���vG,��E��n��7
4
- �4
5
- ���d'��eM���XXˎ��J��ka���]S������
6
- ?�|A���[���W�^����_��A�cA�t�Rx�/�t֠�T;伿�� �o�;���nF���H���V��PB����v
1
+ DCAF1@��0B `�]�����.o����ۜb�ωΎ���6�*�WiX2�6uk$�b��4�u�T�|��,-��.o�u�QTŽH��9q��ņ$d�Tڃk��)`��o��
2
+ �pt����h�qr�����)~k�?O���Ƌ�i�]o��pdW�H���Y���3��K�S[���׻f>��3ŝ&`,��b����ux�4jcF�,l�B���j(0X ��I���A�;F'jvYOq�᳞?�mg���\��Gpe �n�����p��j ;��$�����Kݐ+L?��K�+y>��q�x��da����s�0���p��� ��}8Ř����6�+~ќ��K76���
3
+ ��a��7俤FH�w5���m�Ӝ�jJON�2����^�!
@@ -1,3 +1 @@
1
- DCAF1zg��.ik��m�_��fA�(0�P��SH��
2
- �\���-����F�:G)�O�3��$i��h�m:�!��ejH��
3
- � � F�'���q�=xA2���~h��k��4:��#픑B3%�:�8la���d󒬗���g�ZdH�HNQg�kN:��׳��/?��C����9w)�/H�5�v�5�f�\��̽�,nu'D���| tN2���/��Q�mk�)I�j�K/9��
1
+ DCAF1E�<#��g���GkZ�u��Enw`v�Ze*�8��Ź�a0�E/n��+U�0x�<_ՕGn�ǭ^zEunC8��?������a���'sr������x_R�?{�K����М+v=�M���� +�(L��Aߞ�9���X����¡���rF��`x���-Z�b��I�kh}��>�ag�v��
Binary file
@@ -1 +1 @@
1
- DCAF1S>1$4��C�Mr�����E���]J)�9��k��l�}�3�k�D���DQ�wA�i ��M1 �
1
+ DCAF1A/��zL-+��a��AQ7x�滍�MF�/m%Ǐ���3�&-�>S`*��ܰʡ���Z�V
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var e,t;e=this,t=function(e,t,r,n,s,i,o,a,c,p,l,u,d,m,h,f,y,g,b,v,w,S,I){"use strict";function j(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var x=j(t),z=j(c);class T extends r.MiniLogger{constructor(e,t,r){super(e,t,r)}log(e,t,n,s){const i=this.config("level");r.NumericLogLevels[i],r.NumericLogLevels[e]}}const _=(e,t,...r)=>{const n=(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(n,t)};var E,k,A,O,C;(e=>{e[e.NONE=0]="NONE",e[e.BASIC=1]="BASIC",e[e.ADVANCED=2]="ADVANCED",e[e.HIGH=3]="HIGH"})(E||(E={})),(e=>{e[e.NONE=0]="NONE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(k||(k={})),(e=>{e[e.FREE=0]="FREE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(A||(A={}));class N extends s.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:n}=e||{};let s="string"==typeof t&&t.length>0?this.log.for(t):this.log;return n&&n.clientId&&(s=s.for(n.clientId)),r&&(s=s.for(r.toString())),s}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}}n.__decorate([s.required(),n.__metadata("design:type",String)],N.prototype,"description",void 0),n.__decorate([s.required(),n.__metadata("design:type",String)],N.prototype,"name",void 0),n.__decorate([s.required(),n.__metadata("design:type",String)],N.prototype,"title",void 0);class H extends N{constructor(e){super(e),this.reasoning=E.NONE,this.effort=k.NONE,this.cost=A.FREE}setReasoning(e){return this.reasoning=e,this}setEffort(e){return this.effort=e,this}setCost(e){return this.cost=e,this}}function J(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 P(e,t="schema"){if(J(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,n]of Object.entries(r))e[t]=$(n)?n:i.z.any();return i.z.object(e)}}throw Error(`Registration error: provided a non-canonical ${t}. Export a ZodObject (z.object(...)).`)}function q(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=J(e);return t?"function"==typeof t.shape?t.shape():t.shape||void 0:void 0}function $(e){return!(!e||"object"!=typeof e||!e._def)}n.__decorate([s.required(),n.__metadata("design:type",Number)],H.prototype,"reasoning",void 0),n.__decorate([s.required(),n.__metadata("design:type",Number)],H.prototype,"effort",void 0),n.__decorate([s.required(),n.__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"})(C||(C={}));const R=Buffer.from("DCAF1","ascii");function D(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]?D(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=d.fileURLToPath(r)}catch{continue}if(!r.includes("node:internal"))return c.dirname(r)}})(),U=M?D(M):void 0,B=L??U??process.cwd();function K(...e){return c.join(B,...e)}function F(e){let t=e;for(;;){const e=z.join(t,"lib","assets");if(x.existsSync(e))return e;const r=z.join(t,"src","assets");if(x.existsSync(r))return r;const n=z.join(t,"assets");if(x.existsSync(n))return n;const s=z.dirname(t);if(s===t)break;t=s}}function W(){const e=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(e&&x.existsSync(e))return e;const t=F(__dirname);if(t)return t;const r=process.argv?.[1];if(r){const e=F(z.dirname(r));if(e)return e}const n=[B,process.env.INIT_CWD].filter(Boolean);for(const e of n){const t=F(e);if(t)return t}return K("assets")}let Y=class extends r.LoggedClass{constructor(e){super(),this.basePath=e||W()}listAssets(...e){const t=z.join(this.basePath,...e);return x.readdirSync(t)}listPrompts(){return this.listAssets(C.PROMPT)}getAsset(e,t="md",...r){const n=z.join(this.basePath,...r),s=(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 n=e.subarray(r,r+16);r+=16;const s=e.subarray(r,r+12);r+=12;const i=e.subarray(r,r+16);r+=16;const o=e.subarray(r),a=((e,t)=>l.scryptSync(e,t,32))(t,n),c=l.createDecipheriv("aes-256-gcm",a,s);c.setAuthTag(i);const p=Buffer.concat([c.update(o),c.final()]);return u.gunzipSync(p)})(x.readFileSync(e)).toString("utf-8"):x.readFileSync(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}},i=s(z.join(n,`${e}.${t}`),"enc"===t);if(null!==i)return i;const o=s(z.join(n,e+".enc"),!0);if(null!==o)return o;throw Error("Asset not found: "+z.join(n,`${e}.${t}`))}getAllAssets(e,...t){return this.listAssets(e,...t).reduce((r,n)=>{const s=z.extname(n),i=z.basename(n,s),o=s.replace(/^\./,"")||void 0;return r[i]=this.getAsset(i,o??void 0,e,...t),r},{})}toPromptDef(e){const t=e=>"number"==typeof e?e:"string"==typeof e?(e=>{switch(e){case"none":return E.NONE;case"basic":return E.BASIC;case"advanced":return E.ADVANCED;case"high":return E.HIGH;case"medium":return k.MEDIUM;case"low":return A.LOW;case"free":return A.FREE;default:throw new p.InternalError("Cannon convert unknown level "+e)}})(e.toLowerCase()):E.NONE;return e.effort=t(e.effort),e.reasoning=t(e.reasoning),e.cost=t(e.cost),e}getPrompt(e,...t){const n=this.getAsset(r.toSnakeCase(e),"json",C.PROMPT,...t);let s;try{s=JSON.parse(n)}catch(r){throw new p.SerializationError(`Failed to parse prompt ${e} in categories ${t}: ${r}`)}return this.toPromptDef(s)}getAllPrompts(...e){const t=this.getAllAssets(C.PROMPT,...e);return Object.entries(t).reduce((t,[r,n])=>{try{t[r]=JSON.parse(n)}catch(t){throw new p.SerializationError(`Failed to parse prompt ${r} in categories ${e}: ${t}`)}return t},t)}};Y=n.__decorate([o.injectable(),n.__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,n,s){const i=(t=Array.isArray(t)?t:Object.keys(t)).filter(e=>!Object.prototype.hasOwnProperty.call(n,e));if(i.length)throw new p.ValidationError("Missing replacements for placeholders: "+i.join(", "));s&&(s.verbose("Patching prompt with placeholders: "+JSON.stringify(t)),s.debug("Values: "+JSON.stringify(n)));const o=t.reduce((e,t)=>(e[t]=n[t],e),{});return r.sf(e,o)}patchPrompt(e,t,r,n){return X.patchPrompt(e,t,r,n||this.log.for(this.patchPrompt))}build(e,t){const r=this.log.for(this.build),n=this.hasErrors();if(n)throw new p.ValidationError(n.toString());try{this.argsSchema&&P(this.argsSchema,"argsSchema");const r=q(this.argsSchema);return e.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(e,r)=>{const n=this.logFor(r);e=Object.assign({},t,e||{}),n.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 s=await Promise.resolve(this.cb(e,r));return n.verbose(`Prompt ${this.name} executed successfully.`),n.debug("Prompt execution meta: "+JSON.stringify(s._meta)),s})}catch(e){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),e),e}}}n.__decorate([o.inject(Y),n.__metadata("design:type",Y)],X.prototype,"assets",void 0),n.__decorate([s.required(),n.__metadata("design:type",Object)],X.prototype,"cb",void 0),n.__decorate([s.required(),n.__metadata("design:type",i.ZodObject)],X.prototype,"argsSchema",void 0),n.__decorate([a.prop(),n.__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);s.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 n=this.hasErrors(...Array.from(r));if(n)throw new p.ValidationError(n.toString());const o=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),c=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),l=[...new Set([...t.placeholders,...o.map(e=>e.placeholders||[]),...c.map(e=>e.placeholders||[])].flat())].reduce((e,t)=>(e[t]=i.z.string().describe("The description for "+t),e),{});return this.setArgsSchema(i.z.object(l)),this.setCb((e,t)=>{const r=this.logFor(t).for(G).for(this.promptCategory).for(this.name);function n(e=[]){return Array.isArray(e)?e:Object.keys(e)}const s=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),i=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...s.map(e=>n(e.placeholders)).flat(),...i.map(e=>n(e.placeholders)).flat(),...n(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...s.map(e=>e.prompt),o.prompt,...i.map(e=>e.prompt)].join("\n\n"),a,e,r)}}],_meta:{}}}),super.build(e)}setReasoning(e){throw new p.InternalError("Named prompt builders don't require callback")}setEffort(e){throw new p.InternalError("Named prompt builders don't require callback")}setCost(e){throw new p.InternalError("Named prompt builders don't require callback")}setDescription(e){throw new p.InternalError("Named prompt builders don't require callback")}setTitle(e){throw new p.InternalError("Named prompt builders don't require callback")}static get builder(){return new G}}n.__decorate([s.required(),n.__metadata("design:type",String)],G.prototype,"promptCategory",void 0),n.__decorate([s.list(String),s.minlength(1),n.__metadata("design:type",Array)],G.prototype,"prefixes",void 0),n.__decorate([s.minlength(1),s.list(String),n.__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(i.z.object({message:i.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(i.z.object({gist:i.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 n=G.builder.setCategory(ee.DOCS).setName(e);return["prefix",...t].forEach(e=>n.addPrefix(e)),["suffix",...r].forEach(e=>n.addSuffix(e)),n}(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"])],ne=i.z.object({className:i.z.string().describe("the class name to turn into a builder")}),se=[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(ne).setReasoning(E.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 ie 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 ie}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{this.inputSchema&&P(this.inputSchema,"inputSchema"),this.outputSchema&&P(this.outputSchema,"outputSchema");const t=q(this.inputSchema),r=q(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 n=await Promise.resolve(this.cb(e,t));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(n._meta)),n})}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}}}n.__decorate([s.required(),n.__metadata("design:type",Object)],ie.prototype,"annotations",void 0),n.__decorate([s.required(),n.__metadata("design:type",Object)],ie.prototype,"cb",void 0),n.__decorate([s.required(),n.__metadata("design:type",Function)],ie.prototype,"inputSchema",void 0);const oe=ie.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(i.z.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(oe,{name:oe.getName()});const ae=ie.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(i.z.object({filePath:i.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 n=c.dirname(e);if(n===e)break;e=n}}catch{}return{}}Object.assign(ae,{name:ae.getName()});const pe=ce().version??"0.0.0",le=ce().name??"unknown";a.Metadata.registerLibrary(le,pe);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:pe,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:B,assetDir:W(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0},xray:{host:process.env.XRAY__HOST||process.env.XRAY__API_HOST||"https://xray.cloud.getxray.app",apiUser:process.env.XRAY__API_USER||"",apiSecret:process.env.XRAY__API_SECRET||""},level:r.LogLevel.error},de=r.LoggedEnvironment.accumulate(ue);function me(){const{host:e,email:t,apiKey:r,projectKey:n,issueType:s}=de.jira;return{host:e?.trim(),email:t?.trim(),apiKey:r?.trim(),projectKey:n?.trim(),issueType:s?.trim(),parentIssue:de.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(de);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)}}function ge(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:n,apiKey:s}=(()=>{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}})();return new t({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:n,apiToken:s}}})}const be=i.z.object({name:i.z.string().min(1).optional(),content:i.z.string().min(1),placeholders:i.z.record(i.z.string()).optional()}),ve=i.z.object({template:be.optional()}),we=i.z.union([i.z.object({fields:i.z.record(i.z.any())}).merge(ve),i.z.object({summary:i.z.string().min(1),projectKey:i.z.string().min(1),issueType:i.z.string().min(1),description:i.z.string().optional()}).merge(ve)]);function Se(e,t,r){const n=((e.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!n)return null;const s=n[2],i=r.resolveAttachment?.(s);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Ie(e,t){if(!e)return[];if(!t.enableAtMentions&&!t.enableEmojiShortcodes)return[{type:"text",text:e}];let r=0;const n=[],s=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;r<e.length;){const o=xe(t.enableAtMentions?je(s,e,r):null,t.enableEmojiShortcodes?je(i,e,r):null);if(!o){n.push({type:"text",text:e.slice(r)});break}if(o.index>r&&n.push({type:"text",text:e.slice(r,o.index)}),"mention"===o.kind){const{full:e,groups:s}=o,i=s[0]??"",a=s[1]??"";i&&n.push({type:"text",text:i});const c=t.resolveMention?.(a);c?n.push({type:"mention",attrs:{id:c.id,text:c.text}}):n.push({type:"text",text:"@"+a}),r=o.index+e.length;continue}if("emoji"===o.kind){const{full:e,groups:s}=o,i=`:${s[0]}:`,a=t.resolveEmoji?.(i);n.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:i}}),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})(n)}function je(e,t,r){e.lastIndex=r;const n=e.exec(t);if(!n)return null;const s=e.source.includes("@")?"mention":"emoji";return{index:n.index,full:n[0],groups:n.slice(1),kind:s}}function xe(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 Te(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 _e(e){const t=((e??"")+"").toLowerCase().trim();return!t||"neutral"!==t&&"green"!==t&&"yellow"!==t&&"red"!==t&&"blue"!==t&&"purple"!==t?null:t}function Ee(e,t){const r=[];for(const n of e??[])if(n?.type)if("text"!==n.type)if("strong"!==n.type)if("emphasis"!==n.type)if("delete"!==n.type)if("inlineCode"!==n.type)if("break"!==n.type){if("link"===n.type){const e=(n.url??"")+"",s=Ae(n.children??[],e),i=Se(n,0,t);if(i){"inline"===i.type?r.push(i.node):r.push({type:"text",text:s,marks:[{type:"link",attrs:{href:e}}]});continue}if(t.enableSmartCards&&Oe(s,e)){r.push({type:"inlineCard",attrs:{url:e}});continue}r.push({type:"text",text:s,marks:[{type:"link",attrs:{href:e}}]});continue}if("textDirective"===n.type&&"status"===n.name){const e=ze(n)||"Status",t=_e(n.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:e,color:t}});continue}if("textDirective"===n.type&&"emoji"===n.name){const e=Ce(n);r.push(Ne(e,t));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(n.value??"")+"",marks:[{type:"code"}]});else r.push(...ke(Ee(n.children??[],t),{type:"strike"}));else r.push(...ke(Ee(n.children??[],t),{type:"em"}));else r.push(...ke(Ee(n.children??[],t),{type:"strong"}));else r.push(...Ie((n.value??"")+"",t));return r.filter(e=>!("text"===e.type&&""===(e.text??"")))}function ke(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 Ae(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(Ae(t.children??[],""));return r.join("")||t}function Oe(e,t){const r=(e??"").trim(),n=(t??"").trim();return r===n&&/^https?:\/\//i.test(n)}function Ce(e){return(e.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("").trim()||""}function Ne(e,t){const r=e.startsWith(":")?e:`:${e}:`,n=t.resolveEmoji?.(r);return n?{type:"emoji",attrs:{shortName:n.shortName,text:n.text}}:{type:"emoji",attrs:{shortName:r}}}function He(e){return e?"string"==typeof e?e:"text"===e.type||"inlineCode"===e.type?(e.value??"")+"":Array.isArray(e.children)?e.children.map(He).join(""):"":""}function Je(e,t){if(!e?.type)return null;if((e=>"containerDirective"===e?.type&&"panel"===e?.name)(e))return((e,t)=>{const r=e.attributes??{},n=Te(r.type)??"info",s="string"==typeof r.title?r.title:void 0,i=(e.children??[]).map(e=>Je(e,t)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:n,...s?{panelType:n,title:s}:{panelType:n}},content:i.length?i:[{type:"paragraph",content:[]}]}})(e,t);switch(e.type){case"heading":return{type:"heading",attrs:{level:qe(e.depth??1,1,6)},content:Ee(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 n=(r.url??"")+"";return n?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:n}}]}:null})(e);return r||{type:"paragraph",content:Ee(e.children??[],t)}}case"blockquote":return{type:"blockquote",content:(e.children??[]).map(e=>Je(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 n=0;for(const s of e.children??[]){if("boolean"!=typeof s.checked)continue;n+=1;const e=(s.children??[]).map(e=>Je(e,t)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+n,state:s.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=>Je(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:Ee(e.children??[],t)}]}))}))}))(e,t);case"leafDirective":return"status"===e.name?(e=>{const t=_e((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??{},n=Te(r.type)??"info",s="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:n,...s?{title:s}:{}},content:[{type:"paragraph",content:Ee([{type:"text",value:ze(e)}],t)}]}})(e,t):Pe(e,t);default:return Pe(e,t)}}function Pe(e,t){if("drop"===t.unknownNodeStrategy)return null;const r=He(e);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function qe(e,t,r){const n=Number.isFinite(e)?Math.trunc(e):t;return Math.max(t,Math.min(r,n))}const $e={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function Re(e,t={}){const r={...$e,...t},n=e??"",s=m.unified().use(y).use(f).use(h),i=s.parse(n),o=s.runSync(i);return De(o),((e,t)=>{const r=[];for(const n of e.children??[]){const e=Je(n,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 n=r.attrs?.url;return n?[{type:"blockCard",attrs:{url:n}}]:e})(e)).flat();return{...e,content:r}})({version:1,type:"doc",content:r},t)})(o,r)}function De(e){if(!e||!Array.isArray(e.children))return;const t=[];for(const r of e.children)"definition"!==r?.type&&("html"!==r?.type?(De(r),t.push(r)):t.push({type:"text",value:(r.value??"")+""}));e.children=t}const Le=/\{\{\s*([^\}]+)\s*\}\}/g;function Me(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 g.inspect(e,{depth:null})}})(e);return t?[{type:"text",text:t}]:[]}function Ue(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:Me(r),result:r,structuredContent:r}}const Be={name:"jira-issue-create",inputSchema:we,runTool:async(e,t)=>Ue(await(async(e,t)=>{let r;const n=e=>e&&e.trim()?e.trim():void 0,s=n(de.jira.projectKey),i=n(de.jira.issueType),o=t&&"object"==typeof t&&!Array.isArray(t)?t:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??s,issueType:o.issueType??i};try{r=we.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=(n=t.content,s=t.placeholders,n?n.replace(Le,(e,t)=>{const r=t.trim();if(!r)return"";if(s&&Object.prototype.hasOwnProperty.call(s,r)){const e=s[r];return null==e?"":e+""}return e}):"");var n,s;if(!r.trim())return e;const i=Re(r),o=(a=e.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?Re(a).content:[]:[];var a;return e.description={type:"doc",version:1,content:[...o,...i.content]},e})(c,r.template);const p=e?.issues?.create??e?.issues?.createIssue;if("function"!=typeof p)throw Error("Jira client missing create function");const l=await p.call(e.issues,{fields:c}),u=l&&l.data||l;return{id:u?.id??null,key:u?.key??null}})(e,t))};class Ke 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}}function Fe(e){if(!e)return new Ke({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,n=e?.response?.data??e?.data??e?.response?.body??e?.body,s=[];"string"==typeof e?.message&&s.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)}))})(n,s);const i=r?`Jira API error (${r})`:"Jira API error",o=s.length>0?s.join(" | "):i;return new Ke({code:r?"jira_"+r:e?.code??"jira_error",message:o,details:{httpStatus:r,body:n,raw:e}})}const We=i.z.object({issueId:i.z.string().min(1),deleteSubtasks:i.z.boolean().optional().default(!0)}),Ye={name:"jira-issue-delete",inputSchema:We,runTool:async(e,t)=>{try{const r=We.parse(t),n=e.issues??e.issue??e,s=n?.delete??n?.deleteIssue;if("function"!=typeof s)throw Error("jira client delete endpoint is not available");return await s.call(n,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),Ue({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(e){throw Fe(e)}}},Xe=i.z.object({projectKey:i.z.string().trim().min(1).optional(),issueType:i.z.string().trim().min(1).optional(),parentIssueId:i.z.string().trim().min(1).optional(),name:i.z.string().trim().min(1).optional(),reference:i.z.string().trim().min(1).optional(),jql:i.z.string().trim().min(1).optional(),startAt:i.z.number().int().min(0).optional(),maxResults:i.z.number().int().min(1).optional(),fields:i.z.array(i.z.string()).optional(),expand:i.z.string().optional(),orderBy:i.z.string().trim().min(1).optional()});function Ge(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const Ve={name:"jira-issue-list",inputSchema:Xe,runTool:async(e,t)=>{try{const r=Xe.parse(t),n=r.startAt??0,s=r.maxResults??50;let i=r.jql?.trim();if(i){if(r.orderBy){const e=r.orderBy.trim();e&&(i=/\border\s+by\b/i.test(i)?`${i}, ${e}`:`${i} ORDER BY ${e}`)}}else i=(e=>{const t=[];if(e.projectKey&&t.push(`project = "${Ge(e.projectKey)}"`),e.issueType&&t.push(`issuetype = "${Ge(e.issueType)}"`),e.parentIssueId&&t.push(`parent = "${Ge(e.parentIssueId)}"`),e.name&&t.push(`summary ~ "${Ge(e.name)}"`),e.reference){const r=Ge(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:i,startAt:n,maxResults:s};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 p=await c.call(a,o),l=p?.data??p,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=n),void 0===u.maxResults&&(u.maxResults=s),Ue(u)}catch(e){throw Fe(e)}}},Ze=i.z.object({issueId:i.z.string().min(1),expand:i.z.string().optional(),fields:i.z.array(i.z.string()).optional(),properties:i.z.array(i.z.string()).optional()}),Qe={name:"jira-issue-read",inputSchema:Ze,runTool:async(e,t)=>{try{const r=Ze.parse(t),n={issueIdOrKey:r.issueId};r.expand&&(n.expand=r.expand),r.fields&&(n.fields=r.fields),r.properties&&(n.properties=r.properties);const s=await e.issues.getIssue(n);return Ue(s?.data??s)}catch(e){throw Fe(e)}}},et=i.z.object({issueId:i.z.string().min(1),transitionId:i.z.union([i.z.string(),i.z.number()]),fields:i.z.record(i.z.any()).optional(),update:i.z.record(i.z.array(i.z.object({set:i.z.any().optional(),add:i.z.any().optional(),remove:i.z.any().optional()}))).optional(),comment:i.z.string().optional()}),tt={name:"jira-issue-transition",inputSchema:et,runTool:async(e,t)=>{try{const r=et.parse(t),n={id:r.transitionId};r.fields&&(n.fields=r.fields),r.update&&(n.update=r.update),r.comment&&(n.comment={body:Re(r.comment)});const s=await e.issues.transition({issueIdOrKey:r.issueId,transition:n});return Ue(s?.data??s)}catch(e){throw Fe(e)}}},rt=i.z.object({issueId:i.z.string().min(1),expand:i.z.string().optional()}),nt={name:"jira-transition-list",inputSchema:rt,runTool:async(e,t)=>{try{const r=rt.parse(t),n=e.issues;if(!n||"function"!=typeof n.getTransitions)throw Error("Jira transitions API is unavailable on the client");const s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand);const i=await n.getTransitions(s);return Ue(i?.data??i)}catch(e){throw Fe(e)}}},st=i.z.object({issueId:i.z.string().min(1),fields:i.z.record(i.z.any()).optional(),update:i.z.record(i.z.array(i.z.object({set:i.z.any().optional(),add:i.z.any().optional(),remove:i.z.any().optional(),edit:i.z.any().optional()}))).optional(),properties:i.z.array(i.z.any()).optional(),notifyUsers:i.z.boolean().optional().default(!0),issueTemplateId:i.z.string().optional(),overrideScreenSecurity:i.z.boolean().optional().default(!1),overrideEditableFlag:i.z.boolean().optional().default(!1)}),it={name:"jira-issue-update",inputSchema:st,runTool:async(e,t)=>{try{const r=st.parse(t),n={issueIdOrKey:r.issueId};r.fields&&(n.fields=r.fields),r.update&&(n.update=r.update),r.properties&&(n.properties=r.properties),void 0!==r.notifyUsers&&(n.notifyUsers=r.notifyUsers),r.issueTemplateId&&(n.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(n.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(n.overrideEditableFlag=r.overrideEditableFlag);const s=await e.issues.editIssue(n);return Ue(s?.data??s)}catch(e){throw Fe(e)}}},ot=i.z.object({issueId:i.z.string().min(1),assignee:i.z.union([i.z.string(),i.z.object({accountId:i.z.string().min(1)}),i.z.object({accountType:i.z.string().min(1)})])}),at={name:"jira-assign-issue",inputSchema:ot,runTool:async(e,t)=>{try{const r=ot.parse(t);let n;n="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const s=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:n});return Ue(s?.data??s)}catch(e){throw Fe(e)}}},ct=i.z.object({issueId:i.z.string().min(1)}),pt={name:"jira-unassign-issue",inputSchema:ct,runTool:async(e,t)=>{try{const r=ct.parse(t),n=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return Ue(n?.data??n)}catch(e){throw Fe(e)}}},lt=i.z.object({issueId:i.z.string().min(1),body:i.z.string().min(1),visibility:i.z.object({type:i.z.enum(["role","group"]),value:i.z.string().min(1)}).optional()}),ut={name:"jira-comment-add",inputSchema:lt,runTool:async(e,t)=>{try{const r=lt.parse(t),n=e.issueComments;if(!n||"function"!=typeof n.addComment)throw Error("Jira issueComments API is unavailable on the client");const s={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(s.visibility=r.visibility);const i=await n.addComment(s);return Ue(i?.data??i)}catch(e){throw Fe(e)}}},dt=i.z.object({issueId:i.z.string().min(1),start:i.z.number().optional().default(0),maxResults:i.z.number().optional().default(50),orderBy:i.z.string().optional(),expand:i.z.string().optional()}),mt={name:"jira-comment-list",inputSchema:dt,runTool:async(e,t)=>{try{const r=dt.parse(t),n=e.issueComments;if(!n||"function"!=typeof n.getComments)throw Error("Jira issueComments API is unavailable on the client");const s=await n.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return Ue(s?.data??s)}catch(e){throw Fe(e)}}},ht=i.z.object({link:i.z.object({relationship:i.z.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]),inwardIssue:i.z.object({id:i.z.string().optional(),key:i.z.string().optional()}),outwardIssue:i.z.object({id:i.z.string().optional(),key:i.z.string().optional()}),comment:i.z.object({body:i.z.string().optional(),visibility:i.z.object({type:i.z.enum(["role","group"]),value:i.z.string().min(1)}).optional()}).optional()})});let ft=[];function yt(e){return(e||"").trim().toLowerCase()}const gt=ht;function bt(e){if(e.id)return{id:e.id};if(e.key)return{key:e.key};throw Error("Linked issue must include an id or key")}const vt={name:"jira-link-create",inputSchema:gt,runTool:async(e,t)=>{try{const r=gt.parse(t).link,n={inwardIssue:bt(r.inwardIssue),outwardIssue:bt(r.outwardIssue)};if(r.comment){const e={};r.comment.body&&(e.body=Re(r.comment.body)),r.comment.visibility&&(e.visibility=r.comment.visibility),Object.keys(e).length>0&&(n.comment=e)}const s=e.issueLinks;if(!s||"function"!=typeof s.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const i=await(async(e,t)=>{if(!t)throw Error("Link relationship is required");if(0===ft.length){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();ft=r?.issueLinkTypes??r?.values??[]}const r=yt(t),n=ft.find(e=>[e.name,e.inward,e.outward].some(e=>yt(e)===r));if(!n)throw Error(`No issue link type matching '${t}' found.`);return n})(e,r.relationship);n.type={id:i.id};const o=await s.linkIssues(n);return Ue(o?.data??o)}catch(e){throw Fe(e)}}},wt=i.z.object({issueId:i.z.string().min(1),file:i.z.string().min(1),mimeType:i.z.string().optional(),comment:i.z.string().optional()}),St={name:"jira-attach",inputSchema:wt,runTool:async(e,r)=>{try{const n=wt.parse(r),s=c.resolve(n.file),i=await t.promises.readFile(s),o=c.basename(s),a=new FormData;a.append("file",new Blob([i],{type:n.mimeType??"application/octet-stream"}),o);const p=e?.config??null,l=p?.host,u=p?.authentication?.basic??p?.authentication??p?.auth??null,d=u?.email,m=u?.apiToken??u?.apiKey;if(!l||!d||!m)throw Error("Jira client authentication configuration is unavailable for attachments");const h=await fetch(`${l}/rest/api/3/issue/${n.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${d}:${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(n.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:n.issueId,comment:Re(n.comment)})}return Ue(f)}catch(e){if(e&&e.code&&"string"==typeof e.code&&["ENOENT","EACCES"].includes(e.code))throw Error("Attachment file error: "+e.message);throw Fe(e)}}},It=i.z.object({issueId:i.z.string().min(1)}),jt={name:"jira-attachment-list",inputSchema:It,runTool:async(e,t)=>{try{const r=It.parse(t),n=e.issues;if(!n||"function"!=typeof n.getIssue)throw Error("Jira issues API is unavailable on the client");const s=await n.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),i=s?.data??s;return Ue({attachments:i?.fields?.attachment??[]})}catch(e){throw Fe(e)}}},xt=i.z.object({issueId:i.z.string().min(1),attachmentId:i.z.string().min(1)}),zt={name:"jira-attachment-delete",inputSchema:xt,runTool:async(e,t)=>{try{const r=xt.parse(t),n=e.issueAttachments;if(!n||"function"!=typeof n.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await n.removeAttachment({id:r.attachmentId}),Ue({success:!0,message:`Attachment ${t.attachmentId} deleted successfully`})}catch(e){throw Fe(e)}}},Tt=i.z.object({issueId:i.z.string().min(1),timeSpent:i.z.string().min(1),comment:i.z.string().optional(),author:i.z.object({accountId:i.z.string().min(1)}).optional(),startingOn:i.z.string().optional(),artifact:i.z.string().optional()}),_t={name:"jira-worklog-add",inputSchema:Tt,runTool:async(e,t)=>{try{const r=Tt.parse(t),n={timeSpent:r.timeSpent};r.comment&&(n.comment=r.comment),r.author&&(n.author=r.author),r.startingOn&&(n.started=r.startingOn),r.artifact&&(n.artifact=r.artifact);const s=e.issueWorklogs;if(!s||"function"!=typeof s.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const i=await s.addWorklog({issueIdOrKey:r.issueId,...n});return Ue(i?.data??i)}catch(e){throw Fe(e)}}};class Et{constructor(){this.clientId=de.orThrow().xray.apiUser,this.clientSecret=de.orThrow().xray.apiSecret,this.baseUrl=de.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=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})}),n=await r.json();if(n.errors)throw Error(JSON.stringify(n.errors,null,2));return n.data}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||[],n=[],s=[],i=[];for(let e=0;e<t.length;e++){const i=t[e],o=r[e];o?o.action===i.action&&o.data===i.data&&o.result===i.result||n.push({stepId:o.id,step:i}):s.push(i)}if(r.length>t.length)for(let e=t.length;e<r.length;e++)i.push(r[e].id);await this.addSteps(e,s),await this.updateSteps(n),await this.deleteSteps(i)}}let kt=null;const At=new Map;function Ot(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 n=e.data??e.fields?.Data??e.fields?.data??void 0,s=e.result??e.fields?.Result??e.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof n?n:void 0,result:"string"==typeof s?s:void 0}}async function Ct(e,t){if(!t)throw Error("Issue reference is required when interacting with Xray steps");if(At.has(t))return At.get(t);if(/^[0-9]+$/.test(t))return At.set(t,t),t;const r=e?.issues??e?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const n=await r.getIssue({issueIdOrKey:t,fields:["id"]}),s=n?.id;if(!s)throw Error("Unable to resolve Jira issue ID for "+t);return At.set(t,s),s}async function Nt(e){if(e?.test?.step)return e.test.step;const t=await(async()=>{if(kt)return kt;const e=de.orThrow().xray.apiUser?.trim(),t=de.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=ge(),n=new Et;return kt={test:{step:{async createStep(e,t){const s=await Ct(r,e),i=await n.addStep(s,Ot(t));return{step:i,id:i?.id}},async updateStep(e,t,s){await Ct(r,e);const i=Ot(s),o=await n.updateStep(t.toString(),i);return{step:o,id:o?.id}},deleteStep:async(e,t)=>(await Ct(r,e),{success:!0===await n.deleteStep(t.toString())}),async getSteps(e){const t=await Ct(r,e),s=await n.getTest(t);return{steps:s?.steps??[]}}}}},kt})();if(!t?.test?.step)throw Error("Xray step API is unavailable on the client");return t.test.step}const Ht=i.z.object({issueId:i.z.string().min(1),action:i.z.string().min(1),data:i.z.string().optional(),result:i.z.string().optional()}),Jt={name:"jira-xray-step-add",inputSchema:Ht,runTool:async(e,t)=>{try{const r=Ht.parse(t),n=await Nt(e),s={action:r.action,data:r.data,result:r.result};return Ue(await n.createStep(r.issueId,s))}catch(e){throw Fe(e)}}},Pt=i.z.object({issueId:i.z.string().min(1),stepId:i.z.union([i.z.string(),i.z.number()]),action:i.z.string().min(1),data:i.z.string().optional(),result:i.z.string().optional()}),qt={name:"jira-xray-step-update",inputSchema:Pt,runTool:async(e,t)=>{try{const r=Pt.parse(t),n=await Nt(e),s=r.stepId+"",i={action:r.action,data:r.data,result:r.result};return Ue(await n.updateStep(r.issueId,s,i))}catch(e){throw Fe(e)}}},$t=i.z.object({issueId:i.z.string().min(1),stepId:i.z.union([i.z.string(),i.z.number()])}),Rt={name:"jira-xray-step-delete",inputSchema:$t,runTool:async(e,t)=>{try{const r=$t.parse(t),n=await Nt(e),s=Number(r.stepId);return await n.deleteStep(r.issueId,s),Ue({success:!0})}catch(e){throw Fe(e)}}},Dt=i.z.object({issueId:i.z.string().min(1)}),Lt={name:"jira-xray-step-list",inputSchema:Dt,runTool:async(e,t)=>{try{const r=Dt.parse(t),n=await Nt(e);return Ue(await n.getSteps(r.issueId))}catch(e){throw Fe(e)}}},Mt={[Be.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Qe.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ve.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}},[it.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}},[Ye.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[tt.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[nt.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[at.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[pt.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ut.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}},[mt.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[vt.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[St.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[jt.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[zt.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[_t.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Jt.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[qt.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Rt.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Lt.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 Ut(e){const t=r.Logging.for(Ut);let n,s=null;try{n=ge()}catch(e){if(!(e instanceof ye))return void t.warn("Skipping Jira tool registration; unable to create Jira client",{error:e});s=e,t.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:e})}const i=[Be,Qe,Ve,it,Ye,tt,nt,at,pt,ut,mt,vt,St,jt,zt,_t,Jt,qt,Rt,Lt];for(const r of i){const i=Mt[r.name];if(i)try{await e.registerTool(r.name,{title:i.title,description:i.description,inputSchema:r.inputSchema,annotations:i.annotations},async e=>{if(!n)throw s??Error("Jira client unavailable because credentials could not be loaded.");return r.runTool(n,e)}),t.info("Registered Jira tool "+r.name)}catch(e){t.error("Failed to register Jira tool "+r.name,{error:e})}}}async function Bt(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=se.map(e=>e.getName()).sort();return{content:[{type:"text",text:["Name: "+de.name,"Title: "+de.title,"Version: "+de.version,"Prompts: "+(e.join(", ")||"<none>")].join("\n")}]}})})(e);const t=r.Logging.for(Bt);try{await Ut(e)}catch(e){t.error("Failed to register Jira tools",e)}}class Kt extends N{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 Kt}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{const t="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new v.ResourceTemplate(new b.UriTemplate(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),n=async(e,t)=>{const r=this.logFor(t);r.verbose(`Requesting resource ${this.name} from ${e.toString()}`);const n=await Promise.resolve(this.cb(e,t));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(n._meta)),n};return e.resource(this.name,t,r,n)}catch(e){throw r.Logging.for(this).error("Error registering resource "+this.name,e),e}}}n.__decorate([s.required(),n.__metadata("design:type",String)],Kt.prototype,"uriOrTemplate",void 0),n.__decorate([s.required(),n.__metadata("design:type",Function)],Kt.prototype,"cb",void 0),n.__decorate([s.required(),n.__metadata("design:type",Object)],Kt.prototype,"config",void 0);const Ft=W()??z.join(__dirname,"..","assets"),Wt=z.join(Ft,"templates"),Yt=z.join(Ft,"prompts"),Xt=new WeakMap;class Gt extends r.LoggedClass{get client(){const e=Xt.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 se)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 Bt(this.client),e.verbose("Registered built-in tools")}catch(e){}try{await(async(e,t)=>{t.info("Registering agent templates as resources...");const r=x.readdirSync(Wt).filter(e=>e.endsWith(".md"));for(const n of r){const r=z.basename(n,".md"),s=z.join(Wt,n),i=Kt.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+s).setConfig({mimeType:"text/markdown",description:"Template for "+r}).setCb(async e=>{const t=x.readFileSync(e.pathname,"utf8");return{contents:[{uri:e.toString(),text:t,mimeType:"text/markdown"}],_meta:{}}});try{i.build(e),t.info("Registered template: "+r)}catch(e){t.error(`Failed to register template ${r}:`,e)}}t.info("Registering agent prompts...");const n=x.readdirSync(Yt).filter(e=>e.endsWith(".md"));for(const r of n){const n=z.basename(r,".md"),s=z.join(Yt,r),o=x.readFileSync(s,"utf8"),a=X.builder.setName(n).setTitle("Prompt: "+n).setDescription("Dynamic prompt for "+n).setArgsSchema(i.z.object({})).setCb(async e=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(e),t.info("Registered prompt: "+n)}catch(e){t.error(`Failed to register prompt ${n}:`,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(de.icons)?de.icons:[de.icons])||[]).map(e=>{const t="string"==typeof e?.src?e.src:(e?.src??"")+"",r="string"==typeof e?.mimeType?e.mimeType:(e?.mimeType??"")+"";let n=[];return Array.isArray(e?.sizes)?n=e.sizes.map(e=>e+""):"string"==typeof e?.sizes&&(n=(e.sizes+"").split(",").map(e=>e.trim())),{src:t,mimeType:r,sizes:n}}),n={name:de.name,title:de.title,websiteUrl:de.websiteUrl,version:de.version,icons:t},s=new v.McpServer(n,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((e,t)=>{Xt.set(e,t)})(this,s),s.onerror=e=>{this.log.error("MCP instance onerror",e)},e){case"stdio":e=new S.StdioServerTransport;break;case"http":e=new I.StreamableHTTPServerTransport({sessionIdGenerator:()=>w.v4(),onsessioninitialized:e=>{},onsessionclosed:e=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(i=e)||"object"!=typeof i||"function"!=typeof i.send&&"function"!=typeof i.close&&"function"!=typeof i.on)throw new p.InternalError("Invalid transport type: "+e)}var i;try{await this.load()}catch(e){throw e}await this.client.connect(e)}}const Vt=(new e.Command).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async e=>{const r=K("package.json"),n=JSON.parse(t.readFileSync(r,"utf-8")),s=n.version,{transport:i}=e,o=(new T).for("mcp-server");if("stdio"!==i)throw Error("Unsupported transport mode: "+i);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(e)} for ${n.name} version ${s}`),(new Gt).boot(i)});(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 n=K("package.json"),s=JSON.parse(t.readFileSync(n,"utf-8")),i=s.version;r.Logging.for("md-to-ast").debug(`running with options: ${JSON.stringify(e)} for ${s.name} version ${i}`);const o=Re(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 Zt=(new e.Command).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");Zt.addCommand(Vt),Zt.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("unified"),require("remark-directive"),require("remark-gfm"),require("remark-parse"),require("node:util"),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","unified","remark-directive","remark-gfm","remark-parse","node:util","@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.unified,e.remarkDirective,e.remarkGfm,e.remarkParse,e.node_util,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,n,s,i,o,a,c,l,p,u,d,m,h,f,y,g,b,v,w,I,S){"use strict";function j(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var n=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var k=j(t),x=j(c);class z extends r.MiniLogger{constructor(e,t,r){super(e,t,r)}log(e,t,n,s){const i=this.config("level");r.NumericLogLevels[i],r.NumericLogLevels[e]}}const T=(e,t,...r)=>{const n=(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 z(n,t)};var _,E,A,O,C;(e=>{e[e.NONE=0]="NONE",e[e.BASIC=1]="BASIC",e[e.ADVANCED=2]="ADVANCED",e[e.HIGH=3]="HIGH"})(_||(_={})),(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"})(A||(A={}));class H extends s.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:n}=e||{};let s="string"==typeof t&&t.length>0?this.log.for(t):this.log;return n&&n.clientId&&(s=s.for(n.clientId)),r&&(s=s.for(r.toString())),s}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}}n.__decorate([s.required(),n.__metadata("design:type",String)],H.prototype,"description",void 0),n.__decorate([s.required(),n.__metadata("design:type",String)],H.prototype,"name",void 0),n.__decorate([s.required(),n.__metadata("design:type",String)],H.prototype,"title",void 0);class J extends H{constructor(e){super(e),this.reasoning=_.NONE,this.effort=E.NONE,this.cost=A.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 P(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,n]of Object.entries(r))e[t]=$(n)?n:i.z.any();return i.z.object(e)}}throw Error(`Registration error: provided a non-canonical ${t}. Export a ZodObject (z.object(...)).`)}function q(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 $(e){return!(!e||"object"!=typeof e||!e._def)}n.__decorate([s.required(),n.__metadata("design:type",Number)],J.prototype,"reasoning",void 0),n.__decorate([s.required(),n.__metadata("design:type",Number)],J.prototype,"effort",void 0),n.__decorate([s.required(),n.__metadata("design:type",Number)],J.prototype,"cost",void 0),(e=>{e.ASSETS="assets"})(O||(O={})),(e=>{e.PROMPT="prompts",e.DOCUMENTATION="documentation",e.CODE="code"})(C||(C={}));const R=Buffer.from("DCAF1","ascii");function D(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]?D(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=d.fileURLToPath(r)}catch{continue}if(!r.includes("node:internal"))return c.dirname(r)}})(),U=M?D(M):void 0,B=L??U??process.cwd();function K(...e){return c.join(B,...e)}function F(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 n=x.join(t,"assets");if(k.existsSync(n))return n;const s=x.dirname(t);if(s===t)break;t=s}}function W(){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=F(__dirname);if(t)return t;const r=process.argv?.[1];if(r){const e=F(x.dirname(r));if(e)return e}const n=[B,process.env.INIT_CWD].filter(Boolean);for(const e of n){const t=F(e);if(t)return t}return K("assets")}let Y=class extends r.LoggedClass{constructor(e){super(),this.basePath=e||W()}listAssets(...e){const t=x.join(this.basePath,...e);return k.readdirSync(t)}listPrompts(){return this.listAssets(C.PROMPT)}getAsset(e,t="md",...r){const n=x.join(this.basePath,...r),s=(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 n=e.subarray(r,r+16);r+=16;const s=e.subarray(r,r+12);r+=12;const i=e.subarray(r,r+16);r+=16;const o=e.subarray(r),a=((e,t)=>p.scryptSync(e,t,32))(t,n),c=p.createDecipheriv("aes-256-gcm",a,s);c.setAuthTag(i);const l=Buffer.concat([c.update(o),c.final()]);return u.gunzipSync(l)})(k.readFileSync(e)).toString("utf-8"):k.readFileSync(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}},i=s(x.join(n,`${e}.${t}`),"enc"===t);if(null!==i)return i;const o=s(x.join(n,e+".enc"),!0);if(null!==o)return o;throw Error("Asset not found: "+x.join(n,`${e}.${t}`))}getAllAssets(e,...t){return this.listAssets(e,...t).reduce((r,n)=>{const s=x.extname(n),i=x.basename(n,s),o=s.replace(/^\./,"")||void 0;return r[i]=this.getAsset(i,o??void 0,e,...t),r},{})}toPromptDef(e){const t=e=>"number"==typeof e?e:"string"==typeof e?(e=>{switch(e){case"none":return _.NONE;case"basic":return _.BASIC;case"advanced":return _.ADVANCED;case"high":return _.HIGH;case"medium":return E.MEDIUM;case"low":return A.LOW;case"free":return A.FREE;default:throw new l.InternalError("Cannon convert unknown level "+e)}})(e.toLowerCase()):_.NONE;return e.effort=t(e.effort),e.reasoning=t(e.reasoning),e.cost=t(e.cost),e}getPrompt(e,...t){const n=this.getAsset(r.toSnakeCase(e),"json",C.PROMPT,...t);let s;try{s=JSON.parse(n)}catch(r){throw new l.SerializationError(`Failed to parse prompt ${e} in categories ${t}: ${r}`)}return this.toPromptDef(s)}getAllPrompts(...e){const t=this.getAllAssets(C.PROMPT,...e);return Object.entries(t).reduce((t,[r,n])=>{try{t[r]=JSON.parse(n)}catch(t){throw new l.SerializationError(`Failed to parse prompt ${r} in categories ${e}: ${t}`)}return t},t)}};Y=n.__decorate([o.injectable(),n.__metadata("design:paramtypes",[String])],Y);class X extends J{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,n,s){const i=(t=Array.isArray(t)?t:Object.keys(t)).filter(e=>!Object.prototype.hasOwnProperty.call(n,e));if(i.length)throw new l.ValidationError("Missing replacements for placeholders: "+i.join(", "));s&&(s.verbose("Patching prompt with placeholders: "+JSON.stringify(t)),s.debug("Values: "+JSON.stringify(n)));const o=t.reduce((e,t)=>(e[t]=n[t],e),{});return r.sf(e,o)}patchPrompt(e,t,r,n){return X.patchPrompt(e,t,r,n||this.log.for(this.patchPrompt))}build(e,t){const r=this.log.for(this.build),n=this.hasErrors();if(n)throw new l.ValidationError(n.toString());try{this.argsSchema&&P(this.argsSchema,"argsSchema");const r=q(this.argsSchema);return e.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(e,r)=>{const n=this.logFor(r);e=Object.assign({},t,e||{}),n.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 s=await Promise.resolve(this.cb(e,r));return n.verbose(`Prompt ${this.name} executed successfully.`),n.debug("Prompt execution meta: "+JSON.stringify(s._meta)),s})}catch(e){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),e),e}}}n.__decorate([o.inject(Y),n.__metadata("design:type",Y)],X.prototype,"assets",void 0),n.__decorate([s.required(),n.__metadata("design:type",Object)],X.prototype,"cb",void 0),n.__decorate([s.required(),n.__metadata("design:type",i.ZodObject)],X.prototype,"argsSchema",void 0),n.__decorate([a.prop(),n.__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);s.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 n=this.hasErrors(...Array.from(r));if(n)throw new l.ValidationError(n.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]=i.z.string().describe("The description for "+t),e),{});return this.setArgsSchema(i.z.object(p)),this.setCb((e,t)=>{const r=this.logFor(t).for(G).for(this.promptCategory).for(this.name);function n(e=[]){return Array.isArray(e)?e:Object.keys(e)}const s=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),i=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...s.map(e=>n(e.placeholders)).flat(),...i.map(e=>n(e.placeholders)).flat(),...n(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...s.map(e=>e.prompt),o.prompt,...i.map(e=>e.prompt)].join("\n\n"),a,e,r)}}],_meta:{}}}),super.build(e)}setReasoning(e){throw new l.InternalError("Named prompt builders don't require callback")}setEffort(e){throw new l.InternalError("Named prompt builders don't require callback")}setCost(e){throw new l.InternalError("Named prompt builders don't require callback")}setDescription(e){throw new l.InternalError("Named prompt builders don't require callback")}setTitle(e){throw new l.InternalError("Named prompt builders don't require callback")}static get builder(){return new G}}n.__decorate([s.required(),n.__metadata("design:type",String)],G.prototype,"promptCategory",void 0),n.__decorate([s.list(String),s.minlength(1),n.__metadata("design:type",Array)],G.prototype,"prefixes",void 0),n.__decorate([s.minlength(1),s.list(String),n.__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(i.z.object({message:i.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(i.z.object({gist:i.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 n=G.builder.setCategory(ee.DOCS).setName(e);return["prefix",...t].forEach(e=>n.addPrefix(e)),["suffix",...r].forEach(e=>n.addSuffix(e)),n}(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"])],ne=i.z.object({className:i.z.string().describe("the class name to turn into a builder")}),se=[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(ne).setReasoning(_.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 ie extends J{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 ie}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{this.inputSchema&&P(this.inputSchema,"inputSchema"),this.outputSchema&&P(this.outputSchema,"outputSchema");const t=q(this.inputSchema),r=q(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 n=await Promise.resolve(this.cb(e,t));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(n._meta)),n})}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}}}n.__decorate([s.required(),n.__metadata("design:type",Object)],ie.prototype,"annotations",void 0),n.__decorate([s.required(),n.__metadata("design:type",Object)],ie.prototype,"cb",void 0),n.__decorate([s.required(),n.__metadata("design:type",Function)],ie.prototype,"inputSchema",void 0);const oe=ie.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(i.z.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(oe,{name:oe.getName()});const ae=ie.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(i.z.object({filePath:i.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 n=c.dirname(e);if(n===e)break;e=n}}catch{}return{}}Object.assign(ae,{name:ae.getName()});const le=ce().version??"0.0.0",pe=ce().name??"unknown";a.Metadata.registerLibrary(pe,le);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:le,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:B,assetDir:W(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0},xray:{host:process.env.XRAY__HOST||process.env.XRAY__API_HOST||"https://xray.cloud.getxray.app",apiUser:process.env.XRAY__API_USER||"",apiSecret:process.env.XRAY__API_SECRET||""},level:r.LogLevel.error},de=r.LoggedEnvironment.accumulate(ue);function me(){const{host:e,email:t,apiKey:r,projectKey:n,issueType:s}=de.jira;return{host:e?.trim(),email:t?.trim(),apiKey:r?.trim(),projectKey:n?.trim(),issueType:s?.trim(),parentIssue:de.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(de);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)}}function ge(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:n,apiKey:s}=(()=>{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}})();return new t({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:n,apiToken:s}}})}const be=i.z.object({name:i.z.string().min(1).optional(),content:i.z.string().min(1),placeholders:i.z.record(i.z.string()).optional()}),ve=i.z.object({template:be.optional()}),we=i.z.union([i.z.object({fields:i.z.record(i.z.any())}).merge(ve),i.z.object({summary:i.z.string().min(1),projectKey:i.z.string().min(1),issueType:i.z.string().min(1),description:i.z.string().optional()}).merge(ve)]);function Ie(e,t,r){const n=((e.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!n)return null;const s=n[2],i=r.resolveAttachment?.(s);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Se(e,t){if(!e)return[];if(!t.enableAtMentions&&!t.enableEmojiShortcodes)return[{type:"text",text:e}];let r=0;const n=[],s=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;r<e.length;){const o=ke(t.enableAtMentions?je(s,e,r):null,t.enableEmojiShortcodes?je(i,e,r):null);if(!o){n.push({type:"text",text:e.slice(r)});break}if(o.index>r&&n.push({type:"text",text:e.slice(r,o.index)}),"mention"===o.kind){const{full:e,groups:s}=o,i=s[0]??"",a=s[1]??"";i&&n.push({type:"text",text:i});const c=t.resolveMention?.(a);c?n.push({type:"mention",attrs:{id:c.id,text:c.text}}):n.push({type:"text",text:"@"+a}),r=o.index+e.length;continue}if("emoji"===o.kind){const{full:e,groups:s}=o,i=`:${s[0]}:`,a=t.resolveEmoji?.(i);n.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:i}}),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})(n)}function je(e,t,r){e.lastIndex=r;const n=e.exec(t);if(!n)return null;const s=e.source.includes("@")?"mention":"emoji";return{index:n.index,full:n[0],groups:n.slice(1),kind:s}}function ke(e,t){return e?t&&e.index>t.index?t:e:t}function xe(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 ze(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 Te(e){const t=((e??"")+"").toLowerCase().trim();return!t||"neutral"!==t&&"green"!==t&&"yellow"!==t&&"red"!==t&&"blue"!==t&&"purple"!==t?null:t}function _e(e,t){const r=[];for(const n of e??[])if(n?.type)if("text"!==n.type)if("strong"!==n.type)if("emphasis"!==n.type)if("delete"!==n.type)if("inlineCode"!==n.type)if("break"!==n.type){if("link"===n.type){const e=(n.url??"")+"",s=Ae(n.children??[],e),i=Ie(n,0,t);if(i){"inline"===i.type?r.push(i.node):r.push({type:"text",text:s,marks:[{type:"link",attrs:{href:e}}]});continue}if(t.enableSmartCards&&Oe(s,e)){r.push({type:"inlineCard",attrs:{url:e}});continue}r.push({type:"text",text:s,marks:[{type:"link",attrs:{href:e}}]});continue}if("textDirective"===n.type&&"status"===n.name){const e=xe(n)||"Status",t=Te(n.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:e,color:t}});continue}if("textDirective"===n.type&&"emoji"===n.name){const e=Ce(n);r.push(He(e,t));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(n.value??"")+"",marks:[{type:"code"}]});else r.push(...Ee(_e(n.children??[],t),{type:"strike"}));else r.push(...Ee(_e(n.children??[],t),{type:"em"}));else r.push(...Ee(_e(n.children??[],t),{type:"strong"}));else r.push(...Se((n.value??"")+"",t));return r.filter(e=>!("text"===e.type&&""===(e.text??"")))}function Ee(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 Ae(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(Ae(t.children??[],""));return r.join("")||t}function Oe(e,t){const r=(e??"").trim(),n=(t??"").trim();return r===n&&/^https?:\/\//i.test(n)}function Ce(e){return(e.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("").trim()||""}function He(e,t){const r=e.startsWith(":")?e:`:${e}:`,n=t.resolveEmoji?.(r);return n?{type:"emoji",attrs:{shortName:n.shortName,text:n.text}}:{type:"emoji",attrs:{shortName:r}}}function Je(e){return e?"string"==typeof e?e:"text"===e.type||"inlineCode"===e.type?(e.value??"")+"":Array.isArray(e.children)?e.children.map(Je).join(""):"":""}function Ne(e,t){if(!e?.type)return null;if((e=>"containerDirective"===e?.type&&"panel"===e?.name)(e))return((e,t)=>{const r=e.attributes??{},n=ze(r.type)??"info",s="string"==typeof r.title?r.title:void 0,i=(e.children??[]).map(e=>Ne(e,t)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:n,...s?{panelType:n,title:s}:{panelType:n}},content:i.length?i:[{type:"paragraph",content:[]}]}})(e,t);switch(e.type){case"heading":return{type:"heading",attrs:{level:qe(e.depth??1,1,6)},content:_e(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 n=(r.url??"")+"";return n?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:n}}]}:null})(e);return r||{type:"paragraph",content:_e(e.children??[],t)}}case"blockquote":return{type:"blockquote",content:(e.children??[]).map(e=>Ne(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 n=0;for(const s of e.children??[]){if("boolean"!=typeof s.checked)continue;n+=1;const e=(s.children??[]).map(e=>Ne(e,t)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+n,state:s.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=>Ne(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:_e(e.children??[],t)}]}))}))}))(e,t);case"leafDirective":return"status"===e.name?(e=>{const t=Te((e.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:xe(e)||"Status",color:t}}]}})(e):"panel"===e.name?((e,t)=>{const r=e.attributes??{},n=ze(r.type)??"info",s="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:n,...s?{title:s}:{}},content:[{type:"paragraph",content:_e([{type:"text",value:xe(e)}],t)}]}})(e,t):Pe(e,t);default:return Pe(e,t)}}function Pe(e,t){if("drop"===t.unknownNodeStrategy)return null;const r=Je(e);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function qe(e,t,r){const n=Number.isFinite(e)?Math.trunc(e):t;return Math.max(t,Math.min(r,n))}const $e={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function Re(e,t={}){const r={...$e,...t},n=e??"",s=m.unified().use(y).use(h).use(f),i=s.parse(n),o=s.runSync(i);return De(o),((e,t)=>{const r=[];for(const n of e.children??[]){const e=Ne(n,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 n=r.attrs?.url;return n?[{type:"blockCard",attrs:{url:n}}]:e})(e)).flat();return{...e,content:r}})({version:1,type:"doc",content:r},t)})(o,r)}function De(e){if(!e||!Array.isArray(e.children))return;const t=[];for(const r of e.children)"definition"!==r?.type&&("html"!==r?.type?(De(r),t.push(r)):t.push({type:"text",value:(r.value??"")+""}));e.children=t}function Le(e){return e.flatMap(e=>"panel"===e.type?Le(e.content??[]):[Me(e)])}function Me(e){return e.content?{...e,content:Le(e.content)}:{...e}}const Ue=/\{\{\s*([^\}]+)\s*\}\}/g;function Be(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 g.inspect(e,{depth:null})}})(e);return t?[{type:"text",text:t}]:[]}function Ke(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:Be(r),result:r,structuredContent:r}}const Fe={name:"jira-issue-create",inputSchema:we,runTool:async(e,t)=>Ke(await(async(e,t)=>{let r;const n=e=>e&&e.trim()?e.trim():void 0,s=n(de.jira.projectKey),i=n(de.jira.issueType),o=t&&"object"==typeof t&&!Array.isArray(t)?t:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??s,issueType:o.issueType??i};try{r=we.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=(n=t.content,s=t.placeholders,n?n.replace(Ue,(e,t)=>{const r=t.trim();if(!r)return"";if(s&&Object.prototype.hasOwnProperty.call(s,r)){const e=s[r];return null==e?"":e+""}return e}):"");var n,s;if(!r.trim())return e;const i=Re(r),o=(a=e.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?Re(a).content:[]:[];var a;return e.description={type:"doc",version:1,content:[...o,...i.content]},e})(c,r.template);const l=e?.issues?.create??e?.issues?.createIssue;if("function"!=typeof l)throw Error("Jira client missing create function");const p=await l.call(e.issues,{fields:c}),u=p&&p.data||p;return{id:u?.id??null,key:u?.key??null}})(e,t))};class We 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}}function Ye(e){if(!e)return new We({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,n=e?.response?.data??e?.data??e?.response?.body??e?.body,s=[];"string"==typeof e?.message&&s.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)}))})(n,s);const i=r?`Jira API error (${r})`:"Jira API error",o=s.length>0?s.join(" | "):i;return new We({code:r?"jira_"+r:e?.code??"jira_error",message:o,details:{httpStatus:r,body:n,raw:e}})}const Xe=i.z.object({issueId:i.z.string().min(1),deleteSubtasks:i.z.boolean().optional().default(!0)}),Ge={name:"jira-issue-delete",inputSchema:Xe,runTool:async(e,t)=>{try{const r=Xe.parse(t),n=e.issues??e.issue??e,s=n?.delete??n?.deleteIssue;if("function"!=typeof s)throw Error("jira client delete endpoint is not available");return await s.call(n,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),Ke({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(e){throw Ye(e)}}},Ve=i.z.object({projectKey:i.z.string().trim().min(1).optional(),issueType:i.z.string().trim().min(1).optional(),parentIssueId:i.z.string().trim().min(1).optional(),name:i.z.string().trim().min(1).optional(),reference:i.z.string().trim().min(1).optional(),jql:i.z.string().trim().min(1).optional(),startAt:i.z.number().int().min(0).optional(),maxResults:i.z.number().int().min(1).optional(),fields:i.z.array(i.z.string()).optional(),expand:i.z.string().optional(),orderBy:i.z.string().trim().min(1).optional()});function Ze(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const Qe={name:"jira-issue-list",inputSchema:Ve,runTool:async(e,t)=>{try{const r=Ve.parse(t),n=r.startAt??0,s=r.maxResults??50;let i=r.jql?.trim();if(i){if(r.orderBy){const e=r.orderBy.trim();e&&(i=/\border\s+by\b/i.test(i)?`${i}, ${e}`:`${i} ORDER BY ${e}`)}}else i=(e=>{const t=[];if(e.projectKey&&t.push(`project = "${Ze(e.projectKey)}"`),e.issueType&&t.push(`issuetype = "${Ze(e.issueType)}"`),e.parentIssueId&&t.push(`parent = "${Ze(e.parentIssueId)}"`),e.name&&t.push(`summary ~ "${Ze(e.name)}"`),e.reference){const r=Ze(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:i,startAt:n,maxResults:s};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 l=await c.call(a,o),p=l?.data??l,u="object"==typeof p&&null!==p?{...p}:{};return void 0===u.startAt&&(u.startAt=n),void 0===u.maxResults&&(u.maxResults=s),Ke(u)}catch(e){throw Ye(e)}}},et=i.z.object({issueId:i.z.string().min(1),expand:i.z.string().optional(),fields:i.z.array(i.z.string()).optional(),properties:i.z.array(i.z.string()).optional()}),tt={name:"jira-issue-read",inputSchema:et,runTool:async(e,t)=>{try{const r=et.parse(t),n={issueIdOrKey:r.issueId};r.expand&&(n.expand=r.expand),r.fields&&(n.fields=r.fields),r.properties&&(n.properties=r.properties);const s=await e.issues.getIssue(n);return Ke(s?.data??s)}catch(e){throw Ye(e)}}},rt=i.z.object({issueId:i.z.string().min(1),transitionId:i.z.union([i.z.string(),i.z.number()]),fields:i.z.record(i.z.any()).optional(),update:i.z.record(i.z.array(i.z.object({set:i.z.any().optional(),add:i.z.any().optional(),remove:i.z.any().optional()}))).optional(),comment:i.z.string().optional()}),nt={name:"jira-issue-transition",inputSchema:rt,runTool:async(e,t)=>{try{const r=rt.parse(t),n={id:r.transitionId};r.fields&&(n.fields=r.fields),r.update&&(n.update=r.update),r.comment&&(n.comment={body:Re(r.comment)});const s=await e.issues.transition({issueIdOrKey:r.issueId,transition:n});return Ke(s?.data??s)}catch(e){throw Ye(e)}}},st=i.z.object({issueId:i.z.string().min(1),expand:i.z.string().optional()}),it={name:"jira-transition-list",inputSchema:st,runTool:async(e,t)=>{try{const r=st.parse(t),n=e.issues;if(!n||"function"!=typeof n.getTransitions)throw Error("Jira transitions API is unavailable on the client");const s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand);const i=await n.getTransitions(s);return Ke(i?.data??i)}catch(e){throw Ye(e)}}},ot=i.z.object({issueId:i.z.string().min(1),fields:i.z.record(i.z.any()).optional(),update:i.z.record(i.z.array(i.z.object({set:i.z.any().optional(),add:i.z.any().optional(),remove:i.z.any().optional(),edit:i.z.any().optional()}))).optional(),properties:i.z.array(i.z.any()).optional(),notifyUsers:i.z.boolean().optional().default(!0),issueTemplateId:i.z.string().optional(),overrideScreenSecurity:i.z.boolean().optional().default(!1),overrideEditableFlag:i.z.boolean().optional().default(!1)}),at={name:"jira-issue-update",inputSchema:ot,runTool:async(e,t)=>{try{const r=ot.parse(t),n={issueIdOrKey:r.issueId};r.fields&&(n.fields=(e=>{const t={...e},r=t.description;var n;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=(n=r,{...n,content:Le(n.content??[])})),t})(r.fields)),r.update&&(n.update=r.update),r.properties&&(n.properties=r.properties),void 0!==r.notifyUsers&&(n.notifyUsers=r.notifyUsers),r.issueTemplateId&&(n.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(n.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(n.overrideEditableFlag=r.overrideEditableFlag);const s=await e.issues.editIssue(n);return Ke(s?.data??s)}catch(e){throw Ye(e)}}},ct=i.z.object({issueId:i.z.string().min(1),assignee:i.z.union([i.z.string(),i.z.object({accountId:i.z.string().min(1)}),i.z.object({accountType:i.z.string().min(1)})])}),lt={name:"jira-assign-issue",inputSchema:ct,runTool:async(e,t)=>{try{const r=ct.parse(t);let n;n="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const s=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:n});return Ke(s?.data??s)}catch(e){throw Ye(e)}}},pt=i.z.object({issueId:i.z.string().min(1)}),ut={name:"jira-unassign-issue",inputSchema:pt,runTool:async(e,t)=>{try{const r=pt.parse(t),n=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return Ke(n?.data??n)}catch(e){throw Ye(e)}}},dt=i.z.object({issueId:i.z.string().min(1),body:i.z.string().min(1),visibility:i.z.object({type:i.z.enum(["role","group"]),value:i.z.string().min(1)}).optional()}),mt={name:"jira-comment-add",inputSchema:dt,runTool:async(e,t)=>{try{const r=dt.parse(t),n=e.issueComments;if(!n||"function"!=typeof n.addComment)throw Error("Jira issueComments API is unavailable on the client");const s={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(s.visibility=r.visibility);const i=await n.addComment(s);return Ke(i?.data??i)}catch(e){throw Ye(e)}}},ht=i.z.object({issueId:i.z.string().min(1),start:i.z.number().optional().default(0),maxResults:i.z.number().optional().default(50),orderBy:i.z.string().optional(),expand:i.z.string().optional()}),ft={name:"jira-comment-list",inputSchema:ht,runTool:async(e,t)=>{try{const r=ht.parse(t),n=e.issueComments;if(!n||"function"!=typeof n.getComments)throw Error("Jira issueComments API is unavailable on the client");const s=await n.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return Ke(s?.data??s)}catch(e){throw Ye(e)}}},yt=i.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"]),gt=i.z.object({id:i.z.string().optional(),key:i.z.string().optional()}),bt=i.z.object({type:i.z.enum(["role","group"]),value:i.z.string().min(1)}),vt=i.z.object({body:i.z.string().optional(),visibility:bt.optional()}),wt=i.z.object({link:i.z.object({relationship:yt,inwardIssue:gt,outwardIssue:gt,comment:vt.optional()})});let It=[];function St(e){return(e||"").trim().toLowerCase()}async function jt(e,t){if(!t)throw Error("Link relationship is required");0===It.length&&(It=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(),n=r?.issueLinkTypes??r?.values??r;return Array.isArray(n)?n:[]})(e));const r=St(t),n=It.find(e=>[e.name,e.inward,e.outward].some(e=>St(e)===r));if(!n)throw Error(`No issue link type matching '${t}' found.`);return n}function kt(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 xt(e){if(!e)return;const t={};return e.body&&(t.body=Re(e.body)),e.visibility&&(t.visibility=e.visibility),Object.keys(t).length>0?t:void 0}const zt=wt,Tt={name:"jira-link-create",inputSchema:zt,runTool:async(e,t)=>{try{const r=zt.parse(t).link,n={inwardIssue:kt(r.inwardIssue),outwardIssue:kt(r.outwardIssue)},s=xt(r.comment);s&&(n.comment=s);const i=e.issueLinks;if(!i||"function"!=typeof i.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const o=await jt(e,r.relationship);n.type={id:o.id};const a=await i.linkIssues(n);return Ke(a?.data??a)}catch(e){throw Ye(e)}}},_t=i.z.object({issueId:i.z.string().min(1),file:i.z.string().min(1),mimeType:i.z.string().optional(),comment:i.z.string().optional()}),Et={name:"jira-attach",inputSchema:_t,runTool:async(e,r)=>{try{const n=_t.parse(r),s=c.resolve(n.file),i=await t.promises.readFile(s),o=c.basename(s),a=new FormData;a.append("file",new Blob([i],{type:n.mimeType??"application/octet-stream"}),o);const l=e?.config??null,p=l?.host,u=l?.authentication?.basic??l?.authentication??l?.auth??null,d=u?.email,m=u?.apiToken??u?.apiKey;if(!p||!d||!m)throw Error("Jira client authentication configuration is unavailable for attachments");const h=await fetch(`${p}/rest/api/3/issue/${n.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${d}:${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(n.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:n.issueId,comment:Re(n.comment)})}return Ke(f)}catch(e){if(e&&e.code&&"string"==typeof e.code&&["ENOENT","EACCES"].includes(e.code))throw Error("Attachment file error: "+e.message);throw Ye(e)}}},At=i.z.object({issueId:i.z.string().min(1)}),Ot={name:"jira-attachment-list",inputSchema:At,runTool:async(e,t)=>{try{const r=At.parse(t),n=e.issues;if(!n||"function"!=typeof n.getIssue)throw Error("Jira issues API is unavailable on the client");const s=await n.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),i=s?.data??s;return Ke({attachments:i?.fields?.attachment??[]})}catch(e){throw Ye(e)}}},Ct=i.z.object({issueId:i.z.string().min(1),attachmentId:i.z.string().min(1)}),Ht={name:"jira-attachment-delete",inputSchema:Ct,runTool:async(e,t)=>{try{const r=Ct.parse(t),n=e.issueAttachments;if(!n||"function"!=typeof n.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await n.removeAttachment({id:r.attachmentId}),Ke({success:!0,message:`Attachment ${t.attachmentId} deleted successfully`})}catch(e){throw Ye(e)}}},Jt=i.z.object({issueId:i.z.string().min(1),timeSpent:i.z.string().min(1),comment:i.z.string().optional(),author:i.z.object({accountId:i.z.string().min(1)}).optional(),startingOn:i.z.string().optional(),artifact:i.z.string().optional()}),Nt={name:"jira-worklog-add",inputSchema:Jt,runTool:async(e,t)=>{try{const r=Jt.parse(t),n={timeSpent:r.timeSpent};r.comment&&(n.comment=r.comment),r.author&&(n.author=r.author),r.startingOn&&(n.started=r.startingOn),r.artifact&&(n.artifact=r.artifact);const s=e.issueWorklogs;if(!s||"function"!=typeof s.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const i=await s.addWorklog({issueIdOrKey:r.issueId,...n});return Ke(i?.data??i)}catch(e){throw Ye(e)}}};class Pt{constructor(){this.clientId=de.orThrow().xray.apiUser,this.clientSecret=de.orThrow().xray.apiSecret,this.baseUrl=de.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=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify({query:e,variables:t})}),n=await r.json();if(n.errors)throw Error(JSON.stringify(n.errors,null,2));return n.data}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||[],n=[],s=[],i=[];for(let e=0;e<t.length;e++){const i=t[e],o=r[e];o?o.action===i.action&&o.data===i.data&&o.result===i.result||n.push({stepId:o.id,step:i}):s.push(i)}if(r.length>t.length)for(let e=t.length;e<r.length;e++)i.push(r[e].id);await this.addSteps(e,s),await this.updateSteps(n),await this.deleteSteps(i)}}let qt=null;const $t=new Map;function Rt(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 n=e.data??e.fields?.Data??e.fields?.data??void 0,s=e.result??e.fields?.Result??e.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof n?n:void 0,result:"string"==typeof s?s:void 0}}async function Dt(e,t){if(!t)throw Error("Issue reference is required when interacting with Xray steps");if($t.has(t))return $t.get(t);if(/^[0-9]+$/.test(t))return $t.set(t,t),t;const r=e?.issues??e?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const n=await r.getIssue({issueIdOrKey:t,fields:["id"]}),s=n?.id;if(!s)throw Error("Unable to resolve Jira issue ID for "+t);return $t.set(t,s),s}async function Lt(e){if(e?.test?.step)return e.test.step;const t=await(async()=>{if(qt)return qt;const e=de.orThrow().xray.apiUser?.trim(),t=de.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=ge(),n=new Pt;return qt={test:{step:{async createStep(e,t){const s=await Dt(r,e),i=await n.addStep(s,Rt(t));return{step:i,id:i?.id}},async updateStep(e,t,s){await Dt(r,e);const i=Rt(s),o=await n.updateStep(t.toString(),i);return{step:o,id:o?.id}},deleteStep:async(e,t)=>(await Dt(r,e),{success:!0===await n.deleteStep(t.toString())}),async getSteps(e){const t=await Dt(r,e),s=await n.getTest(t);return{steps:s?.steps??[]}}}}},qt})();if(!t?.test?.step)throw Error("Xray step API is unavailable on the client");return t.test.step}const Mt=i.z.object({issueId:i.z.string().min(1),action:i.z.string().min(1),data:i.z.string().optional(),result:i.z.string().optional()}),Ut={name:"jira-xray-step-add",inputSchema:Mt,runTool:async(e,t)=>{try{const r=Mt.parse(t),n=await Lt(e),s={action:r.action,data:r.data,result:r.result};return Ke(await n.createStep(r.issueId,s))}catch(e){throw Ye(e)}}},Bt=i.z.object({issueId:i.z.string().min(1),stepId:i.z.union([i.z.string(),i.z.number()]),action:i.z.string().min(1),data:i.z.string().optional(),result:i.z.string().optional()}),Kt={name:"jira-xray-step-update",inputSchema:Bt,runTool:async(e,t)=>{try{const r=Bt.parse(t),n=await Lt(e),s=r.stepId+"",i={action:r.action,data:r.data,result:r.result};return Ke(await n.updateStep(r.issueId,s,i))}catch(e){throw Ye(e)}}},Ft=i.z.object({issueId:i.z.string().min(1),stepId:i.z.union([i.z.string(),i.z.number()])}),Wt={name:"jira-xray-step-delete",inputSchema:Ft,runTool:async(e,t)=>{try{const r=Ft.parse(t),n=await Lt(e);return await n.deleteStep(r.issueId,r.stepId.toString()),Ke({success:!0})}catch(e){throw Ye(e)}}},Yt=i.z.object({issueId:i.z.string().min(1)}),Xt={name:"jira-xray-step-list",inputSchema:Yt,runTool:async(e,t)=>{try{const r=Yt.parse(t),n=await Lt(e);return Ke(await n.getSteps(r.issueId))}catch(e){throw Ye(e)}}},Gt=i.z.object({linkId:i.z.string().min(1)}),Vt={name:"jira-link-delete",inputSchema:Gt,runTool:async(e,t)=>{try{const r=Gt.parse(t),n=e.issueLinks;if(!n||"function"!=typeof n.deleteIssueLink)throw Error("Jira issueLinks API is unavailable on the client");return await n.deleteIssueLink({linkId:r.linkId}),Ke({success:!0,message:`Issue link ${r.linkId} deleted successfully`})}catch(e){throw Ye(e)}}},Zt=i.z.object({linkId:i.z.string().min(1),relationship:yt,comment:vt.optional()}),Qt={name:"jira-link-update",inputSchema:Zt,runTool:async(e,t)=>{try{const r=Zt.parse(t),n=e.issueLinks;if(!n||"function"!=typeof n.getIssueLink||"function"!=typeof n.deleteIssueLink||"function"!=typeof n.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const s=await n.getIssueLink({linkId:r.linkId}),i=s?.data??s;if(!i)throw Error(`Issue link ${r.linkId} not found`);const o=i.inwardIssue,a=i.outwardIssue;if(!o||!a)throw Error("Issue link payload is missing linked issues");const c=await jt(e,r.relationship);await n.deleteIssueLink({linkId:r.linkId});const l={inwardIssue:kt(o),outwardIssue:kt(a),type:{id:c.id}},p=xt(r.comment);return p&&(l.comment=p),await n.linkIssues(l),Ke({success:!0,message:`Issue link ${r.linkId} updated to ${r.relationship}`})}catch(e){throw Ye(e)}}},er={[Fe.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[tt.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Qe.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}},[at.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}},[Ge.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[nt.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[it.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[lt.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ut.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[mt.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}},[ft.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Tt.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Qt.name]:{title:"Jira Link Update",description:"Change the relationship type for an existing issue link",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Vt.name]:{title:"Jira Link Delete",description:"Delete an issue link from Jira",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Et.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ot.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ht.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Nt.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ut.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Kt.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Wt.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Xt.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 tr(e){const t=r.Logging.for(tr);let n,s=null;try{n=ge()}catch(e){if(!(e instanceof ye))return void t.warn("Skipping Jira tool registration; unable to create Jira client",{error:e});s=e,t.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:e})}const i=[Fe,tt,Qe,at,Ge,nt,it,lt,ut,mt,ft,Tt,Qt,Vt,Et,Ot,Ht,Nt,Ut,Kt,Wt,Xt];for(const r of i){const i=er[r.name];if(i)try{await e.registerTool(r.name,{title:i.title,description:i.description,inputSchema:r.inputSchema,annotations:i.annotations},async e=>{if(!n)throw s??Error("Jira client unavailable because credentials could not be loaded.");return r.runTool(n,e)}),t.info("Registered Jira tool "+r.name)}catch(e){t.error("Failed to register Jira tool "+r.name,{error:e})}}}async function rr(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=se.map(e=>e.getName()).sort();return{content:[{type:"text",text:["Name: "+de.name,"Title: "+de.title,"Version: "+de.version,"Prompts: "+(e.join(", ")||"<none>")].join("\n")}]}})})(e);const t=r.Logging.for(rr);try{await tr(e)}catch(e){t.error("Failed to register Jira tools",e)}}class nr extends H{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 nr}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{const t="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new v.ResourceTemplate(new b.UriTemplate(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),n=async(e,t)=>{const r=this.logFor(t);r.verbose(`Requesting resource ${this.name} from ${e.toString()}`);const n=await Promise.resolve(this.cb(e,t));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(n._meta)),n};return e.resource(this.name,t,r,n)}catch(e){throw r.Logging.for(this).error("Error registering resource "+this.name,e),e}}}n.__decorate([s.required(),n.__metadata("design:type",String)],nr.prototype,"uriOrTemplate",void 0),n.__decorate([s.required(),n.__metadata("design:type",Function)],nr.prototype,"cb",void 0),n.__decorate([s.required(),n.__metadata("design:type",Object)],nr.prototype,"config",void 0);const sr=W()??x.join(__dirname,"..","assets"),ir=x.join(sr,"templates"),or=x.join(sr,"prompts"),ar=new WeakMap;class cr extends r.LoggedClass{get client(){const e=ar.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 se)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 rr(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(ir).filter(e=>e.endsWith(".md"));for(const n of r){const r=x.basename(n,".md"),s=x.join(ir,n),i=nr.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+s).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{i.build(e),t.info("Registered template: "+r)}catch(e){t.error(`Failed to register template ${r}:`,e)}}t.info("Registering agent prompts...");const n=k.readdirSync(or).filter(e=>e.endsWith(".md"));for(const r of n){const n=x.basename(r,".md"),s=x.join(or,r),o=k.readFileSync(s,"utf8"),a=X.builder.setName(n).setTitle("Prompt: "+n).setDescription("Dynamic prompt for "+n).setArgsSchema(i.z.object({})).setCb(async e=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(e),t.info("Registered prompt: "+n)}catch(e){t.error(`Failed to register prompt ${n}:`,e)}}})(this.client,e)}catch(e){}}async boot(e="stdio"){"stdio"===e&&r.Logging.setFactory(T),r.Logging.for(this.constructor.name);const t=((Array.isArray(de.icons)?de.icons:[de.icons])||[]).map(e=>{const t="string"==typeof e?.src?e.src:(e?.src??"")+"",r="string"==typeof e?.mimeType?e.mimeType:(e?.mimeType??"")+"";let n=[];return Array.isArray(e?.sizes)?n=e.sizes.map(e=>e+""):"string"==typeof e?.sizes&&(n=(e.sizes+"").split(",").map(e=>e.trim())),{src:t,mimeType:r,sizes:n}}),n={name:de.name,title:de.title,websiteUrl:de.websiteUrl,version:de.version,icons:t},s=new v.McpServer(n,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((e,t)=>{ar.set(e,t)})(this,s),s.onerror=e=>{this.log.error("MCP instance onerror",e)},e){case"stdio":e=new I.StdioServerTransport;break;case"http":e=new S.StreamableHTTPServerTransport({sessionIdGenerator:()=>w.v4(),onsessioninitialized:e=>{},onsessionclosed:e=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(i=e)||"object"!=typeof i||"function"!=typeof i.send&&"function"!=typeof i.close&&"function"!=typeof i.on)throw new l.InternalError("Invalid transport type: "+e)}var i;try{await this.load()}catch(e){throw e}await this.client.connect(e)}}const lr=(new e.Command).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async e=>{const r=K("package.json"),n=JSON.parse(t.readFileSync(r,"utf-8")),s=n.version,{transport:i}=e,o=(new z).for("mcp-server");if("stdio"!==i)throw Error("Unsupported transport mode: "+i);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(e)} for ${n.name} version ${s}`),(new cr).boot(i)});(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 n=K("package.json"),s=JSON.parse(t.readFileSync(n,"utf-8")),i=s.version;r.Logging.for("md-to-ast").debug(`running with options: ${JSON.stringify(e)} for ${s.name} version ${i}`);const o=Re(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 pr=(new e.Command).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");pr.addCommand(lr),pr.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("unified"),require("remark-directive"),require("remark-gfm"),require("remark-parse"),require("node:util"),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","unified","remark-directive","remark-gfm","remark-parse","node:util","@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.unified,e.remarkDirective,e.remarkGfm,e.remarkParse,e.node_util,e.uriTemplate_js,e.mcp_js,e.uuid,e.stdio_js,e.streamableHttp_js);
3
3
  //# sourceMappingURL=mcp-server.cjs.map