@agiflowai/scaffold-mcp 0.5.0 → 1.0.0

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