Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
12 changes: 10 additions & 2 deletions packages/b2c-dx-mcp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,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 @@ -140,6 +140,12 @@ 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 (schema.yaml, api.json, script.js). Requires `apiName` (kebab-case) and `cartridgeName` (must exist in project). Optional: apiType (shopper|admin), apiDescription, includeExampleEndpoints, projectRoot, outputDir, dryRun, force. Set `--working-directory` (or SFCC_WORKING_DIRECTORY) so the MCP server discovers cartridges in your project.

- ✅ "Use the MCP tool to scaffold a new custom API named my-products 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 @@ -289,6 +295,7 @@ PWA Kit v3 development tools for building headless storefronts.
| `pwakit_install_agent_rules` | Install AI agent rules for PWA Kit development |
| `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 schema, api.json, script.js) in an existing cartridge. |
| `mrt_bundle_push` | Build, push bundle (optionally deploy) |

#### SCAPI
Expand All @@ -299,7 +306,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` | Scaffold a new custom SCAPI API (not yet implemented) |
| `scapi_customapi_scaffold` | Generate a new custom SCAPI endpoint (OAS schema, api.json, script.js) in an existing cartridge. |

#### STOREFRONTNEXT
Storefront Next development tools for building modern storefronts.
Expand All @@ -316,6 +323,7 @@ Storefront Next development tools for building modern storefronts.
| `storefront_next_generate_page_designer_metadata` | Generate Page Designer metadata for 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 schema, api.json, script.js) in an existing cartridge. |
| `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
3 changes: 2 additions & 1 deletion packages/b2c-dx-mcp/src/commands/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,11 @@ export default class McpServerCommand extends BaseCommand<typeof McpServerComman
...mrt.options,
};

// Combine B2C instance flags and MRT config flags
// Combine B2C instance flags, MRT config, and working directory so tools use the configured project path
const flagConfig = {
...extractInstanceFlags(this.flags as Record<string, unknown>),
...mrt.config,
workingDirectory: this.flags['working-directory'],
Copy link
Contributor

Choose a reason for hiding this comment

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

working-directory is deprecated. See #199.

also see prior #160 which exposes workingDirectory/projectDirectory in thecontext.services.getWorkingDirectory() passed to each tool. Not sure which approach is better, but we should standardize on a best one.

Copy link
Contributor

Choose a reason for hiding this comment

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

resolved

Copy link
Contributor

Choose a reason for hiding this comment

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

getBaseConfigOptions() already supplies workingDirectory so we do not need it here again.

};

return loadConfig(flagConfig, options);
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),
];
}
241 changes: 241 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,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;
Copy link
Contributor

Choose a reason for hiding this comment

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

Wonder when agent will set this to false? Do we need this input?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

it's default to true. I can remove it.

/** 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;
Copy link
Contributor

Choose a reason for hiding this comment

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

What will happen when dryRun is true? Do we need this?

/** 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',
Copy link
Contributor

Choose a reason for hiding this comment

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

We have scapi_custom_apis_status tool, can we unify the tool name? Maybe scapi_custom_api_scaffold

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

This name "scapi_custom_api_scaffold" is following the LLD. Once LLD is updated, will update here.

Copy link
Contributor

@yhsieh1 yhsieh1 Feb 25, 2026

Choose a reason for hiding this comment

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

@wei-liu-sf I corrected the name in LLD so that it matches the naming with other scapi tools. Please update it to scapi_custom_api_scaffold. Thank you.

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, dryRun, force. \
Copy link
Contributor

Choose a reason for hiding this comment

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

Description can be improved to avoid duplicated inputs info that is specified in the input schema. Also we probably can skip the mention of CLI since that seems not help agent to use the tool.

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.',
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 give more details so that agent knows how to add a cartridge project?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Sure, will do

};
}
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,
);
}
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 @@ -91,6 +91,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_customapi_scaffold');
});

it('should create STOREFRONTNEXT tools', () => {
Expand Down Expand Up @@ -310,6 +311,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_customapi_scaffold');
});

it('should trigger auto-discovery when all individual tools are invalid', async () => {
Expand All @@ -326,6 +328,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_customapi_scaffold');
});

it('should skip non-GA tools when allowNonGaTools is false', async () => {
Expand Down
14 changes: 12 additions & 2 deletions packages/b2c-tooling-sdk/src/operations/code/cartridges.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,20 @@ export interface FindCartridgesOptions {
export function findCartridges(directory?: string, options: FindCartridgesOptions = {}): CartridgeMapping[] {
const searchDir = directory ? path.resolve(directory) : process.cwd();

// Find all .project files (Eclipse project markers)
// Find all .project files (Eclipse project markers).
// Ignore common non-cartridge dirs to keep discovery fast when projectRoot is broad (e.g. MCP working directory).
const projectFiles = globSync('**/.project', {
cwd: searchDir,
ignore: ['**/node_modules/**'],
ignore: [
'**/node_modules/**',
'**/.git/**',
'**/dist/**',
'**/build/**',
'**/coverage/**',
'**/.cache/**',
'**/tmp/**',
'**/temp/**',
],
});

let cartridges = projectFiles.map((f) => {
Expand Down
Loading
Loading