-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathmcp.ts
More file actions
300 lines (285 loc) · 11.9 KB
/
mcp.ts
File metadata and controls
300 lines (285 loc) · 11.9 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
* 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
*/
/**
* MCP Server Command - Salesforce B2C Commerce Developer Experience
*
* This is the main entry point for the B2C DX MCP server, built with oclif.
* It exposes B2C Commerce Cloud developer tools to AI assistants via the
* Model Context Protocol (MCP).
*
* ## Flags
*
* ### MCP-Specific Flags
* | Flag | Env Variable | Description |
* |------|--------------|-------------|
* | `--toolsets` | `SFCC_TOOLSETS` | Comma-separated toolsets to enable (case-insensitive) |
* | `--tools` | `SFCC_TOOLS` | Comma-separated individual tools to enable (case-insensitive) |
* | `--allow-non-ga-tools` | `SFCC_ALLOW_NON_GA_TOOLS` | Enable experimental/non-GA tools |
*
* ### MRT Flags (from MrtCommand.baseFlags)
* | Flag | Env Variable | Description |
* |------|--------------|-------------|
* | `--api-key` | `SFCC_MRT_API_KEY` | MRT API key for Managed Runtime operations |
* | `--project` | `SFCC_MRT_PROJECT` | MRT project slug (required for MRT tools) |
* | `--environment` | `SFCC_MRT_ENVIRONMENT` | MRT environment (e.g., staging, production) |
* | `--cloud-origin` | `SFCC_MRT_CLOUD_ORIGIN` | MRT cloud origin URL for environment-specific ~/.mobify config |
*
* ### B2C Instance Flags (from InstanceCommand.baseFlags)
* | Flag | Env Variable | Description |
* |------|--------------|-------------|
* | `--server` | `SFCC_SERVER` | B2C instance hostname |
* | `--code-version` | `SFCC_CODE_VERSION` | Code version for deployments |
* | `--username` | `SFCC_USERNAME` | Username for Basic auth (WebDAV) |
* | `--password` | `SFCC_PASSWORD` | Password/access key for Basic auth |
* | `--client-id` | `SFCC_CLIENT_ID` | OAuth client ID |
* | `--client-secret` | `SFCC_CLIENT_SECRET` | OAuth client secret |
*
* ### Global Flags (inherited from BaseCommand)
* | Flag | Env Variable | Description |
* |------|--------------|-------------|
* | `--working-directory` | `SFCC_WORKING_DIRECTORY` | Project working directory (see note below) |
* | `--config` | `SFCC_CONFIG` | Path to dw.json config file (auto-discovered if not provided) |
* | `--instance` | `SFCC_INSTANCE` | Instance name from configuration file |
* | `--log-level` | `SFCC_LOG_LEVEL` | Set logging verbosity (trace, debug, info, warn, error, silent) |
* | `--debug` | `SFCC_DEBUG` | Enable debug logging |
* | `--json` | - | Output logs as JSON lines |
* | `--lang` | - | Language for messages |
*
* **Note on `--working-directory`**: Many MCP clients (Cursor, Claude Desktop) spawn servers from the
* user's home directory (`~`) rather than the project directory. This flag is used for:
* - Auto-discovery (detecting project type when no `--toolsets` or `--tools` are provided)
* - Scaffolding tools (creating files in the correct project location)
* - Any tool that needs to operate on the project directory
*
* Use `--working-directory` or `SFCC_WORKING_DIRECTORY` env var to specify the actual project path.
*
* ## Configuration
*
* Different tools require different configuration:
* - **MRT tools** (e.g., `mrt_bundle_push`) → MRT flags (--project, --api-key)
* - **B2C instance tools** (e.g., `cartridge_deploy`, SCAPI) → Instance flags or dw.json
* - **Local tools** (e.g., scaffolding) → None
*
* ### B2C Instance Configuration
* Priority (highest to lowest):
* 1. Flags (`--server`, `--username`, `--password`, `--client-id`, `--client-secret`, `--code-version`)
* 2. Environment variables (via oclif flag env support)
* 3. dw.json file (via `--config` flag or auto-discovered)
*
* ### MRT API Key
* Priority (highest to lowest):
* 1. `--api-key` flag
* 2. `SFCC_MRT_API_KEY` environment variable
* 3. `~/.mobify` config file (or `~/.mobify--[hostname]` if `--cloud-origin` is set)
*
* ## Toolset Validation
*
* - Invalid toolsets are ignored with a warning (server still starts)
* - If all toolsets are invalid, auto-discovery kicks in
*
* @example mcp.json - All toolsets
* ```json
* { "args": ["--toolsets", "all", "--allow-non-ga-tools"] }
* ```
*
* @example mcp.json - Specific toolsets
* ```json
* { "args": ["--toolsets", "CARTRIDGES,MRT", "--allow-non-ga-tools"] }
* ```
*
* @example mcp.json - MRT tools with project, environment, and API key
* ```json
* {
* "args": ["--toolsets", "MRT", "--project", "my-project", "--environment", "staging", "--allow-non-ga-tools"],
* "env": { "SFCC_MRT_API_KEY": "your-api-key" }
* }
* ```
*
* @example mcp.json - MRT tools with staging cloud origin (uses ~/.mobify--cloud-staging.mobify.com)
* ```json
* { "args": ["--toolsets", "MRT", "--project", "my-project", "--cloud-origin", "https://cloud-staging.mobify.com", "--allow-non-ga-tools"] }
* ```
*
* @example mcp.json - Cartridge tools with dw.json config
* ```json
* { "args": ["--toolsets", "CARTRIDGES", "--config", "/path/to/dw.json", "--allow-non-ga-tools"] }
* ```
*
* @example mcp.json - Cartridge tools with env vars
* ```json
* {
* "args": ["--toolsets", "CARTRIDGES", "--allow-non-ga-tools"],
* "env": {
* "SFCC_HOSTNAME": "your-sandbox.demandware.net",
* "SFCC_CLIENT_ID": "your-client-id",
* "SFCC_CLIENT_SECRET": "your-client-secret"
* }
* }
* ```
*
* @example mcp.json - Enable debug logging
* ```json
* { "args": ["--toolsets", "all", "--allow-non-ga-tools", "--debug"] }
* ```
*/
import {Flags} from '@oclif/core';
import {BaseCommand, MrtCommand, InstanceCommand} from '@salesforce/b2c-tooling-sdk/cli';
import {StdioServerTransport} from '@modelcontextprotocol/sdk/server/stdio.js';
import {B2CDxMcpServer} from '../server.js';
import {Services} from '../services.js';
import {registerToolsets} from '../registry.js';
import {TOOLSETS, type StartupFlags} from '../utils/index.js';
/**
* oclif Command that starts the B2C DX MCP server.
*
* Uses oclif's single-command strategy - this IS the CLI, not a subcommand.
* Extends BaseCommand from @salesforce/b2c-tooling-sdk which provides:
* - Global flags for config, logging, and debugging
* - Structured pino logging via `this.logger`
* - Automatic dw.json loading via `this.resolvedConfig`
* - `this.config` - package.json metadata and standard config paths
*/
export default class McpServerCommand extends BaseCommand<typeof McpServerCommand> {
static description =
'Salesforce B2C Commerce Cloud Developer Experience MCP Server - Expose B2C Commerce Developer Experience tools to AI assistants';
static examples = [
{
description: 'All toolsets',
command: '<%= config.bin %> --toolsets all --allow-non-ga-tools',
},
{
description: 'MRT tools with project and API key',
command: '<%= config.bin %> --toolsets MRT --project my-project --api-key your-api-key --allow-non-ga-tools',
},
{
description: 'MRT tools with project, environment, and API key',
command:
'<%= config.bin %> --toolsets MRT --project my-project --environment staging --api-key your-api-key --allow-non-ga-tools',
},
{
description: 'Cartridge tools with explicit config',
command: '<%= config.bin %> --toolsets CARTRIDGES --config /path/to/dw.json --allow-non-ga-tools',
},
{
description: 'Debug logging',
command: '<%= config.bin %> --toolsets all --allow-non-ga-tools --debug',
},
];
static flags = {
// Inherit MRT flags (api-key, cloud-origin, project, environment)
// Also includes BaseCommand flags (config, debug, log-level, etc.) - safe to re-spread
...MrtCommand.baseFlags,
// Inherit Instance flags (server, code-version, username, password, client-id, client-secret)
// These provide B2C instance configuration for tools like cartridge_deploy
...InstanceCommand.baseFlags,
// MCP-specific toolset selection flags
toolsets: Flags.string({
description: `Toolsets to enable (comma-separated). Options: all, ${TOOLSETS.join(', ')}`,
env: 'SFCC_TOOLSETS',
parse: async (input) => input.toUpperCase(),
}),
tools: Flags.string({
description: 'Individual tools to enable (comma-separated)',
env: 'SFCC_TOOLS',
parse: async (input) => input.toLowerCase(),
}),
// Feature flags
'allow-non-ga-tools': Flags.boolean({
description: 'Enable non-GA (experimental) tools',
env: 'SFCC_ALLOW_NON_GA_TOOLS',
default: false,
}),
};
/**
* Main entry point - starts the MCP server.
*
* Execution flow:
* 1. BaseCommand.init() parses flags and loads config
* 2. Filter and validate toolsets (invalid ones are skipped with warning)
* 3. Create B2CDxMcpServer instance
* 4. Create Services via Services.create() which resolves B2C instance and MRT config
* 5. Register tools based on --toolsets and --tools flags
* 6. Connect to stdio transport (JSON-RPC over stdin/stdout)
* 7. Log startup message to stderr
*
* @throws Never throws - invalid toolsets are filtered, not rejected
*
* BaseCommand provides:
* - `this.flags` - Parsed flags including global flags (config, debug, log-level, etc.)
* - `this.resolvedConfig` - Loaded dw.json configuration
* - `this.logger` - Structured pino logger
*
* oclif provides standard config paths via `this.config`:
* - `this.config.configDir` - User config (~/.config/b2c-dx-mcp)
* - `this.config.dataDir` - User data (~/.local/share/b2c-dx-mcp)
* - `this.config.cacheDir` - Cache (~/.cache/b2c-dx-mcp)
* These can be exposed to Services if needed for features like telemetry or caching.
*/
async run(): Promise<void> {
// Flags are already parsed by BaseCommand.init()
// Parse toolsets and tools from comma-separated strings
// Note: toolsets are uppercased, tools are lowercased by their parse functions
const startupFlags: StartupFlags = {
toolsets: this.flags.toolsets ? this.flags.toolsets.split(',').map((s) => s.trim()) : undefined,
tools: this.flags.tools ? this.flags.tools.split(',').map((s) => s.trim()) : undefined,
allowNonGaTools: this.flags['allow-non-ga-tools'],
configPath: this.flags.config,
// Working directory for auto-discovery. oclif handles flag with env fallback.
workingDirectory: this.flags['working-directory'],
};
// TODO: Telemetry - Initialize telemetry unless disabled
// if (!flags["no-telemetry"]) {
// telemetry = new Telemetry({
// toolsets: (startupFlags.toolsets ?? []).join(", "),
// configDir,
// version: this.config.version,
// });
// await telemetry.start();
// process.stdin.on("close", (err) => {
// telemetry?.sendEvent(err ? "SERVER_STOPPED_ERROR" : "SERVER_STOPPED_SUCCESS");
// telemetry?.stop();
// });
// }
// Create MCP server
const server = new B2CDxMcpServer(
{
name: this.config.name,
version: this.config.version,
},
{
capabilities: {
resources: {},
tools: {},
},
},
);
// Create services with config resolved from flags (which have env var fallbacks via oclif)
const services = Services.create({
b2cInstance: {
configPath: this.flags.config,
hostname: this.flags.server,
codeVersion: this.flags['code-version'],
username: this.flags.username,
password: this.flags.password,
clientId: this.flags['client-id'],
clientSecret: this.flags['client-secret'],
},
mrt: {
apiKey: this.flags['api-key'],
cloudOrigin: this.flags['cloud-origin'],
project: this.flags.project,
environment: this.flags.environment,
},
});
// Register toolsets
await registerToolsets(startupFlags, server, services);
// Connect to stdio transport
const transport = new StdioServerTransport();
await server.connect(transport);
// Log startup message using the structured logger
this.logger.info({version: this.config.version}, 'MCP Server running on stdio');
}
}