@easynet/agent-tool 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 (157) hide show
  1. package/README.md +103 -0
  2. package/dist/chunk-3YLVPZRJ.cjs +32 -0
  3. package/dist/chunk-3YLVPZRJ.cjs.map +1 -0
  4. package/dist/chunk-AXUNV4MK.js +28 -0
  5. package/dist/chunk-AXUNV4MK.js.map +1 -0
  6. package/dist/chunk-BM4EVYI5.js +1069 -0
  7. package/dist/chunk-BM4EVYI5.js.map +1 -0
  8. package/dist/chunk-P3UEAZHK.cjs +171 -0
  9. package/dist/chunk-P3UEAZHK.cjs.map +1 -0
  10. package/dist/chunk-RPAMQCFH.js +167 -0
  11. package/dist/chunk-RPAMQCFH.js.map +1 -0
  12. package/dist/chunk-Z7TGIG77.cjs +1108 -0
  13. package/dist/chunk-Z7TGIG77.cjs.map +1 -0
  14. package/dist/cli.cjs +154 -0
  15. package/dist/cli.cjs.map +1 -0
  16. package/dist/cli.d.ts +10 -0
  17. package/dist/cli.d.ts.map +1 -0
  18. package/dist/cli.js +147 -0
  19. package/dist/cli.js.map +1 -0
  20. package/dist/codegen/build.d.ts +23 -0
  21. package/dist/codegen/build.d.ts.map +1 -0
  22. package/dist/codegen/generator.d.ts +15 -0
  23. package/dist/codegen/generator.d.ts.map +1 -0
  24. package/dist/codegen/index.d.ts +21 -0
  25. package/dist/codegen/index.d.ts.map +1 -0
  26. package/dist/codegen/init.d.ts +17 -0
  27. package/dist/codegen/init.d.ts.map +1 -0
  28. package/dist/codegen/run.d.ts +19 -0
  29. package/dist/codegen/run.d.ts.map +1 -0
  30. package/dist/codegen/scan/scanN8n.d.ts +17 -0
  31. package/dist/codegen/scan/scanN8n.d.ts.map +1 -0
  32. package/dist/codegen/scan/scanSkill.d.ts +17 -0
  33. package/dist/codegen/scan/scanSkill.d.ts.map +1 -0
  34. package/dist/codegen/scan/scanTools.d.ts +31 -0
  35. package/dist/codegen/scan/scanTools.d.ts.map +1 -0
  36. package/dist/codegen/scan/scanner.d.ts +26 -0
  37. package/dist/codegen/scan/scanner.d.ts.map +1 -0
  38. package/dist/codegen/scan/schemaFromTs.d.ts +16 -0
  39. package/dist/codegen/scan/schemaFromTs.d.ts.map +1 -0
  40. package/dist/codegen/types.d.ts +81 -0
  41. package/dist/codegen/types.d.ts.map +1 -0
  42. package/dist/core.cjs +20 -0
  43. package/dist/core.cjs.map +1 -0
  44. package/dist/core.d.ts +8 -0
  45. package/dist/core.d.ts.map +1 -0
  46. package/dist/core.js +3 -0
  47. package/dist/core.js.map +1 -0
  48. package/dist/discovery/MCPProcessManager.d.ts +57 -0
  49. package/dist/discovery/MCPProcessManager.d.ts.map +1 -0
  50. package/dist/discovery/errors.d.ts +13 -0
  51. package/dist/discovery/errors.d.ts.map +1 -0
  52. package/dist/discovery/load/LangChainLoader.d.ts +7 -0
  53. package/dist/discovery/load/LangChainLoader.d.ts.map +1 -0
  54. package/dist/discovery/load/MCPLoader.d.ts +8 -0
  55. package/dist/discovery/load/MCPLoader.d.ts.map +1 -0
  56. package/dist/discovery/load/N8nLoader.d.ts +25 -0
  57. package/dist/discovery/load/N8nLoader.d.ts.map +1 -0
  58. package/dist/discovery/load/SkillLoader.d.ts +20 -0
  59. package/dist/discovery/load/SkillLoader.d.ts.map +1 -0
  60. package/dist/discovery/load/SkillManifest.d.ts +79 -0
  61. package/dist/discovery/load/SkillManifest.d.ts.map +1 -0
  62. package/dist/discovery/load/SkillMdParser.d.ts +31 -0
  63. package/dist/discovery/load/SkillMdParser.d.ts.map +1 -0
  64. package/dist/discovery/load/index.d.ts +6 -0
  65. package/dist/discovery/load/index.d.ts.map +1 -0
  66. package/dist/discovery/load/resolveEntry.d.ts +7 -0
  67. package/dist/discovery/load/resolveEntry.d.ts.map +1 -0
  68. package/dist/discovery/scan/DirectoryScanner.d.ts +37 -0
  69. package/dist/discovery/scan/DirectoryScanner.d.ts.map +1 -0
  70. package/dist/discovery/scan/scanUtil.d.ts +16 -0
  71. package/dist/discovery/scan/scanUtil.d.ts.map +1 -0
  72. package/dist/discovery/types.d.ts +99 -0
  73. package/dist/discovery/types.d.ts.map +1 -0
  74. package/dist/index.cjs +3014 -0
  75. package/dist/index.cjs.map +1 -0
  76. package/dist/index.d.ts +68 -0
  77. package/dist/index.d.ts.map +1 -0
  78. package/dist/index.js +2778 -0
  79. package/dist/index.js.map +1 -0
  80. package/dist/llm/AgentLLMAdapter.d.ts +27 -0
  81. package/dist/llm/AgentLLMAdapter.d.ts.map +1 -0
  82. package/dist/llm/LangChainToolsHub.d.ts +31 -0
  83. package/dist/llm/LangChainToolsHub.d.ts.map +1 -0
  84. package/dist/llm/OpenAICompatibleClient.d.ts +64 -0
  85. package/dist/llm/OpenAICompatibleClient.d.ts.map +1 -0
  86. package/dist/llm/ReActAgent.d.ts +35 -0
  87. package/dist/llm/ReActAgent.d.ts.map +1 -0
  88. package/dist/llm-export.cjs +20 -0
  89. package/dist/llm-export.cjs.map +1 -0
  90. package/dist/llm-export.d.ts +9 -0
  91. package/dist/llm-export.d.ts.map +1 -0
  92. package/dist/llm-export.js +3 -0
  93. package/dist/llm-export.js.map +1 -0
  94. package/dist/mcp/MCPClientAdapter.d.ts +34 -0
  95. package/dist/mcp/MCPClientAdapter.d.ts.map +1 -0
  96. package/dist/mcp/connectMCP.d.ts +47 -0
  97. package/dist/mcp/connectMCP.d.ts.map +1 -0
  98. package/dist/mcp/index.d.ts +10 -0
  99. package/dist/mcp/index.d.ts.map +1 -0
  100. package/dist/mcp/registerMCPTools.d.ts +24 -0
  101. package/dist/mcp/registerMCPTools.d.ts.map +1 -0
  102. package/dist/observability/EventLog.d.ts +60 -0
  103. package/dist/observability/EventLog.d.ts.map +1 -0
  104. package/dist/observability/Logger.d.ts +33 -0
  105. package/dist/observability/Logger.d.ts.map +1 -0
  106. package/dist/observability/Metrics.d.ts +70 -0
  107. package/dist/observability/Metrics.d.ts.map +1 -0
  108. package/dist/observability/Tracing.d.ts +69 -0
  109. package/dist/observability/Tracing.d.ts.map +1 -0
  110. package/dist/registry/ToolRegistry.d.ts +68 -0
  111. package/dist/registry/ToolRegistry.d.ts.map +1 -0
  112. package/dist/report/AgentReportGenerator.d.ts +53 -0
  113. package/dist/report/AgentReportGenerator.d.ts.map +1 -0
  114. package/dist/report/agent-report-template.html +362 -0
  115. package/dist/report/index.d.ts +3 -0
  116. package/dist/report/index.d.ts.map +1 -0
  117. package/dist/report/types.d.ts +101 -0
  118. package/dist/report/types.d.ts.map +1 -0
  119. package/dist/runAgent.d.ts +37 -0
  120. package/dist/runAgent.d.ts.map +1 -0
  121. package/dist/runtime/Budget.d.ts +63 -0
  122. package/dist/runtime/Budget.d.ts.map +1 -0
  123. package/dist/runtime/Evidence.d.ts +19 -0
  124. package/dist/runtime/Evidence.d.ts.map +1 -0
  125. package/dist/runtime/PTCRuntime.d.ts +115 -0
  126. package/dist/runtime/PTCRuntime.d.ts.map +1 -0
  127. package/dist/runtime/PTCRuntimeObservability.d.ts +26 -0
  128. package/dist/runtime/PTCRuntimeObservability.d.ts.map +1 -0
  129. package/dist/runtime/PTCRuntimePipeline.d.ts +62 -0
  130. package/dist/runtime/PTCRuntimePipeline.d.ts.map +1 -0
  131. package/dist/runtime/PolicyEngine.d.ts +67 -0
  132. package/dist/runtime/PolicyEngine.d.ts.map +1 -0
  133. package/dist/runtime/Retry.d.ts +33 -0
  134. package/dist/runtime/Retry.d.ts.map +1 -0
  135. package/dist/runtime/SchemaValidator.d.ts +42 -0
  136. package/dist/runtime/SchemaValidator.d.ts.map +1 -0
  137. package/dist/templates/mcp-server.js +48 -0
  138. package/dist/templates/n8n-invoker.js +11 -0
  139. package/dist/templates/skill-invoker.js +11 -0
  140. package/dist/templates/tool-index.js +9 -0
  141. package/dist/toolDescriptor.d.ts +38 -0
  142. package/dist/toolDescriptor.d.ts.map +1 -0
  143. package/dist/types/Events.d.ts +99 -0
  144. package/dist/types/Events.d.ts.map +1 -0
  145. package/dist/types/ToolIntent.d.ts +40 -0
  146. package/dist/types/ToolIntent.d.ts.map +1 -0
  147. package/dist/types/ToolResult.d.ts +30 -0
  148. package/dist/types/ToolResult.d.ts.map +1 -0
  149. package/dist/types/ToolSpec.d.ts +99 -0
  150. package/dist/types/ToolSpec.d.ts.map +1 -0
  151. package/dist/types/index.d.ts +6 -0
  152. package/dist/types/index.d.ts.map +1 -0
  153. package/extensions/examples/README.md +40 -0
  154. package/extensions/examples/scripts/agent-tool-react-stock.mjs +30 -0
  155. package/extensions/examples/tools/instruction-only/skill/SKILL.md +26 -0
  156. package/extensions/examples/tools/web-search/mcp/mcp.json +8 -0
  157. package/package.json +122 -0
@@ -0,0 +1,1069 @@
1
+ import * as fs3 from 'fs/promises';
2
+ import { readdir, readFile } from 'fs/promises';
3
+ import * as path5 from 'path';
4
+ import { join, extname, relative, basename } from 'path';
5
+ import * as fs2 from 'fs';
6
+ import * as ts2 from 'typescript';
7
+ import yaml from 'js-yaml';
8
+ import { fileURLToPath } from 'url';
9
+ import { spawn } from 'child_process';
10
+
11
+ // src/codegen/init.ts
12
+ var TEMPLATES = {
13
+ "package.json": `{
14
+ "name": "my-mcp-tools",
15
+ "version": "1.0.0",
16
+ "private": true,
17
+ "type": "module",
18
+ "scripts": {
19
+ "build": "node build.mjs",
20
+ "start": "node start.mjs"
21
+ },
22
+ "devDependencies": {
23
+ "@easynet/agent-tool": "latest"
24
+ }
25
+ }
26
+ `,
27
+ "build.mjs": `import { buildMcpPackage } from "@easynet/agent-tool";
28
+
29
+ const result = await buildMcpPackage({ outDir: "dist" });
30
+ console.log("Built", result.toolCount, "tool(s) ->", result.outDir);
31
+ `,
32
+ "start.mjs": `import { runMcpServer } from "@easynet/agent-tool";
33
+
34
+ const { process: child } = await runMcpServer({ path: "./dist" });
35
+ child.stdin?.pipe(process.stdin);
36
+ child.stdout?.pipe(process.stdout);
37
+ child.stderr?.pipe(process.stderr);
38
+ process.stdin?.ref();
39
+ child.on("close", (code) => process.exit(code ?? 0));
40
+ `,
41
+ "tsconfig.json": `{
42
+ "compilerOptions": {
43
+ "target": "ES2022",
44
+ "module": "ESNext",
45
+ "strict": true,
46
+ "skipLibCheck": true,
47
+ "noEmit": true
48
+ },
49
+ "include": ["src/**/*.ts"]
50
+ }
51
+ `,
52
+ "src/tools/example.ts": `/**
53
+ * Add two numbers.
54
+ * @tool
55
+ */
56
+ export async function add(a: number, b: number): Promise<number> {
57
+ return a + b;
58
+ }
59
+ `,
60
+ "skills/hello-skill/SKILL.md": `---
61
+ name: hello-skill
62
+ description: Say hello with a name.
63
+ ---
64
+
65
+ # Hello Skill
66
+
67
+ Returns a greeting for the given name.
68
+ `,
69
+ "skills/hello-skill/handler.js": `export default async function handler(args, ctx) {
70
+ const name = args?.name ?? "World";
71
+ return { message: \`Hello, \${name}!\` };
72
+ }
73
+ `,
74
+ "README.md": `# MCP Tool Project
75
+
76
+ Scaffolded by \`agent-tool init\`. Workflow:
77
+
78
+ 1. **init** \u2014 create project template (you are here)
79
+ 2. **npm install** \u2014 install dependencies
80
+ 3. **npm run build** \u2014 generate MCP package under \`dist/\`
81
+ 4. **npm start** \u2014 start the MCP server for testing
82
+
83
+ ## Quick start
84
+
85
+ \`\`\`bash
86
+ npm install
87
+ npm run build
88
+ npm start
89
+ \`\`\`
90
+
91
+ Edit \`src/tools/*.ts\` (add \`@tool\` JSDoc) and/or \`skills/*/SKILL.md\`, then \`npm run build\` again.
92
+ `
93
+ };
94
+ async function initProject(options = {}) {
95
+ const targetPath = path5.resolve(options.targetPath ?? process.cwd());
96
+ const filesCreated = [];
97
+ await fs3.mkdir(targetPath, { recursive: true });
98
+ for (const [relPath, content] of Object.entries(TEMPLATES)) {
99
+ const fullPath = path5.join(targetPath, relPath);
100
+ await fs3.mkdir(path5.dirname(fullPath), { recursive: true });
101
+ try {
102
+ await fs3.access(fullPath);
103
+ if (relPath === "package.json") continue;
104
+ } catch {
105
+ }
106
+ await fs3.writeFile(fullPath, content, "utf8");
107
+ filesCreated.push(relPath);
108
+ }
109
+ return { targetPath, filesCreated };
110
+ }
111
+ async function findDirsContainingFile(rootPath, fileName) {
112
+ const found = [];
113
+ await collectDirsWithFile(rootPath, fileName, found);
114
+ return found;
115
+ }
116
+ async function collectDirsWithFile(dir, fileName, found) {
117
+ let entries;
118
+ try {
119
+ const e = await readdir(dir, { withFileTypes: true });
120
+ entries = e.map((x) => ({
121
+ name: x.name,
122
+ isDirectory: x.isDirectory(),
123
+ isFile: x.isFile()
124
+ }));
125
+ } catch {
126
+ return;
127
+ }
128
+ if (entries.some((x) => x.isFile && x.name === fileName)) {
129
+ found.push(dir);
130
+ }
131
+ for (const entry of entries) {
132
+ if (!entry.isDirectory || entry.name === "node_modules" || entry.name.startsWith(".")) {
133
+ continue;
134
+ }
135
+ await collectDirsWithFile(join(dir, entry.name), fileName, found);
136
+ }
137
+ }
138
+ function pathToToolName(sourcePath, programName) {
139
+ const normalized = sourcePath.replace(/\\/g, "/").replace(/\.(ts|tsx|js|mjs|json)$/i, "");
140
+ const segments = normalized.split("/").filter(Boolean);
141
+ if (segments.length === 0) return programName;
142
+ const pathPart = segments.join(".");
143
+ return `${pathPart}.${programName}`;
144
+ }
145
+ function buildOutputSchemaFromReturnType(node, typeChecker, onWarn) {
146
+ const sig = typeChecker.getSignatureFromDeclaration(node);
147
+ if (!sig) {
148
+ onWarn?.("Could not get signature for return type, using object");
149
+ return { type: "object", additionalProperties: true };
150
+ }
151
+ let returnType = typeChecker.getReturnTypeOfSignature(sig);
152
+ if (returnType.getSymbol?.()?.getName() === "Promise") {
153
+ const typeArgs = returnType.typeArguments;
154
+ if (typeArgs?.[0]) returnType = typeArgs[0];
155
+ }
156
+ const schema = typeToJsonSchema(returnType, typeChecker, onWarn);
157
+ const hasProps = typeof schema === "object" && schema.type === "object" && Object.keys(schema.properties ?? {}).length > 0;
158
+ return hasProps ? schema : { type: "object", additionalProperties: true };
159
+ }
160
+ function buildInputSchemaFromParams(node, typeChecker, onWarn) {
161
+ const properties = {};
162
+ const required = [];
163
+ if (!node.parameters.length) {
164
+ return { schema: { type: "object", properties: {} }, required: [] };
165
+ }
166
+ for (const param of node.parameters) {
167
+ const name = param.name.getText();
168
+ if (name.startsWith("_") && name.length <= 2) continue;
169
+ const sym = param.symbol;
170
+ const paramType = sym ? typeChecker.getTypeOfSymbolAtLocation(sym, param) : typeChecker.getTypeAtLocation(param);
171
+ const isOptional = !!param.questionToken || param.initializer !== void 0;
172
+ const propSchema = typeToJsonSchema(paramType, typeChecker, onWarn);
173
+ properties[name] = propSchema;
174
+ if (!isOptional) required.push(name);
175
+ }
176
+ return {
177
+ schema: {
178
+ type: "object",
179
+ properties,
180
+ ...required.length > 0 ? { required } : {}
181
+ },
182
+ required
183
+ };
184
+ }
185
+ function typeToJsonSchema(type, typeChecker, onWarn) {
186
+ const flags = type.flags;
187
+ if (flags & ts2.TypeFlags.String) return { type: "string" };
188
+ if (flags & ts2.TypeFlags.Number) return { type: "number" };
189
+ if (flags & ts2.TypeFlags.Boolean) return { type: "boolean" };
190
+ if (flags & ts2.TypeFlags.Null) return { type: "null" };
191
+ if (flags & ts2.TypeFlags.Undefined || flags & ts2.TypeFlags.Void) return {};
192
+ if (flags & ts2.TypeFlags.Any || flags & ts2.TypeFlags.Unknown) {
193
+ onWarn?.(`Unsupported type: any/unknown, using empty schema`);
194
+ return {};
195
+ }
196
+ if (type.isUnion?.()) {
197
+ const union = type;
198
+ const types = union.types;
199
+ const withoutUndef = types.filter(
200
+ (t) => !(t.flags & ts2.TypeFlags.Undefined) && !(t.flags & ts2.TypeFlags.Void)
201
+ );
202
+ if (withoutUndef.length === 1) return typeToJsonSchema(withoutUndef[0], typeChecker, onWarn);
203
+ if (withoutUndef.length === 0) return {};
204
+ }
205
+ if (typeChecker.isArrayType(type)) {
206
+ const typeRef = type;
207
+ const typeArgs = typeRef.typeArguments;
208
+ const itemType = typeArgs?.[0];
209
+ const items = itemType ? typeToJsonSchema(itemType, typeChecker, onWarn) : {};
210
+ return { type: "array", items: Object.keys(items).length ? items : {} };
211
+ }
212
+ const str = typeChecker.typeToString(type);
213
+ if (str === "string") return { type: "string" };
214
+ if (str === "number") return { type: "number" };
215
+ if (str === "boolean") return { type: "boolean" };
216
+ if (str.endsWith("[]")) {
217
+ const inner = str.slice(0, -2).trim();
218
+ const itemType = inner === "string" ? { type: "string" } : inner === "number" ? { type: "number" } : {};
219
+ return { type: "array", items: itemType };
220
+ }
221
+ if (type.getProperties && type.getProperties().length >= 0) {
222
+ const props = type.getProperties();
223
+ const properties = {};
224
+ const required = [];
225
+ for (const p of props) {
226
+ const decl = p.valueDeclaration;
227
+ const propType = decl ? typeChecker.getTypeAtLocation(decl) : typeChecker.getTypeOfSymbolAtLocation(p, p.valueDeclaration);
228
+ const optional = decl && ts2.isPropertySignature(decl) ? !!decl.questionToken : false;
229
+ properties[p.name] = typeToJsonSchema(propType, typeChecker, onWarn);
230
+ if (!optional) required.push(p.name);
231
+ }
232
+ return { type: "object", properties, ...required.length ? { required } : {} };
233
+ }
234
+ onWarn?.(`Unsupported type: ${str}, using object`);
235
+ return { type: "object" };
236
+ }
237
+
238
+ // src/codegen/scan/scanner.ts
239
+ var TOOL_TAG = "@tool";
240
+ var EFFECT_VALUES = ["none", "local_write", "external_write", "destructive"];
241
+ function scanForTools(options) {
242
+ const projectPath = path5.resolve(options.projectPath);
243
+ const tsconfigPath = options.tsconfigPath ?? path5.join(projectPath, "tsconfig.json");
244
+ const include = options.include ?? ["**/*.ts"];
245
+ const errors = [];
246
+ const warnings = [];
247
+ let config;
248
+ let configPathResolved = path5.resolve(projectPath, tsconfigPath);
249
+ if (!fs2.existsSync(configPathResolved)) {
250
+ configPathResolved = path5.join(projectPath, "tsconfig.json");
251
+ }
252
+ if (fs2.existsSync(configPathResolved)) {
253
+ const configFile = ts2.readConfigFile(configPathResolved, ts2.sys.readFile);
254
+ if (configFile.error) {
255
+ errors.push({ file: configPathResolved, message: String(configFile.error.messageText) });
256
+ return { specs: [], errors, warnings };
257
+ }
258
+ const parsed = ts2.parseJsonConfigFileContent(
259
+ configFile.config,
260
+ ts2.sys,
261
+ path5.dirname(configPathResolved)
262
+ );
263
+ if (parsed.errors.length) {
264
+ for (const e of parsed.errors) {
265
+ errors.push({ file: e.file?.fileName ?? "tsconfig", message: String(e.messageText) });
266
+ }
267
+ return { specs: [], errors, warnings };
268
+ }
269
+ config = parsed;
270
+ } else {
271
+ config = {
272
+ options: {
273
+ target: ts2.ScriptTarget.ES2022,
274
+ module: ts2.ModuleKind.ESNext,
275
+ moduleResolution: ts2.ModuleResolutionKind.NodeNext,
276
+ strict: true,
277
+ skipLibCheck: true,
278
+ noEmit: true
279
+ },
280
+ fileNames: resolveGlob(projectPath, include),
281
+ errors: []
282
+ };
283
+ }
284
+ const program = ts2.createProgram(config.fileNames, config.options);
285
+ const typeChecker = program.getTypeChecker();
286
+ const specs = [];
287
+ for (const sourceFile of program.getSourceFiles()) {
288
+ const fileName = sourceFile.fileName;
289
+ if (fileName.includes("node_modules") || fileName.endsWith(".d.ts")) continue;
290
+ if (!config.fileNames.some((f) => path5.resolve(f) === path5.resolve(fileName))) continue;
291
+ ts2.forEachChild(sourceFile, (node) => {
292
+ const decl = getExportedFunctionDeclaration(node);
293
+ if (!decl) return;
294
+ const func = decl.func;
295
+ const name = decl.name;
296
+ if (!name) return;
297
+ const host = getJSDocHost(func);
298
+ if (!hasToolTag(host)) return;
299
+ const jsDoc = getJSDocComments(host);
300
+ const description = getDescription(jsDoc);
301
+ if (!description) {
302
+ warnings.push({ file: fileName, message: `Tool ${name}: missing description, using humanized name` });
303
+ }
304
+ const sideEffect = getEffect(host);
305
+ const onWarn = (msg) => warnings.push({ file: fileName, message: `${name}: ${msg}` });
306
+ const { schema } = buildInputSchemaFromParams(func, typeChecker, onWarn);
307
+ const inputSchema = Object.keys(schema.properties ?? {}).length > 0 ? schema : { type: "object", properties: {} };
308
+ const outputSchema = buildOutputSchemaFromReturnType(func, typeChecker, onWarn);
309
+ const sourcePath = path5.relative(projectPath, fileName) || path5.basename(fileName);
310
+ const toolName = pathToToolName(sourcePath, name);
311
+ specs.push({
312
+ kind: "function",
313
+ name: toolName,
314
+ description: description || humanize(name),
315
+ inputSchema,
316
+ outputSchema,
317
+ _meta: { hitl: { sideEffect } },
318
+ sourcePath,
319
+ exportName: name
320
+ });
321
+ });
322
+ }
323
+ return { specs, errors, warnings };
324
+ }
325
+ function resolveGlob(projectPath, patterns) {
326
+ const result = [];
327
+ const seen = /* @__PURE__ */ new Set();
328
+ const add = (f) => {
329
+ const abs = path5.resolve(f);
330
+ if (f.endsWith(".ts") && !f.endsWith(".d.ts") && !seen.has(abs)) {
331
+ seen.add(abs);
332
+ result.push(abs);
333
+ }
334
+ };
335
+ for (const p of patterns) {
336
+ const full = path5.join(projectPath, p);
337
+ if (full.includes("*")) {
338
+ const baseDir = full.replace(/\*\*\/.*$/, "").replace(/\*.*$/, "").replace(/\/?$/, "") || ".";
339
+ const dir = path5.resolve(projectPath, baseDir);
340
+ if (fs2.existsSync(dir)) walk(dir, add);
341
+ } else {
342
+ const resolved = path5.resolve(projectPath, full);
343
+ if (fs2.existsSync(resolved)) {
344
+ if (fs2.statSync(resolved).isFile()) add(resolved);
345
+ else walk(resolved, add);
346
+ }
347
+ }
348
+ }
349
+ if (result.length > 0) return result;
350
+ const srcDir = path5.join(projectPath, "src");
351
+ if (fs2.existsSync(srcDir)) return walkCollect(srcDir);
352
+ return [];
353
+ }
354
+ function walkCollect(dir) {
355
+ const out = [];
356
+ walk(dir, (fullPath) => {
357
+ if (fullPath.endsWith(".ts") && !fullPath.endsWith(".d.ts")) out.push(path5.resolve(fullPath));
358
+ });
359
+ return out;
360
+ }
361
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", "generated", "dist"]);
362
+ function walk(dir, visit) {
363
+ try {
364
+ const entries = fs2.readdirSync(dir, { withFileTypes: true });
365
+ for (const e of entries) {
366
+ const full = path5.join(dir, e.name);
367
+ if (e.isDirectory() && !SKIP_DIRS.has(e.name)) walk(full, visit);
368
+ else if (e.isFile()) visit(full);
369
+ }
370
+ } catch {
371
+ }
372
+ }
373
+ function getExportedFunctionDeclaration(node, _sourceFile) {
374
+ if (ts2.isFunctionDeclaration(node) && node.name) {
375
+ const exported = (ts2.getModifiers(node) ?? []).some((m) => m.kind === ts2.SyntaxKind.ExportKeyword);
376
+ if (exported) return { func: node, name: node.name.getText() };
377
+ return null;
378
+ }
379
+ if (ts2.isVariableStatement(node)) {
380
+ const exported = (ts2.getModifiers(node) ?? []).some((m) => m.kind === ts2.SyntaxKind.ExportKeyword);
381
+ if (!exported) return null;
382
+ for (const decl of node.declarationList.declarations) {
383
+ const init = decl.initializer;
384
+ if (init && ts2.isArrowFunction(init)) {
385
+ const name = decl.name.getText();
386
+ return { func: init, name };
387
+ }
388
+ if (init && ts2.isFunctionExpression(init)) {
389
+ const name = decl.name.getText();
390
+ return { func: init, name };
391
+ }
392
+ }
393
+ }
394
+ return null;
395
+ }
396
+ function getJSDocHost(node) {
397
+ const parent = node.parent;
398
+ if (ts2.isVariableDeclaration(parent)) {
399
+ const gp = parent.parent;
400
+ if (ts2.isVariableDeclarationList(gp) && gp.parent && ts2.isVariableStatement(gp.parent)) return gp.parent;
401
+ }
402
+ return node;
403
+ }
404
+ function getJSDocComments(host) {
405
+ const all = ts2.getJSDocCommentsAndTags(host);
406
+ return all.filter((t) => ts2.isJSDoc(t));
407
+ }
408
+ function hasToolTag(host) {
409
+ const tags = ts2.getJSDocTags(host);
410
+ for (const tag of tags) {
411
+ const name = tag.tagName?.getText() ?? "";
412
+ if (name === "tool") return true;
413
+ }
414
+ const all = ts2.getJSDocCommentsAndTags(host);
415
+ for (const t of all) {
416
+ if (ts2.isJSDoc(t)) {
417
+ const full = t.getFullText();
418
+ if (full.includes(TOOL_TAG)) return true;
419
+ }
420
+ }
421
+ return false;
422
+ }
423
+ function getDescription(jsDocs, fallbackName) {
424
+ for (const doc of jsDocs) {
425
+ const comment = doc.comment;
426
+ if (typeof comment === "string") {
427
+ const first = comment.split(/\n/)[0]?.trim() ?? "";
428
+ if (first && !first.startsWith("@")) return first;
429
+ }
430
+ if (Array.isArray(comment)) {
431
+ const first = comment[0];
432
+ if (first && typeof first === "object" && "text" in first) {
433
+ const t = first.text.trim();
434
+ if (t && !t.startsWith("@")) return t;
435
+ }
436
+ }
437
+ const full = doc.getFullText();
438
+ const match = full.match(/\*\s*@tool\s+(.+?)(?=\n|$|\*\/)/s);
439
+ if (match?.[1]) return match[1].trim();
440
+ }
441
+ return "";
442
+ }
443
+ function getEffect(host) {
444
+ const tags = ts2.getJSDocTags(host);
445
+ for (const tag of tags) {
446
+ const name = tag.tagName?.getText() ?? "";
447
+ if (name === "effect") {
448
+ const comment = tag.comment;
449
+ const v = (typeof comment === "string" ? comment : "").trim().toLowerCase();
450
+ if (EFFECT_VALUES.includes(v)) return v;
451
+ }
452
+ }
453
+ const all = ts2.getJSDocCommentsAndTags(host);
454
+ for (const t of all) {
455
+ if (ts2.isJSDoc(t)) {
456
+ const full = t.getFullText();
457
+ const match = full.match(/\*\s*@effect\s+(\w+)/);
458
+ if (match && EFFECT_VALUES.includes(match[1])) return match[1];
459
+ }
460
+ }
461
+ return "none";
462
+ }
463
+ function humanize(name) {
464
+ return name.replace(/([A-Z])/g, " $1").replace(/^./, (s) => s.toUpperCase()).trim();
465
+ }
466
+
467
+ // src/discovery/load/SkillManifest.ts
468
+ var SkillManifestError = class extends Error {
469
+ constructor(path8, field, message) {
470
+ super(`SKILL.md error in ${path8}: ${message}`);
471
+ this.path = path8;
472
+ this.field = field;
473
+ this.name = "SkillManifestError";
474
+ }
475
+ };
476
+ var NAME_PATTERN = /^[a-z0-9-]+$/;
477
+ var NAME_MAX_LENGTH = 64;
478
+ var DESCRIPTION_MAX_LENGTH = 1024;
479
+ var COMPATIBILITY_MAX_LENGTH = 500;
480
+ var RESERVED_WORDS = ["anthropic", "claude"];
481
+ var XML_TAG_PATTERN = /<\/?[a-zA-Z][^>]*>/;
482
+ function validateFrontmatter(fm, filePath) {
483
+ if (!fm.name || typeof fm.name !== "string") {
484
+ throw new SkillManifestError(filePath, "name", "name is required");
485
+ }
486
+ if (fm.name.length > NAME_MAX_LENGTH) {
487
+ throw new SkillManifestError(
488
+ filePath,
489
+ "name",
490
+ `name must be at most ${NAME_MAX_LENGTH} characters (got ${fm.name.length})`
491
+ );
492
+ }
493
+ if (!NAME_PATTERN.test(fm.name)) {
494
+ throw new SkillManifestError(
495
+ filePath,
496
+ "name",
497
+ "name must contain only lowercase letters, numbers, and hyphens"
498
+ );
499
+ }
500
+ if (fm.name.startsWith("-") || fm.name.endsWith("-")) {
501
+ throw new SkillManifestError(
502
+ filePath,
503
+ "name",
504
+ "name must not start or end with a hyphen"
505
+ );
506
+ }
507
+ if (fm.name.includes("--")) {
508
+ throw new SkillManifestError(
509
+ filePath,
510
+ "name",
511
+ "name must not contain consecutive hyphens"
512
+ );
513
+ }
514
+ if (XML_TAG_PATTERN.test(fm.name)) {
515
+ throw new SkillManifestError(filePath, "name", "name cannot contain XML tags");
516
+ }
517
+ for (const reserved of RESERVED_WORDS) {
518
+ if (fm.name.includes(reserved)) {
519
+ throw new SkillManifestError(
520
+ filePath,
521
+ "name",
522
+ `name cannot contain reserved word "${reserved}"`
523
+ );
524
+ }
525
+ }
526
+ if (!fm.description || typeof fm.description !== "string") {
527
+ throw new SkillManifestError(
528
+ filePath,
529
+ "description",
530
+ "description is required and must be non-empty"
531
+ );
532
+ }
533
+ if (fm.description.length > DESCRIPTION_MAX_LENGTH) {
534
+ throw new SkillManifestError(
535
+ filePath,
536
+ "description",
537
+ `description must be at most ${DESCRIPTION_MAX_LENGTH} characters (got ${fm.description.length})`
538
+ );
539
+ }
540
+ if (XML_TAG_PATTERN.test(fm.description)) {
541
+ throw new SkillManifestError(
542
+ filePath,
543
+ "description",
544
+ "description cannot contain XML tags"
545
+ );
546
+ }
547
+ if (fm.compatibility != null && typeof fm.compatibility === "string") {
548
+ if (fm.compatibility.length > COMPATIBILITY_MAX_LENGTH) {
549
+ throw new SkillManifestError(
550
+ filePath,
551
+ "compatibility",
552
+ `compatibility must be at most ${COMPATIBILITY_MAX_LENGTH} characters (got ${fm.compatibility.length})`
553
+ );
554
+ }
555
+ }
556
+ }
557
+ var CODE_EXTENSIONS = /* @__PURE__ */ new Set([
558
+ ".py",
559
+ ".js",
560
+ ".mjs",
561
+ ".ts",
562
+ ".sh",
563
+ ".bash",
564
+ ".rb",
565
+ ".go"
566
+ ]);
567
+ var INSTRUCTION_EXTENSIONS = /* @__PURE__ */ new Set([".md", ".markdown", ".txt"]);
568
+ var EXCLUDED_FILES = /* @__PURE__ */ new Set(["SKILL.md", "tool.json"]);
569
+ function parseSkillMd(content, filePath) {
570
+ const trimmed = content.trimStart();
571
+ if (!trimmed.startsWith("---")) {
572
+ throw new SkillManifestError(
573
+ filePath,
574
+ "frontmatter",
575
+ "SKILL.md must start with YAML frontmatter (---)"
576
+ );
577
+ }
578
+ const endIndex = trimmed.indexOf("\n---", 3);
579
+ if (endIndex === -1) {
580
+ throw new SkillManifestError(
581
+ filePath,
582
+ "frontmatter",
583
+ "SKILL.md frontmatter is not closed (missing closing ---)"
584
+ );
585
+ }
586
+ const yamlBlock = trimmed.slice(4, endIndex).trim();
587
+ const body = trimmed.slice(endIndex + 4).trim();
588
+ let raw;
589
+ try {
590
+ const parsed = yaml.load(yamlBlock);
591
+ if (parsed == null || typeof parsed !== "object" || Array.isArray(parsed)) {
592
+ throw new SkillManifestError(
593
+ filePath,
594
+ "frontmatter",
595
+ "YAML frontmatter must be an object (key: value)"
596
+ );
597
+ }
598
+ raw = parsed;
599
+ } catch (err) {
600
+ const message = err instanceof Error ? err.message : String(err);
601
+ throw new SkillManifestError(
602
+ filePath,
603
+ "frontmatter",
604
+ `Invalid YAML frontmatter: ${message}`
605
+ );
606
+ }
607
+ const name = stringField(raw, "name", filePath);
608
+ const description = stringField(raw, "description", filePath);
609
+ if (!name || !description) {
610
+ throw new SkillManifestError(
611
+ filePath,
612
+ "frontmatter",
613
+ !name ? "name is required" : "description is required"
614
+ );
615
+ }
616
+ const license = stringField(raw, "license");
617
+ const compatibility = stringField(raw, "compatibility");
618
+ const allowedTools = stringField(raw, "allowed-tools");
619
+ const metadata = normalizeMetadata(raw.metadata);
620
+ const frontmatter = {
621
+ name,
622
+ description,
623
+ ...license && { license },
624
+ ...compatibility && { compatibility },
625
+ ...allowedTools && { allowedTools },
626
+ ...metadata && Object.keys(metadata).length > 0 && { metadata }
627
+ };
628
+ validateFrontmatter(frontmatter, filePath);
629
+ return { frontmatter, instructions: body };
630
+ }
631
+ function stringField(raw, key, filePath) {
632
+ const v = raw[key];
633
+ if (v == null) return "";
634
+ if (typeof v === "string") return v;
635
+ if (typeof v === "number" || typeof v === "boolean") return String(v);
636
+ if (Array.isArray(v)) {
637
+ return v.map((x) => typeof x === "string" ? x : String(x)).join("\n");
638
+ }
639
+ if (filePath) {
640
+ throw new SkillManifestError(
641
+ filePath,
642
+ "frontmatter",
643
+ `Frontmatter field "${key}" must be a string, number, boolean, or array`
644
+ );
645
+ }
646
+ return String(v);
647
+ }
648
+ function normalizeMetadata(val) {
649
+ if (val == null) return void 0;
650
+ if (typeof val === "object" && !Array.isArray(val)) {
651
+ const out = {};
652
+ for (const [k, v] of Object.entries(val)) {
653
+ if (typeof k === "string" && v !== void 0 && v !== null) {
654
+ out[k] = typeof v === "object" ? JSON.stringify(v) : String(v);
655
+ }
656
+ }
657
+ return Object.keys(out).length ? out : void 0;
658
+ }
659
+ if (typeof val === "string" || typeof val === "number" || typeof val === "boolean") {
660
+ return { value: String(val) };
661
+ }
662
+ return void 0;
663
+ }
664
+ async function scanSkillResources(dirPath) {
665
+ const resources = [];
666
+ await scanDir(dirPath, dirPath, resources);
667
+ return resources;
668
+ }
669
+ async function scanDir(basePath, currentPath, resources) {
670
+ let entries;
671
+ try {
672
+ entries = await readdir(currentPath, { withFileTypes: true });
673
+ } catch {
674
+ return;
675
+ }
676
+ for (const entry of entries) {
677
+ const fullPath = join(currentPath, entry.name);
678
+ if (entry.isDirectory()) {
679
+ if (entry.name.startsWith(".") || entry.name === "node_modules") {
680
+ continue;
681
+ }
682
+ await scanDir(basePath, fullPath, resources);
683
+ } else if (entry.isFile()) {
684
+ if (EXCLUDED_FILES.has(entry.name)) {
685
+ continue;
686
+ }
687
+ const ext = extname(entry.name).toLowerCase();
688
+ const relPath = relative(basePath, fullPath);
689
+ resources.push({
690
+ relativePath: relPath,
691
+ absolutePath: fullPath,
692
+ extension: ext,
693
+ type: inferResourceType(ext)
694
+ });
695
+ }
696
+ }
697
+ }
698
+ function inferResourceType(ext) {
699
+ if (CODE_EXTENSIONS.has(ext)) return "code";
700
+ if (INSTRUCTION_EXTENSIONS.has(ext)) return "instructions";
701
+ return "data";
702
+ }
703
+ async function loadSkillDefinition(dirPath) {
704
+ const skillMdPath = join(dirPath, "SKILL.md");
705
+ let content;
706
+ try {
707
+ content = await readFile(skillMdPath, "utf-8");
708
+ } catch (err) {
709
+ throw new SkillManifestError(
710
+ skillMdPath,
711
+ "file",
712
+ `Cannot read SKILL.md: ${err.message}`
713
+ );
714
+ }
715
+ const { frontmatter, instructions } = parseSkillMd(content, skillMdPath);
716
+ const resources = await scanSkillResources(dirPath);
717
+ return {
718
+ frontmatter,
719
+ instructions,
720
+ resources,
721
+ dirPath,
722
+ skillMdPath
723
+ };
724
+ }
725
+
726
+ // src/discovery/errors.ts
727
+ var DiscoveryError = class extends Error {
728
+ /** Absolute path to the tool directory that caused the error */
729
+ toolDir;
730
+ /** Phase in which the error occurred */
731
+ phase;
732
+ /** The underlying cause */
733
+ cause;
734
+ constructor(toolDir, phase, message, cause) {
735
+ super(`[${phase}] ${toolDir}: ${message}`);
736
+ this.name = "DiscoveryError";
737
+ this.toolDir = toolDir;
738
+ this.phase = phase;
739
+ this.cause = cause;
740
+ }
741
+ };
742
+ var defaultInputSchema = { type: "object", properties: {}, additionalProperties: true };
743
+ async function scanForSkill(projectPath) {
744
+ const projectRoot = path5.resolve(projectPath);
745
+ const dirs = await findDirsContainingFile(projectRoot, "SKILL.md");
746
+ const skills = [];
747
+ const errors = [];
748
+ for (const dirPath of dirs) {
749
+ const relativePath = path5.relative(projectRoot, dirPath) || path5.basename(dirPath);
750
+ try {
751
+ const skillDef = await loadSkillDefinition(dirPath);
752
+ const name = pathToToolName(relativePath, skillDef.frontmatter.name);
753
+ skills.push({
754
+ kind: "skill",
755
+ name,
756
+ description: skillDef.frontmatter.description,
757
+ inputSchema: defaultInputSchema,
758
+ _meta: { hitl: { sideEffect: "none" } },
759
+ sourcePath: relativePath.replace(/\\/g, "/")
760
+ });
761
+ } catch (err) {
762
+ errors.push({ dir: relativePath, message: err instanceof Error ? err.message : String(err) });
763
+ }
764
+ }
765
+ return { skills, errors };
766
+ }
767
+ async function readWorkflowMeta(dirPath, workflowFileName = "workflow.json") {
768
+ const workflowPath = join(dirPath, workflowFileName);
769
+ let raw;
770
+ try {
771
+ raw = await readFile(workflowPath, "utf-8");
772
+ } catch (err) {
773
+ throw new DiscoveryError(
774
+ dirPath,
775
+ "load",
776
+ `Failed to read workflow: ${workflowPath}`,
777
+ err
778
+ );
779
+ }
780
+ let workflowDef;
781
+ try {
782
+ workflowDef = JSON.parse(raw);
783
+ } catch (err) {
784
+ throw new DiscoveryError(
785
+ dirPath,
786
+ "load",
787
+ `Invalid JSON in ${workflowPath}`,
788
+ err
789
+ );
790
+ }
791
+ if (!workflowDef.nodes || !Array.isArray(workflowDef.nodes)) {
792
+ throw new DiscoveryError(
793
+ dirPath,
794
+ "validate",
795
+ `workflow.json must have a "nodes" array`
796
+ );
797
+ }
798
+ const meta = workflowDef.meta;
799
+ const name = workflowDef.name || meta?.name || basename(dirPath);
800
+ const description = workflowDef.description || meta?.description || `n8n workflow: ${name}`;
801
+ let webhookUrl;
802
+ const nodes = workflowDef.nodes;
803
+ if (Array.isArray(nodes)) {
804
+ const webhookNode = nodes.find(
805
+ (n) => n.type === "n8n-nodes-base.webhook" || n.type?.includes("webhook")
806
+ );
807
+ if (webhookNode?.parameters && typeof webhookNode.parameters === "object") {
808
+ const params = webhookNode.parameters;
809
+ const pathVal = params.path ?? params.webhookPath;
810
+ if (typeof pathVal === "string" && pathVal.startsWith("http")) {
811
+ webhookUrl = pathVal;
812
+ }
813
+ }
814
+ }
815
+ return { name, description, webhookUrl, workflowDef };
816
+ }
817
+ async function loadN8nTool(dirPath, manifest) {
818
+ const { workflowDef } = await readWorkflowMeta(
819
+ dirPath,
820
+ manifest.entryPoint ?? "workflow.json"
821
+ );
822
+ return { manifest, dirPath, workflowDef };
823
+ }
824
+
825
+ // src/codegen/scan/scanN8n.ts
826
+ var defaultInputSchema2 = { type: "object", properties: {}, additionalProperties: true };
827
+ async function scanForN8n(projectPath) {
828
+ const projectRoot = path5.resolve(projectPath);
829
+ const dirs = await findDirsContainingFile(projectRoot, "workflow.json");
830
+ const n8n = [];
831
+ const errors = [];
832
+ for (const dirPath of dirs) {
833
+ const relativePath = path5.relative(projectRoot, dirPath) || path5.basename(dirPath);
834
+ try {
835
+ const { name: wfName, description: wfDesc, webhookUrl } = await readWorkflowMeta(dirPath);
836
+ const toolName = pathToToolName(relativePath, wfName);
837
+ n8n.push({
838
+ kind: "n8n",
839
+ name: toolName,
840
+ description: wfDesc,
841
+ inputSchema: defaultInputSchema2,
842
+ _meta: { hitl: { sideEffect: "external_write" } },
843
+ sourcePath: relativePath.replace(/\\/g, "/"),
844
+ webhookUrl
845
+ });
846
+ } catch (err) {
847
+ errors.push({ dir: relativePath, message: err instanceof Error ? err.message : String(err) });
848
+ }
849
+ }
850
+ return { n8n, errors };
851
+ }
852
+
853
+ // src/codegen/scan/scanTools.ts
854
+ async function scanForAllTools(projectPath, options = {}) {
855
+ const include = options.include ?? ["**/*.ts"];
856
+ const tsconfigPath = options.tsconfigPath;
857
+ const includeN8n = options.includeN8n === true;
858
+ const [functionResult, skillResult, n8nResult] = await Promise.all([
859
+ Promise.resolve(scanForTools({ projectPath, include, tsconfigPath })),
860
+ scanForSkill(projectPath),
861
+ includeN8n ? scanForN8n(projectPath) : Promise.resolve({ n8n: [], errors: [] })
862
+ ]);
863
+ const specs = [
864
+ ...functionResult.specs,
865
+ ...skillResult.skills,
866
+ ...n8nResult.n8n
867
+ ];
868
+ const errors = [
869
+ ...functionResult.errors,
870
+ ...skillResult.errors.map((e) => ({ file: e.dir, message: e.message })),
871
+ ...includeN8n ? n8nResult.errors.map((e) => ({ file: e.dir, message: e.message })) : []
872
+ ];
873
+ const warnings = [...functionResult.warnings];
874
+ return { specs, errors, warnings };
875
+ }
876
+ var __dirname$1 = path5.dirname(fileURLToPath(import.meta.url));
877
+ async function loadTemplate(name) {
878
+ for (const dir of [
879
+ path5.join(__dirname$1, "templates"),
880
+ path5.join(__dirname$1, "..", "templates")
881
+ ]) {
882
+ try {
883
+ return await fs3.readFile(path5.join(dir, name), "utf-8");
884
+ } catch {
885
+ continue;
886
+ }
887
+ }
888
+ throw new Error(`Template not found: ${name}. Tried templates/ next to generator and ../templates.`);
889
+ }
890
+ var TEMPLATE_NAMES = {
891
+ mcpServer: "mcp-server.js",
892
+ toolIndex: "tool-index.js",
893
+ skillInvoker: "skill-invoker.js",
894
+ n8nInvoker: "n8n-invoker.js"
895
+ };
896
+ function buildToolIndexCases(specs, fromGeneratedToProject) {
897
+ return specs.map((s) => {
898
+ const modPath = path5.join(fromGeneratedToProject, s.sourcePath).replace(/\\/g, "/");
899
+ return ` case "${s.name}": return (await import("${modPath}")).${s.exportName};`;
900
+ }).join("\n");
901
+ }
902
+ function buildSkillInvokerCases(specs, fromGeneratedToProject) {
903
+ return specs.map((s) => {
904
+ const handlerPath = path5.join(fromGeneratedToProject, s.sourcePath, "handler").replace(/\\/g, "/");
905
+ const descEscaped = s.description.replace(/"/g, '\\"');
906
+ return ` case "${s.name}": {
907
+ const mod = await import("${handlerPath}.js").catch(() => import("${handlerPath}.mjs"));
908
+ const fn = mod.default ?? mod.handler;
909
+ if (typeof fn !== "function") return { result: null, error: "No handler" };
910
+ const ctx = { requestId: "mcp", taskId: "mcp", skill: { name: "${s.name}", description: "${descEscaped}", instructions: "", resources: [], readResource: async () => "", getResourcesByType: () => [], dirPath: "" } };
911
+ const out = await fn(args, ctx);
912
+ return out?.result !== undefined ? out.result : out;
913
+ }`;
914
+ }).join("\n");
915
+ }
916
+ function buildN8nInvokerCases(specs) {
917
+ return specs.map((s) => {
918
+ const url = s.webhookUrl ? `"${s.webhookUrl}"` : "process.env.N8N_WEBHOOK_" + s.name.replace(/[^a-zA-Z0-9]/g, "_").toUpperCase() + " ?? null";
919
+ return ` case "${s.name}": {
920
+ const url = ${url};
921
+ if (!url) throw new Error("n8n webhook not configured for ${s.name}. Set N8N_WEBHOOK_* or add webhook to workflow.");
922
+ const res = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(args) });
923
+ if (!res.ok) throw new Error("n8n request failed: " + res.status);
924
+ return res.json().catch(() => ({}));
925
+ }`;
926
+ }).join("\n");
927
+ }
928
+ async function generate(options) {
929
+ const { specs, outDir, projectPath } = options;
930
+ await fs3.mkdir(outDir, { recursive: true });
931
+ const functionSpecs = specs.filter((s) => s.kind === "function");
932
+ const skillSpecs = specs.filter((s) => s.kind === "skill");
933
+ const n8nSpecs = specs.filter((s) => s.kind === "n8n");
934
+ const toolSpecsJson = specs.map((s) => ({
935
+ kind: s.kind,
936
+ name: s.name,
937
+ description: s.description,
938
+ inputSchema: s.inputSchema,
939
+ ...s.kind === "function" && {
940
+ outputSchema: s.outputSchema ?? { type: "object", additionalProperties: true },
941
+ sourcePath: s.sourcePath,
942
+ exportName: s.exportName
943
+ },
944
+ _meta: s._meta,
945
+ ...s.kind === "skill" && { sourcePath: s.sourcePath },
946
+ ...s.kind === "n8n" && { sourcePath: s.sourcePath, webhookUrl: s.webhookUrl }
947
+ }));
948
+ await fs3.writeFile(
949
+ path5.join(outDir, "tool-specs.json"),
950
+ JSON.stringify(toolSpecsJson, null, 2),
951
+ "utf-8"
952
+ );
953
+ const configJson = { projectPath: path5.resolve(projectPath) };
954
+ await fs3.writeFile(path5.join(outDir, "config.json"), JSON.stringify(configJson, null, 2), "utf-8");
955
+ const rel = path5.relative(outDir, projectPath) || ".";
956
+ const fromGeneratedToProject = rel.split(path5.sep).length ? rel : ".";
957
+ const [mcpServerTemplate, toolIndexTemplate, skillInvokerTemplate, n8nInvokerTemplate] = await Promise.all([
958
+ loadTemplate(TEMPLATE_NAMES.mcpServer),
959
+ loadTemplate(TEMPLATE_NAMES.toolIndex),
960
+ loadTemplate(TEMPLATE_NAMES.skillInvoker),
961
+ loadTemplate(TEMPLATE_NAMES.n8nInvoker)
962
+ ]);
963
+ const toolIndexTs = toolIndexTemplate.replace("{{CASES}}", buildToolIndexCases(functionSpecs, fromGeneratedToProject));
964
+ await fs3.writeFile(path5.join(outDir, "tool-index.ts"), toolIndexTs, "utf-8");
965
+ const skillCases = buildSkillInvokerCases(skillSpecs, fromGeneratedToProject);
966
+ const skillDefaultCase = skillSpecs.length === 0 ? "default: throw new Error('Unknown skill: ' + name);" : 'default: throw new Error("Unknown skill: " + name);';
967
+ const skillInvokerTs = skillInvokerTemplate.replace("{{CASES}}", skillCases).replace("{{DEFAULT_CASE}}", skillDefaultCase);
968
+ await fs3.writeFile(path5.join(outDir, "skill-invoker.ts"), skillInvokerTs, "utf-8");
969
+ const n8nCases = buildN8nInvokerCases(n8nSpecs);
970
+ const n8nDefaultCase = n8nSpecs.length === 0 ? "default: throw new Error('Unknown n8n tool: ' + name);" : 'default: throw new Error("Unknown n8n tool: " + name);';
971
+ const n8nInvokerTs = n8nInvokerTemplate.replace("{{CASES}}", n8nCases).replace("{{DEFAULT_CASE}}", n8nDefaultCase);
972
+ await fs3.writeFile(path5.join(outDir, "n8n-invoker.ts"), n8nInvokerTs, "utf-8");
973
+ await fs3.writeFile(path5.join(outDir, "mcp-server.ts"), mcpServerTemplate, "utf-8");
974
+ const mcpJson = {
975
+ command: "npx",
976
+ args: ["-y", "tsx", path5.join(outDir, "mcp-server.ts")]
977
+ };
978
+ await fs3.writeFile(path5.join(outDir, "mcp.json"), JSON.stringify(mcpJson, null, 2), "utf-8");
979
+ const packageJson = {
980
+ name: "function-tools-mcp",
981
+ version: "1.0.0",
982
+ type: "module",
983
+ description: "MCP server generated from @tool functions, SKILL.md, and workflow.json",
984
+ main: "mcp-server.ts",
985
+ scripts: { start: "npx tsx mcp-server.ts" },
986
+ dependencies: {
987
+ "@modelcontextprotocol/sdk": "^1.25.3",
988
+ typescript: ">=5.0.0",
989
+ tsx: ">=4.0.0"
990
+ }
991
+ };
992
+ await fs3.writeFile(path5.join(outDir, "package.json"), JSON.stringify(packageJson, null, 2), "utf-8");
993
+ return {
994
+ entryPath: path5.join(outDir, "mcp-server.ts"),
995
+ mcpJsonPath: path5.join(outDir, "mcp.json")
996
+ };
997
+ }
998
+
999
+ // src/codegen/build.ts
1000
+ async function buildMcpPackage(options = {}) {
1001
+ const projectPath = path5.resolve(options.projectPath ?? process.cwd());
1002
+ const outDir = path5.resolve(projectPath, options.outDir ?? "dist");
1003
+ const include = options.include ?? ["**/*.ts"];
1004
+ const tsconfigPath = options.tsconfigPath;
1005
+ const scanResult = await scanForAllTools(projectPath, {
1006
+ include,
1007
+ tsconfigPath,
1008
+ includeN8n: options.includeN8n
1009
+ });
1010
+ if (scanResult.errors.length > 0) {
1011
+ const msg = scanResult.errors.map((e) => `${e.file}: ${e.message}`).join("; ");
1012
+ throw new Error(`Scan failed: ${msg}`);
1013
+ }
1014
+ const allSpecs = scanResult.specs;
1015
+ if (allSpecs.length === 0) {
1016
+ throw new Error(
1017
+ "No tools found. Add @tool functions (JSDoc), SKILL.md directories, or workflow.json directories."
1018
+ );
1019
+ }
1020
+ const { entryPath, mcpJsonPath } = await generate({
1021
+ specs: allSpecs,
1022
+ outDir,
1023
+ projectPath
1024
+ });
1025
+ return {
1026
+ outDir,
1027
+ toolCount: allSpecs.length,
1028
+ entryPath,
1029
+ mcpJsonPath
1030
+ };
1031
+ }
1032
+ var buildFunctionToTool = buildMcpPackage;
1033
+ async function runMcpServer(options = {}) {
1034
+ const base = options.path ?? process.cwd();
1035
+ const candidates = [
1036
+ path5.join(base, "mcp-server.ts"),
1037
+ path5.join(base, "mcp-server.js"),
1038
+ path5.join(base, "dist", "mcp-server.ts"),
1039
+ path5.join(base, "dist", "mcp-server.js"),
1040
+ path5.join(base, "generated", "mcp-server.ts"),
1041
+ path5.join(base, "generated", "mcp-server.js")
1042
+ ];
1043
+ let entry = "";
1044
+ for (const p of candidates) {
1045
+ try {
1046
+ await fs3.access(p);
1047
+ entry = p;
1048
+ break;
1049
+ } catch {
1050
+ }
1051
+ }
1052
+ if (!entry) {
1053
+ throw new Error(
1054
+ `MCP entrypoint not found. Run "agent-tool build" first, or pass --path to a directory containing mcp-server.ts. Tried: ${candidates.join(", ")}`
1055
+ );
1056
+ }
1057
+ const dir = path5.dirname(entry);
1058
+ const child = spawn("npx", ["-y", "tsx", path5.basename(entry)], {
1059
+ cwd: dir,
1060
+ stdio: ["pipe", "pipe", "inherit"],
1061
+ shell: false
1062
+ });
1063
+ return { process: child };
1064
+ }
1065
+ var runGeneratedMCP = runMcpServer;
1066
+
1067
+ export { DiscoveryError, SkillManifestError, buildFunctionToTool, buildMcpPackage, initProject, loadN8nTool, loadSkillDefinition, parseSkillMd, runGeneratedMCP, runMcpServer, scanForTools, scanSkillResources, validateFrontmatter };
1068
+ //# sourceMappingURL=chunk-BM4EVYI5.js.map
1069
+ //# sourceMappingURL=chunk-BM4EVYI5.js.map