@decaf-ts/mcp-server 1.5.7 → 1.5.9
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.
- package/dist/assets/code/patterns/builder.enc +0 -0
- package/dist/assets/prompts/agent/agent.enc +0 -0
- package/dist/assets/prompts/agent/init.enc +0 -0
- package/dist/assets/prompts/constitution_commands.enc +0 -0
- package/dist/assets/prompts/documentation/class.enc +0 -0
- package/dist/assets/prompts/documentation/constant.enc +0 -0
- package/dist/assets/prompts/documentation/decorator.enc +0 -0
- package/dist/assets/prompts/documentation/file.enc +0 -0
- package/dist/assets/prompts/documentation/function.enc +0 -0
- package/dist/assets/prompts/documentation/interface.enc +0 -0
- package/dist/assets/prompts/documentation/iterate.enc +0 -0
- package/dist/assets/prompts/documentation/module.enc +0 -0
- package/dist/assets/prompts/documentation/prefix.enc +0 -0
- package/dist/assets/prompts/documentation/repo.enc +0 -0
- package/dist/assets/prompts/documentation/suffix.enc +0 -0
- package/dist/assets/prompts/git_commands.enc +0 -0
- package/dist/assets/prompts/jira/operational_prompts.enc +0 -0
- package/dist/assets/prompts/jira/system_prompt.enc +0 -0
- package/dist/assets/prompts/mode_commands.enc +0 -0
- package/dist/assets/prompts/plan_commands.enc +0 -0
- package/dist/assets/prompts/repository/readme.enc +0 -0
- package/dist/assets/prompts/repository/release_notes.enc +0 -0
- package/dist/assets/prompts/repository/setup.enc +0 -0
- package/dist/assets/prompts/specification_commands.enc +0 -0
- package/dist/assets/prompts/startup_command.enc +0 -0
- package/dist/assets/prompts/task_commands.enc +0 -0
- package/dist/assets/prompts/tests/coverage.enc +0 -0
- package/dist/assets/templates/AGENTS.enc +0 -0
- package/dist/assets/templates/agents_template.enc +0 -0
- package/dist/assets/templates/constitution_template.enc +0 -0
- package/dist/assets/templates/decaf/context/logCtx.enc +0 -0
- package/dist/assets/templates/decaf/services/client_based_service.enc +0 -0
- package/dist/assets/templates/decaf/services/model_service.enc +0 -0
- package/dist/assets/templates/decaf/services/service.enc +0 -0
- package/dist/assets/templates/decaf_guidelines.enc +1 -1
- package/dist/assets/templates/instructions_template.enc +0 -0
- package/dist/assets/templates/jira_templates.enc +0 -0
- package/dist/assets/templates/plan_template.enc +0 -0
- package/dist/assets/templates/specification_template.enc +0 -0
- package/dist/assets/templates/task_template.enc +0 -0
- package/dist/mcp-server.cjs +1 -1
- package/dist/mcp-server.cjs.map +1 -1
- package/dist/mcp-server.js +1 -1
- package/dist/mcp-server.js.map +1 -1
- package/package.json +1 -1
package/dist/mcp-server.js
CHANGED
|
@@ -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 A from"path";import E from"path";import{InternalError as k,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{inspect as H}from"node:util";import{unified as _}from"unified";import $ from"remark-directive";import D from"remark-gfm";import P from"remark-parse";import{UriTemplate as R}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";import{ResourceTemplate as M,McpServer as q}from"@modelcontextprotocol/sdk/server/mcp.js";import{v4 as F}from"uuid";import{StdioServerTransport as B}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as W}from"@modelcontextprotocol/sdk/server/streamableHttp.js";class U 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 L=(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 U(s,e)};var K,z,Y,G,Z;(t=>{t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.ADVANCED=2]="ADVANCED",t[t.HIGH=3]="HIGH"})(K||(K={})),(t=>{t[t.NONE=0]="NONE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(z||(z={})),(t=>{t[t.FREE=0]="FREE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(Y||(Y={}));class V 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)],V.prototype,"description",void 0),m([f(),h("design:type",String)],V.prototype,"name",void 0),m([f(),h("design:type",String)],V.prototype,"title",void 0);class Q extends V{constructor(t){super(t),this.reasoning=K.NONE,this.effort=z.NONE,this.cost=Y.FREE}setReasoning(t){return this.reasoning=t,this}setEffort(t){return this.effort=t,this}setCost(t){return this.cost=t,this}}function X(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 tt(t,e="schema"){if(X(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]=rt(s)?s:v.any();return v.object(t)}}throw Error(`Registration error: provided a non-canonical ${e}. Export a ZodObject (z.object(...)).`)}function et(t){if(!t)return;if(t&&"object"==typeof t&&!t._def)return t.def&&"object"==typeof t.def&&t.def.shape?t.def.shape:t;const e=X(t);return e?"function"==typeof e.shape?e.shape():e.shape||void 0:void 0}function rt(t){return!(!t||"object"!=typeof t||!t._def)}m([f(),h("design:type",Number)],Q.prototype,"reasoning",void 0),m([f(),h("design:type",Number)],Q.prototype,"effort",void 0),m([f(),h("design:type",Number)],Q.prototype,"cost",void 0),(t=>{t.ASSETS="assets"})(G||(G={})),(t=>{t.PROMPT="prompts",t.DOCUMENTATION="documentation",t.CODE="code"})(Z||(Z={}));const st=Buffer.from("DCAF1","ascii");function nt(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 it=process.argv?.[1]?nt(E.dirname(E.resolve(process.argv[1]))):void 0,ot=(()=>{const t=Error().stack;if(!t)return;const e=t.split(/\r?\n/).slice(1);for(const t of e){const e=t.match(/\(?([^()]+?):\d+:\d+\)?/);if(!e)continue;let r=e[1];if(r.startsWith("file://"))try{r=J(r)}catch{continue}if(!r.includes("node:internal"))return E.dirname(r)}})(),at=ot?nt(ot):void 0,ct=it??at??process.cwd();function pt(...t){return E.join(ct,...t)}function lt(t){let r=t;for(;;){const t=A.join(r,"lib","assets");if(e.existsSync(t))return t;const s=A.join(r,"src","assets");if(e.existsSync(s))return s;const n=A.join(r,"assets");if(e.existsSync(n))return n;const i=A.dirname(r);if(i===r)break;r=i}}function ut(){const t=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(t&&e.existsSync(t))return t;const r=lt(__dirname);if(r)return r;const s=process.argv?.[1];if(s){const t=lt(A.dirname(s));if(t)return t}const n=[ct,process.env.INIT_CWD].filter(Boolean);for(const t of n){const e=lt(t);if(e)return e}return pt("assets")}let dt=class extends a{constructor(t){super(),this.basePath=t||ut()}listAssets(...t){const r=A.join(this.basePath,...t);return e.readdirSync(r)}listPrompts(){return this.listAssets(Z.PROMPT)}getAsset(t,r="md",...s){const n=A.join(this.basePath,...s),i=(t,r=!1)=>{try{return r?(t=>{if(t.length<st.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!t.subarray(0,st.length).equals(st))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=st.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(A.join(n,`${t}.${r}`),"enc"===r);if(null!==o)return o;const a=i(A.join(n,t+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+A.join(n,`${t}.${r}`))}getAllAssets(t,...e){return this.listAssets(t,...e).reduce((r,s)=>{const n=A.extname(s),i=A.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 K.NONE;case"basic":return K.BASIC;case"advanced":return K.ADVANCED;case"high":return K.HIGH;case"medium":return z.MEDIUM;case"low":return Y.LOW;case"free":return Y.FREE;default:throw new k("Cannon convert unknown level "+t)}})(t.toLowerCase()):K.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",Z.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(Z.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)}};dt=m([S(),h("design:paramtypes",[String])],dt);class mt extends Q{constructor(t){super(t)}setCb(t){return this.cb=t,this}setArgsSchema(t){return this.argsSchema=t,this}static get builder(){return new mt}static patchPrompt(t,e,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 mt.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&&tt(this.argsSchema,"argsSchema");const r=et(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(dt),h("design:type",dt)],mt.prototype,"assets",void 0),m([f(),h("design:type",Object)],mt.prototype,"cb",void 0),m([f(),h("design:type",w)],mt.prototype,"argsSchema",void 0),m([x(),h("design:type",Object)],mt.prototype,"placeholders",void 0);class ht extends mt{setCategory(t){return this.promptCategory=t,this}addPrefix(t){return this.prefixes=this.prefixes||[],this.prefixes.push(t),this}addSuffix(t){return this.suffixes=this.suffixes||[],this.suffixes.push(t),this}constructor(t){super(t)}build(t){const e=this.assets.getPrompt(this.name,this.promptCategory);y.fromObject(this,e);const r=new Set((I.properties(ht)||[]).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(ht).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 k("Named prompt builders don't require callback")}setEffort(t){throw new k("Named prompt builders don't require callback")}setCost(t){throw new k("Named prompt builders don't require callback")}setDescription(t){throw new k("Named prompt builders don't require callback")}setTitle(t){throw new k("Named prompt builders don't require callback")}static get builder(){return new ht}}m([f(),h("design:type",String)],ht.prototype,"promptCategory",void 0),m([g(String),b(1),h("design:type",Array)],ht.prototype,"prefixes",void 0),m([b(1),g(String),h("design:type",Array)],ht.prototype,"suffixes",void 0);const ft=mt.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(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}}}),yt=mt.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}}}),gt=Object.assign(yt,{name:yt.getName()});var bt;function vt(t,e=[],r=[]){const s=ht.builder.setCategory(bt.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"})(bt||(bt={}));const wt=[vt("class"),vt("constant"),vt("decorator"),vt("function"),vt("module"),vt("file"),vt("repo",[],["iterate"])],St=v.object({className:v.string().describe("the class name to turn into a builder")}),jt=[ft,gt,...wt,mt.builder.setName("ts-code-dp-builder").setTitle("Typescript builder design patter prompt").setDescription("for a class, with a defined set of properties, scafold a builder design pattern").setArgsSchema(St).setReasoning(K.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 xt extends Q{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 xt}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{this.inputSchema&&tt(this.inputSchema,"inputSchema"),this.outputSchema&&tt(this.outputSchema,"outputSchema");const e=et(this.inputSchema),r=et(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)],xt.prototype,"annotations",void 0),m([f(),h("design:type",Object)],xt.prototype,"cb",void 0),m([f(),h("design:type",Function)],xt.prototype,"inputSchema",void 0);const It=xt.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(It,{name:It.getName()});const At=xt.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 Et(){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(At,{name:At.getName()});const kt=Et().version??"0.0.0",Tt=Et().name??"unknown";I.registerLibrary(Tt,kt);const Ot={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:kt,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:ct,assetDir:ut(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0},level:u.error},Nt=d.accumulate(Ot);function Ct(){const{host:t,email:e,apiKey:r,projectKey:s,issueType:n}=Nt.jira;return{host:t?.trim(),email:e?.trim(),apiKey:r?.trim(),projectKey:s?.trim(),issueType:n?.trim(),parentIssue:Nt.jira.parentIssue?.trim()}}function Jt(){const t=Ct();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 Ht(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(Nt);class _t extends Error{constructor(t){const e=Jt(),r=(t=>{const e=Jt();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(Ht).join("\n")}`})(t);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=e,this.missing=t,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,_t)}}class $t extends Error{constructor({code:t,message:e,details:r}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=t,this.details=r}}function Dt(t){if(!t)return new $t({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 new $t({code:r?"jira_"+r:t?.code??"jira_error",message:o,details:{httpStatus:r,body:s,raw:t}})}function Pt(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 H(t,{depth:null})}})(t);return e?[{type:"text",text:e}]:[]}function Rt(t={},e=[]){return{content:e.length?e:Pt(t),result:t,structuredContent:t}}const Mt=v.object({issueId:v.string().min(1),deleteSubtasks:v.boolean().optional().default(!0)}),qt={name:"jira-issue-delete",inputSchema:Mt,runTool:async(t,e)=>{try{const r=Mt.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}),Rt({success:!0,message:`Issue ${e.issueId} deleted successfully`})}catch(t){throw Dt(t)}}},Ft=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 Bt(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const Wt={name:"jira-issue-list",inputSchema:Ft,runTool:async(t,e)=>{try{const r=Ft.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 = "${Bt(t.projectKey)}"`),t.issueType&&e.push(`issuetype = "${Bt(t.issueType)}"`),t.parentIssueId&&e.push(`parent = "${Bt(t.parentIssueId)}"`),t.name&&e.push(`summary ~ "${Bt(t.name)}"`),t.reference){const r=Bt(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),l=p?.data??p,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=s),void 0===u.maxResults&&(u.maxResults=n),Rt(u)}catch(t){throw Dt(t)}}},Ut=v.object({issueId:v.string().min(1),expand:v.string().optional(),fields:v.array(v.string()).optional(),properties:v.array(v.string()).optional()}),Lt={name:"jira-issue-read",inputSchema:Ut,runTool:async(t,e)=>{try{const r=Ut.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 Rt(n?.data??n)}catch(t){throw Dt(t)}}};function Kt(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 zt(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=Gt(e.enableAtMentions?Yt(n,t,r):null,e.enableEmojiShortcodes?Yt(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 Yt(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 Gt(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 Vt(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 Qt(t){const e=((t??"")+"").toLowerCase().trim();return!e||"neutral"!==e&&"green"!==e&&"yellow"!==e&&"red"!==e&&"blue"!==e&&"purple"!==e?null:e}function Xt(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=ee(s.children??[],t),i=Kt(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&&re(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=Qt(s.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:t,color:e}});continue}if("textDirective"===s.type&&"emoji"===s.name){const t=se(s);r.push(ne(t,e));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(s.value??"")+"",marks:[{type:"code"}]});else r.push(...te(Xt(s.children??[],e),{type:"strike"}));else r.push(...te(Xt(s.children??[],e),{type:"em"}));else r.push(...te(Xt(s.children??[],e),{type:"strong"}));else r.push(...zt((s.value??"")+"",e));return r.filter(t=>!("text"===t.type&&""===(t.text??"")))}function te(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 ee(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(ee(e.children??[],""));return r.join("")||e}function re(t,e){const r=(t??"").trim(),s=(e??"").trim();return r===s&&/^https?:\/\//i.test(s)}function se(t){return(t.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("").trim()||""}function ne(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 ie(t){return t?"string"==typeof t?t:"text"===t.type||"inlineCode"===t.type?(t.value??"")+"":Array.isArray(t.children)?t.children.map(ie).join(""):"":""}function oe(t,e){if(!t?.type)return null;if((t=>"containerDirective"===t?.type&&"panel"===t?.name)(t))return((t,e)=>{const r=t.attributes??{},s=Vt(r.type)??"info",n="string"==typeof r.title?r.title:void 0,i=(t.children??[]).map(t=>oe(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:ce(t.depth??1,1,6)},content:Xt(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:Xt(t.children??[],e)};case"blockquote":return{type:"blockquote",content:(t.children??[]).map(t=>oe(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=>oe(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=>oe(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:Xt(t.children??[],e)}]}))}))}))(t,e);case"leafDirective":return"status"===t.name?(t=>{const e=Qt((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=Vt(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:Xt([{type:"text",value:Zt(t)}],e)}]}})(t,e):ae(t,e);default:return ae(t,e)}}function ae(t,e){if("drop"===e.unknownNodeStrategy)return null;const r=ie(t);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function ce(t,e,r){const s=Number.isFinite(t)?Math.trunc(t):e;return Math.max(e,Math.min(r,s))}const pe={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function le(t,e={}){const r={...pe,...e},s=t??"",n=_().use(P).use(D).use($),i=n.parse(s),o=n.runSync(i);return ue(o),((t,e)=>{const r=[];for(const s of t.children??[]){const t=oe(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 ue(t){if(!t||!Array.isArray(t.children))return;const e=[];for(const r of t.children)"definition"!==r?.type&&("html"!==r?.type?(ue(r),e.push(r)):e.push({type:"text",value:(r.value??"")+""}));t.children=e}const de=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()}),me={name:"jira-issue-transition",inputSchema:de,runTool:async(t,e)=>{try{const r=de.parse(e),s={id:r.transitionId};r.fields&&(s.fields=r.fields),r.update&&(s.update=r.update),r.comment&&(s.comment={body:le(r.comment)});const n=await t.issues.transition({issueId:r.issueId,transition:s});return Rt(n?.data??n)}catch(t){throw Dt(t)}}},he=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)}),fe={name:"jira-issue-update",inputSchema:he,runTool:async(t,e)=>{try{const r=he.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 Rt(n?.data??n)}catch(t){throw Dt(t)}}},ye=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)})])}),ge={name:"jira-assign-issue",inputSchema:ye,runTool:async(t,e)=>{try{const r=ye.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 Rt(n?.data??n)}catch(t){throw Dt(t)}}},be=v.object({issueId:v.string().min(1)}),ve={name:"jira-unassign-issue",inputSchema:be,runTool:async(t,e)=>{try{const r=be.parse(e),s=await t.issues.assign({issueId:r.issueId,assignee:{accountId:"-1"}});return Rt(s?.data??s)}catch(t){throw Dt(t)}}},we=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()}),Se={name:"jira-comment-add",inputSchema:we,runTool:async(t,e)=>{try{const r=we.parse(e),s={body:le(r.body)};r.visibility&&(s.visibility=r.visibility);const n=await t.issues.addComment({issueId:r.issueId,comment:s});return Rt(n?.data??n)}catch(t){throw Dt(t)}}},je=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()}),xe={name:"jira-comment-list",inputSchema:je,runTool:async(t,e)=>{try{const r=je.parse(e),s=t.issueComments;if(!s||"function"!=typeof s.getComments)throw Error("Jira issueComments API is unavailable on the client");const n=await s.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return Rt(n?.data??n)}catch(t){throw Dt(t)}}},Ie=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()})}),Ae={name:"jira-link-create",inputSchema:Ie,runTool:async(t,e)=>{try{const r=Ie.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=le(r.comment.body)),r.comment.visibility&&(s.visibility=r.comment.visibility));const n=await t.issues.link(s);return Rt(n?.data??n)}catch(t){throw Dt(t)}}},Ee=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:Ee,runTool:async(t,e)=>{try{const r=Ee.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 Rt(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 Dt(t)}}},Te=v.object({issueId:v.string().min(1)}),Oe={name:"jira-attachment-list",inputSchema:Te,runTool:async(t,e)=>{try{const r=Te.parse(e),s=await t.issues.getAttachments({issueId:r.issueId});return Rt(s?.data??s)}catch(t){throw Dt(t)}}},Ne=v.object({issueId:v.string().min(1),attachmentId:v.string().min(1)}),Ce={name:"jira-attachment-delete",inputSchema:Ne,runTool:async(t,e)=>{try{const r=Ne.parse(e);return await t.issues.deleteAttachment({issueId:r.issueId,attachmentId:r.attachmentId}),Rt({success:!0,message:`Attachment ${e.attachmentId} deleted successfully`})}catch(t){throw Dt(t)}}},Je=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()}),He={name:"jira-worklog-add",inputSchema:Je,runTool:async(t,e)=>{try{const r=Je.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 Rt(n?.data??n)}catch(t){throw Dt(t)}}},_e={[Lt.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Wt.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}},[fe.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}},[qt.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[me.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ge.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ve.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Se.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}},[xe.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ae.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}},[Oe.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Ce.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[He.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}}};async function $e(t){const e=o.for($e);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=Ct(),e=Jt().filter(t=>t.required&&!t.value);if(e.length>0)throw new _t(e);return{host:t.host,email:t.email,apiKey:t.apiKey}})();return new t({host:e.startsWith("http://")||e.startsWith("https://")?e:"https://"+e,authentication:{basic:{email:r,apiToken:s}}})})()}catch(t){if(!(t instanceof _t))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=[Lt,Wt,fe,qt,me,ge,ve,Se,xe,Ae,ke,Oe,Ce,He];for(const i of n){const n=_e[i.name];if(n)try{await t.registerTool(i.name,{title:n.title,description:n.description,inputSchema:et(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 De(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=jt.map(t=>t.getName()).sort();return{content:[{type:"text",text:["Name: "+Nt.name,"Title: "+Nt.title,"Version: "+Nt.version,"Prompts: "+(t.join(", ")||"<none>")].join("\n")}]}})})(t);const e=o.for(De);try{await $e(t)}catch(t){e.error("Failed to register Jira tools",t)}}class Pe extends V{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 Pe}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{const e="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new M(new R(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)],Pe.prototype,"uriOrTemplate",void 0),m([f(),h("design:type",Function)],Pe.prototype,"cb",void 0),m([f(),h("design:type",Object)],Pe.prototype,"config",void 0);const Re=ut()??A.join(__dirname,"..","assets"),Me=A.join(Re,"templates"),qe=A.join(Re,"prompts"),Fe=new WeakMap;class Be extends a{get client(){const t=Fe.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 jt)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 De(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(Me).filter(t=>t.endsWith(".md"));for(const n of s){const s=A.basename(n,".md"),i=A.join(Me,n),o=Pe.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(qe).filter(t=>t.endsWith(".md"));for(const s of n){const n=A.basename(s,".md"),i=A.join(qe,s),o=e.readFileSync(i,"utf8"),a=mt.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(L),o.for(this.constructor.name);const e=((Array.isArray(Nt.icons)?Nt.icons:[Nt.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:Nt.name,title:Nt.title,websiteUrl:Nt.websiteUrl,version:Nt.version,icons:e},s=new q(r,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((t,e)=>{Fe.set(t,e)})(this,s),s.onerror=t=>{this.log.error("MCP instance onerror",t)},t){case"stdio":t=new B;break;case"http":t=new W({sessionIdGenerator:()=>F(),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 k("Invalid transport type: "+t)}var n;try{await this.load()}catch(t){throw t}await this.client.connect(t)}}const We=(new t).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async t=>{const e=pt("package.json"),s=JSON.parse(r.readFileSync(e,"utf-8")),n=s.version,{transport:i}=t,o=(new U).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 Be).boot(i)});(new t).command("md-to-ast").description("pipes markdown to jira ast: `cat file.md` | npx decaf-mcp md-to-ast > ast.json").action(async t=>{const e=pt("package.json"),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=le(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 Ue=(new t).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");Ue.addCommand(We),Ue.parse(process.argv);
|
|
1
|
+
import{Command as t}from"commander";import*as e from"fs";import r,{promises as n}from"fs";import{MiniLogger as s,NumericLogLevels as i,Logging as o,LoggedClass as a,toSnakeCase as c,sf as p,toPascalCase as l,LogLevel as u,LoggedEnvironment as d}from"@decaf-ts/logging";import{__decorate as m,__metadata as h}from"tslib";import{required as f,Model as y,list as g,minlength as b}from"@decaf-ts/decorator-validation";import{z as v,ZodObject as w}from"zod";import{injectable as j,inject as S}from"@decaf-ts/injectable-decorators";import{prop as I,Metadata as x}from"@decaf-ts/decoration";import*as k from"path";import A from"path";import{InternalError as E,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 P from"remark-directive";import $ from"remark-gfm";import _ from"remark-parse";import{inspect as D}from"node:util";import{UriTemplate as R}from"@modelcontextprotocol/sdk/shared/uriTemplate.js";import{ResourceTemplate as M,McpServer as q}from"@modelcontextprotocol/sdk/server/mcp.js";import{v4 as B}from"uuid";import{StdioServerTransport as F}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as K}from"@modelcontextprotocol/sdk/server/streamableHttp.js";class L extends s{constructor(t,e,r){super(t,e,r)}log(t,e,r,n){const s=this.config("level");i[s],i[t]}}const W=(t,e,...r)=>{const n=(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 L(n,e)};var U,z,Y,G,Z;(t=>{t[t.NONE=0]="NONE",t[t.BASIC=1]="BASIC",t[t.ADVANCED=2]="ADVANCED",t[t.HIGH=3]="HIGH"})(U||(U={})),(t=>{t[t.NONE=0]="NONE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(z||(z={})),(t=>{t[t.FREE=0]="FREE",t[t.LOW=1]="LOW",t[t.MEDIUM=2]="MEDIUM",t[t.HIGH=3]="HIGH"})(Y||(Y={}));class V 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:n}=t||{};let s="string"==typeof e&&e.length>0?this.log.for(e):this.log;return n&&n.clientId&&(s=s.for(n.clientId)),r&&(s=s.for(r.toString())),s}setDescription(t){return this.description=t,this}getDescription(){return this.description}setName(t){return this.name=t,this}getName(){return this.name}setTitle(t){return this.title=t,this}}m([f(),h("design:type",String)],V.prototype,"description",void 0),m([f(),h("design:type",String)],V.prototype,"name",void 0),m([f(),h("design:type",String)],V.prototype,"title",void 0);class Q extends V{constructor(t){super(t),this.reasoning=U.NONE,this.effort=z.NONE,this.cost=Y.FREE}setReasoning(t){return this.reasoning=t,this}setEffort(t){return this.effort=t,this}setCost(t){return this.cost=t,this}}function X(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 tt(t,e="schema"){if(X(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,n]of Object.entries(r))t[e]=rt(n)?n:v.any();return v.object(t)}}throw Error(`Registration error: provided a non-canonical ${e}. Export a ZodObject (z.object(...)).`)}function et(t){if(!t)return;if(t&&"object"==typeof t&&!t._def)return t.def&&"object"==typeof t.def&&t.def.shape?t.def.shape:t;const e=X(t);return e?"function"==typeof e.shape?e.shape():e.shape||void 0:void 0}function rt(t){return!(!t||"object"!=typeof t||!t._def)}m([f(),h("design:type",Number)],Q.prototype,"reasoning",void 0),m([f(),h("design:type",Number)],Q.prototype,"effort",void 0),m([f(),h("design:type",Number)],Q.prototype,"cost",void 0),(t=>{t.ASSETS="assets"})(G||(G={})),(t=>{t.PROMPT="prompts",t.DOCUMENTATION="documentation",t.CODE="code"})(Z||(Z={}));const nt=Buffer.from("DCAF1","ascii");function st(t){let e=A.resolve(t);for(;;){if(r.existsSync(A.join(e,"package.json")))return e;const t=A.dirname(e);if(t===e)break;e=t}}const it=process.argv?.[1]?st(A.dirname(A.resolve(process.argv[1]))):void 0,ot=(()=>{const t=Error().stack;if(!t)return;const e=t.split(/\r?\n/).slice(1);for(const t of e){const e=t.match(/\(?([^()]+?):\d+:\d+\)?/);if(!e)continue;let r=e[1];if(r.startsWith("file://"))try{r=J(r)}catch{continue}if(!r.includes("node:internal"))return A.dirname(r)}})(),at=ot?st(ot):void 0,ct=it??at??process.cwd();function pt(...t){return A.join(ct,...t)}function lt(t){let r=t;for(;;){const t=k.join(r,"lib","assets");if(e.existsSync(t))return t;const n=k.join(r,"src","assets");if(e.existsSync(n))return n;const s=k.join(r,"assets");if(e.existsSync(s))return s;const i=k.dirname(r);if(i===r)break;r=i}}function ut(){const t=process.env.DECAF_ASSET_DIR||process.env.MCP_ASSET_DIR||process.env.ASSET_DIR||"";if(t&&e.existsSync(t))return t;const r=lt(__dirname);if(r)return r;const n=process.argv?.[1];if(n){const t=lt(k.dirname(n));if(t)return t}const s=[ct,process.env.INIT_CWD].filter(Boolean);for(const t of s){const e=lt(t);if(e)return e}return pt("assets")}let dt=class extends a{constructor(t){super(),this.basePath=t||ut()}listAssets(...t){const r=k.join(this.basePath,...t);return e.readdirSync(r)}listPrompts(){return this.listAssets(Z.PROMPT)}getAsset(t,r="md",...n){const s=k.join(this.basePath,...n),i=(t,r=!1)=>{try{return r?(t=>{if(t.length<nt.length+16+12+16)throw Error("Invalid prompt payload (too short)");if(!t.subarray(0,nt.length).equals(nt))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=nt.length;const n=t.subarray(r,r+16);r+=16;const s=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,n),c=N.createDecipheriv("aes-256-gcm",a,s);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(s,`${t}.${r}`),"enc"===r);if(null!==o)return o;const a=i(k.join(s,t+".enc"),!0);if(null!==a)return a;throw Error("Asset not found: "+k.join(s,`${t}.${r}`))}getAllAssets(t,...e){return this.listAssets(t,...e).reduce((r,n)=>{const s=k.extname(n),i=k.basename(n,s),o=s.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 U.NONE;case"basic":return U.BASIC;case"advanced":return U.ADVANCED;case"high":return U.HIGH;case"medium":return z.MEDIUM;case"low":return Y.LOW;case"free":return Y.FREE;default:throw new E("Cannon convert unknown level "+t)}})(t.toLowerCase()):U.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",Z.PROMPT,...e);let n;try{n=JSON.parse(r)}catch(r){throw new T(`Failed to parse prompt ${t} in categories ${e}: ${r}`)}return this.toPromptDef(n)}getAllPrompts(...t){const e=this.getAllAssets(Z.PROMPT,...t);return Object.entries(e).reduce((e,[r,n])=>{try{e[r]=JSON.parse(n)}catch(e){throw new T(`Failed to parse prompt ${r} in categories ${t}: ${e}`)}return e},e)}};dt=m([j(),h("design:paramtypes",[String])],dt);class mt extends Q{constructor(t){super(t)}setCb(t){return this.cb=t,this}setArgsSchema(t){return this.argsSchema=t,this}static get builder(){return new mt}static patchPrompt(t,e,r,n){const s=(e=Array.isArray(e)?e:Object.keys(e)).filter(t=>!Object.prototype.hasOwnProperty.call(r,t));if(s.length)throw new O("Missing replacements for placeholders: "+s.join(", "));n&&(n.verbose("Patching prompt with placeholders: "+JSON.stringify(e)),n.debug("Values: "+JSON.stringify(r)));const i=e.reduce((t,e)=>(t[e]=r[e],t),{});return p(t,i)}patchPrompt(t,e,r,n){return mt.patchPrompt(t,e,r,n||this.log.for(this.patchPrompt))}build(t,e){const r=this.log.for(this.build),n=this.hasErrors();if(n)throw new O(n.toString());try{this.argsSchema&&tt(this.argsSchema,"argsSchema");const r=et(this.argsSchema);return t.registerPrompt(this.name,{title:this.title,description:this.description,argsSchema:r},async(t,r)=>{const n=this.logFor(r);t=Object.assign({},e,t||{}),n.verbose(`Executing prompt ${this.name} with args: ${JSON.stringify(t)}`),t._meta=Object.assign(t._meta||{},{usage:{reasoning:this.reasoning,effort:this.effort,cost:this.cost}});const s=await Promise.resolve(this.cb(t,r));return n.verbose(`Prompt ${this.name} executed successfully.`),n.debug("Prompt execution meta: "+JSON.stringify(s._meta)),s})}catch(t){throw r.error("Failed to register prompt "+(this.name||this.constructor.name),t),t}}}m([S(dt),h("design:type",dt)],mt.prototype,"assets",void 0),m([f(),h("design:type",Object)],mt.prototype,"cb",void 0),m([f(),h("design:type",w)],mt.prototype,"argsSchema",void 0),m([I(),h("design:type",Object)],mt.prototype,"placeholders",void 0);class ht extends mt{setCategory(t){return this.promptCategory=t,this}addPrefix(t){return this.prefixes=this.prefixes||[],this.prefixes.push(t),this}addSuffix(t){return this.suffixes=this.suffixes||[],this.suffixes.push(t),this}constructor(t){super(t)}build(t){const e=this.assets.getPrompt(this.name,this.promptCategory);y.fromObject(this,e);const r=new Set((x.properties(ht)||[]).filter(t=>!["assets","promptCategory","prefixes","suffixes"].includes(t)));["cb","argsSchema"].forEach(t=>r.add(t));const n=this.hasErrors(...Array.from(r));if(n)throw new O(n.toString());const s=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=[...new Set([...e.placeholders,...s.map(t=>t.placeholders||[]),...i.map(t=>t.placeholders||[])].flat())].reduce((t,e)=>(t[e]=v.string().describe("The description for "+e),t),{});return this.setArgsSchema(v.object(o)),this.setCb((t,e)=>{const r=this.logFor(e).for(ht).for(this.promptCategory).for(this.name);function n(t=[]){return Array.isArray(t)?t:Object.keys(t)}const s=(this.prefixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),i=(this.suffixes||[]).map(t=>this.assets.getPrompt(t,this.promptCategory)),o=this.assets.getPrompt(this.name,this.promptCategory),a=[...new Set([...s.map(t=>n(t.placeholders)).flat(),...i.map(t=>n(t.placeholders)).flat(),...n(o.placeholders).flat()])];return{messages:[{role:"user",content:{type:"text",text:this.patchPrompt([...s.map(t=>t.prompt),o.prompt,...i.map(t=>t.prompt)].join("\n\n"),a,t,r)}}],_meta:{}}}),super.build(t)}setReasoning(t){throw new E("Named prompt builders don't require callback")}setEffort(t){throw new E("Named prompt builders don't require callback")}setCost(t){throw new E("Named prompt builders don't require callback")}setDescription(t){throw new E("Named prompt builders don't require callback")}setTitle(t){throw new E("Named prompt builders don't require callback")}static get builder(){return new ht}}m([f(),h("design:type",String)],ht.prototype,"promptCategory",void 0),m([g(String),b(1),h("design:type",Array)],ht.prototype,"prefixes",void 0),m([b(1),g(String),h("design:type",Array)],ht.prototype,"suffixes",void 0);const ft=mt.builder.setName("example-prompt").setTitle("Example prompt").setDescription("Example prompt for testing").setArgsSchema(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}}}),yt=mt.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}}}),gt=Object.assign(yt,{name:yt.getName()});var bt;function vt(t,e=[],r=[]){const n=ht.builder.setCategory(bt.DOCS).setName(t);return["prefix",...e].forEach(t=>n.addPrefix(t)),["suffix",...r].forEach(t=>n.addSuffix(t)),n}(t=>{t.DOCS="documentation",t.CODE="code"})(bt||(bt={}));const wt=[vt("class"),vt("constant"),vt("decorator"),vt("function"),vt("module"),vt("file"),vt("repo",[],["iterate"])],jt=v.object({className:v.string().describe("the class name to turn into a builder")}),St=[ft,gt,...wt,mt.builder.setName("ts-code-dp-builder").setTitle("Typescript builder design patter prompt").setDescription("for a class, with a defined set of properties, scafold a builder design pattern").setArgsSchema(jt).setReasoning(U.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 It extends Q{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 It}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{this.inputSchema&&tt(this.inputSchema,"inputSchema"),this.outputSchema&&tt(this.outputSchema,"outputSchema");const e=et(this.inputSchema),r=et(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 n=await Promise.resolve(this.cb(t,e));return r.verbose(`Tool ${this.name} executed successfully.`),r.debug("Tool execution meta: "+JSON.stringify(n._meta)),n})}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)],It.prototype,"annotations",void 0),m([f(),h("design:type",Object)],It.prototype,"cb",void 0),m([f(),h("design:type",Function)],It.prototype,"inputSchema",void 0);const xt=It.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 kt=It.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 At(){try{let t=process.argv[1]?A.dirname(A.resolve(process.argv[1])):process.cwd();for(;;){const e=A.join(t,"package.json");if(r.existsSync(e))return JSON.parse(r.readFileSync(e,"utf-8"));const n=A.dirname(t);if(n===t)break;t=n}}catch{}return{}}Object.assign(kt,{name:kt.getName()});const Et=At().version??"0.0.0",Tt=At().name??"unknown";x.registerLibrary(Tt,Et);const Ot={mcpId:"decaf",name:"decaf-ts mcp server",title:"Decaf-TS MCP Server",description:"Provides precise coding assistance for the decaf-ts framework",version:Et,websiteUrl:"https://decaf-ts.github.io",repositoryUrl:"https://github.com/decaf-ts/mcp-server",license:"AGPL-3.0",workingDir:ct,assetDir:ut(),contacts:[{name:"Decaf-TS",url:"https://decaf-ts.github.io"}],tags:"server,official,decaf-ts",metadata:{},icons:[{src:"workdocs/assets/favicon.svg",mimeType:"image/svg+xml",sizes:"any"}],jira:{host:process.env.JIRA__HOST||"decaf-ts.atlassian.net",email:process.env.JIRA__EMAIL||"",apiKey:process.env.JIRA__API_KEY||process.env.JIRA__APIKEY||"",projectKey:process.env.JIRA__PROJECT_KEY||void 0,issueType:process.env.JIRA__ISSUE_TYPE||void 0,parentIssue:process.env.JIRA__PARENT_ISSUE||void 0},level:u.error},Nt=d.accumulate(Ot);function Ct(){const{host:t,email:e,apiKey:r,projectKey:n,issueType:s}=Nt.jira;return{host:t?.trim(),email:e?.trim(),apiKey:r?.trim(),projectKey:n?.trim(),issueType:s?.trim(),parentIssue:Nt.jira.parentIssue?.trim()}}function Jt(){const t=Ct();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 Ht(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(Nt);class Pt extends Error{constructor(t){const e=Jt(),r=(t=>{const e=Jt();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(Ht).join("\n")}`})(t);super(r),this.name="MissingJiraEnvironmentError",this.descriptors=e,this.missing=t,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,Pt)}}const $t=v.object({name:v.string().min(1).optional(),content:v.string().min(1),placeholders:v.record(v.string()).optional()}),_t=v.object({template:$t.optional()}),Dt=v.union([v.object({fields:v.record(v.any())}).merge(_t),v.object({summary:v.string().min(1),projectKey:v.string().min(1),issueType:v.string().min(1),description:v.string().optional()}).merge(_t)]);function Rt(t,e,r){const n=((t.url??"")+"").match(/^(attachment|jira-attachment):(.+)$/i);if(!n)return null;const s=n[2],i=r.resolveAttachment?.(s);return i?{type:"block",node:{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"file",id:i.id,collection:i.collection??"attachments"}}]}}:null}function Mt(t,e){if(!t)return[];if(!e.enableAtMentions&&!e.enableEmojiShortcodes)return[{type:"text",text:t}];let r=0;const n=[],s=/(^|[^A-Za-z0-9_])@([A-Za-z0-9._-]{1,64})/g,i=/:([a-z0-9_+-]{1,64}):/gi;for(;r<t.length;){const o=Bt(e.enableAtMentions?qt(s,t,r):null,e.enableEmojiShortcodes?qt(i,t,r):null);if(!o){n.push({type:"text",text:t.slice(r)});break}if(o.index>r&&n.push({type:"text",text:t.slice(r,o.index)}),"mention"===o.kind){const{full:t,groups:s}=o,i=s[0]??"",a=s[1]??"";i&&n.push({type:"text",text:i});const c=e.resolveMention?.(a);c?n.push({type:"mention",attrs:{id:c.id,text:c.text}}):n.push({type:"text",text:"@"+a}),r=o.index+t.length;continue}if("emoji"===o.kind){const{full:t,groups:s}=o,i=`:${s[0]}:`,a=e.resolveEmoji?.(i);n.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})(n)}function qt(t,e,r){t.lastIndex=r;const n=t.exec(e);if(!n)return null;const s=t.source.includes("@")?"mention":"emoji";return{index:n.index,full:n[0],groups:n.slice(1),kind:s}}function Bt(t,e){return t?e&&t.index>e.index?e:t:e}function Ft(t){const e=(t.children??[])[0];return"text"===e?.type?(e.value??"")+"":"paragraph"===e?.type?((e.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("")||"")+"":""}function Kt(t){const e=((t??"")+"").toLowerCase().trim();return e?"info"===e||"note"===e||"success"===e||"warning"===e||"error"===e?e:"danger"===e?"error":null:null}function Lt(t){const e=((t??"")+"").toLowerCase().trim();return!e||"neutral"!==e&&"green"!==e&&"yellow"!==e&&"red"!==e&&"blue"!==e&&"purple"!==e?null:e}function Wt(t,e){const r=[];for(const n of t??[])if(n?.type)if("text"!==n.type)if("strong"!==n.type)if("emphasis"!==n.type)if("delete"!==n.type)if("inlineCode"!==n.type)if("break"!==n.type){if("link"===n.type){const t=(n.url??"")+"",s=zt(n.children??[],t),i=Rt(n,0,e);if(i){"inline"===i.type?r.push(i.node):r.push({type:"text",text:s,marks:[{type:"link",attrs:{href:t}}]});continue}if(e.enableSmartCards&&Yt(s,t)){r.push({type:"inlineCard",attrs:{url:t}});continue}r.push({type:"text",text:s,marks:[{type:"link",attrs:{href:t}}]});continue}if("textDirective"===n.type&&"status"===n.name){const t=Ft(n)||"Status",e=Lt(n.attributes?.color)??"neutral";r.push({type:"status",attrs:{text:t,color:e}});continue}if("textDirective"===n.type&&"emoji"===n.name){const t=Gt(n);r.push(Zt(t,e));continue}}else r.push({type:"hardBreak"});else r.push({type:"text",text:(n.value??"")+"",marks:[{type:"code"}]});else r.push(...Ut(Wt(n.children??[],e),{type:"strike"}));else r.push(...Ut(Wt(n.children??[],e),{type:"em"}));else r.push(...Ut(Wt(n.children??[],e),{type:"strong"}));else r.push(...Mt((n.value??"")+"",e));return r.filter(t=>!("text"===t.type&&""===(t.text??"")))}function Ut(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 zt(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(zt(e.children??[],""));return r.join("")||e}function Yt(t,e){const r=(t??"").trim(),n=(e??"").trim();return r===n&&/^https?:\/\//i.test(n)}function Gt(t){return(t.children??[]).map(t=>"text"===t.type?(t.value??"")+"":"").join("").trim()||""}function Zt(t,e){const r=t.startsWith(":")?t:`:${t}:`,n=e.resolveEmoji?.(r);return n?{type:"emoji",attrs:{shortName:n.shortName,text:n.text}}:{type:"emoji",attrs:{shortName:r}}}function Vt(t){return t?"string"==typeof t?t:"text"===t.type||"inlineCode"===t.type?(t.value??"")+"":Array.isArray(t.children)?t.children.map(Vt).join(""):"":""}function Qt(t,e){if(!t?.type)return null;if((t=>"containerDirective"===t?.type&&"panel"===t?.name)(t))return((t,e)=>{const r=t.attributes??{},n=Kt(r.type)??"info",s="string"==typeof r.title?r.title:void 0,i=(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);return{type:"panel",attrs:{panelType:n,...s?{panelType:n,title:s}:{panelType:n}},content:i.length?i:[{type:"paragraph",content:[]}]}})(t,e);switch(t.type){case"heading":return{type:"heading",attrs:{level:te(t.depth??1,1,6)},content:Wt(t.children??[],e)};case"paragraph":return(t=>{const e=t.children??[];if(1!==e.length)return null;const r=e[0];if("image"!==r?.type)return null;const n=(r.url??"")+"";return n?{type:"mediaSingle",attrs:{layout:"center"},content:[{type:"media",attrs:{type:"external",url:n}}]}:null})(t)||{type:"paragraph",content:Wt(t.children??[],e)};case"blockquote":return{type:"blockquote",content:(t.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean)};case"list":return((t,e)=>e.enableTaskLists&&(t.children??[]).some(t=>"boolean"==typeof t.checked)?((t,e)=>{const r=[];let n=0;for(const s of t.children??[]){if("boolean"!=typeof s.checked)continue;n+=1;const t=(s.children??[]).map(t=>Qt(t,e)).flat().filter(Boolean);r.push({type:"taskItem",attrs:{localId:"task-"+n,state:s.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=>Qt(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:Wt(t.children??[],e)}]}))}))}))(t,e);case"leafDirective":return"status"===t.name?(t=>{const e=Lt((t.attributes??{}).color)??"neutral";return{type:"paragraph",content:[{type:"status",attrs:{text:Ft(t)||"Status",color:e}}]}})(t):"panel"===t.name?((t,e)=>{const r=t.attributes??{},n=Kt(r.type)??"info",s="string"==typeof r.title?r.title:void 0;return{type:"panel",attrs:{panelType:n,...s?{title:s}:{}},content:[{type:"paragraph",content:Wt([{type:"text",value:Ft(t)}],e)}]}})(t,e):Xt(t,e);default:return Xt(t,e)}}function Xt(t,e){if("drop"===e.unknownNodeStrategy)return null;const r=Vt(t);return r?{type:"paragraph",content:[{type:"text",text:r}]}:null}function te(t,e,r){const n=Number.isFinite(t)?Math.trunc(t):e;return Math.max(e,Math.min(r,n))}const ee={resolveMention:void 0,resolveAttachment:void 0,resolveEmoji:void 0,enableSmartCards:!0,enableMermaid:!0,enableEmojiShortcodes:!0,enableAtMentions:!0,enableTaskLists:!0,unknownNodeStrategy:"text"};function re(t,e={}){const r={...ee,...e},n=t??"",s=H().use(_).use($).use(P),i=s.parse(n),o=s.runSync(i);return ne(o),((t,e)=>{const r=[];for(const n of t.children??[]){const t=Qt(n,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 n=r.attrs?.url;return n?[{type:"blockCard",attrs:{url:n}}]:t})(t)).flat();return{...t,content:r}})({version:1,type:"doc",content:r},e)})(o,r)}function ne(t){if(!t||!Array.isArray(t.children))return;const e=[];for(const r of t.children)"definition"!==r?.type&&("html"!==r?.type?(ne(r),e.push(r)):e.push({type:"text",value:(r.value??"")+""}));t.children=e}const se=/\{\{\s*([^\}]+)\s*\}\}/g;function ie(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 D(t,{depth:null})}})(t);return e?[{type:"text",text:e}]:[]}function oe(t={},e=[]){const r=(t=>t&&"object"==typeof t?Array.isArray(t)?{items:t}:t:"string"==typeof t?{message:t}:null==t?{}:{value:t})(t);return{content:e.length?e:ie(r),result:r,structuredContent:r}}const ae={name:"jira-issue-create",inputSchema:Dt,runTool:async(t,e)=>oe(await(async(t,e)=>{let r;const n=t=>t&&t.trim()?t.trim():void 0,s=n(Nt.jira.projectKey),i=n(Nt.jira.issueType),o=e&&"object"==typeof e&&!Array.isArray(e)?e:{},a=Object.prototype.hasOwnProperty.call(o,"fields")?o:{...o,projectKey:o.projectKey??s,issueType:o.issueType??i};try{r=Dt.parse(a)}catch(t){const e=Error("validation error");throw e.code="validation_error",e}let c;c=r&&"object"==typeof r&&"fields"in r&&r.fields?{...r.fields}:{summary:r.summary,project:{key:r.projectKey},issuetype:{name:r.issueType},...r.description?{description:r.description}:{}},c=((t,e)=>{if(!e||!e.content)return t;const r=(n=e.content,s=e.placeholders,n?n.replace(se,(t,e)=>{const r=e.trim();if(!r)return"";if(s&&Object.prototype.hasOwnProperty.call(s,r)){const t=s[r];return null==t?"":t+""}return t}):"");var n,s;if(!r.trim())return t;const i=re(r),o=(a=t.description)?"object"==typeof a&&"doc"===a.type&&Array.isArray(a.content)?a.content:"string"==typeof a?re(a).content:[]:[];var a;return t.description={type:"doc",version:1,content:[...o,...i.content]},t})(c,r.template);const p=t?.issues?.create??t?.issues?.createIssue;if("function"!=typeof p)throw Error("Jira client missing create function");const l=await p.call(t.issues,{fields:c}),u=l&&l.data||l;return{id:u?.id??null,key:u?.key??null}})(t,e))};class ce extends Error{constructor({code:t,message:e,details:r}){super(e),Object.setPrototypeOf(this,new.target.prototype),this.name="NormalizedJiraError",this.code=t,this.details=r}}function pe(t){if(!t)return new ce({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,n=t?.response?.data??t?.data??t?.response?.body??t?.body,s=[];"string"==typeof t?.message&&s.push(t.message),((t,e)=>{t&&(Array.isArray(t.errorMessages)&&t.errorMessages.forEach(t=>"string"==typeof t&&e.push(t)),"string"==typeof t.errorMessage&&e.push(t.errorMessage),t.errorCollection&&Array.isArray(t.errorCollection.errors)&&t.errorCollection.errors.forEach(t=>{"string"==typeof t?e.push(t):t&&"string"==typeof t.message&&e.push(t.message)}),t?.errors&&"object"==typeof t.errors&&Object.values(t.errors).forEach(t=>{"string"==typeof t?e.push(t):"string"==typeof t?.message&&e.push(t.message)}))})(n,s);const i=r?`Jira API error (${r})`:"Jira API error",o=s.length>0?s.join(" | "):i;return new ce({code:r?"jira_"+r:t?.code??"jira_error",message:o,details:{httpStatus:r,body:n,raw:t}})}const le=v.object({issueId:v.string().min(1),deleteSubtasks:v.boolean().optional().default(!0)}),ue={name:"jira-issue-delete",inputSchema:le,runTool:async(t,e)=>{try{const r=le.parse(e),n=t.issues??t.issue??t,s=n?.delete??n?.deleteIssue;if("function"!=typeof s)throw Error("jira client delete endpoint is not available");return await s.call(n,{issueIdOrKey:r.issueId,deleteSubtasks:r.deleteSubtasks}),oe({success:!0,message:`Issue ${r.issueId} deleted successfully`})}catch(t){throw pe(t)}}},de=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 me(t){return t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}const he={name:"jira-issue-list",inputSchema:de,runTool:async(t,e)=>{try{const r=de.parse(e),n=r.startAt??0,s=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 = "${me(t.projectKey)}"`),t.issueType&&e.push(`issuetype = "${me(t.issueType)}"`),t.parentIssueId&&e.push(`parent = "${me(t.parentIssueId)}"`),t.name&&e.push(`summary ~ "${me(t.name)}"`),t.reference){const r=me(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:n,maxResults:s};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),l=p?.data??p,u="object"==typeof l&&null!==l?{...l}:{};return void 0===u.startAt&&(u.startAt=n),void 0===u.maxResults&&(u.maxResults=s),oe(u)}catch(t){throw pe(t)}}},fe=v.object({issueId:v.string().min(1),expand:v.string().optional(),fields:v.array(v.string()).optional(),properties:v.array(v.string()).optional()}),ye={name:"jira-issue-read",inputSchema:fe,runTool:async(t,e)=>{try{const r=fe.parse(e),n={issueIdOrKey:r.issueId};r.expand&&(n.expand=r.expand),r.fields&&(n.fields=r.fields),r.properties&&(n.properties=r.properties);const s=await t.issues.getIssue(n);return oe(s?.data??s)}catch(t){throw pe(t)}}},ge=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()}),be={name:"jira-issue-transition",inputSchema:ge,runTool:async(t,e)=>{try{const r=ge.parse(e),n={id:r.transitionId};r.fields&&(n.fields=r.fields),r.update&&(n.update=r.update),r.comment&&(n.comment={body:re(r.comment)});const s=await t.issues.transition({issueIdOrKey:r.issueId,transition:n});return oe(s?.data??s)}catch(t){throw pe(t)}}},ve=v.object({issueId:v.string().min(1),expand:v.string().optional()}),we={name:"jira-transition-list",inputSchema:ve,runTool:async(t,e)=>{try{const r=ve.parse(e),n=t.issues;if(!n||"function"!=typeof n.getTransitions)throw Error("Jira transitions API is unavailable on the client");const s={issueIdOrKey:r.issueId};r.expand&&(s.expand=r.expand);const i=await n.getTransitions(s);return oe(i?.data??i)}catch(t){throw pe(t)}}},je=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)}),Se={name:"jira-issue-update",inputSchema:je,runTool:async(t,e)=>{try{const r=je.parse(e),n={issueIdOrKey:r.issueId};r.fields&&(n.fields=r.fields),r.update&&(n.update=r.update),r.properties&&(n.properties=r.properties),void 0!==r.notifyUsers&&(n.notifyUsers=r.notifyUsers),r.issueTemplateId&&(n.issueTemplateId=r.issueTemplateId),void 0!==r.overrideScreenSecurity&&(n.overrideScreenSecurity=r.overrideScreenSecurity),void 0!==r.overrideEditableFlag&&(n.overrideEditableFlag=r.overrideEditableFlag);const s=await t.issues.editIssue(n);return oe(s?.data??s)}catch(t){throw pe(t)}}},Ie=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)})])}),xe={name:"jira-assign-issue",inputSchema:Ie,runTool:async(t,e)=>{try{const r=Ie.parse(e);let n;n="string"==typeof r.assignee?{accountId:r.assignee}:r.assignee;const s=await t.issues.assignIssue({issueIdOrKey:r.issueId,assignee:n});return oe(s?.data??s)}catch(t){throw pe(t)}}},ke=v.object({issueId:v.string().min(1)}),Ae={name:"jira-unassign-issue",inputSchema:ke,runTool:async(t,e)=>{try{const r=ke.parse(e),n=await t.issues.assignIssue({issueIdOrKey:r.issueId,assignee:{accountId:"-1"}});return oe(n?.data??n)}catch(t){throw pe(t)}}},Ee=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()}),Te={name:"jira-comment-add",inputSchema:Ee,runTool:async(t,e)=>{try{const r=Ee.parse(e),n=t.issueComments;if(!n||"function"!=typeof n.addComment)throw Error("Jira issueComments API is unavailable on the client");const s={issueIdOrKey:r.issueId,comment:r.body};r.visibility&&(s.visibility=r.visibility);const i=await n.addComment(s);return oe(i?.data??i)}catch(t){throw pe(t)}}},Oe=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()}),Ne={name:"jira-comment-list",inputSchema:Oe,runTool:async(t,e)=>{try{const r=Oe.parse(e),n=t.issueComments;if(!n||"function"!=typeof n.getComments)throw Error("Jira issueComments API is unavailable on the client");const s=await n.getComments({issueIdOrKey:r.issueId,startAt:r.start,maxResults:r.maxResults,orderBy:r.orderBy,expand:r.expand});return oe(s?.data??s)}catch(t){throw pe(t)}}},Ce=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()})});let Je=[];function He(t){return(t||"").trim().toLowerCase()}const Pe=Ce;function $e(t){if(t.id)return{id:t.id};if(t.key)return{key:t.key};throw Error("Linked issue must include an id or key")}const _e={name:"jira-link-create",inputSchema:Pe,runTool:async(t,e)=>{try{const r=Pe.parse(e).link,n={inwardIssue:$e(r.inwardIssue),outwardIssue:$e(r.outwardIssue)};if(r.comment){const t={};r.comment.body&&(t.body=re(r.comment.body)),r.comment.visibility&&(t.visibility=r.comment.visibility),Object.keys(t).length>0&&(n.comment=t)}const s=t.issueLinks;if(!s||"function"!=typeof s.linkIssues)throw Error("Jira issueLinks API is unavailable on the client");const i=await(async(t,e)=>{if(!e)throw Error("Link relationship is required");if(0===Je.length){const e=t.issueLinkTypes;if(!e||"function"!=typeof e.getIssueLinkTypes)throw Error("Jira issueLinkTypes API is unavailable on the client");const r=await e.getIssueLinkTypes();Je=r?.issueLinkTypes??r?.values??[]}const r=He(e),n=Je.find(t=>[t.name,t.inward,t.outward].some(t=>He(t)===r));if(!n)throw Error(`No issue link type matching '${e}' found.`);return n})(t,r.relationship);n.type={id:i.id};const o=await s.linkIssues(n);return oe(o?.data??o)}catch(t){throw pe(t)}}},De=v.object({issueId:v.string().min(1),file:v.string().min(1),mimeType:v.string().optional(),comment:v.string().optional()}),Re={name:"jira-attach",inputSchema:De,runTool:async(t,e)=>{try{const r=De.parse(e),s=A.resolve(r.file),i=await n.readFile(s),o=A.basename(s),a=new FormData;a.append("file",new Blob([i],{type:r.mimeType??"application/octet-stream"}),o);const c=t?.config??null,p=c?.host,l=c?.authentication?.basic??c?.authentication??c?.auth??null,u=l?.email,d=l?.apiToken??l?.apiKey;if(!p||!u||!d)throw Error("Jira client authentication configuration is unavailable for attachments");const m=await fetch(`${p}/rest/api/3/issue/${r.issueId}/attachments`,{method:"POST",headers:{Authorization:"Basic "+Buffer.from(`${u}:${d}`).toString("base64"),"X-Atlassian-Token":"no-check"},body:a});if(!m.ok){const t=await m.text();throw Error(`Jira attachment upload failed (${m.status}): ${t}`)}const h=await m.json();if(r.comment){const e=t.issueComments;if(!e||"function"!=typeof e.addComment)throw Error("Jira issueComments API is unavailable on the client");await e.addComment({issueIdOrKey:r.issueId,comment:re(r.comment)})}return oe(h)}catch(t){if(t&&t.code&&"string"==typeof t.code&&["ENOENT","EACCES"].includes(t.code))throw Error("Attachment file error: "+t.message);throw pe(t)}}},Me=v.object({issueId:v.string().min(1)}),qe={name:"jira-attachment-list",inputSchema:Me,runTool:async(t,e)=>{try{const r=Me.parse(e),n=t.issues;if(!n||"function"!=typeof n.getIssue)throw Error("Jira issues API is unavailable on the client");const s=await n.getIssue({issueIdOrKey:r.issueId,fields:["attachment"]}),i=s?.data??s;return oe({attachments:i?.fields?.attachment??[]})}catch(t){throw pe(t)}}},Be=v.object({issueId:v.string().min(1),attachmentId:v.string().min(1)}),Fe={name:"jira-attachment-delete",inputSchema:Be,runTool:async(t,e)=>{try{const r=Be.parse(e),n=t.issueAttachments;if(!n||"function"!=typeof n.removeAttachment)throw Error("Jira issueAttachments API is unavailable on the client");return await n.removeAttachment({id:r.attachmentId}),oe({success:!0,message:`Attachment ${e.attachmentId} deleted successfully`})}catch(t){throw pe(t)}}},Ke=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()}),Le={name:"jira-worklog-add",inputSchema:Ke,runTool:async(t,e)=>{try{const r=Ke.parse(e),n={timeSpent:r.timeSpent};r.comment&&(n.comment=r.comment),r.author&&(n.author=r.author),r.startingOn&&(n.started=r.startingOn),r.artifact&&(n.artifact=r.artifact);const s=t.issueWorklogs;if(!s||"function"!=typeof s.addWorklog)throw Error("Jira issueWorklogs API is unavailable on the client");const i=await s.addWorklog({issueIdOrKey:r.issueId,...n});return oe(i?.data??i)}catch(t){throw pe(t)}}},We={[ae.name]:{title:"Jira Issue Create",description:"Create a Jira issue (optionally applying a markdown template)",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[ye.name]:{title:"Jira Issue Read",description:"Read a Jira issue with expandable fields and properties",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[he.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}},[Se.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}},[ue.name]:{title:"Jira Issue Delete",description:"Delete a Jira issue and optionally remove its subtasks",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[be.name]:{title:"Jira Issue Transition",description:"Transition a Jira issue while optionally adding a comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[we.name]:{title:"Jira Transition List",description:"List available transitions for a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[xe.name]:{title:"Jira Issue Assign",description:"Assign a Jira issue to a user or account",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Ae.name]:{title:"Jira Issue Unassign",description:"Unassign the current owner from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Te.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}},[Ne.name]:{title:"Jira Comment List",description:"List comments on a Jira issue with pagination support",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[_e.name]:{title:"Jira Link Create",description:"Create an issue link relationship with optional comment",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[Re.name]:{title:"Jira Attachment Add",description:"Attach a local file to a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}},[qe.name]:{title:"Jira Attachment List",description:"List attachments on a Jira issue",annotations:{readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!1}},[Fe.name]:{title:"Jira Attachment Delete",description:"Delete an attachment from a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!0,idempotentHint:!1,openWorldHint:!0}},[Le.name]:{title:"Jira Worklog Add",description:"Log time spent on a Jira issue",annotations:{readOnlyHint:!1,destructiveHint:!1,idempotentHint:!1,openWorldHint:!0}}};async function Ue(t){const e=o.for(Ue);let r,n=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:n}=(()=>{const t=Ct(),e=Jt().filter(t=>t.required&&!t.value);if(e.length>0)throw new Pt(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:n}}})})()}catch(t){if(!(t instanceof Pt))return void e.warn("Skipping Jira tool registration; unable to create Jira client",{error:t});n=t,e.warn("Registering Jira tools without credentials; each tool will report configuration requirements.",{error:t})}const s=[ae,ye,he,Se,ue,be,we,xe,Ae,Te,Ne,_e,Re,qe,Fe,Le];for(const i of s){const s=We[i.name];if(s)try{await t.registerTool(i.name,{title:s.title,description:s.description,inputSchema:i.inputSchema,annotations:s.annotations},async t=>{if(!r)throw n??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 ze(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: "+Nt.name,"Title: "+Nt.title,"Version: "+Nt.version,"Prompts: "+(t.join(", ")||"<none>")].join("\n")}]}})})(t);const e=o.for(ze);try{await Ue(t)}catch(t){e.error("Failed to register Jira tools",t)}}class Ye extends V{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 Ye}build(t){const e=this.hasErrors();if(e)throw Error(e.toString());try{const e="string"==typeof this.uriOrTemplate&&this.uriOrTemplate.includes("{")?new M(new R(this.uriOrTemplate),{list:void 0}):this.uriOrTemplate,r=Object.assign(this.config,{_meta:{}}),n=async(t,e)=>{const r=this.logFor(e);r.verbose(`Requesting resource ${this.name} from ${t.toString()}`);const n=await Promise.resolve(this.cb(t,e));return r.verbose(`Resource ${this.name} retrieved successfully.`),r.debug("Resource retrieval meta: "+JSON.stringify(n._meta)),n};return t.resource(this.name,e,r,n)}catch(t){throw o.for(this).error("Error registering resource "+this.name,t),t}}}m([f(),h("design:type",String)],Ye.prototype,"uriOrTemplate",void 0),m([f(),h("design:type",Function)],Ye.prototype,"cb",void 0),m([f(),h("design:type",Object)],Ye.prototype,"config",void 0);const Ge=ut()??k.join(__dirname,"..","assets"),Ze=k.join(Ge,"templates"),Ve=k.join(Ge,"prompts"),Qe=new WeakMap;class Xe extends a{get client(){const t=Qe.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 ze(this.client),t.verbose("Registered built-in tools")}catch(t){}try{await(async(t,r)=>{r.info("Registering agent templates as resources...");const n=e.readdirSync(Ze).filter(t=>t.endsWith(".md"));for(const s of n){const n=k.basename(s,".md"),i=k.join(Ze,s),o=Ye.builder.setName(n).setTitle("Template: "+n).setDescription("Resource template for "+n).setUriOtTemplate("file:///"+i).setConfig({mimeType:"text/markdown",description:"Template for "+n}).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: "+n)}catch(t){r.error(`Failed to register template ${n}:`,t)}}r.info("Registering agent prompts...");const s=e.readdirSync(Ve).filter(t=>t.endsWith(".md"));for(const n of s){const s=k.basename(n,".md"),i=k.join(Ve,n),o=e.readFileSync(i,"utf8"),a=mt.builder.setName(s).setTitle("Prompt: "+s).setDescription("Dynamic prompt for "+s).setArgsSchema(v.object({})).setCb(async t=>({messages:[{role:"user",content:{type:"text",text:o}}],_meta:{}}));try{a.build(t),r.info("Registered prompt: "+s)}catch(t){r.error(`Failed to register prompt ${s}:`,t)}}})(this.client,t)}catch(t){}}async boot(t="stdio"){"stdio"===t&&o.setFactory(W),o.for(this.constructor.name);const e=((Array.isArray(Nt.icons)?Nt.icons:[Nt.icons])||[]).map(t=>{const e="string"==typeof t?.src?t.src:(t?.src??"")+"",r="string"==typeof t?.mimeType?t.mimeType:(t?.mimeType??"")+"";let n=[];return Array.isArray(t?.sizes)?n=t.sizes.map(t=>t+""):"string"==typeof t?.sizes&&(n=(t.sizes+"").split(",").map(t=>t.trim())),{src:e,mimeType:r,sizes:n}}),r={name:Nt.name,title:Nt.title,websiteUrl:Nt.websiteUrl,version:Nt.version,icons:e},n=new q(r,{instructions:"You are an AI assistant designed to help users with programming tasks related to the Decaf-TS framework. \nProvide clear, concise, and accurate information.\nIf you don't know the answer, admit it rather than making up information.\nAlways prioritize the user's intent and provide helpful suggestions when appropriate.\n",capabilities:{logging:{},tools:{},prompts:{}}});switch(((t,e)=>{Qe.set(t,e)})(this,n),n.onerror=t=>{this.log.error("MCP instance onerror",t)},t){case"stdio":t=new F;break;case"http":t=new K({sessionIdGenerator:()=>B(),onsessioninitialized:t=>{},onsessionclosed:t=>{},enableJsonResponse:!0,eventStore:void 0});break;default:if(!(s=t)||"object"!=typeof s||"function"!=typeof s.send&&"function"!=typeof s.close&&"function"!=typeof s.on)throw new E("Invalid transport type: "+t)}var s;try{await this.load()}catch(t){throw t}await this.client.connect(t)}}const tr=(new t).command("start").option("--transport [String]","transport mode","stdio").description("starts decaf's mcp server").action(async t=>{const e=pt("package.json"),n=JSON.parse(r.readFileSync(e,"utf-8")),s=n.version,{transport:i}=t,o=(new L).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 ${n.name} version ${s}`),(new Xe).boot(i)});(new t).command("md-to-ast").description("pipes markdown to jira ast: `cat file.md` | npx decaf-mcp md-to-ast > ast.json").action(async t=>{const e=pt("package.json"),n=JSON.parse(r.readFileSync(e,"utf-8")),s=n.version;o.for("md-to-ast").debug(`running with options: ${JSON.stringify(t)} for ${n.name} version ${s}`);const i=re(await(async()=>{const t=[];for await(const e of process.stdin)t.push(Buffer.from(e));return Buffer.concat(t).toString("utf8")})(),{resolveMention:t=>({id:t,text:"@"+t}),resolveAttachment:t=>({id:t,collection:"attachments"})});process.stdout.write(JSON.stringify(i,null,2)+"\n")});const er=(new t).name("mcp-server").command("mcp-server").description("decaf mcp server and agentic functionality");er.addCommand(tr),er.parse(process.argv);
|
|
2
2
|
//# sourceMappingURL=mcp-server.js.map
|