@agiflowai/scaffold-mcp 0.6.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +11 -71
  2. package/dist/ScaffoldConfigLoader-CI0T6zdG.js +142 -0
  3. package/dist/{ScaffoldConfigLoader-DzcV5a_c.cjs → ScaffoldConfigLoader-DQMCLVGD.cjs} +1 -1
  4. package/dist/ScaffoldConfigLoader-DhthV6xq.js +3 -0
  5. package/dist/ScaffoldService-B3En_m4t.cjs +3 -0
  6. package/dist/{ScaffoldService-BgFWAOLQ.cjs → ScaffoldService-BwDmXt83.cjs} +17 -8
  7. package/dist/ScaffoldService-CJ3vNmAj.js +3 -0
  8. package/dist/ScaffoldService-DB7-Cyod.js +293 -0
  9. package/dist/TemplateService-BZRt3NI8.cjs +3 -0
  10. package/dist/TemplateService-CiZJA06s.js +79 -0
  11. package/dist/TemplateService-DropYdp8.js +3 -0
  12. package/dist/VariableReplacementService-BAwTGv_R.js +3 -0
  13. package/dist/{VariableReplacementService-YUpL5nAC.cjs → VariableReplacementService-CroHkMha.cjs} +1 -1
  14. package/dist/{VariableReplacementService-ClshNY_C.cjs → VariableReplacementService-D0QnWKUW.cjs} +2 -2
  15. package/dist/VariableReplacementService-DRxd9ILB.js +66 -0
  16. package/dist/cli.cjs +779 -0
  17. package/dist/cli.d.cts +1 -0
  18. package/dist/cli.d.ts +1 -0
  19. package/dist/cli.js +774 -0
  20. package/dist/index.cjs +38 -3208
  21. package/dist/index.d.cts +814 -0
  22. package/dist/index.d.ts +815 -0
  23. package/dist/index.js +137 -0
  24. package/dist/stdio-Bxn4A1IU.js +2073 -0
  25. package/dist/stdio-TGsG8akc.cjs +2178 -0
  26. package/package.json +19 -5
  27. package/dist/ScaffoldService-BvD9WvRi.cjs +0 -3
  28. package/dist/TemplateService-B5EZjPB0.cjs +0 -3
  29. /package/dist/{ScaffoldConfigLoader-1Pcv9cxm.cjs → ScaffoldConfigLoader-BrmvENTo.cjs} +0 -0
  30. /package/dist/{TemplateService-_KpkoLfZ.cjs → TemplateService-DRubcvS9.cjs} +0 -0
@@ -0,0 +1,2178 @@
1
+ const require_chunk = require('./chunk-CUT6urMc.cjs');
2
+ const require_ScaffoldConfigLoader = require('./ScaffoldConfigLoader-BrmvENTo.cjs');
3
+ const require_ScaffoldService = require('./ScaffoldService-BwDmXt83.cjs');
4
+ const require_TemplateService = require('./TemplateService-DRubcvS9.cjs');
5
+ const require_VariableReplacementService = require('./VariableReplacementService-D0QnWKUW.cjs');
6
+ let __agiflowai_aicode_utils = require("@agiflowai/aicode-utils");
7
+ __agiflowai_aicode_utils = require_chunk.__toESM(__agiflowai_aicode_utils);
8
+ let node_path = require("node:path");
9
+ node_path = require_chunk.__toESM(node_path);
10
+ let __composio_json_schema_to_zod = require("@composio/json-schema-to-zod");
11
+ __composio_json_schema_to_zod = require_chunk.__toESM(__composio_json_schema_to_zod);
12
+ let fs_extra = require("fs-extra");
13
+ fs_extra = require_chunk.__toESM(fs_extra);
14
+ let js_yaml = require("js-yaml");
15
+ js_yaml = require_chunk.__toESM(js_yaml);
16
+ let zod = require("zod");
17
+ zod = require_chunk.__toESM(zod);
18
+ let __modelcontextprotocol_sdk_types_js = require("@modelcontextprotocol/sdk/types.js");
19
+ __modelcontextprotocol_sdk_types_js = require_chunk.__toESM(__modelcontextprotocol_sdk_types_js);
20
+ let node_crypto = require("node:crypto");
21
+ node_crypto = require_chunk.__toESM(node_crypto);
22
+ let __modelcontextprotocol_sdk_server_streamableHttp_js = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
23
+ __modelcontextprotocol_sdk_server_streamableHttp_js = require_chunk.__toESM(__modelcontextprotocol_sdk_server_streamableHttp_js);
24
+ let express = require("express");
25
+ express = require_chunk.__toESM(express);
26
+ let __modelcontextprotocol_sdk_server_sse_js = require("@modelcontextprotocol/sdk/server/sse.js");
27
+ __modelcontextprotocol_sdk_server_sse_js = require_chunk.__toESM(__modelcontextprotocol_sdk_server_sse_js);
28
+ let __modelcontextprotocol_sdk_server_stdio_js = require("@modelcontextprotocol/sdk/server/stdio.js");
29
+ __modelcontextprotocol_sdk_server_stdio_js = require_chunk.__toESM(__modelcontextprotocol_sdk_server_stdio_js);
30
+
31
+ //#region src/services/FileSystemService.ts
32
+ var FileSystemService = class {
33
+ async pathExists(path$2) {
34
+ return fs_extra.default.pathExists(path$2);
35
+ }
36
+ async readFile(path$2, encoding = "utf8") {
37
+ return fs_extra.default.readFile(path$2, encoding);
38
+ }
39
+ async readJson(path$2) {
40
+ return fs_extra.default.readJson(path$2);
41
+ }
42
+ async writeFile(path$2, content, encoding = "utf8") {
43
+ return fs_extra.default.writeFile(path$2, content, encoding);
44
+ }
45
+ async ensureDir(path$2) {
46
+ return fs_extra.default.ensureDir(path$2);
47
+ }
48
+ async copy(src, dest) {
49
+ return fs_extra.default.copy(src, dest);
50
+ }
51
+ async readdir(path$2) {
52
+ return fs_extra.default.readdir(path$2);
53
+ }
54
+ async stat(path$2) {
55
+ return fs_extra.default.stat(path$2);
56
+ }
57
+ };
58
+
59
+ //#endregion
60
+ //#region src/services/BoilerplateService.ts
61
+ var BoilerplateService = class {
62
+ templatesPath;
63
+ templateService;
64
+ scaffoldService;
65
+ constructor(templatesPath) {
66
+ this.templatesPath = templatesPath;
67
+ this.templateService = new require_TemplateService.TemplateService();
68
+ const fileSystemService = new FileSystemService();
69
+ this.scaffoldService = new require_ScaffoldService.ScaffoldService(fileSystemService, new require_ScaffoldConfigLoader.ScaffoldConfigLoader(fileSystemService, this.templateService), new require_VariableReplacementService.VariableReplacementService(fileSystemService, this.templateService), templatesPath);
70
+ }
71
+ /**
72
+ * Scans all scaffold.yaml files and returns available boilerplates
73
+ */
74
+ async listBoilerplates() {
75
+ const boilerplates = [];
76
+ const templateDirs = await this.discoverTemplateDirectories();
77
+ for (const templatePath of templateDirs) {
78
+ const scaffoldYamlPath = node_path.join(this.templatesPath, templatePath, "scaffold.yaml");
79
+ if (fs_extra.existsSync(scaffoldYamlPath)) try {
80
+ const scaffoldContent = fs_extra.readFileSync(scaffoldYamlPath, "utf8");
81
+ const scaffoldConfig = js_yaml.load(scaffoldContent);
82
+ if (scaffoldConfig.boilerplate) for (const boilerplate of scaffoldConfig.boilerplate) {
83
+ if (!boilerplate.targetFolder) {
84
+ __agiflowai_aicode_utils.log.warn(`Skipping boilerplate '${boilerplate.name}' in ${templatePath}: targetFolder is required in scaffold.yaml`);
85
+ continue;
86
+ }
87
+ boilerplates.push({
88
+ name: boilerplate.name,
89
+ description: boilerplate.description,
90
+ instruction: boilerplate.instruction,
91
+ variables_schema: boilerplate.variables_schema,
92
+ template_path: templatePath,
93
+ target_folder: boilerplate.targetFolder,
94
+ includes: boilerplate.includes
95
+ });
96
+ }
97
+ } catch (error) {
98
+ __agiflowai_aicode_utils.log.warn(`Failed to load scaffold.yaml for ${templatePath}:`, error);
99
+ }
100
+ }
101
+ return { boilerplates };
102
+ }
103
+ /**
104
+ * Dynamically discovers template directories by finding all directories
105
+ * that contain both package.json and scaffold.yaml files
106
+ */
107
+ async discoverTemplateDirectories() {
108
+ const templateDirs = [];
109
+ const findTemplates = (dir, baseDir = "") => {
110
+ if (!fs_extra.existsSync(dir)) return;
111
+ const items = fs_extra.readdirSync(dir);
112
+ const hasPackageJson = items.includes("package.json") || items.includes("package.json.liquid");
113
+ const hasScaffoldYaml = items.includes("scaffold.yaml");
114
+ if (hasPackageJson && hasScaffoldYaml) templateDirs.push(baseDir);
115
+ for (const item of items) {
116
+ const itemPath = node_path.join(dir, item);
117
+ if (fs_extra.statSync(itemPath).isDirectory() && !item.startsWith(".") && item !== "node_modules") findTemplates(itemPath, baseDir ? node_path.join(baseDir, item) : item);
118
+ }
119
+ };
120
+ findTemplates(this.templatesPath);
121
+ return templateDirs;
122
+ }
123
+ /**
124
+ * Executes a specific boilerplate with provided variables
125
+ */
126
+ async useBoilerplate(request) {
127
+ let { boilerplateName, variables, monolith, targetFolderOverride } = request;
128
+ if (monolith === void 0) try {
129
+ const config = await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd());
130
+ monolith = config.type === "monolith";
131
+ __agiflowai_aicode_utils.log.info(`Auto-detected project type: ${config.type}`);
132
+ } catch (_error) {
133
+ monolith = false;
134
+ __agiflowai_aicode_utils.log.info("No project configuration found, defaulting to monorepo mode");
135
+ }
136
+ if (monolith && !boilerplateName) try {
137
+ boilerplateName = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
138
+ __agiflowai_aicode_utils.log.info(`Using boilerplate from toolkit.yaml: ${boilerplateName}`);
139
+ } catch (error) {
140
+ return {
141
+ success: false,
142
+ message: `Failed to read boilerplate name from toolkit.yaml: ${error instanceof Error ? error.message : String(error)}`
143
+ };
144
+ }
145
+ if (!boilerplateName) return {
146
+ success: false,
147
+ message: "Missing required parameter: boilerplateName"
148
+ };
149
+ const boilerplateList = await this.listBoilerplates();
150
+ const boilerplate = boilerplateList.boilerplates.find((b) => b.name === boilerplateName);
151
+ if (!boilerplate) return {
152
+ success: false,
153
+ message: `Boilerplate '${boilerplateName}' not found. Available boilerplates: ${boilerplateList.boilerplates.map((b) => b.name).join(", ")}`
154
+ };
155
+ const validationResult = this.validateBoilerplateVariables(boilerplate, variables);
156
+ if (!validationResult.isValid) return {
157
+ success: false,
158
+ message: `Validation failed: ${validationResult.errors.join(", ")}`
159
+ };
160
+ const packageName = variables.packageName || variables.appName;
161
+ if (!packageName) return {
162
+ success: false,
163
+ message: "Missing required parameter: packageName or appName"
164
+ };
165
+ const folderName = packageName.includes("/") ? packageName.split("/")[1] : packageName;
166
+ const targetFolder = targetFolderOverride || (monolith ? "." : boilerplate.target_folder);
167
+ const projectNameForPath = monolith ? "" : folderName;
168
+ try {
169
+ const result = await this.scaffoldService.useBoilerplate({
170
+ projectName: projectNameForPath,
171
+ packageName,
172
+ targetFolder,
173
+ templateFolder: boilerplate.template_path,
174
+ boilerplateName,
175
+ variables: {
176
+ ...variables,
177
+ packageName,
178
+ appName: folderName,
179
+ sourceTemplate: boilerplate.template_path
180
+ }
181
+ });
182
+ if (!result.success) return result;
183
+ if (monolith) await __agiflowai_aicode_utils.ProjectConfigResolver.createToolkitYaml(boilerplate.template_path);
184
+ else {
185
+ const projectPath = node_path.join(targetFolder, folderName);
186
+ await __agiflowai_aicode_utils.ProjectConfigResolver.createProjectJson(projectPath, folderName, boilerplate.template_path);
187
+ }
188
+ return {
189
+ success: result.success,
190
+ message: result.message,
191
+ warnings: result.warnings,
192
+ createdFiles: result.createdFiles,
193
+ existingFiles: result.existingFiles
194
+ };
195
+ } catch (error) {
196
+ return {
197
+ success: false,
198
+ message: `Failed to scaffold boilerplate: ${error instanceof Error ? error.message : String(error)}`
199
+ };
200
+ }
201
+ }
202
+ /**
203
+ * Gets a specific boilerplate configuration by name with optional variable rendering
204
+ */
205
+ async getBoilerplate(name, variables) {
206
+ const boilerplate = (await this.listBoilerplates()).boilerplates.find((b) => b.name === name);
207
+ if (!boilerplate) return null;
208
+ if (variables && this.templateService.containsTemplateVariables(boilerplate.instruction)) return {
209
+ ...boilerplate,
210
+ instruction: this.templateService.renderString(boilerplate.instruction, variables)
211
+ };
212
+ return boilerplate;
213
+ }
214
+ /**
215
+ * Processes boilerplate instruction with template service
216
+ */
217
+ processBoilerplateInstruction(instruction, variables) {
218
+ if (this.templateService.containsTemplateVariables(instruction)) return this.templateService.renderString(instruction, variables);
219
+ return instruction;
220
+ }
221
+ /**
222
+ * Validates boilerplate variables against schema using Zod
223
+ */
224
+ validateBoilerplateVariables(boilerplate, variables) {
225
+ const errors = [];
226
+ try {
227
+ (0, __composio_json_schema_to_zod.jsonSchemaToZod)(boilerplate.variables_schema).parse(variables);
228
+ return {
229
+ isValid: true,
230
+ errors: []
231
+ };
232
+ } catch (error) {
233
+ if (error instanceof zod.z.ZodError) {
234
+ const zodErrors = error.errors.map((err) => {
235
+ return `${err.path.length > 0 ? err.path.join(".") : "root"}: ${err.message}`;
236
+ });
237
+ errors.push(...zodErrors);
238
+ } else errors.push(`Validation error: ${error instanceof Error ? error.message : String(error)}`);
239
+ return {
240
+ isValid: false,
241
+ errors
242
+ };
243
+ }
244
+ }
245
+ };
246
+
247
+ //#endregion
248
+ //#region src/services/BoilerplateGeneratorService.ts
249
+ /**
250
+ * Service for generating boilerplate configurations in scaffold.yaml files
251
+ */
252
+ var BoilerplateGeneratorService = class {
253
+ templatesPath;
254
+ constructor(templatesPath) {
255
+ this.templatesPath = templatesPath;
256
+ }
257
+ /**
258
+ * Custom YAML dumper that forces literal block style (|) for description and instruction fields
259
+ */
260
+ dumpYamlWithLiteralBlocks(config) {
261
+ const LiteralBlockType = new js_yaml.Type("tag:yaml.org,2002:str", {
262
+ kind: "scalar",
263
+ construct: (data) => data,
264
+ represent: (data) => {
265
+ return data;
266
+ },
267
+ defaultStyle: "|"
268
+ });
269
+ const LITERAL_SCHEMA = js_yaml.DEFAULT_SCHEMA.extend([LiteralBlockType]);
270
+ const processedConfig = this.processConfigForLiteralBlocks(config);
271
+ return js_yaml.dump(processedConfig, {
272
+ schema: LITERAL_SCHEMA,
273
+ indent: 2,
274
+ lineWidth: -1,
275
+ noRefs: true,
276
+ sortKeys: false,
277
+ styles: { "!!str": "literal" },
278
+ replacer: (key, value) => {
279
+ if ((key === "description" || key === "instruction") && typeof value === "string") return value;
280
+ return value;
281
+ }
282
+ });
283
+ }
284
+ /**
285
+ * Process config to ensure description and instruction use literal block style
286
+ */
287
+ processConfigForLiteralBlocks(config) {
288
+ const processed = JSON.parse(JSON.stringify(config));
289
+ if (processed.boilerplate) processed.boilerplate = processed.boilerplate.map((bp) => {
290
+ const newBp = { ...bp };
291
+ if (newBp.description && typeof newBp.description === "string") newBp.description = this.ensureMultilineFormat(newBp.description);
292
+ if (newBp.instruction && typeof newBp.instruction === "string") newBp.instruction = this.ensureMultilineFormat(newBp.instruction);
293
+ return newBp;
294
+ });
295
+ if (processed.features) processed.features = processed.features.map((feature) => {
296
+ const newFeature = { ...feature };
297
+ if (newFeature.description && typeof newFeature.description === "string") newFeature.description = this.ensureMultilineFormat(newFeature.description);
298
+ if (newFeature.instruction && typeof newFeature.instruction === "string") newFeature.instruction = this.ensureMultilineFormat(newFeature.instruction);
299
+ return newFeature;
300
+ });
301
+ return processed;
302
+ }
303
+ /**
304
+ * Ensure string is properly formatted for YAML literal blocks
305
+ */
306
+ ensureMultilineFormat(text) {
307
+ return text.trim();
308
+ }
309
+ /**
310
+ * Generate or update a boilerplate configuration in scaffold.yaml
311
+ */
312
+ async generateBoilerplate(options) {
313
+ const { templateName, boilerplateName, description, instruction, targetFolder, variables, includes = [] } = options;
314
+ const templatePath = node_path.join(this.templatesPath, templateName);
315
+ await fs_extra.ensureDir(templatePath);
316
+ const scaffoldYamlPath = node_path.join(templatePath, "scaffold.yaml");
317
+ let scaffoldConfig = {};
318
+ if (await fs_extra.pathExists(scaffoldYamlPath)) {
319
+ const yamlContent$1 = await fs_extra.readFile(scaffoldYamlPath, "utf-8");
320
+ scaffoldConfig = js_yaml.load(yamlContent$1);
321
+ }
322
+ if (!scaffoldConfig.boilerplate) scaffoldConfig.boilerplate = [];
323
+ if (scaffoldConfig.boilerplate.findIndex((b) => b.name === boilerplateName) !== -1) return {
324
+ success: false,
325
+ message: `Boilerplate '${boilerplateName}' already exists in ${scaffoldYamlPath}`
326
+ };
327
+ const requiredVars = variables.filter((v) => v.required).map((v) => v.name);
328
+ const boilerplateDefinition = {
329
+ name: boilerplateName,
330
+ targetFolder,
331
+ description,
332
+ variables_schema: {
333
+ type: "object",
334
+ properties: variables.reduce((acc, v) => {
335
+ acc[v.name] = {
336
+ type: v.type,
337
+ description: v.description
338
+ };
339
+ if (v.default !== void 0) acc[v.name].default = v.default;
340
+ return acc;
341
+ }, {}),
342
+ required: requiredVars,
343
+ additionalProperties: false
344
+ },
345
+ includes: includes.length > 0 ? includes : []
346
+ };
347
+ if (instruction) boilerplateDefinition.instruction = instruction;
348
+ scaffoldConfig.boilerplate.push(boilerplateDefinition);
349
+ const yamlContent = this.dumpYamlWithLiteralBlocks(scaffoldConfig);
350
+ await fs_extra.writeFile(scaffoldYamlPath, yamlContent, "utf-8");
351
+ return {
352
+ success: true,
353
+ message: `Boilerplate '${boilerplateName}' added to ${scaffoldYamlPath}`,
354
+ templatePath,
355
+ scaffoldYamlPath
356
+ };
357
+ }
358
+ /**
359
+ * List all templates (directories in templates folder)
360
+ */
361
+ async listTemplates() {
362
+ return (await fs_extra.readdir(this.templatesPath, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
363
+ }
364
+ /**
365
+ * Check if a template exists
366
+ */
367
+ async templateExists(templateName) {
368
+ const templatePath = node_path.join(this.templatesPath, templateName);
369
+ return fs_extra.pathExists(templatePath);
370
+ }
371
+ /**
372
+ * Create or update a template file for a boilerplate
373
+ */
374
+ async createTemplateFile(options) {
375
+ const { templateName, filePath, content, sourceFile, header } = options;
376
+ const templatePath = node_path.join(this.templatesPath, templateName);
377
+ if (!await fs_extra.pathExists(templatePath)) return {
378
+ success: false,
379
+ message: `Template directory '${templateName}' does not exist at ${templatePath}`
380
+ };
381
+ let fileContent = content || "";
382
+ if (sourceFile) {
383
+ if (!await fs_extra.pathExists(sourceFile)) return {
384
+ success: false,
385
+ message: `Source file '${sourceFile}' does not exist`
386
+ };
387
+ fileContent = await fs_extra.readFile(sourceFile, "utf-8");
388
+ }
389
+ if (!fileContent && !sourceFile) return {
390
+ success: false,
391
+ message: "Either content or sourceFile must be provided"
392
+ };
393
+ const templateFilePath = filePath.endsWith(".liquid") ? filePath : `${filePath}.liquid`;
394
+ const fullPath = node_path.join(templatePath, templateFilePath);
395
+ await fs_extra.ensureDir(node_path.dirname(fullPath));
396
+ let finalContent = fileContent;
397
+ if (header) finalContent = `${header}\n\n${fileContent}`;
398
+ await fs_extra.writeFile(fullPath, finalContent, "utf-8");
399
+ return {
400
+ success: true,
401
+ message: "Template file created successfully",
402
+ filePath: templateFilePath,
403
+ fullPath
404
+ };
405
+ }
406
+ };
407
+
408
+ //#endregion
409
+ //#region src/tools/GenerateBoilerplateFileTool.ts
410
+ /**
411
+ * Tool to generate template files for boilerplates and features
412
+ */
413
+ var GenerateBoilerplateFileTool = class GenerateBoilerplateFileTool {
414
+ static TOOL_NAME = "generate-boilerplate-file";
415
+ boilerplateGeneratorService;
416
+ isMonolith;
417
+ constructor(templatesPath, isMonolith = false) {
418
+ this.boilerplateGeneratorService = new BoilerplateGeneratorService(templatesPath);
419
+ this.isMonolith = isMonolith;
420
+ }
421
+ /**
422
+ * Get the tool definition for MCP
423
+ */
424
+ getDefinition() {
425
+ const properties = {};
426
+ if (!this.isMonolith) properties.templateName = {
427
+ type: "string",
428
+ description: "Name of the template folder (must already exist)"
429
+ };
430
+ Object.assign(properties, {
431
+ filePath: {
432
+ type: "string",
433
+ description: "Path of the file to create within the template (e.g., \"package.json\", \"src/app/page.tsx\")"
434
+ },
435
+ content: {
436
+ type: "string",
437
+ description: `Content of the template file using Liquid template syntax.
438
+
439
+ LIQUID SYNTAX:
440
+ - Variables: {{ variableName }} - Replaced with actual values
441
+ - Conditionals: {% if condition %}...{% endif %} - Conditional rendering
442
+ - Else: {% if condition %}...{% else %}...{% endif %}
443
+ - Elsif: {% if condition %}...{% elsif other %}...{% endif %}
444
+ - Equality: {% if var == 'value' %}...{% endif %}
445
+
446
+ AVAILABLE FILTERS:
447
+ You can transform variables using these filters with the pipe (|) syntax:
448
+
449
+ Case Conversion:
450
+ - {{ name | camelCase }} - Convert to camelCase (myVariableName)
451
+ - {{ name | pascalCase }} - Convert to PascalCase (MyVariableName)
452
+ - {{ name | titleCase }} - Convert to TitleCase (alias for pascalCase)
453
+ - {{ name | kebabCase }} - Convert to kebab-case (my-variable-name)
454
+ - {{ name | snakeCase }} - Convert to snake_case (my_variable_name)
455
+ - {{ name | upperCase }} - Convert to UPPER_CASE (MY_VARIABLE_NAME)
456
+ - {{ name | lower }} or {{ name | downcase }} - Convert to lowercase
457
+ - {{ name | upper }} or {{ name | upcase }} - Convert to UPPERCASE
458
+
459
+ String Manipulation:
460
+ - {{ name | strip }} - Remove leading/trailing whitespace
461
+ - {{ name | replace: "old", "new" }} - Replace text (e.g., replace: "Tool", "")
462
+ - {{ name | pluralize }} - Add plural suffix (simple: book → books, class → classes)
463
+ - {{ name | singularize }} - Remove plural suffix (simple: books → book)
464
+
465
+ Chaining Filters:
466
+ - {{ toolName | downcase | replace: "tool", "" | strip }} - Combine multiple filters
467
+
468
+ Example with variables and conditionals:
469
+ {
470
+ "name": "{{ packageName }}",{% if withFeature %}
471
+ "feature": "enabled",{% endif %}
472
+ "dependencies": {
473
+ "core": "1.0.0"{% if withOptional %},
474
+ "optional": "2.0.0"{% endif %}
475
+ }
476
+ }
477
+
478
+ Example with filters:
479
+ export class {{ serviceName | pascalCase }} {
480
+ private {{ serviceName | camelCase }}: string;
481
+
482
+ constructor() {
483
+ this.{{ serviceName | camelCase }} = "{{ serviceName | kebabCase }}";
484
+ }
485
+ }
486
+
487
+ IMPORTANT - Keep content minimal and business-agnostic:
488
+ - Focus on structure and patterns, not specific business logic
489
+ - Use placeholder data and generic examples
490
+ - Include only essential boilerplate code
491
+ - Demonstrate the pattern, not a complete implementation
492
+ - Let AI fill in business-specific logic later
493
+
494
+ Example (good - minimal):
495
+ export function {{ functionName }}() {
496
+ // TODO: Implement logic
497
+ return null;
498
+ }
499
+
500
+ Example (bad - too specific):
501
+ export function calculateTax(income: number) {
502
+ const federalRate = 0.22;
503
+ const stateRate = 0.05;
504
+ return income * (federalRate + stateRate);
505
+ }`
506
+ },
507
+ sourceFile: {
508
+ type: "string",
509
+ description: "Optional: Path to a source file to copy and convert to a template"
510
+ },
511
+ header: {
512
+ type: "string",
513
+ description: `Optional: Header comment to add at the top of the file to provide AI hints about design patterns, coding standards, and best practices.
514
+
515
+ Example format for TypeScript/JavaScript files:
516
+ /**
517
+ * {{ componentName }} Component
518
+ *
519
+ * DESIGN PATTERNS:
520
+ * - Component pattern description
521
+ * - Architecture decisions
522
+ *
523
+ * CODING STANDARDS:
524
+ * - Naming conventions
525
+ * - Required elements
526
+ *
527
+ * AVOID:
528
+ * - Common pitfalls
529
+ * - Anti-patterns
530
+ */
531
+
532
+ The header helps AI understand and follow established patterns when working with generated code.`
533
+ }
534
+ });
535
+ const required = ["filePath"];
536
+ if (!this.isMonolith) required.unshift("templateName");
537
+ return {
538
+ name: GenerateBoilerplateFileTool.TOOL_NAME,
539
+ description: `Create or update template files for boilerplates or features in the specified template directory.
540
+
541
+ This tool:
542
+ - Creates template files with .liquid extension for variable substitution
543
+ - Supports creating nested directory structures
544
+ - Can create files from source files (copying and converting to templates)
545
+ - Validates that the template directory exists
546
+ - Works for both boilerplate includes and feature scaffold includes
547
+
548
+ IMPORTANT - Always add header comments:
549
+ - For code files (*.ts, *.tsx, *.js, *.jsx), ALWAYS include a header parameter with design patterns, coding standards, and things to avoid
550
+ - Headers help AI understand and follow established patterns when working with generated code
551
+ - Use the header parameter to document the architectural decisions and best practices
552
+
553
+ Use this after generate-boilerplate or generate-feature-scaffold to create the actual template files referenced in the includes array.`,
554
+ inputSchema: {
555
+ type: "object",
556
+ properties,
557
+ required,
558
+ additionalProperties: false
559
+ }
560
+ };
561
+ }
562
+ /**
563
+ * Execute the tool
564
+ */
565
+ async execute(args) {
566
+ try {
567
+ let { templateName } = args;
568
+ if (this.isMonolith && !templateName) try {
569
+ templateName = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
570
+ } catch (error) {
571
+ return {
572
+ content: [{
573
+ type: "text",
574
+ text: `Failed to read template name from configuration: ${error instanceof Error ? error.message : String(error)}`
575
+ }],
576
+ isError: true
577
+ };
578
+ }
579
+ if (!templateName) return {
580
+ content: [{
581
+ type: "text",
582
+ text: "Missing required parameter: templateName"
583
+ }],
584
+ isError: true
585
+ };
586
+ const result = await this.boilerplateGeneratorService.createTemplateFile({
587
+ ...args,
588
+ templateName
589
+ });
590
+ if (!result.success) return {
591
+ content: [{
592
+ type: "text",
593
+ text: result.message
594
+ }],
595
+ isError: true
596
+ };
597
+ return { content: [{
598
+ type: "text",
599
+ text: JSON.stringify({
600
+ success: true,
601
+ message: result.message,
602
+ filePath: result.filePath,
603
+ fullPath: result.fullPath,
604
+ sourceFile: args.sourceFile || null
605
+ }, null, 2)
606
+ }] };
607
+ } catch (error) {
608
+ return {
609
+ content: [{
610
+ type: "text",
611
+ text: `Error creating template file: ${error instanceof Error ? error.message : String(error)}`
612
+ }],
613
+ isError: true
614
+ };
615
+ }
616
+ }
617
+ };
618
+
619
+ //#endregion
620
+ //#region src/tools/GenerateBoilerplateTool.ts
621
+ /**
622
+ * Tool to generate a new boilerplate configuration in scaffold.yaml
623
+ */
624
+ var GenerateBoilerplateTool = class GenerateBoilerplateTool {
625
+ static TOOL_NAME = "generate-boilerplate";
626
+ boilerplateGeneratorService;
627
+ isMonolith;
628
+ constructor(templatesPath, isMonolith = false) {
629
+ this.boilerplateGeneratorService = new BoilerplateGeneratorService(templatesPath);
630
+ this.isMonolith = isMonolith;
631
+ }
632
+ /**
633
+ * Get the tool definition for MCP
634
+ */
635
+ getDefinition() {
636
+ const properties = {};
637
+ if (!this.isMonolith) properties.templateName = {
638
+ type: "string",
639
+ description: "Name of the template folder (kebab-case, e.g., \"my-framework\")"
640
+ };
641
+ Object.assign(properties, {
642
+ boilerplateName: {
643
+ type: "string",
644
+ description: "Name of the boilerplate (kebab-case, e.g., \"scaffold-my-app\")"
645
+ },
646
+ targetFolder: {
647
+ type: "string",
648
+ description: "Target folder where projects will be created (e.g., \"apps\", \"packages\")"
649
+ },
650
+ description: {
651
+ type: "string",
652
+ description: `Detailed description of what this boilerplate creates and its key features.
653
+
654
+ STRUCTURE (3-5 sentences in multiple paragraphs):
655
+ - Paragraph 1: Core technology stack and primary value proposition
656
+ - Paragraph 2: Target use cases and ideal project types
657
+ - Paragraph 3: Key integrations or special features (if applicable)
658
+
659
+ Example: "A modern React SPA template powered by Vite for lightning-fast HMR, featuring TanStack Router for type-safe routing and TanStack Query for server state management.
660
+ Perfect for building data-driven dashboards, admin panels, and interactive web applications requiring client-side routing and real-time data synchronization.
661
+
662
+ Includes Agiflow Config Management System integration with systematic environment variable naming (VITE_{CATEGORY}_{SUBCATEGORY}_{PROPERTY}) and auto-generated configuration templates for cloud deployment."`
663
+ },
664
+ instruction: {
665
+ type: "string",
666
+ description: `Optional detailed instructions about the generated files, their purposes, and how to work with them.
667
+
668
+ STRUCTURE (Multi-section guide):
669
+
670
+ 1. **File purposes** section:
671
+ List each major file/directory with its purpose
672
+ Format: "- path/to/file: Description of what this file does"
673
+
674
+ 2. **How to use the scaffolded code** section:
675
+ Step-by-step workflows for common tasks
676
+ Format: Numbered list with specific examples
677
+ - How to add routes/pages
678
+ - How to fetch data
679
+ - How to handle authentication
680
+ - How to configure environment variables
681
+
682
+ 3. **Design patterns to follow** section:
683
+ Key architectural decisions and conventions
684
+ Format: "- Pattern Name: Explanation and when to use it"
685
+ - Routing patterns
686
+ - State management patterns
687
+ - Data fetching patterns
688
+ - Error handling patterns
689
+ - Performance optimization patterns
690
+
691
+ Example: "[Framework] application template with [key technologies].
692
+
693
+ File purposes:
694
+ - package.json: NPM package configuration with [framework] and dependencies
695
+ - src/main.tsx: Application entry point with [setup details]
696
+ - src/routes/: Route definitions following [pattern]
697
+ [... list all major files ...]
698
+
699
+ How to use the scaffolded code:
700
+ 1. Routes: Create new routes by [specific instructions with example]
701
+ 2. Data Fetching: Use [specific pattern] for [use case]
702
+ 3. Authentication: Use [specific components/modules] for user management
703
+ [... numbered steps for common tasks ...]
704
+
705
+ Design patterns to follow:
706
+ - File-based Routing: Use directory structure in src/routes/ to define URL paths
707
+ - Type-safe Routes: Leverage [framework] type inference for params
708
+ - State Management: Use [library] for server state, [library] for client state
709
+ [... list key patterns with explanations ...]"`
710
+ },
711
+ variables: {
712
+ type: "array",
713
+ description: "Array of variable definitions for the boilerplate",
714
+ items: {
715
+ type: "object",
716
+ properties: {
717
+ name: {
718
+ type: "string",
719
+ description: "Variable name (camelCase)"
720
+ },
721
+ description: {
722
+ type: "string",
723
+ description: "Variable description"
724
+ },
725
+ type: {
726
+ type: "string",
727
+ enum: [
728
+ "string",
729
+ "number",
730
+ "boolean"
731
+ ],
732
+ description: "Variable type"
733
+ },
734
+ required: {
735
+ type: "boolean",
736
+ description: "Whether this variable is required"
737
+ },
738
+ default: { description: "Optional default value for the variable" }
739
+ },
740
+ required: [
741
+ "name",
742
+ "description",
743
+ "type",
744
+ "required"
745
+ ]
746
+ }
747
+ },
748
+ includes: {
749
+ type: "array",
750
+ description: `Array of specific file paths to include in the boilerplate (highly recommended to list explicitly).
751
+
752
+ Examples:
753
+ - ["package.json", "tsconfig.json", "src/index.ts"] - Explicit file list (recommended)
754
+ - ["**/*"] - Include all files (not recommended, too broad)
755
+
756
+ Best practices:
757
+ - List each file explicitly for clarity and control
758
+ - Use relative paths from the template root
759
+ - Include configuration files (package.json, tsconfig.json, etc.)
760
+ - Include source files (src/index.ts, src/app/page.tsx, etc.)
761
+ - Avoid wildcards unless you have a good reason
762
+
763
+ See templates/nextjs-15/scaffold.yaml for a good example of explicit file listing.`,
764
+ items: { type: "string" }
765
+ }
766
+ });
767
+ const required = [
768
+ "boilerplateName",
769
+ "description",
770
+ "variables"
771
+ ];
772
+ if (!this.isMonolith) {
773
+ required.unshift("templateName");
774
+ required.push("targetFolder");
775
+ }
776
+ return {
777
+ name: GenerateBoilerplateTool.TOOL_NAME,
778
+ description: `Add a new boilerplate configuration to a template's scaffold.yaml file.
779
+
780
+ This tool:
781
+ - Creates or updates scaffold.yaml in the specified template directory
782
+ - Adds a boilerplate entry with proper schema following the nextjs-15 pattern
783
+ - Validates the boilerplate name doesn't already exist
784
+ - Creates the template directory if it doesn't exist
785
+
786
+ Use this to add custom boilerplate configurations for frameworks not yet supported or for your specific project needs.`,
787
+ inputSchema: {
788
+ type: "object",
789
+ properties,
790
+ required,
791
+ additionalProperties: false
792
+ }
793
+ };
794
+ }
795
+ /**
796
+ * Execute the tool
797
+ */
798
+ async execute(args) {
799
+ try {
800
+ let { templateName, targetFolder } = args;
801
+ if (this.isMonolith && !templateName) try {
802
+ templateName = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
803
+ } catch (error) {
804
+ return {
805
+ content: [{
806
+ type: "text",
807
+ text: `Failed to read template name from configuration: ${error instanceof Error ? error.message : String(error)}`
808
+ }],
809
+ isError: true
810
+ };
811
+ }
812
+ if (this.isMonolith && !targetFolder) targetFolder = ".";
813
+ if (!templateName) return {
814
+ content: [{
815
+ type: "text",
816
+ text: "Missing required parameter: templateName"
817
+ }],
818
+ isError: true
819
+ };
820
+ if (!targetFolder) return {
821
+ content: [{
822
+ type: "text",
823
+ text: "Missing required parameter: targetFolder"
824
+ }],
825
+ isError: true
826
+ };
827
+ const result = await this.boilerplateGeneratorService.generateBoilerplate({
828
+ ...args,
829
+ templateName,
830
+ targetFolder
831
+ });
832
+ if (!result.success) return {
833
+ content: [{
834
+ type: "text",
835
+ text: result.message
836
+ }],
837
+ isError: true
838
+ };
839
+ return { content: [{
840
+ type: "text",
841
+ text: JSON.stringify({
842
+ success: true,
843
+ message: result.message,
844
+ templatePath: result.templatePath,
845
+ scaffoldYamlPath: result.scaffoldYamlPath,
846
+ nextSteps: [
847
+ "Use generate-boilerplate-file tool to create template files for the includes array",
848
+ "Customize the template files with Liquid variable placeholders ({{ variableName }})",
849
+ `Test with: scaffold-mcp boilerplate create ${args.boilerplateName} --vars '{"appName":"test"}'`
850
+ ]
851
+ }, null, 2)
852
+ }] };
853
+ } catch (error) {
854
+ return {
855
+ content: [{
856
+ type: "text",
857
+ text: `Error generating boilerplate: ${error instanceof Error ? error.message : String(error)}`
858
+ }],
859
+ isError: true
860
+ };
861
+ }
862
+ }
863
+ };
864
+
865
+ //#endregion
866
+ //#region src/services/ScaffoldGeneratorService.ts
867
+ /**
868
+ * Service for generating feature scaffold configurations in scaffold.yaml files
869
+ */
870
+ var ScaffoldGeneratorService = class {
871
+ templatesPath;
872
+ constructor(templatesPath) {
873
+ this.templatesPath = templatesPath;
874
+ }
875
+ /**
876
+ * Custom YAML dumper that forces literal block style (|) for description and instruction fields
877
+ */
878
+ dumpYamlWithLiteralBlocks(config) {
879
+ const LiteralBlockType = new js_yaml.Type("tag:yaml.org,2002:str", {
880
+ kind: "scalar",
881
+ construct: (data) => data,
882
+ represent: (data) => {
883
+ return data;
884
+ },
885
+ defaultStyle: "|"
886
+ });
887
+ const LITERAL_SCHEMA = js_yaml.DEFAULT_SCHEMA.extend([LiteralBlockType]);
888
+ const processedConfig = this.processConfigForLiteralBlocks(config);
889
+ return js_yaml.dump(processedConfig, {
890
+ schema: LITERAL_SCHEMA,
891
+ indent: 2,
892
+ lineWidth: -1,
893
+ noRefs: true,
894
+ sortKeys: false,
895
+ styles: { "!!str": "literal" },
896
+ replacer: (key, value) => {
897
+ if ((key === "description" || key === "instruction") && typeof value === "string") return value;
898
+ return value;
899
+ }
900
+ });
901
+ }
902
+ /**
903
+ * Process config to ensure description and instruction use literal block style
904
+ */
905
+ processConfigForLiteralBlocks(config) {
906
+ const processed = JSON.parse(JSON.stringify(config));
907
+ if (processed.boilerplate) processed.boilerplate = processed.boilerplate.map((bp) => {
908
+ const newBp = { ...bp };
909
+ if (newBp.description && typeof newBp.description === "string") newBp.description = this.ensureMultilineFormat(newBp.description);
910
+ if (newBp.instruction && typeof newBp.instruction === "string") newBp.instruction = this.ensureMultilineFormat(newBp.instruction);
911
+ return newBp;
912
+ });
913
+ if (processed.features) processed.features = processed.features.map((feature) => {
914
+ const newFeature = { ...feature };
915
+ if (newFeature.description && typeof newFeature.description === "string") newFeature.description = this.ensureMultilineFormat(newFeature.description);
916
+ if (newFeature.instruction && typeof newFeature.instruction === "string") newFeature.instruction = this.ensureMultilineFormat(newFeature.instruction);
917
+ return newFeature;
918
+ });
919
+ return processed;
920
+ }
921
+ /**
922
+ * Ensure string is properly formatted for YAML literal blocks
923
+ */
924
+ ensureMultilineFormat(text) {
925
+ return text.trim();
926
+ }
927
+ /**
928
+ * Generate or update a feature configuration in scaffold.yaml
929
+ */
930
+ async generateFeatureScaffold(options) {
931
+ const { templateName, featureName, description, instruction, variables, includes = [], patterns = [] } = options;
932
+ const templatePath = node_path.join(this.templatesPath, templateName);
933
+ await fs_extra.ensureDir(templatePath);
934
+ const scaffoldYamlPath = node_path.join(templatePath, "scaffold.yaml");
935
+ let scaffoldConfig = {};
936
+ if (await fs_extra.pathExists(scaffoldYamlPath)) {
937
+ const yamlContent$1 = await fs_extra.readFile(scaffoldYamlPath, "utf-8");
938
+ scaffoldConfig = js_yaml.load(yamlContent$1);
939
+ }
940
+ if (!scaffoldConfig.features) scaffoldConfig.features = [];
941
+ if (scaffoldConfig.features.findIndex((f) => f.name === featureName) !== -1) return {
942
+ success: false,
943
+ message: `Feature '${featureName}' already exists in ${scaffoldYamlPath}`
944
+ };
945
+ const requiredVars = variables.filter((v) => v.required).map((v) => v.name);
946
+ const featureDefinition = {
947
+ name: featureName,
948
+ description,
949
+ variables_schema: {
950
+ type: "object",
951
+ properties: variables.reduce((acc, v) => {
952
+ acc[v.name] = {
953
+ type: v.type,
954
+ description: v.description
955
+ };
956
+ if (v.default !== void 0) acc[v.name].default = v.default;
957
+ return acc;
958
+ }, {}),
959
+ required: requiredVars,
960
+ additionalProperties: false
961
+ },
962
+ includes: includes.length > 0 ? includes : []
963
+ };
964
+ if (instruction) featureDefinition.instruction = instruction;
965
+ if (patterns && patterns.length > 0) featureDefinition.patterns = patterns;
966
+ scaffoldConfig.features.push(featureDefinition);
967
+ const yamlContent = this.dumpYamlWithLiteralBlocks(scaffoldConfig);
968
+ await fs_extra.writeFile(scaffoldYamlPath, yamlContent, "utf-8");
969
+ return {
970
+ success: true,
971
+ message: `Feature '${featureName}' added to ${scaffoldYamlPath}`,
972
+ templatePath,
973
+ scaffoldYamlPath
974
+ };
975
+ }
976
+ /**
977
+ * List all templates (directories in templates folder)
978
+ */
979
+ async listTemplates() {
980
+ return (await fs_extra.readdir(this.templatesPath, { withFileTypes: true })).filter((entry) => entry.isDirectory()).map((entry) => entry.name);
981
+ }
982
+ /**
983
+ * Check if a template exists
984
+ */
985
+ async templateExists(templateName) {
986
+ const templatePath = node_path.join(this.templatesPath, templateName);
987
+ return fs_extra.pathExists(templatePath);
988
+ }
989
+ };
990
+
991
+ //#endregion
992
+ //#region src/tools/GenerateFeatureScaffoldTool.ts
993
+ /**
994
+ * Tool to generate a new feature scaffold configuration in scaffold.yaml
995
+ */
996
+ var GenerateFeatureScaffoldTool = class GenerateFeatureScaffoldTool {
997
+ static TOOL_NAME = "generate-feature-scaffold";
998
+ scaffoldGeneratorService;
999
+ isMonolith;
1000
+ constructor(templatesPath, isMonolith = false) {
1001
+ this.scaffoldGeneratorService = new ScaffoldGeneratorService(templatesPath);
1002
+ this.isMonolith = isMonolith;
1003
+ }
1004
+ /**
1005
+ * Get the tool definition for MCP
1006
+ */
1007
+ getDefinition() {
1008
+ const properties = {};
1009
+ if (!this.isMonolith) properties.templateName = {
1010
+ type: "string",
1011
+ description: "Name of the template folder (kebab-case, e.g., \"nextjs-15\")"
1012
+ };
1013
+ Object.assign(properties, {
1014
+ featureName: {
1015
+ type: "string",
1016
+ description: "Name of the feature (kebab-case, e.g., \"scaffold-nextjs-page\")"
1017
+ },
1018
+ description: {
1019
+ type: "string",
1020
+ description: `Detailed description of what this feature creates and its key capabilities.
1021
+
1022
+ STRUCTURE (2-3 sentences):
1023
+ - Sentence 1: What type of code it generates (component, page, service, etc.)
1024
+ - Sentence 2: Key features or capabilities included
1025
+ - Sentence 3: Primary use cases or when to use it
1026
+
1027
+ Example: "Generate a new service class for TypeScript libraries following best practices. Creates a service class with interface, implementation, and unit tests. Perfect for creating reusable service modules with dependency injection patterns."`
1028
+ },
1029
+ instruction: {
1030
+ type: "string",
1031
+ description: `Optional detailed instructions about the generated files, their purposes, and how to work with them.
1032
+
1033
+ STRUCTURE (Concise multi-aspect guide):
1034
+
1035
+ 1. **Pattern explanation**: Describe the architectural pattern used
1036
+ 2. **File organization**: Where files should be placed
1037
+ 3. **Naming conventions**: How to name things (PascalCase, camelCase, etc.)
1038
+ 4. **Usage guidelines**: How to use the generated code
1039
+ 5. **Testing approach**: How to test the feature
1040
+
1041
+ Example: "Services follow a class-based pattern with optional interface separation. The service class implements business logic and can be dependency injected. Place services in src/services/ directory. For services with interfaces, define the interface in src/types/interfaces/ for better separation of concerns. Service names should be PascalCase and end with 'Service' suffix. Write comprehensive unit tests for all public methods."`
1042
+ },
1043
+ variables: {
1044
+ type: "array",
1045
+ description: "Array of variable definitions for the feature",
1046
+ items: {
1047
+ type: "object",
1048
+ properties: {
1049
+ name: {
1050
+ type: "string",
1051
+ description: "Variable name (camelCase)"
1052
+ },
1053
+ description: {
1054
+ type: "string",
1055
+ description: "Variable description"
1056
+ },
1057
+ type: {
1058
+ type: "string",
1059
+ enum: [
1060
+ "string",
1061
+ "number",
1062
+ "boolean"
1063
+ ],
1064
+ description: "Variable type"
1065
+ },
1066
+ required: {
1067
+ type: "boolean",
1068
+ description: "Whether this variable is required"
1069
+ },
1070
+ default: { description: "Optional default value for the variable" }
1071
+ },
1072
+ required: [
1073
+ "name",
1074
+ "description",
1075
+ "type",
1076
+ "required"
1077
+ ]
1078
+ }
1079
+ },
1080
+ includes: {
1081
+ type: "array",
1082
+ description: `Array of specific file paths to include in the feature (highly recommended to list explicitly).
1083
+
1084
+ Supports advanced syntax:
1085
+ - Basic: "src/app/page/page.tsx" - Always included
1086
+ - Conditional: "src/app/page/layout.tsx?withLayout=true" - Only included when withLayout variable is true
1087
+ - Multiple conditions: "file.tsx?withLayout=true&withTests=true" - Use & to combine conditions
1088
+ - Path mapping: "source.tsx->target/path.tsx" - Map source template file to different target path
1089
+ - Combined: "source.tsx->{{ pagePath }}/page.tsx?withPage=true" - Combine path mapping with variables and conditions
1090
+
1091
+ Examples:
1092
+ - ["src/components/Button.tsx", "src/components/Button.test.tsx"] - Explicit file list (recommended)
1093
+ - ["src/app/page/page.tsx", "src/app/page/layout.tsx?withLayout=true"] - Conditional include
1094
+ - ["template.tsx->src/app/{{ pagePath }}/page.tsx"] - Dynamic path with variables
1095
+
1096
+ Best practices:
1097
+ - List each file explicitly for clarity and control
1098
+ - Use relative paths from the template root
1099
+ - Use conditional includes with ?variableName=value for optional files
1100
+ - Use path mapping with -> when source and target paths differ
1101
+ - Use {{ variableName }} in target paths for dynamic file placement
1102
+ - Avoid wildcards unless you have a good reason`,
1103
+ items: { type: "string" }
1104
+ },
1105
+ patterns: {
1106
+ type: "array",
1107
+ description: `Optional array of glob patterns to match existing files that this feature works with.
1108
+
1109
+ Used to help identify where this feature can be applied in a project.
1110
+
1111
+ Examples:
1112
+ - ["src/app/**/page.tsx", "src/app/**/layout.tsx"] - Next.js app router files
1113
+ - ["src/components/**/*.tsx"] - React component files
1114
+ - ["src/services/**/*.ts"] - Service files
1115
+
1116
+ Best practices:
1117
+ - Use glob patterns that match the file types this feature works with
1118
+ - Keep patterns specific enough to be meaningful but broad enough to be useful
1119
+ - Consider both the feature's output and input files`,
1120
+ items: { type: "string" }
1121
+ }
1122
+ });
1123
+ const required = [
1124
+ "featureName",
1125
+ "description",
1126
+ "variables"
1127
+ ];
1128
+ if (!this.isMonolith) required.unshift("templateName");
1129
+ return {
1130
+ name: GenerateFeatureScaffoldTool.TOOL_NAME,
1131
+ description: `Add a new feature scaffold configuration to a template's scaffold.yaml file.
1132
+
1133
+ This tool:
1134
+ - Creates or updates scaffold.yaml in the specified template directory
1135
+ - Adds a feature entry with proper schema following the nextjs-15 pattern
1136
+ - Validates the feature name doesn't already exist
1137
+ - Creates the template directory if it doesn't exist
1138
+
1139
+ Use this to add custom feature scaffolds (pages, components, services, etc.) for frameworks not yet supported or for your specific project needs.`,
1140
+ inputSchema: {
1141
+ type: "object",
1142
+ properties,
1143
+ required,
1144
+ additionalProperties: false
1145
+ }
1146
+ };
1147
+ }
1148
+ /**
1149
+ * Execute the tool
1150
+ */
1151
+ async execute(args) {
1152
+ try {
1153
+ let { templateName } = args;
1154
+ if (this.isMonolith && !templateName) try {
1155
+ templateName = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
1156
+ } catch (error) {
1157
+ return {
1158
+ content: [{
1159
+ type: "text",
1160
+ text: `Failed to read template name from configuration: ${error instanceof Error ? error.message : String(error)}`
1161
+ }],
1162
+ isError: true
1163
+ };
1164
+ }
1165
+ if (!templateName) return {
1166
+ content: [{
1167
+ type: "text",
1168
+ text: "Missing required parameter: templateName"
1169
+ }],
1170
+ isError: true
1171
+ };
1172
+ const result = await this.scaffoldGeneratorService.generateFeatureScaffold({
1173
+ ...args,
1174
+ templateName
1175
+ });
1176
+ if (!result.success) return {
1177
+ content: [{
1178
+ type: "text",
1179
+ text: result.message
1180
+ }],
1181
+ isError: true
1182
+ };
1183
+ return { content: [{
1184
+ type: "text",
1185
+ text: JSON.stringify({
1186
+ success: true,
1187
+ message: result.message,
1188
+ templatePath: result.templatePath,
1189
+ scaffoldYamlPath: result.scaffoldYamlPath,
1190
+ nextSteps: [
1191
+ "Use generate-boilerplate-file tool to create template files for the includes array",
1192
+ "Customize the template files with Liquid variable placeholders ({{ variableName }})",
1193
+ "Create the generator file if it uses custom logic (referenced in the generator field)",
1194
+ `Test with: scaffold-mcp feature create ${args.featureName} --vars '{"appName":"test"}'`
1195
+ ]
1196
+ }, null, 2)
1197
+ }] };
1198
+ } catch (error) {
1199
+ return {
1200
+ content: [{
1201
+ type: "text",
1202
+ text: `Error generating feature scaffold: ${error instanceof Error ? error.message : String(error)}`
1203
+ }],
1204
+ isError: true
1205
+ };
1206
+ }
1207
+ }
1208
+ };
1209
+
1210
+ //#endregion
1211
+ //#region src/instructions/tools/list-boilerplates/description.md?raw
1212
+ var description_default$2 = "{% if isMonolith %}\nNot available for monolith projects. Monolith uses a single template defined in `toolkit.yaml`.\n\nUse `list-scaffolding-methods` for available features instead.\n{% else %}\nLists all available project boilerplates for creating new applications, APIs, or packages in the monorepo.\n\nEach boilerplate includes:\n- Complete project template with starter files\n- Variable schema for customization\n- Target directory information (e.g., apps/, packages/)\n- Required and optional configuration options\n\nUse this FIRST when creating new projects to understand available templates and their requirements.\n{% endif %}\n";
1213
+
1214
+ //#endregion
1215
+ //#region src/tools/ListBoilerplatesTool.ts
1216
+ var ListBoilerplatesTool = class ListBoilerplatesTool {
1217
+ static TOOL_NAME = "list-boilerplates";
1218
+ boilerplateService;
1219
+ templateService;
1220
+ isMonolith;
1221
+ constructor(templatesPath, isMonolith = false) {
1222
+ this.boilerplateService = new BoilerplateService(templatesPath);
1223
+ this.templateService = new require_TemplateService.TemplateService();
1224
+ this.isMonolith = isMonolith;
1225
+ }
1226
+ /**
1227
+ * Get the tool definition for MCP
1228
+ */
1229
+ getDefinition() {
1230
+ const description = this.templateService.renderString(description_default$2, { isMonolith: this.isMonolith });
1231
+ return {
1232
+ name: ListBoilerplatesTool.TOOL_NAME,
1233
+ description: description.trim(),
1234
+ inputSchema: {
1235
+ type: "object",
1236
+ properties: {},
1237
+ additionalProperties: false
1238
+ }
1239
+ };
1240
+ }
1241
+ /**
1242
+ * Execute the tool
1243
+ */
1244
+ async execute(_args = {}) {
1245
+ try {
1246
+ const result = await this.boilerplateService.listBoilerplates();
1247
+ return { content: [{
1248
+ type: "text",
1249
+ text: JSON.stringify(result, null, 2)
1250
+ }] };
1251
+ } catch (error) {
1252
+ return {
1253
+ content: [{
1254
+ type: "text",
1255
+ text: `Error listing boilerplates: ${error instanceof Error ? error.message : String(error)}`
1256
+ }],
1257
+ isError: true
1258
+ };
1259
+ }
1260
+ }
1261
+ };
1262
+
1263
+ //#endregion
1264
+ //#region src/instructions/tools/list-scaffolding-methods/description.md?raw
1265
+ var description_default$1 = "Lists all available scaffolding methods (features) that can be added to an existing project{% if not isMonolith %} or for a specific template{% endif %}.\n\nThis tool:\n{% if isMonolith %}\n- Reads your project's sourceTemplate from toolkit.yaml at workspace root\n{% else %}\n- Reads the project's sourceTemplate from project.json (monorepo) or toolkit.yaml (monolith), OR\n- Directly uses the provided templateName to list available features\n{% endif %}\n- Returns available features for that template type\n- Provides variable schemas for each scaffolding method\n- Shows descriptions of what each method creates\n\nUse this FIRST when adding features to understand:\n- What scaffolding methods are available\n- What variables each method requires\n- What files/features will be generated\n\nExample methods might include:\n- Adding new React routes (for React apps)\n- Creating API endpoints (for backend projects)\n- Adding new components (for frontend projects)\n- Setting up database models (for API projects)\n";
1266
+
1267
+ //#endregion
1268
+ //#region src/services/ScaffoldingMethodsService.ts
1269
+ var ScaffoldingMethodsService = class {
1270
+ templateService;
1271
+ constructor(fileSystem, templatesRootPath) {
1272
+ this.fileSystem = fileSystem;
1273
+ this.templatesRootPath = templatesRootPath;
1274
+ this.templateService = new require_TemplateService.TemplateService();
1275
+ }
1276
+ async listScaffoldingMethods(projectPath) {
1277
+ const absoluteProjectPath = node_path.default.resolve(projectPath);
1278
+ const sourceTemplate = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(absoluteProjectPath)).sourceTemplate;
1279
+ return this.listScaffoldingMethodsByTemplate(sourceTemplate);
1280
+ }
1281
+ async listScaffoldingMethodsByTemplate(templateName) {
1282
+ const templatePath = await this.findTemplatePath(templateName);
1283
+ if (!templatePath) throw new Error(`Template not found for sourceTemplate: ${templateName}`);
1284
+ const fullTemplatePath = node_path.default.join(this.templatesRootPath, templatePath);
1285
+ const scaffoldYamlPath = node_path.default.join(fullTemplatePath, "scaffold.yaml");
1286
+ if (!await this.fileSystem.pathExists(scaffoldYamlPath)) throw new Error(`scaffold.yaml not found at ${scaffoldYamlPath}`);
1287
+ const scaffoldContent = await this.fileSystem.readFile(scaffoldYamlPath, "utf8");
1288
+ const architectConfig = js_yaml.default.load(scaffoldContent);
1289
+ const methods = [];
1290
+ if (architectConfig.features && Array.isArray(architectConfig.features)) architectConfig.features.forEach((feature) => {
1291
+ const featureName = feature.name || `scaffold-${templateName}`;
1292
+ methods.push({
1293
+ name: featureName,
1294
+ description: feature.description || "",
1295
+ instruction: feature.instruction || "",
1296
+ variables_schema: feature.variables_schema || {
1297
+ type: "object",
1298
+ properties: {},
1299
+ required: [],
1300
+ additionalProperties: false
1301
+ },
1302
+ generator: feature.generator
1303
+ });
1304
+ });
1305
+ return {
1306
+ sourceTemplate: templateName,
1307
+ templatePath,
1308
+ methods
1309
+ };
1310
+ }
1311
+ /**
1312
+ * Gets scaffolding methods with instructions rendered using provided variables
1313
+ */
1314
+ async listScaffoldingMethodsWithVariables(projectPath, variables) {
1315
+ const result = await this.listScaffoldingMethods(projectPath);
1316
+ const processedMethods = result.methods.map((method) => ({
1317
+ ...method,
1318
+ instruction: method.instruction ? this.processScaffoldInstruction(method.instruction, variables) : void 0
1319
+ }));
1320
+ return {
1321
+ ...result,
1322
+ methods: processedMethods
1323
+ };
1324
+ }
1325
+ /**
1326
+ * Processes scaffold instruction with template service
1327
+ */
1328
+ processScaffoldInstruction(instruction, variables) {
1329
+ if (this.templateService.containsTemplateVariables(instruction)) return this.templateService.renderString(instruction, variables);
1330
+ return instruction;
1331
+ }
1332
+ async findTemplatePath(sourceTemplate) {
1333
+ const templateDirs = await this.discoverTemplateDirs();
1334
+ if (templateDirs.includes(sourceTemplate)) return sourceTemplate;
1335
+ for (const templateDir of templateDirs) {
1336
+ const templatePath = node_path.default.join(this.templatesRootPath, templateDir);
1337
+ const scaffoldYamlPath = node_path.default.join(templatePath, "scaffold.yaml");
1338
+ if (await this.fileSystem.pathExists(scaffoldYamlPath)) try {
1339
+ const scaffoldContent = await this.fileSystem.readFile(scaffoldYamlPath, "utf8");
1340
+ const architectConfig = js_yaml.default.load(scaffoldContent);
1341
+ if (architectConfig.boilerplate && Array.isArray(architectConfig.boilerplate)) {
1342
+ for (const boilerplate of architectConfig.boilerplate) if (boilerplate.name?.includes(sourceTemplate)) return templateDir;
1343
+ }
1344
+ } catch (error) {
1345
+ __agiflowai_aicode_utils.log.warn(`Failed to read scaffold.yaml at ${scaffoldYamlPath}:`, error);
1346
+ }
1347
+ }
1348
+ return null;
1349
+ }
1350
+ /**
1351
+ * Resolves the project path, handling both monorepo and monolith cases
1352
+ * Uses ProjectConfigResolver to find the correct workspace/project root
1353
+ */
1354
+ async resolveProjectPath(projectPath) {
1355
+ const absolutePath = node_path.default.resolve(projectPath);
1356
+ return (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(absolutePath)).workspaceRoot || absolutePath;
1357
+ }
1358
+ /**
1359
+ * Dynamically discovers all template directories
1360
+ * Supports both flat structure (templates/nextjs-15) and nested structure (templates/apps/nextjs-15)
1361
+ **/
1362
+ async discoverTemplateDirs() {
1363
+ const templateDirs = [];
1364
+ try {
1365
+ const items = await this.fileSystem.readdir(this.templatesRootPath);
1366
+ for (const item of items) {
1367
+ const itemPath = node_path.default.join(this.templatesRootPath, item);
1368
+ if (!(await this.fileSystem.stat(itemPath)).isDirectory()) continue;
1369
+ const scaffoldYamlPath = node_path.default.join(itemPath, "scaffold.yaml");
1370
+ if (await this.fileSystem.pathExists(scaffoldYamlPath)) {
1371
+ templateDirs.push(item);
1372
+ continue;
1373
+ }
1374
+ try {
1375
+ const subItems = await this.fileSystem.readdir(itemPath);
1376
+ for (const subItem of subItems) {
1377
+ const subItemPath = node_path.default.join(itemPath, subItem);
1378
+ if (!(await this.fileSystem.stat(subItemPath)).isDirectory()) continue;
1379
+ const subScaffoldYamlPath = node_path.default.join(subItemPath, "scaffold.yaml");
1380
+ if (await this.fileSystem.pathExists(subScaffoldYamlPath)) {
1381
+ const relativePath = node_path.default.join(item, subItem);
1382
+ templateDirs.push(relativePath);
1383
+ }
1384
+ }
1385
+ } catch (error) {
1386
+ __agiflowai_aicode_utils.log.warn(`Failed to read subdirectories in ${itemPath}:`, error);
1387
+ }
1388
+ }
1389
+ } catch (error) {
1390
+ __agiflowai_aicode_utils.log.warn(`Failed to read templates root directory ${this.templatesRootPath}:`, error);
1391
+ }
1392
+ return templateDirs;
1393
+ }
1394
+ async useScaffoldMethod(request) {
1395
+ const { projectPath, scaffold_feature_name, variables } = request;
1396
+ const absoluteProjectPath = await this.resolveProjectPath(projectPath);
1397
+ const scaffoldingMethods = await this.listScaffoldingMethods(absoluteProjectPath);
1398
+ const method = scaffoldingMethods.methods.find((m) => m.name === scaffold_feature_name);
1399
+ if (!method) {
1400
+ const availableMethods = scaffoldingMethods.methods.map((m) => m.name).join(", ");
1401
+ throw new Error(`Scaffold method '${scaffold_feature_name}' not found. Available methods: ${availableMethods}`);
1402
+ }
1403
+ const ScaffoldService$1 = (await Promise.resolve().then(() => require("./ScaffoldService-B3En_m4t.cjs"))).ScaffoldService;
1404
+ const ScaffoldConfigLoader$1 = (await Promise.resolve().then(() => require("./ScaffoldConfigLoader-DQMCLVGD.cjs"))).ScaffoldConfigLoader;
1405
+ const VariableReplacementService$1 = (await Promise.resolve().then(() => require("./VariableReplacementService-CroHkMha.cjs"))).VariableReplacementService;
1406
+ const TemplateService$1 = (await Promise.resolve().then(() => require("./TemplateService-BZRt3NI8.cjs"))).TemplateService;
1407
+ const templateService = new TemplateService$1();
1408
+ const scaffoldConfigLoader = new ScaffoldConfigLoader$1(this.fileSystem, templateService);
1409
+ const variableReplacer = new VariableReplacementService$1(this.fileSystem, templateService);
1410
+ const scaffoldService = new ScaffoldService$1(this.fileSystem, scaffoldConfigLoader, variableReplacer, this.templatesRootPath);
1411
+ const projectName = node_path.default.basename(absoluteProjectPath);
1412
+ const result = await scaffoldService.useFeature({
1413
+ projectPath: absoluteProjectPath,
1414
+ templateFolder: scaffoldingMethods.templatePath,
1415
+ featureName: scaffold_feature_name,
1416
+ variables: {
1417
+ ...variables,
1418
+ appPath: absoluteProjectPath,
1419
+ appName: projectName
1420
+ }
1421
+ });
1422
+ if (!result.success) throw new Error(result.message);
1423
+ return {
1424
+ success: true,
1425
+ message: `
1426
+ Successfully scaffolded ${scaffold_feature_name} in ${projectPath}.
1427
+ Please follow this **instruction**: \n ${method.instruction}.
1428
+ -> Create or update the plan based on the instruction.
1429
+ `,
1430
+ warnings: result.warnings,
1431
+ createdFiles: result.createdFiles,
1432
+ existingFiles: result.existingFiles
1433
+ };
1434
+ }
1435
+ };
1436
+
1437
+ //#endregion
1438
+ //#region src/tools/ListScaffoldingMethodsTool.ts
1439
+ var ListScaffoldingMethodsTool = class ListScaffoldingMethodsTool {
1440
+ static TOOL_NAME = "list-scaffolding-methods";
1441
+ fileSystemService;
1442
+ scaffoldingMethodsService;
1443
+ templateService;
1444
+ isMonolith;
1445
+ constructor(templatesPath, isMonolith = false) {
1446
+ this.fileSystemService = new FileSystemService();
1447
+ this.scaffoldingMethodsService = new ScaffoldingMethodsService(this.fileSystemService, templatesPath);
1448
+ this.templateService = new require_TemplateService.TemplateService();
1449
+ this.isMonolith = isMonolith;
1450
+ }
1451
+ /**
1452
+ * Get the tool definition for MCP
1453
+ */
1454
+ getDefinition() {
1455
+ const description = this.templateService.renderString(description_default$1, { isMonolith: this.isMonolith });
1456
+ const properties = {};
1457
+ if (!this.isMonolith) {
1458
+ properties.projectPath = {
1459
+ type: "string",
1460
+ description: "Absolute path to the project directory (for monorepo: containing project.json; for monolith: workspace root with toolkit.yaml). Either projectPath or templateName is required."
1461
+ };
1462
+ properties.templateName = {
1463
+ type: "string",
1464
+ description: "Name of the template to list scaffolding methods for (e.g., \"nextjs-15\", \"typescript-mcp-package\"). Either projectPath or templateName is required."
1465
+ };
1466
+ }
1467
+ return {
1468
+ name: ListScaffoldingMethodsTool.TOOL_NAME,
1469
+ description: description.trim(),
1470
+ inputSchema: {
1471
+ type: "object",
1472
+ properties,
1473
+ additionalProperties: false
1474
+ }
1475
+ };
1476
+ }
1477
+ /**
1478
+ * Execute the tool
1479
+ */
1480
+ async execute(args) {
1481
+ try {
1482
+ const { projectPath, templateName } = args;
1483
+ let result;
1484
+ if (this.isMonolith) try {
1485
+ const resolvedTemplateName = (await __agiflowai_aicode_utils.ProjectConfigResolver.resolveProjectConfig(process.cwd())).sourceTemplate;
1486
+ result = await this.scaffoldingMethodsService.listScaffoldingMethodsByTemplate(resolvedTemplateName);
1487
+ } catch (error) {
1488
+ throw new Error(`Failed to read template name from configuration: ${error instanceof Error ? error.message : String(error)}`);
1489
+ }
1490
+ else {
1491
+ if (!projectPath && !templateName) throw new Error("Either projectPath or templateName must be provided");
1492
+ if (projectPath) result = await this.scaffoldingMethodsService.listScaffoldingMethods(projectPath);
1493
+ else result = await this.scaffoldingMethodsService.listScaffoldingMethodsByTemplate(templateName);
1494
+ }
1495
+ return { content: [{
1496
+ type: "text",
1497
+ text: JSON.stringify(result, null, 2)
1498
+ }] };
1499
+ } catch (error) {
1500
+ return {
1501
+ content: [{
1502
+ type: "text",
1503
+ text: `Error listing scaffolding methods: ${error instanceof Error ? error.message : String(error)}`
1504
+ }],
1505
+ isError: true
1506
+ };
1507
+ }
1508
+ }
1509
+ };
1510
+
1511
+ //#endregion
1512
+ //#region src/instructions/tools/use-boilerplate/description.md?raw
1513
+ var description_default = "{% if isMonolith %}\nThis tool is not available for monolith projects.\n\nMonolith projects use a single template specified in `toolkit.yaml` (sourceTemplate field). The template cannot be changed through this tool - it's determined by the workspace configuration.\n\nUse `list-scaffolding-methods` and `use-scaffold-method` to add features to your monolith project instead.\n{% else %}\nCreates a new project from a boilerplate template with the specified variables.\n\n**For Monorepo Projects Only:**\nThis tool creates new sub-projects (apps, packages) in your monorepo. Each project can use a different template.\n\nThis tool will:\n- Generate all necessary files from the selected boilerplate template\n- Replace template variables with provided values\n- Create the project in targetFolder/projectName (e.g., apps/my-new-app)\n- Set up initial configuration files (package.json, tsconfig.json, etc.)\n- Create project.json with sourceTemplate reference\n\nIMPORTANT:\n- Always call `list-boilerplates` first to get the exact variable schema\n- Follow the schema exactly - required fields must be provided\n- Use kebab-case for project names (e.g., \"my-new-app\", not \"MyNewApp\")\n- The tool will validate all variables against the schema before proceeding\n- Each new project can use a different boilerplate template\n{% endif %}\n";
1514
+
1515
+ //#endregion
1516
+ //#region src/tools/UseBoilerplateTool.ts
1517
+ var UseBoilerplateTool = class UseBoilerplateTool {
1518
+ static TOOL_NAME = "use-boilerplate";
1519
+ boilerplateService;
1520
+ templateService;
1521
+ isMonolith;
1522
+ constructor(templatesPath, isMonolith = false) {
1523
+ this.boilerplateService = new BoilerplateService(templatesPath);
1524
+ this.templateService = new require_TemplateService.TemplateService();
1525
+ this.isMonolith = isMonolith;
1526
+ }
1527
+ /**
1528
+ * Get the tool definition for MCP
1529
+ */
1530
+ getDefinition() {
1531
+ const description = this.templateService.renderString(description_default, { isMonolith: this.isMonolith });
1532
+ const properties = { variables: {
1533
+ type: "object",
1534
+ description: "Variables object matching the boilerplate's variables_schema exactly"
1535
+ } };
1536
+ if (!this.isMonolith) {
1537
+ properties.boilerplateName = {
1538
+ type: "string",
1539
+ description: "Exact name of the boilerplate to use (from list-boilerplates response)"
1540
+ };
1541
+ properties.targetFolderOverride = {
1542
+ type: "string",
1543
+ description: "Optional override for target folder. If not provided, uses boilerplate targetFolder (monorepo) or workspace root (monolith)"
1544
+ };
1545
+ }
1546
+ return {
1547
+ name: UseBoilerplateTool.TOOL_NAME,
1548
+ description: description.trim(),
1549
+ inputSchema: {
1550
+ type: "object",
1551
+ properties,
1552
+ required: this.isMonolith ? ["variables"] : ["boilerplateName", "variables"],
1553
+ additionalProperties: false
1554
+ }
1555
+ };
1556
+ }
1557
+ /**
1558
+ * Execute the tool
1559
+ */
1560
+ async execute(args) {
1561
+ try {
1562
+ const { boilerplateName, variables, targetFolderOverride } = args;
1563
+ const request = {
1564
+ boilerplateName,
1565
+ variables,
1566
+ targetFolderOverride,
1567
+ monolith: this.isMonolith
1568
+ };
1569
+ return { content: [{
1570
+ type: "text",
1571
+ text: `${(await this.boilerplateService.useBoilerplate(request)).message}
1572
+
1573
+ IMPORTANT - Next Steps:
1574
+ 1. READ the generated project files to understand their structure
1575
+ 2. Review the boilerplate configuration and understand what was created
1576
+ 3. If the project requires additional features, use list-scaffolding-methods to see available options
1577
+ 4. Install dependencies (pnpm install) before testing or building
1578
+ 5. Follow the project's README for setup instructions
1579
+
1580
+ The boilerplate provides a starting point - you may need to add features or customize the generated code based on the project requirements.`
1581
+ }] };
1582
+ } catch (error) {
1583
+ return {
1584
+ content: [{
1585
+ type: "text",
1586
+ text: `Error using boilerplate: ${error instanceof Error ? error.message : String(error)}`
1587
+ }],
1588
+ isError: true
1589
+ };
1590
+ }
1591
+ }
1592
+ };
1593
+
1594
+ //#endregion
1595
+ //#region src/tools/UseScaffoldMethodTool.ts
1596
+ var UseScaffoldMethodTool = class UseScaffoldMethodTool {
1597
+ static TOOL_NAME = "use-scaffold-method";
1598
+ fileSystemService;
1599
+ scaffoldingMethodsService;
1600
+ isMonolith;
1601
+ constructor(templatesPath, isMonolith = false) {
1602
+ this.fileSystemService = new FileSystemService();
1603
+ this.scaffoldingMethodsService = new ScaffoldingMethodsService(this.fileSystemService, templatesPath);
1604
+ this.isMonolith = isMonolith;
1605
+ }
1606
+ /**
1607
+ * Get the tool definition for MCP
1608
+ */
1609
+ getDefinition() {
1610
+ const properties = {
1611
+ scaffold_feature_name: {
1612
+ type: "string",
1613
+ description: "Exact name of the scaffold method to use (from list-scaffolding-methods response)"
1614
+ },
1615
+ variables: {
1616
+ type: "object",
1617
+ description: "Variables object matching the scaffold method's variables_schema exactly"
1618
+ }
1619
+ };
1620
+ if (!this.isMonolith) properties.projectPath = {
1621
+ type: "string",
1622
+ description: "Absolute path to the project directory (for monorepo: containing project.json; for monolith: workspace root with toolkit.yaml)"
1623
+ };
1624
+ return {
1625
+ name: UseScaffoldMethodTool.TOOL_NAME,
1626
+ description: `Generates and adds a specific feature to an existing project using a scaffolding method.
1627
+
1628
+ This tool will:
1629
+ - Generate files based on the selected scaffolding method
1630
+ - Replace template variables with provided values
1631
+ - Add files to the appropriate locations in the project
1632
+ - Follow the project's existing patterns and conventions
1633
+ - Update imports and exports as needed
1634
+
1635
+ IMPORTANT:
1636
+ - Always call \`list-scaffolding-methods\` first to see available methods and their schemas
1637
+ - Use the exact scaffold method name from the list response
1638
+ - Provide variables that match the method's variables_schema exactly
1639
+ - The tool validates all inputs before generating code
1640
+ `,
1641
+ inputSchema: {
1642
+ type: "object",
1643
+ properties,
1644
+ required: this.isMonolith ? ["scaffold_feature_name", "variables"] : [
1645
+ "projectPath",
1646
+ "scaffold_feature_name",
1647
+ "variables"
1648
+ ],
1649
+ additionalProperties: false
1650
+ }
1651
+ };
1652
+ }
1653
+ /**
1654
+ * Execute the tool
1655
+ */
1656
+ async execute(args) {
1657
+ try {
1658
+ const { projectPath, scaffold_feature_name, variables } = args;
1659
+ const resolvedProjectPath = this.isMonolith ? process.cwd() : projectPath;
1660
+ return { content: [{
1661
+ type: "text",
1662
+ text: `${(await this.scaffoldingMethodsService.useScaffoldMethod({
1663
+ projectPath: resolvedProjectPath,
1664
+ scaffold_feature_name,
1665
+ variables
1666
+ })).message}
1667
+
1668
+ IMPORTANT - Next Steps:
1669
+ 1. READ the generated files to understand their structure and template placeholders
1670
+ 2. IMPLEMENT the actual business logic according to the feature's purpose (replace TODOs and template variables)
1671
+ 3. REGISTER the feature in the appropriate files (e.g., import and register tools in server/index.ts, export from index.ts)
1672
+ 4. TEST the implementation to ensure it works correctly
1673
+ 5. Only after completing the implementation should you move to other tasks
1674
+
1675
+ Do not skip the implementation step - the scaffolded files contain templates that need actual code.`
1676
+ }] };
1677
+ } catch (error) {
1678
+ return {
1679
+ content: [{
1680
+ type: "text",
1681
+ text: `Error using scaffold method: ${error instanceof Error ? error.message : String(error)}`
1682
+ }],
1683
+ isError: true
1684
+ };
1685
+ }
1686
+ }
1687
+ };
1688
+
1689
+ //#endregion
1690
+ //#region src/tools/WriteToFileTool.ts
1691
+ var WriteToFileTool = class WriteToFileTool {
1692
+ static TOOL_NAME = "write-to-file";
1693
+ fileSystemService;
1694
+ constructor() {
1695
+ this.fileSystemService = new FileSystemService();
1696
+ }
1697
+ /**
1698
+ * Get the tool definition for MCP
1699
+ */
1700
+ getDefinition() {
1701
+ return {
1702
+ name: WriteToFileTool.TOOL_NAME,
1703
+ description: `Writes content to a file, creating the file and any necessary directories if they don't exist.
1704
+
1705
+ This tool will:
1706
+ - Create the target file if it doesn't exist
1707
+ - Create any necessary parent directories
1708
+ - Write the provided content to the file
1709
+ - Overwrite existing files with new content
1710
+
1711
+ Parameters:
1712
+ - file_path: Absolute or relative path to the target file
1713
+ - content: The content to write to the file`,
1714
+ inputSchema: {
1715
+ type: "object",
1716
+ properties: {
1717
+ file_path: {
1718
+ type: "string",
1719
+ description: "Path to the file to write (absolute or relative to current working directory)"
1720
+ },
1721
+ content: {
1722
+ type: "string",
1723
+ description: "Content to write to the file"
1724
+ }
1725
+ },
1726
+ required: ["file_path", "content"],
1727
+ additionalProperties: false
1728
+ }
1729
+ };
1730
+ }
1731
+ /**
1732
+ * Execute the tool
1733
+ */
1734
+ async execute(args) {
1735
+ try {
1736
+ const { file_path, content } = args;
1737
+ if (!file_path) throw new Error("Missing required parameter: file_path");
1738
+ if (content === void 0 || content === null) throw new Error("Missing required parameter: content");
1739
+ const resolvedPath = node_path.default.isAbsolute(file_path) ? file_path : node_path.default.resolve(process.cwd(), file_path);
1740
+ const dirPath = node_path.default.dirname(resolvedPath);
1741
+ await this.fileSystemService.ensureDir(dirPath);
1742
+ await this.fileSystemService.writeFile(resolvedPath, content);
1743
+ return { content: [{
1744
+ type: "text",
1745
+ text: `Successfully wrote content to file: ${resolvedPath}`
1746
+ }] };
1747
+ } catch (error) {
1748
+ return {
1749
+ content: [{
1750
+ type: "text",
1751
+ text: `Error writing to file: ${error instanceof Error ? error.message : String(error)}`
1752
+ }],
1753
+ isError: true
1754
+ };
1755
+ }
1756
+ }
1757
+ };
1758
+
1759
+ //#endregion
1760
+ //#region src/transports/http.ts
1761
+ /**
1762
+ * HTTP session manager
1763
+ */
1764
+ var HttpFullSessionManager = class {
1765
+ sessions = /* @__PURE__ */ new Map();
1766
+ getSession(sessionId) {
1767
+ return this.sessions.get(sessionId);
1768
+ }
1769
+ setSession(sessionId, transport, server) {
1770
+ this.sessions.set(sessionId, {
1771
+ transport,
1772
+ server
1773
+ });
1774
+ }
1775
+ deleteSession(sessionId) {
1776
+ const session = this.sessions.get(sessionId);
1777
+ if (session) session.server.close();
1778
+ this.sessions.delete(sessionId);
1779
+ }
1780
+ hasSession(sessionId) {
1781
+ return this.sessions.has(sessionId);
1782
+ }
1783
+ clear() {
1784
+ for (const session of this.sessions.values()) session.server.close();
1785
+ this.sessions.clear();
1786
+ }
1787
+ };
1788
+ /**
1789
+ * HTTP transport handler using Streamable HTTP (protocol version 2025-03-26)
1790
+ * Provides stateful session management with resumability support
1791
+ */
1792
+ var HttpTransportHandler = class {
1793
+ serverFactory;
1794
+ app;
1795
+ server = null;
1796
+ sessionManager;
1797
+ config;
1798
+ constructor(serverFactory, config) {
1799
+ this.serverFactory = typeof serverFactory === "function" ? serverFactory : () => serverFactory;
1800
+ this.app = (0, express.default)();
1801
+ this.sessionManager = new HttpFullSessionManager();
1802
+ this.config = {
1803
+ mode: config.mode,
1804
+ port: config.port ?? 3e3,
1805
+ host: config.host ?? "localhost"
1806
+ };
1807
+ this.setupMiddleware();
1808
+ this.setupRoutes();
1809
+ }
1810
+ setupMiddleware() {
1811
+ this.app.use(express.default.json());
1812
+ }
1813
+ setupRoutes() {
1814
+ this.app.post("/mcp", async (req, res) => {
1815
+ await this.handlePostRequest(req, res);
1816
+ });
1817
+ this.app.get("/mcp", async (req, res) => {
1818
+ await this.handleGetRequest(req, res);
1819
+ });
1820
+ this.app.delete("/mcp", async (req, res) => {
1821
+ await this.handleDeleteRequest(req, res);
1822
+ });
1823
+ this.app.get("/health", (_req, res) => {
1824
+ res.json({
1825
+ status: "ok",
1826
+ transport: "http"
1827
+ });
1828
+ });
1829
+ }
1830
+ async handlePostRequest(req, res) {
1831
+ const sessionId = req.headers["mcp-session-id"];
1832
+ let transport;
1833
+ if (sessionId && this.sessionManager.hasSession(sessionId)) transport = this.sessionManager.getSession(sessionId).transport;
1834
+ else if (!sessionId && (0, __modelcontextprotocol_sdk_types_js.isInitializeRequest)(req.body)) {
1835
+ const mcpServer = this.serverFactory();
1836
+ transport = new __modelcontextprotocol_sdk_server_streamableHttp_js.StreamableHTTPServerTransport({
1837
+ sessionIdGenerator: () => (0, node_crypto.randomUUID)(),
1838
+ enableJsonResponse: true,
1839
+ onsessioninitialized: (sessionId$1) => {
1840
+ this.sessionManager.setSession(sessionId$1, transport, mcpServer);
1841
+ }
1842
+ });
1843
+ transport.onclose = () => {
1844
+ if (transport.sessionId) this.sessionManager.deleteSession(transport.sessionId);
1845
+ };
1846
+ await mcpServer.connect(transport);
1847
+ } else {
1848
+ res.status(400).json({
1849
+ jsonrpc: "2.0",
1850
+ error: {
1851
+ code: -32e3,
1852
+ message: "Bad Request: No valid session ID provided"
1853
+ },
1854
+ id: null
1855
+ });
1856
+ return;
1857
+ }
1858
+ await transport.handleRequest(req, res, req.body);
1859
+ }
1860
+ async handleGetRequest(req, res) {
1861
+ const sessionId = req.headers["mcp-session-id"];
1862
+ if (!sessionId || !this.sessionManager.hasSession(sessionId)) {
1863
+ res.status(400).send("Invalid or missing session ID");
1864
+ return;
1865
+ }
1866
+ await this.sessionManager.getSession(sessionId).transport.handleRequest(req, res);
1867
+ }
1868
+ async handleDeleteRequest(req, res) {
1869
+ const sessionId = req.headers["mcp-session-id"];
1870
+ if (!sessionId || !this.sessionManager.hasSession(sessionId)) {
1871
+ res.status(400).send("Invalid or missing session ID");
1872
+ return;
1873
+ }
1874
+ await this.sessionManager.getSession(sessionId).transport.handleRequest(req, res);
1875
+ this.sessionManager.deleteSession(sessionId);
1876
+ }
1877
+ async start() {
1878
+ return new Promise((resolve, reject) => {
1879
+ try {
1880
+ this.server = this.app.listen(this.config.port, this.config.host, () => {
1881
+ console.error(`Scaffolding MCP server started on http://${this.config.host}:${this.config.port}/mcp`);
1882
+ console.error(`Health check: http://${this.config.host}:${this.config.port}/health`);
1883
+ resolve();
1884
+ });
1885
+ this.server.on("error", (error) => {
1886
+ reject(error);
1887
+ });
1888
+ } catch (error) {
1889
+ reject(error);
1890
+ }
1891
+ });
1892
+ }
1893
+ async stop() {
1894
+ return new Promise((resolve, reject) => {
1895
+ if (this.server) {
1896
+ this.sessionManager.clear();
1897
+ this.server.close((err) => {
1898
+ if (err) reject(err);
1899
+ else {
1900
+ this.server = null;
1901
+ resolve();
1902
+ }
1903
+ });
1904
+ } else resolve();
1905
+ });
1906
+ }
1907
+ getPort() {
1908
+ return this.config.port;
1909
+ }
1910
+ getHost() {
1911
+ return this.config.host;
1912
+ }
1913
+ };
1914
+
1915
+ //#endregion
1916
+ //#region src/transports/sse.ts
1917
+ /**
1918
+ * Session manager for SSE transports
1919
+ */
1920
+ var SseSessionManager = class {
1921
+ sessions = /* @__PURE__ */ new Map();
1922
+ getSession(sessionId) {
1923
+ return this.sessions.get(sessionId)?.transport;
1924
+ }
1925
+ setSession(sessionId, transport, server) {
1926
+ this.sessions.set(sessionId, {
1927
+ transport,
1928
+ server
1929
+ });
1930
+ }
1931
+ deleteSession(sessionId) {
1932
+ const session = this.sessions.get(sessionId);
1933
+ if (session) session.server.close();
1934
+ this.sessions.delete(sessionId);
1935
+ }
1936
+ hasSession(sessionId) {
1937
+ return this.sessions.has(sessionId);
1938
+ }
1939
+ clear() {
1940
+ for (const session of this.sessions.values()) session.server.close();
1941
+ this.sessions.clear();
1942
+ }
1943
+ };
1944
+ /**
1945
+ * SSE (Server-Sent Events) transport handler
1946
+ * Legacy transport for backwards compatibility (protocol version 2024-11-05)
1947
+ * Uses separate endpoints: /sse for SSE stream (GET) and /messages for client messages (POST)
1948
+ */
1949
+ var SseTransportHandler = class {
1950
+ serverFactory;
1951
+ app;
1952
+ server = null;
1953
+ sessionManager;
1954
+ config;
1955
+ constructor(serverFactory, config) {
1956
+ this.serverFactory = typeof serverFactory === "function" ? serverFactory : () => serverFactory;
1957
+ this.app = (0, express.default)();
1958
+ this.sessionManager = new SseSessionManager();
1959
+ this.config = {
1960
+ mode: config.mode,
1961
+ port: config.port ?? 3e3,
1962
+ host: config.host ?? "localhost"
1963
+ };
1964
+ this.setupMiddleware();
1965
+ this.setupRoutes();
1966
+ }
1967
+ setupMiddleware() {
1968
+ this.app.use(express.default.json());
1969
+ }
1970
+ setupRoutes() {
1971
+ this.app.get("/sse", async (req, res) => {
1972
+ await this.handleSseConnection(req, res);
1973
+ });
1974
+ this.app.post("/messages", async (req, res) => {
1975
+ await this.handlePostMessage(req, res);
1976
+ });
1977
+ this.app.get("/health", (_req, res) => {
1978
+ res.json({
1979
+ status: "ok",
1980
+ transport: "sse"
1981
+ });
1982
+ });
1983
+ }
1984
+ async handleSseConnection(_req, res) {
1985
+ try {
1986
+ const mcpServer = this.serverFactory();
1987
+ const transport = new __modelcontextprotocol_sdk_server_sse_js.SSEServerTransport("/messages", res);
1988
+ this.sessionManager.setSession(transport.sessionId, transport, mcpServer);
1989
+ res.on("close", () => {
1990
+ this.sessionManager.deleteSession(transport.sessionId);
1991
+ });
1992
+ await mcpServer.connect(transport);
1993
+ console.error(`SSE session established: ${transport.sessionId}`);
1994
+ } catch (error) {
1995
+ console.error("Error handling SSE connection:", error);
1996
+ if (!res.headersSent) res.status(500).send("Internal Server Error");
1997
+ }
1998
+ }
1999
+ async handlePostMessage(req, res) {
2000
+ const sessionId = req.query.sessionId;
2001
+ if (!sessionId) {
2002
+ res.status(400).send("Missing sessionId query parameter");
2003
+ return;
2004
+ }
2005
+ const transport = this.sessionManager.getSession(sessionId);
2006
+ if (!transport) {
2007
+ res.status(404).send("No transport found for sessionId");
2008
+ return;
2009
+ }
2010
+ try {
2011
+ await transport.handlePostMessage(req, res, req.body);
2012
+ } catch (error) {
2013
+ console.error("Error handling post message:", error);
2014
+ if (!res.headersSent) res.status(500).send("Internal Server Error");
2015
+ }
2016
+ }
2017
+ async start() {
2018
+ return new Promise((resolve, reject) => {
2019
+ try {
2020
+ this.server = this.app.listen(this.config.port, this.config.host, () => {
2021
+ console.error(`Scaffolding MCP server started with SSE transport on http://${this.config.host}:${this.config.port}`);
2022
+ console.error(`SSE endpoint: http://${this.config.host}:${this.config.port}/sse`);
2023
+ console.error(`Messages endpoint: http://${this.config.host}:${this.config.port}/messages`);
2024
+ console.error(`Health check: http://${this.config.host}:${this.config.port}/health`);
2025
+ resolve();
2026
+ });
2027
+ this.server.on("error", (error) => {
2028
+ reject(error);
2029
+ });
2030
+ } catch (error) {
2031
+ reject(error);
2032
+ }
2033
+ });
2034
+ }
2035
+ async stop() {
2036
+ return new Promise((resolve, reject) => {
2037
+ if (this.server) {
2038
+ this.sessionManager.clear();
2039
+ this.server.close((err) => {
2040
+ if (err) reject(err);
2041
+ else {
2042
+ this.server = null;
2043
+ resolve();
2044
+ }
2045
+ });
2046
+ } else resolve();
2047
+ });
2048
+ }
2049
+ getPort() {
2050
+ return this.config.port;
2051
+ }
2052
+ getHost() {
2053
+ return this.config.host;
2054
+ }
2055
+ };
2056
+
2057
+ //#endregion
2058
+ //#region src/transports/stdio.ts
2059
+ /**
2060
+ * Stdio transport handler for MCP server
2061
+ * Used for command-line and direct integrations
2062
+ */
2063
+ var StdioTransportHandler = class {
2064
+ server;
2065
+ transport = null;
2066
+ constructor(server) {
2067
+ this.server = server;
2068
+ }
2069
+ async start() {
2070
+ this.transport = new __modelcontextprotocol_sdk_server_stdio_js.StdioServerTransport();
2071
+ await this.server.connect(this.transport);
2072
+ console.error("Scaffolding MCP server started on stdio");
2073
+ }
2074
+ async stop() {
2075
+ if (this.transport) {
2076
+ await this.transport.close();
2077
+ this.transport = null;
2078
+ }
2079
+ }
2080
+ };
2081
+
2082
+ //#endregion
2083
+ Object.defineProperty(exports, 'BoilerplateGeneratorService', {
2084
+ enumerable: true,
2085
+ get: function () {
2086
+ return BoilerplateGeneratorService;
2087
+ }
2088
+ });
2089
+ Object.defineProperty(exports, 'BoilerplateService', {
2090
+ enumerable: true,
2091
+ get: function () {
2092
+ return BoilerplateService;
2093
+ }
2094
+ });
2095
+ Object.defineProperty(exports, 'FileSystemService', {
2096
+ enumerable: true,
2097
+ get: function () {
2098
+ return FileSystemService;
2099
+ }
2100
+ });
2101
+ Object.defineProperty(exports, 'GenerateBoilerplateFileTool', {
2102
+ enumerable: true,
2103
+ get: function () {
2104
+ return GenerateBoilerplateFileTool;
2105
+ }
2106
+ });
2107
+ Object.defineProperty(exports, 'GenerateBoilerplateTool', {
2108
+ enumerable: true,
2109
+ get: function () {
2110
+ return GenerateBoilerplateTool;
2111
+ }
2112
+ });
2113
+ Object.defineProperty(exports, 'GenerateFeatureScaffoldTool', {
2114
+ enumerable: true,
2115
+ get: function () {
2116
+ return GenerateFeatureScaffoldTool;
2117
+ }
2118
+ });
2119
+ Object.defineProperty(exports, 'HttpTransportHandler', {
2120
+ enumerable: true,
2121
+ get: function () {
2122
+ return HttpTransportHandler;
2123
+ }
2124
+ });
2125
+ Object.defineProperty(exports, 'ListBoilerplatesTool', {
2126
+ enumerable: true,
2127
+ get: function () {
2128
+ return ListBoilerplatesTool;
2129
+ }
2130
+ });
2131
+ Object.defineProperty(exports, 'ListScaffoldingMethodsTool', {
2132
+ enumerable: true,
2133
+ get: function () {
2134
+ return ListScaffoldingMethodsTool;
2135
+ }
2136
+ });
2137
+ Object.defineProperty(exports, 'ScaffoldGeneratorService', {
2138
+ enumerable: true,
2139
+ get: function () {
2140
+ return ScaffoldGeneratorService;
2141
+ }
2142
+ });
2143
+ Object.defineProperty(exports, 'ScaffoldingMethodsService', {
2144
+ enumerable: true,
2145
+ get: function () {
2146
+ return ScaffoldingMethodsService;
2147
+ }
2148
+ });
2149
+ Object.defineProperty(exports, 'SseTransportHandler', {
2150
+ enumerable: true,
2151
+ get: function () {
2152
+ return SseTransportHandler;
2153
+ }
2154
+ });
2155
+ Object.defineProperty(exports, 'StdioTransportHandler', {
2156
+ enumerable: true,
2157
+ get: function () {
2158
+ return StdioTransportHandler;
2159
+ }
2160
+ });
2161
+ Object.defineProperty(exports, 'UseBoilerplateTool', {
2162
+ enumerable: true,
2163
+ get: function () {
2164
+ return UseBoilerplateTool;
2165
+ }
2166
+ });
2167
+ Object.defineProperty(exports, 'UseScaffoldMethodTool', {
2168
+ enumerable: true,
2169
+ get: function () {
2170
+ return UseScaffoldMethodTool;
2171
+ }
2172
+ });
2173
+ Object.defineProperty(exports, 'WriteToFileTool', {
2174
+ enumerable: true,
2175
+ get: function () {
2176
+ return WriteToFileTool;
2177
+ }
2178
+ });