-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathscapi-customapi-scaffold.ts
More file actions
241 lines (225 loc) · 9.18 KB
/
scapi-customapi-scaffold.ts
File metadata and controls
241 lines (225 loc) · 9.18 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
* Copyright (c) 2025, Salesforce, Inc.
* SPDX-License-Identifier: Apache-2
* For full license text, see the license.txt file in the repo root or http://www.apache.org/licenses/LICENSE-2.0
*/
/**
* SCAPI Custom API Scaffold tool.
*
* Generates a new custom SCAPI endpoint using the SDK's custom-api scaffold
* (schema.yaml, api.json, script.js). Mirrors CLI: b2c scaffold generate custom-api.
*
* @module tools/scapi/scapi-customapi-scaffold
*/
import path from 'node:path';
import {z} from 'zod';
import {createToolAdapter, jsonResult, errorResult} from '../adapter.js';
import type {Services} from '../../services.js';
import type {McpTool} from '../../utils/index.js';
import {
createScaffoldRegistry,
generateFromScaffold,
resolveScaffoldParameters,
resolveOutputDirectory,
} from '@salesforce/b2c-tooling-sdk/scaffold';
import {findCartridges} from '@salesforce/b2c-tooling-sdk/operations/code';
const CUSTOM_API_SCAFFOLD_ID = 'custom-api';
/**
* Input schema for scapi_customapi_scaffold tool.
* Parameters match the custom-api scaffold: apiName, apiType, cartridgeName, etc.
*/
interface ScaffoldCustomApiInput {
/** API name (kebab-case, e.g. my-products). Required. */
apiName: string;
/** Cartridge name that will contain the API. Optional; defaults to first cartridge found in project. */
cartridgeName?: string;
/** API type: admin (no siteId) or shopper (siteId, customer-facing). Default: shopper */
apiType?: 'admin' | 'shopper';
/** Short description of the API. Default: "A custom B2C Commerce API" */
apiDescription?: string;
/** Include example GET/POST endpoints in schema and script. Default: true */
includeExampleEndpoints?: boolean;
/** Project root for cartridge discovery and output. Default: MCP working directory */
projectRoot?: string;
/** Output directory override. Default: scaffold default or project root */
outputDir?: string;
/** If true, preview only (no files written). Default: false */
dryRun?: boolean;
/** If true, overwrite existing files. Default: false */
force?: boolean;
}
/**
* Output schema for scapi_customapi_scaffold tool.
*/
interface ScaffoldCustomApiOutput {
scaffold: string;
outputDir: string;
dryRun: boolean;
files: Array<{
path: string;
action: string;
skipReason?: string;
}>;
postInstructions?: string;
error?: string;
}
/**
* Creates the scapi_customapi_scaffold tool.
*
* Uses @salesforce/b2c-tooling-sdk scaffold: registry, resolveScaffoldParameters,
* resolveOutputDirectory, generateFromScaffold. cartridgeName must be a cartridge
* discovered under projectRoot (e.g. from .project or cartridges/). CLI: b2c scaffold generate custom-api.
*/
export function createScaffoldCustomApiTool(loadServices: () => Services): McpTool {
return createToolAdapter<ScaffoldCustomApiInput, ScaffoldCustomApiOutput>(
{
name: 'scapi_customapi_scaffold',
description: `Generate a new custom SCAPI endpoint (OAS 3.0 schema, api.json, script.js) in an existing cartridge. \
Uses the same scaffold as CLI: b2c scaffold generate custom-api. \
Required: apiName (kebab-case). Optional: cartridgeName (defaults to first cartridge found in project), apiType (shopper|admin), apiDescription, includeExampleEndpoints, projectRoot, outputDir, dryRun, force. \
cartridgeName must be one of the cartridges discovered under projectRoot (--working-directory or SFCC_WORKING_DIRECTORY). \
Set projectRoot to override the working directory. \
For faster runs, set --working-directory to your cartridge project root (same as where you would run the CLI from). \
CLI: b2c scaffold generate custom-api.`,
toolsets: ['PWAV3', 'SCAPI', 'STOREFRONTNEXT'],
isGA: false,
requiresInstance: false,
inputSchema: {
apiName: z
.string()
.min(1)
.describe(
'API name in kebab-case (e.g. my-products). Must start with lowercase letter, only letters, numbers, hyphens.',
),
cartridgeName: z
.string()
.min(1)
.nullish()
.describe(
'Cartridge name that will contain the API. Optional; omit to use the first cartridge found under working directory (--working-directory or SFCC_WORKING_DIRECTORY).',
),
apiType: z
.enum(['admin', 'shopper'])
.optional()
.describe('Admin (no siteId) or shopper (siteId, customer-facing). Default: shopper'),
apiDescription: z.string().optional().describe('Short description of the API.'),
includeExampleEndpoints: z.boolean().optional().describe('Include example GET/POST endpoints. Default: true'),
projectRoot: z
.string()
.nullish()
.describe(
'Project root for cartridge discovery. Default: working directory. Set to override the working directory.',
),
outputDir: z.string().optional().describe('Output directory override. Default: project root'),
dryRun: z.boolean().optional().describe('If true, preview only (no files written). Default: false'),
force: z.boolean().optional().describe('If true, overwrite existing files. Default: false'),
},
async execute(args, {services}) {
const projectRoot = path.resolve(args.projectRoot ?? services.getWorkingDirectory());
const registry = createScaffoldRegistry();
const scaffold = await registry.getScaffold(CUSTOM_API_SCAFFOLD_ID, {
projectRoot,
});
if (!scaffold) {
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir: projectRoot,
dryRun: args.dryRun ?? false,
files: [],
error: `Scaffold not found: ${CUSTOM_API_SCAFFOLD_ID}. Ensure @salesforce/b2c-tooling-sdk is installed.`,
};
}
let cartridgeName = args.cartridgeName;
// If cartridgeName is not provided, use the first cartridge found in project directory.
if (!cartridgeName) {
const cartridges = findCartridges(projectRoot);
if (cartridges.length === 0) {
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir: projectRoot,
dryRun: args.dryRun ?? false,
files: [],
error:
'No cartridges found in project. Add a cartridge (directory with .project file) or pass cartridgeName explicitly.',
};
}
cartridgeName = cartridges[0].name;
}
const providedVariables: Record<string, boolean | string> = {
apiName: args.apiName,
cartridgeName,
};
if (args.apiType !== undefined) providedVariables.apiType = args.apiType;
if (args.apiDescription !== undefined) providedVariables.apiDescription = args.apiDescription;
if (args.includeExampleEndpoints !== undefined) {
providedVariables.includeExampleEndpoints = args.includeExampleEndpoints;
}
const resolved = await resolveScaffoldParameters(scaffold, {
providedVariables,
projectRoot,
useDefaults: true,
});
if (resolved.errors.length > 0) {
const message = resolved.errors.map((e) => `${e.parameter}: ${e.message}`).join('; ');
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir: projectRoot,
dryRun: args.dryRun ?? false,
files: [],
error: `Parameter validation failed: ${message}`,
};
}
const missingRequired = resolved.missingParameters.filter((p) => p.required);
if (missingRequired.length > 0) {
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir: projectRoot,
dryRun: args.dryRun ?? false,
files: [],
error: `Missing required parameter: ${missingRequired[0].name}. For cartridgeName, ensure the cartridge exists in the project (under projectRoot).`,
};
}
const outputDir = resolveOutputDirectory({
outputDir: args.outputDir,
scaffold,
projectRoot,
});
try {
const result = await generateFromScaffold(scaffold, {
outputDir,
variables: resolved.variables as Record<string, boolean | string>,
dryRun: args.dryRun ?? false,
force: args.force ?? false,
});
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir,
dryRun: result.dryRun,
files: result.files.map((f) => ({
path: f.path,
action: f.action,
skipReason: f.skipReason,
})),
postInstructions: result.postInstructions,
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir,
dryRun: args.dryRun ?? false,
files: [],
error: `Scaffold generation failed: ${message}`,
};
}
},
formatOutput(output) {
if (output.error) {
return errorResult(output.error);
}
return jsonResult(output);
},
},
loadServices,
);
}