@decaf-ts/mcp-server 1.5.13 → 1.5.14

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