-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathscapi-custom-api-generate-scaffold.ts
More file actions
254 lines (235 loc) · 8.63 KB
/
scapi-custom-api-generate-scaffold.ts
File metadata and controls
254 lines (235 loc) · 8.63 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
242
243
244
245
246
247
248
249
250
251
252
253
254
/*
* 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 Generate Scaffold tool.
*
* Generates a new custom SCAPI endpoint using the SDK's custom-api scaffold
* (schema.yaml, api.json, script.js).
*
* @module tools/scapi/scapi-custom-api-generate-scaffold
*/
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 type {Scaffold, ResolvedParameters, ResolveParametersOptions} from '@salesforce/b2c-tooling-sdk/scaffold';
import {findCartridges} from '@salesforce/b2c-tooling-sdk/operations/code';
const CUSTOM_API_SCAFFOLD_ID = 'custom-api';
/** Optional overrides for testing (scaffold not found, missing required). */
export interface ScaffoldCustomApiExecuteOverrides {
getScaffold?: (id: string, opts: {projectRoot: string}) => Promise<null | Scaffold>;
resolveScaffoldParameters?: (scaffold: Scaffold, opts: ResolveParametersOptions) => Promise<ResolvedParameters>;
}
/**
* Input schema for scapi_custom_api_generate_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;
/** Project root for cartridge discovery and output. Default: MCP project directory */
projectRoot?: string;
/** Output directory override. Default: scaffold default or project root */
outputDir?: string;
}
/**
* Output schema for scapi_custom_api_generate_scaffold tool.
*/
interface ScaffoldCustomApiOutput {
scaffold: string;
outputDir: string;
dryRun: boolean;
files: Array<{
path: string;
action: string;
skipReason?: string;
}>;
postInstructions?: string;
error?: string;
}
/**
* Core execute logic for the custom API scaffold tool.
* Exported for tests so we can inject getScaffold / resolveScaffoldParameters and cover error branches.
*/
export async function executeScaffoldCustomApi(
args: ScaffoldCustomApiInput,
services: Services,
overrides?: ScaffoldCustomApiExecuteOverrides,
): Promise<ScaffoldCustomApiOutput> {
const projectRoot = services.resolveWithProjectDirectory(args.projectRoot);
const getScaffold =
overrides?.getScaffold ??
(async (id: string, opts: {projectRoot: string}) => {
const registry = createScaffoldRegistry();
return registry.getScaffold(id, opts);
});
const scaffold = await getScaffold(CUSTOM_API_SCAFFOLD_ID, {projectRoot});
if (!scaffold) {
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir: projectRoot,
dryRun: false,
files: [],
error: `Scaffold not found: ${CUSTOM_API_SCAFFOLD_ID}. Ensure @salesforce/b2c-tooling-sdk is installed.`,
};
}
const cartridges = findCartridges(projectRoot);
if (cartridges.length === 0) {
return {
scaffold: CUSTOM_API_SCAFFOLD_ID,
outputDir: projectRoot,
dryRun: false,
files: [],
error:
'No cartridges found in project. Custom API scaffold requires an existing cartridge. Create a cartridge first: use `b2c scaffold cartridge --name app_custom`, or manually create a directory with a `.project` file (e.g., cartridges/app_custom/.project).',
};
}
let cartridgeName = args.cartridgeName;
if (!cartridgeName) {
cartridgeName = cartridges[0].name;
}
const providedVariables: Record<string, boolean | string> = {
apiName: args.apiName,
cartridgeName,
includeExampleEndpoints: true,
};
if (args.apiType !== undefined) providedVariables.apiType = args.apiType;
if (args.apiDescription !== undefined) providedVariables.apiDescription = args.apiDescription;
const resolveParams = overrides?.resolveScaffoldParameters ?? resolveScaffoldParameters;
const resolved = await resolveParams(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: 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: 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: false,
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: false,
files: [],
error: `Scaffold generation failed: ${message}`,
};
}
}
/**
* Creates the scapi_custom_api_generate_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/).
*
* @param loadServices - Function that returns Services (used by adapter on each call).
* @param executeOverrides - Optional overrides for testing (getScaffold, resolveScaffoldParameters).
*/
export function createScaffoldCustomApiTool(
loadServices: () => Promise<Services> | Services,
executeOverrides?: ScaffoldCustomApiExecuteOverrides,
): McpTool {
return createToolAdapter<ScaffoldCustomApiInput, ScaffoldCustomApiOutput>(
{
name: 'scapi_custom_api_generate_scaffold',
description: `Generate a new custom SCAPI endpoint (OAS 3.0 schema, api.json, script.js) in an existing cartridge. \
Required: apiName (kebab-case). Optional: cartridgeName (defaults to first cartridge found in project), apiType (shopper|admin) default to shopper, \
apiDescription, projectRoot, outputDir.`,
toolsets: ['PWAV3', 'SCAPI', 'STOREFRONTNEXT'],
isGA: true,
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 project root).',
),
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.'),
projectRoot: z
.string()
.nullish()
.describe(
'Project root for cartridge discovery. Default: project directory. Set to override the project directory.',
),
outputDir: z.string().optional().describe('Output directory override. Default: project root'),
},
async execute(args, {services}) {
return executeScaffoldCustomApi(args, services, executeOverrides);
},
formatOutput(output) {
if (output.error) {
return errorResult(output.error);
}
return jsonResult(output);
},
},
loadServices,
);
}