@bridge_gpt/mcp-server 0.2.25 → 0.2.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,256 @@
1
+ /**
2
+ * BAPI-634: thin CLI handler exposing the deterministic conductor-bundle helpers
3
+ * to `emit-conductor-bundle.md`.
4
+ *
5
+ * Why this exists: the instruction ships **compiled** to consuming repositories
6
+ * inside `build/pipelines.generated.js`. `mcp_server/src/` does not exist there,
7
+ * so an instruction that told the agent to "call `validateConductorBundleInputs`"
8
+ * would be referencing a path only this repository has. This subcommand is the
9
+ * reachable surface, mirroring how `store-and-approve-epic-plan.md` invokes
10
+ * `setup-epic` rather than hand-rolling HTTP calls.
11
+ *
12
+ * It holds no policy of its own: it parses argv, delegates to
13
+ * `conductor-bundle-artifacts.ts`, and prints a JSON envelope. All I/O is behind
14
+ * an injectable seam so tests never touch a real disk or construct a server.
15
+ */
16
+ import path from "node:path";
17
+ import { finalizeEpicPlanSidecar, serializeSiblingTicketManifest, validateConductorBundleInputs, writeJsonAtomically, } from "./conductor-bundle-artifacts.js";
18
+ const USAGE = [
19
+ "Usage: emit-conductor-bundle <validate|finalize> --input <file> [--docs-dir <dir>] [--json]",
20
+ "",
21
+ " validate Validate identities, the node->ticket mapping, manifest agreement,",
22
+ " and path containment. Writes nothing.",
23
+ " finalize Validate, then finalize epic-plan.dag.json with real keys and",
24
+ " per-node touched_files, and write the sibling-ticket manifest.",
25
+ "",
26
+ "Options:",
27
+ " --input <file> JSON document with epic_key, epic_slug, mappings,",
28
+ " decomposition_fingerprint, and (for finalize)",
29
+ " touched_files_by_key.",
30
+ " --docs-dir <dir> Docs directory (default: $BAPI_DOCS_DIR, else docs/tmp).",
31
+ " --json Emit a machine-readable result on stdout.",
32
+ " -h, --help Show this help.",
33
+ ].join("\n");
34
+ /** Read a flag's value, rejecting a missing or flag-shaped value. */
35
+ function takeValue(argv, index, flag) {
36
+ const value = argv[index + 1];
37
+ if (value === undefined || value.startsWith("-")) {
38
+ throw new Error(`Flag "${flag}" requires a value.`);
39
+ }
40
+ return value;
41
+ }
42
+ /** Parse argv into options, or throw with an actionable message. */
43
+ export function parseConductorBundleArgs(argv) {
44
+ const mode = argv[0];
45
+ if (mode === "-h" || mode === "--help" || mode === undefined) {
46
+ return { mode: "validate", inputFile: "", json: false, help: true };
47
+ }
48
+ if (mode !== "validate" && mode !== "finalize") {
49
+ throw new Error(`Unknown subcommand "${mode}". Expected "validate" or "finalize".`);
50
+ }
51
+ let inputFile;
52
+ let docsDir;
53
+ let json = false;
54
+ let help = false;
55
+ for (let i = 1; i < argv.length; i++) {
56
+ const arg = argv[i];
57
+ switch (arg) {
58
+ case "--input":
59
+ inputFile = takeValue(argv, i, "--input");
60
+ i++;
61
+ break;
62
+ case "--docs-dir":
63
+ docsDir = takeValue(argv, i, "--docs-dir");
64
+ i++;
65
+ break;
66
+ case "--json":
67
+ json = true;
68
+ break;
69
+ case "-h":
70
+ case "--help":
71
+ help = true;
72
+ break;
73
+ default:
74
+ throw new Error(`Unknown argument "${arg}".`);
75
+ }
76
+ }
77
+ if (help)
78
+ return { mode, inputFile: inputFile ?? "", docsDir, json, help: true };
79
+ if (!inputFile)
80
+ throw new Error('Flag "--input" is required.');
81
+ return { mode, inputFile, docsDir, json, help: false };
82
+ }
83
+ /** Parse JSON, converting a syntax error into an actionable message. */
84
+ async function readJson(filePath, fs, label) {
85
+ let raw;
86
+ try {
87
+ raw = await fs.readFile(filePath);
88
+ }
89
+ catch (err) {
90
+ throw new Error(`Could not read ${label} at ${filePath}: ${err instanceof Error ? err.message : String(err)}`);
91
+ }
92
+ try {
93
+ return JSON.parse(raw);
94
+ }
95
+ catch (err) {
96
+ throw new Error(`${label} at ${filePath} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
97
+ }
98
+ }
99
+ /** Read an optional JSON file, returning null when it does not exist. */
100
+ async function readOptionalJson(filePath, fs, label) {
101
+ try {
102
+ await fs.readFile(filePath);
103
+ }
104
+ catch {
105
+ return null;
106
+ }
107
+ return readJson(filePath, fs, label);
108
+ }
109
+ /**
110
+ * Run the `emit-conductor-bundle` subcommand. Returns a process exit code; never
111
+ * throws for an expected validation failure.
112
+ */
113
+ export async function runConductorBundleCli(argv, overrides = {}) {
114
+ const deps = {
115
+ env: process.env,
116
+ cwd: process.cwd(),
117
+ fs: createDefaultBundleFs(),
118
+ log: (m) => console.log(m),
119
+ // Diagnostics go to stderr so `--json` keeps stdout a single result object.
120
+ errorLog: (m) => console.error(m),
121
+ ...overrides,
122
+ };
123
+ let opts;
124
+ try {
125
+ opts = parseConductorBundleArgs(argv);
126
+ }
127
+ catch (err) {
128
+ deps.errorLog(err instanceof Error ? err.message : String(err));
129
+ deps.errorLog(USAGE);
130
+ return 1;
131
+ }
132
+ if (opts.help) {
133
+ deps.log(USAGE);
134
+ return 0;
135
+ }
136
+ const emitFailure = (error) => {
137
+ if (opts.json)
138
+ deps.log(JSON.stringify({ ok: false, error }));
139
+ else
140
+ deps.errorLog(`Error: ${error}`);
141
+ return 1;
142
+ };
143
+ const docsDir = path.resolve(deps.cwd, opts.docsDir ?? deps.env.BAPI_DOCS_DIR ?? path.join("docs", "tmp"));
144
+ let input;
145
+ try {
146
+ input = (await readJson(path.resolve(deps.cwd, opts.inputFile), deps.fs, "--input document"));
147
+ }
148
+ catch (err) {
149
+ return emitFailure(err instanceof Error ? err.message : String(err));
150
+ }
151
+ if (!input || typeof input !== "object") {
152
+ return emitFailure("--input document must be a JSON object.");
153
+ }
154
+ const epicDir = path.resolve(docsDir, "epic-plans", String(input.epic_slug));
155
+ const sidecarPath = path.join(epicDir, "epic-plan.dag.json");
156
+ const manifestPath = path.join(epicDir, "sibling-ticket-manifest.json");
157
+ let sidecar;
158
+ let existingManifest;
159
+ try {
160
+ sidecar = await readJson(sidecarPath, deps.fs, "epic-plan.dag.json");
161
+ existingManifest = await readOptionalJson(manifestPath, deps.fs, "sibling-ticket-manifest.json");
162
+ }
163
+ catch (err) {
164
+ return emitFailure(err instanceof Error ? err.message : String(err));
165
+ }
166
+ const validation = await validateConductorBundleInputs({
167
+ epic_key: input.epic_key,
168
+ epic_slug: input.epic_slug,
169
+ docs_dir: docsDir,
170
+ mappings: input.mappings,
171
+ sidecar,
172
+ existing_manifest: existingManifest ?? undefined,
173
+ decomposition_fingerprint: input.decomposition_fingerprint,
174
+ }, deps.fs);
175
+ if (!validation.ok)
176
+ return emitFailure(validation.error);
177
+ if (opts.mode === "validate") {
178
+ const result = {
179
+ ok: true,
180
+ mode: "validate",
181
+ epic_key: validation.value.epic_key,
182
+ plan_version: validation.value.plan_version,
183
+ mapped_nodes: validation.value.mappings.length,
184
+ sidecar_path: validation.value.sidecar_path,
185
+ };
186
+ if (opts.json)
187
+ deps.log(JSON.stringify(result));
188
+ else {
189
+ deps.log(`Validated ${result.mapped_nodes} node mapping(s) for ${result.epic_key} ` +
190
+ `(plan v${result.plan_version}). Nothing was written.`);
191
+ }
192
+ return 0;
193
+ }
194
+ // ---- finalize ----------------------------------------------------------
195
+ const nodeKeyMap = {};
196
+ for (const m of validation.value.mappings) {
197
+ nodeKeyMap[m.plan_node_id] = m.ticket_key;
198
+ }
199
+ const finalized = finalizeEpicPlanSidecar({
200
+ sidecar,
201
+ node_key_map: nodeKeyMap,
202
+ touched_files_by_key: input.touched_files_by_key ?? {},
203
+ plan_version_already_stored: input.plan_version_already_stored === true,
204
+ });
205
+ if (!finalized.ok)
206
+ return emitFailure(finalized.error);
207
+ const sidecarWrite = await writeJsonAtomically(validation.value.sidecar_path, finalized.value, deps.fs);
208
+ if (!sidecarWrite.ok)
209
+ return emitFailure(sidecarWrite.error);
210
+ const manifest = serializeSiblingTicketManifest({
211
+ schema_version: 1,
212
+ epic_key: validation.value.epic_key,
213
+ epic_slug: validation.value.epic_slug,
214
+ plan_version: validation.value.plan_version,
215
+ decomposition_fingerprint: input.decomposition_fingerprint,
216
+ finalized_fingerprint: null,
217
+ run_phase: input.run_phase ?? "staged",
218
+ mappings: validation.value.mappings.map((m) => ({
219
+ plan_node_id: m.plan_node_id,
220
+ ticket_key: m.ticket_key,
221
+ exploration_path: m.exploration_path,
222
+ draft_path: m.draft_path,
223
+ })),
224
+ decisions: [],
225
+ completed_mutations: [],
226
+ });
227
+ const manifestWrite = await writeJsonAtomically(validation.value.manifest_path, manifest, deps.fs);
228
+ if (!manifestWrite.ok)
229
+ return emitFailure(manifestWrite.error);
230
+ const result = {
231
+ ok: true,
232
+ mode: "finalize",
233
+ epic_key: validation.value.epic_key,
234
+ plan_version: validation.value.plan_version,
235
+ sidecar_path: validation.value.sidecar_path,
236
+ manifest_path: validation.value.manifest_path,
237
+ ticket_keys: validation.value.mappings.map((m) => m.ticket_key),
238
+ };
239
+ if (opts.json)
240
+ deps.log(JSON.stringify(result));
241
+ else {
242
+ deps.log(`Finalized ${result.sidecar_path} with ${result.ticket_keys.length} real key(s) ` +
243
+ `and per-node touched_files. Manifest: ${result.manifest_path}`);
244
+ }
245
+ return 0;
246
+ }
247
+ /** Real filesystem seam, loaded lazily so importing this module stays cheap. */
248
+ function createDefaultBundleFs() {
249
+ return {
250
+ readFile: async (p) => (await import("node:fs/promises")).readFile(p, "utf-8"),
251
+ writeFile: async (p, data) => (await import("node:fs/promises")).writeFile(p, data, "utf-8"),
252
+ rename: async (from, to) => (await import("node:fs/promises")).rename(from, to),
253
+ unlink: async (p) => (await import("node:fs/promises")).unlink(p),
254
+ realpath: async (p) => (await import("node:fs/promises")).realpath(p),
255
+ };
256
+ }
@@ -1,5 +1,6 @@
1
1
  // AUTO-GENERATED — do not edit manually. Regenerate with: npm run build
2
2
  // This file is produced by scripts/bundle-docs.js
3
3
  export const DOCS = {
4
- "docs/mcp-tool-integrations.md": "# MCP tool integrations — the human \"why\" behind the capability report\n\nThis catalog is **explanatory prose only**. It exists so the `/install-bridge`\ncapability report can cite a human-readable \"why\" for each gate. It is **not** a\nsource of truth for gating: the server computes every `locked_tools` /\n`unlocked_tools` membership decision itself and the agent must never recompute a\ntool's dependencies from this document.\n\n**Authoritative source of gating.** The enforced rules — which tools are blocked,\nwhich are degraded, and what each requires — live in\n`api/library/vcs/vcs_route_operations.py`:\n\n- `VCS_ROUTE_REQUIREMENTS` — routes that **BLOCK** (are unavailable) without a\n VCS connection.\n- `VCS_ROUTE_WARNINGS` — routes that **DEGRADE** (stay usable, but without\n codebase context) without a VCS connection.\n- `NEVER_GATED_ROUTE_KEYS` — routes that are never gated on any integration.\n- `INDEX_REQUIRED_ROUTE_KEYS`, `INDEX_REQUIRED_BRAINSTORM_MODES`,\n `CREATE_DOC_CODEBASE_CONTEXT_DOC_TYPES`, `CREATE_DOC_WARN_DOC_TYPES` — the\n conditional \"requires a successful code index\" dimension.\n- The resolver helpers `get_required_vcs_operation()`, `get_warn_vcs_operation()`,\n and `requires_successful_index()` are the authoritative functions that decide a\n case. The capability report is derived from these; this catalog explains them.\n\n## Reading the capability report\n\nEach tool entry the server returns has the exact shape\n`{tool, effect, missing, semantics}`:\n\n- **`effect`**\n - **`BLOCK`** — the tool is **unavailable** until every listed dependency is\n met. It will refuse to run without them.\n - **`DEGRADE`** — the tool is **usable right now**, but **without codebase\n context** (it cannot ground its output in your repository). Connecting the\n listed dependency upgrades it from \"works blind\" to \"works with full context\".\n A `DEGRADE` tool is never \"failed\".\n- **`missing`** — the server-computed dependency identifiers still needed:\n integration ids such as `github_app` / `vcs_access_token`, and the synthetic\n `code_index` (a successful repository index).\n- **`semantics`**\n - **`all_of`** — every id in `missing` is required.\n - **`any_of`** — the VCS-provider candidates in `missing` are alternatives:\n **either** `github_app` **or** `vcs_access_token` satisfies the VCS\n requirement (this is the \"provider unknown\" case). When `code_index` also\n appears, it remains separately required — `semantics` describes only the VCS\n provider candidates, and a code index is always mandatory in addition.\n\nThe three readiness dimensions `configured` / `learned` / `indexed` are reported\nindependently. `indexed` may be `true`, `false`, or `null` — a `null` means the\nindex status could not be confirmed and must **not** be read as \"indexed\".\n\n## The integrations\n\n| Integration id | What it is | What it unlocks |\n| --- | --- | --- |\n| `jira` | Jira API access | Ticket reads/writes, estimation and review automations, status transitions. |\n| `github_app` | GitHub App installation | Pull requests, code review, and private-repo parsing on GitHub projects. |\n| `vcs_access_token` | VCS access token | Pull requests, code review, and private-repo parsing on Bitbucket projects. |\n| `vcs_webhook` | VCS webhook secret | Merge webhooks and CI follow-up triggers. |\n| `code_index` | A successful repository index | Codebase-grounded planning, architecture, reimplementation, and technical/discovery brainstorms. Produced by `/parse-repository`. |\n\nA project's `github_app` **or** `vcs_access_token` provides the VCS connection;\nwhich one applies depends on the project's version-control system. When the\nproject's provider is unknown, either credential satisfies the requirement — the\nreport expresses that as `semantics: any_of`.\n\n## The gates, by capability\n\n### Pull requests and CI (BLOCK on VCS)\n\nTools like `create_pull_request`, `resolve_ci_checks`, `poll_ci_checks`, and\n`materialize_fresh_base` are **unavailable** (`BLOCK`) until a VCS connection is\nconfigured. They act directly on the version-control host, so without a\nconnection there is nothing for them to talk to.\n\n### Repository indexing and maps (BLOCK on VCS)\n\n`parse_repository` and `regenerate_directory_map` need a VCS connection to read\nthe repository. They **BLOCK** until VCS is connected.\n\n### Codebase-grounded generation (BLOCK on VCS **and** a code index)\n\nPlanning and architecture tools — `generate_plan_direct`,\n`generate_architecture_direct`, `request_reimplement_context`,\n`code_writer_generate_plan`, `code_writer_generate_architecture`, and\n`create_doc` for **TDD** / **architecture** documents — ground their output in\nyour indexed codebase. They **BLOCK** until BOTH a VCS connection AND a\nsuccessful code index exist (`all_of`, with `code_index` in `missing`).\n\n### Brainstorms (BLOCK on a code index, mode-dependent)\n\n`request_brainstorm` in **technical** or **discovery** mode searches your indexed\ncodebase, so it **BLOCK**s on `code_index`. **Design**-mode brainstorming never\nqueries the index and is never gated.\n\n### Document generation that DEGRADEs (usable without codebase context)\n\nTools like `generate_prd_direct`, `generate_fsd_direct`,\n`code_writer_generate_fsd`, `generate_clarifying_questions_direct`,\n`generate_ticket_critique_direct`, `generate_ticket_review_direct`, and\n`create_doc` for **PRD** / **FSD** documents **DEGRADE** rather than block: they\nrun today from the ticket alone, and connecting VCS simply lets them ground their\noutput in your codebase. They always appear under \"Tools you can use now\", with a\nreduced-context caveat when the VCS connection is missing.\n\n### Never gated\n\nSetup and bootstrap tools (`ping`, `config_field`, `get_install_manifest`,\n`apply_install_manifest`, `get_my_role`, `persist_routing_credential`,\n`get_docs_dir`, and the bootstrap-invite exchange) are always available — they\nare how you configure everything else.\n"
4
+ "docs/mcp-tool-integrations.md": "# MCP tool integrations — the human \"why\" behind the capability report\n\nThis catalog is **explanatory prose only**. It exists so the `/install-bridge`\ncapability report can cite a human-readable \"why\" for each gate. It is **not** a\nsource of truth for gating: the server computes every `locked_tools` /\n`unlocked_tools` membership decision itself and the agent must never recompute a\ntool's dependencies from this document.\n\n**Authoritative source of gating.** The enforced rules — which tools are blocked,\nwhich are degraded, and what each requires — live in\n`api/library/vcs/vcs_route_operations.py`:\n\n- `VCS_ROUTE_REQUIREMENTS` — routes that **BLOCK** (are unavailable) without a\n VCS connection.\n- `VCS_ROUTE_WARNINGS` — routes that **DEGRADE** (stay usable, but without\n codebase context) without a VCS connection.\n- `NEVER_GATED_ROUTE_KEYS` — routes that are never gated on any integration.\n- `INDEX_REQUIRED_ROUTE_KEYS`, `INDEX_REQUIRED_BRAINSTORM_MODES`,\n `CREATE_DOC_CODEBASE_CONTEXT_DOC_TYPES`, `CREATE_DOC_WARN_DOC_TYPES` — the\n conditional \"requires a successful code index\" dimension.\n- The resolver helpers `get_required_vcs_operation()`, `get_warn_vcs_operation()`,\n and `requires_successful_index()` are the authoritative functions that decide a\n case. The capability report is derived from these; this catalog explains them.\n\n## Reading the capability report\n\nEach tool entry the server returns has the exact shape\n`{tool, effect, missing, semantics}`:\n\n- **`effect`**\n - **`BLOCK`** — the tool is **unavailable** until every listed dependency is\n met. It will refuse to run without them.\n - **`DEGRADE`** — the tool is **usable right now**, but **without codebase\n context** (it cannot ground its output in your repository). Connecting the\n listed dependency upgrades it from \"works blind\" to \"works with full context\".\n A `DEGRADE` tool is never \"failed\".\n- **`missing`** — the server-computed dependency identifiers still needed:\n integration ids such as `github_app` / `vcs_access_token`, and the synthetic\n `code_index` (a successful repository index).\n- **`semantics`**\n - **`all_of`** — every id in `missing` is required.\n - **`any_of`** — the VCS-provider candidates in `missing` are alternatives:\n **either** `github_app` **or** `vcs_access_token` satisfies the VCS\n requirement (this is the \"provider unknown\" case). When `code_index` also\n appears, it remains separately required — `semantics` describes only the VCS\n provider candidates, and a code index is always mandatory in addition.\n\nThe three readiness dimensions `configured` / `learned` / `indexed` are reported\nindependently. `indexed` may be `true`, `false`, or `null` — a `null` means the\nindex status could not be confirmed and must **not** be read as \"indexed\".\n\n## The integrations\n\n| Integration id | What it is | What it unlocks |\n| --- | --- | --- |\n| `jira` | Jira API access | Ticket reads/writes, estimation and review automations, status transitions. |\n| `github_app` | GitHub App installation | Pull requests, code review, and private-repo parsing on GitHub projects. |\n| `vcs_access_token` | VCS access token | Pull requests, code review, and private-repo parsing on Bitbucket projects. |\n| `vcs_webhook` | VCS webhook secret | Merge webhooks and CI follow-up triggers. |\n| `code_index` | A successful repository index | Codebase-grounded planning, architecture, reimplementation, and technical/discovery brainstorms. Produced by `/parse-repository`. |\n\nA project's `github_app` **or** `vcs_access_token` provides the VCS connection;\nwhich one applies depends on the project's version-control system. When the\nproject's provider is unknown, either credential satisfies the requirement — the\nreport expresses that as `semantics: any_of`.\n\n## The gates, by capability\n\n### Pull requests and CI (BLOCK on VCS)\n\nTools like `create_pull_request`, `resolve_ci_checks`, `poll_ci_checks`, and\n`materialize_fresh_base` are **unavailable** (`BLOCK`) until a VCS connection is\nconfigured. They act directly on the version-control host, so without a\nconnection there is nothing for them to talk to.\n\n### Repository indexing and maps (BLOCK on VCS)\n\n`parse_repository` and `regenerate_directory_map` need a VCS connection to read\nthe repository. They **BLOCK** until VCS is connected.\n\n### Codebase-grounded generation (BLOCK on VCS **and** a code index)\n\nPlanning and architecture tools — `generate_plan_direct`,\n`generate_architecture_direct`, `request_reimplement_context`,\n`code_writer_generate_plan`, `code_writer_generate_architecture`, and\n`create_doc` for **TDD** / **architecture** documents — ground their output in\nyour indexed codebase. They **BLOCK** until BOTH a VCS connection AND a\nsuccessful code index exist (`all_of`, with `code_index` in `missing`).\n\n### Council (BLOCK on a code index, mode-dependent)\n\n`request_council` in **technical** or **discovery** mode searches your indexed\ncodebase, so it **BLOCK**s on `code_index`. **Design**-mode brainstorming never\nqueries the index and is never gated.\n\n### Document generation that DEGRADEs (usable without codebase context)\n\nTools like `generate_prd_direct`, `generate_fsd_direct`,\n`code_writer_generate_fsd`, `generate_clarifying_questions_direct`,\n`generate_ticket_critique_direct`, `generate_ticket_review_direct`, and\n`create_doc` for **PRD** / **FSD** documents **DEGRADE** rather than block: they\nrun today from the ticket alone, and connecting VCS simply lets them ground their\noutput in your codebase. They always appear under \"Tools you can use now\", with a\nreduced-context caveat when the VCS connection is missing.\n\n### Never gated\n\nSetup and bootstrap tools (`ping`, `config_field`, `get_install_manifest`,\n`apply_install_manifest`, `get_my_role`, `persist_routing_credential`,\n`get_docs_dir`, and the bootstrap-invite exchange) are always available — they\nare how you configure everything else.\n",
5
+ "docs/install/sfcc-integration.md": "# Installing the SFCC Integration (OCAPI)\n\nBridge's Salesforce B2C Commerce (SFCC) tools give an AI coding agent read access to\na sandbox's object model, custom object definitions, and site preferences — plus a\nsmall set of sandbox-only writes — through the **OCAPI Data API**. This guide covers\nsetting up the OCAPI client that those tools authenticate against.\n\n> **Sandbox / local development only.** This integration is intended for a **developer\n> sandbox**. The tools reject non-sandbox instances, and the permissions grant below is\n> deliberately broad (all methods, all resources) — appropriate for a throwaway dev\n> sandbox, **never** for staging or production. Do not configure this grant on any\n> instance that holds real data. Credentials stay local (in `dw.json` or `SFCC_*` env\n> vars) and are never sent to Bridge.\n\nFor the full per-tool list and what each SFCC tool depends on, see\n[MCP Tool Integration Dependencies](./mcp-tool-integrations.md). For the tool reference\nand the `BRIDGE_MCP_PROFILE` gating, see the SFCC section of the\n[package README](../../README.md).\n\n## Prerequisites\n\n- A running SFCC **developer sandbox** and its hostname\n (e.g. `zzzz-001.sandbox.us01.dx.commercecloud.salesforce.com`).\n- An **Account Manager API client** — a `client-id` and `client-secret`. This is the\n OCAPI client the tools use to obtain an OAuth token. Create one in Account Manager\n (**API Client** → *Add API Client*) if you don't already have it, and note its\n `client_id`.\n- Business Manager access to the sandbox with permission to edit **Open Commerce API\n Settings**.\n\n## 1. Grant the OCAPI client access in Business Manager\n\nIn Business Manager for the sandbox:\n\n**Administration → Site Development → Open Commerce API Settings → Data API** tab.\n\nAdd the following client entry to the `clients` array of the Data API settings, then\n**Save**. This grants the client full read/write access to every Data API resource —\nacceptable only on a developer sandbox:\n\n```json\n{\n \"client_id\": \"<your-client-id-here>\",\n \"resources\": [\n {\n \"methods\": [\"get\", \"post\", \"put\", \"patch\", \"delete\"],\n \"read_attributes\": \"(**)\",\n \"write_attributes\": \"(**)\",\n \"resource_id\": \"/**\"\n }\n ]\n}\n```\n\nNotes:\n\n- The `client_id` **must match** the Account Manager API client whose credentials you\n put in `dw.json` / `SFCC_*` below. Replace the value above with your own client id if\n it differs.\n- If the Data API settings are empty, wrap the entry in the standard settings envelope:\n\n ```json\n {\n \"_v\": \"23.2\",\n \"clients\": [\n {\n \"client_id\": \"<your-client-id-here>\",\n \"resources\": [\n {\n \"methods\": [\"get\", \"post\", \"put\", \"patch\", \"delete\"],\n \"read_attributes\": \"(**)\",\n \"write_attributes\": \"(**)\",\n \"resource_id\": \"/**\"\n }\n ]\n }\n ]\n }\n ```\n\n- `check_permissions` (below) prints a ready-to-paste grant JSON on a 401/403, so you can\n also let the tool tell you exactly what to add.\n\n## 2. Provide credentials locally\n\nCreate a `dw.json` in your project root (auto-added to git exclude — never commit it):\n\n```json\n{\n \"hostname\": \"zzzz-001.sandbox.us01.dx.commercecloud.salesforce.com\",\n \"client-id\": \"<your-client-id-here>\",\n \"client-secret\": \"<account-manager-client-secret>\"\n}\n```\n\nAccepted key spellings: `hostname`/`host`, `client-id`/`clientId`/`client_id`,\n`client-secret`/`clientSecret`/`client_secret`. Prefer a single config — a multi-entry\n`configs[]` array forces an explicit `instance` on every call. Alternatively, export\n`SFCC_HOSTNAME` / `SFCC_CLIENT_ID` / `SFCC_CLIENT_SECRET` in the MCP server environment.\n\n## 3. Set the repo `version` config field\n\nSet the repo's `version` config to your SFCC project type — one of\n`sfra | pwakit | sitegenesis | storefrontnext | hybrid`. The call-time gate reads this;\na non-SFCC value blocks every SFCC tool except `sfcc_setup_status`. Set it via your\nnormal config path, the `config_field` MCP tool (operation `update`, field `version`),\nor the `/teach-bridge` skill.\n\n## 4. Enable the SFCC tools\n\nThe two diagnostic tools (`sfcc_setup_status`, `check_permissions`) are always\nregistered. The read tools, write tools, and `sfcc_log_query` are gated behind the\n`sfcc` profile. Add `sfcc` to `BRIDGE_MCP_PROFILE` in the MCP server `env` block (it is\ncomma-separated; `full` also works), then **restart the MCP client**:\n\n```json\n\"env\": { \"BRIDGE_MCP_PROFILE\": \"sfcc\" }\n```\n\n## 5. Verify\n\nAsk your agent to run:\n\n1. `sfcc_setup_status` — expect all prerequisite checks ✓ (Bridge API key, repo name,\n `version` config, `dw.json` presence/uniqueness, AM/OCAPI token acquisition).\n2. `check_permissions` — probes OCAPI via `GET /system_object_definitions`. A 200 (with\n the OCAPI version) confirms the grant. On 401/403 it prints the exact grant JSON to\n paste back in step 1.\n\nRestart the MCP client after any credential, grant, or env change — a running session\ndoes not pick them up.\n\n## Notes\n\n- **WebDAV logs are separate.** `sfcc_log_query` authenticates with a Business Manager\n username + a 40-character **WebDAV access key** over HTTP Basic auth — *not* the OCAPI\n OAuth token configured here. `sfcc_setup_status` reports OCAPI (step 5) and WebDAV\n (step 6) independently; one can be green while the other is not.\n- **Writes are sandbox-only.** The write tools (attribute/preference create/update) target\n a developer sandbox and echo a paste-ready grant JSON on a 403.\n"
5
6
  };
package/build/doctor.js CHANGED
@@ -20,7 +20,11 @@ import os from "os";
20
20
  import path from "path";
21
21
  import { createDefaultStartTicketsDeps } from "./start-tickets.js";
22
22
  import { VERSION } from "./version.generated.js";
23
- import { collectInstallStatusChecks, formatInstallStatusReport, } from "./install-doctor.js";
23
+ import { collectInstallStatusChecks, formatInstallStatusReport, resolveInstallDoctorTarget, } from "./install-doctor.js";
24
+ import { parseDefaultOnEnvFlag } from "./env-flags.js";
25
+ import { createBridgeApiUrls } from "./bridge-api-urls.js";
26
+ import { probeToolSurface } from "./tool-surface-gating.js";
27
+ import { resolveBapiCredentials } from "./credential-store.js";
24
28
  import { DEFAULT_AGENT_NAME, resolveAgentSpec, isAgentName, formatValidAgentNames, } from "./agent-registry.js";
25
29
  import { getDoctorPrereqDescriptors, probePrerequisite, } from "./start-tickets-prereqs.js";
26
30
  import { resolveProfiles } from "./mcp-profile.js";
@@ -51,6 +55,14 @@ export function getDoctorUsage() {
51
55
  "bootstrap-field completeness, and repository-indexing state. It performs",
52
56
  "read-only GETs only and never affects the exit code.",
53
57
  "",
58
+ "It also includes an advisory 'MCP tool surface' section (BAPI-641): what",
59
+ "dynamic capability gating would advertise for this repo. It performs at most",
60
+ "one read-only GET to /jira/mcp/tool-surface (none under the kill switch) and",
61
+ "is advisory/fail-open — a timeout or malformed response is reported as",
62
+ "'fail-open to full surface' and never affects the exit code. Clients that",
63
+ "ignore notifications/tools/list_changed must reconnect or start a new MCP",
64
+ "session to observe surface changes; no project MCP config change is required.",
65
+ "",
54
66
  "Conductor ledger / native-module diagnostics (the SQLite ledger's native",
55
67
  "binding load status and Node-version skew) live under a separate command:",
56
68
  " conductor doctor",
@@ -363,6 +375,111 @@ export function formatLauncherCacheReport(inspections) {
363
375
  }
364
376
  return lines.join("\n");
365
377
  }
378
+ /**
379
+ * Collect the read-only tool-surface diagnostic. Evaluates the kill switch first
380
+ * and returns without any network request when disabled. For an enabled flag and
381
+ * a resolved repo/credential, performs ONE 500 ms `probeToolSurface()` GET to the
382
+ * deployed route. Credential values live ONLY in the request headers and never in
383
+ * the returned result. Never throws.
384
+ */
385
+ export async function collectToolSurfaceDiagnostic(deps) {
386
+ const enabled = parseDefaultOnEnvFlag(deps.env.BAPI_MCP_TOOL_SURFACE_GATING_ENABLED);
387
+ if (!enabled) {
388
+ return { enabled: false, reason: "kill-switch" };
389
+ }
390
+ const target = await resolveInstallDoctorTarget(deps);
391
+ if (!target.repoName) {
392
+ return {
393
+ enabled: true,
394
+ reason: "unresolved",
395
+ detail: "no BAPI_REPO_NAME in the environment or project-local MCP configs",
396
+ };
397
+ }
398
+ const credDeps = {
399
+ env: deps.env,
400
+ homedir: deps.homedir,
401
+ platform: deps.platform,
402
+ readFile: deps.readFile,
403
+ stat: deps.stat,
404
+ stderr: () => { },
405
+ };
406
+ const cred = await resolveBapiCredentials(target.repoName, credDeps);
407
+ if (!cred.ok) {
408
+ return {
409
+ enabled: true,
410
+ reason: "unresolved",
411
+ detail: `no Bridge API credential resolved (${cred.kind})`,
412
+ };
413
+ }
414
+ const apiKey = cred.credentials.apiKey;
415
+ const urls = createBridgeApiUrls(target.baseUrl);
416
+ const url = urls.buildGetUrl("/mcp/tool-surface", {
417
+ repo_name: target.repoName,
418
+ });
419
+ const result = await probeToolSurface({
420
+ url,
421
+ resolveHeaders: async () => ({ "X-API-Key": apiKey }),
422
+ fetchFn: deps.fetch,
423
+ });
424
+ if (result.reason === "blocked") {
425
+ return {
426
+ enabled: true,
427
+ reason: "blocked",
428
+ blockedTools: Array.from(result.blockedTools),
429
+ catalogRevision: result.catalogRevision,
430
+ evaluatedToolCount: result.evaluatedToolCount,
431
+ };
432
+ }
433
+ if (result.reason === "timeout") {
434
+ return { enabled: true, reason: "timeout" };
435
+ }
436
+ return { enabled: true, reason: "malformed", subtype: result.subtype };
437
+ }
438
+ /**
439
+ * Render the advisory "MCP tool surface" section (pure formatting — no probing).
440
+ * States the kill-switch state, probe reachability, decision reason/subtype,
441
+ * fail-open behavior when applicable, blocked IDs/count/revision for a valid
442
+ * response, and clarifies that blocked IDs are intersected with the locally
443
+ * active profile and SDK-enabled baseline only when an MCP session starts.
444
+ */
445
+ export function formatToolSurfaceDiagnosticReport(diag) {
446
+ const lines = ["", "MCP tool surface (dynamic capability gating — advisory)", ""];
447
+ lines.push(`Kill switch: ${diag.enabled ? "ENABLED (gating active)" : "DISABLED (full surface)"}`);
448
+ switch (diag.reason) {
449
+ case "kill-switch":
450
+ lines.push("Reason: kill-switch — BAPI_MCP_TOOL_SURFACE_GATING_ENABLED is off, so the full profile surface is advertised and no probe is performed.");
451
+ break;
452
+ case "unresolved":
453
+ lines.push(`Reason: unresolved — ${diag.detail ?? "repo/credential not resolved"}; the probe was skipped and the full surface is advertised (fail-open to full surface).`);
454
+ break;
455
+ case "blocked": {
456
+ const ids = diag.blockedTools ?? [];
457
+ lines.push("Reason: blocked — the backend returned a valid capability decision.");
458
+ lines.push(`Probe: reachable (HTTP 200, valid response).`);
459
+ lines.push(`Blocked tools (${ids.length}): [${ids.join(", ")}]`);
460
+ if (diag.catalogRevision)
461
+ lines.push(`Catalog revision: ${diag.catalogRevision}`);
462
+ if (typeof diag.evaluatedToolCount === "number") {
463
+ lines.push(`Evaluated tool count: ${diag.evaluatedToolCount}`);
464
+ }
465
+ break;
466
+ }
467
+ case "timeout":
468
+ lines.push("Reason: timeout — the 500 ms probe deadline elapsed; fail-open to full surface.");
469
+ break;
470
+ case "malformed":
471
+ lines.push(`Reason: malformed (${diag.subtype ?? "unknown"}) — fail-open to full surface.`);
472
+ break;
473
+ }
474
+ lines.push("");
475
+ lines.push("Blocked IDs are intersected with the locally active MCP profile and the current SDK-enabled");
476
+ lines.push("baseline only when an MCP session starts, so IDs unknown to this package or excluded by the");
477
+ lines.push("active profile have no effect. Capability-hidden tools remain registered and callable — the");
478
+ lines.push("backend is the enforcement boundary. This section is advisory and never changes the exit code.");
479
+ lines.push("Clients that ignore notifications/tools/list_changed must reconnect or start a new MCP session");
480
+ lines.push("to observe surface changes; no project MCP configuration change is required.");
481
+ return lines.join("\n");
482
+ }
366
483
  /**
367
484
  * CLI entry for the read-only `doctor` subcommand. Returns a process exit code.
368
485
  * Help returns 0; parser errors return 1; otherwise it prints the report and
@@ -429,6 +546,36 @@ export async function runDoctorCli(argv, overrides = {}) {
429
546
  /* install-status diagnostics are advisory; never block the doctor report */
430
547
  }
431
548
  }
549
+ // Advisory MCP tool-surface capability section (BAPI-641). Strictly read-only:
550
+ // one 500 ms GET (or none, under the kill switch). Any timeout, malformed
551
+ // response, or unexpected throw degrades to a "fail-open to full surface" line
552
+ // and never affects the exit code, exactly like install-status above.
553
+ if (overrides.toolSurface !== false) {
554
+ try {
555
+ const injectedFs = deps;
556
+ const toolSurfaceDeps = {
557
+ env: overrides.toolSurface?.env ?? deps.env,
558
+ cwd: overrides.toolSurface?.cwd ?? deps.cwd,
559
+ platform: overrides.toolSurface?.platform ?? deps.platform,
560
+ homedir: overrides.toolSurface?.homedir ?? injectedFs.homedir ?? os.homedir,
561
+ readFile: overrides.toolSurface?.readFile ??
562
+ injectedFs.readFile ??
563
+ ((p) => readFile(p, "utf-8")),
564
+ stat: overrides.toolSurface?.stat ?? injectedFs.stat ?? ((p) => stat(p)),
565
+ fetch: overrides.toolSurface?.fetch ?? ((...args) => fetch(...args)),
566
+ };
567
+ const diagnostic = await collectToolSurfaceDiagnostic(toolSurfaceDeps);
568
+ log(formatToolSurfaceDiagnosticReport(diagnostic));
569
+ }
570
+ catch {
571
+ // Any unexpected failure still degrades to a sanitized advisory section.
572
+ log(formatToolSurfaceDiagnosticReport({
573
+ enabled: parseDefaultOnEnvFlag(deps.env.BAPI_MCP_TOOL_SURFACE_GATING_ENABLED),
574
+ reason: "malformed",
575
+ subtype: "unexpected",
576
+ }));
577
+ }
578
+ }
432
579
  if (!collection.ok)
433
580
  return 1;
434
581
  return collection.results.some((r) => !r.found) ? 1 : 0;
@@ -0,0 +1,31 @@
1
+ /**
2
+ * env-flags — shared parsing for default-ON boolean environment flags.
3
+ *
4
+ * Extracted from `index.ts` (BAPI-641) so normal server startup and the
5
+ * `doctor` diagnostic share ONE implementation of the default-on semantics.
6
+ * A default-on flag is enabled unless explicitly set to a recognized off-token,
7
+ * so an unknown value fails OPEN (enabled) rather than silently disabling a
8
+ * feature.
9
+ */
10
+ /** The recognized, case-insensitive off-tokens for a default-on flag. */
11
+ const OFF_TOKENS = new Set([
12
+ "false",
13
+ "0",
14
+ "no",
15
+ "off",
16
+ "disabled",
17
+ ]);
18
+ /**
19
+ * Parse a default-ON boolean env flag. `undefined` / blank → true; the
20
+ * normalized off-tokens (`false`, `0`, `no`, `off`, `disabled`) → false; any
21
+ * other value → true (preserving default-on / fail-open behavior). Matching is
22
+ * case-insensitive and trims surrounding whitespace.
23
+ */
24
+ export function parseDefaultOnEnvFlag(value) {
25
+ if (value === undefined)
26
+ return true;
27
+ const normalized = value.trim().toLowerCase();
28
+ if (normalized === "")
29
+ return true;
30
+ return !OFF_TOKENS.has(normalized);
31
+ }