Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion packages/b2c-dx-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ The `storefront_next_development_guidelines` tool provides critical architecture

##### SCAPI Discovery

Use **scapi_schemas_list** for both standard SCAPI (Shop, Admin, Shopper APIs) and custom APIs. Use **scapi_custom_apis_status** for endpoint-level registration status (active/not_registered).
Use **scapi_schemas_list** for both standard SCAPI (Shop, Admin, Shopper APIs) and custom APIs. Use **scapi_custom_apis_status** for endpoint-level registration status (active/not_registered). Use **scapi_customapi_scaffold** to generate a new custom API in an existing cartridge.

**SCAPI Schemas (tool: `scapi_schemas_list`):**

Expand All @@ -138,6 +138,14 @@ Discover schema metadata and fetch OpenAPI specs for both standard and custom SC
- ✅ "Use the MCP tool to list custom API definitions." → list with apiFamily: custom.
- ✅ "Use the MCP tool to show me the loyalty-points custom API schema." → apiFamily: custom, apiName: loyalty-points, apiVersion: v1, includeSchemas: true.

**Custom API Scaffold (tool: `scapi_customapi_scaffold`):**

Generate a new custom SCAPI endpoint in an existing cartridge (OAS 3.0 schema.yaml, api.json, script.js with example GET endpoints). Requires **apiName** (kebab-case). Optional: **cartridgeName** (omit to use the first cartridge found under the working directory), **apiType** (shopper | admin; default shopper), **apiDescription**, **projectRoot**, **outputDir**. Set `--working-directory` (or SFCC_WORKING_DIRECTORY) so the server discovers cartridges in your project. Files are always generated (no dry run) and existing files are never overwritten.

- ✅ "Use the MCP tool to scaffold a new custom API named my-products."
- ✅ "Use the MCP tool to create a custom admin API called customer-trips."
- ✅ "Use the MCP tool to scaffold a new shopper custom API gift-registry-list in cartridge app_custom."

**Custom API Endpoint Status (tool: `scapi_custom_apis_status`):**

Get registration status of custom API endpoints deployed on the instance (remote only). Returns individual HTTP endpoints (e.g., GET /hello, POST /items/{id}) with registration status (active/not_registered), one row per endpoint per site. Requires OAuth with `sfcc.custom-apis` scope.
Expand Down Expand Up @@ -282,6 +290,7 @@ PWA Kit v3 development tools for building headless storefronts.
|------|-------------|
| `scapi_schemas_list` | List or fetch SCAPI schemas (standard and custom). Use apiFamily: "custom" for custom APIs. |
| `scapi_custom_apis_status` | Get registration status of custom API endpoints (active/not_registered). Remote only, requires OAuth. |
| `scapi_customapi_scaffold` | Generate a new custom SCAPI endpoint (OAS 3.0 schema, api.json, script.js) in an existing cartridge. Required: apiName. Optional: cartridgeName (defaults to first cartridge), apiType, apiDescription, projectRoot, outputDir. |
| `mrt_bundle_push` | Build, push bundle (optionally deploy) |

#### SCAPI
Expand All @@ -292,6 +301,7 @@ Salesforce Commerce API discovery and exploration.
|------|-------------|
| `scapi_schemas_list` | List or fetch SCAPI schemas (standard and custom). Use apiFamily: "custom" for custom APIs. |
| `scapi_custom_apis_status` | Get registration status of custom API endpoints (active/not_registered). Remote only, requires OAuth. |
| `scapi_customapi_scaffold` | Generate a new custom SCAPI endpoint (OAS 3.0 schema, api.json, script.js) in an existing cartridge. Required: apiName. Optional: cartridgeName (defaults to first cartridge), apiType, apiDescription, projectRoot, outputDir. |

#### STOREFRONTNEXT
Storefront Next development tools for building modern storefronts.
Expand All @@ -303,6 +313,7 @@ Storefront Next development tools for building modern storefronts.
| `storefront_next_page_designer_decorator` | Add Page Designer decorators to Storefront Next components |
| `scapi_schemas_list` | List or fetch SCAPI schemas (standard and custom). Use apiFamily: "custom" for custom APIs. |
| `scapi_custom_apis_status` | Get registration status of custom API endpoints (active/not_registered). Remote only, requires OAuth. |
| `scapi_customapi_scaffold` | Generate a new custom SCAPI endpoint (OAS 3.0 schema, api.json, script.js) in an existing cartridge. Required: apiName. Optional: cartridgeName (defaults to first cartridge), apiType, apiDescription, projectRoot, outputDir. |
| `mrt_bundle_push` | Build, push bundle (optionally deploy) |

> **Note:** Some tools appear in multiple toolsets (e.g., `mrt_bundle_push`, `scapi_schemas_list`, `scapi_custom_apis_status`). When using multiple toolsets, tools are automatically deduplicated.
Expand Down
9 changes: 7 additions & 2 deletions packages/b2c-dx-mcp/src/tools/scapi/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
* SCAPI toolset for B2C Commerce.
*
* This toolset provides MCP tools for Salesforce Commerce API (SCAPI) discovery and exploration.
* Includes both standard SCAPI schemas and custom API status tools.
* Includes standard SCAPI schemas, custom API status, and custom API scaffold tools.
*
* @module tools/scapi
*/
Expand All @@ -17,6 +17,7 @@ import type {McpTool} from '../../utils/index.js';
import type {Services} from '../../services.js';
import {createScapiSchemasListTool} from './scapi-schemas-list.js';
import {createScapiCustomApisStatusTool} from './scapi-custom-apis-status.js';
import {createScaffoldCustomApiTool} from './scapi-customapi-scaffold.js';

/**
* Creates all tools for the SCAPI toolset.
Expand All @@ -25,5 +26,9 @@ import {createScapiCustomApisStatusTool} from './scapi-custom-apis-status.js';
* @returns Array of MCP tools
*/
export function createScapiTools(loadServices: () => Services): McpTool[] {
return [createScapiSchemasListTool(loadServices), createScapiCustomApisStatusTool(loadServices)];
return [
createScapiSchemasListTool(loadServices),
createScapiCustomApisStatusTool(loadServices),
createScaffoldCustomApiTool(loadServices),
];
}
230 changes: 230 additions & 0 deletions packages/b2c-dx-mcp/src/tools/scapi/scapi-customapi-scaffold.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
/*
* 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_custom_api_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 working directory */
projectRoot?: string;
/** Output directory override. Default: scaffold default or project root */
outputDir?: string;
}

/**
* Output schema for scapi_custom_api_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_custom_api_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_custom_api_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. \
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we remove LCI from the description? We should try to keep description short and simple. Mention of CLI might confuse agent.

Required: apiName (kebab-case). Optional: cartridgeName (defaults to first cartridge found in project), apiType (shopper|admin), apiDescription, includeExampleEndpoints, projectRoot, outputDir. \
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.'),
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'),
},
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: 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: false,
files: [],
error:
'No cartridges found in project. Custom API scaffold requires an existing cartridge. Create a cartridge (directory with .project file) first. You can use the `b2c scaffold cartridge` command to create a cartridge.',
};
}
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 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: 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}`,
};
}
},
formatOutput(output) {
if (output.error) {
return errorResult(output.error);
}
return jsonResult(output);
},
},
loadServices,
);
}
3 changes: 3 additions & 0 deletions packages/b2c-dx-mcp/test/registry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ describe('registry', () => {
const toolNames = registry.SCAPI.map((t) => t.name);
expect(toolNames).to.include('scapi_schemas_list');
expect(toolNames).to.include('scapi_custom_apis_status');
expect(toolNames).to.include('scapi_custom_api_scaffold');
});

it('should create STOREFRONTNEXT tools', () => {
Expand Down Expand Up @@ -303,6 +304,7 @@ describe('registry', () => {
// Auto-discovery always includes BASE_TOOLSET (SCAPI), even if no project type detected
expect(server.registeredTools).to.include('scapi_schemas_list');
expect(server.registeredTools).to.include('scapi_custom_apis_status');
expect(server.registeredTools).to.include('scapi_custom_api_scaffold');
});

it('should trigger auto-discovery when all individual tools are invalid', async () => {
Expand All @@ -319,6 +321,7 @@ describe('registry', () => {
// Auto-discovery always includes BASE_TOOLSET (SCAPI), even if no project type detected
expect(server.registeredTools).to.include('scapi_schemas_list');
expect(server.registeredTools).to.include('scapi_custom_apis_status');
expect(server.registeredTools).to.include('scapi_custom_api_scaffold');
});

it('should skip non-GA tools when allowNonGaTools is false', async () => {
Expand Down
Loading
Loading