@decaf-ts/mcp-server 1.7.1 → 1.7.3

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 (52) 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 +0 -0
  9. package/dist/assets/prompts/documentation/function.enc +0 -0
  10. package/dist/assets/prompts/documentation/interface.enc +0 -0
  11. package/dist/assets/prompts/documentation/iterate.enc +0 -0
  12. package/dist/assets/prompts/documentation/module.enc +0 -0
  13. package/dist/assets/prompts/documentation/prefix.enc +0 -0
  14. package/dist/assets/prompts/documentation/repo.enc +0 -0
  15. package/dist/assets/prompts/documentation/suffix.enc +0 -0
  16. package/dist/assets/prompts/git_commands.enc +0 -0
  17. package/dist/assets/prompts/jira/operational_prompts.enc +0 -0
  18. package/dist/assets/prompts/jira/system_prompt.enc +0 -0
  19. package/dist/assets/prompts/mode_commands.enc +0 -0
  20. package/dist/assets/prompts/plan_commands.enc +0 -0
  21. package/dist/assets/prompts/repository/readme.enc +0 -0
  22. package/dist/assets/prompts/repository/release_notes.enc +0 -0
  23. package/dist/assets/prompts/repository/setup.enc +0 -0
  24. package/dist/assets/prompts/specification_commands.enc +0 -0
  25. package/dist/assets/prompts/startup_command.enc +0 -0
  26. package/dist/assets/prompts/task_commands.enc +0 -0
  27. package/dist/assets/prompts/tests/coverage.enc +0 -0
  28. package/dist/assets/resources/decoration/builder.enc +0 -0
  29. package/dist/assets/resources/decoration/metadata.enc +0 -0
  30. package/dist/assets/resources/decoration/validation.enc +0 -0
  31. package/dist/assets/resources/golden/model-builder.enc +0 -0
  32. package/dist/assets/resources/golden/validation-errors.enc +0 -0
  33. package/dist/assets/resources/golden/xray-step-template.enc +0 -0
  34. package/dist/assets/resources/repo-metadata.enc +0 -0
  35. package/dist/assets/templates/AGENTS.enc +0 -0
  36. package/dist/assets/templates/agents_template.enc +0 -0
  37. package/dist/assets/templates/constitution_template.enc +0 -0
  38. package/dist/assets/templates/decaf/context/logCtx.enc +0 -0
  39. package/dist/assets/templates/decaf/services/client_based_service.enc +0 -0
  40. package/dist/assets/templates/decaf/services/model_service.enc +0 -0
  41. package/dist/assets/templates/decaf/services/service.enc +0 -0
  42. package/dist/assets/templates/decaf_guidelines.enc +0 -0
  43. package/dist/assets/templates/instructions_template.enc +0 -0
  44. package/dist/assets/templates/jira_templates.enc +0 -0
  45. package/dist/assets/templates/plan_template.enc +0 -0
  46. package/dist/assets/templates/specification_template.enc +0 -0
  47. package/dist/assets/templates/task_template.enc +0 -0
  48. package/dist/mcp-server.cjs +1 -1
  49. package/dist/mcp-server.cjs.map +1 -1
  50. package/dist/mcp-server.js +1 -1
  51. package/dist/mcp-server.js.map +1 -1
  52. package/package.json +3 -2
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- var e,t;e=this,t=function(e,t,r,i,n,s,a,o,c,d,l,u,p,m,h,g,y,f,b,w,v,z,j,k){"use strict";function I(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var S=I(t),x=I(c);class T extends r.MiniLogger{constructor(e,t,r){super(e,t,r)}log(e,t,i,n){const s=this.config("level");r.NumericLogLevels[s],r.NumericLogLevels[e]}}const A=(e,t,...r)=>{const i=(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(i,t)};var E,_,O,J,D;(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"})(_||(_={})),(e=>{e[e.FREE=0]="FREE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(O||(O={}));class C extends n.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:i}=e||{};let n="string"==typeof t&&t.length>0?this.log.for(t):this.log;return i&&i.clientId&&(n=n.for(i.clientId)),r&&(n=n.for(r.toString())),n}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}}i.__decorate([n.required(),i.__metadata("design:type",String)],C.prototype,"description",void 0),i.__decorate([n.required(),i.__metadata("design:type",String)],C.prototype,"name",void 0),i.__decorate([n.required(),i.__metadata("design:type",String)],C.prototype,"title",void 0);class N extends C{constructor(e){super(e),this.reasoning=E.NONE,this.effort=_.NONE,this.cost=O.FREE}setReasoning(e){return this.reasoning=e,this}setEffort(e){return this.effort=e,this}setCost(e){return this.cost=e,this}}function H(e){if(!e)return;let t=e,r=t&&t._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)t=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)t=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)t=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)t=r.innerType;else{if(!r.schema)return;t=r.schema}r=t&&t._def}return r&&"ZodObject"===r.typeName?r:void 0}function q(e,t="schema"){if(H(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,i]of Object.entries(r))e[t]=R(i)?i:s.z.any();return s.z.object(e)}}throw Error(`Registration error: provided a non-canonical ${t}. Export a ZodObject (z.object(...)).`)}function P(e){if(!e)return;if(e&&"object"==typeof e&&!e._def)return e.def&&"object"==typeof e.def&&e.def.shape?e.def.shape:e;const t=H(e);return t?"function"==typeof t.shape?t.shape():t.shape||void 0:void 0}function R(e){return!(!e||"object"!=typeof e||!e._def)}i.__decorate([n.required(),i.__metadata("design:type",Number)],N.prototype,"reasoning",void 0),i.__decorate([n.required(),i.__metadata("design:type",Number)],N.prototype,"effort",void 0),i.__decorate([n.required(),i.__metadata("design:type",Number)],N.prototype,"cost",void 0),(e=>{e.ASSETS="assets"})(J||(J={})),(e=>{e.PROMPT="prompts",e.DOCUMENTATION="documentation",e.CODE="code"})(D||(D={}));const L=Buffer.from("DCAF1","ascii");function M(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 $=process.argv?.[1]?M(c.dirname(c.resolve(process.argv[1]))):void 0,F=(()=>{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=p.fileURLToPath(r)}catch{continue}if(!r.includes("node:internal"))return c.dirname(r)}})(),U=F?M(F):void 0,W=$??U??process.cwd();function K(...e){return c.join(W,...e)}function B(e){let t=e;for(;;){const e=x.join(t,"lib","assets");if(S.existsSync(e))return e;const r=x.join(t,"src","assets");if(S.existsSync(r))return r;const i=x.join(t,"assets");if(S.existsSync(i))return i;const n=x.dirname(t);if(n===t)break;t=n}}function X(){const e=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(e&&S.existsSync(e))return e;const t=B(__dirname);if(t)return t;const r=process.argv?.[1];if(r){const e=B(x.dirname(r));if(e)return e}const i=[W,process.env.INIT_CWD].filter(Boolean);for(const e of i){const t=B(e);if(t)return t}return K("assets")}let Y=class extends r.LoggedClass{constructor(e){super(),this.basePath=e||X()}listAssets(...e){const t=x.join(this.basePath,...e);return S.readdirSync(t)}listPrompts(){return this.listAssets(D.PROMPT)}getAsset(e,t="md",...r){const i=x.join(this.basePath,...r),n=(e,t=!1)=>{try{return t?(e=>{if(e.length<L.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!e.subarray(0,L.length).equals(L))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=L.length;const i=e.subarray(r,r+16);r+=16;const n=e.subarray(r,r+12);r+=12;const s=e.subarray(r,r+16);r+=16;const a=e.subarray(r),o=((e,t)=>l.scryptSync(e,t,32))(t,i),c=l.createDecipheriv("aes-256-gcm",o,n);c.setAuthTag(s);const d=Buffer.concat([c.update(a),c.final()]);return u.gunzipSync(d)})(S.readFileSync(e)).toString("utf-8"):S.readFileSync(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}},s=n(x.join(i,`${e}.${t}`),"enc"===t);if(null!==s)return s;const a=n(x.join(i,e+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+x.join(i,`${e}.${t}`))}getAllAssets(e,...t){return this.listAssets(e,...t).reduce((r,i)=>{const n=x.extname(i),s=x.basename(i,n),a=n.replace(/^\./,"")||void 0;return r[s]=this.getAsset(s,a??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 _.MEDIUM;case"low":return O.LOW;case"free":return O.FREE;default:throw new d.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 i=this.getAsset(r.toSnakeCase(e),"json",D.PROMPT,...t);let n;try{n=JSON.parse(i)}catch(r){throw new d.SerializationError(`Failed to parse prompt ${e} in categories ${t}: ${r}`)}return this.toPromptDef(n)}getAllPrompts(...e){const t=this.getAllAssets(D.PROMPT,...e);return Object.entries(t).reduce((t,[r,i])=>{try{t[r]=JSON.parse(i)}catch(t){throw new d.SerializationError(`Failed to parse prompt ${r} in categories ${e}: ${t}`)}return t},t)}};Y=i.__decorate([a.injectable(),i.__metadata("design:paramtypes",[String])],Y);class G extends N{constructor(e){super(e)}setCb(e){return this.cb=e,this}setArgsSchema(e){return this.argsSchema=e,this}static get builder(){return new G}static patchPrompt(e,t,i,n){const s=(t=Array.isArray(t)?t:Object.keys(t)).filter(e=>!Object.prototype.hasOwnProperty.call(i,e));if(s.length)throw new d.ValidationError("Missing replacements for placeholders: "+s.join(", "));n&&(n.verbose("Patching prompt with placeholders: "+JSON.stringify(t)),n.debug("Values: "+JSON.stringify(i)));const a=t.reduce((e,t)=>(e[t]=i[t],e),{});return r.sf(e,a)}patchPrompt(e,t,r,i){return G.patchPrompt(e,t,r,i||this.log.for(this.patchPrompt))}build(e,t){const r=this.log.for(this.build),i=this.hasErrors();if(i)throw new d.ValidationError(i.toString());try{this.argsSchema&&q(this.argsSchema,"argsSchema");const r=P(this.argsSchema);return e.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(e,r)=>{const i=this.logFor(r);e=Object.assign({},t,e||{}),i.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 n=await Promise.resolve(this.cb(e,r));return i.verbose(`Prompt ${this.name} executed successfully.`),i.debug("Prompt execution meta: "+JSON.stringify(n._meta)),n})}catch(e){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),e),e}}}i.__decorate([a.inject(Y),i.__metadata("design:type",Y)],G.prototype,"assets",void 0),i.__decorate([n.required(),i.__metadata("design:type",Object)],G.prototype,"cb",void 0),i.__decorate([n.required(),i.__metadata("design:type",s.ZodObject)],G.prototype,"argsSchema",void 0),i.__decorate([o.prop(),i.__metadata("design:type",Object)],G.prototype,"placeholders",void 0);class V extends G{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);n.Model.fromObject(this,t);const r=new Set((o.Metadata.properties(V)||[]).filter(e=>!["assets","promptCategory","prefixes","suffixes"].includes(e)));["cb","argsSchema"].forEach(e=>r.add(e));const i=this.hasErrors(...Array.from(r));if(i)throw new d.ValidationError(i.toString());const a=(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,...a.map(e=>e.placeholders||[]),...c.map(e=>e.placeholders||[])].flat())].reduce((e,t)=>(e[t]=s.z.string().describe("The description for "+t),e),{});return this.setArgsSchema(s.z.object(l)),this.setCb((e,t)=>{const r=this.logFor(t).for(V).for(this.promptCategory).for(this.name);function i(e=[]){return Array.isArray(e)?e:Object.keys(e)}const n=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),s=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),a=this.assets.getPrompt(this.name,this.promptCategory),o=[...new Set([...n.map(e=>i(e.placeholders)).flat(),...s.map(e=>i(e.placeholders)).flat(),...i(a.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...n.map(e=>e.prompt),a.prompt,...s.map(e=>e.prompt)].join("\n\n"),o,e,r)}}],_meta:{}}}),super.build(e)}setReasoning(e){throw new d.InternalError("Named prompt builders don't require callback")}setEffort(e){throw new d.InternalError("Named prompt builders don't require callback")}setCost(e){throw new d.InternalError("Named prompt builders don't require callback")}setDescription(e){throw new d.InternalError("Named prompt builders don't require callback")}setTitle(e){throw new d.InternalError("Named prompt builders don't require callback")}static get builder(){return new V}}i.__decorate([n.required(),i.__metadata("design:type",String)],V.prototype,"promptCategory",void 0),i.__decorate([n.list(String),n.minlength(1),i.__metadata("design:type",Array)],V.prototype,"prefixes",void 0),i.__decorate([n.minlength(1),n.list(String),i.__metadata("design:type",Array)],V.prototype,"suffixes",void 0);const Z=G.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc helper prompt").setDescription("Interactive JSDoc helper that mirrors common doc-health prompts; provide a gist to steer the assistant.").setArgsSchema(s.z.object({gist:s.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 i=V.builder.setCategory(ee.DOCS).setName(e);return["prefix",...t].forEach(e=>i.addPrefix(e)),["suffix",...r].forEach(e=>i.addSuffix(e)),i}(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"])],ie=s.z.object({className:s.z.string().describe("the class name to turn into a builder")}),ne=G.builder.setName("ts-code-dp-builder").setTitle("Typescript builder design pattern prompt").setDescription("Generate a builder pattern implementation for a class so the assistant knows to emit chained setters plus Model validation.").setArgsSchema(ie).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:{}})),se=e=>{const t=Object.entries(e||{}).filter(([,e])=>null!=e);return t.length?t.map(([e,t])=>`- ${e}: ${JSON.stringify(t)}`).join("\n"):"- no input provided; ask a clarifying question if necessary."},ae=(e,t)=>{const r=e.resources.length?e.resources.join(", "):"none";return[e.description,"","Scenario:\n"+e.scenario,"","Resources: "+r,"\nProvided inputs:",se(t),"\nCall specification:",e.callTemplate,"\nGuidance:",(i=e.guidance,i.map((e,t)=>`${t+1}. ${e}`).join("\n"))].join("\n");var i},oe=[Q,...re,ne,...[{name:"guide-file-summarizer-tool",title:"MCP guide: file summarizer",description:"Explain how to obtain a concise preview of a file before discussing its contents or instructing other tools.",toolName:"file-summarizer",scenario:"Before referencing or editing a file, invoke this tool to gather a short summary of the opening lines.",resources:["resource://repo.metadata"],guidance:["Default to README.md when the user does not specify a path and call out that the summary is truncated to the first ten meaningful lines.","Trace any hiccups (file not found / permission issues) through the tool\u2019s structured result so the agent can resolve the path before editing."],argsSchema:s.z.object({filePath:s.z.string().optional()}),callTemplate:'{\n "name": "file-summarizer",\n "arguments": {\n "filePath": "<optional-path>"\n }\n}'},{name:"guide-server-info-tool",title:"MCP guide: server info",description:"Show how to use the server diagnostics tool to list registered prompts, versions, and capabilities without side effects.",toolName:"decaf-server-info",scenario:"When you need to confirm what prompts and metadata the MCP server currently exposes.",resources:["resource://repo.metadata"],guidance:["Treat the server info response as read-only configuration data that helps you decide which prompts to invoke next.","Do not rely on stale memory; re-run this tool if the environment might have changed."],argsSchema:s.z.object({}),callTemplate:'{\n "name": "decaf-server-info",\n "arguments": {}\n}'},{name:"jira-guide-issue-create-tool",title:"Jira guide: issue create",description:"Turn user requests into the structured fields that `jira-issue-create` expects, then call the tool.",toolName:"jira-issue-create",scenario:"Whenever a new ticket, task, or story must be created from requirements or spec notes.",resources:["resource://repo.metadata","resource://decoration.schematic.metadata"],guidance:["Confirm the project key from metadata when it is not in the inputs and prefer the canonical repo name.","Gather summary, description, issueType, and any extra `fields` before calling the tool; do not call within the prompt itself.","Present an action preview that lists the fields and mentions attachments or links that might also be created."],argsSchema:s.z.object({project:s.z.string().optional(),issueType:s.z.string().optional(),summary:s.z.string().optional(),description:s.z.string().optional(),assignee:s.z.string().optional(),fields:s.z.record(s.z.any()).optional()}).partial(),callTemplate:'{\n "name": "jira-issue-create",\n "arguments": {\n "project": { "key": "<project>" },\n "issuetype": { "name": "<issueType>" },\n "summary": "<summary>",\n "description": "<description>",\n "assignee": "<assignee>",\n "fields": { ... }\n }\n}'},{name:"jira-guide-issue-read-tool",title:"Jira guide: issue read",description:"Explain when and how to fetch live issue data with `jira-issue-read` before referencing it.",toolName:"jira-issue-read",scenario:"Before reporting the state of a Jira ticket or quoting field values.",resources:["resource://repo.metadata"],guidance:["Always prefer the issue ID or key provided in the argument; ask clarifying questions if missing.","Mention which fields you need (description, status, comments) so the tool can optimize the call, then rely on the fresh payload instead of memory."],argsSchema:s.z.object({issueId:s.z.string().optional(),issueKey:s.z.string().optional(),fields:s.z.array(s.z.string()).optional()}).partial(),callTemplate:'{\n "name": "jira-issue-read",\n "arguments": {\n "issueId": "<id>",\n "fields": ["summary", "status", "description"]\n }\n}'},{name:"jira-guide-issue-list-tool",title:"Jira guide: issue list",description:"Map exploratory or filtering requests into safe calls to `jira-issue-list`.",toolName:"jira-issue-list",scenario:"When the user wants to discover tickets that match a summary, project, or JQL filter.",resources:["resource://repo.metadata"],guidance:["Translate the requirements into explicit filters or JQL before invoking the tool.","Respect pagination hints and summarize how many tickets the tool should return in the action preview."],argsSchema:s.z.object({jql:s.z.string().optional(),filters:s.z.record(s.z.any()).optional(),limit:s.z.number().optional(),order:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-list",\n "arguments": {\n "jql": "<JQL>",\n "filters": { ... },\n "startAt": 0,\n "maxResults": <limit>\n }\n}'},{name:"jira-guide-issue-update-tool",title:"Jira guide: issue update",description:"Document how to gather updates before calling `jira-issue-update` so the user\u2019s request is satisfied.",toolName:"jira-issue-update",scenario:"When a ticket needs field changes, transitions, or property toggles.",resources:["resource://repo.metadata","resource://decoration.schematic.builder"],guidance:["Call `jira-issue-read` first if you need the latest state before updating.","Describe the delta (fields being changed) in the action preview and encode them under the `fields` argument.","Include a comment or transition info if the change ought to be annotated."],argsSchema:s.z.object({issueId:s.z.string().optional(),fields:s.z.record(s.z.any()).optional(),comment:s.z.string().optional(),transition:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-update",\n "arguments": {\n "issueId": "<id>",\n "fields": { ... },\n "comment": "<comment>",\n "transition": "<transition>"\n }\n}'},{name:"jira-guide-issue-delete-tool",title:"Jira guide: issue delete",description:"Warn when to permanently delete an issue via `jira-issue-delete` and how to confirm it.",toolName:"jira-issue-delete",scenario:"When a ticket must be removed or cleaned up after duplication.",resources:["resource://repo.metadata"],guidance:["Double-check permissions and confirm the issue ID; do not delete unless the user explicitly accepts data loss.","Call out whether subtasks should be removed via `deleteSubtasks`."],argsSchema:s.z.object({issueId:s.z.string().optional(),deleteSubtasks:s.z.boolean().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-delete",\n "arguments": {\n "issueId": "<id>",\n "deleteSubtasks": <true|false>\n }\n}'},{name:"jira-guide-issue-transition-tool",title:"Jira guide: issue transition",description:"Define the process for transitioning a Jira issue and invoking `jira-issue-transition`.",toolName:"jira-issue-transition",scenario:"When a ticket needs a workflow change such as To Do \u2192 In Progress \u2192 Done.",resources:["resource://repo.metadata","resource://decoration.schematic.validation"],guidance:["Check available transitions with `jira-transition-list` before deciding which one to run.","Document the business reason in the comment argument to aid reviewers."],argsSchema:s.z.object({issueId:s.z.string().optional(),transition:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-transition",\n "arguments": {\n "issueId": "<id>",\n "transition": "<transition>",\n "comment": "<comment>"\n }\n}'},{name:"jira-guide-transition-list-tool",title:"Jira guide: transition list",description:"Explain how to use `jira-transition-list` to inspect available workflow steps before triggering one.",toolName:"jira-transition-list",scenario:"When you need to know which transitions are possible for a ticket before calling the transition tool.",resources:["resource://repo.metadata"],guidance:["Always capture the transition names and IDs to reference in the action preview.","Only call `jira-issue-transition` after confirming the desired transition exists."],argsSchema:s.z.object({issueId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-transition-list",\n "arguments": {\n "issueId": "<id>"\n }\n}'},{name:"jira-guide-assign-issue-tool",title:"Jira guide: assign issue",description:"Describe how to safely assign or reassign ownership via `jira-assign-issue`.",toolName:"jira-assign-issue",scenario:"When a ticket should be assigned or moved between assignees.",resources:["resource://repo.metadata"],guidance:["Translate user mentions or names into account IDs and include them in the call.","Mention why the reassignment is happening in your action preview to keep the workflow transparent."],argsSchema:s.z.object({issueId:s.z.string().optional(),assignee:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-assign-issue",\n "arguments": {\n "issueId": "<id>",\n "assignee": { "accountId": "<id>" }\n }\n}'},{name:"jira-guide-unassign-issue-tool",title:"Jira guide: unassign issue",description:"Explain the steps for removing an assignee using `jira-unassign-issue`.",toolName:"jira-unassign-issue",scenario:"When the user wants to unassign an owner to make the ticket available.",resources:["resource://repo.metadata"],guidance:["Document whether the ticket should remain unassigned or be moved immediately to someone else.","Confirm there is no auto-assignment policy that will conflict with the unassign action."],argsSchema:s.z.object({issueId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-unassign-issue",\n "arguments": {\n "issueId": "<id>"\n }\n}'},{name:"jira-guide-comment-add-tool",title:"Jira guide: comment add",description:"Clarify how to craft a structured comment (tiered sections, mentions) and call `jira-comment-add`.",toolName:"jira-comment-add",scenario:"When you need to capture findings, reviews, or blockers on a ticket.",resources:["resource://repo.metadata"],guidance:["Use panels, mentions, and sections when describing blockers or decisions.","Reference the relevant attachments or links and mention next steps."],argsSchema:s.z.object({issueId:s.z.string().optional(),comment:s.z.string().optional(),visibility:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-comment-add",\n "arguments": {\n "issueId": "<id>",\n "comment": "<markdown comment>",\n "visibility": "<role>"\n }\n}'},{name:"jira-guide-comment-list-tool",title:"Jira guide: comment list",description:"Indicate when to fetch the comment trail via `jira-comment-list`.",toolName:"jira-comment-list",scenario:"When decisions or conversations need to be reviewed before adding new comments.",resources:["resource://repo.metadata"],guidance:["Specify pagination or filters so you only pull the required batch of comments.","Summarize the key threads in the action preview before calling the tool again to append."],argsSchema:s.z.object({issueId:s.z.string().optional(),page:s.z.number().optional()}).partial(),callTemplate:'{\n "name": "jira-comment-list",\n "arguments": {\n "issueId": "<id>",\n "page": 0,\n "maxResults": 25\n }\n}'},{name:"jira-guide-link-create-tool",title:"Jira guide: link create",description:"Describe how to link issues (e.g., tests to specs) and call `jira-link-create`.",toolName:"jira-link-create",scenario:"When a ticket must be related to another via tested-by, duplicates, or dependees.",resources:["resource://repo.metadata"],guidance:["Include a short note on why the link exists so reviewers can trace the intent.","Verify that both issue keys exist before calling the tool; fetch via `jira-issue-read` if necessary."],argsSchema:s.z.object({inwardIssue:s.z.string().optional(),outwardIssue:s.z.string().optional(),linkType:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-link-create",\n "arguments": {\n "inwardIssue": "<inward>",\n "outwardIssue": "<outward>",\n "linkType": "<relation>",\n "comment": "<note>"\n }\n}'},{name:"jira-guide-link-update-tool",title:"Jira guide: link update",description:"Detail how to change an existing link type with `jira-link-update`.",toolName:"jira-link-update",scenario:"When the relationship between two issues needs to change (e.g., blocks \u2192 relates to).",resources:["resource://repo.metadata"],guidance:["Document the desired new relationship and why the previous one no longer applies.","List the link ID you are targeting so the tool updates precisely that connection."],argsSchema:s.z.object({linkId:s.z.string().optional(),linkType:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-link-update",\n "arguments": {\n "linkId": "<id>",\n "linkType": "<new relation>"\n }\n}'},{name:"jira-guide-link-delete-tool",title:"Jira guide: link delete",description:"Explain how to remove an incorrect or outdated link with `jira-link-delete`.",toolName:"jira-link-delete",scenario:"When a previously created link must be removed or replaced.",resources:["resource://repo.metadata"],guidance:["Ensure you reference the correct link ID and confirm both issues still exist.","Mention why the link is no longer valid to keep the audit trail clear."],argsSchema:s.z.object({linkId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-link-delete",\n "arguments": {\n "linkId": "<id>"\n }\n}'},{name:"jira-guide-attach-issue-tool",title:"Jira guide: attach file",description:"Describe when to upload artifacts with `jira-attach-issue` and how to include comments.",toolName:"jira-attach-issue",scenario:"When the user references logs, screenshots, or generated files that should be attached.",resources:["resource://repo.metadata"],guidance:["State which files are being attached and describe their purpose in the preview comment.","Ensure the file path is accessible and safe for the tool to read before calling it."],argsSchema:s.z.object({issueId:s.z.string().optional(),filePath:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-attach-issue",\n "arguments": {\n "issueId": "<id>",\n "filePath": "<path>",\n "comment": "<note>"\n }\n}'},{name:"jira-guide-attachment-list-tool",title:"Jira guide: attachment list",description:"Explain when to list attachments before adding or deleting files.",toolName:"jira-attachment-list",scenario:"When you need to verify existing attachments prior to uploading or removing files.",resources:["resource://repo.metadata"],guidance:["Capture the attached file names so you can reference the correct ID for deletion.","Use pagination hints if the ticket has many attachments."],argsSchema:s.z.object({issueId:s.z.string().optional(),page:s.z.number().optional()}).partial(),callTemplate:'{\n "name": "jira-attachment-list",\n "arguments": {\n "issueId": "<id>",\n "page": 0\n }\n}'},{name:"jira-guide-attachment-delete-tool",title:"Jira guide: attachment delete",description:"Describe how to delete a specific attachment with `jira-attachment-delete`.",toolName:"jira-attachment-delete",scenario:"When an attachment is obsolete, sensitive, or incorrect.",resources:["resource://repo.metadata"],guidance:["Confirm you have the attachment ID from the listing step to avoid removing the wrong file.","Summarize why the attachment is being removed in the action preview."],argsSchema:s.z.object({issueId:s.z.string().optional(),attachmentId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-attachment-delete",\n "arguments": {\n "issueId": "<id>",\n "attachmentId": "<attachment>"\n }\n}'},{name:"jira-guide-worklog-add-tool",title:"Jira guide: worklog add",description:"Clarify how to log time against an issue with `jira-worklog-add`.",toolName:"jira-worklog-add",scenario:"When the user reports effort spent on a ticket and needs to record it.",resources:["resource://repo.metadata"],guidance:["Convert natural language durations into Jira-friendly strings and include the context of the work.","Mention whether the log should be visible to everyone or restricted."],argsSchema:s.z.object({issueId:s.z.string().optional(),timeSpent:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-worklog-add",\n "arguments": {\n "issueId": "<id>",\n "timeSpent": "<duration>",\n "comment": "<details>"\n }\n}'},{name:"jira-guide-markdown-to-adf-tool",title:"Jira guide: markdown to ADF",description:"Summarize when to pre-process Markdown into Jira ADF before calling other tools.",toolName:"jira-markdown-to-adf",scenario:"When you need to send Markdown content into Jira fields (descriptions, comments) through other tools.",resources:["resource://repo.metadata","resource://golden.override.model-builder"],guidance:["Use this conversion whenever you cannot guarantee that Jira will accept raw Markdown.","Keep the resulting ADF document handy for downstream calls (issue-update, comment-add, etc.)."],argsSchema:s.z.object({markdown:s.z.string().optional(),context:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-markdown-to-adf",\n "arguments": {\n "markdown": "<text>",\n "context": "<purpose>"\n }\n}'},{name:"jira-guide-adf-to-markdown-tool",title:"Jira guide: ADF to Markdown",description:"Describe why to convert Jira ADF back into Markdown for editing.",toolName:"jira-adf-to-markdown",scenario:"When a user needs to edit a field that already contains ADF (comments/descriptions).",resources:["resource://repo.metadata"],guidance:["Convert the ADF, revise it, then re-run markdown-to-adf if you plan to push it back through Jira.","Keep the Markdown summary in the action preview for reviewers."],argsSchema:s.z.object({adf:s.z.any().optional()}).partial(),callTemplate:'{\n "name": "jira-adf-to-markdown",\n "arguments": {\n "adf": <ADF payload>\n }\n}'},{name:"jira-guide-xray-step-add-tool",title:"Jira guide: Xray step add",description:"Explain how to add a test step from the golden template to a test case via `jira-xray-step-add`.",toolName:"jira-xray-step-add",scenario:"When you document new verification steps for an automated or manual test case.",resources:["resource://repo.metadata","resource://golden.override.xray-step-template"],guidance:["Reference the golden step template before composing the new instruction.","Include both the action and verification so reviewers immediately know the expected result."],argsSchema:s.z.object({testCaseKey:s.z.string().optional(),step:s.z.string().optional(),status:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-add",\n "arguments": {\n "testCaseKey": "<key>",\n "step": "<description>",\n "status": "<PASS|FAIL|TODO>"\n }\n}'},{name:"jira-guide-xray-step-update-tool",title:"Jira guide: Xray step update",description:"Document how to update an existing Xray step via `jira-xray-step-update`.",toolName:"jira-xray-step-update",scenario:"When a test step needs corrections to instructions or expected results.",resources:["resource://repo.metadata","resource://golden.override.xray-step-template"],guidance:["Summarize the delta (what\u2019s changing) before calling the tool so the reviewer knows the context.","Be precise with the `stepId` to avoid editing the wrong step."],argsSchema:s.z.object({testCaseKey:s.z.string().optional(),stepId:s.z.string().optional(),update:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-update",\n "arguments": {\n "testCaseKey": "<key>",\n "stepId": "<id>",\n "update": "<new text>"\n }\n}'},{name:"jira-guide-xray-step-delete-tool",title:"Jira guide: Xray step delete",description:"Explain why you would remove a test step and how to use `jira-xray-step-delete`.",toolName:"jira-xray-step-delete",scenario:"When a chore is no longer relevant and its step should be removed.",resources:["resource://repo.metadata"],guidance:["Confirm the step ID and test case key using the list or read tools before deleting.","Document the reason for removal so auditors understand the change."],argsSchema:s.z.object({testCaseKey:s.z.string().optional(),stepId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-delete",\n "arguments": {\n "testCaseKey": "<key>",\n "stepId": "<id>"\n }\n}'},{name:"jira-guide-xray-step-list-tool",title:"Jira guide: Xray step list",description:"Describe how to inspect the existing Xray steps before editing or deleting them.",toolName:"jira-xray-step-list",scenario:"When you should view the existing test steps to confirm numbering or status.",resources:["resource://repo.metadata"],guidance:["Report the step IDs and descriptions in your preview so you can reference them later.","Use the list data instead of memory to keep numbering accurate."],argsSchema:s.z.object({testCaseKey:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-list",\n "arguments": {\n "testCaseKey": "<key>"\n }\n}'}].map(e=>G.builder.setName(e.name).setTitle(e.title).setDescription(e.description).setArgsSchema(e.argsSchema).setCb(async(t={},r)=>({messages:[{role:"user",content:{type:"text",text:ae(e,t)}}],structuredContent:{tool:e.toolName,args:t},result:{tool:e.toolName,args:t},_meta:{}})))];class ce extends N{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 ce}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{this.inputSchema&&q(this.inputSchema,"inputSchema"),this.outputSchema&&q(this.outputSchema,"outputSchema");const t=P(this.inputSchema),r=P(this.outputSchema);return e.registerTool(this.name,{title:this.title,description:this.description,inputSchema:t,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(e,t)=>{const r=this.logFor(t);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(e)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const i=await Promise.resolve(this.cb(e,t));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(i._meta)),i})}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}}}i.__decorate([n.required(),i.__metadata("design:type",Object)],ce.prototype,"annotations",void 0),i.__decorate([n.required(),i.__metadata("design:type",Object)],ce.prototype,"cb",void 0),i.__decorate([n.required(),i.__metadata("design:type",Function)],ce.prototype,"inputSchema",void 0);const de=c.resolve(process.cwd(),"README.md"),le=ce.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summarizes a file so the model knows the gist before making decisions; defaults to README.md when no path is supplied.").setInputSchema(s.z.object({filePath:s.z.string().optional()})).setCb(async e=>{const t=e?.filePath?c.resolve(process.cwd(),e.filePath):de;let r,i="ok";try{r=(await m.readFile(t,"utf8")).split(/\r?\n/).filter(e=>e.trim().length>0).slice(0,10).join(" ").slice(0,800),r=r||"(file contained no readable content)"}catch(t){i="error";const n=t instanceof Error?t.message:"unknown error reading file";r=`Unable to summarize ${e?.filePath??"README.md"}: ${n}`}const n={filePath:t,status:i,summary:r};return{content:[{type:"text",text:r}],structuredContent:n,result:n}});function ue(){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 i=c.dirname(e);if(i===e)break;e=i}}catch{}return{}}Object.assign(le,{name:le.getName()});const pe=ue().version??"0.0.0",me=ue().name??"unknown";o.Metadata.registerLibrary(me,pe);const he={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:W,assetDir:X(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0,timeout:process.env.JIRA__TIMEOUT?parseInt(process.env.JIRA__TIMEOUT):1e3,rateLimitRetryDelayMs:process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS?parseInt(process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS):3e3},xray:{host:process.env.XRAY__HOST||process.env.XRAY__API_HOST||"https://xray.cloud.getxray.app",apiUser:process.env.XRAY__API_USER||"",apiSecret:process.env.XRAY__API_SECRET||""},level:r.LogLevel.error},ge=r.LoggedEnvironment.accumulate(he);function ye(){const{host:e,email:t,apiKey:r,projectKey:i,issueType:n}=ge.jira;return{host:e?.trim(),email:t?.trim(),apiKey:r?.trim(),projectKey:i?.trim(),issueType:n?.trim(),parentIssue:ge.jira.parentIssue?.trim()}}function fe(){const e=ye();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 be(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(ge);class we extends Error{constructor(e){const t=fe(),r=(e=>{const t=fe();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(be).join("\n")}`})(e);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=t,this.missing=e,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,we)}}const ve=r.Logging.for("jira.client"),ze=/(authorization|cookie)/i;function je(e){if(!e)return;const t=e.baseURL??"",r=e.url??"";return t&&r?`${t.endsWith("/")?t.slice(0,-1):t}/${r.startsWith("/")?r.slice(1):r}`:r||t||void 0}function ke(e){if(void 0!==e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch(t){return h.inspect(e,{depth:null})}}}function Ie(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,r])=>{t[e]=ze.test(e)&&r?"[REDACTED]":r}),t}function Se(e){let t;try{const e=require("jira.js");t=e?.Version3Client||e.default?.Version3Client||e.default||e}catch(e){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+e)}const{host:r,email:i,apiKey:n}=(()=>{const e=ye(),t=fe().filter(e=>e.required&&!e.value);if(t.length>0)throw new we(t);return{host:e.host,email:e.email,apiKey:e.apiKey}})(),s=new t({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:i,apiToken:n}},baseRequestConfig:{headers:{Accept:"application/json","Content-Type":"application/json"}}});return(e=>{if(!e)return;const t="__jiraLoggingAttached";e[t]||(e[t]=!0,e.interceptors.request.use(e=>{e.headers=(e=>{const t={...e||{}};return Object.keys(t).some(e=>"accept"===e.toLowerCase())||(t.Accept="application/json"),Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),t})(e.headers);const t=(e.method??"GET").toString().toUpperCase(),r=je(e);return ve.info("jira.request",{method:t,url:r,headers:Ie(e.headers),params:e.params,data:ke(e.data)}),e},e=>(ve.error("jira.request.error",{message:e.message}),Promise.reject(e))),e.interceptors.response.use(e=>{const t=(e.config?.method??"GET").toString().toUpperCase(),r=je(e.config);return ve.info("jira.response",{method:t,url:r,status:e.status,headers:Ie(e.headers),data:ke(e.data)}),e},e=>{const t=e.config,r=e.response,i=(t?.method??"GET").toString().toUpperCase(),n=je(t);return ve.error("jira.response.error",{method:i,url:n,status:r?.status,headers:Ie(r?.headers),data:ke(r?.data),message:e.message}),Promise.reject(e)}))})(s.instance),s}const xe=s.z.object({name:s.z.string().min(1).optional().describe("Optional template name that pre-populates additional fields"),content:s.z.string().min(1).describe("Markdown template content to apply when constructing the description"),placeholders:s.z.record(s.z.string()).optional().describe("Map of placeholder replacements used by the template")}).describe("Template metadata used to adjust the created description"),Te=s.z.object({template:xe.optional().describe("Optional template settings for this create request")}).describe("Additional template controls available when creating an issue"),Ae=s.z.union([s.z.object({fields:s.z.record(s.z.any()).describe("Full raw field map that gets delivered to Jira")}).merge(Te).describe("Create argument that supplies every field explicitly"),s.z.object({summary:s.z.string().min(1).describe("Title or summary of the new issue"),projectKey:s.z.string().min(1).describe("Project key where the issue is created"),issueType:s.z.string().min(1).describe("Type name for the new issue (story, task, etc.)"),description:s.z.string().optional().describe("Optional textual description for the issue")}).merge(Te).describe("Create argument with minimal required identifiers plus optional description")]).describe("Union describing how to create an issue either via raw fields or shorthand properties");function Ee(e,t,r){const i=((e.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!i)return null;const n=i[2],s=r.resolveAttachment?.(n);return s?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:s.id,collection:s.collection??"attachments"}}]}}:null}function _e(e,t){if(!e)return[];if(!t.enableAtMentions&&!t.enableEmojiShortcodes)return[{type:"text",text:e}];let r=0;const i=[],n=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,s=/:([a-z0-9_+-]{1,64}):/gi;for(;r<e.length;){const a=Je(t.enableAtMentions?Oe(n,e,r):null,t.enableEmojiShortcodes?Oe(s,e,r):null);if(!a){i.push({type:"text",text:e.slice(r)});break}if(a.index>r&&i.push({type:"text",text:e.slice(r,a.index)}),"mention"===a.kind){const{full:e,groups:n}=a,s=n[0]??"",o=n[1]??"";s&&i.push({type:"text",text:s});const c=t.resolveMention?.(o);c?i.push({type:"mention",attrs:{id:c.id,text:c.text}}):i.push({type:"text",text:"@"+o}),r=a.index+e.length;continue}if("emoji"===a.kind){const{full:e,groups:n}=a,s=`:${n[0]}:`,o=t.resolveEmoji?.(s);i.push({type:"emoji",attrs:o?{shortName:o.shortName,text:o.text}:{shortName:s}}),r=a.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})(i)}function Oe(e,t,r){e.lastIndex=r;const i=e.exec(t);if(!i)return null;const n=e.source.includes("@")?"mention":"emoji";return{index:i.index,full:i[0],groups:i.slice(1),kind:n}}function Je(e,t){return e?t&&e.index>t.index?t:e:t}function De(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 Ce(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 Ne(e){const t=((e??"")+"").toLowerCase().trim();return!t||"neutral"!==t&&"green"!==t&&"yellow"!==t&&"red"!==t&&"blue"!==t&&"purple"!==t?null:t}function He(e,t){const r=[];for(const i of e??[])if(i?.type)if("text"!==i.type)if("strong"!==i.type)if("emphasis"!==i.type)if("delete"!==i.type)if("inlineCode"!==i.type)if("break"!==i.type){if("link"===i.type){const e=(i.url??"")+"",n=Pe(i.children??[],e),s=Ee(i,0,t);if(s){"inline"===s.type?r.push(s.node):r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:e}}]});continue}if(t.enableSmartCards&&Re(n,e)){r.push({type:"inlineCard",attrs:{url:e}});continue}r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:e}}]});continue}if("textDirective"===i.type&&"status"===i.name){const e=De(i)||"Status",t=Ne(i.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:e,color:t}});continue}if("textDirective"===i.type&&"emoji"===i.name){const e=Le(i);r.push(Me(e,t));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(i.value??"")+"",marks:[{type:"code"}]});else r.push(...qe(He(i.children??[],t),{type:"strike"}));else r.push(...qe(He(i.children??[],t),{type:"em"}));else r.push(...qe(He(i.children??[],t),{type:"strong"}));else r.push(..._e((i.value??"")+"",t));return r.filter(e=>!("text"===e.type&&""===(e.text??"")))}function qe(e,t){return e.map(e=>{if("text"!==e.type)return e;if(e.marks?.some(e=>"code"===e.type))return e;const r=e.marks?[...e.marks,t]:[t];return{...e,marks:r}})}function Pe(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(Pe(t.children??[],""));return r.join("")||t}function Re(e,t){const r=(e??"").trim(),i=(t??"").trim();return r===i&&/^https?:\/\//i.test(i)}function Le(e){return(e.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("").trim()||""}function Me(e,t){const r=e.startsWith(":")?e:`:${e}:`,i=t.resolveEmoji?.(r);return i?{type:"emoji",attrs:{shortName:i.shortName,text:i.text}}:{type:"emoji",attrs:{shortName:r}}}function $e(e){return e?"string"==typeof e?e:"text"===e.type||"inlineCode"===e.type?(e.value??"")+"":Array.isArray(e.children)?e.children.map($e).join(""):"":""}function Fe(e,t){if(!e?.type)return null;if((e=>"containerDirective"===e?.type&&"panel"===e?.name)(e))return((e,t)=>{const r=e.attributes??{},i=Ce(r.type)??"info",n="string"==typeof r.title?r.title:void 0,s=(e.children??[]).map(e=>Fe(e,t)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:i,...n?{panelType:i,title:n}:{panelType:i}},content:s.length?s:[{type:"paragraph",content:[]}]}})(e,t);switch(e.type){case"heading":return{type:"heading",attrs:{level:We(e.depth??1,1,6)},content:He(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 i=(r.url??"")+"";return i?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:i}}]}:null})(e);return r||{type:"paragraph",content:He(e.children??[],t)}}case"blockquote":return{type:"blockquote",content:(e.children??[]).map(e=>Fe(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 i=0;for(const n of e.children??[]){if("boolean"!=typeof n.checked)continue;i+=1;const e=(n.children??[]).map(e=>Fe(e,t)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+i,state:n.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=>Fe(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&&r.includes("mermaid")?"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:He(e.children??[],t)}]}))}))}))(e,t);case"leafDirective":return"status"===e.name?(e=>{const t=Ne((e.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:De(e)||"Status",color:t}}]}})(e):"panel"===e.name?((e,t)=>{const r=e.attributes??{},i=Ce(r.type)??"info",n="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:i,...n?{title:n}:{}},content:[{type:"paragraph",content:He([{type:"text",value:De(e)}],t)}]}})(e,t):Ue(e,t);default:return Ue(e,t)}}function Ue(e,t){if("drop"===t.unknownNodeStrategy)return null;const r=$e(e);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function We(e,t,r){const i=Number.isFinite(e)?Math.trunc(e):t;return Math.max(t,Math.min(r,i))}const Ke={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function Be(e,t={}){const r={...Ke,...t},i=e??"",n=g.unified().use(b).use(y).use(f),s=n.parse(i),a=n.runSync(s);return Xe(a),((e,t)=>{const r=[];for(const i of e.children??[]){const e=Fe(i,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 i=r.attrs?.url;return i?[{type:"blockCard",attrs:{url:i}}]:e})(e)).flat();return{...e,content:r}})({version:1,type:"doc",content:r},t)})(a,r)}function Xe(e){if(!e||!Array.isArray(e.children))return;const t=[];for(const r of e.children)"definition"!==r?.type&&("html"!==r?.type?(Xe(r),t.push(r)):t.push({type:"text",value:(r.value??"")+""}));e.children=t}function Ye(e){return{...e,content:Ge(e.content??[])}}function Ge(e){return e.flatMap(e=>"panel"===e.type?Ge(e.content??[]):[Ve(e)])}function Ve(e){return e.content?{...e,content:Ge(e.content)}:{...e}}const Ze=/\{\{\s*([^\}]+)\s*\}\}/g;function Qe(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 h.inspect(e,{depth:null})}})(e);return t?[{type:"text",text:t}]:[]}function et(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:Qe(r),result:r,structuredContent:r}}const tt={name:"jira-issue-create",inputSchema:Ae,runTool:async(e,t)=>{const r=await(async(e,t)=>{let r;const i=e=>e&&e.trim()?e.trim():void 0,n=i(ge.jira.projectKey),s=i(ge.jira.issueType),a=t&&"object"==typeof t&&!Array.isArray(t)?t:{},o=Object.prototype.hasOwnProperty.call(a,"fields")?a:{...a,projectKey:a.projectKey??n,issueType:a.issueType??s};try{r=Ae.parse(o)}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=(i=t.content,n=t.placeholders,i?i.replace(Ze,(e,t)=>{const r=t.trim();if(!r)return"";if(n&&Object.prototype.hasOwnProperty.call(n,r)){const e=n[r];return null==e?"":e+""}return e}):"");var i,n;if(!r.trim())return e;const s=Be(r),a=(o=e.description)?"object"==typeof o&&"doc"===o.type&&Array.isArray(o.content)?o.content:"string"==typeof o?Be(o).content:[]:[];var o;return e.description={type:"doc",version:1,content:[...a,...s.content]},e})(c,r.template);const d=e?.issues?.create??e?.issues?.createIssue;if("function"!=typeof d)throw Error("Jira client missing create function");const l=await d.call(e.issues,{fields:c}),u=l&&l.data||l;return{id:u?.id??null,key:u?.key??null}})(e,t);return et(r)}};class rt extends Error{constructor({code:e,message:t,details:r}){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=e,this.details=r}}const it=r.Logging.for("jira.errors");function nt(e){if(!e)return new rt({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,i=e?.response?.data??e?.data??e?.response?.body??e?.body,n=e?.response?.statusText??(r?""+r:void 0),s=e?.response?.headers?Ie(e.response.headers):void 0,a=[];"string"==typeof e?.message&&a.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)}))})(i,a);const o=r?`Jira API error (${r})`:"Jira API error",c=a.length>0?a.join(" | "):o,d=r?"jira_"+r:e?.code??"jira_error",l=e?.config,u=l?{method:l.method?l.method.toString().toUpperCase():void 0,url:l.url,headers:Ie(l.headers),data:ke(l.data)}:void 0,p={httpStatus:r,body:i,request:u,response:s?{statusText:n,headers:s}:n?{statusText:n}:void 0,raw:e};return it.error("jira.error",{code:d,message:c,httpStatus:r,statusText:n,responseHeaders:s,request:u,body:ke(i)??i}),new rt({code:d,message:c,details:p})}const st=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID to delete"),deleteSubtasks:s.z.boolean().optional().default(!0).describe("Whether to delete the subtasks alongside this issue")}).describe("Arguments used to delete a Jira issue (with optional subtasks)"),at={name:"jira-issue-delete",inputSchema:st,runTool:async(e,t)=>{try{const r=st.parse(t),i=e.issues??e.issue??e,n=i?.delete??i?.deleteIssue;if("function"!=typeof n)throw Error("jira client delete endpoint is not available");return await n.call(i,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),et({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(e){throw nt(e)}}},ot=s.z.object({projectKey:s.z.string().trim().min(1).optional().describe("Project key used to scope the issue search"),issueType:s.z.string().trim().min(1).optional().describe("Issue type name used to filter the results"),parentIssueId:s.z.string().trim().min(1).optional().describe("Optional parent issue key/ID to limit results to a subtree"),name:s.z.string().trim().min(1).optional().describe("Issue summary to match exactly"),reference:s.z.string().trim().min(1).optional().describe("External reference or custom identifier to filter by"),jql:s.z.string().trim().min(1).optional().describe("Free-form JQL query to drive the search"),startAt:s.z.number().int().min(0).optional().describe("Index for paging through the search results"),maxResults:s.z.number().int().min(1).optional().describe("Maximum number of issues to return"),fields:s.z.array(s.z.string()).optional().describe("List of issue fields to include in the response"),expand:s.z.string().optional().describe("Optional expansion clause for the results"),orderBy:s.z.string().trim().min(1).optional().describe("Field or clause used to order the returned issues")}).describe("Parameters describing how to search for Jira issues");function ct(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const dt={name:"jira-issue-list",inputSchema:ot,runTool:async(e,t)=>{try{const r=ot.parse(t),i=r.startAt??0,n=r.maxResults??50;let s=r.jql?.trim();if(s){if(r.orderBy){const e=r.orderBy.trim();e&&(s=/\border\s+by\b/i.test(s)?`${s}, ${e}`:`${s} ORDER BY ${e}`)}}else s=(e=>{const t=[];if(e.projectKey&&t.push(`project = "${ct(e.projectKey)}"`),e.issueType&&t.push(`issuetype = "${ct(e.issueType)}"`),e.parentIssueId&&t.push(`parent = "${ct(e.parentIssueId)}"`),e.name&&t.push(`summary ~ "${ct(e.name)}"`),e.reference){const r=ct(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 a={jql:s,startAt:i,maxResults:n};r.fields&&(a.fields=r.fields),r.expand&&(a.expand=r.expand);const o=e.issueSearch,c=o&&"function"==typeof o.searchForIssuesUsingJqlEnhancedSearch?o.searchForIssuesUsingJqlEnhancedSearch:o&&"function"==typeof o.searchForIssuesUsingJql?o.searchForIssuesUsingJql:void 0;if(!c)throw Error("Jira search API is unavailable on the client");const d=await c.call(o,a),l=d?.data??d,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=i),void 0===u.maxResults&&(u.maxResults=n),et(u)}catch(e){throw nt(e)}}},lt=s.z.object({issueId:s.z.string().min(1).describe("Jira issue key or numeric ID to read"),expand:s.z.string().optional().describe("Optional expand clause for nested fields or changelog"),fields:s.z.array(s.z.string()).optional().describe("Explicit list of issue fields to return"),properties:s.z.array(s.z.string()).optional().describe("Specific issue properties to include in the response")}).describe("Arguments required to read a Jira issue"),ut={name:"jira-issue-read",inputSchema:lt,runTool:async(e,t)=>{try{const r=lt.parse(t),i={issueIdOrKey:r.issueId};r.expand&&(i.expand=r.expand),r.fields&&(i.fields=r.fields),r.properties&&(i.properties=r.properties);const n=await e.issues.getIssue(i);return et(n?.data??n)}catch(e){throw nt(e)}}},pt=s.z.object({issueId:s.z.string().min(1).describe("Target issue key or ID to transition"),transitionId:s.z.union([s.z.string(),s.z.number()]).describe("Identifier for the transition to execute"),fields:s.z.record(s.z.any()).optional().describe("Optional field updates to apply during the transition"),update:s.z.record(s.z.array(s.z.object({set:s.z.any().optional().describe("Set operation for the transition update"),add:s.z.any().optional().describe("Add operation for the transition update"),remove:s.z.any().optional().describe("Remove operation for the transition update")}))).optional().describe("Structured update operations to send alongside the transition"),comment:s.z.string().optional().describe("Optional comment to attach during the transition")}).describe("Inputs needed to transition a Jira issue"),mt={name:"jira-issue-transition",inputSchema:pt,runTool:async(e,t)=>{try{const r=pt.parse(t),i={id:r.transitionId};r.fields&&(i.fields=r.fields),r.update&&(i.update=r.update),r.comment&&(i.comment={body:Be(r.comment)});const n=await e.issues.transition({issueIdOrKey:r.issueId,transition:i});return et(n?.data??n)}catch(e){throw nt(e)}}},ht=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID for which to list transitions"),expand:s.z.string().optional().describe("Optional expand parameter for the transition response")}).describe("Inputs used to fetch available transitions for an issue"),gt={name:"jira-transition-list",inputSchema:ht,runTool:async(e,t)=>{try{const r=ht.parse(t),i=e.issues;if(!i||"function"!=typeof i.getTransitions)throw Error("Jira transitions API is unavailable on the client");const n={issueIdOrKey:r.issueId};r.expand&&(n.expand=r.expand);const s=await i.getTransitions(n);return et(s?.data??s)}catch(e){throw nt(e)}}},yt=s.z.object({description:s.z.string().optional().describe("Markdown description that is converted to Jira ADF (use jira-md-to-adf if you need raw ADF input)")}).catchall(s.z.any()).describe("Field map that gets delivered to Jira (labels, components, etc.)"),ft=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID to update"),fields:yt.optional(),update:s.z.record(s.z.array(s.z.object({set:s.z.any().optional().describe("Set operation alongside the update key"),add:s.z.any().optional().describe("Add operation alongside the update key"),remove:s.z.any().optional().describe("Remove operation alongside the update key"),edit:s.z.any().optional().describe("Edit operation alongside the update key")}))).optional().describe("Structured update operations for array/set fields"),properties:s.z.array(s.z.any()).optional().describe("Property payloads to attach to the issue"),notifyUsers:s.z.boolean().optional().default(!0).describe("Whether to notify watchers when the issue is updated"),issueTemplateId:s.z.string().optional().describe("Optional template ID to render issue descriptions"),overrideScreenSecurity:s.z.boolean().optional().default(!1).describe("Temporarily bypass screen security restrictions"),overrideEditableFlag:s.z.boolean().optional().default(!1).describe("Temporarily bypass the editable flag on the screen")}).describe("Arguments used to update existing Jira issues"),bt=s.z.record(s.z.any()).optional(),wt=s.z.object({type:s.z.string().describe("Mark name, such as strong, emphasis, code, or link"),attrs:bt}).describe("Inline formatting or link marks applied to text nodes"),vt=s.z.object({type:s.z.literal("text"),text:s.z.string().describe("Rendered string content for the text node"),marks:s.z.array(wt).optional()}).describe("Plain text node that carries optional formatting marks"),zt=s.z.object({type:s.z.literal("mention"),attrs:s.z.object({id:s.z.string().describe("Jira internal identifier for the mention"),text:s.z.string().describe("Human readable mention text"),userType:s.z.string().optional(),accessLevel:s.z.string().optional(),localizedAccessLevel:s.z.string().optional()}).describe("Metadata describing the mentioned user")}).describe("Represents a user or team mention in a block or inline context"),jt=s.z.object({type:s.z.literal("emoji"),attrs:s.z.object({shortName:s.z.string().describe("Emoji shortcode such as smiling_face"),id:s.z.string().optional(),text:s.z.string().optional()}).describe("Emoji metadata")}).describe("Emoji inline node"),kt=s.z.object({type:s.z.literal("inlineCard"),attrs:s.z.object({url:s.z.string().url().describe("Target URL that backs the inline card")}).describe("Inline card attributes")}).describe("Inline card that represents a linked resource"),It=s.z.object({type:s.z.literal("status"),attrs:s.z.object({text:s.z.string().describe("Status label text"),color:s.z.string().describe("Color code applied by Jira"),localId:s.z.string().optional(),style:s.z.string().optional()}).describe("Status metadata published by Jira")}).describe("Status node used for Jira workflow or custom fields"),St=s.z.object({type:s.z.literal("date"),attrs:s.z.object({representation:s.z.string().optional(),timestamp:s.z.number().optional()}).describe("Date metadata, usually RFC3339 or timestamp")}).describe("Date node that embeds a Jira date reference"),xt=s.z.object({type:s.z.literal("hardBreak")}).describe("Inline hard break that forces a newline"),Tt=s.z.object({type:s.z.literal("rule")}).describe("Horizontal rule dividing sections of the document");let At,Et;const _t=s.z.lazy(()=>s.z.union([vt,zt,jt,kt,It,St,xt])),Ot=s.z.lazy(()=>s.z.object({type:s.z.literal("paragraph"),content:s.z.array(_t).describe("Inline nodes contained by the paragraph")})),Jt=s.z.lazy(()=>s.z.object({type:s.z.literal("heading"),attrs:s.z.object({level:s.z.number().int().min(1).max(6).describe("Heading level, 1-6")}).optional(),content:s.z.array(_t).describe("Inline nodes composing the heading")})),Dt=s.z.lazy(()=>s.z.object({type:s.z.literal("listItem"),attrs:s.z.object({localId:s.z.string().optional()}).optional(),content:s.z.array(s.z.lazy(()=>At)).describe("Block level nodes nested inside the list item")})),Ct=s.z.lazy(()=>s.z.object({type:s.z.literal("bulletList"),content:s.z.array(Dt).describe("List items within the bullet list")})),Nt=s.z.lazy(()=>s.z.object({type:s.z.literal("orderedList"),attrs:s.z.object({order:s.z.number().int().min(1).optional()}).optional(),content:s.z.array(Dt)})),Ht=s.z.lazy(()=>s.z.object({type:s.z.literal("taskItem"),attrs:s.z.object({localId:s.z.string().optional(),state:s.z.enum(["TODO","IN_PROGRESS","DONE"]).optional()}).optional(),content:s.z.array(s.z.lazy(()=>At)).describe("Blocks living inside the task item")})),qt=s.z.lazy(()=>s.z.object({type:s.z.literal("taskList"),content:s.z.array(Ht).describe("Task items inside the list")})),Pt=s.z.lazy(()=>s.z.object({type:s.z.literal("codeBlock"),attrs:s.z.object({language:s.z.string().optional()}).optional(),content:s.z.array(vt).optional()})),Rt=s.z.lazy(()=>s.z.object({type:s.z.literal("panel"),attrs:s.z.object({panelType:s.z.enum(["info","note","tip","warning","success"]).optional(),title:s.z.string().optional()}).optional(),content:s.z.array(s.z.lazy(()=>At)).describe("Panels may nest paragraphs, lists, or other blocks")})),Lt=s.z.lazy(()=>s.z.object({type:s.z.literal("blockquote"),content:s.z.array(s.z.lazy(()=>At)).describe("Quoted block content")})),Mt=s.z.lazy(()=>s.z.object({type:s.z.literal("blockCard"),attrs:s.z.object({url:s.z.string().url().describe("URL for the card")})})),$t=s.z.lazy(()=>s.z.object({type:s.z.literal("media"),attrs:s.z.object({id:s.z.string().describe("Media identifier in Jira storage"),type:s.z.string().describe("Media type, e.g., file or link"),collection:s.z.string().optional(),width:s.z.number().optional(),height:s.z.number().optional()}).describe("Metadata describing the embedded media")})),Ft=s.z.lazy(()=>s.z.object({type:s.z.literal("mediaSingle"),content:s.z.array($t).describe("Single media block content")})),Ut=s.z.lazy(()=>s.z.object({type:s.z.literal("mediaGroup"),content:s.z.array($t).describe("Gallery-style media grouping")})),Wt=s.z.object({type:s.z.literal("tableCell"),attrs:s.z.object({colspan:s.z.number().int().min(1).optional(),rowspan:s.z.number().int().min(1).optional()}).optional(),content:s.z.array(s.z.lazy(()=>At)).describe("Content inside the table cell")}).describe("A regular table cell container"),Kt=s.z.lazy(()=>Wt),Bt=s.z.lazy(()=>Wt.extend({type:s.z.literal("tableHeader")})),Xt=s.z.lazy(()=>s.z.object({type:s.z.literal("tableRow"),content:s.z.array(s.z.union([Kt,Bt]))})),Yt=s.z.lazy(()=>s.z.object({type:s.z.literal("table"),content:s.z.array(Xt)})),Gt=s.z.lazy(()=>s.z.object({type:s.z.literal("decisionItem"),attrs:s.z.object({localId:s.z.string().optional(),state:s.z.enum(["DECIDED","DECIDING"]).optional()}).optional(),content:s.z.array(s.z.lazy(()=>At))})),Vt=s.z.lazy(()=>s.z.object({type:s.z.literal("decisionList"),content:s.z.array(Gt)})),Zt=s.z.lazy(()=>s.z.object({type:s.z.string(),attrs:s.z.record(s.z.any()).optional(),content:s.z.array(s.z.lazy(()=>Et)).optional(),marks:s.z.array(wt).optional(),text:s.z.string().optional()}).describe("Unknown or extended Jira node"));At=s.z.lazy(()=>s.z.union([Ot,Jt,Ct,Nt,Dt,qt,Ht,Pt,Rt,Lt,Mt,Ft,Ut,Yt,Xt,Kt,Bt,Vt,Gt,Tt,Zt])),Et=s.z.lazy(()=>s.z.union([At,_t]));const Qt=s.z.object({type:s.z.literal("doc"),version:s.z.literal(1),content:s.z.array(At).describe("Top-level block nodes in the document")}).describe("Jira ADF document structure; run jira-md-to-adf when converting markdown"),er=r.Logging.for("jira.rate-limit"),tr=ge.jira.rateLimitRetryDelayMs??3e3;let rr=!1;const ir="jira-issue-update",nr=ft,sr={name:ir,inputSchema:nr,runTool:async(e,t)=>{try{const r=nr.parse(t),i={issueIdOrKey:r.issueId};r.fields&&(i.fields=(e=>{const t={...e},r=t.description;if("string"==typeof r){const e=Ye(Be(r));t.description=Qt.parse(e)}else if(r&&"object"==typeof r){const e=Ye(Qt.parse(r));t.description=e}return t})(r.fields)),r.update&&(i.update=r.update),r.properties&&(i.properties=r.properties),void 0!==r.notifyUsers&&(i.notifyUsers=r.notifyUsers),r.issueTemplateId&&(i.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(i.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(i.overrideEditableFlag=r.overrideEditableFlag);const n=await(async(e,t)=>{try{return await t()}catch(i){if((e=>{const t=(e=>e?.status??e?.statusCode??e?.response?.status??e?.response?.statusCode??void 0)(e);if(403!==t)return!1;const r=(e=>{const t=e?.response?.data??e?.data??e?.response?.body??e,r=[];return"string"==typeof t&&r.push(t),"string"==typeof t?.message&&r.push(t.message),"string"==typeof t?.errorMessage&&r.push(t.errorMessage),Array.isArray(t?.errorMessages)&&r.push(...t.errorMessages.filter(e=>"string"==typeof e)),"string"==typeof t?.details?.message&&r.push(t.details.message),r.join(" ")||""})(e);return/rate\s?limit/i.test(r)})(i))return rr||(er.warn(`Jira rate limit detected for ${e}; waiting ${tr}ms before retrying.`,{retryDelayMs:tr}),rr=!0),tr>0&&await(r=tr,new Promise(e=>setTimeout(e,r))),t();throw i}var r})(ir,()=>e.issues.editIssue(i));return et(n?.data??n)}catch(e){throw nt(e)}}},ar=s.z.object({markdown:s.z.string().describe("Markdown source that will be converted into Jira ADF"),options:s.z.record(s.z.any()).optional().describe("Optional MarkdownToAdfOptions passed to the converter")}).describe("Convert markdown into a sanitized Jira ADF document"),or={name:"jira-md-to-adf",inputSchema:ar,runTool:async(e,t)=>{const r=ar.parse(t),i=Ye(Be(r.markdown,r.options));return et(Qt.parse(i))}},cr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID for the assignment change"),assignee:s.z.union([s.z.string().describe("Username or account name of the new assignee"),s.z.object({accountId:s.z.string().min(1).describe("Account ID of the assignee")}),s.z.object({accountType:s.z.string().min(1).describe("Account type filter (e.g., user, app)")})]).describe("How the new assignee is specified")}).describe("Arguments required to assign a Jira issue to someone"),dr={name:"jira-assign-issue",inputSchema:cr,runTool:async(e,t)=>{try{const r=cr.parse(t);let i;i="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const n=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:i});return et(n?.data??n)}catch(e){throw nt(e)}}},lr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID to remove the assignee from")}).describe("Inputs required to unassign a Jira issue"),ur={name:"jira-unassign-issue",inputSchema:lr,runTool:async(e,t)=>{try{const r=lr.parse(t),i=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return et(i?.data??i)}catch(e){throw nt(e)}}},pr=s.z.object({issueId:s.z.string().min(1).describe("The Jira issue key or numeric ID receiving the comment"),body:s.z.string().min(1).describe("The markdown-compatible text of the comment"),visibility:s.z.object({type:s.z.enum(["role","group"]).describe("Visibility type that restricts the comment to a role or group"),value:s.z.string().min(1).describe("The name of the role or group granted visibility")}).optional().describe("Optional visibility override controlling who can read the comment")}).describe("Arguments for adding a comment to a Jira issue"),mr={name:"jira-comment-add",inputSchema:pr,runTool:async(e,t)=>{try{const r=pr.parse(t),i=e.issueComments;if(!i||"function"!=typeof i.addComment)throw Error("Jira issueComments API is unavailable on the client");const n={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(n.visibility=r.visibility);const s=await i.addComment(n);return et(s?.data??s)}catch(e){throw nt(e)}}},hr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID whose comments should be retrieved"),start:s.z.number().optional().default(0).describe("Zero-based index to start pagination from"),maxResults:s.z.number().optional().default(50).describe("Maximum number of comments to return"),orderBy:s.z.string().optional().describe("Field name to order the returned comments by"),expand:s.z.string().optional().describe("Optional expansion clause for the comment response")}).describe("Parameters for fetching comments on a Jira issue"),gr={name:"jira-comment-list",inputSchema:hr,runTool:async(e,t)=>{try{const r=hr.parse(t),i=e.issueComments;if(!i||"function"!=typeof i.getComments)throw Error("Jira issueComments API is unavailable on the client");const n=await i.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return et(n?.data??n)}catch(e){throw nt(e)}}},yr=s.z.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","is tested by","tests","Is covered by","covered by","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]).describe("The named relationship (Blocks, Relates to, etc.) that describes the link type"),fr=s.z.object({id:s.z.string().optional().describe("Numeric Jira ID used when referencing an issue"),key:s.z.string().optional().describe("Human-readable key of the linked issue")}).describe("An issue reference (ID or key) used when building a link payload"),br=s.z.object({type:s.z.enum(["role","group"]).describe("Visibility scope type attached to the comment"),value:s.z.string().min(1).describe("Name of the role or group granted visibility to the comment")}).describe("Optional visibility settings applied to the comment"),wr=s.z.object({body:s.z.string().optional().describe("Markdown text to include as a linked-comment"),visibility:br.optional().describe("Optional ACL for the comment")}).describe("Optional comment applied at the time the link is created or updated"),vr=s.z.object({link:s.z.object({relationship:yr,inwardIssue:fr,outwardIssue:fr,comment:wr.optional()}).describe("Definition of the link that should be created between two issues")}).describe("Arguments required to create a Jira issue link");let zr=[];function jr(e){return(e||"").trim().toLowerCase()}async function kr(e,t){if(!t)throw Error("Link relationship is required");0===zr.length&&(zr=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(),i=r?.issueLinkTypes??r?.values??r;return Array.isArray(i)?i:[]})(e));const r=jr(t),i=zr.find(e=>[e.name,e.inward,e.outward].some(e=>jr(e)===r));if(!i)throw Error(`No issue link type matching '${t}' found.`);return i}function Ir(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 Sr(e){if(!e)return;const t={};return e.body&&(t.body=Be(e.body)),e.visibility&&(t.visibility=e.visibility),Object.keys(t).length>0?t:void 0}const xr=vr,Tr={name:"jira-link-create",inputSchema:xr,runTool:async(e,t)=>{try{const r=xr.parse(t).link,i={inwardIssue:Ir(r.inwardIssue),outwardIssue:Ir(r.outwardIssue)},n=Sr(r.comment);n&&(i.comment=n);const s=e.issueLinks;if(!s||"function"!=typeof s.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const a=await kr(e,r.relationship);i.type={id:a.id};const o=await s.linkIssues(i);return et(o?.data??o)}catch(e){throw nt(e)}}},Ar=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID receiving the attachment"),file:s.z.string().min(1).describe("Base64 or path to the file contents to upload"),mimeType:s.z.string().optional().describe("Optional MIME type override for the attachment"),comment:s.z.string().optional().describe("Optional comment to associate with the attachment")}).describe("Inputs needed to attach a file to a Jira issue"),Er={name:"jira-attach",inputSchema:Ar,runTool:async(e,r)=>{try{const i=Ar.parse(r),n=c.resolve(i.file),s=await t.promises.readFile(n),a=c.basename(n),o=new FormData;o.append("file",new Blob([s],{type:i.mimeType??"application/octet-stream"}),a);const d=e?.config??null,l=d?.host,u=d?.authentication?.basic??d?.authentication??d?.auth??null,p=u?.email,m=u?.apiToken??u?.apiKey;if(!l||!p||!m)throw Error("Jira client authentication configuration is unavailable for attachments");const h=await fetch(`${l}/rest/api/3/issue/${i.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${p}:${m}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:o});if(!h.ok){const e=await h.text();throw Error(`Jira attachment upload failed (${h.status}): ${e}`)}const g=await h.json();if(i.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:i.issueId,comment:Be(i.comment)})}return et(g)}catch(e){if(e&&e.code&&"string"==typeof e.code&&["ENOENT","EACCES"].includes(e.code))throw Error("Attachment file error: "+e.message);throw nt(e)}}},_r=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID whose attachments should be listed")}).describe("Arguments used to fetch attachments for a Jira issue"),Or={name:"jira-attachment-list",inputSchema:_r,runTool:async(e,t)=>{try{const r=_r.parse(t),i=e.issues;if(!i||"function"!=typeof i.getIssue)throw Error("Jira issues API is unavailable on the client");const n=await i.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),s=n?.data??n;return et({attachments:s?.fields?.attachment??[]})}catch(e){throw nt(e)}}},Jr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID owning the attachment"),attachmentId:s.z.string().min(1).describe("ID of the attachment to delete")}).describe("Arguments required to remove an attachment from Jira"),Dr={name:"jira-attachment-delete",inputSchema:Jr,runTool:async(e,t)=>{try{const r=Jr.parse(t),i=e.issueAttachments;if(!i||"function"!=typeof i.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await i.removeAttachment({id:r.attachmentId}),et({success:!0,message:`Attachment ${t.attachmentId} deleted successfully`})}catch(e){throw nt(e)}}},Cr=s.z.object({issueId:s.z.string().min(1).describe("Target issue key or ID for the worklog entry"),timeSpent:s.z.string().min(1).describe('Time spent text (e.g., "1h 30m")'),comment:s.z.string().optional().describe("Optional worklog comment in markdown"),author:s.z.object({accountId:s.z.string().min(1).describe("Account ID of the user logging the work")}).optional().describe("Optional author override for the worklog entry"),startingOn:s.z.string().optional().describe("Optional timestamp for when the work started (ISO)"),artifact:s.z.string().optional().describe("Optional identifier linking the worklog to another artifact")}).describe("Arguments required to add a worklog entry to a Jira issue"),Nr={name:"jira-worklog-add",inputSchema:Cr,runTool:async(e,t)=>{try{const r=Cr.parse(t),i={timeSpent:r.timeSpent};r.comment&&(i.comment=r.comment),r.author&&(i.author=r.author),r.startingOn&&(i.started=r.startingOn),r.artifact&&(i.artifact=r.artifact);const n=e.issueWorklogs;if(!n||"function"!=typeof n.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const s=await n.addWorklog({issueIdOrKey:r.issueId,...i});return et(s?.data??s)}catch(e){throw nt(e)}}},Hr=r.Logging.for("jira.xray");class qr{constructor(){this.clientId=ge.orThrow().xray.apiUser,this.clientSecret=ge.orThrow().xray.apiSecret,this.baseUrl=ge.orThrow().xray.host||"https://eu.xray.cloud.getxray.app"}async authenticate(){if(!this.clientId||!this.clientSecret)throw Error("Xray API credentials are missing (XRAY__API_USER, XRAY__API_SECRET).");const e=await fetch(this.baseUrl+"/api/v2/authenticate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId,client_secret:this.clientSecret})}),t=await e.text();return this.token=t.replace(/"/g,""),this.token}async graphql(e,t){this.token||await this.authenticate();const r={query:e,variables:t};Hr.info("xray.graphql.request",{payload:ke(r)});try{const e=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify(r)}),t=await e.json();if(Hr.info("xray.graphql.response",{status:e.status,headers:e.headers?.get?e.headers.get("content-type"):void 0,body:ke(t)}),t.errors)throw Hr.error("xray.graphql.errors",{errors:ke(t.errors)}),Error(JSON.stringify(t.errors,null,2));return t.data}catch(e){throw Hr.error("xray.graphql.failure",{error:e+""}),e}}async getTest(e){return(await this.graphql('\n query GetTest($issueId: String!) {\n getTest(issueId: $issueId) {\n issueId\n jira(fields:["key"])\n steps {\n id\n action\n data\n result\n }\n }\n }\n ',{issueId:e})).getTest}async addStep(e,t){return(await this.graphql("\n mutation AddTestStep($issueId: String!, $step: CreateStepInput!) {\n addTestStep(issueId: $issueId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{issueId:e,step:t})).addTestStep}async updateStep(e,t){return(await this.graphql("\n mutation UpdateTestStep($stepId: String!, $step: UpdateStepInput!) {\n updateTestStep(stepId: $stepId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{stepId:e,step:t})).updateTestStep}async deleteStep(e){return(await this.graphql("\n mutation RemoveTestStep($stepId: String!) {\n removeTestStep(stepId: $stepId)\n }\n ",{stepId:e})).removeTestStep}async addSteps(e,t){return Promise.all(t.map(t=>this.addStep(e,t)))}async updateSteps(e){return Promise.all(e.map(e=>this.updateStep(e.stepId,e.step)))}async deleteSteps(e){return Promise.all(e.map(e=>this.deleteStep(e)))}async syncSteps(e,t){const r=(await this.getTest(e)).steps||[],i=[],n=[],s=[];for(let e=0;e<t.length;e++){const s=t[e],a=r[e];a?a.action===s.action&&a.data===s.data&&a.result===s.result||i.push({stepId:a.id,step:s}):n.push(s)}if(r.length>t.length)for(let e=t.length;e<r.length;e++)s.push(r[e].id);await this.addSteps(e,n),await this.updateSteps(i),await this.deleteSteps(s)}}let Pr=null;const Rr=new Map;function Lr(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 i=e.data??e.fields?.Data??e.fields?.data??void 0,n=e.result??e.fields?.Result??e.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof i?i:void 0,result:"string"==typeof n?n:void 0}}async function Mr(e,t){if(!t)throw Error("Issue reference is required when interacting with Xray steps");if(Rr.has(t))return Rr.get(t);if(/^[0-9]+$/.test(t))return Rr.set(t,t),t;const r=e?.issues??e?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const i=await r.getIssue({issueIdOrKey:t,fields:["id"]}),n=i?.id;if(!n)throw Error("Unable to resolve Jira issue ID for "+t);return Rr.set(t,n),n}async function $r(e){if(e?.test?.step)return e.test.step;const t=await(async()=>{if(Pr)return Pr;const e=ge.orThrow().xray.apiUser?.trim(),t=ge.orThrow().xray.apiSecret?.trim();if(!e||!t)throw Error("Xray credentials are missing (XRAY__API_USER, XRAY__API_SECRET). Please configure them before using Xray tools.");const r=Se(),i=new qr,n={async createStep(e,t){const n=await Mr(r,e),s=await i.addStep(n,Lr(t));return{step:s,id:s?.id}},async updateStep(e,t,n){await Mr(r,e);const s=Lr(n),a=await i.updateStep(t.toString(),s);return{step:a,id:a?.id}},deleteStep:async(e,t)=>(await Mr(r,e),{success:!0===await i.deleteStep(t.toString())}),async getSteps(e){const t=await Mr(r,e),n=await i.getTest(t);return{steps:n?.steps??[]}}};return Pr={test:{step:n}},Pr})();if(!t?.test?.step)throw Error("Xray step API is unavailable on the client");return t.test.step}const Fr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID that owns the step"),action:s.z.string().min(1).describe("Action description for the new Xray step"),data:s.z.string().optional().describe("Optional data or context used by this step"),result:s.z.string().optional().describe("Optional expected result for the step")}).describe("Inputs for adding a step to an Xray test case"),Ur={name:"jira-xray-step-add",inputSchema:Fr,runTool:async(e,t)=>{try{const r=Fr.parse(t),i=await $r(e),n={action:r.action,data:r.data,result:r.result};return et(await i.createStep(r.issueId,n))}catch(e){throw nt(e)}}},Wr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID that owns the step"),stepId:s.z.union([s.z.string(),s.z.number()]).describe("Identifier for the step that should be updated"),action:s.z.string().min(1).describe("New action text for the step"),data:s.z.string().optional().describe("Updated data/context for the step"),result:s.z.string().optional().describe("Updated expected result for the step")}).describe("Inputs required to modify an Xray test step"),Kr={name:"jira-xray-step-update",inputSchema:Wr,runTool:async(e,t)=>{try{const r=Wr.parse(t),i=await $r(e),n=r.stepId+"",s={action:r.action,data:r.data,result:r.result};return et(await i.updateStep(r.issueId,n,s))}catch(e){throw nt(e)}}},Br=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID owning the step"),stepId:s.z.union([s.z.string(),s.z.number()]).describe("Identifier of the step to delete")}).describe("Arguments used to remove an Xray test step"),Xr={name:"jira-xray-step-delete",inputSchema:Br,runTool:async(e,t)=>{try{const r=Br.parse(t),i=await $r(e);return await i.deleteStep(r.issueId,r.stepId.toString()),et({success:!0})}catch(e){throw nt(e)}}},Yr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID whose steps should be returned")}).describe("Inputs required to list steps on an Xray test case"),Gr={name:"jira-xray-step-list",inputSchema:Yr,runTool:async(e,t)=>{try{const r=Yr.parse(t),i=await $r(e);return et(await i.getSteps(r.issueId))}catch(e){throw nt(e)}}},Vr=s.z.object({linkId:s.z.string().min(1).describe("Identifier for the Jira issue link to remove")}).describe("Inputs required to delete an existing Jira issue link"),Zr={name:"jira-link-delete",inputSchema:Vr,runTool:async(e,t)=>{try{const r=Vr.parse(t),i=e.issueLinks;if(!i||"function"!=typeof i.deleteIssueLink)throw Error("Jira issueLinks API is unavailable on the client");return await i.deleteIssueLink({linkId:r.linkId}),et({success:!0,message:`Issue link ${r.linkId} deleted successfully`})}catch(e){throw nt(e)}}},Qr=s.z.object({linkId:s.z.string().min(1).describe("ID of the existing issue link to change"),relationship:yr,comment:wr.optional().describe("Optional comment to attach while recreating the link")}).describe("Inputs required to update (recreate) a Jira issue link"),ei={name:"jira-link-update",inputSchema:Qr,runTool:async(e,t)=>{try{const r=Qr.parse(t),i=e.issueLinks;if(!i||"function"!=typeof i.getIssueLink||"function"!=typeof i.deleteIssueLink||"function"!=typeof i.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const n=await i.getIssueLink({linkId:r.linkId}),s=n?.data??n;if(!s)throw Error(`Issue link ${r.linkId} not found`);const a=s.inwardIssue,o=s.outwardIssue;if(!a||!o)throw Error("Issue link payload is missing linked issues");const c=await kr(e,r.relationship);await i.deleteIssueLink({linkId:r.linkId});const d={inwardIssue:Ir(a),outwardIssue:Ir(o),type:{id:c.id}},l=Sr(r.comment);return l&&(d.comment=l),await i.linkIssues(d),et({success:!0,message:`Issue link ${r.linkId} updated to ${r.relationship}`})}catch(e){throw nt(e)}}};function ti(e=[]){return e.map(ri).join("")}function ri(e){switch(e.type){case"text":return(e=>{let t=e.text||"";for(const r of e.marks||[])switch(r.type){case"strong":t=`**${t}**`;break;case"em":t=`*${t}*`;break;case"strike":t=`~~${t}~~`;break;case"code":t="`"+t+"`";break;case"link":t=`[${t}](${r.attrs.href})`}return t})(e);case"mention":return e.attrs.text||"@"+e.attrs.id;case"emoji":return e.attrs.shortName||"";case"inlineCard":return e.attrs.url;case"status":return`:status{color="${e.attrs.color}"}[${e.attrs.text}]`;case"hardBreak":return" \n"}return""}function ii(e){switch(e.type){case"heading":return"#".repeat(e.attrs?.level)+" "+ti(e.content);case"paragraph":return ti(e.content);case"blockquote":return e.content.map(ii).map(e=>"> "+e).join("\n");case"bulletList":case"orderedList":case"taskList":return(e=>{const t=[];let r=1;for(const i of e.content){let n="- ";"orderedList"===e.type&&(n=r+++". "),"taskList"===e.type&&(n="- "+("DONE"===i.attrs?.state?"[x] ":"[ ] "));const s=i.content.map(ii).join(" ");t.push(n+s)}return t.join("\n")})(e);case"table":return(e=>{const t=e.content||[];return t.length?["| "+t[0].content.map(e=>ti(e.content[0].content)).join(" | ")+" |","| "+t[0].content.map(()=>"---").join(" | ")+" |",...t.slice(1).map(e=>e.content.map(e=>ti(e.content[0].content)).join(" | ")).map(e=>"| "+e+" |")].join("\n"):""})(e);case"codeBlock":return"```"+(e.attrs?.language||"")+"\n"+e.content?.map(e=>e.text).join("")+"\n```";case"panel":return(e=>`::panel{type="${e.attrs?.panelType||"info"}"}\n${e.content.map(ii).join("\n")}\n::`)(e);case"rule":return"---";case"mediaSingle":return(e=>{const t=e.content?.[0];return t?"external"===t.attrs?.type?`![](${t.attrs.url})`:"file"===t.attrs?.type?`[attachment](attachment:${t.attrs.id})`:"":""})(e);case"blockCard":return e.attrs?.url}return""}const ni=s.z.object({document:Qt.describe("Jira ADF document you want to translate into Markdown (use jira-md-to-adf to go the other way).")}).describe("Convert Jira ADF documents back to Markdown text for editing or review"),si={name:"jira-adf-to-markdown",inputSchema:ni,runTool:async(e,t)=>{return et({markdown:(r=ni.parse(t).document,(e=>{if(!e||"doc"!==e.type)return"";const t=[];for(const r of e.content||[])t.push(ii(r));return t.join("\n\n")})(r))});var r}},ai={[tt.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ut.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[dt.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}},[sr.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}},[or.name]:{title:"Jira Markdown to ADF",description:"Convert Markdown into a sanitized Jira ADF document so fields.description can be supplied to jira-issue-update and other tools that expect Jira documents",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[si.name]:{title:"Jira ADF to Markdown",description:"Translate Jira ADF documents back into Markdown text so you can edit them before sending them through tooling or LLM prompts (use jira-md-to-adf to get valid ADF inputs).",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[at.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[mt.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[gt.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[dr.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ur.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[mr.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}},[gr.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Tr.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ei.name]:{title:"Jira Link Update",description:"Change the relationship type for an existing issue link",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Zr.name]:{title:"Jira Link Delete",description:"Delete an issue link from Jira",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Er.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Or.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Dr.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Nr.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ur.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Kr.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Xr.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Gr.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 oi(e){const t=r.Logging.for(oi);let i,n=null;try{i=Se()}catch(e){if(!(e instanceof we))return void t.warn("Skipping Jira tool registration; unable to create Jira client",{error:e});n=e,t.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:e})}const s=[tt,ut,dt,sr,or,si,at,mt,gt,dr,ur,mr,gr,Tr,ei,Zr,Er,Or,Dr,Nr,Ur,Kr,Xr,Gr];for(const r of s){const s=ai[r.name];if(s)try{await e.registerTool(r.name,{title:s.title,description:s.description,inputSchema:r.inputSchema,annotations:s.annotations},async e=>{if(!i)throw n??Error("Jira client unavailable because credentials could not be loaded.");return r.runTool(i,e)}),t.info("Registered Jira tool "+r.name)}catch(e){t.error("Failed to register Jira tool "+r.name,{error:e})}}}async function ci(e){await(async e=>{e.registerTool("decaf-server-info",{title:"Decaf MCP Server Info",description:"Return read-only server metadata, version, and registered prompt lists so callers can discover what exposures are available without side effects.",inputSchema:{},outputSchema:void 0,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{const e=oe.map(e=>e.getName()).sort();return{content:[{type:"text",text:["Name: "+ge.name,"Title: "+ge.title,"Version: "+ge.version,"Prompts: "+(e.join(", ")||"<none>")].join("\n")}]}})})(e);const t=r.Logging.for(ci);try{await oi(e)}catch(e){t.error("Failed to register Jira tools",e)}}class di extends C{setCb(e){return this.cb=e,this}setConfig(e){return this.config=e,this}setUriOtTemplate(e){return this.uriOrTemplate=e,this}constructor(e){super(e)}static get builder(){return new di}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 w.UriTemplate(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),i=async(e,t)=>{const r=this.logFor(t);r.verbose(`Requesting resource ${this.name} from ${e.toString()}`);const i=await Promise.resolve(this.cb(e,t));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(i._meta)),i};return e.resource(this.name,t,r,i)}catch(e){throw r.Logging.for(this).error("Error registering resource "+this.name,e),e}}}i.__decorate([n.required(),i.__metadata("design:type",String)],di.prototype,"uriOrTemplate",void 0),i.__decorate([n.required(),i.__metadata("design:type",Function)],di.prototype,"cb",void 0),i.__decorate([n.required(),i.__metadata("design:type",Object)],di.prototype,"config",void 0);const li=X()??x.join(__dirname,"..","assets"),ui=x.join(li,"templates"),pi=x.join(li,"prompts"),mi=x.join(__dirname,"..","assets"),hi=X()||mi,gi=x.join(hi,"resources");function yi(e){const t=x.join(gi,e);return S.readFileSync(t,"utf-8")}const fi="resource://repo.metadata",bi=(()=>{const e=yi("repo-metadata.json");return JSON.parse(e)})(),wi=di.builder.setName("repo.metadata").setTitle("Repository metadata snapshot").setDescription("Deterministic metadata about the decaf-ts MCP server, Jira defaults, and the canonical project key.").setUriOtTemplate(fi).setConfig({mimeType:"application/json",description:"Static repository metadata that documents the MCP surface."}).setCb(async()=>{const e=ge.version,t=ge.jira.projectKey??bi.jira?.projectKey??"DECAF",r={...bi,version:e,projectKey:t};return{contents:[{uri:fi,mimeType:"application/json",text:JSON.stringify(r,null,2)}],_meta:{source:"assets/repo-metadata.json"}}}),vi="resource://decoration.schematic.metadata",zi=yi("decoration/metadata.json"),ji=di.builder.setName("decoration.schematic.metadata").setTitle("Decoration metadata schematic").setDescription("Outlines the annotation and field metadata contracts that decorators expose.").setUriOtTemplate(vi).setConfig({mimeType:"application/json",description:"Annotation metadata definitions for decorator tooling."}).setCb(async()=>({contents:[{uri:vi,mimeType:"application/json",text:zi}],_meta:{schematic:"metadata"}})),ki="resource://decoration.schematic.builder",Ii=yi("decoration/builder.json"),Si=di.builder.setName("decoration.schematic.builder").setTitle("Decoration builder pattern schematic").setDescription("Describes how decorated models spawn builder classes with fluent setters and validation.").setUriOtTemplate(ki).setConfig({mimeType:"application/json",description:"Builder conventions for decorated models."}).setCb(async()=>({contents:[{uri:ki,mimeType:"application/json",text:Ii}],_meta:{schematic:"builder"}})),xi="resource://decoration.schematic.validation",Ti=yi("decoration/validation.json"),Ai=di.builder.setName("decoration.schematic.validation").setTitle("Decoration validation schematic").setDescription("Tracks how decorator metadata flows through validation routines and error serialization.").setUriOtTemplate(xi).setConfig({mimeType:"application/json",description:"Validation lifecycle and error contract for decorated models."}).setCb(async()=>({contents:[{uri:xi,mimeType:"application/json",text:Ti}],_meta:{schematic:"validation"}})),Ei="resource://golden.override.model-builder",_i=yi("golden/model-builder.txt"),Oi=di.builder.setName("golden.override.model-builder").setTitle("Golden override: model builder snippet").setDescription("A coding template that shows how a Model builder keeps setters fluent and enforces validation.").setUriOtTemplate(Ei).setConfig({mimeType:"text/plain",description:"Model builder golden snippet for copy/paste reference."}).setCb(async()=>({contents:[{uri:Ei,mimeType:"text/plain",text:_i}],_meta:{override:"model-builder"}})),Ji="resource://golden.override.validation-errors",Di=yi("golden/validation-errors.json"),Ci=di.builder.setName("golden.override.validation-errors").setTitle("Golden override: validation error report").setDescription("Shows the structure returned when decorator validation fails, including error arrays and metadata.").setUriOtTemplate(Ji).setConfig({mimeType:"application/json",description:"Example validation error payload emitted by decorated models."}).setCb(async()=>({contents:[{uri:Ji,mimeType:"application/json",text:Di}],_meta:{override:"validation-errors"}})),Ni="resource://golden.override.xray-step-template",Hi=yi("golden/xray-step-template.txt"),qi=[wi,ji,Si,Ai,Oi,Ci,di.builder.setName("golden.override.xray-step-template").setTitle("Golden override: Xray step template").setDescription("A compliant Xray test-step template that lists the precondition, action, and verification.").setUriOtTemplate(Ni).setConfig({mimeType:"text/plain",description:"Template for documenting Xray steps."}).setCb(async()=>({contents:[{uri:Ni,mimeType:"text/plain",text:Hi}],_meta:{override:"xray-step-template"}}))];async function Pi(e){const t=r.Logging.for(Pi);for(const r of qi)try{await r.build(e),t.info("Registered resource "+r.getName())}catch(e){t.error("Failed to register resource "+r.getName(),e)}}const Ri=new WeakMap;class Li extends r.LoggedClass{get client(){const e=Ri.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 oe)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 ci(this.client),e.verbose("Registered built-in tools")}catch(e){}try{await Pi(this.client),e.verbose("Registered built-in resources")}catch(e){}try{await(async(e,t)=>{t.info("Registering agent templates as resources...");const r=S.readdirSync(ui).filter(e=>e.endsWith(".md"));for(const i of r){const r=x.basename(i,".md"),n=x.join(ui,i),s=di.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+n).setConfig({mimeType:"text/markdown",description:"Template for "+r}).setCb(async e=>{const t=S.readFileSync(e.pathname,"utf8");return{contents:[{uri:e.toString(),text:t,mimeType:"text/markdown"}],_meta:{}}});try{s.build(e),t.info("Registered template: "+r)}catch(e){t.error(`Failed to register template ${r}:`,e)}}t.info("Registering agent prompts...");const i=S.readdirSync(pi).filter(e=>e.endsWith(".md"));for(const r of i){const i=x.basename(r,".md"),n=x.join(pi,r),a=S.readFileSync(n,"utf8"),o=G.builder.setName(i).setTitle("Prompt: "+i).setDescription("Dynamic prompt for "+i).setArgsSchema(s.z.object({})).setCb(async e=>({messages:[{role:"user",content:{type:"text",text:a}}],_meta:{}}));try{o.build(e),t.info("Registered prompt: "+i)}catch(e){t.error(`Failed to register prompt ${i}:`,e)}}})(this.client,e)}catch(e){}}async boot(e="stdio"){"stdio"===e&&r.Logging.setFactory(A),r.Logging.for(this.constructor.name);const t=((Array.isArray(ge.icons)?ge.icons:[ge.icons])||[]).map(e=>{const t="string"==typeof e?.src?e.src:(e?.src??"")+"",r="string"==typeof e?.mimeType?e.mimeType:(e?.mimeType??"")+"";let i=[];return Array.isArray(e?.sizes)?i=e.sizes.map(e=>e+""):"string"==typeof e?.sizes&&(i=(e.sizes+"").split(",").map(e=>e.trim())),{src:t,mimeType:r,sizes:i}}),i={name:ge.name,title:ge.title,websiteUrl:ge.websiteUrl,version:ge.version,icons:t},n=new v.McpServer(i,{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)=>{Ri.set(e,t)})(this,n),n.onerror=e=>{this.log.error("MCP instance onerror",e)},e){case"stdio":e=new j.StdioServerTransport;break;case"http":e=new k.StreamableHTTPServerTransport({sessionIdGenerator:()=>z.v4(),onsessioninitialized:e=>{},onsessionclosed:e=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(s=e)||"object"!=typeof s||"function"!=typeof s.send&&"function"!=typeof s.close&&"function"!=typeof s.on)throw new d.InternalError("Invalid transport type: "+e)}var s;try{await this.load()}catch(e){throw e}await this.client.connect(e)}}const Mi=(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"),i=JSON.parse(t.readFileSync(r,"utf-8")),n=i.version,{transport:s}=e,a=(new T).for("mcp-server");if("stdio"!==s)throw Error("Unsupported transport mode: "+s);return a.info("Transport stdio"),a.debug(`running with options: ${JSON.stringify(e)} for ${i.name} version ${n}`),(new Li).boot(s)});(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 i=K("package.json"),n=JSON.parse(t.readFileSync(i,"utf-8")),s=n.version;r.Logging.for("md-to-ast").debug(`running with options: ${JSON.stringify(e)} for ${n.name} version ${s}`);const a=Be(await(async()=>{const e=[];for await(const t of process.stdin)e.push(Buffer.from(t));return Buffer.concat(e).toString("utf8")})(),{resolveMention:e=>({id:e,text:"@"+e}),resolveAttachment:e=>({id:e,collection:"attachments"})});process.stdout.write(JSON.stringify(a,null,2)+"\n")});const $i=(new e.Command).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");$i.addCommand(Mi),$i.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("fs/promises"),require("node:util"),require("unified"),require("remark-directive"),require("remark-gfm"),require("remark-parse"),require("@modelcontextprotocol/sdk/shared/uriTemplate.js"),require("@modelcontextprotocol/sdk/server/mcp.js"),require("uuid"),require("@modelcontextprotocol/sdk/server/stdio.js"),require("@modelcontextprotocol/sdk/server/streamableHttp.js")):"function"==typeof define&&define.amd?define(["commander","fs","@decaf-ts/logging","tslib","@decaf-ts/decorator-validation","zod","@decaf-ts/injectable-decorators","@decaf-ts/decoration","path","@decaf-ts/db-decorators","crypto","zlib","url","fs/promises","node:util","unified","remark-directive","remark-gfm","remark-parse","@modelcontextprotocol/sdk/shared/uriTemplate.js","@modelcontextprotocol/sdk/server/mcp.js","uuid","@modelcontextprotocol/sdk/server/stdio.js","@modelcontextprotocol/sdk/server/streamableHttp.js"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).commander,e.fs,e.decafTsLogging,e.tslib,e.decafTsDecoratorValidation,e.zod,e.decafTsInjectableDecorators,e.decafTsDecoration,e.path,e.decafTsDbDecorators,e.crypto,e.zlib,e.url,e.fsPromises,e.node_util,e.unified,e.remarkDirective,e.remarkGfm,e.remarkParse,e.uriTemplate_js,e.mcp_js,e.uuid,e.stdio_js,e.streamableHttp_js);
2
+ var e,t;e=this,t=function(e,t,r,i,n,s,a,o,c,d,l,u,p,m,h,g,y,f,b,w,z,v,j,k){"use strict";function I(e){var t=Object.create(null);return e&&Object.keys(e).forEach(r=>{if("default"!==r){var i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}),t.default=e,Object.freeze(t)}var S=I(t),x=I(c);class T extends r.MiniLogger{constructor(e,t,r){super(e,t,r)}log(e,t,i,n){const s=this.config("level");r.NumericLogLevels[s],r.NumericLogLevels[e]}}const A=(e,t,...r)=>{const i=(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(i,t)};var E,_,O,J,D;(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"})(_||(_={})),(e=>{e[e.FREE=0]="FREE",e[e.LOW=1]="LOW",e[e.MEDIUM=2]="MEDIUM",e[e.HIGH=3]="HIGH"})(O||(O={}));class C extends n.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:i}=e||{};let n="string"==typeof t&&t.length>0?this.log.for(t):this.log;return i&&i.clientId&&(n=n.for(i.clientId)),r&&(n=n.for(r.toString())),n}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}}i.__decorate([n.required(),i.__metadata("design:type",String)],C.prototype,"description",void 0),i.__decorate([n.required(),i.__metadata("design:type",String)],C.prototype,"name",void 0),i.__decorate([n.required(),i.__metadata("design:type",String)],C.prototype,"title",void 0);class N extends C{constructor(e){super(e),this.reasoning=E.NONE,this.effort=_.NONE,this.cost=O.FREE}setReasoning(e){return this.reasoning=e,this}setEffort(e){return this.effort=e,this}setCost(e){return this.cost=e,this}}function H(e){if(!e)return;let t=e,r=t&&t._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)t=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)t=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)t=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)t=r.innerType;else{if(!r.schema)return;t=r.schema}r=t&&t._def}return r&&"ZodObject"===r.typeName?r:void 0}function q(e,t="schema"){if(H(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,i]of Object.entries(r))e[t]=R(i)?i:s.z.any();return s.z.object(e)}}throw Error(`Registration error: provided a non-canonical ${t}. Export a ZodObject (z.object(...)).`)}function P(e){if(!e)return;if(e&&"object"==typeof e&&!e._def)return e.def&&"object"==typeof e.def&&e.def.shape?e.def.shape:e;const t=H(e);return t?"function"==typeof t.shape?t.shape():t.shape||void 0:void 0}function R(e){return!(!e||"object"!=typeof e||!e._def)}i.__decorate([n.required(),i.__metadata("design:type",Number)],N.prototype,"reasoning",void 0),i.__decorate([n.required(),i.__metadata("design:type",Number)],N.prototype,"effort",void 0),i.__decorate([n.required(),i.__metadata("design:type",Number)],N.prototype,"cost",void 0),(e=>{e.ASSETS="assets"})(J||(J={})),(e=>{e.PROMPT="prompts",e.DOCUMENTATION="documentation",e.CODE="code"})(D||(D={}));const L=Buffer.from("DCAF1","ascii");function M(e){if(e.length<L.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!e.subarray(0,L.length).equals(L))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=L.length;const i=e.subarray(r,r+16);r+=16;const n=e.subarray(r,r+12);r+=12;const s=e.subarray(r,r+16);r+=16;const a=e.subarray(r),o=((e,t)=>l.scryptSync(e,t,32))(t,i),c=l.createDecipheriv("aes-256-gcm",o,n);c.setAuthTag(s);const d=Buffer.concat([c.update(a),c.final()]);return u.gunzipSync(d)}function $(e){let r=c.resolve(e);for(;;){if(t.existsSync(c.join(r,"package.json")))return r;const e=c.dirname(r);if(e===r)break;r=e}}const F=process.argv?.[1]?$(c.dirname(c.resolve(process.argv[1]))):void 0,W=(()=>{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=p.fileURLToPath(r)}catch{continue}if(!r.includes("node:internal"))return c.dirname(r)}})(),U=W?$(W):void 0,K=F??U??process.cwd();function B(...e){return c.join(K,...e)}function X(e){let t=e;for(;;){const e=x.join(t,"lib","assets");if(S.existsSync(e))return e;const r=x.join(t,"src","assets");if(S.existsSync(r))return r;const i=x.join(t,"assets");if(S.existsSync(i))return i;const n=x.dirname(t);if(n===t)break;t=n}}function Y(){const e=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(e&&S.existsSync(e))return e;const t=X(__dirname);if(t)return t;const r=process.argv?.[1];if(r){const e=X(x.dirname(r));if(e)return e}const i=[K,process.env.INIT_CWD].filter(Boolean);for(const e of i){const t=X(e);if(t)return t}return B("assets")}let G=class extends r.LoggedClass{constructor(e){super(),this.basePath=e||Y()}listAssets(...e){const t=x.join(this.basePath,...e);return S.readdirSync(t)}listPrompts(){return this.listAssets(D.PROMPT)}getAsset(e,t="md",...r){const i=x.join(this.basePath,...r),n=(e,t=!1)=>{try{return t?M(S.readFileSync(e)).toString("utf-8"):S.readFileSync(e,"utf-8")}catch(e){if("ENOENT"===e.code)return null;throw e}},s=n(x.join(i,`${e}.${t}`),"enc"===t);if(null!==s)return s;const a=n(x.join(i,e+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+x.join(i,`${e}.${t}`))}getAllAssets(e,...t){return this.listAssets(e,...t).reduce((r,i)=>{const n=x.extname(i),s=x.basename(i,n),a=n.replace(/^\./,"")||void 0;return r[s]=this.getAsset(s,a??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 _.MEDIUM;case"low":return O.LOW;case"free":return O.FREE;default:throw new d.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 i=this.getAsset(r.toSnakeCase(e),"json",D.PROMPT,...t);let n;try{n=JSON.parse(i)}catch(r){throw new d.SerializationError(`Failed to parse prompt ${e} in categories ${t}: ${r}`)}return this.toPromptDef(n)}getAllPrompts(...e){const t=this.getAllAssets(D.PROMPT,...e);return Object.entries(t).reduce((t,[r,i])=>{try{t[r]=JSON.parse(i)}catch(t){throw new d.SerializationError(`Failed to parse prompt ${r} in categories ${e}: ${t}`)}return t},t)}};G=i.__decorate([a.injectable(),i.__metadata("design:paramtypes",[String])],G);class V extends N{constructor(e){super(e)}setCb(e){return this.cb=e,this}setArgsSchema(e){return this.argsSchema=e,this}static get builder(){return new V}static patchPrompt(e,t,i,n){const s=(t=Array.isArray(t)?t:Object.keys(t)).filter(e=>!Object.prototype.hasOwnProperty.call(i,e));if(s.length)throw new d.ValidationError("Missing replacements for placeholders: "+s.join(", "));n&&(n.verbose("Patching prompt with placeholders: "+JSON.stringify(t)),n.debug("Values: "+JSON.stringify(i)));const a=t.reduce((e,t)=>(e[t]=i[t],e),{});return r.sf(e,a)}patchPrompt(e,t,r,i){return V.patchPrompt(e,t,r,i||this.log.for(this.patchPrompt))}build(e,t){const r=this.log.for(this.build),i=this.hasErrors();if(i)throw new d.ValidationError(i.toString());try{this.argsSchema&&q(this.argsSchema,"argsSchema");const r=P(this.argsSchema);return e.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(e,r)=>{const i=this.logFor(r);e=Object.assign({},t,e||{}),i.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 n=await Promise.resolve(this.cb(e,r));return i.verbose(`Prompt ${this.name} executed successfully.`),i.debug("Prompt execution meta: "+JSON.stringify(n._meta)),n})}catch(e){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),e),e}}}i.__decorate([a.inject(G),i.__metadata("design:type",G)],V.prototype,"assets",void 0),i.__decorate([n.required(),i.__metadata("design:type",Object)],V.prototype,"cb",void 0),i.__decorate([n.required(),i.__metadata("design:type",s.ZodObject)],V.prototype,"argsSchema",void 0),i.__decorate([o.prop(),i.__metadata("design:type",Object)],V.prototype,"placeholders",void 0);class Z extends V{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);n.Model.fromObject(this,t);const r=new Set((o.Metadata.properties(Z)||[]).filter(e=>!["assets","promptCategory","prefixes","suffixes"].includes(e)));["cb","argsSchema"].forEach(e=>r.add(e));const i=this.hasErrors(...Array.from(r));if(i)throw new d.ValidationError(i.toString());const a=(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,...a.map(e=>e.placeholders||[]),...c.map(e=>e.placeholders||[])].flat())].reduce((e,t)=>(e[t]=s.z.string().describe("The description for "+t),e),{});return this.setArgsSchema(s.z.object(l)),this.setCb((e,t)=>{const r=this.logFor(t).for(Z).for(this.promptCategory).for(this.name);function i(e=[]){return Array.isArray(e)?e:Object.keys(e)}const n=(this.prefixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),s=(this.suffixes||[]).map(e=>this.assets.getPrompt(e,this.promptCategory)),a=this.assets.getPrompt(this.name,this.promptCategory),o=[...new Set([...n.map(e=>i(e.placeholders)).flat(),...s.map(e=>i(e.placeholders)).flat(),...i(a.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...n.map(e=>e.prompt),a.prompt,...s.map(e=>e.prompt)].join("\n\n"),o,e,r)}}],_meta:{}}}),super.build(e)}setReasoning(e){throw new d.InternalError("Named prompt builders don't require callback")}setEffort(e){throw new d.InternalError("Named prompt builders don't require callback")}setCost(e){throw new d.InternalError("Named prompt builders don't require callback")}setDescription(e){throw new d.InternalError("Named prompt builders don't require callback")}setTitle(e){throw new d.InternalError("Named prompt builders don't require callback")}static get builder(){return new Z}}i.__decorate([n.required(),i.__metadata("design:type",String)],Z.prototype,"promptCategory",void 0),i.__decorate([n.list(String),n.minlength(1),i.__metadata("design:type",Array)],Z.prototype,"prefixes",void 0),i.__decorate([n.minlength(1),n.list(String),i.__metadata("design:type",Array)],Z.prototype,"suffixes",void 0);const Q=V.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc helper prompt").setDescription("Interactive JSDoc helper that mirrors common doc-health prompts; provide a gist to steer the assistant.").setArgsSchema(s.z.object({gist:s.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}}}),ee=Object.assign(Q,{name:Q.getName()});var te;function re(e,t=[],r=[]){const i=Z.builder.setCategory(te.DOCS).setName(e);return["prefix",...t].forEach(e=>i.addPrefix(e)),["suffix",...r].forEach(e=>i.addSuffix(e)),i}(e=>{e.DOCS="documentation",e.CODE="code"})(te||(te={}));const ie=[re("class"),re("constant"),re("decorator"),re("function"),re("module"),re("file"),re("repo",[],["iterate"])],ne=s.z.object({className:s.z.string().describe("the class name to turn into a builder")}),se=V.builder.setName("ts-code-dp-builder").setTitle("Typescript builder design pattern prompt").setDescription("Generate a builder pattern implementation for a class so the assistant knows to emit chained setters plus Model validation.").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:{}})),ae=e=>{const t=Object.entries(e||{}).filter(([,e])=>null!=e);return t.length?t.map(([e,t])=>`- ${e}: ${JSON.stringify(t)}`).join("\n"):"- no input provided; ask a clarifying question if necessary."},oe=(e,t)=>{const r=e.resources.length?e.resources.join(", "):"none";return[e.description,"","Scenario:\n"+e.scenario,"","Resources: "+r,"\nProvided inputs:",ae(t),"\nCall specification:",e.callTemplate,"\nGuidance:",(i=e.guidance,i.map((e,t)=>`${t+1}. ${e}`).join("\n"))].join("\n");var i},ce=[ee,...ie,se,...[{name:"guide-file-summarizer-tool",title:"MCP guide: file summarizer",description:"Explain how to obtain a concise preview of a file before discussing its contents or instructing other tools.",toolName:"file-summarizer",scenario:"Before referencing or editing a file, invoke this tool to gather a short summary of the opening lines.",resources:["resource://repo.metadata"],guidance:["Default to README.md when the user does not specify a path and call out that the summary is truncated to the first ten meaningful lines.","Trace any hiccups (file not found / permission issues) through the tool\u2019s structured result so the agent can resolve the path before editing."],argsSchema:s.z.object({filePath:s.z.string().optional()}),callTemplate:'{\n "name": "file-summarizer",\n "arguments": {\n "filePath": "<optional-path>"\n }\n}'},{name:"guide-server-info-tool",title:"MCP guide: server info",description:"Show how to use the server diagnostics tool to list registered prompts, versions, and capabilities without side effects.",toolName:"decaf-server-info",scenario:"When you need to confirm what prompts and metadata the MCP server currently exposes.",resources:["resource://repo.metadata"],guidance:["Treat the server info response as read-only configuration data that helps you decide which prompts to invoke next.","Do not rely on stale memory; re-run this tool if the environment might have changed."],argsSchema:s.z.object({}),callTemplate:'{\n "name": "decaf-server-info",\n "arguments": {}\n}'},{name:"jira-guide-issue-create-tool",title:"Jira guide: issue create",description:"Turn user requests into the structured fields that `jira-issue-create` expects, then call the tool.",toolName:"jira-issue-create",scenario:"Whenever a new ticket, task, or story must be created from requirements or spec notes.",resources:["resource://repo.metadata","resource://decoration.schematic.metadata"],guidance:["Confirm the project key from metadata when it is not in the inputs and prefer the canonical repo name.","Gather summary, description, issueType, and any extra `fields` before calling the tool; do not call within the prompt itself.","Present an action preview that lists the fields and mentions attachments or links that might also be created."],argsSchema:s.z.object({project:s.z.string().optional(),issueType:s.z.string().optional(),summary:s.z.string().optional(),description:s.z.string().optional(),assignee:s.z.string().optional(),fields:s.z.record(s.z.string(),s.z.any()).optional()}).partial(),callTemplate:'{\n "name": "jira-issue-create",\n "arguments": {\n "project": { "key": "<project>" },\n "issuetype": { "name": "<issueType>" },\n "summary": "<summary>",\n "description": "<description>",\n "assignee": "<assignee>",\n "fields": { ... }\n }\n}'},{name:"jira-guide-issue-read-tool",title:"Jira guide: issue read",description:"Explain when and how to fetch live issue data with `jira-issue-read` before referencing it.",toolName:"jira-issue-read",scenario:"Before reporting the state of a Jira ticket or quoting field values.",resources:["resource://repo.metadata"],guidance:["Always prefer the issue ID or key provided in the argument; ask clarifying questions if missing.","Mention which fields you need (description, status, comments) so the tool can optimize the call, then rely on the fresh payload instead of memory."],argsSchema:s.z.object({issueId:s.z.string().optional(),issueKey:s.z.string().optional(),fields:s.z.array(s.z.string()).optional()}).partial(),callTemplate:'{\n "name": "jira-issue-read",\n "arguments": {\n "issueId": "<id>",\n "fields": ["summary", "status", "description"]\n }\n}'},{name:"jira-guide-issue-list-tool",title:"Jira guide: issue list",description:"Map exploratory or filtering requests into safe calls to `jira-issue-list`.",toolName:"jira-issue-list",scenario:"When the user wants to discover tickets that match a summary, project, or JQL filter.",resources:["resource://repo.metadata"],guidance:["Translate the requirements into explicit filters or JQL before invoking the tool.","Respect pagination hints and summarize how many tickets the tool should return in the action preview."],argsSchema:s.z.object({jql:s.z.string().optional(),filters:s.z.record(s.z.string(),s.z.any()).optional(),limit:s.z.number().optional(),order:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-list",\n "arguments": {\n "jql": "<JQL>",\n "filters": { ... },\n "startAt": 0,\n "maxResults": <limit>\n }\n}'},{name:"jira-guide-issue-update-tool",title:"Jira guide: issue update",description:"Document how to gather updates before calling `jira-issue-update` so the user\u2019s request is satisfied.",toolName:"jira-issue-update",scenario:"When a ticket needs field changes, transitions, or property toggles.",resources:["resource://repo.metadata","resource://decoration.schematic.builder"],guidance:["Call `jira-issue-read` first if you need the latest state before updating.","Describe the delta (fields being changed) in the action preview and encode them under the `fields` argument.","Include a comment or transition info if the change ought to be annotated."],argsSchema:s.z.object({issueId:s.z.string().optional(),fields:s.z.record(s.z.string(),s.z.any()).optional(),comment:s.z.string().optional(),transition:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-update",\n "arguments": {\n "issueId": "<id>",\n "fields": { ... },\n "comment": "<comment>",\n "transition": "<transition>"\n }\n}'},{name:"jira-guide-issue-delete-tool",title:"Jira guide: issue delete",description:"Warn when to permanently delete an issue via `jira-issue-delete` and how to confirm it.",toolName:"jira-issue-delete",scenario:"When a ticket must be removed or cleaned up after duplication.",resources:["resource://repo.metadata"],guidance:["Double-check permissions and confirm the issue ID; do not delete unless the user explicitly accepts data loss.","Call out whether subtasks should be removed via `deleteSubtasks`."],argsSchema:s.z.object({issueId:s.z.string().optional(),deleteSubtasks:s.z.boolean().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-delete",\n "arguments": {\n "issueId": "<id>",\n "deleteSubtasks": <true|false>\n }\n}'},{name:"jira-guide-issue-transition-tool",title:"Jira guide: issue transition",description:"Define the process for transitioning a Jira issue and invoking `jira-issue-transition`.",toolName:"jira-issue-transition",scenario:"When a ticket needs a workflow change such as To Do \u2192 In Progress \u2192 Done.",resources:["resource://repo.metadata","resource://decoration.schematic.validation"],guidance:["Check available transitions with `jira-transition-list` before deciding which one to run.","Document the business reason in the comment argument to aid reviewers."],argsSchema:s.z.object({issueId:s.z.string().optional(),transition:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-issue-transition",\n "arguments": {\n "issueId": "<id>",\n "transition": "<transition>",\n "comment": "<comment>"\n }\n}'},{name:"jira-guide-transition-list-tool",title:"Jira guide: transition list",description:"Explain how to use `jira-transition-list` to inspect available workflow steps before triggering one.",toolName:"jira-transition-list",scenario:"When you need to know which transitions are possible for a ticket before calling the transition tool.",resources:["resource://repo.metadata"],guidance:["Always capture the transition names and IDs to reference in the action preview.","Only call `jira-issue-transition` after confirming the desired transition exists."],argsSchema:s.z.object({issueId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-transition-list",\n "arguments": {\n "issueId": "<id>"\n }\n}'},{name:"jira-guide-assign-issue-tool",title:"Jira guide: assign issue",description:"Describe how to safely assign or reassign ownership via `jira-assign-issue`.",toolName:"jira-assign-issue",scenario:"When a ticket should be assigned or moved between assignees.",resources:["resource://repo.metadata"],guidance:["Translate user mentions or names into account IDs and include them in the call.","Mention why the reassignment is happening in your action preview to keep the workflow transparent."],argsSchema:s.z.object({issueId:s.z.string().optional(),assignee:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-assign-issue",\n "arguments": {\n "issueId": "<id>",\n "assignee": { "accountId": "<id>" }\n }\n}'},{name:"jira-guide-unassign-issue-tool",title:"Jira guide: unassign issue",description:"Explain the steps for removing an assignee using `jira-unassign-issue`.",toolName:"jira-unassign-issue",scenario:"When the user wants to unassign an owner to make the ticket available.",resources:["resource://repo.metadata"],guidance:["Document whether the ticket should remain unassigned or be moved immediately to someone else.","Confirm there is no auto-assignment policy that will conflict with the unassign action."],argsSchema:s.z.object({issueId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-unassign-issue",\n "arguments": {\n "issueId": "<id>"\n }\n}'},{name:"jira-guide-comment-add-tool",title:"Jira guide: comment add",description:"Clarify how to craft a structured comment (tiered sections, mentions) and call `jira-comment-add`.",toolName:"jira-comment-add",scenario:"When you need to capture findings, reviews, or blockers on a ticket.",resources:["resource://repo.metadata"],guidance:["Use panels, mentions, and sections when describing blockers or decisions.","Reference the relevant attachments or links and mention next steps."],argsSchema:s.z.object({issueId:s.z.string().optional(),comment:s.z.string().optional(),visibility:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-comment-add",\n "arguments": {\n "issueId": "<id>",\n "comment": "<markdown comment>",\n "visibility": "<role>"\n }\n}'},{name:"jira-guide-comment-list-tool",title:"Jira guide: comment list",description:"Indicate when to fetch the comment trail via `jira-comment-list`.",toolName:"jira-comment-list",scenario:"When decisions or conversations need to be reviewed before adding new comments.",resources:["resource://repo.metadata"],guidance:["Specify pagination or filters so you only pull the required batch of comments.","Summarize the key threads in the action preview before calling the tool again to append."],argsSchema:s.z.object({issueId:s.z.string().optional(),page:s.z.number().optional()}).partial(),callTemplate:'{\n "name": "jira-comment-list",\n "arguments": {\n "issueId": "<id>",\n "page": 0,\n "maxResults": 25\n }\n}'},{name:"jira-guide-link-create-tool",title:"Jira guide: link create",description:"Describe how to link issues (e.g., tests to specs) and call `jira-link-create`.",toolName:"jira-link-create",scenario:"When a ticket must be related to another via tested-by, duplicates, or dependees.",resources:["resource://repo.metadata"],guidance:["Include a short note on why the link exists so reviewers can trace the intent.","Verify that both issue keys exist before calling the tool; fetch via `jira-issue-read` if necessary."],argsSchema:s.z.object({inwardIssue:s.z.string().optional(),outwardIssue:s.z.string().optional(),linkType:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-link-create",\n "arguments": {\n "inwardIssue": "<inward>",\n "outwardIssue": "<outward>",\n "linkType": "<relation>",\n "comment": "<note>"\n }\n}'},{name:"jira-guide-link-update-tool",title:"Jira guide: link update",description:"Detail how to change an existing link type with `jira-link-update`.",toolName:"jira-link-update",scenario:"When the relationship between two issues needs to change (e.g., blocks \u2192 relates to).",resources:["resource://repo.metadata"],guidance:["Document the desired new relationship and why the previous one no longer applies.","List the link ID you are targeting so the tool updates precisely that connection."],argsSchema:s.z.object({linkId:s.z.string().optional(),linkType:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-link-update",\n "arguments": {\n "linkId": "<id>",\n "linkType": "<new relation>"\n }\n}'},{name:"jira-guide-link-delete-tool",title:"Jira guide: link delete",description:"Explain how to remove an incorrect or outdated link with `jira-link-delete`.",toolName:"jira-link-delete",scenario:"When a previously created link must be removed or replaced.",resources:["resource://repo.metadata"],guidance:["Ensure you reference the correct link ID and confirm both issues still exist.","Mention why the link is no longer valid to keep the audit trail clear."],argsSchema:s.z.object({linkId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-link-delete",\n "arguments": {\n "linkId": "<id>"\n }\n}'},{name:"jira-guide-attach-issue-tool",title:"Jira guide: attach file",description:"Describe when to upload artifacts with `jira-attach-issue` and how to include comments.",toolName:"jira-attach-issue",scenario:"When the user references logs, screenshots, or generated files that should be attached.",resources:["resource://repo.metadata"],guidance:["State which files are being attached and describe their purpose in the preview comment.","Ensure the file path is accessible and safe for the tool to read before calling it."],argsSchema:s.z.object({issueId:s.z.string().optional(),filePath:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-attach-issue",\n "arguments": {\n "issueId": "<id>",\n "filePath": "<path>",\n "comment": "<note>"\n }\n}'},{name:"jira-guide-attachment-list-tool",title:"Jira guide: attachment list",description:"Explain when to list attachments before adding or deleting files.",toolName:"jira-attachment-list",scenario:"When you need to verify existing attachments prior to uploading or removing files.",resources:["resource://repo.metadata"],guidance:["Capture the attached file names so you can reference the correct ID for deletion.","Use pagination hints if the ticket has many attachments."],argsSchema:s.z.object({issueId:s.z.string().optional(),page:s.z.number().optional()}).partial(),callTemplate:'{\n "name": "jira-attachment-list",\n "arguments": {\n "issueId": "<id>",\n "page": 0\n }\n}'},{name:"jira-guide-attachment-delete-tool",title:"Jira guide: attachment delete",description:"Describe how to delete a specific attachment with `jira-attachment-delete`.",toolName:"jira-attachment-delete",scenario:"When an attachment is obsolete, sensitive, or incorrect.",resources:["resource://repo.metadata"],guidance:["Confirm you have the attachment ID from the listing step to avoid removing the wrong file.","Summarize why the attachment is being removed in the action preview."],argsSchema:s.z.object({issueId:s.z.string().optional(),attachmentId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-attachment-delete",\n "arguments": {\n "issueId": "<id>",\n "attachmentId": "<attachment>"\n }\n}'},{name:"jira-guide-worklog-add-tool",title:"Jira guide: worklog add",description:"Clarify how to log time against an issue with `jira-worklog-add`.",toolName:"jira-worklog-add",scenario:"When the user reports effort spent on a ticket and needs to record it.",resources:["resource://repo.metadata"],guidance:["Convert natural language durations into Jira-friendly strings and include the context of the work.","Mention whether the log should be visible to everyone or restricted."],argsSchema:s.z.object({issueId:s.z.string().optional(),timeSpent:s.z.string().optional(),comment:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-worklog-add",\n "arguments": {\n "issueId": "<id>",\n "timeSpent": "<duration>",\n "comment": "<details>"\n }\n}'},{name:"jira-guide-markdown-to-adf-tool",title:"Jira guide: markdown to ADF",description:"Summarize when to pre-process Markdown into Jira ADF before calling other tools.",toolName:"jira-markdown-to-adf",scenario:"When you need to send Markdown content into Jira fields (descriptions, comments) through other tools.",resources:["resource://repo.metadata","resource://golden.override.model-builder"],guidance:["Use this conversion whenever you cannot guarantee that Jira will accept raw Markdown.","Keep the resulting ADF document handy for downstream calls (issue-update, comment-add, etc.)."],argsSchema:s.z.object({markdown:s.z.string().optional(),context:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-markdown-to-adf",\n "arguments": {\n "markdown": "<text>",\n "context": "<purpose>"\n }\n}'},{name:"jira-guide-adf-to-markdown-tool",title:"Jira guide: ADF to Markdown",description:"Describe why to convert Jira ADF back into Markdown for editing.",toolName:"jira-adf-to-markdown",scenario:"When a user needs to edit a field that already contains ADF (comments/descriptions).",resources:["resource://repo.metadata"],guidance:["Convert the ADF, revise it, then re-run markdown-to-adf if you plan to push it back through Jira.","Keep the Markdown summary in the action preview for reviewers."],argsSchema:s.z.object({adf:s.z.any().optional()}).partial(),callTemplate:'{\n "name": "jira-adf-to-markdown",\n "arguments": {\n "adf": <ADF payload>\n }\n}'},{name:"jira-guide-xray-step-add-tool",title:"Jira guide: Xray step add",description:"Explain how to add a test step from the golden template to a test case via `jira-xray-step-add`.",toolName:"jira-xray-step-add",scenario:"When you document new verification steps for an automated or manual test case.",resources:["resource://repo.metadata","resource://golden.override.xray-step-template"],guidance:["Reference the golden step template before composing the new instruction.","Include both the action and verification so reviewers immediately know the expected result."],argsSchema:s.z.object({testCaseKey:s.z.string().optional(),step:s.z.string().optional(),status:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-add",\n "arguments": {\n "testCaseKey": "<key>",\n "step": "<description>",\n "status": "<PASS|FAIL|TODO>"\n }\n}'},{name:"jira-guide-xray-step-update-tool",title:"Jira guide: Xray step update",description:"Document how to update an existing Xray step via `jira-xray-step-update`.",toolName:"jira-xray-step-update",scenario:"When a test step needs corrections to instructions or expected results.",resources:["resource://repo.metadata","resource://golden.override.xray-step-template"],guidance:["Summarize the delta (what\u2019s changing) before calling the tool so the reviewer knows the context.","Be precise with the `stepId` to avoid editing the wrong step."],argsSchema:s.z.object({testCaseKey:s.z.string().optional(),stepId:s.z.string().optional(),update:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-update",\n "arguments": {\n "testCaseKey": "<key>",\n "stepId": "<id>",\n "update": "<new text>"\n }\n}'},{name:"jira-guide-xray-step-delete-tool",title:"Jira guide: Xray step delete",description:"Explain why you would remove a test step and how to use `jira-xray-step-delete`.",toolName:"jira-xray-step-delete",scenario:"When a chore is no longer relevant and its step should be removed.",resources:["resource://repo.metadata"],guidance:["Confirm the step ID and test case key using the list or read tools before deleting.","Document the reason for removal so auditors understand the change."],argsSchema:s.z.object({testCaseKey:s.z.string().optional(),stepId:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-delete",\n "arguments": {\n "testCaseKey": "<key>",\n "stepId": "<id>"\n }\n}'},{name:"jira-guide-xray-step-list-tool",title:"Jira guide: Xray step list",description:"Describe how to inspect the existing Xray steps before editing or deleting them.",toolName:"jira-xray-step-list",scenario:"When you should view the existing test steps to confirm numbering or status.",resources:["resource://repo.metadata"],guidance:["Report the step IDs and descriptions in your preview so you can reference them later.","Use the list data instead of memory to keep numbering accurate."],argsSchema:s.z.object({testCaseKey:s.z.string().optional()}).partial(),callTemplate:'{\n "name": "jira-xray-step-list",\n "arguments": {\n "testCaseKey": "<key>"\n }\n}'}].map(e=>V.builder.setName(e.name).setTitle(e.title).setDescription(e.description).setArgsSchema(e.argsSchema).setCb(async(t={},r)=>({messages:[{role:"user",content:{type:"text",text:oe(e,t)}}],structuredContent:{tool:e.toolName,args:t},result:{tool:e.toolName,args:t},_meta:{}})))];class de extends N{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 de}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{this.inputSchema&&q(this.inputSchema,"inputSchema"),this.outputSchema&&q(this.outputSchema,"outputSchema");const t=P(this.inputSchema),r=P(this.outputSchema);return e.registerTool(this.name,{title:this.title,description:this.description,inputSchema:t,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(e,t)=>{const r=this.logFor(t);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(e)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const i=await Promise.resolve(this.cb(e,t));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(i._meta)),i})}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}}}i.__decorate([n.required(),i.__metadata("design:type",Object)],de.prototype,"annotations",void 0),i.__decorate([n.required(),i.__metadata("design:type",Object)],de.prototype,"cb",void 0),i.__decorate([n.required(),i.__metadata("design:type",Function)],de.prototype,"inputSchema",void 0);const le=c.resolve(process.cwd(),"README.md"),ue=de.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summarizes a file so the model knows the gist before making decisions; defaults to README.md when no path is supplied.").setInputSchema(s.z.object({filePath:s.z.string().optional()})).setCb(async e=>{const t=e?.filePath?c.resolve(process.cwd(),e.filePath):le;let r,i="ok";try{r=(await m.readFile(t,"utf8")).split(/\r?\n/).filter(e=>e.trim().length>0).slice(0,10).join(" ").slice(0,800),r=r||"(file contained no readable content)"}catch(t){i="error";const n=t instanceof Error?t.message:"unknown error reading file";r=`Unable to summarize ${e?.filePath??"README.md"}: ${n}`}const n={filePath:t,status:i,summary:r};return{content:[{type:"text",text:r}],structuredContent:n,result:n}});function pe(){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 i=c.dirname(e);if(i===e)break;e=i}}catch{}return{}}Object.assign(ue,{name:ue.getName()});const me=pe().version??"0.0.0",he=pe().name??"unknown";o.Metadata.registerLibrary(he,me);const ge={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:me,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:K,assetDir:Y(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0,timeout:process.env.JIRA__TIMEOUT?parseInt(process.env.JIRA__TIMEOUT):1e3,rateLimitRetryDelayMs:process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS?parseInt(process.env.JIRA__RATE_LIMIT_RETRY_DELAY_MS):3e3},xray:{host:process.env.XRAY__HOST||process.env.XRAY__API_HOST||"https://xray.cloud.getxray.app",apiUser:process.env.XRAY__API_USER||"",apiSecret:process.env.XRAY__API_SECRET||""},level:r.LogLevel.error},ye=r.LoggedEnvironment.accumulate(ge);function fe(){const{host:e,email:t,apiKey:r,projectKey:i,issueType:n}=ye.jira;return{host:e?.trim(),email:t?.trim(),apiKey:r?.trim(),projectKey:i?.trim(),issueType:n?.trim(),parentIssue:ye.jira.parentIssue?.trim()}}function be(){const e=fe();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 we(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(ye);class ze extends Error{constructor(e){const t=be(),r=(e=>{const t=be();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(we).join("\n")}`})(e);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=t,this.missing=e,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,ze)}}const ve=r.Logging.for("jira.client"),je=/(authorization|cookie)/i;function ke(e){if(!e)return;const t=e.baseURL??"",r=e.url??"";return t&&r?`${t.endsWith("/")?t.slice(0,-1):t}/${r.startsWith("/")?r.slice(1):r}`:r||t||void 0}function Ie(e){if(void 0!==e){if("string"==typeof e)return e;try{return JSON.stringify(e,null,2)}catch(t){return h.inspect(e,{depth:null})}}}function Se(e){if(!e)return;const t={};return Object.entries(e).forEach(([e,r])=>{t[e]=je.test(e)&&r?"[REDACTED]":r}),t}function xe(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:i,apiKey:n}=(()=>{const e=fe(),t=be().filter(e=>e.required&&!e.value);if(t.length>0)throw new ze(t);return{host:e.host,email:e.email,apiKey:e.apiKey}})(),s=new t({host:r.startsWith("http://")||r.startsWith("https://")?r:"https://"+r,authentication:{basic:{email:i,apiToken:n}},baseRequestConfig:{headers:{Accept:"application/json","Content-Type":"application/json"}}});return(e=>{if(!e)return;const t="__jiraLoggingAttached";e[t]||(e[t]=!0,e.interceptors.request.use(e=>{e.headers=(e=>{const t={...e||{}};return Object.keys(t).some(e=>"accept"===e.toLowerCase())||(t.Accept="application/json"),Object.keys(t).some(e=>"content-type"===e.toLowerCase())||(t["Content-Type"]="application/json"),t})(e.headers);const t=(e.method??"GET").toString().toUpperCase(),r=ke(e);return ve.info("jira.request",{method:t,url:r,headers:Se(e.headers),params:e.params,data:Ie(e.data)}),e},e=>(ve.error("jira.request.error",{message:e.message}),Promise.reject(e))),e.interceptors.response.use(e=>{const t=(e.config?.method??"GET").toString().toUpperCase(),r=ke(e.config);return ve.info("jira.response",{method:t,url:r,status:e.status,headers:Se(e.headers),data:Ie(e.data)}),e},e=>{const t=e.config,r=e.response,i=(t?.method??"GET").toString().toUpperCase(),n=ke(t);return ve.error("jira.response.error",{method:i,url:n,status:r?.status,headers:Se(r?.headers),data:Ie(r?.data),message:e.message}),Promise.reject(e)}))})(s.instance),s}const Te=s.z.object({name:s.z.string().min(1).optional().describe("Optional template name that pre-populates additional fields"),content:s.z.string().min(1).describe("Markdown template content to apply when constructing the description"),placeholders:s.z.record(s.z.string(),s.z.string()).optional().describe("Map of placeholder replacements used by the template")}).describe("Template metadata used to adjust the created description"),Ae=s.z.object({template:Te.optional().describe("Optional template settings for this create request")}).describe("Additional template controls available when creating an issue"),Ee=s.z.union([s.z.object({fields:s.z.record(s.z.string(),s.z.any()).describe("Full raw field map that gets delivered to Jira")}).merge(Ae).describe("Create argument that supplies every field explicitly"),s.z.object({summary:s.z.string().min(1).describe("Title or summary of the new issue"),projectKey:s.z.string().min(1).describe("Project key where the issue is created"),issueType:s.z.string().min(1).describe("Type name for the new issue (story, task, etc.)"),description:s.z.string().optional().describe("Optional textual description for the issue")}).merge(Ae).describe("Create argument with minimal required identifiers plus optional description")]).describe("Union describing how to create an issue either via raw fields or shorthand properties");function _e(e,t,r){const i=((e.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!i)return null;const n=i[2],s=r.resolveAttachment?.(n);return s?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:s.id,collection:s.collection??"attachments"}}]}}:null}function Oe(e,t){if(!e)return[];if(!t.enableAtMentions&&!t.enableEmojiShortcodes)return[{type:"text",text:e}];let r=0;const i=[],n=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,s=/:([a-z0-9_+-]{1,64}):/gi;for(;r<e.length;){const a=De(t.enableAtMentions?Je(n,e,r):null,t.enableEmojiShortcodes?Je(s,e,r):null);if(!a){i.push({type:"text",text:e.slice(r)});break}if(a.index>r&&i.push({type:"text",text:e.slice(r,a.index)}),"mention"===a.kind){const{full:e,groups:n}=a,s=n[0]??"",o=n[1]??"";s&&i.push({type:"text",text:s});const c=t.resolveMention?.(o);c?i.push({type:"mention",attrs:{id:c.id,text:c.text}}):i.push({type:"text",text:"@"+o}),r=a.index+e.length;continue}if("emoji"===a.kind){const{full:e,groups:n}=a,s=`:${n[0]}:`,o=t.resolveEmoji?.(s);i.push({type:"emoji",attrs:o?{shortName:o.shortName,text:o.text}:{shortName:s}}),r=a.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})(i)}function Je(e,t,r){e.lastIndex=r;const i=e.exec(t);if(!i)return null;const n=e.source.includes("@")?"mention":"emoji";return{index:i.index,full:i[0],groups:i.slice(1),kind:n}}function De(e,t){return e?t&&e.index>t.index?t:e:t}function Ce(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 Ne(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 He(e){const t=((e??"")+"").toLowerCase().trim();return!t||"neutral"!==t&&"green"!==t&&"yellow"!==t&&"red"!==t&&"blue"!==t&&"purple"!==t?null:t}function qe(e,t){const r=[];for(const i of e??[])if(i?.type)if("text"!==i.type)if("strong"!==i.type)if("emphasis"!==i.type)if("delete"!==i.type)if("inlineCode"!==i.type)if("break"!==i.type){if("link"===i.type){const e=(i.url??"")+"",n=Re(i.children??[],e),s=_e(i,0,t);if(s){"inline"===s.type?r.push(s.node):r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:e}}]});continue}if(t.enableSmartCards&&Le(n,e)){r.push({type:"inlineCard",attrs:{url:e}});continue}r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:e}}]});continue}if("textDirective"===i.type&&"status"===i.name){const e=Ce(i)||"Status",t=He(i.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:e,color:t}});continue}if("textDirective"===i.type&&"emoji"===i.name){const e=Me(i);r.push($e(e,t));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(i.value??"")+"",marks:[{type:"code"}]});else r.push(...Pe(qe(i.children??[],t),{type:"strike"}));else r.push(...Pe(qe(i.children??[],t),{type:"em"}));else r.push(...Pe(qe(i.children??[],t),{type:"strong"}));else r.push(...Oe((i.value??"")+"",t));return r.filter(e=>!("text"===e.type&&""===(e.text??"")))}function Pe(e,t){return e.map(e=>{if("text"!==e.type)return e;if(e.marks?.some(e=>"code"===e.type))return e;const r=e.marks?[...e.marks,t]:[t];return{...e,marks:r}})}function Re(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(Re(t.children??[],""));return r.join("")||t}function Le(e,t){const r=(e??"").trim(),i=(t??"").trim();return r===i&&/^https?:\/\//i.test(i)}function Me(e){return(e.children??[]).map(e=>"text"===e.type?(e.value??"")+"":"").join("").trim()||""}function $e(e,t){const r=e.startsWith(":")?e:`:${e}:`,i=t.resolveEmoji?.(r);return i?{type:"emoji",attrs:{shortName:i.shortName,text:i.text}}:{type:"emoji",attrs:{shortName:r}}}function Fe(e){return e?"string"==typeof e?e:"text"===e.type||"inlineCode"===e.type?(e.value??"")+"":Array.isArray(e.children)?e.children.map(Fe).join(""):"":""}function We(e,t){if(!e?.type)return null;if((e=>"containerDirective"===e?.type&&"panel"===e?.name)(e))return((e,t)=>{const r=e.attributes??{},i=Ne(r.type)??"info",n="string"==typeof r.title?r.title:void 0,s=(e.children??[]).map(e=>We(e,t)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:i,...n?{panelType:i,title:n}:{panelType:i}},content:s.length?s:[{type:"paragraph",content:[]}]}})(e,t);switch(e.type){case"heading":return{type:"heading",attrs:{level:Ke(e.depth??1,1,6)},content:qe(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 i=(r.url??"")+"";return i?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:i}}]}:null})(e);return r||{type:"paragraph",content:qe(e.children??[],t)}}case"blockquote":return{type:"blockquote",content:(e.children??[]).map(e=>We(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 i=0;for(const n of e.children??[]){if("boolean"!=typeof n.checked)continue;i+=1;const e=(n.children??[]).map(e=>We(e,t)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+i,state:n.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=>We(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&&r.includes("mermaid")?"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:qe(e.children??[],t)}]}))}))}))(e,t);case"leafDirective":return"status"===e.name?(e=>{const t=He((e.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:Ce(e)||"Status",color:t}}]}})(e):"panel"===e.name?((e,t)=>{const r=e.attributes??{},i=Ne(r.type)??"info",n="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:i,...n?{title:n}:{}},content:[{type:"paragraph",content:qe([{type:"text",value:Ce(e)}],t)}]}})(e,t):Ue(e,t);default:return Ue(e,t)}}function Ue(e,t){if("drop"===t.unknownNodeStrategy)return null;const r=Fe(e);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function Ke(e,t,r){const i=Number.isFinite(e)?Math.trunc(e):t;return Math.max(t,Math.min(r,i))}const Be={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function Xe(e,t={}){const r={...Be,...t},i=e??"",n=g.unified().use(b).use(y).use(f),s=n.parse(i),a=n.runSync(s);return Ye(a),((e,t)=>{const r=[];for(const i of e.children??[]){const e=We(i,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 i=r.attrs?.url;return i?[{type:"blockCard",attrs:{url:i}}]:e})(e)).flat();return{...e,content:r}})({version:1,type:"doc",content:r},t)})(a,r)}function Ye(e){if(!e||!Array.isArray(e.children))return;const t=[];for(const r of e.children)"definition"!==r?.type&&("html"!==r?.type?(Ye(r),t.push(r)):t.push({type:"text",value:(r.value??"")+""}));e.children=t}function Ge(e){return{...e,content:Ve(e.content??[])}}function Ve(e){return e.flatMap(e=>"panel"===e.type?Ve(e.content??[]):[Ze(e)])}function Ze(e){return e.content?{...e,content:Ve(e.content)}:{...e}}const Qe=/\{\{\s*([^\}]+)\s*\}\}/g;function et(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 h.inspect(e,{depth:null})}})(e);return t?[{type:"text",text:t}]:[]}function tt(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:et(r),result:r,structuredContent:r}}const rt={name:"jira-issue-create",inputSchema:Ee,runTool:async(e,t)=>{const r=await(async(e,t)=>{let r;const i=e=>e&&e.trim()?e.trim():void 0,n=i(ye.jira.projectKey),s=i(ye.jira.issueType),a=t&&"object"==typeof t&&!Array.isArray(t)?t:{},o=Object.prototype.hasOwnProperty.call(a,"fields")?a:{...a,projectKey:a.projectKey??n,issueType:a.issueType??s};try{r=Ee.parse(o)}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=(i=t.content,n=t.placeholders,i?i.replace(Qe,(e,t)=>{const r=t.trim();if(!r)return"";if(n&&Object.prototype.hasOwnProperty.call(n,r)){const e=n[r];return null==e?"":e+""}return e}):"");var i,n;if(!r.trim())return e;const s=Xe(r),a=(o=e.description)?"object"==typeof o&&"doc"===o.type&&Array.isArray(o.content)?o.content:"string"==typeof o?Xe(o).content:[]:[];var o;return e.description={type:"doc",version:1,content:[...a,...s.content]},e})(c,r.template);const d=e?.issues?.create??e?.issues?.createIssue;if("function"!=typeof d)throw Error("Jira client missing create function");const l=await d.call(e.issues,{fields:c}),u=l&&l.data||l;return{id:u?.id??null,key:u?.key??null}})(e,t);return tt(r)}};class it extends Error{constructor({code:e,message:t,details:r}){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=e,this.details=r}}const nt=r.Logging.for("jira.errors");function st(e){if(!e)return new it({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,i=e?.response?.data??e?.data??e?.response?.body??e?.body,n=e?.response?.statusText??(r?""+r:void 0),s=e?.response?.headers?Se(e.response.headers):void 0,a=[];"string"==typeof e?.message&&a.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)}))})(i,a);const o=r?`Jira API error (${r})`:"Jira API error",c=a.length>0?a.join(" | "):o,d=r?"jira_"+r:e?.code??"jira_error",l=e?.config,u=l?{method:l.method?l.method.toString().toUpperCase():void 0,url:l.url,headers:Se(l.headers),data:Ie(l.data)}:void 0,p={httpStatus:r,body:i,request:u,response:s?{statusText:n,headers:s}:n?{statusText:n}:void 0,raw:e};return nt.error("jira.error",{code:d,message:c,httpStatus:r,statusText:n,responseHeaders:s,request:u,body:Ie(i)??i}),new it({code:d,message:c,details:p})}const at=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID to delete"),deleteSubtasks:s.z.boolean().optional().default(!0).describe("Whether to delete the subtasks alongside this issue")}).describe("Arguments used to delete a Jira issue (with optional subtasks)"),ot={name:"jira-issue-delete",inputSchema:at,runTool:async(e,t)=>{try{const r=at.parse(t),i=e.issues??e.issue??e,n=i?.delete??i?.deleteIssue;if("function"!=typeof n)throw Error("jira client delete endpoint is not available");return await n.call(i,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),tt({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(e){throw st(e)}}},ct=s.z.object({projectKey:s.z.string().trim().min(1).optional().describe("Project key used to scope the issue search"),issueType:s.z.string().trim().min(1).optional().describe("Issue type name used to filter the results"),parentIssueId:s.z.string().trim().min(1).optional().describe("Optional parent issue key/ID to limit results to a subtree"),name:s.z.string().trim().min(1).optional().describe("Issue summary to match exactly"),reference:s.z.string().trim().min(1).optional().describe("External reference or custom identifier to filter by"),jql:s.z.string().trim().min(1).optional().describe("Free-form JQL query to drive the search"),startAt:s.z.number().int().min(0).optional().describe("Index for paging through the search results"),maxResults:s.z.number().int().min(1).optional().describe("Maximum number of issues to return"),fields:s.z.array(s.z.string()).optional().describe("List of issue fields to include in the response"),expand:s.z.string().optional().describe("Optional expansion clause for the results"),orderBy:s.z.string().trim().min(1).optional().describe("Field or clause used to order the returned issues")}).describe("Parameters describing how to search for Jira issues");function dt(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const lt={name:"jira-issue-list",inputSchema:ct,runTool:async(e,t)=>{try{const r=ct.parse(t),i=r.startAt??0,n=r.maxResults??50;let s=r.jql?.trim();if(s){if(r.orderBy){const e=r.orderBy.trim();e&&(s=/\border\s+by\b/i.test(s)?`${s}, ${e}`:`${s} ORDER BY ${e}`)}}else s=(e=>{const t=[];if(e.projectKey&&t.push(`project = "${dt(e.projectKey)}"`),e.issueType&&t.push(`issuetype = "${dt(e.issueType)}"`),e.parentIssueId&&t.push(`parent = "${dt(e.parentIssueId)}"`),e.name&&t.push(`summary ~ "${dt(e.name)}"`),e.reference){const r=dt(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 a={jql:s,startAt:i,maxResults:n};r.fields&&(a.fields=r.fields),r.expand&&(a.expand=r.expand);const o=e.issueSearch,c=o&&"function"==typeof o.searchForIssuesUsingJqlEnhancedSearch?o.searchForIssuesUsingJqlEnhancedSearch:o&&"function"==typeof o.searchForIssuesUsingJql?o.searchForIssuesUsingJql:void 0;if(!c)throw Error("Jira search API is unavailable on the client");const d=await c.call(o,a),l=d?.data??d,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=i),void 0===u.maxResults&&(u.maxResults=n),tt(u)}catch(e){throw st(e)}}},ut=s.z.object({issueId:s.z.string().min(1).describe("Jira issue key or numeric ID to read"),expand:s.z.string().optional().describe("Optional expand clause for nested fields or changelog"),fields:s.z.array(s.z.string()).optional().describe("Explicit list of issue fields to return"),properties:s.z.array(s.z.string()).optional().describe("Specific issue properties to include in the response")}).describe("Arguments required to read a Jira issue"),pt={name:"jira-issue-read",inputSchema:ut,runTool:async(e,t)=>{try{const r=ut.parse(t),i={issueIdOrKey:r.issueId};r.expand&&(i.expand=r.expand),r.fields&&(i.fields=r.fields),r.properties&&(i.properties=r.properties);const n=await e.issues.getIssue(i);return tt(n?.data??n)}catch(e){throw st(e)}}},mt=s.z.object({issueId:s.z.string().min(1).describe("Target issue key or ID to transition"),transitionId:s.z.union([s.z.string(),s.z.number()]).describe("Identifier for the transition to execute"),fields:s.z.record(s.z.string(),s.z.any()).optional().describe("Optional field updates to apply during the transition"),update:s.z.record(s.z.string(),s.z.array(s.z.object({set:s.z.any().optional().describe("Set operation for the transition update"),add:s.z.any().optional().describe("Add operation for the transition update"),remove:s.z.any().optional().describe("Remove operation for the transition update")}))).optional().describe("Structured update operations to send alongside the transition"),comment:s.z.string().optional().describe("Optional comment to attach during the transition")}).describe("Inputs needed to transition a Jira issue"),ht={name:"jira-issue-transition",inputSchema:mt,runTool:async(e,t)=>{try{const r=mt.parse(t),i={id:r.transitionId};r.fields&&(i.fields=r.fields),r.update&&(i.update=r.update),r.comment&&(i.comment={body:Xe(r.comment)});const n=await e.issues.transition({issueIdOrKey:r.issueId,transition:i});return tt(n?.data??n)}catch(e){throw st(e)}}},gt=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID for which to list transitions"),expand:s.z.string().optional().describe("Optional expand parameter for the transition response")}).describe("Inputs used to fetch available transitions for an issue"),yt={name:"jira-transition-list",inputSchema:gt,runTool:async(e,t)=>{try{const r=gt.parse(t),i=e.issues;if(!i||"function"!=typeof i.getTransitions)throw Error("Jira transitions API is unavailable on the client");const n={issueIdOrKey:r.issueId};r.expand&&(n.expand=r.expand);const s=await i.getTransitions(n);return tt(s?.data??s)}catch(e){throw st(e)}}},ft=s.z.object({description:s.z.string().optional().describe("Markdown description that is converted to Jira ADF (use jira-md-to-adf if you need raw ADF input)")}).catchall(s.z.any()).describe("Field map that gets delivered to Jira (labels, components, etc.)"),bt=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID to update"),fields:ft.optional(),update:s.z.record(s.z.string(),s.z.array(s.z.object({set:s.z.any().optional().describe("Set operation alongside the update key"),add:s.z.any().optional().describe("Add operation alongside the update key"),remove:s.z.any().optional().describe("Remove operation alongside the update key"),edit:s.z.any().optional().describe("Edit operation alongside the update key")}))).optional().describe("Structured update operations for array/set fields"),properties:s.z.array(s.z.any()).optional().describe("Property payloads to attach to the issue"),notifyUsers:s.z.boolean().optional().default(!0).describe("Whether to notify watchers when the issue is updated"),issueTemplateId:s.z.string().optional().describe("Optional template ID to render issue descriptions"),overrideScreenSecurity:s.z.boolean().optional().default(!1).describe("Temporarily bypass screen security restrictions"),overrideEditableFlag:s.z.boolean().optional().default(!1).describe("Temporarily bypass the editable flag on the screen")}).describe("Arguments used to update existing Jira issues"),wt=s.z.record(s.z.string(),s.z.any()).optional(),zt=s.z.object({type:s.z.string().describe("Mark name, such as strong, emphasis, code, or link"),attrs:wt}).describe("Inline formatting or link marks applied to text nodes"),vt=s.z.object({type:s.z.literal("text"),text:s.z.string().describe("Rendered string content for the text node"),marks:s.z.array(zt).optional()}).describe("Plain text node that carries optional formatting marks"),jt=s.z.object({type:s.z.literal("mention"),attrs:s.z.object({id:s.z.string().describe("Jira internal identifier for the mention"),text:s.z.string().describe("Human readable mention text"),userType:s.z.string().optional(),accessLevel:s.z.string().optional(),localizedAccessLevel:s.z.string().optional()}).describe("Metadata describing the mentioned user")}).describe("Represents a user or team mention in a block or inline context"),kt=s.z.object({type:s.z.literal("emoji"),attrs:s.z.object({shortName:s.z.string().describe("Emoji shortcode such as smiling_face"),id:s.z.string().optional(),text:s.z.string().optional()}).describe("Emoji metadata")}).describe("Emoji inline node"),It=s.z.object({type:s.z.literal("inlineCard"),attrs:s.z.object({url:s.z.string().url().describe("Target URL that backs the inline card")}).describe("Inline card attributes")}).describe("Inline card that represents a linked resource"),St=s.z.object({type:s.z.literal("status"),attrs:s.z.object({text:s.z.string().describe("Status label text"),color:s.z.string().describe("Color code applied by Jira"),localId:s.z.string().optional(),style:s.z.string().optional()}).describe("Status metadata published by Jira")}).describe("Status node used for Jira workflow or custom fields"),xt=s.z.object({type:s.z.literal("date"),attrs:s.z.object({representation:s.z.string().optional(),timestamp:s.z.number().optional()}).describe("Date metadata, usually RFC3339 or timestamp")}).describe("Date node that embeds a Jira date reference"),Tt=s.z.object({type:s.z.literal("hardBreak")}).describe("Inline hard break that forces a newline"),At=s.z.object({type:s.z.literal("rule")}).describe("Horizontal rule dividing sections of the document");let Et,_t;const Ot=s.z.lazy(()=>s.z.union([vt,jt,kt,It,St,xt,Tt])),Jt=s.z.lazy(()=>s.z.object({type:s.z.literal("paragraph"),content:s.z.array(Ot).describe("Inline nodes contained by the paragraph")})),Dt=s.z.lazy(()=>s.z.object({type:s.z.literal("heading"),attrs:s.z.object({level:s.z.number().int().min(1).max(6).describe("Heading level, 1-6")}).optional(),content:s.z.array(Ot).describe("Inline nodes composing the heading")})),Ct=s.z.lazy(()=>s.z.object({type:s.z.literal("listItem"),attrs:s.z.object({localId:s.z.string().optional()}).optional(),content:s.z.array(s.z.lazy(()=>Et)).describe("Block level nodes nested inside the list item")})),Nt=s.z.lazy(()=>s.z.object({type:s.z.literal("bulletList"),content:s.z.array(Ct).describe("List items within the bullet list")})),Ht=s.z.lazy(()=>s.z.object({type:s.z.literal("orderedList"),attrs:s.z.object({order:s.z.number().int().min(1).optional()}).optional(),content:s.z.array(Ct)})),qt=s.z.lazy(()=>s.z.object({type:s.z.literal("taskItem"),attrs:s.z.object({localId:s.z.string().optional(),state:s.z.enum(["TODO","IN_PROGRESS","DONE"]).optional()}).optional(),content:s.z.array(s.z.lazy(()=>Et)).describe("Blocks living inside the task item")})),Pt=s.z.lazy(()=>s.z.object({type:s.z.literal("taskList"),content:s.z.array(qt).describe("Task items inside the list")})),Rt=s.z.lazy(()=>s.z.object({type:s.z.literal("codeBlock"),attrs:s.z.object({language:s.z.string().optional()}).optional(),content:s.z.array(vt).optional()})),Lt=s.z.lazy(()=>s.z.object({type:s.z.literal("panel"),attrs:s.z.object({panelType:s.z.enum(["info","note","tip","warning","success"]).optional(),title:s.z.string().optional()}).optional(),content:s.z.array(s.z.lazy(()=>Et)).describe("Panels may nest paragraphs, lists, or other blocks")})),Mt=s.z.lazy(()=>s.z.object({type:s.z.literal("blockquote"),content:s.z.array(s.z.lazy(()=>Et)).describe("Quoted block content")})),$t=s.z.lazy(()=>s.z.object({type:s.z.literal("blockCard"),attrs:s.z.object({url:s.z.string().url().describe("URL for the card")})})),Ft=s.z.lazy(()=>s.z.object({type:s.z.literal("media"),attrs:s.z.object({id:s.z.string().describe("Media identifier in Jira storage"),type:s.z.string().describe("Media type, e.g., file or link"),collection:s.z.string().optional(),width:s.z.number().optional(),height:s.z.number().optional()}).describe("Metadata describing the embedded media")})),Wt=s.z.lazy(()=>s.z.object({type:s.z.literal("mediaSingle"),content:s.z.array(Ft).describe("Single media block content")})),Ut=s.z.lazy(()=>s.z.object({type:s.z.literal("mediaGroup"),content:s.z.array(Ft).describe("Gallery-style media grouping")})),Kt=s.z.object({type:s.z.literal("tableCell"),attrs:s.z.object({colspan:s.z.number().int().min(1).optional(),rowspan:s.z.number().int().min(1).optional()}).optional(),content:s.z.array(s.z.lazy(()=>Et)).describe("Content inside the table cell")}).describe("A regular table cell container"),Bt=s.z.lazy(()=>Kt),Xt=s.z.lazy(()=>Kt.extend({type:s.z.literal("tableHeader")})),Yt=s.z.lazy(()=>s.z.object({type:s.z.literal("tableRow"),content:s.z.array(s.z.union([Bt,Xt]))})),Gt=s.z.lazy(()=>s.z.object({type:s.z.literal("table"),content:s.z.array(Yt)})),Vt=s.z.lazy(()=>s.z.object({type:s.z.literal("decisionItem"),attrs:s.z.object({localId:s.z.string().optional(),state:s.z.enum(["DECIDED","DECIDING"]).optional()}).optional(),content:s.z.array(s.z.lazy(()=>Et))})),Zt=s.z.lazy(()=>s.z.object({type:s.z.literal("decisionList"),content:s.z.array(Vt)})),Qt=s.z.lazy(()=>s.z.object({type:s.z.string(),attrs:s.z.record(s.z.string(),s.z.any()).optional(),content:s.z.array(s.z.lazy(()=>_t)).optional(),marks:s.z.array(zt).optional(),text:s.z.string().optional()}).describe("Unknown or extended Jira node"));Et=s.z.lazy(()=>s.z.union([Jt,Dt,Nt,Ht,Ct,Pt,qt,Rt,Lt,Mt,$t,Wt,Ut,Gt,Yt,Bt,Xt,Zt,Vt,At,Qt])),_t=s.z.lazy(()=>s.z.union([Et,Ot]));const er=s.z.object({type:s.z.literal("doc"),version:s.z.literal(1),content:s.z.array(Et).describe("Top-level block nodes in the document")}).describe("Jira ADF document structure; run jira-md-to-adf when converting markdown"),tr=r.Logging.for("jira.rate-limit"),rr=ye.jira.rateLimitRetryDelayMs??3e3;let ir=!1;const nr="jira-issue-update",sr=bt,ar={name:nr,inputSchema:sr,runTool:async(e,t)=>{try{const r=sr.parse(t),i={issueIdOrKey:r.issueId};r.fields&&(i.fields=(e=>{const t={...e},r=t.description;if("string"==typeof r){const e=Ge(Xe(r));t.description=er.parse(e)}else if(r&&"object"==typeof r){const e=Ge(er.parse(r));t.description=e}return t})(r.fields)),r.update&&(i.update=r.update),r.properties&&(i.properties=r.properties),void 0!==r.notifyUsers&&(i.notifyUsers=r.notifyUsers),r.issueTemplateId&&(i.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(i.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(i.overrideEditableFlag=r.overrideEditableFlag);const n=await(async(e,t)=>{try{return await t()}catch(i){if((e=>{const t=(e=>e?.status??e?.statusCode??e?.response?.status??e?.response?.statusCode??void 0)(e);if(403!==t)return!1;const r=(e=>{const t=e?.response?.data??e?.data??e?.response?.body??e,r=[];return"string"==typeof t&&r.push(t),"string"==typeof t?.message&&r.push(t.message),"string"==typeof t?.errorMessage&&r.push(t.errorMessage),Array.isArray(t?.errorMessages)&&r.push(...t.errorMessages.filter(e=>"string"==typeof e)),"string"==typeof t?.details?.message&&r.push(t.details.message),r.join(" ")||""})(e);return/rate\s?limit/i.test(r)})(i))return ir||(tr.warn(`Jira rate limit detected for ${e}; waiting ${rr}ms before retrying.`,{retryDelayMs:rr}),ir=!0),rr>0&&await(r=rr,new Promise(e=>setTimeout(e,r))),t();throw i}var r})(nr,()=>e.issues.editIssue(i));return tt(n?.data??n)}catch(e){throw st(e)}}},or=s.z.object({markdown:s.z.string().describe("Markdown source that will be converted into Jira ADF"),options:s.z.record(s.z.string(),s.z.any()).optional().describe("Optional MarkdownToAdfOptions passed to the converter")}).describe("Convert markdown into a sanitized Jira ADF document"),cr={name:"jira-md-to-adf",inputSchema:or,runTool:async(e,t)=>{const r=or.parse(t),i=Ge(Xe(r.markdown,r.options));return tt(er.parse(i))}},dr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID for the assignment change"),assignee:s.z.union([s.z.string().describe("Username or account name of the new assignee"),s.z.object({accountId:s.z.string().min(1).describe("Account ID of the assignee")}),s.z.object({accountType:s.z.string().min(1).describe("Account type filter (e.g., user, app)")})]).describe("How the new assignee is specified")}).describe("Arguments required to assign a Jira issue to someone"),lr={name:"jira-assign-issue",inputSchema:dr,runTool:async(e,t)=>{try{const r=dr.parse(t);let i;i="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const n=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:i});return tt(n?.data??n)}catch(e){throw st(e)}}},ur=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID to remove the assignee from")}).describe("Inputs required to unassign a Jira issue"),pr={name:"jira-unassign-issue",inputSchema:ur,runTool:async(e,t)=>{try{const r=ur.parse(t),i=await e.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return tt(i?.data??i)}catch(e){throw st(e)}}},mr=s.z.object({issueId:s.z.string().min(1).describe("The Jira issue key or numeric ID receiving the comment"),body:s.z.string().min(1).describe("The markdown-compatible text of the comment"),visibility:s.z.object({type:s.z.enum(["role","group"]).describe("Visibility type that restricts the comment to a role or group"),value:s.z.string().min(1).describe("The name of the role or group granted visibility")}).optional().describe("Optional visibility override controlling who can read the comment")}).describe("Arguments for adding a comment to a Jira issue"),hr={name:"jira-comment-add",inputSchema:mr,runTool:async(e,t)=>{try{const r=mr.parse(t),i=e.issueComments;if(!i||"function"!=typeof i.addComment)throw Error("Jira issueComments API is unavailable on the client");const n={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(n.visibility=r.visibility);const s=await i.addComment(n);return tt(s?.data??s)}catch(e){throw st(e)}}},gr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID whose comments should be retrieved"),start:s.z.number().optional().default(0).describe("Zero-based index to start pagination from"),maxResults:s.z.number().optional().default(50).describe("Maximum number of comments to return"),orderBy:s.z.string().optional().describe("Field name to order the returned comments by"),expand:s.z.string().optional().describe("Optional expansion clause for the comment response")}).describe("Parameters for fetching comments on a Jira issue"),yr={name:"jira-comment-list",inputSchema:gr,runTool:async(e,t)=>{try{const r=gr.parse(t),i=e.issueComments;if(!i||"function"!=typeof i.getComments)throw Error("Jira issueComments API is unavailable on the client");const n=await i.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return tt(n?.data??n)}catch(e){throw st(e)}}},fr=s.z.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","is tested by","tests","Is covered by","covered by","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]).describe("The named relationship (Blocks, Relates to, etc.) that describes the link type"),br=s.z.object({id:s.z.string().optional().describe("Numeric Jira ID used when referencing an issue"),key:s.z.string().optional().describe("Human-readable key of the linked issue")}).describe("An issue reference (ID or key) used when building a link payload"),wr=s.z.object({type:s.z.enum(["role","group"]).describe("Visibility scope type attached to the comment"),value:s.z.string().min(1).describe("Name of the role or group granted visibility to the comment")}).describe("Optional visibility settings applied to the comment"),zr=s.z.object({body:s.z.string().optional().describe("Markdown text to include as a linked-comment"),visibility:wr.optional().describe("Optional ACL for the comment")}).describe("Optional comment applied at the time the link is created or updated"),vr=s.z.object({link:s.z.object({relationship:fr,inwardIssue:br,outwardIssue:br,comment:zr.optional()}).describe("Definition of the link that should be created between two issues")}).describe("Arguments required to create a Jira issue link");let jr=[];function kr(e){return(e||"").trim().toLowerCase()}async function Ir(e,t){if(!t)throw Error("Link relationship is required");0===jr.length&&(jr=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(),i=r?.issueLinkTypes??r?.values??r;return Array.isArray(i)?i:[]})(e));const r=kr(t),i=jr.find(e=>[e.name,e.inward,e.outward].some(e=>kr(e)===r));if(!i)throw Error(`No issue link type matching '${t}' found.`);return i}function Sr(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 xr(e){if(!e)return;const t={};return e.body&&(t.body=Xe(e.body)),e.visibility&&(t.visibility=e.visibility),Object.keys(t).length>0?t:void 0}const Tr=vr,Ar={name:"jira-link-create",inputSchema:Tr,runTool:async(e,t)=>{try{const r=Tr.parse(t).link,i={inwardIssue:Sr(r.inwardIssue),outwardIssue:Sr(r.outwardIssue)},n=xr(r.comment);n&&(i.comment=n);const s=e.issueLinks;if(!s||"function"!=typeof s.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const a=await Ir(e,r.relationship);i.type={id:a.id};const o=await s.linkIssues(i);return tt(o?.data??o)}catch(e){throw st(e)}}},Er=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID receiving the attachment"),file:s.z.string().min(1).describe("Base64 or path to the file contents to upload"),mimeType:s.z.string().optional().describe("Optional MIME type override for the attachment"),comment:s.z.string().optional().describe("Optional comment to associate with the attachment")}).describe("Inputs needed to attach a file to a Jira issue"),_r={name:"jira-attach",inputSchema:Er,runTool:async(e,r)=>{try{const i=Er.parse(r),n=c.resolve(i.file),s=await t.promises.readFile(n),a=c.basename(n),o=new FormData;o.append("file",new Blob([s],{type:i.mimeType??"application/octet-stream"}),a);const d=e?.config??null,l=d?.host,u=d?.authentication?.basic??d?.authentication??d?.auth??null,p=u?.email,m=u?.apiToken??u?.apiKey;if(!l||!p||!m)throw Error("Jira client authentication configuration is unavailable for attachments");const h=await fetch(`${l}/rest/api/3/issue/${i.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${p}:${m}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:o});if(!h.ok){const e=await h.text();throw Error(`Jira attachment upload failed (${h.status}): ${e}`)}const g=await h.json();if(i.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:i.issueId,comment:Xe(i.comment)})}return tt(g)}catch(e){if(e&&e.code&&"string"==typeof e.code&&["ENOENT","EACCES"].includes(e.code))throw Error("Attachment file error: "+e.message);throw st(e)}}},Or=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID whose attachments should be listed")}).describe("Arguments used to fetch attachments for a Jira issue"),Jr={name:"jira-attachment-list",inputSchema:Or,runTool:async(e,t)=>{try{const r=Or.parse(t),i=e.issues;if(!i||"function"!=typeof i.getIssue)throw Error("Jira issues API is unavailable on the client");const n=await i.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),s=n?.data??n;return tt({attachments:s?.fields?.attachment??[]})}catch(e){throw st(e)}}},Dr=s.z.object({issueId:s.z.string().min(1).describe("Issue key or ID owning the attachment"),attachmentId:s.z.string().min(1).describe("ID of the attachment to delete")}).describe("Arguments required to remove an attachment from Jira"),Cr={name:"jira-attachment-delete",inputSchema:Dr,runTool:async(e,t)=>{try{const r=Dr.parse(t),i=e.issueAttachments;if(!i||"function"!=typeof i.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await i.removeAttachment({id:r.attachmentId}),tt({success:!0,message:`Attachment ${t.attachmentId} deleted successfully`})}catch(e){throw st(e)}}},Nr=s.z.object({issueId:s.z.string().min(1).describe("Target issue key or ID for the worklog entry"),timeSpent:s.z.string().min(1).describe('Time spent text (e.g., "1h 30m")'),comment:s.z.string().optional().describe("Optional worklog comment in markdown"),author:s.z.object({accountId:s.z.string().min(1).describe("Account ID of the user logging the work")}).optional().describe("Optional author override for the worklog entry"),startingOn:s.z.string().optional().describe("Optional timestamp for when the work started (ISO)"),artifact:s.z.string().optional().describe("Optional identifier linking the worklog to another artifact")}).describe("Arguments required to add a worklog entry to a Jira issue"),Hr={name:"jira-worklog-add",inputSchema:Nr,runTool:async(e,t)=>{try{const r=Nr.parse(t),i={timeSpent:r.timeSpent};r.comment&&(i.comment=r.comment),r.author&&(i.author=r.author),r.startingOn&&(i.started=r.startingOn),r.artifact&&(i.artifact=r.artifact);const n=e.issueWorklogs;if(!n||"function"!=typeof n.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const s=await n.addWorklog({issueIdOrKey:r.issueId,...i});return tt(s?.data??s)}catch(e){throw st(e)}}},qr=r.Logging.for("jira.xray");class Pr{constructor(){this.clientId=ye.orThrow().xray.apiUser,this.clientSecret=ye.orThrow().xray.apiSecret,this.baseUrl=ye.orThrow().xray.host||"https://eu.xray.cloud.getxray.app"}async authenticate(){if(!this.clientId||!this.clientSecret)throw Error("Xray API credentials are missing (XRAY__API_USER, XRAY__API_SECRET).");const e=await fetch(this.baseUrl+"/api/v2/authenticate",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:this.clientId,client_secret:this.clientSecret})}),t=await e.text();return this.token=t.replace(/"/g,""),this.token}async graphql(e,t){this.token||await this.authenticate();const r={query:e,variables:t};qr.info("xray.graphql.request",{payload:Ie(r)});try{const e=await fetch(this.baseUrl+"/api/v2/graphql",{method:"POST",headers:{Authorization:"Bearer "+this.token,"Content-Type":"application/json"},body:JSON.stringify(r)}),t=await e.json();if(qr.info("xray.graphql.response",{status:e.status,headers:e.headers?.get?e.headers.get("content-type"):void 0,body:Ie(t)}),t.errors)throw qr.error("xray.graphql.errors",{errors:Ie(t.errors)}),Error(JSON.stringify(t.errors,null,2));return t.data}catch(e){throw qr.error("xray.graphql.failure",{error:e+""}),e}}async getTest(e){return(await this.graphql('\n query GetTest($issueId: String!) {\n getTest(issueId: $issueId) {\n issueId\n jira(fields:["key"])\n steps {\n id\n action\n data\n result\n }\n }\n }\n ',{issueId:e})).getTest}async addStep(e,t){return(await this.graphql("\n mutation AddTestStep($issueId: String!, $step: CreateStepInput!) {\n addTestStep(issueId: $issueId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{issueId:e,step:t})).addTestStep}async updateStep(e,t){return(await this.graphql("\n mutation UpdateTestStep($stepId: String!, $step: UpdateStepInput!) {\n updateTestStep(stepId: $stepId, step: $step) {\n id\n action\n data\n result\n }\n }\n ",{stepId:e,step:t})).updateTestStep}async deleteStep(e){return(await this.graphql("\n mutation RemoveTestStep($stepId: String!) {\n removeTestStep(stepId: $stepId)\n }\n ",{stepId:e})).removeTestStep}async addSteps(e,t){return Promise.all(t.map(t=>this.addStep(e,t)))}async updateSteps(e){return Promise.all(e.map(e=>this.updateStep(e.stepId,e.step)))}async deleteSteps(e){return Promise.all(e.map(e=>this.deleteStep(e)))}async syncSteps(e,t){const r=(await this.getTest(e)).steps||[],i=[],n=[],s=[];for(let e=0;e<t.length;e++){const s=t[e],a=r[e];a?a.action===s.action&&a.data===s.data&&a.result===s.result||i.push({stepId:a.id,step:s}):n.push(s)}if(r.length>t.length)for(let e=t.length;e<r.length;e++)s.push(r[e].id);await this.addSteps(e,n),await this.updateSteps(i),await this.deleteSteps(s)}}let Rr=null;const Lr=new Map;function Mr(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 i=e.data??e.fields?.Data??e.fields?.data??void 0,n=e.result??e.fields?.Result??e.fields?.result??void 0;return{action:r.toString(),data:"string"==typeof i?i:void 0,result:"string"==typeof n?n:void 0}}async function $r(e,t){if(!t)throw Error("Issue reference is required when interacting with Xray steps");if(Lr.has(t))return Lr.get(t);if(/^[0-9]+$/.test(t))return Lr.set(t,t),t;const r=e?.issues??e?.issue;if(!r?.getIssue)throw Error("Jira client does not expose issue lookup functionality");const i=await r.getIssue({issueIdOrKey:t,fields:["id"]}),n=i?.id;if(!n)throw Error("Unable to resolve Jira issue ID for "+t);return Lr.set(t,n),n}async function Fr(e){if(e?.test?.step)return e.test.step;const t=await(async()=>{if(Rr)return Rr;const e=ye.orThrow().xray.apiUser?.trim(),t=ye.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=xe(),i=new Pr,n={async createStep(e,t){const n=await $r(r,e),s=await i.addStep(n,Mr(t));return{step:s,id:s?.id}},async updateStep(e,t,n){await $r(r,e);const s=Mr(n),a=await i.updateStep(t.toString(),s);return{step:a,id:a?.id}},deleteStep:async(e,t)=>(await $r(r,e),{success:!0===await i.deleteStep(t.toString())}),async getSteps(e){const t=await $r(r,e),n=await i.getTest(t);return{steps:n?.steps??[]}}};return Rr={test:{step:n}},Rr})();if(!t?.test?.step)throw Error("Xray step API is unavailable on the client");return t.test.step}const Wr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID that owns the step"),action:s.z.string().min(1).describe("Action description for the new Xray step"),data:s.z.string().optional().describe("Optional data or context used by this step"),result:s.z.string().optional().describe("Optional expected result for the step")}).describe("Inputs for adding a step to an Xray test case"),Ur={name:"jira-xray-step-add",inputSchema:Wr,runTool:async(e,t)=>{try{const r=Wr.parse(t),i=await Fr(e),n={action:r.action,data:r.data,result:r.result};return tt(await i.createStep(r.issueId,n))}catch(e){throw st(e)}}},Kr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID that owns the step"),stepId:s.z.union([s.z.string(),s.z.number()]).describe("Identifier for the step that should be updated"),action:s.z.string().min(1).describe("New action text for the step"),data:s.z.string().optional().describe("Updated data/context for the step"),result:s.z.string().optional().describe("Updated expected result for the step")}).describe("Inputs required to modify an Xray test step"),Br={name:"jira-xray-step-update",inputSchema:Kr,runTool:async(e,t)=>{try{const r=Kr.parse(t),i=await Fr(e),n=r.stepId+"",s={action:r.action,data:r.data,result:r.result};return tt(await i.updateStep(r.issueId,n,s))}catch(e){throw st(e)}}},Xr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID owning the step"),stepId:s.z.union([s.z.string(),s.z.number()]).describe("Identifier of the step to delete")}).describe("Arguments used to remove an Xray test step"),Yr={name:"jira-xray-step-delete",inputSchema:Xr,runTool:async(e,t)=>{try{const r=Xr.parse(t),i=await Fr(e);return await i.deleteStep(r.issueId,r.stepId.toString()),tt({success:!0})}catch(e){throw st(e)}}},Gr=s.z.object({issueId:s.z.string().min(1).describe("Xray test case key or ID whose steps should be returned")}).describe("Inputs required to list steps on an Xray test case"),Vr={name:"jira-xray-step-list",inputSchema:Gr,runTool:async(e,t)=>{try{const r=Gr.parse(t),i=await Fr(e);return tt(await i.getSteps(r.issueId))}catch(e){throw st(e)}}},Zr=s.z.object({linkId:s.z.string().min(1).describe("Identifier for the Jira issue link to remove")}).describe("Inputs required to delete an existing Jira issue link"),Qr={name:"jira-link-delete",inputSchema:Zr,runTool:async(e,t)=>{try{const r=Zr.parse(t),i=e.issueLinks;if(!i||"function"!=typeof i.deleteIssueLink)throw Error("Jira issueLinks API is unavailable on the client");return await i.deleteIssueLink({linkId:r.linkId}),tt({success:!0,message:`Issue link ${r.linkId} deleted successfully`})}catch(e){throw st(e)}}},ei=s.z.object({linkId:s.z.string().min(1).describe("ID of the existing issue link to change"),relationship:fr,comment:zr.optional().describe("Optional comment to attach while recreating the link")}).describe("Inputs required to update (recreate) a Jira issue link"),ti={name:"jira-link-update",inputSchema:ei,runTool:async(e,t)=>{try{const r=ei.parse(t),i=e.issueLinks;if(!i||"function"!=typeof i.getIssueLink||"function"!=typeof i.deleteIssueLink||"function"!=typeof i.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const n=await i.getIssueLink({linkId:r.linkId}),s=n?.data??n;if(!s)throw Error(`Issue link ${r.linkId} not found`);const a=s.inwardIssue,o=s.outwardIssue;if(!a||!o)throw Error("Issue link payload is missing linked issues");const c=await Ir(e,r.relationship);await i.deleteIssueLink({linkId:r.linkId});const d={inwardIssue:Sr(a),outwardIssue:Sr(o),type:{id:c.id}},l=xr(r.comment);return l&&(d.comment=l),await i.linkIssues(d),tt({success:!0,message:`Issue link ${r.linkId} updated to ${r.relationship}`})}catch(e){throw st(e)}}};function ri(e=[]){return e.map(ii).join("")}function ii(e){switch(e.type){case"text":return(e=>{let t=e.text||"";for(const r of e.marks||[])switch(r.type){case"strong":t=`**${t}**`;break;case"em":t=`*${t}*`;break;case"strike":t=`~~${t}~~`;break;case"code":t="`"+t+"`";break;case"link":t=`[${t}](${r.attrs.href})`}return t})(e);case"mention":return e.attrs.text||"@"+e.attrs.id;case"emoji":return e.attrs.shortName||"";case"inlineCard":return e.attrs.url;case"status":return`:status{color="${e.attrs.color}"}[${e.attrs.text}]`;case"hardBreak":return" \n"}return""}function ni(e){switch(e.type){case"heading":return"#".repeat(e.attrs?.level)+" "+ri(e.content);case"paragraph":return ri(e.content);case"blockquote":return e.content.map(ni).map(e=>"> "+e).join("\n");case"bulletList":case"orderedList":case"taskList":return(e=>{const t=[];let r=1;for(const i of e.content){let n="- ";"orderedList"===e.type&&(n=r+++". "),"taskList"===e.type&&(n="- "+("DONE"===i.attrs?.state?"[x] ":"[ ] "));const s=i.content.map(ni).join(" ");t.push(n+s)}return t.join("\n")})(e);case"table":return(e=>{const t=e.content||[];return t.length?["| "+t[0].content.map(e=>ri(e.content[0].content)).join(" | ")+" |","| "+t[0].content.map(()=>"---").join(" | ")+" |",...t.slice(1).map(e=>e.content.map(e=>ri(e.content[0].content)).join(" | ")).map(e=>"| "+e+" |")].join("\n"):""})(e);case"codeBlock":return"```"+(e.attrs?.language||"")+"\n"+e.content?.map(e=>e.text).join("")+"\n```";case"panel":return(e=>`::panel{type="${e.attrs?.panelType||"info"}"}\n${e.content.map(ni).join("\n")}\n::`)(e);case"rule":return"---";case"mediaSingle":return(e=>{const t=e.content?.[0];return t?"external"===t.attrs?.type?`![](${t.attrs.url})`:"file"===t.attrs?.type?`[attachment](attachment:${t.attrs.id})`:"":""})(e);case"blockCard":return e.attrs?.url}return""}const si=s.z.object({document:er.describe("Jira ADF document you want to translate into Markdown (use jira-md-to-adf to go the other way).")}).describe("Convert Jira ADF documents back to Markdown text for editing or review"),ai={name:"jira-adf-to-markdown",inputSchema:si,runTool:async(e,t)=>{return tt({markdown:(r=si.parse(t).document,(e=>{if(!e||"doc"!==e.type)return"";const t=[];for(const r of e.content||[])t.push(ni(r));return t.join("\n\n")})(r))});var r}},oi={[rt.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[pt.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[lt.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}},[ar.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}},[cr.name]:{title:"Jira Markdown to ADF",description:"Convert Markdown into a sanitized Jira ADF document so fields.description can be supplied to jira-issue-update and other tools that expect Jira documents",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[ai.name]:{title:"Jira ADF to Markdown",description:"Translate Jira ADF documents back into Markdown text so you can edit them before sending them through tooling or LLM prompts (use jira-md-to-adf to get valid ADF inputs).",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[ot.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[ht.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[yt.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[lr.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[pr.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[hr.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}},[yr.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ar.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ti.name]:{title:"Jira Link Update",description:"Change the relationship type for an existing issue link",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Qr.name]:{title:"Jira Link Delete",description:"Delete an issue link from Jira",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[_r.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Jr.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Cr.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Hr.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ur.name]:{title:"Jira Xray Step Add",description:"Add a step to an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Br.name]:{title:"Jira Xray Step Update",description:"Update a step on an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Yr.name]:{title:"Jira Xray Step Delete",description:"Delete a step from an Xray test case",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Vr.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 ci(e){const t=r.Logging.for(ci);let i,n=null;try{i=xe()}catch(e){if(!(e instanceof ze))return void t.warn("Skipping Jira tool registration; unable to create Jira client",{error:e});n=e,t.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:e})}const s=[rt,pt,lt,ar,cr,ai,ot,ht,yt,lr,pr,hr,yr,Ar,ti,Qr,_r,Jr,Cr,Hr,Ur,Br,Yr,Vr];for(const r of s){const s=oi[r.name];if(s)try{await e.registerTool(r.name,{title:s.title,description:s.description,inputSchema:r.inputSchema,annotations:s.annotations},async e=>{if(!i)throw n??Error("Jira client unavailable because credentials could not be loaded.");return r.runTool(i,e)}),t.info("Registered Jira tool "+r.name)}catch(e){t.error("Failed to register Jira tool "+r.name,{error:e})}}}async function di(e){await(async e=>{e.registerTool("decaf-server-info",{title:"Decaf MCP Server Info",description:"Return read-only server metadata, version, and registered prompt lists so callers can discover what exposures are available without side effects.",inputSchema:{},outputSchema:void 0,annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},async()=>{const e=ce.map(e=>e.getName()).sort();return{content:[{type:"text",text:["Name: "+ye.name,"Title: "+ye.title,"Version: "+ye.version,"Prompts: "+(e.join(", ")||"<none>")].join("\n")}]}})})(e);const t=r.Logging.for(di);try{await ci(e)}catch(e){t.error("Failed to register Jira tools",e)}}class li extends C{setCb(e){return this.cb=e,this}setConfig(e){return this.config=e,this}setUriOtTemplate(e){return this.uriOrTemplate=e,this}constructor(e){super(e)}static get builder(){return new li}build(e){const t=this.hasErrors();if(t)throw Error(t.toString());try{const t="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new z.ResourceTemplate(new w.UriTemplate(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),i=async(e,t)=>{const r=this.logFor(t);r.verbose(`Requesting resource ${this.name} from ${e.toString()}`);const i=await Promise.resolve(this.cb(e,t));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(i._meta)),i};return e.resource(this.name,t,r,i)}catch(e){throw r.Logging.for(this).error("Error registering resource "+this.name,e),e}}}i.__decorate([n.required(),i.__metadata("design:type",String)],li.prototype,"uriOrTemplate",void 0),i.__decorate([n.required(),i.__metadata("design:type",Function)],li.prototype,"cb",void 0),i.__decorate([n.required(),i.__metadata("design:type",Object)],li.prototype,"config",void 0);const ui=Y()??x.join(__dirname,"..","assets"),pi=x.join(ui,"templates"),mi=x.join(ui,"prompts"),hi=x.join(__dirname,"..","assets"),gi=Y()||hi,yi=x.join(gi,"resources");function fi(e){const t=x.join(yi,e);try{return S.readFileSync(t,"utf-8")}catch(e){if("ENOENT"!==e.code)throw e}const r=(i=t).endsWith(".json")?i.slice(0,-5)+".enc":i+".enc";var i;if(!S.existsSync(r))throw Error("Asset not found: "+e);return M(S.readFileSync(r)).toString("utf-8")}const bi="resource://repo.metadata",wi=(()=>{const e=fi("repo-metadata.json");return JSON.parse(e)})(),zi=li.builder.setName("repo.metadata").setTitle("Repository metadata snapshot").setDescription("Deterministic metadata about the decaf-ts MCP server, Jira defaults, and the canonical project key.").setUriOtTemplate(bi).setConfig({mimeType:"application/json",description:"Static repository metadata that documents the MCP surface."}).setCb(async()=>{const e=ye.version,t=ye.jira.projectKey??wi.jira?.projectKey??"DECAF",r={...wi,version:e,projectKey:t};return{contents:[{uri:bi,mimeType:"application/json",text:JSON.stringify(r,null,2)}],_meta:{source:"assets/repo-metadata.json"}}}),vi="resource://decoration.schematic.metadata",ji=fi("decoration/metadata.json"),ki=li.builder.setName("decoration.schematic.metadata").setTitle("Decoration metadata schematic").setDescription("Outlines the annotation and field metadata contracts that decorators expose.").setUriOtTemplate(vi).setConfig({mimeType:"application/json",description:"Annotation metadata definitions for decorator tooling."}).setCb(async()=>({contents:[{uri:vi,mimeType:"application/json",text:ji}],_meta:{schematic:"metadata"}})),Ii="resource://decoration.schematic.builder",Si=fi("decoration/builder.json"),xi=li.builder.setName("decoration.schematic.builder").setTitle("Decoration builder pattern schematic").setDescription("Describes how decorated models spawn builder classes with fluent setters and validation.").setUriOtTemplate(Ii).setConfig({mimeType:"application/json",description:"Builder conventions for decorated models."}).setCb(async()=>({contents:[{uri:Ii,mimeType:"application/json",text:Si}],_meta:{schematic:"builder"}})),Ti="resource://decoration.schematic.validation",Ai=fi("decoration/validation.json"),Ei=li.builder.setName("decoration.schematic.validation").setTitle("Decoration validation schematic").setDescription("Tracks how decorator metadata flows through validation routines and error serialization.").setUriOtTemplate(Ti).setConfig({mimeType:"application/json",description:"Validation lifecycle and error contract for decorated models."}).setCb(async()=>({contents:[{uri:Ti,mimeType:"application/json",text:Ai}],_meta:{schematic:"validation"}})),_i="resource://golden.override.model-builder",Oi=fi("golden/model-builder.txt"),Ji=li.builder.setName("golden.override.model-builder").setTitle("Golden override: model builder snippet").setDescription("A coding template that shows how a Model builder keeps setters fluent and enforces validation.").setUriOtTemplate(_i).setConfig({mimeType:"text/plain",description:"Model builder golden snippet for copy/paste reference."}).setCb(async()=>({contents:[{uri:_i,mimeType:"text/plain",text:Oi}],_meta:{override:"model-builder"}})),Di="resource://golden.override.validation-errors",Ci=fi("golden/validation-errors.json"),Ni=li.builder.setName("golden.override.validation-errors").setTitle("Golden override: validation error report").setDescription("Shows the structure returned when decorator validation fails, including error arrays and metadata.").setUriOtTemplate(Di).setConfig({mimeType:"application/json",description:"Example validation error payload emitted by decorated models."}).setCb(async()=>({contents:[{uri:Di,mimeType:"application/json",text:Ci}],_meta:{override:"validation-errors"}})),Hi="resource://golden.override.xray-step-template",qi=fi("golden/xray-step-template.txt"),Pi=[zi,ki,xi,Ei,Ji,Ni,li.builder.setName("golden.override.xray-step-template").setTitle("Golden override: Xray step template").setDescription("A compliant Xray test-step template that lists the precondition, action, and verification.").setUriOtTemplate(Hi).setConfig({mimeType:"text/plain",description:"Template for documenting Xray steps."}).setCb(async()=>({contents:[{uri:Hi,mimeType:"text/plain",text:qi}],_meta:{override:"xray-step-template"}}))];async function Ri(e){const t=r.Logging.for(Ri);for(const r of Pi)try{await r.build(e),t.info("Registered resource "+r.getName())}catch(e){t.error("Failed to register resource "+r.getName(),e)}}const Li=new WeakMap;class Mi extends r.LoggedClass{get client(){const e=Li.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 ce)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 di(this.client),e.verbose("Registered built-in tools")}catch(e){}try{await Ri(this.client),e.verbose("Registered built-in resources")}catch(e){}try{await(async(e,t)=>{t.info("Registering agent templates as resources...");const r=S.readdirSync(pi).filter(e=>e.endsWith(".md"));for(const i of r){const r=x.basename(i,".md"),n=x.join(pi,i),s=li.builder.setName(r).setTitle("Template: "+r).setDescription("Resource template for "+r).setUriOtTemplate("file:///"+n).setConfig({mimeType:"text/markdown",description:"Template for "+r}).setCb(async e=>{const t=S.readFileSync(e.pathname,"utf8");return{contents:[{uri:e.toString(),text:t,mimeType:"text/markdown"}],_meta:{}}});try{s.build(e),t.info("Registered template: "+r)}catch(e){t.error(`Failed to register template ${r}:`,e)}}t.info("Registering agent prompts...");const i=S.readdirSync(mi).filter(e=>e.endsWith(".md"));for(const r of i){const i=x.basename(r,".md"),n=x.join(mi,r),a=S.readFileSync(n,"utf8"),o=V.builder.setName(i).setTitle("Prompt: "+i).setDescription("Dynamic prompt for "+i).setArgsSchema(s.z.object({})).setCb(async e=>({messages:[{role:"user",content:{type:"text",text:a}}],_meta:{}}));try{o.build(e),t.info("Registered prompt: "+i)}catch(e){t.error(`Failed to register prompt ${i}:`,e)}}})(this.client,e)}catch(e){}}async boot(e="stdio"){"stdio"===e&&r.Logging.setFactory(A),r.Logging.for(this.constructor.name);const t=((Array.isArray(ye.icons)?ye.icons:[ye.icons])||[]).map(e=>{const t="string"==typeof e?.src?e.src:(e?.src??"")+"",r="string"==typeof e?.mimeType?e.mimeType:(e?.mimeType??"")+"";let i=[];return Array.isArray(e?.sizes)?i=e.sizes.map(e=>e+""):"string"==typeof e?.sizes&&(i=(e.sizes+"").split(",").map(e=>e.trim())),{src:t,mimeType:r,sizes:i}}),i={name:ye.name,title:ye.title,websiteUrl:ye.websiteUrl,version:ye.version,icons:t},n=new z.McpServer(i,{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)=>{Li.set(e,t)})(this,n),n.onerror=e=>{this.log.error("MCP instance onerror",e)},e){case"stdio":e=new j.StdioServerTransport;break;case"http":e=new k.StreamableHTTPServerTransport({sessionIdGenerator:()=>v.v4(),onsessioninitialized:e=>{},onsessionclosed:e=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(s=e)||"object"!=typeof s||"function"!=typeof s.send&&"function"!=typeof s.close&&"function"!=typeof s.on)throw new d.InternalError("Invalid transport type: "+e)}var s;try{await this.load()}catch(e){throw e}await this.client.connect(e)}}const $i=(new e.Command).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async e=>{const r=B("package.json"),i=JSON.parse(t.readFileSync(r,"utf-8")),n=i.version,{transport:s}=e,a=(new T).for("mcp-server");if("stdio"!==s)throw Error("Unsupported transport mode: "+s);return a.info("Transport stdio"),a.debug(`running with options: ${JSON.stringify(e)} for ${i.name} version ${n}`),(new Mi).boot(s)});(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 i=B("package.json"),n=JSON.parse(t.readFileSync(i,"utf-8")),s=n.version;r.Logging.for("md-to-ast").debug(`running with options: ${JSON.stringify(e)} for ${n.name} version ${s}`);const a=Xe(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(a,null,2)+"\n")});const Fi=(new e.Command).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");Fi.addCommand($i),Fi.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("fs/promises"),require("node:util"),require("unified"),require("remark-directive"),require("remark-gfm"),require("remark-parse"),require("@modelcontextprotocol/sdk/shared/uriTemplate.js"),require("@modelcontextprotocol/sdk/server/mcp.js"),require("uuid"),require("@modelcontextprotocol/sdk/server/stdio.js"),require("@modelcontextprotocol/sdk/server/streamableHttp.js")):"function"==typeof define&&define.amd?define(["commander","fs","@decaf-ts/logging","tslib","@decaf-ts/decorator-validation","zod","@decaf-ts/injectable-decorators","@decaf-ts/decoration","path","@decaf-ts/db-decorators","crypto","zlib","url","fs/promises","node:util","unified","remark-directive","remark-gfm","remark-parse","@modelcontextprotocol/sdk/shared/uriTemplate.js","@modelcontextprotocol/sdk/server/mcp.js","uuid","@modelcontextprotocol/sdk/server/stdio.js","@modelcontextprotocol/sdk/server/streamableHttp.js"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).commander,e.fs,e.decafTsLogging,e.tslib,e.decafTsDecoratorValidation,e.zod,e.decafTsInjectableDecorators,e.decafTsDecoration,e.path,e.decafTsDbDecorators,e.crypto,e.zlib,e.url,e.fsPromises,e.node_util,e.unified,e.remarkDirective,e.remarkGfm,e.remarkParse,e.uriTemplate_js,e.mcp_js,e.uuid,e.stdio_js,e.streamableHttp_js);
3
3
  //# sourceMappingURL=mcp-server.cjs.map