@decaf-ts/mcp-server 1.5.2 → 1.5.4

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 +4 -2
  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 +2 -2
  20. package/dist/assets/prompts/plan_commands.enc +0 -0
  21. package/dist/assets/prompts/repository/readme.enc +0 -0
  22. package/dist/assets/prompts/repository/release_notes.enc +0 -0
  23. package/dist/assets/prompts/repository/setup.enc +0 -0
  24. package/dist/assets/prompts/specification_commands.enc +0 -0
  25. package/dist/assets/prompts/startup_command.enc +0 -0
  26. package/dist/assets/prompts/task_commands.enc +0 -0
  27. package/dist/assets/prompts/tests/coverage.enc +0 -0
  28. package/dist/assets/templates/AGENTS.enc +0 -0
  29. package/dist/assets/templates/agents_template.enc +0 -0
  30. package/dist/assets/templates/constitution_template.enc +0 -0
  31. package/dist/assets/templates/decaf/context/logCtx.enc +0 -0
  32. package/dist/assets/templates/decaf/services/client_based_service.enc +0 -0
  33. package/dist/assets/templates/decaf/services/model_service.enc +0 -0
  34. package/dist/assets/templates/decaf/services/service.enc +0 -0
  35. package/dist/assets/templates/decaf_guidelines.enc +1 -1
  36. package/dist/assets/templates/instructions_template.enc +0 -0
  37. package/dist/assets/templates/jira_templates.enc +0 -0
  38. package/dist/assets/templates/plan_template.enc +0 -0
  39. package/dist/assets/templates/specification_template.enc +0 -0
  40. package/dist/assets/templates/task_template.enc +0 -0
  41. package/dist/mcp-server.cjs +1 -1
  42. package/dist/mcp-server.cjs.map +1 -1
  43. package/dist/mcp-server.js +1 -1
  44. package/dist/mcp-server.js.map +1 -1
  45. package/package.json +1 -1
@@ -1,2 +1,2 @@
1
- import{Command as t}from"commander";import*as e from"fs";import r,{promises as s}from"fs";import{MiniLogger as n,NumericLogLevels as i,Logging as o,LoggedClass as a,toSnakeCase as c,sf as p,toPascalCase as l,LogLevel as u,LoggedEnvironment as d}from"@decaf-ts/logging";import{__decorate as m,__metadata as h}from"tslib";import{required as f,Model as y,list as g,minlength as b}from"@decaf-ts/decorator-validation";import{z as v,ZodObject as w}from"zod";import{injectable as S,inject as j}from"@decaf-ts/injectable-decorators";import{prop as x,Metadata as I}from"@decaf-ts/decoration";import*as k from"path";import E from"path";import{InternalError as A,SerializationError as T,ValidationError as O}from"@decaf-ts/db-decorators";import N from"crypto";import C from"zlib";import{fileURLToPath as J}from"url";import{unified as H}from"unified";import _ from"remark-directive";import $ from"remark-gfm";import D from"remark-parse";import{UriTemplate as P}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";import{ResourceTemplate as R,McpServer as M}from"@modelcontextprotocol/sdk/server/mcp.js";import{v4 as q}from"uuid";import{StdioServerTransport as F}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as B}from"@modelcontextprotocol/sdk/server/streamableHttp.js";class W extends n{constructor(t,e,r){super(t,e,r)}log(t,e,r,s){const n=this.config("level");i[n],i[t]}}const U=(t,e,...r)=>{const s=(t=>{if("string"==typeof t)return t;if(!t)return"unknown";if("function"==typeof t)return t.name||"unknown";if("object"==typeof t&&"constructor"in t){const e=t.constructor;if(e&&e.name)return e.name}return"unknown"})(t);return new W(s,e)};var L,K,z,Y,G;(t=>{t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.ADVANCED=2]="ADVANCED",t[t.HIGH=3]="HIGH"})(L||(L={})),(t=>{t[t.NONE=0]="NONE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(K||(K={})),(t=>{t[t.FREE=0]="FREE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(z||(z={}));class Z extends y{get log(){return this._log||(this._log=o.for(this)),this._log}constructor(t){super(t)}logFor(t){const{sessionId:e,requestId:r,authInfo:s}=t||{};let n="string"==typeof e&&e.length>0?this.log.for(e):this.log;return s&&s.clientId&&(n=n.for(s.clientId)),r&&(n=n.for(r.toString())),n}setDescription(t){return this.description=t,this}getDescription(){return this.description}setName(t){return this.name=t,this}getName(){return this.name}setTitle(t){return this.title=t,this}}m([f(),h("design:type",String)],Z.prototype,"description",void 0),m([f(),h("design:type",String)],Z.prototype,"name",void 0),m([f(),h("design:type",String)],Z.prototype,"title",void 0);class V extends Z{constructor(t){super(t),this.reasoning=L.NONE,this.effort=K.NONE,this.cost=z.FREE}setReasoning(t){return this.reasoning=t,this}setEffort(t){return this.effort=t,this}setCost(t){return this.cost=t,this}}function Q(t){if(!t)return;let e=t,r=e&&e._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)e=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)e=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)e=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)e=r.innerType;else{if(!r.schema)return;e=r.schema}r=e&&e._def}return r&&"ZodObject"===r.typeName?r:void 0}function X(t,e="schema"){if(Q(t))return t;if(t&&"object"==typeof t){const e=t.def&&"object"==typeof t.def?t.def:void 0,r=e&&(e.shape||"object"===e.type)&&e.shape||("object"===t.type?t.shape:void 0)||(e&&"object"===e.type?{}:void 0);if(e||"object"===t.type||r){const t={};if(r&&"object"==typeof r)for(const[e,s]of Object.entries(r))t[e]=et(s)?s:v.any();return v.object(t)}}throw Error(`Registration error: provided a non-canonical ${e}. Export a ZodObject (z.object(...)).`)}function tt(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 et(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"})(Y||(Y={})),(t=>{t.PROMPT="prompts",t.DOCUMENTATION="documentation",t.CODE="code"})(G||(G={}));const rt=Buffer.from("DCAF1","ascii");function st(t){let e=E.resolve(t);for(;;){if(r.existsSync(E.join(e,"package.json")))return e;const t=E.dirname(e);if(t===e)break;e=t}}const nt=process.argv?.[1]?st(E.dirname(E.resolve(process.argv[1]))):void 0,it=(()=>{const t=Error().stack;if(!t)return;const e=t.split(/\r?\n/).slice(1);for(const t of e){const e=t.match(/\(?([^()]+?):\d+:\d+\)?/);if(!e)continue;let r=e[1];if(r.startsWith("file://"))try{r=J(r)}catch{continue}if(!r.includes("node:internal"))return E.dirname(r)}})(),ot=it?st(it):void 0,at=nt??ot??process.cwd();function ct(...t){return E.join(at,...t)}function pt(t){let r=t;for(;;){const t=k.join(r,"lib","assets");if(e.existsSync(t))return t;const s=k.join(r,"src","assets");if(e.existsSync(s))return s;const n=k.join(r,"assets");if(e.existsSync(n))return n;const i=k.dirname(r);if(i===r)break;r=i}}function lt(){const t=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(t&&e.existsSync(t))return t;const r=pt(__dirname);if(r)return r;const s=process.argv?.[1];if(s){const t=pt(k.dirname(s));if(t)return t}const n=[at,process.env.INIT_CWD].filter(Boolean);for(const t of n){const e=pt(t);if(e)return e}return ct("assets")}let ut=class extends a{constructor(t){super(),this.basePath=t||lt()}listAssets(...t){const r=k.join(this.basePath,...t);return e.readdirSync(r)}listPrompts(){return this.listAssets(G.PROMPT)}getAsset(t,r="md",...s){const n=k.join(this.basePath,...s),i=(t,r=!1)=>{try{return r?(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 r=rt.length;const s=t.subarray(r,r+16);r+=16;const n=t.subarray(r,r+12);r+=12;const i=t.subarray(r,r+16);r+=16;const o=t.subarray(r),a=((t,e)=>N.scryptSync(t,e,32))(e,s),c=N.createDecipheriv("aes-256-gcm",a,n);c.setAuthTag(i);const p=Buffer.concat([c.update(o),c.final()]);return C.gunzipSync(p)})(e.readFileSync(t)).toString("utf-8"):e.readFileSync(t,"utf-8")}catch(t){if("ENOENT"===t.code)return null;throw t}},o=i(k.join(n,`${t}.${r}`),"enc"===r);if(null!==o)return o;const a=i(k.join(n,t+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+k.join(n,`${t}.${r}`))}getAllAssets(t,...e){return this.listAssets(t,...e).reduce((r,s)=>{const n=k.extname(s),i=k.basename(s,n),o=n.replace(/^\./,"")||void 0;return r[i]=this.getAsset(i,o??void 0,t,...e),r},{})}toPromptDef(t){const e=t=>"number"==typeof t?t:"string"==typeof t?(t=>{switch(t){case"none":return L.NONE;case"basic":return L.BASIC;case"advanced":return L.ADVANCED;case"high":return L.HIGH;case"medium":return K.MEDIUM;case"low":return z.LOW;case"free":return z.FREE;default:throw new A("Cannon convert unknown level "+t)}})(t.toLowerCase()):L.NONE;return t.effort=e(t.effort),t.reasoning=e(t.reasoning),t.cost=e(t.cost),t}getPrompt(t,...e){const r=this.getAsset(c(t),"json",G.PROMPT,...e);let s;try{s=JSON.parse(r)}catch(r){throw new T(`Failed to parse prompt ${t} in categories ${e}: ${r}`)}return this.toPromptDef(s)}getAllPrompts(...t){const e=this.getAllAssets(G.PROMPT,...t);return Object.entries(e).reduce((e,[r,s])=>{try{e[r]=JSON.parse(s)}catch(e){throw new T(`Failed to parse prompt ${r} in categories ${t}: ${e}`)}return e},e)}};ut=m([S(),h("design:paramtypes",[String])],ut);class dt 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 dt}static patchPrompt(t,e,r,s){const n=(e=Array.isArray(e)?e:Object.keys(e)).filter(t=>!Object.prototype.hasOwnProperty.call(r,t));if(n.length)throw new O("Missing replacements for placeholders: "+n.join(", "));s&&(s.verbose("Patching prompt with placeholders: "+JSON.stringify(e)),s.debug("Values: "+JSON.stringify(r)));const i=e.reduce((t,e)=>(t[e]=r[e],t),{});return p(t,i)}patchPrompt(t,e,r,s){return dt.patchPrompt(t,e,r,s||this.log.for(this.patchPrompt))}build(t,e){const r=this.log.for(this.build),s=this.hasErrors();if(s)throw new O(s.toString());try{this.argsSchema&&X(this.argsSchema,"argsSchema");const r=tt(this.argsSchema);return t.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(t,r)=>{const s=this.logFor(r);t=Object.assign({},e,t||{}),s.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(t)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const n=await Promise.resolve(this.cb(t,r));return s.verbose(`Prompt ${this.name} executed successfully.`),s.debug("Prompt execution meta: "+JSON.stringify(n._meta)),n})}catch(t){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),t),t}}}m([j(ut),h("design:type",ut)],dt.prototype,"assets",void 0),m([f(),h("design:type",Object)],dt.prototype,"cb",void 0),m([f(),h("design:type",w)],dt.prototype,"argsSchema",void 0),m([x(),h("design:type",Object)],dt.prototype,"placeholders",void 0);class mt extends dt{setCategory(t){return this.promptCategory=t,this}addPrefix(t){return this.prefixes=this.prefixes||[],this.prefixes.push(t),this}addSuffix(t){return this.suffixes=this.suffixes||[],this.suffixes.push(t),this}constructor(t){super(t)}build(t){const e=this.assets.getPrompt(this.name,this.promptCategory);y.fromObject(this,e);const r=new Set((I.properties(mt)||[]).filter(t=>!["assets","promptCategory","prefixes","suffixes"].includes(t)));["cb","argsSchema"].forEach(t=>r.add(t));const s=this.hasErrors(...Array.from(r));if(s)throw new O(s.toString());const n=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=[...new Set([...e.placeholders,...n.map(t=>t.placeholders||[]),...i.map(t=>t.placeholders||[])].flat())].reduce((t,e)=>(t[e]=v.string().describe("The description for "+e),t),{});return this.setArgsSchema(v.object(o)),this.setCb((t,e)=>{const r=this.logFor(e).for(mt).for(this.promptCategory).for(this.name);function s(t=[]){return Array.isArray(t)?t:Object.keys(t)}const n=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...n.map(t=>s(t.placeholders)).flat(),...i.map(t=>s(t.placeholders)).flat(),...s(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...n.map(t=>t.prompt),o.prompt,...i.map(t=>t.prompt)].join("\n\n"),a,t,r)}}],_meta:{}}}),super.build(t)}setReasoning(t){throw new A("Named prompt builders don't require callback")}setEffort(t){throw new A("Named prompt builders don't require callback")}setCost(t){throw new A("Named prompt builders don't require callback")}setDescription(t){throw new A("Named prompt builders don't require callback")}setTitle(t){throw new A("Named prompt builders don't require callback")}static get builder(){return new mt}}m([f(),h("design:type",String)],mt.prototype,"promptCategory",void 0),m([g(String),b(1),h("design:type",Array)],mt.prototype,"prefixes",void 0),m([b(1),g(String),h("design:type",Array)],mt.prototype,"suffixes",void 0);const ht=dt.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(v.object({message:v.string().optional()})).setCb(async t=>{const e=t.message??"default";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),ft=dt.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc prompt").setDescription("Interactive prompt for jogging JSDoc helpers").setArgsSchema(v.object({gist:v.string().optional()})).setCb(async t=>{const e=t.gist??"interactive jsdoc response";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),yt=Object.assign(ft,{name:ft.getName()});var gt;function bt(t,e=[],r=[]){const s=mt.builder.setCategory(gt.DOCS).setName(t);return["prefix",...e].forEach(t=>s.addPrefix(t)),["suffix",...r].forEach(t=>s.addSuffix(t)),s}(t=>{t.DOCS="documentation",t.CODE="code"})(gt||(gt={}));const vt=[bt("class"),bt("constant"),bt("decorator"),bt("function"),bt("module"),bt("file"),bt("repo",[],["iterate"])],wt=v.object({className:v.string().describe("the class name to turn into a builder")}),St=[ht,yt,...vt,dt.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(wt).setReasoning(L.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&&X(this.inputSchema,"inputSchema"),this.outputSchema&&X(this.outputSchema,"outputSchema");const e=tt(this.inputSchema),r=tt(this.outputSchema);return t.registerTool(this.name,{title:this.title,description:this.description,inputSchema:e,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(t,e)=>{const r=this.logFor(e);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(t)}`),e._meta=Object.assign(e._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(t,e));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(s._meta)),s})}catch(t){const e=t?.message||t+"";if("string"==typeof e&&e.includes("already registered"))return o.for(this).warn(`Tool ${this.name} already registered - skipping duplicate registration`),{name:this.name};throw o.for(this).error("Error building tool",t),t}}}m([f(),h("design:type",Object)],jt.prototype,"annotations",void 0),m([f(),h("design:type",Object)],jt.prototype,"cb",void 0),m([f(),h("design:type",Function)],jt.prototype,"inputSchema",void 0);const xt=jt.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(v.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(xt,{name:xt.getName()});const It=jt.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(v.object({filePath:v.string().optional()})).setCb(async()=>({content:[{type:"text",text:"file summary stub"}],result:{summary:"file summary stub"}}));function kt(){try{let t=process.argv[1]?E.dirname(E.resolve(process.argv[1])):process.cwd();for(;;){const e=E.join(t,"package.json");if(r.existsSync(e))return JSON.parse(r.readFileSync(e,"utf-8"));const s=E.dirname(t);if(s===t)break;t=s}}catch{}return{}}Object.assign(It,{name:It.getName()});const Et=kt().version??"0.0.0",At=kt().name??"unknown";I.registerLibrary(At,Et);const Tt={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:Et,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:at,assetDir:lt(),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},level:u.error},Ot=d.accumulate(Tt);function Nt(){const{host:t,email:e,apiKey:r,projectKey:s,issueType:n}=Ot.jira;return{host:t?.trim(),email:e?.trim(),apiKey:r?.trim(),projectKey:s?.trim(),issueType:n?.trim(),parentIssue:Ot.jira.parentIssue?.trim()}}function Ct(){const t=Nt();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 Jt(t){const e=t.value?((t,e)=>{if(t)return e?"<configured>":t})(t.value,t.sensitive):"not set",r=t.required?"(required)":"(optional)";return`\u2022 ${t.name} ${r}: ${t.description} Current state: ${e}.`}o.setConfig(Ot);class Ht extends Error{constructor(t){const e=Ct(),r=(t=>{const e=Ct();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(Jt).join("\n")}`})(t);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=e,this.missing=t,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ht)}}function _t(t){if(!t)return{code:"jira_error",message:"Unknown Jira error",details:{raw:t}};const e=t?.status??t?.statusCode??t?.response?.status??t?.response?.statusCode,r="number"==typeof e?e:Number(e)||void 0,s=t?.response?.data??t?.data??t?.response?.body??t?.body,n=[];"string"==typeof t?.message&&n.push(t.message),((t,e)=>{t&&(Array.isArray(t.errorMessages)&&t.errorMessages.forEach(t=>"string"==typeof t&&e.push(t)),"string"==typeof t.errorMessage&&e.push(t.errorMessage),t.errorCollection&&Array.isArray(t.errorCollection.errors)&&t.errorCollection.errors.forEach(t=>{"string"==typeof t?e.push(t):t&&"string"==typeof t.message&&e.push(t.message)}),t?.errors&&"object"==typeof t.errors&&Object.values(t.errors).forEach(t=>{"string"==typeof t?e.push(t):"string"==typeof t?.message&&e.push(t.message)}))})(s,n);const i=r?`Jira API error (${r})`:"Jira API error",o=n.length>0?n.join(" | "):i;return{code:r?"jira_"+r:t?.code??"jira_error",message:o,details:{httpStatus:r,body:s,raw:t}}}function $t(t={},e=[]){return{content:e,result:t,structuredContent:t}}const Dt=v.object({issueId:v.string().min(1),deleteSubtasks:v.boolean().optional().default(!0)}),Pt={name:"jira-issue-delete",inputSchema:Dt,runTool:async(t,e)=>{try{const r=Dt.parse(e),s=t.issues??t.issue??t,n=s?.delete??s?.deleteIssue;if("function"!=typeof n)throw Error("jira client delete endpoint is not available");return await n.call(s,{issueId:r.issueId,deleteSubtasks:r.deleteSubtasks}),$t({success:!0,message:`Issue ${e.issueId} deleted successfully`})}catch(t){throw _t(t)}}},Rt=v.object({projectKey:v.string().trim().min(1).optional(),issueType:v.string().trim().min(1).optional(),parentIssueId:v.string().trim().min(1).optional(),name:v.string().trim().min(1).optional(),reference:v.string().trim().min(1).optional(),jql:v.string().trim().min(1).optional(),startAt:v.number().int().min(0).optional(),maxResults:v.number().int().min(1).optional(),fields:v.array(v.string()).optional(),expand:v.string().optional(),orderBy:v.string().trim().min(1).optional()});function Mt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const qt={name:"jira-issue-list",inputSchema:Rt,runTool:async(t,e)=>{try{const r=Rt.parse(e),s=r.startAt??0,n=r.maxResults??50;let i=r.jql?.trim();if(i){if(r.orderBy){const t=r.orderBy.trim();t&&(i=/\border\s+by\b/i.test(i)?`${i}, ${t}`:`${i} ORDER BY ${t}`)}}else i=(t=>{const e=[];if(t.projectKey&&e.push(`project = "${Mt(t.projectKey)}"`),t.issueType&&e.push(`issuetype = "${Mt(t.issueType)}"`),t.parentIssueId&&e.push(`parent = "${Mt(t.parentIssueId)}"`),t.name&&e.push(`summary ~ "${Mt(t.name)}"`),t.reference){const r=Mt(t.reference);e.push(`(key ~ "${r}" OR summary ~ "${r}" OR text ~ "${r}")`)}if(0===e.length){const t=Error("Provide a jql query or at least one filter (project, name, reference, parent, issue type, etc.).");throw t.code="validation_error",t}let r=e.join(" AND ");if(t.orderBy){const e=t.orderBy.trim();e&&(r=/\border\s+by\b/i.test(r)?`${r}, ${e}`:`${r} ORDER BY ${e}`)}return r})(r);const o={jql:i,startAt:s,maxResults:n};r.fields&&(o.fields=r.fields),r.expand&&(o.expand=r.expand);const a=t.issueSearch,c=a&&"function"==typeof a.searchForIssuesUsingJqlEnhancedSearch?a.searchForIssuesUsingJqlEnhancedSearch:a&&"function"==typeof a.searchForIssuesUsingJql?a.searchForIssuesUsingJql:void 0;if(!c)throw Error("Jira search API is unavailable on the client");const p=await c.call(a,o);return $t(p?.data??p)}catch(t){throw _t(t)}}},Ft=v.object({issueId:v.string().min(1),expand:v.string().optional(),fields:v.array(v.string()).optional(),properties:v.array(v.string()).optional()}),Bt={name:"jira-issue-read",inputSchema:Ft,runTool:async(t,e)=>{try{const r=Ft.parse(e),s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand),r.fields&&(s.fields=r.fields),r.properties&&(s.properties=r.properties);const n=await t.issues.get(s);return $t(n?.data??n)}catch(t){throw _t(t)}}};function Wt(t,e,r){const s=((t.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!s)return null;const n=s[2],i=r.resolveAttachment?.(n);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Ut(t,e){if(!t)return[];if(!e.enableAtMentions&&!e.enableEmojiShortcodes)return[{type:"text",text:t}];let r=0;const s=[],n=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;r<t.length;){const o=Kt(e.enableAtMentions?Lt(n,t,r):null,e.enableEmojiShortcodes?Lt(i,t,r):null);if(!o){s.push({type:"text",text:t.slice(r)});break}if(o.index>r&&s.push({type:"text",text:t.slice(r,o.index)}),"mention"===o.kind){const{full:t,groups:n}=o,i=n[0]??"",a=n[1]??"";i&&s.push({type:"text",text:i});const c=e.resolveMention?.(a);c?s.push({type:"mention",attrs:{id:c.id,text:c.text}}):s.push({type:"text",text:"@"+a}),r=o.index+t.length;continue}if("emoji"===o.kind){const{full:t,groups:n}=o,i=`:${n[0]}:`,a=e.resolveEmoji?.(i);s.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:i}}),r=o.index+t.length;continue}}return(t=>{const e=[];for(const r of t){const t=e[e.length-1];"text"!==r.type||"text"!==t?.type||t.marks||r.marks?e.push(r):t.text=(t.text??"")+(r.text??"")}return e})(s)}function Lt(t,e,r){t.lastIndex=r;const s=t.exec(e);if(!s)return null;const n=t.source.includes("@")?"mention":"emoji";return{index:s.index,full:s[0],groups:s.slice(1),kind:n}}function Kt(t,e){return t?e&&t.index>e.index?e:t:e}function zt(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 Yt(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 Gt(t){const e=((t??"")+"").toLowerCase().trim();return!e||"neutral"!==e&&"green"!==e&&"yellow"!==e&&"red"!==e&&"blue"!==e&&"purple"!==e?null:e}function Zt(t,e){const r=[];for(const s of t??[])if(s?.type)if("text"!==s.type)if("strong"!==s.type)if("emphasis"!==s.type)if("delete"!==s.type)if("inlineCode"!==s.type)if("break"!==s.type){if("link"===s.type){const t=(s.url??"")+"",n=Qt(s.children??[],t),i=Wt(s,0,e);if(i){"inline"===i.type?r.push(i.node):r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:t}}]});continue}if(e.enableSmartCards&&Xt(n,t)){r.push({type:"inlineCard",attrs:{url:t}});continue}r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:t}}]});continue}if("textDirective"===s.type&&"status"===s.name){const t=zt(s)||"Status",e=Gt(s.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:t,color:e}});continue}if("textDirective"===s.type&&"emoji"===s.name){const t=te(s);r.push(ee(t,e));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(s.value??"")+"",marks:[{type:"code"}]});else r.push(...Vt(Zt(s.children??[],e),{type:"strike"}));else r.push(...Vt(Zt(s.children??[],e),{type:"em"}));else r.push(...Vt(Zt(s.children??[],e),{type:"strong"}));else r.push(...Ut((s.value??"")+"",e));return r.filter(t=>!("text"===t.type&&""===(t.text??"")))}function Vt(t,e){return t.map(t=>{if("text"!==t.type)return t;const r=t.marks?[...t.marks,e]:[e];return{...t,marks:r}})}function Qt(t,e){const r=[];for(const e of t??[])"text"===e.type||"inlineCode"===e.type?r.push((e.value??"")+""):"emphasis"!==e.type&&"strong"!==e.type&&"delete"!==e.type||r.push(Qt(e.children??[],""));return r.join("")||e}function Xt(t,e){const r=(t??"").trim(),s=(e??"").trim();return r===s&&/^https?:\/\//i.test(s)}function te(t){return(t.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("").trim()||""}function ee(t,e){const r=t.startsWith(":")?t:`:${t}:`,s=e.resolveEmoji?.(r);return s?{type:"emoji",attrs:{shortName:s.shortName,text:s.text}}:{type:"emoji",attrs:{shortName:r}}}function re(t){return t?"string"==typeof t?t:"text"===t.type||"inlineCode"===t.type?(t.value??"")+"":Array.isArray(t.children)?t.children.map(re).join(""):"":""}function se(t,e){if(!t?.type)return null;if((t=>"containerDirective"===t?.type&&"panel"===t?.name)(t))return((t,e)=>{const r=t.attributes??{},s=Yt(r.type)??"info",n="string"==typeof r.title?r.title:void 0,i=(t.children??[]).map(t=>se(t,e)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:s,...n?{panelType:s,title:n}:{panelType:s}},content:i.length?i:[{type:"paragraph",content:[]}]}})(t,e);switch(t.type){case"heading":return{type:"heading",attrs:{level:ie(t.depth??1,1,6)},content:Zt(t.children??[],e)};case"paragraph":return(t=>{const e=t.children??[];if(1!==e.length)return null;const r=e[0];if("image"!==r?.type)return null;const s=(r.url??"")+"";return s?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:s}}]}:null})(t)||{type:"paragraph",content:Zt(t.children??[],e)};case"blockquote":return{type:"blockquote",content:(t.children??[]).map(t=>se(t,e)).flat().filter(Boolean)};case"list":return((t,e)=>e.enableTaskLists&&(t.children??[]).some(t=>"boolean"==typeof t.checked)?((t,e)=>{const r=[];let s=0;for(const n of t.children??[]){if("boolean"!=typeof n.checked)continue;s+=1;const t=(n.children??[]).map(t=>se(t,e)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+s,state:n.checked?"DONE":"TODO"},content:t.length?t:[{type:"paragraph",content:[]}]})}return{type:"taskList",content:r}})(t,e):{type:t.ordered?"orderedList":"bulletList",content:(t.children??[]).map(t=>((t,e)=>{const r=(t.children??[]).map(t=>se(t,e)).flat().filter(Boolean);return{type:"listItem",content:r.length?r:[{type:"paragraph",content:[]}]}})(t,e))})(t,e);case"code":{const r=((t,e)=>{const r=(t??"").toString().trim().toLowerCase();return r?e.enableMermaid&&"mermaid"===r?"mermaid":(t=>{const e=t.trim().toLowerCase();return{js:"javascript",javascript:"javascript",jsx:"javascript",ts:"typescript",typescript:"typescript",tsx:"typescript",py:"python",python:"python",rb:"ruby",ruby:"ruby",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",yml:"yaml",yaml:"yaml",json:"json",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",sql:"sql",go:"go",rust:"rust",java:"java",c:"c",cpp:"cpp","c++":"cpp",cs:"csharp",csharp:"csharp",php:"php",kotlin:"kotlin",swift:"swift",md:"markdown",markdown:"markdown",graphql:"graphql",gql:"graphql",dockerfile:"docker",makefile:"make",ini:"ini"}[e]??e})(r):null})(t.lang,e);return{type:"codeBlock",attrs:{language:r},content:[{type:"text",text:(t.value??"")+""}]}}case"thematicBreak":return{type:"rule"};case"table":return((t,e)=>({type:"table",content:(t.children??[]).map((t,r)=>({type:"tableRow",content:(t.children??[]).map(t=>({type:0===r?"tableHeader":"tableCell",content:[{type:"paragraph",content:Zt(t.children??[],e)}]}))}))}))(t,e);case"leafDirective":return"status"===t.name?(t=>{const e=Gt((t.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:zt(t)||"Status",color:e}}]}})(t):"panel"===t.name?((t,e)=>{const r=t.attributes??{},s=Yt(r.type)??"info",n="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:s,...n?{title:n}:{}},content:[{type:"paragraph",content:Zt([{type:"text",value:zt(t)}],e)}]}})(t,e):ne(t,e);default:return ne(t,e)}}function ne(t,e){if("drop"===e.unknownNodeStrategy)return null;const r=re(t);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function ie(t,e,r){const s=Number.isFinite(t)?Math.trunc(t):e;return Math.max(e,Math.min(r,s))}const oe={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function ae(t,e={}){const r={...oe,...e},s=t??"",n=H().use(D).use($).use(_),i=n.parse(s),o=n.runSync(i);return ce(o),((t,e)=>{const r=[];for(const s of t.children??[]){const t=se(s,e);t&&(Array.isArray(t)?r.push(...t):r.push(t))}return((t,e)=>{if(!e.enableSmartCards)return t;const r=t.content.map(t=>(t=>{if("paragraph"!==t.type)return t;const e=t.content??[];if(1!==e.length)return t;const r=e[0];if("inlineCard"!==r?.type)return t;const s=r.attrs?.url;return s?[{type:"blockCard",attrs:{url:s}}]:t})(t)).flat();return{...t,content:r}})({version:1,type:"doc",content:r},e)})(o,r)}function ce(t){if(!t||!Array.isArray(t.children))return;const e=[];for(const r of t.children)"definition"!==r?.type&&("html"!==r?.type?(ce(r),e.push(r)):e.push({type:"text",value:(r.value??"")+""}));t.children=e}const pe=v.object({issueId:v.string().min(1),transitionId:v.union([v.string(),v.number()]),fields:v.record(v.any()).optional(),update:v.record(v.array(v.object({set:v.any().optional(),add:v.any().optional(),remove:v.any().optional()}))).optional(),comment:v.string().optional()}),le={name:"jira-issue-transition",inputSchema:pe,runTool:async(t,e)=>{try{const r=pe.parse(e),s={id:r.transitionId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.comment&&(s.comment={body:ae(r.comment)});const n=await t.issues.transition({issueId:r.issueId,transition:s});return $t(n?.data??n)}catch(t){throw _t(t)}}},ue=v.object({issueId:v.string().min(1),fields:v.record(v.any()).optional(),update:v.record(v.array(v.object({set:v.any().optional(),add:v.any().optional(),remove:v.any().optional(),edit:v.any().optional()}))).optional(),properties:v.array(v.any()).optional(),notifyUsers:v.boolean().optional().default(!0),issueTemplateId:v.string().optional(),overrideScreenSecurity:v.boolean().optional().default(!1),overrideEditableFlag:v.boolean().optional().default(!1)}),de={name:"jira-issue-update",inputSchema:ue,runTool:async(t,e)=>{try{const r=ue.parse(e),s={issueId:r.issueId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.properties&&(s.properties=r.properties),void 0!==r.notifyUsers&&(s.notifyUsers=r.notifyUsers),r.issueTemplateId&&(s.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(s.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(s.overrideEditableFlag=r.overrideEditableFlag);const n=await t.issues.update(s);return $t(n?.data??n)}catch(t){throw _t(t)}}},me=v.object({issueId:v.string().min(1),assignee:v.union([v.string(),v.object({accountId:v.string().min(1)}),v.object({accountType:v.string().min(1)})])}),he={name:"jira-assign-issue",inputSchema:me,runTool:async(t,e)=>{try{const r=me.parse(e);let s;s="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const n=await t.issues.assign({issueId:r.issueId,assignee:s});return $t(n?.data??n)}catch(t){throw _t(t)}}},fe=v.object({issueId:v.string().min(1)}),ye={name:"jira-unassign-issue",inputSchema:fe,runTool:async(t,e)=>{try{const r=fe.parse(e),s=await t.issues.assign({issueId:r.issueId,assignee:{accountId:"-1"}});return $t(s?.data??s)}catch(t){throw _t(t)}}},ge=v.object({issueId:v.string().min(1),body:v.string().min(1),visibility:v.object({type:v.enum(["role","group"]),value:v.string().min(1)}).optional()}),be={name:"jira-comment-add",inputSchema:ge,runTool:async(t,e)=>{try{const r=ge.parse(e),s={body:ae(r.body)};r.visibility&&(s.visibility=r.visibility);const n=await t.issues.addComment({issueId:r.issueId,comment:s});return $t(n?.data??n)}catch(t){throw _t(t)}}},ve=v.object({issueId:v.string().min(1),start:v.number().optional().default(0),maxResults:v.number().optional().default(50),orderBy:v.string().optional(),expand:v.string().optional()}),we={name:"jira-comment-list",inputSchema:ve,runTool:async(t,e)=>{try{const r=ve.parse(e),s=await t.issues.getComments({issueId:r.issueId,start:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return $t(s?.data??s)}catch(t){throw _t(t)}}},Se=v.object({link:v.object({relationship:v.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]),inwardIssue:v.object({id:v.string().optional(),key:v.string().optional()}),outwardIssue:v.object({id:v.string().optional(),key:v.string().optional()}),comment:v.object({body:v.string().optional(),visibility:v.object({type:v.enum(["role","group"]),value:v.string().min(1)}).optional()}).optional()})}),je={name:"jira-link-create",inputSchema:Se,runTool:async(t,e)=>{try{const r=Se.parse(e).link,s={relationship:r.relationship,inwardIssue:r.inwardIssue.id||r.inwardIssue.key,outwardIssue:r.outwardIssue.id||r.outwardIssue.key};r.comment&&(r.comment.body&&(s.comment=ae(r.comment.body)),r.comment.visibility&&(s.visibility=r.comment.visibility));const n=await t.issues.link(s);return $t(n?.data??n)}catch(t){throw _t(t)}}},xe=v.object({issueId:v.string().min(1),file:v.string().min(1),mimeType:v.string().optional(),comment:v.string().optional()}),Ie={name:"jira-attach",inputSchema:xe,runTool:async(t,e)=>{try{const r=xe.parse(e),n=E.resolve(r.file),i=await s.readFile(n),o=E.basename(n),a=await t.issues.addAttachment({issueId:r.issueId,file:{name:o,content:i,mimeType:r.mimeType??"application/octet-stream"},comment:r.comment});return $t(a?.data??a)}catch(t){if(t&&t.code&&"string"==typeof t.code&&["ENOENT","EACCES"].includes(t.code))throw Error("Attachment file error: "+t.message);throw _t(t)}}},ke=v.object({issueId:v.string().min(1)}),Ee={name:"jira-attachment-list",inputSchema:ke,runTool:async(t,e)=>{try{const r=ke.parse(e),s=await t.issues.getAttachments({issueId:r.issueId});return $t(s?.data??s)}catch(t){throw _t(t)}}},Ae=v.object({issueId:v.string().min(1),attachmentId:v.string().min(1)}),Te={name:"jira-attachment-delete",inputSchema:Ae,runTool:async(t,e)=>{try{const r=Ae.parse(e);return await t.issues.deleteAttachment({issueId:r.issueId,attachmentId:r.attachmentId}),$t({success:!0,message:`Attachment ${e.attachmentId} deleted successfully`})}catch(t){throw _t(t)}}},Oe=v.object({issueId:v.string().min(1),timeSpent:v.string().min(1),comment:v.string().optional(),author:v.object({accountId:v.string().min(1)}).optional(),startingOn:v.string().optional(),artifact:v.string().optional()}),Ne={name:"jira-worklog-add",inputSchema:Oe,runTool:async(t,e)=>{try{const r=Oe.parse(e),s={timeSpent:r.timeSpent};r.comment&&(s.comment=r.comment),r.author&&(s.author=r.author),r.startingOn&&(s.started=r.startingOn),r.artifact&&(s.artifact=r.artifact);const n=await t.issues.addWorklog({issueId:r.issueId,...s});return $t(n?.data??n)}catch(t){throw _t(t)}}},Ce={[Bt.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[qt.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}},[de.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}},[Pt.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[le.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[he.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ye.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[be.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}},[we.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[je.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ie.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ee.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Te.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Ne.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}}};async function Je(t){const e=o.for(Je);let r,s=null;try{r=(()=>{let t;try{const e=require("jira.js");t=e?.Version3Client||e.default?.Version3Client||e.default||e}catch(t){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+t)}const{host:e,email:r,apiKey:s}=(()=>{const t=Nt(),e=Ct().filter(t=>t.required&&!t.value);if(e.length>0)throw new Ht(e);return{host:t.host,email:t.email,apiKey:t.apiKey}})();return new t({host:e.startsWith("http://")||e.startsWith("https://")?e:"https://"+e,authentication:{basic:{email:r,apiToken:s}}})})()}catch(t){if(!(t instanceof Ht))return void e.warn("Skipping Jira tool registration; unable to create Jira client",{error:t});s=t,e.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:t})}const n=[Bt,qt,de,Pt,le,he,ye,be,we,je,Ie,Ee,Te,Ne];for(const i of n){const n=Ce[i.name];if(n)try{await t.registerTool(i.name,{title:n.title,description:n.description,inputSchema:tt(i.inputSchema),annotations:n.annotations},async t=>{if(!r)throw s??Error("Jira client unavailable because credentials could not be loaded.");return i.runTool(r,t)}),e.info("Registered Jira tool "+i.name)}catch(t){e.error("Failed to register Jira tool "+i.name,{error:t})}}}async function He(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: "+Ot.name,"Title: "+Ot.title,"Version: "+Ot.version,"Prompts: "+(t.join(", ")||"<none>")].join("\n")}]}})})(t);const e=o.for(He);try{await Je(t)}catch(t){e.error("Failed to register Jira tools",t)}}class _e 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 _e}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{const e="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new R(new P(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),s=async(t,e)=>{const r=this.logFor(e);r.verbose(`Requesting resource ${this.name} from ${t.toString()}`);const s=await Promise.resolve(this.cb(t,e));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(s._meta)),s};return t.resource(this.name,e,r,s)}catch(t){throw o.for(this).error("Error registering resource "+this.name,t),t}}}m([f(),h("design:type",String)],_e.prototype,"uriOrTemplate",void 0),m([f(),h("design:type",Function)],_e.prototype,"cb",void 0),m([f(),h("design:type",Object)],_e.prototype,"config",void 0);const $e=lt()??k.join(__dirname,"..","assets"),De=k.join($e,"templates"),Pe=k.join($e,"prompts"),Re=new WeakMap;class Me extends a{get client(){const t=Re.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 r=e.build(this.client);t.verbose(`Loaded prompt ${r.title} from ${e.getName()} definition`)}catch(r){t.error("Failed to load prompt "+e.getName(),r)}try{await He(this.client),t.verbose("Registered built-in tools")}catch(t){}try{await(async(t,r)=>{r.info("Registering agent templates as resources...");const s=e.readdirSync(De).filter(t=>t.endsWith(".md"));for(const n of s){const s=k.basename(n,".md"),i=k.join(De,n),o=_e.builder.setName(s).setTitle("Template: "+s).setDescription("Resource template for "+s).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+s}).setCb(async t=>{const r=e.readFileSync(t.pathname,"utf8");return{contents:[{uri:t.toString(),text:r,mimeType:"text/markdown"}],_meta:{}}});try{o.build(t),r.info("Registered template: "+s)}catch(t){r.error(`Failed to register template ${s}:`,t)}}r.info("Registering agent prompts...");const n=e.readdirSync(Pe).filter(t=>t.endsWith(".md"));for(const s of n){const n=k.basename(s,".md"),i=k.join(Pe,s),o=e.readFileSync(i,"utf8"),a=dt.builder.setName(n).setTitle("Prompt: "+n).setDescription("Dynamic prompt for "+n).setArgsSchema(v.object({})).setCb(async t=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(t),r.info("Registered prompt: "+n)}catch(t){r.error(`Failed to register prompt ${n}:`,t)}}})(this.client,t)}catch(t){}}async boot(t="stdio"){"stdio"===t&&o.setFactory(U),o.for(this.constructor.name);const e=((Array.isArray(Ot.icons)?Ot.icons:[Ot.icons])||[]).map(t=>{const e="string"==typeof t?.src?t.src:(t?.src??"")+"",r="string"==typeof t?.mimeType?t.mimeType:(t?.mimeType??"")+"";let s=[];return Array.isArray(t?.sizes)?s=t.sizes.map(t=>t+""):"string"==typeof t?.sizes&&(s=(t.sizes+"").split(",").map(t=>t.trim())),{src:e,mimeType:r,sizes:s}}),r={name:Ot.name,title:Ot.title,websiteUrl:Ot.websiteUrl,version:Ot.version,icons:e},s=new M(r,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((t,e)=>{Re.set(t,e)})(this,s),s.onerror=t=>{this.log.error("MCP instance onerror",t)},t){case"stdio":t=new F;break;case"http":t=new B({sessionIdGenerator:()=>q(),onsessioninitialized:t=>{},onsessionclosed:t=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(n=t)||"object"!=typeof n||"function"!=typeof n.send&&"function"!=typeof n.close&&"function"!=typeof n.on)throw new A("Invalid transport type: "+t)}var n;try{await this.load()}catch(t){throw t}await this.client.connect(t)}}const qe=(new t).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async t=>{const e=ct("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version,{transport:i}=t,o=(new W).for("mcp-server");if("stdio"!==i)throw Error("Unsupported transport mode: "+i);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(t)} for ${s.name} version ${n}`),(new Me).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=ct("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version;o.for("md-to-ast").debug(`running with options: ${JSON.stringify(t)} for ${s.name} version ${n}`);const i=ae(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 Fe=(new t).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");Fe.addCommand(qe),Fe.parse(process.argv);
1
+ import{Command as t}from"commander";import*as e from"fs";import r,{promises as s}from"fs";import{MiniLogger as n,NumericLogLevels as i,Logging as o,LoggedClass as a,toSnakeCase as c,sf as p,toPascalCase as l,LogLevel as u,LoggedEnvironment as d}from"@decaf-ts/logging";import{__decorate as m,__metadata as h}from"tslib";import{required as f,Model as y,list as g,minlength as b}from"@decaf-ts/decorator-validation";import{z as v,ZodObject as w}from"zod";import{injectable as S,inject as j}from"@decaf-ts/injectable-decorators";import{prop as x,Metadata as I}from"@decaf-ts/decoration";import*as k from"path";import E from"path";import{InternalError as A,SerializationError as T,ValidationError as O}from"@decaf-ts/db-decorators";import N from"crypto";import C from"zlib";import{fileURLToPath as J}from"url";import{unified as H}from"unified";import _ from"remark-directive";import $ from"remark-gfm";import D from"remark-parse";import{UriTemplate as P}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";import{ResourceTemplate as R,McpServer as M}from"@modelcontextprotocol/sdk/server/mcp.js";import{v4 as q}from"uuid";import{StdioServerTransport as F}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as B}from"@modelcontextprotocol/sdk/server/streamableHttp.js";class W extends n{constructor(t,e,r){super(t,e,r)}log(t,e,r,s){const n=this.config("level");i[n],i[t]}}const U=(t,e,...r)=>{const s=(t=>{if("string"==typeof t)return t;if(!t)return"unknown";if("function"==typeof t)return t.name||"unknown";if("object"==typeof t&&"constructor"in t){const e=t.constructor;if(e&&e.name)return e.name}return"unknown"})(t);return new W(s,e)};var L,K,z,Y,G;(t=>{t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.ADVANCED=2]="ADVANCED",t[t.HIGH=3]="HIGH"})(L||(L={})),(t=>{t[t.NONE=0]="NONE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(K||(K={})),(t=>{t[t.FREE=0]="FREE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(z||(z={}));class Z extends y{get log(){return this._log||(this._log=o.for(this)),this._log}constructor(t){super(t)}logFor(t){const{sessionId:e,requestId:r,authInfo:s}=t||{};let n="string"==typeof e&&e.length>0?this.log.for(e):this.log;return s&&s.clientId&&(n=n.for(s.clientId)),r&&(n=n.for(r.toString())),n}setDescription(t){return this.description=t,this}getDescription(){return this.description}setName(t){return this.name=t,this}getName(){return this.name}setTitle(t){return this.title=t,this}}m([f(),h("design:type",String)],Z.prototype,"description",void 0),m([f(),h("design:type",String)],Z.prototype,"name",void 0),m([f(),h("design:type",String)],Z.prototype,"title",void 0);class V extends Z{constructor(t){super(t),this.reasoning=L.NONE,this.effort=K.NONE,this.cost=z.FREE}setReasoning(t){return this.reasoning=t,this}setEffort(t){return this.effort=t,this}setCost(t){return this.cost=t,this}}function Q(t){if(!t)return;let e=t,r=e&&e._def;for(;r&&"ZodObject"!==r.typeName;){if("ZodEffects"===r.typeName&&r.schema)e=r.schema;else if("ZodOptional"===r.typeName&&r.innerType)e=r.innerType;else if("ZodDefault"===r.typeName&&r.innerType)e=r.innerType;else if("ZodNullable"===r.typeName&&r.innerType)e=r.innerType;else{if(!r.schema)return;e=r.schema}r=e&&e._def}return r&&"ZodObject"===r.typeName?r:void 0}function X(t,e="schema"){if(Q(t))return t;if(t&&"object"==typeof t){const e=t.def&&"object"==typeof t.def?t.def:void 0,r=e&&(e.shape||"object"===e.type)&&e.shape||("object"===t.type?t.shape:void 0)||(e&&"object"===e.type?{}:void 0);if(e||"object"===t.type||r){const t={};if(r&&"object"==typeof r)for(const[e,s]of Object.entries(r))t[e]=et(s)?s:v.any();return v.object(t)}}throw Error(`Registration error: provided a non-canonical ${e}. Export a ZodObject (z.object(...)).`)}function tt(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 et(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"})(Y||(Y={})),(t=>{t.PROMPT="prompts",t.DOCUMENTATION="documentation",t.CODE="code"})(G||(G={}));const rt=Buffer.from("DCAF1","ascii");function st(t){let e=E.resolve(t);for(;;){if(r.existsSync(E.join(e,"package.json")))return e;const t=E.dirname(e);if(t===e)break;e=t}}const nt=process.argv?.[1]?st(E.dirname(E.resolve(process.argv[1]))):void 0,it=(()=>{const t=Error().stack;if(!t)return;const e=t.split(/\r?\n/).slice(1);for(const t of e){const e=t.match(/\(?([^()]+?):\d+:\d+\)?/);if(!e)continue;let r=e[1];if(r.startsWith("file://"))try{r=J(r)}catch{continue}if(!r.includes("node:internal"))return E.dirname(r)}})(),ot=it?st(it):void 0,at=nt??ot??process.cwd();function ct(...t){return E.join(at,...t)}function pt(t){let r=t;for(;;){const t=k.join(r,"lib","assets");if(e.existsSync(t))return t;const s=k.join(r,"src","assets");if(e.existsSync(s))return s;const n=k.join(r,"assets");if(e.existsSync(n))return n;const i=k.dirname(r);if(i===r)break;r=i}}function lt(){const t=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(t&&e.existsSync(t))return t;const r=pt(__dirname);if(r)return r;const s=process.argv?.[1];if(s){const t=pt(k.dirname(s));if(t)return t}const n=[at,process.env.INIT_CWD].filter(Boolean);for(const t of n){const e=pt(t);if(e)return e}return ct("assets")}let ut=class extends a{constructor(t){super(),this.basePath=t||lt()}listAssets(...t){const r=k.join(this.basePath,...t);return e.readdirSync(r)}listPrompts(){return this.listAssets(G.PROMPT)}getAsset(t,r="md",...s){const n=k.join(this.basePath,...s),i=(t,r=!1)=>{try{return r?(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 r=rt.length;const s=t.subarray(r,r+16);r+=16;const n=t.subarray(r,r+12);r+=12;const i=t.subarray(r,r+16);r+=16;const o=t.subarray(r),a=((t,e)=>N.scryptSync(t,e,32))(e,s),c=N.createDecipheriv("aes-256-gcm",a,n);c.setAuthTag(i);const p=Buffer.concat([c.update(o),c.final()]);return C.gunzipSync(p)})(e.readFileSync(t)).toString("utf-8"):e.readFileSync(t,"utf-8")}catch(t){if("ENOENT"===t.code)return null;throw t}},o=i(k.join(n,`${t}.${r}`),"enc"===r);if(null!==o)return o;const a=i(k.join(n,t+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+k.join(n,`${t}.${r}`))}getAllAssets(t,...e){return this.listAssets(t,...e).reduce((r,s)=>{const n=k.extname(s),i=k.basename(s,n),o=n.replace(/^\./,"")||void 0;return r[i]=this.getAsset(i,o??void 0,t,...e),r},{})}toPromptDef(t){const e=t=>"number"==typeof t?t:"string"==typeof t?(t=>{switch(t){case"none":return L.NONE;case"basic":return L.BASIC;case"advanced":return L.ADVANCED;case"high":return L.HIGH;case"medium":return K.MEDIUM;case"low":return z.LOW;case"free":return z.FREE;default:throw new A("Cannon convert unknown level "+t)}})(t.toLowerCase()):L.NONE;return t.effort=e(t.effort),t.reasoning=e(t.reasoning),t.cost=e(t.cost),t}getPrompt(t,...e){const r=this.getAsset(c(t),"json",G.PROMPT,...e);let s;try{s=JSON.parse(r)}catch(r){throw new T(`Failed to parse prompt ${t} in categories ${e}: ${r}`)}return this.toPromptDef(s)}getAllPrompts(...t){const e=this.getAllAssets(G.PROMPT,...t);return Object.entries(e).reduce((e,[r,s])=>{try{e[r]=JSON.parse(s)}catch(e){throw new T(`Failed to parse prompt ${r} in categories ${t}: ${e}`)}return e},e)}};ut=m([S(),h("design:paramtypes",[String])],ut);class dt 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 dt}static patchPrompt(t,e,r,s){const n=(e=Array.isArray(e)?e:Object.keys(e)).filter(t=>!Object.prototype.hasOwnProperty.call(r,t));if(n.length)throw new O("Missing replacements for placeholders: "+n.join(", "));s&&(s.verbose("Patching prompt with placeholders: "+JSON.stringify(e)),s.debug("Values: "+JSON.stringify(r)));const i=e.reduce((t,e)=>(t[e]=r[e],t),{});return p(t,i)}patchPrompt(t,e,r,s){return dt.patchPrompt(t,e,r,s||this.log.for(this.patchPrompt))}build(t,e){const r=this.log.for(this.build),s=this.hasErrors();if(s)throw new O(s.toString());try{this.argsSchema&&X(this.argsSchema,"argsSchema");const r=tt(this.argsSchema);return t.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(t,r)=>{const s=this.logFor(r);t=Object.assign({},e,t||{}),s.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(t)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const n=await Promise.resolve(this.cb(t,r));return s.verbose(`Prompt ${this.name} executed successfully.`),s.debug("Prompt execution meta: "+JSON.stringify(n._meta)),n})}catch(t){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),t),t}}}m([j(ut),h("design:type",ut)],dt.prototype,"assets",void 0),m([f(),h("design:type",Object)],dt.prototype,"cb",void 0),m([f(),h("design:type",w)],dt.prototype,"argsSchema",void 0),m([x(),h("design:type",Object)],dt.prototype,"placeholders",void 0);class mt extends dt{setCategory(t){return this.promptCategory=t,this}addPrefix(t){return this.prefixes=this.prefixes||[],this.prefixes.push(t),this}addSuffix(t){return this.suffixes=this.suffixes||[],this.suffixes.push(t),this}constructor(t){super(t)}build(t){const e=this.assets.getPrompt(this.name,this.promptCategory);y.fromObject(this,e);const r=new Set((I.properties(mt)||[]).filter(t=>!["assets","promptCategory","prefixes","suffixes"].includes(t)));["cb","argsSchema"].forEach(t=>r.add(t));const s=this.hasErrors(...Array.from(r));if(s)throw new O(s.toString());const n=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=[...new Set([...e.placeholders,...n.map(t=>t.placeholders||[]),...i.map(t=>t.placeholders||[])].flat())].reduce((t,e)=>(t[e]=v.string().describe("The description for "+e),t),{});return this.setArgsSchema(v.object(o)),this.setCb((t,e)=>{const r=this.logFor(e).for(mt).for(this.promptCategory).for(this.name);function s(t=[]){return Array.isArray(t)?t:Object.keys(t)}const n=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...n.map(t=>s(t.placeholders)).flat(),...i.map(t=>s(t.placeholders)).flat(),...s(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...n.map(t=>t.prompt),o.prompt,...i.map(t=>t.prompt)].join("\n\n"),a,t,r)}}],_meta:{}}}),super.build(t)}setReasoning(t){throw new A("Named prompt builders don't require callback")}setEffort(t){throw new A("Named prompt builders don't require callback")}setCost(t){throw new A("Named prompt builders don't require callback")}setDescription(t){throw new A("Named prompt builders don't require callback")}setTitle(t){throw new A("Named prompt builders don't require callback")}static get builder(){return new mt}}m([f(),h("design:type",String)],mt.prototype,"promptCategory",void 0),m([g(String),b(1),h("design:type",Array)],mt.prototype,"prefixes",void 0),m([b(1),g(String),h("design:type",Array)],mt.prototype,"suffixes",void 0);const ht=dt.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(v.object({message:v.string().optional()})).setCb(async t=>{const e=t.message??"default";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),ft=dt.builder.setName("interactive-jsdoc").setTitle("Interactive JSDoc prompt").setDescription("Interactive prompt for jogging JSDoc helpers").setArgsSchema(v.object({gist:v.string().optional()})).setCb(async t=>{const e=t.gist??"interactive jsdoc response";return{messages:[{role:"assistant",content:{type:"text",text:e}}],content:[],structuredContent:{message:e},result:{message:e}}}),yt=Object.assign(ft,{name:ft.getName()});var gt;function bt(t,e=[],r=[]){const s=mt.builder.setCategory(gt.DOCS).setName(t);return["prefix",...e].forEach(t=>s.addPrefix(t)),["suffix",...r].forEach(t=>s.addSuffix(t)),s}(t=>{t.DOCS="documentation",t.CODE="code"})(gt||(gt={}));const vt=[bt("class"),bt("constant"),bt("decorator"),bt("function"),bt("module"),bt("file"),bt("repo",[],["iterate"])],wt=v.object({className:v.string().describe("the class name to turn into a builder")}),St=[ht,yt,...vt,dt.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(wt).setReasoning(L.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&&X(this.inputSchema,"inputSchema"),this.outputSchema&&X(this.outputSchema,"outputSchema");const e=tt(this.inputSchema),r=tt(this.outputSchema);return t.registerTool(this.name,{title:this.title,description:this.description,inputSchema:e,outputSchema:r,annotations:this.annotations,_meta:{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}}},async(t,e)=>{const r=this.logFor(e);r.verbose(`Executing tool ${this.name} with args: ${JSON.stringify(t)}`),e._meta=Object.assign(e._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(t,e));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(s._meta)),s})}catch(t){const e=t?.message||t+"";if("string"==typeof e&&e.includes("already registered"))return o.for(this).warn(`Tool ${this.name} already registered - skipping duplicate registration`),{name:this.name};throw o.for(this).error("Error building tool",t),t}}}m([f(),h("design:type",Object)],jt.prototype,"annotations",void 0),m([f(),h("design:type",Object)],jt.prototype,"cb",void 0),m([f(),h("design:type",Function)],jt.prototype,"inputSchema",void 0);const xt=jt.builder.setName("example-tool").setTitle("Example tool").setDescription("A smoke tool used for quick testing").setInputSchema(v.object({})).setCb(async()=>({content:[{type:"text",text:"example tool ok"}],result:{status:"ok"}}));Object.assign(xt,{name:xt.getName()});const It=jt.builder.setName("file-summarizer").setTitle("File summarizer").setDescription("Summaries files for quick previews").setInputSchema(v.object({filePath:v.string().optional()})).setCb(async()=>({content:[{type:"text",text:"file summary stub"}],result:{summary:"file summary stub"}}));function kt(){try{let t=process.argv[1]?E.dirname(E.resolve(process.argv[1])):process.cwd();for(;;){const e=E.join(t,"package.json");if(r.existsSync(e))return JSON.parse(r.readFileSync(e,"utf-8"));const s=E.dirname(t);if(s===t)break;t=s}}catch{}return{}}Object.assign(It,{name:It.getName()});const Et=kt().version??"0.0.0",At=kt().name??"unknown";I.registerLibrary(At,Et);const Tt={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:Et,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:at,assetDir:lt(),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},level:u.error},Ot=d.accumulate(Tt);function Nt(){const{host:t,email:e,apiKey:r,projectKey:s,issueType:n}=Ot.jira;return{host:t?.trim(),email:e?.trim(),apiKey:r?.trim(),projectKey:s?.trim(),issueType:n?.trim(),parentIssue:Ot.jira.parentIssue?.trim()}}function Ct(){const t=Nt();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 Jt(t){const e=t.value?((t,e)=>{if(t)return e?"<configured>":t})(t.value,t.sensitive):"not set",r=t.required?"(required)":"(optional)";return`\u2022 ${t.name} ${r}: ${t.description} Current state: ${e}.`}o.setConfig(Ot);class Ht extends Error{constructor(t){const e=Ct(),r=(t=>{const e=Ct();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(Jt).join("\n")}`})(t);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=e,this.missing=t,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Ht)}}function _t(t){if(!t)return{code:"jira_error",message:"Unknown Jira error",details:{raw:t}};const e=t?.status??t?.statusCode??t?.response?.status??t?.response?.statusCode,r="number"==typeof e?e:Number(e)||void 0,s=t?.response?.data??t?.data??t?.response?.body??t?.body,n=[];"string"==typeof t?.message&&n.push(t.message),((t,e)=>{t&&(Array.isArray(t.errorMessages)&&t.errorMessages.forEach(t=>"string"==typeof t&&e.push(t)),"string"==typeof t.errorMessage&&e.push(t.errorMessage),t.errorCollection&&Array.isArray(t.errorCollection.errors)&&t.errorCollection.errors.forEach(t=>{"string"==typeof t?e.push(t):t&&"string"==typeof t.message&&e.push(t.message)}),t?.errors&&"object"==typeof t.errors&&Object.values(t.errors).forEach(t=>{"string"==typeof t?e.push(t):"string"==typeof t?.message&&e.push(t.message)}))})(s,n);const i=r?`Jira API error (${r})`:"Jira API error",o=n.length>0?n.join(" | "):i;return{code:r?"jira_"+r:t?.code??"jira_error",message:o,details:{httpStatus:r,body:s,raw:t}}}function $t(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 t+""}})(t);return e?[{type:"text",text:e}]:[]}function Dt(t={},e=[]){return{content:e.length?e:$t(t),result:t,structuredContent:t}}const Pt=v.object({issueId:v.string().min(1),deleteSubtasks:v.boolean().optional().default(!0)}),Rt={name:"jira-issue-delete",inputSchema:Pt,runTool:async(t,e)=>{try{const r=Pt.parse(e),s=t.issues??t.issue??t,n=s?.delete??s?.deleteIssue;if("function"!=typeof n)throw Error("jira client delete endpoint is not available");return await n.call(s,{issueId:r.issueId,deleteSubtasks:r.deleteSubtasks}),Dt({success:!0,message:`Issue ${e.issueId} deleted successfully`})}catch(t){throw _t(t)}}},Mt=v.object({projectKey:v.string().trim().min(1).optional(),issueType:v.string().trim().min(1).optional(),parentIssueId:v.string().trim().min(1).optional(),name:v.string().trim().min(1).optional(),reference:v.string().trim().min(1).optional(),jql:v.string().trim().min(1).optional(),startAt:v.number().int().min(0).optional(),maxResults:v.number().int().min(1).optional(),fields:v.array(v.string()).optional(),expand:v.string().optional(),orderBy:v.string().trim().min(1).optional()});function qt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const Ft={name:"jira-issue-list",inputSchema:Mt,runTool:async(t,e)=>{try{const r=Mt.parse(e),s=r.startAt??0,n=r.maxResults??50;let i=r.jql?.trim();if(i){if(r.orderBy){const t=r.orderBy.trim();t&&(i=/\border\s+by\b/i.test(i)?`${i}, ${t}`:`${i} ORDER BY ${t}`)}}else i=(t=>{const e=[];if(t.projectKey&&e.push(`project = "${qt(t.projectKey)}"`),t.issueType&&e.push(`issuetype = "${qt(t.issueType)}"`),t.parentIssueId&&e.push(`parent = "${qt(t.parentIssueId)}"`),t.name&&e.push(`summary ~ "${qt(t.name)}"`),t.reference){const r=qt(t.reference);e.push(`(key ~ "${r}" OR summary ~ "${r}" OR text ~ "${r}")`)}if(0===e.length){const t=Error("Provide a jql query or at least one filter (project, name, reference, parent, issue type, etc.).");throw t.code="validation_error",t}let r=e.join(" AND ");if(t.orderBy){const e=t.orderBy.trim();e&&(r=/\border\s+by\b/i.test(r)?`${r}, ${e}`:`${r} ORDER BY ${e}`)}return r})(r);const o={jql:i,startAt:s,maxResults:n};r.fields&&(o.fields=r.fields),r.expand&&(o.expand=r.expand);const a=t.issueSearch,c=a&&"function"==typeof a.searchForIssuesUsingJqlEnhancedSearch?a.searchForIssuesUsingJqlEnhancedSearch:a&&"function"==typeof a.searchForIssuesUsingJql?a.searchForIssuesUsingJql:void 0;if(!c)throw Error("Jira search API is unavailable on the client");const p=await c.call(a,o);return Dt(p?.data??p)}catch(t){throw _t(t)}}},Bt=v.object({issueId:v.string().min(1),expand:v.string().optional(),fields:v.array(v.string()).optional(),properties:v.array(v.string()).optional()}),Wt={name:"jira-issue-read",inputSchema:Bt,runTool:async(t,e)=>{try{const r=Bt.parse(e),s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand),r.fields&&(s.fields=r.fields),r.properties&&(s.properties=r.properties);const n=await t.issues.get(s);return Dt(n?.data??n)}catch(t){throw _t(t)}}};function Ut(t,e,r){const s=((t.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!s)return null;const n=s[2],i=r.resolveAttachment?.(n);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Lt(t,e){if(!t)return[];if(!e.enableAtMentions&&!e.enableEmojiShortcodes)return[{type:"text",text:t}];let r=0;const s=[],n=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;r<t.length;){const o=zt(e.enableAtMentions?Kt(n,t,r):null,e.enableEmojiShortcodes?Kt(i,t,r):null);if(!o){s.push({type:"text",text:t.slice(r)});break}if(o.index>r&&s.push({type:"text",text:t.slice(r,o.index)}),"mention"===o.kind){const{full:t,groups:n}=o,i=n[0]??"",a=n[1]??"";i&&s.push({type:"text",text:i});const c=e.resolveMention?.(a);c?s.push({type:"mention",attrs:{id:c.id,text:c.text}}):s.push({type:"text",text:"@"+a}),r=o.index+t.length;continue}if("emoji"===o.kind){const{full:t,groups:n}=o,i=`:${n[0]}:`,a=e.resolveEmoji?.(i);s.push({type:"emoji",attrs:a?{shortName:a.shortName,text:a.text}:{shortName:i}}),r=o.index+t.length;continue}}return(t=>{const e=[];for(const r of t){const t=e[e.length-1];"text"!==r.type||"text"!==t?.type||t.marks||r.marks?e.push(r):t.text=(t.text??"")+(r.text??"")}return e})(s)}function Kt(t,e,r){t.lastIndex=r;const s=t.exec(e);if(!s)return null;const n=t.source.includes("@")?"mention":"emoji";return{index:s.index,full:s[0],groups:s.slice(1),kind:n}}function zt(t,e){return t?e&&t.index>e.index?e:t:e}function Yt(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 Gt(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 Zt(t){const e=((t??"")+"").toLowerCase().trim();return!e||"neutral"!==e&&"green"!==e&&"yellow"!==e&&"red"!==e&&"blue"!==e&&"purple"!==e?null:e}function Vt(t,e){const r=[];for(const s of t??[])if(s?.type)if("text"!==s.type)if("strong"!==s.type)if("emphasis"!==s.type)if("delete"!==s.type)if("inlineCode"!==s.type)if("break"!==s.type){if("link"===s.type){const t=(s.url??"")+"",n=Xt(s.children??[],t),i=Ut(s,0,e);if(i){"inline"===i.type?r.push(i.node):r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:t}}]});continue}if(e.enableSmartCards&&te(n,t)){r.push({type:"inlineCard",attrs:{url:t}});continue}r.push({type:"text",text:n,marks:[{type:"link",attrs:{href:t}}]});continue}if("textDirective"===s.type&&"status"===s.name){const t=Yt(s)||"Status",e=Zt(s.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:t,color:e}});continue}if("textDirective"===s.type&&"emoji"===s.name){const t=ee(s);r.push(re(t,e));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(s.value??"")+"",marks:[{type:"code"}]});else r.push(...Qt(Vt(s.children??[],e),{type:"strike"}));else r.push(...Qt(Vt(s.children??[],e),{type:"em"}));else r.push(...Qt(Vt(s.children??[],e),{type:"strong"}));else r.push(...Lt((s.value??"")+"",e));return r.filter(t=>!("text"===t.type&&""===(t.text??"")))}function Qt(t,e){return t.map(t=>{if("text"!==t.type)return t;const r=t.marks?[...t.marks,e]:[e];return{...t,marks:r}})}function Xt(t,e){const r=[];for(const e of t??[])"text"===e.type||"inlineCode"===e.type?r.push((e.value??"")+""):"emphasis"!==e.type&&"strong"!==e.type&&"delete"!==e.type||r.push(Xt(e.children??[],""));return r.join("")||e}function te(t,e){const r=(t??"").trim(),s=(e??"").trim();return r===s&&/^https?:\/\//i.test(s)}function ee(t){return(t.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("").trim()||""}function re(t,e){const r=t.startsWith(":")?t:`:${t}:`,s=e.resolveEmoji?.(r);return s?{type:"emoji",attrs:{shortName:s.shortName,text:s.text}}:{type:"emoji",attrs:{shortName:r}}}function se(t){return t?"string"==typeof t?t:"text"===t.type||"inlineCode"===t.type?(t.value??"")+"":Array.isArray(t.children)?t.children.map(se).join(""):"":""}function ne(t,e){if(!t?.type)return null;if((t=>"containerDirective"===t?.type&&"panel"===t?.name)(t))return((t,e)=>{const r=t.attributes??{},s=Gt(r.type)??"info",n="string"==typeof r.title?r.title:void 0,i=(t.children??[]).map(t=>ne(t,e)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:s,...n?{panelType:s,title:n}:{panelType:s}},content:i.length?i:[{type:"paragraph",content:[]}]}})(t,e);switch(t.type){case"heading":return{type:"heading",attrs:{level:oe(t.depth??1,1,6)},content:Vt(t.children??[],e)};case"paragraph":return(t=>{const e=t.children??[];if(1!==e.length)return null;const r=e[0];if("image"!==r?.type)return null;const s=(r.url??"")+"";return s?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:s}}]}:null})(t)||{type:"paragraph",content:Vt(t.children??[],e)};case"blockquote":return{type:"blockquote",content:(t.children??[]).map(t=>ne(t,e)).flat().filter(Boolean)};case"list":return((t,e)=>e.enableTaskLists&&(t.children??[]).some(t=>"boolean"==typeof t.checked)?((t,e)=>{const r=[];let s=0;for(const n of t.children??[]){if("boolean"!=typeof n.checked)continue;s+=1;const t=(n.children??[]).map(t=>ne(t,e)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+s,state:n.checked?"DONE":"TODO"},content:t.length?t:[{type:"paragraph",content:[]}]})}return{type:"taskList",content:r}})(t,e):{type:t.ordered?"orderedList":"bulletList",content:(t.children??[]).map(t=>((t,e)=>{const r=(t.children??[]).map(t=>ne(t,e)).flat().filter(Boolean);return{type:"listItem",content:r.length?r:[{type:"paragraph",content:[]}]}})(t,e))})(t,e);case"code":{const r=((t,e)=>{const r=(t??"").toString().trim().toLowerCase();return r?e.enableMermaid&&"mermaid"===r?"mermaid":(t=>{const e=t.trim().toLowerCase();return{js:"javascript",javascript:"javascript",jsx:"javascript",ts:"typescript",typescript:"typescript",tsx:"typescript",py:"python",python:"python",rb:"ruby",ruby:"ruby",sh:"bash",bash:"bash",zsh:"bash",shell:"bash",yml:"yaml",yaml:"yaml",json:"json",toml:"toml",xml:"xml",html:"html",css:"css",scss:"scss",sql:"sql",go:"go",rust:"rust",java:"java",c:"c",cpp:"cpp","c++":"cpp",cs:"csharp",csharp:"csharp",php:"php",kotlin:"kotlin",swift:"swift",md:"markdown",markdown:"markdown",graphql:"graphql",gql:"graphql",dockerfile:"docker",makefile:"make",ini:"ini"}[e]??e})(r):null})(t.lang,e);return{type:"codeBlock",attrs:{language:r},content:[{type:"text",text:(t.value??"")+""}]}}case"thematicBreak":return{type:"rule"};case"table":return((t,e)=>({type:"table",content:(t.children??[]).map((t,r)=>({type:"tableRow",content:(t.children??[]).map(t=>({type:0===r?"tableHeader":"tableCell",content:[{type:"paragraph",content:Vt(t.children??[],e)}]}))}))}))(t,e);case"leafDirective":return"status"===t.name?(t=>{const e=Zt((t.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:Yt(t)||"Status",color:e}}]}})(t):"panel"===t.name?((t,e)=>{const r=t.attributes??{},s=Gt(r.type)??"info",n="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:s,...n?{title:n}:{}},content:[{type:"paragraph",content:Vt([{type:"text",value:Yt(t)}],e)}]}})(t,e):ie(t,e);default:return ie(t,e)}}function ie(t,e){if("drop"===e.unknownNodeStrategy)return null;const r=se(t);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function oe(t,e,r){const s=Number.isFinite(t)?Math.trunc(t):e;return Math.max(e,Math.min(r,s))}const ae={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function ce(t,e={}){const r={...ae,...e},s=t??"",n=H().use(D).use($).use(_),i=n.parse(s),o=n.runSync(i);return pe(o),((t,e)=>{const r=[];for(const s of t.children??[]){const t=ne(s,e);t&&(Array.isArray(t)?r.push(...t):r.push(t))}return((t,e)=>{if(!e.enableSmartCards)return t;const r=t.content.map(t=>(t=>{if("paragraph"!==t.type)return t;const e=t.content??[];if(1!==e.length)return t;const r=e[0];if("inlineCard"!==r?.type)return t;const s=r.attrs?.url;return s?[{type:"blockCard",attrs:{url:s}}]:t})(t)).flat();return{...t,content:r}})({version:1,type:"doc",content:r},e)})(o,r)}function pe(t){if(!t||!Array.isArray(t.children))return;const e=[];for(const r of t.children)"definition"!==r?.type&&("html"!==r?.type?(pe(r),e.push(r)):e.push({type:"text",value:(r.value??"")+""}));t.children=e}const le=v.object({issueId:v.string().min(1),transitionId:v.union([v.string(),v.number()]),fields:v.record(v.any()).optional(),update:v.record(v.array(v.object({set:v.any().optional(),add:v.any().optional(),remove:v.any().optional()}))).optional(),comment:v.string().optional()}),ue={name:"jira-issue-transition",inputSchema:le,runTool:async(t,e)=>{try{const r=le.parse(e),s={id:r.transitionId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.comment&&(s.comment={body:ce(r.comment)});const n=await t.issues.transition({issueId:r.issueId,transition:s});return Dt(n?.data??n)}catch(t){throw _t(t)}}},de=v.object({issueId:v.string().min(1),fields:v.record(v.any()).optional(),update:v.record(v.array(v.object({set:v.any().optional(),add:v.any().optional(),remove:v.any().optional(),edit:v.any().optional()}))).optional(),properties:v.array(v.any()).optional(),notifyUsers:v.boolean().optional().default(!0),issueTemplateId:v.string().optional(),overrideScreenSecurity:v.boolean().optional().default(!1),overrideEditableFlag:v.boolean().optional().default(!1)}),me={name:"jira-issue-update",inputSchema:de,runTool:async(t,e)=>{try{const r=de.parse(e),s={issueId:r.issueId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.properties&&(s.properties=r.properties),void 0!==r.notifyUsers&&(s.notifyUsers=r.notifyUsers),r.issueTemplateId&&(s.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(s.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(s.overrideEditableFlag=r.overrideEditableFlag);const n=await t.issues.update(s);return Dt(n?.data??n)}catch(t){throw _t(t)}}},he=v.object({issueId:v.string().min(1),assignee:v.union([v.string(),v.object({accountId:v.string().min(1)}),v.object({accountType:v.string().min(1)})])}),fe={name:"jira-assign-issue",inputSchema:he,runTool:async(t,e)=>{try{const r=he.parse(e);let s;s="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const n=await t.issues.assign({issueId:r.issueId,assignee:s});return Dt(n?.data??n)}catch(t){throw _t(t)}}},ye=v.object({issueId:v.string().min(1)}),ge={name:"jira-unassign-issue",inputSchema:ye,runTool:async(t,e)=>{try{const r=ye.parse(e),s=await t.issues.assign({issueId:r.issueId,assignee:{accountId:"-1"}});return Dt(s?.data??s)}catch(t){throw _t(t)}}},be=v.object({issueId:v.string().min(1),body:v.string().min(1),visibility:v.object({type:v.enum(["role","group"]),value:v.string().min(1)}).optional()}),ve={name:"jira-comment-add",inputSchema:be,runTool:async(t,e)=>{try{const r=be.parse(e),s={body:ce(r.body)};r.visibility&&(s.visibility=r.visibility);const n=await t.issues.addComment({issueId:r.issueId,comment:s});return Dt(n?.data??n)}catch(t){throw _t(t)}}},we=v.object({issueId:v.string().min(1),start:v.number().optional().default(0),maxResults:v.number().optional().default(50),orderBy:v.string().optional(),expand:v.string().optional()}),Se={name:"jira-comment-list",inputSchema:we,runTool:async(t,e)=>{try{const r=we.parse(e),s=await t.issues.getComments({issueId:r.issueId,start:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return Dt(s?.data??s)}catch(t){throw _t(t)}}},je=v.object({link:v.object({relationship:v.enum(["Blocks","Relates to","Duplicates","Is blocked by","Is related to","Is duplicated by","Causes","Is caused by","Clone","Required","Work on","Split","Roll up"]),inwardIssue:v.object({id:v.string().optional(),key:v.string().optional()}),outwardIssue:v.object({id:v.string().optional(),key:v.string().optional()}),comment:v.object({body:v.string().optional(),visibility:v.object({type:v.enum(["role","group"]),value:v.string().min(1)}).optional()}).optional()})}),xe={name:"jira-link-create",inputSchema:je,runTool:async(t,e)=>{try{const r=je.parse(e).link,s={relationship:r.relationship,inwardIssue:r.inwardIssue.id||r.inwardIssue.key,outwardIssue:r.outwardIssue.id||r.outwardIssue.key};r.comment&&(r.comment.body&&(s.comment=ce(r.comment.body)),r.comment.visibility&&(s.visibility=r.comment.visibility));const n=await t.issues.link(s);return Dt(n?.data??n)}catch(t){throw _t(t)}}},Ie=v.object({issueId:v.string().min(1),file:v.string().min(1),mimeType:v.string().optional(),comment:v.string().optional()}),ke={name:"jira-attach",inputSchema:Ie,runTool:async(t,e)=>{try{const r=Ie.parse(e),n=E.resolve(r.file),i=await s.readFile(n),o=E.basename(n),a=await t.issues.addAttachment({issueId:r.issueId,file:{name:o,content:i,mimeType:r.mimeType??"application/octet-stream"},comment:r.comment});return Dt(a?.data??a)}catch(t){if(t&&t.code&&"string"==typeof t.code&&["ENOENT","EACCES"].includes(t.code))throw Error("Attachment file error: "+t.message);throw _t(t)}}},Ee=v.object({issueId:v.string().min(1)}),Ae={name:"jira-attachment-list",inputSchema:Ee,runTool:async(t,e)=>{try{const r=Ee.parse(e),s=await t.issues.getAttachments({issueId:r.issueId});return Dt(s?.data??s)}catch(t){throw _t(t)}}},Te=v.object({issueId:v.string().min(1),attachmentId:v.string().min(1)}),Oe={name:"jira-attachment-delete",inputSchema:Te,runTool:async(t,e)=>{try{const r=Te.parse(e);return await t.issues.deleteAttachment({issueId:r.issueId,attachmentId:r.attachmentId}),Dt({success:!0,message:`Attachment ${e.attachmentId} deleted successfully`})}catch(t){throw _t(t)}}},Ne=v.object({issueId:v.string().min(1),timeSpent:v.string().min(1),comment:v.string().optional(),author:v.object({accountId:v.string().min(1)}).optional(),startingOn:v.string().optional(),artifact:v.string().optional()}),Ce={name:"jira-worklog-add",inputSchema:Ne,runTool:async(t,e)=>{try{const r=Ne.parse(e),s={timeSpent:r.timeSpent};r.comment&&(s.comment=r.comment),r.author&&(s.author=r.author),r.startingOn&&(s.started=r.startingOn),r.artifact&&(s.artifact=r.artifact);const n=await t.issues.addWorklog({issueId:r.issueId,...s});return Dt(n?.data??n)}catch(t){throw _t(t)}}},Je={[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}},[Ft.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}},[me.name]:{title:"Jira Issue Update",description:"Update a Jira issue using fields, update ops, and property toggles",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Rt.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[ue.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[fe.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ge.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ve.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}},[Se.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[xe.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ke.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ae.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Oe.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Ce.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}}};async function He(t){const e=o.for(He);let r,s=null;try{r=(()=>{let t;try{const e=require("jira.js");t=e?.Version3Client||e.default?.Version3Client||e.default||e}catch(t){throw Error("Unable to require 'jira.js' \u2014 ensure it is installed as a dependency: "+t)}const{host:e,email:r,apiKey:s}=(()=>{const t=Nt(),e=Ct().filter(t=>t.required&&!t.value);if(e.length>0)throw new Ht(e);return{host:t.host,email:t.email,apiKey:t.apiKey}})();return new t({host:e.startsWith("http://")||e.startsWith("https://")?e:"https://"+e,authentication:{basic:{email:r,apiToken:s}}})})()}catch(t){if(!(t instanceof Ht))return void e.warn("Skipping Jira tool registration; unable to create Jira client",{error:t});s=t,e.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:t})}const n=[Wt,Ft,me,Rt,ue,fe,ge,ve,Se,xe,ke,Ae,Oe,Ce];for(const i of n){const n=Je[i.name];if(n)try{await t.registerTool(i.name,{title:n.title,description:n.description,inputSchema:tt(i.inputSchema),annotations:n.annotations},async t=>{if(!r)throw s??Error("Jira client unavailable because credentials could not be loaded.");return i.runTool(r,t)}),e.info("Registered Jira tool "+i.name)}catch(t){e.error("Failed to register Jira tool "+i.name,{error:t})}}}async function _e(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: "+Ot.name,"Title: "+Ot.title,"Version: "+Ot.version,"Prompts: "+(t.join(", ")||"<none>")].join("\n")}]}})})(t);const e=o.for(_e);try{await He(t)}catch(t){e.error("Failed to register Jira tools",t)}}class $e 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 $e}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{const e="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new R(new P(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),s=async(t,e)=>{const r=this.logFor(e);r.verbose(`Requesting resource ${this.name} from ${t.toString()}`);const s=await Promise.resolve(this.cb(t,e));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(s._meta)),s};return t.resource(this.name,e,r,s)}catch(t){throw o.for(this).error("Error registering resource "+this.name,t),t}}}m([f(),h("design:type",String)],$e.prototype,"uriOrTemplate",void 0),m([f(),h("design:type",Function)],$e.prototype,"cb",void 0),m([f(),h("design:type",Object)],$e.prototype,"config",void 0);const De=lt()??k.join(__dirname,"..","assets"),Pe=k.join(De,"templates"),Re=k.join(De,"prompts"),Me=new WeakMap;class qe extends a{get client(){const t=Me.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 r=e.build(this.client);t.verbose(`Loaded prompt ${r.title} from ${e.getName()} definition`)}catch(r){t.error("Failed to load prompt "+e.getName(),r)}try{await _e(this.client),t.verbose("Registered built-in tools")}catch(t){}try{await(async(t,r)=>{r.info("Registering agent templates as resources...");const s=e.readdirSync(Pe).filter(t=>t.endsWith(".md"));for(const n of s){const s=k.basename(n,".md"),i=k.join(Pe,n),o=$e.builder.setName(s).setTitle("Template: "+s).setDescription("Resource template for "+s).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+s}).setCb(async t=>{const r=e.readFileSync(t.pathname,"utf8");return{contents:[{uri:t.toString(),text:r,mimeType:"text/markdown"}],_meta:{}}});try{o.build(t),r.info("Registered template: "+s)}catch(t){r.error(`Failed to register template ${s}:`,t)}}r.info("Registering agent prompts...");const n=e.readdirSync(Re).filter(t=>t.endsWith(".md"));for(const s of n){const n=k.basename(s,".md"),i=k.join(Re,s),o=e.readFileSync(i,"utf8"),a=dt.builder.setName(n).setTitle("Prompt: "+n).setDescription("Dynamic prompt for "+n).setArgsSchema(v.object({})).setCb(async t=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(t),r.info("Registered prompt: "+n)}catch(t){r.error(`Failed to register prompt ${n}:`,t)}}})(this.client,t)}catch(t){}}async boot(t="stdio"){"stdio"===t&&o.setFactory(U),o.for(this.constructor.name);const e=((Array.isArray(Ot.icons)?Ot.icons:[Ot.icons])||[]).map(t=>{const e="string"==typeof t?.src?t.src:(t?.src??"")+"",r="string"==typeof t?.mimeType?t.mimeType:(t?.mimeType??"")+"";let s=[];return Array.isArray(t?.sizes)?s=t.sizes.map(t=>t+""):"string"==typeof t?.sizes&&(s=(t.sizes+"").split(",").map(t=>t.trim())),{src:e,mimeType:r,sizes:s}}),r={name:Ot.name,title:Ot.title,websiteUrl:Ot.websiteUrl,version:Ot.version,icons:e},s=new M(r,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((t,e)=>{Me.set(t,e)})(this,s),s.onerror=t=>{this.log.error("MCP instance onerror",t)},t){case"stdio":t=new F;break;case"http":t=new B({sessionIdGenerator:()=>q(),onsessioninitialized:t=>{},onsessionclosed:t=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(n=t)||"object"!=typeof n||"function"!=typeof n.send&&"function"!=typeof n.close&&"function"!=typeof n.on)throw new A("Invalid transport type: "+t)}var n;try{await this.load()}catch(t){throw t}await this.client.connect(t)}}const Fe=(new t).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async t=>{const e=ct("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version,{transport:i}=t,o=(new W).for("mcp-server");if("stdio"!==i)throw Error("Unsupported transport mode: "+i);return o.info("Transport stdio"),o.debug(`running with options: ${JSON.stringify(t)} for ${s.name} version ${n}`),(new qe).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=ct("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version;o.for("md-to-ast").debug(`running with options: ${JSON.stringify(t)} for ${s.name} version ${n}`);const i=ce(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 Be=(new t).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");Be.addCommand(Fe),Be.parse(process.argv);
2
2
  //# sourceMappingURL=mcp-server.js.map