@cyanmycelium/mcp-broker 1.3.3 → 1.4.0

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.
@@ -333,6 +333,40 @@ What happens when a provider connects to a slot another socket already holds.
333
333
 
334
334
  Also `MCP_BROKER_PROVIDER_TAKEOVER`.
335
335
 
336
+ ## Resource subscriptions
337
+
338
+ ```json
339
+ "resourceSubscriptions": {
340
+ "maxSubscriptionsPerClient": 64,
341
+ "maxSubscriptionsPerSlot": 1024,
342
+ "maxResourceUriLength": 2048
343
+ }
344
+ ```
345
+
346
+ When a client sends `resources/subscribe`, the broker answers it itself and
347
+ asks the provider only once per URI, however many clients watch it. It then
348
+ delivers `notifications/resources/updated` to the clients that subscribed to
349
+ that URI, and to nobody else. These three optional keys bound what clients can
350
+ make it hold; the values shown are the defaults.
351
+
352
+ ### `maxSubscriptionsPerClient`
353
+
354
+ How many URIs one client (a WebSocket, an SSE stream, a Streamable HTTP session)
355
+ may watch at once. Past it, the subscription is refused with `-32000`. Also
356
+ `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT`.
357
+
358
+ ### `maxSubscriptionsPerSlot`
359
+
360
+ How many client subscriptions one slot may hold in total. This is the bound that
361
+ matters for Streamable HTTP clients that close their tab without `DELETE`:
362
+ their sessions never expire, and neither do their subscriptions. Also
363
+ `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT`.
364
+
365
+ ### `maxResourceUriLength`
366
+
367
+ The longest URI accepted, in characters. A longer one is refused with `-32602`.
368
+ Also `MCP_BROKER_MAX_RESOURCE_URI_LENGTH`.
369
+
336
370
  ## TLS
337
371
 
338
372
  ```json
@@ -340,6 +340,41 @@ autre socket.
340
340
 
341
341
  Aussi `MCP_BROKER_PROVIDER_TAKEOVER`.
342
342
 
343
+ ## Abonnements aux ressources
344
+
345
+ ```json
346
+ "resourceSubscriptions": {
347
+ "maxSubscriptionsPerClient": 64,
348
+ "maxSubscriptionsPerSlot": 1024,
349
+ "maxResourceUriLength": 2048
350
+ }
351
+ ```
352
+
353
+ Quand un client envoie `resources/subscribe`, le broker y répond lui-même et ne
354
+ sollicite le fournisseur qu'une seule fois par URI, quel que soit le nombre de
355
+ clients qui la surveillent. Il remet ensuite `notifications/resources/updated`
356
+ aux seuls clients abonnés à cette URI. Ces trois clés facultatives bornent ce
357
+ que les clients peuvent lui faire conserver ; les valeurs montrées sont celles
358
+ par défaut.
359
+
360
+ ### `maxSubscriptionsPerClient`
361
+
362
+ Nombre d'URI qu'un même client (un WebSocket, un flux SSE, une session
363
+ Streamable HTTP) peut surveiller à la fois. Au-delà, l'abonnement est refusé
364
+ avec `-32000`. Aussi `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT`.
365
+
366
+ ### `maxSubscriptionsPerSlot`
367
+
368
+ Nombre total d'abonnements clients qu'un slot peut conserver. C'est la borne qui
369
+ compte pour les clients Streamable HTTP qui ferment leur onglet sans `DELETE` :
370
+ leurs sessions n'expirent jamais, leurs abonnements non plus. Aussi
371
+ `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT`.
372
+
373
+ ### `maxResourceUriLength`
374
+
375
+ Longueur maximale d'une URI, en caractères. Une URI plus longue est refusée avec
376
+ `-32602`. Aussi `MCP_BROKER_MAX_RESOURCE_URI_LENGTH`.
377
+
343
378
  ## TLS
344
379
 
345
380
  ```json
@@ -19,6 +19,12 @@
19
19
  "providerRequestTimeoutMs": 60000,
20
20
  "providerTakeover": "liveness",
21
21
 
22
+ "resourceSubscriptions": {
23
+ "maxSubscriptionsPerClient": 64,
24
+ "maxSubscriptionsPerSlot": 1024,
25
+ "maxResourceUriLength": 2048
26
+ },
27
+
22
28
  "tls": {
23
29
  "cert": "certs/cert.pem",
24
30
  "key": "certs/key.pem"
package/README.md CHANGED
@@ -225,6 +225,19 @@ Matching resources for clients that prefer `resources/read`: `broker://info`,
225
225
  `broker://providers`, the template `broker://providers/{name}`, the six
226
226
  `broker://guide/<topic>` pages and the template `broker://guide/{topic}`.
227
227
 
228
+ **Watch slots instead of polling.** `broker://providers` and
229
+ `broker://providers/<name>` accept `resources/subscribe`. A slot appearing, a
230
+ provider attaching or detaching, a slot joining or leaving `_all` each send
231
+ `notifications/resources/updated`; the counters never do, since reading moves
232
+ them. Reads are always live.
233
+
234
+ ```jsonc
235
+ // -> {"jsonrpc":"2.0","id":2,"method":"resources/subscribe","params":{"uri":"broker://providers"}}
236
+ // <- {"jsonrpc":"2.0","id":2,"result":{}}
237
+ // ...a provider connects:
238
+ // <- {"jsonrpc":"2.0","method":"notifications/resources/updated","params":{"uri":"broker://providers"}}
239
+ ```
240
+
228
241
  Each provider entry from `providers_list` / `provider_status`:
229
242
 
230
243
  ```json
@@ -237,7 +250,8 @@ Each provider entry from `providers_list` / `provider_status`:
237
250
  "connectedForMs": 184211,
238
251
  "clientCount": 0,
239
252
  "sessionCount": 1,
240
- "pendingCount": 0
253
+ "pendingCount": 0,
254
+ "resourceSubscriptionCount": 0
241
255
  }
242
256
  ```
243
257
 
@@ -256,6 +270,9 @@ Each provider entry from `providers_list` / `provider_status`:
256
270
  Streamable HTTP client reads as `clientCount: 0, sessionCount: 1`.
257
271
  - `pendingCount` is the number of in-flight requests. One that only grows is the
258
272
  signature of a provider that is connected and not answering.
273
+ - `resourceSubscriptionCount` is the client/URI pairs held by
274
+ `resources/subscribe`. One that only grows is HTTP clients leaving without
275
+ `DELETE`.
259
276
 
260
277
  ### `_all`, the aggregate
261
278
 
@@ -306,6 +323,44 @@ rejecting the call: a caller sees only the providers it is scoped for, and a
306
323
  tool it may not see answers `-32602 Unknown aggregated tool`, deliberately
307
324
  indistinguishable from a name that does not exist.
308
325
 
326
+ ## Resource subscriptions
327
+
328
+ `resources/subscribe` works on every slot except `_all`, over every client
329
+ transport. The broker owns the reference count between clients and provider:
330
+
331
+ - N clients on one URI cost the provider **one** `resources/subscribe`; the last
332
+ one leaving sends **one** `resources/unsubscribe`. Concurrent requests are
333
+ serialized per URI.
334
+ - `notifications/resources/updated` reaches only the sessions subscribed to that
335
+ exact `params.uri`. One without a usable `uri` is dropped and logged, never
336
+ broadcast. Every other notification is still broadcast to the slot.
337
+ - Closing a WebSocket or an SSE stream, `DELETE /<slot>/mcp`, closing stdio,
338
+ closing an in-process client from `openInternalClient()`, and stopping the
339
+ broker all release what the client held.
340
+ - When a provider reconnects, the broker replays the last client `initialize`,
341
+ then one subscribe per URI still held, then sends each subscriber one
342
+ `updated` so it re-reads. Install the provider's message handler before its
343
+ socket opens.
344
+ - `resources/subscribe` needs `mcp.resources.read` on the slot
345
+ (`broker.providers.read` on `_broker`); each update is re-checked per
346
+ recipient, and one that lost the grant is unsubscribed. `resources/unsubscribe`
347
+ is never refused.
348
+ - Limits: `resourceSubscriptions` in `config.json` (see
349
+ [config.md](docs/config.md#resourcesubscriptions)), or
350
+ `withResourceSubscriptionLimits()` on the builder.
351
+
352
+ A provider built on `@cyanmycelium/mcp-core` 1.3.0 or later answers
353
+ `resources/subscribe` itself; its behaviors only report changes:
354
+
355
+ ```ts
356
+ class GaugeAdapter extends McpAdapterBase {
357
+ set(value: number): void {
358
+ this._value = value;
359
+ this._forwardResourceContentChanged("plant://gauge"); // -> notifications/resources/updated, subscribers only
360
+ }
361
+ }
362
+ ```
363
+
309
364
  ## Authorization (OAuth 2.1)
310
365
 
311
366
  By default the broker performs **no** authentication. That is fine behind a
@@ -709,6 +764,9 @@ covers the failures the broker cannot see from the inside.
709
764
  | `-32602 Unknown aggregated tool` | the prefixed name was reconstructed rather than echoed | re-run `tools/list`, pass the name back verbatim |
710
765
  | `did not respond within 60000ms` | the provider stayed connected and never answered | raise `providerRequestTimeoutMs`, or fix the provider |
711
766
  | `sessionCount` grows and never falls | Streamable HTTP and SSE sessions do not expire | send `DELETE /<slot>/mcp` when a client is done; restart if it is already large |
767
+ | Subscribed, `notifications/resources/updated` never arrives | the update names another URI (exact match), carries no `params.uri` (dropped, logged once), or the read grant was revoked | compare URIs byte for byte; read the broker log |
768
+ | `resources/subscribe` answers `-32601` on a provider slot | the provider does not implement it (mcp-core before 1.3.0 did not) | upgrade the provider |
769
+ | `-32000 Subscription limit reached` | `maxSubscriptionsPerClient` or `maxSubscriptionsPerSlot` | unsubscribe what you no longer watch, or raise `resourceSubscriptions` |
712
770
 
713
771
  Reading the console: the broker prints one line per accepted WebSocket upgrade
714
772
  naming the path, the role the router assigned (`dedicated-provider`,
package/dist/bin.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { PACKAGE_NAME, VERSION, loadBrokerConfig, WsTunnelBuilder, loadMcpbBundle, BROKER_AGGREGATE_NAME, BROKER_PROVIDER_NAME, resolveOpenTarget } from './chunk-J5TN5RYU.js';
2
+ import { PACKAGE_NAME, VERSION, loadBrokerConfig, WsTunnelBuilder, loadMcpbBundle, BROKER_AGGREGATE_NAME, BROKER_PROVIDER_NAME, resolveOpenTarget } from './chunk-YTRVLPHP.js';
3
3
  import * as fs from 'fs';
4
4
  import * as path from 'path';
5
5
  import open from 'open';
@@ -107,6 +107,9 @@ envFromConfig("MCP_BROKER_SSE_PATH", config.paths?.sse);
107
107
  envFromConfig("MCP_BROKER_MESSAGES_PATH", config.paths?.messages);
108
108
  envFromConfig("MCP_BROKER_PROVIDER_HEARTBEAT_MS", config.providerHeartbeatIntervalMs);
109
109
  envFromConfig("MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS", config.providerRequestTimeoutMs);
110
+ envFromConfig("MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT", config.resourceSubscriptions?.maxSubscriptionsPerClient);
111
+ envFromConfig("MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT", config.resourceSubscriptions?.maxSubscriptionsPerSlot);
112
+ envFromConfig("MCP_BROKER_MAX_RESOURCE_URI_LENGTH", config.resourceSubscriptions?.maxResourceUriLength);
110
113
  envFromConfig("MCP_BROKER_PROVIDER_TAKEOVER", config.providerTakeover);
111
114
  envFromConfig("MCP_BROKER_OPEN", config.www?.open === true ? "1" : typeof config.www?.open === "string" ? config.www.open : void 0);
112
115
  envFromConfig("MCP_BROKER_AUTH_ENABLED", config.auth?.enabled === true ? "1" : void 0);
@@ -154,6 +157,21 @@ function millisFromEnv(envName) {
154
157
  }
155
158
  var providerHeartbeatIntervalMs = millisFromEnv("MCP_BROKER_PROVIDER_HEARTBEAT_MS");
156
159
  var providerRequestTimeoutMs = millisFromEnv("MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS");
160
+ function countFromEnv(envName) {
161
+ const raw = process.env[envName];
162
+ if (raw === void 0 || raw.trim() === "") return void 0;
163
+ const value = Number(raw);
164
+ if (!Number.isInteger(value) || value < 1) {
165
+ console.warn(`[mcp-broker] Ignoring ${envName}="${raw}": expected a whole number of at least 1. Using the default.`);
166
+ return void 0;
167
+ }
168
+ return value;
169
+ }
170
+ var resourceSubscriptionLimits = {
171
+ maxSubscriptionsPerClient: countFromEnv("MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT"),
172
+ maxSubscriptionsPerSlot: countFromEnv("MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT"),
173
+ maxResourceUriLength: countFromEnv("MCP_BROKER_MAX_RESOURCE_URI_LENGTH")
174
+ };
157
175
  var takeoverRaw = process.env["MCP_BROKER_PROVIDER_TAKEOVER"]?.trim().toLowerCase();
158
176
  var providerTakeover;
159
177
  if (takeoverRaw) {
@@ -210,6 +228,10 @@ async function main() {
210
228
  if (providerRequestTimeoutMs !== void 0) {
211
229
  builder.withProviderRequestTimeout(providerRequestTimeoutMs);
212
230
  }
231
+ const limits = Object.fromEntries(Object.entries(resourceSubscriptionLimits).filter(([, v]) => v !== void 0));
232
+ if (Object.keys(limits).length > 0) {
233
+ builder.withResourceSubscriptionLimits(limits);
234
+ }
213
235
  if (providerTakeover) {
214
236
  builder.withProviderTakeover(providerTakeover);
215
237
  }
package/dist/bin.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/bin.ts"],"names":[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AAE,eAAe,KAAA,CAAA,IAAU,CAAC,QAAQ,QAAA,CAAS,MAAA,CAAO,IAAI,CAAC,CAAA,EAAG;AAC5D,IAAA,OAAA,CAAQ,KAAA;AAAA,MACJ,CAAA,2CAAA,EAA8C,IAAA,IAAQ,SAAS,CAAA,MAAA,EAAS,IAAI,CAAA,uFAAA;AAAA,KAChF;AAAA,EACJ;AAEA,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAClB,CAAC,CAAA","file":"bin.js","sourcesContent":["#!/usr/bin/env node\n/**\n * Standalone entry-point that starts the mcp-broker WebSocket server.\n *\n * ## Configuration sources (highest priority first)\n *\n * 1. Environment variables (`MCP_BROKER_*`).\n * 2. JSON config file. Resolved in order:\n * a. `MCP_BROKER_CONFIG` env var.\n * b. `./.mcp-broker/config.json` in the current working directory.\n * c. `./mcp-broker.config.json` (legacy, with a deprecation warning).\n * 3. Built-in defaults.\n *\n * ## Path resolution\n *\n * - Env-var paths (`MCP_BROKER_*_DIR`, `MCP_BROKER_TLS_*`) are resolved\n * against `process.cwd()`.\n * - Config-file paths (`tls.cert`, `www.mounts[*].dir`, `stdioUpstreams[*]`,\n * `mcpbBundles[*]`) are resolved against the **config file's directory**: so a config in\n * `./.mcp-broker/config.json` referring to `\"certs/cert.pem\"` points at\n * `./.mcp-broker/certs/cert.pem`. The folder is self-contained.\n *\n * ## Local grammar overrides\n *\n * When `.mcp-broker/grammars/<userAgent>/<locale>.json` files exist next to\n * the config file, they are merged **on top of** the packaged grammars. Lets\n * users customize tool/resource descriptions for their organization without\n * forking the package.\n *\n * ## Environment variables\n *\n * | Variable | Default | Notes |\n * |--------------------------------|----------|--------------------------------------------------------|\n * | MCP_BROKER_CONFIG | (none) | Path to a JSON config file (see above). |\n * | MCP_BROKER_PORT | 3000 | |\n * | MCP_BROKER_HOST | 0.0.0.0 | |\n * | MCP_BROKER_PROVIDER_PATH | /provider| Prefix for one-slot-per-socket providers (plain frames)|\n * | MCP_BROKER_PROVIDERS_PATH |/providers| Exact path for multiplexed providers (envelope frames) |\n * | MCP_BROKER_CLIENT_PATH | / | Prefix for raw WS clients |\n * | MCP_BROKER_MCP_PATH | /mcp | Suffix for Streamable HTTP transport |\n * | MCP_BROKER_SSE_PATH | /sse | Suffix for the legacy SSE stream (GET) |\n * | MCP_BROKER_MESSAGES_PATH | /messages| Suffix for legacy SSE JSON-RPC posts |\n * | MCP_BROKER_WWW_DIR | (none) | Ergonomic shortcut: mount this directory at \"/\" |\n * | MCP_BROKER_BUNDLE_DIR | (none) | Ergonomic shortcut: mount this directory at \"/bundle\" |\n * | MCP_BROKER_OPEN | (unset) | \"1\" for the root URL, or a path/same-origin URL to open|\n * | MCP_BROKER_TLS_CERT | (none) | Path to a PEM TLS certificate |\n * | MCP_BROKER_TLS_KEY | (none) | Path to a PEM private key |\n * | MCP_BROKER_PROTOCOL | auto | \"http\" to force plain, \"https\" to force TLS, otherwise |\n * | | | TLS is enabled iff cert+key are both set |\n * | MCP_BROKER_STDIO_PROVIDER | (none) | When set, stdin/stdout carry JSON-RPC for the named |\n * | | | provider (Claude Desktop bridge). |\n * | MCP_BROKER_LOCALE | en | Locale used for tool descriptions on the `_broker` |\n * | | | slot. ISO 639-1 base; regional variants accepted. |\n * | MCP_BROKER_ALLOWED_ORIGINS | (none) | Comma-separated browser origins allowed on the client |\n * | | | HTTP surface (`/<slot>/mcp`, `/sse`, `/messages`). |\n * | | | None means no browser origin passes. |\n * | MCP_BROKER_PROVIDER_HEARTBEAT_MS | 30000 | Provider ws ping interval; 0 disables liveness. |\n * | MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS| 60000 | Deadline for one provider answer; 0 disables. |\n * | MCP_BROKER_PROVIDER_TAKEOVER | liveness | \"reject\" | \"liveness\" | \"always\" on slot contention |\n */\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport open from \"open\";\nimport { WsTunnelBuilder, VERSION, PACKAGE_NAME, BROKER_PROVIDER_NAME, BROKER_AGGREGATE_NAME, type ProviderTakeoverMode } from \"./index\";\nimport { loadBrokerConfig, resolveOpenTarget } from \"./config\";\nimport { loadMcpbBundle } from \"./mcpb/mcpb.loader\";\n\n// ---------------------------------------------------------------------------\n// CLI flags\n// ---------------------------------------------------------------------------\n// Handled before ANY other work (config load, logging, server start) so that\n// `--help` / `--version` never boot a server or bind a port.\n\nconst argv = process.argv.slice(2);\n\nif (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n printHelp();\n process.exit(0);\n}\nif (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n process.stdout.write(`${PACKAGE_NAME} ${VERSION}\\n`);\n process.exit(0);\n}\n\nfunction printHelp(): void {\n process.stdout.write(\n `\\n${PACKAGE_NAME} ${VERSION}\\n` +\n `WebSocket-based Model Context Protocol broker.\\n\\n` +\n `USAGE\\n` +\n ` npx @cyanmycelium/mcp-broker Start the broker (foreground)\\n` +\n ` npx @cyanmycelium/mcp-broker --help Show this help\\n` +\n ` npx @cyanmycelium/mcp-broker --version Print the version\\n\\n` +\n `The broker takes no positional arguments. Configure it with a\\n` +\n `.mcp-broker/config.json file or MCP_BROKER_* environment variables\\n` +\n `(env vars win over the file).\\n\\n` +\n `COMMON ENVIRONMENT VARIABLES\\n` +\n ` MCP_BROKER_CONFIG Path to a JSON config file\\n` +\n ` MCP_BROKER_PORT TCP port (default 3000)\\n` +\n ` MCP_BROKER_HOST Bind interface (default 0.0.0.0)\\n` +\n ` MCP_BROKER_PROTOCOL \"http\" | \"https\" (default: auto from TLS)\\n` +\n ` MCP_BROKER_TLS_CERT PEM certificate path (enables HTTPS/WSS)\\n` +\n ` MCP_BROKER_TLS_KEY PEM private key path\\n` +\n ` MCP_BROKER_STDIO_PROVIDER Bridge stdin/stdout to this provider (\"_all\" is the safe target)\\n` +\n ` MCP_BROKER_LOCALE Locale for _broker tool descriptions (default en)\\n` +\n ` MCP_BROKER_ALLOWED_ORIGINS Comma-separated browser origins allowed on /<slot>/mcp,\\n` +\n ` /<slot>/sse and /<slot>/messages (default: none pass)\\n` +\n ` MCP_BROKER_WWW_DIR Serve this directory at \"/\"\\n` +\n ` MCP_BROKER_BUNDLE_DIR Serve this directory at \"/bundle\"\\n` +\n ` MCP_BROKER_OPEN \"1\" to open the root in a browser, or a path such as /app/\\n\\n` +\n `ENDPOINT PATHS (change these only if every peer agrees)\\n` +\n ` MCP_BROKER_PROVIDER_PATH Prefix for one provider per socket (default /provider);\\n` +\n ` connect as <prefix>/<slot> with DirectTransport (plain frames)\\n` +\n ` MCP_BROKER_PROVIDERS_PATH Exact path for many providers on one socket (default /providers);\\n` +\n ` connect with MultiplexTransport (envelope frames)\\n` +\n ` MCP_BROKER_CLIENT_PATH Prefix for raw WebSocket clients (default /)\\n` +\n ` MCP_BROKER_MCP_PATH Streamable HTTP suffix (default /mcp)\\n` +\n ` MCP_BROKER_SSE_PATH Legacy SSE stream suffix (default /sse)\\n` +\n ` MCP_BROKER_MESSAGES_PATH Legacy SSE post suffix (default /messages)\\n\\n` +\n `PROVIDER LIVENESS\\n` +\n ` MCP_BROKER_PROVIDER_HEARTBEAT_MS Ping interval per provider socket (default 30000, 0 off)\\n` +\n ` MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS Deadline for one provider answer (default 60000, 0 off)\\n` +\n ` MCP_BROKER_PROVIDER_TAKEOVER reject | liveness | always (default liveness)\\n\\n` +\n `AUTHORIZATION (OAuth 2.1, opt-in)\\n` +\n ` MCP_BROKER_AUTH_ENABLED \"1\" to require bearer tokens on client endpoints\\n` +\n ` MCP_BROKER_PUBLIC_BASE_URL Public origin, e.g. https://mcp.example.com\\n` +\n ` MCP_BROKER_JWKS Authorization server JWKS URL\\n` +\n ` MCP_BROKER_ISSUER Expected token issuer\\n` +\n ` MCP_BROKER_PROVIDER_SECRET Shared secret required from providers\\n\\n` +\n `CONFIG-FILE ONLY (no env var; .mcp-broker/config.json)\\n` +\n ` stdioUpstreams[] Local MCP servers the broker spawns. NOT in _all unless \"aggregate\": true\\n` +\n ` mcpServers[] Remote MCP servers the broker dials out to. In _all unless \"aggregate\": false\\n` +\n ` mcpbBundles[] Signed .mcpb bundles, verified then spawned. In _all unless \"aggregate\": false\\n` +\n ` www.mounts[] Several urlPrefix -> dir mappings (the env vars above mount one each)\\n` +\n ` allowedOrigins Also accepts { \"pattern\": \"<regexp>\" }; the env var takes a list only\\n` +\n ` auth.* Roles, assignments, denies, per-slot and per-provider scopes\\n` +\n ` brokerName Library-only: no builder setter exists, so the CLI cannot forward it\\n\\n` +\n `RESERVED SLOTS (always present, no provider needed)\\n` +\n ` _broker Introspection: broker_info, providers_list, provider_status,\\n` +\n ` broker_guide (integration docs), broker_diagnose (live problem report)\\n` +\n ` _all Live aggregate of every opted-in provider. The right target for\\n` +\n ` MCP_BROKER_STDIO_PROVIDER, since it exists before any provider connects.\\n\\n` +\n `Start here: call broker_guide on the _broker slot for the integration guide.\\n` +\n `Full reference: https://github.com/pandaGaume/mcp-broker/tree/main/node\\n\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\n\nconst { config, baseDir } = loadBrokerConfig();\nconst cwd = process.cwd();\n\n/**\n * Fills an env var from the config file when the env var is not already set.\n * Used for **non-path** scalars, path-bearing fields are read directly so\n * they can be resolved against `baseDir` (config file's directory) instead\n * of `cwd` (deploy environment).\n */\nfunction envFromConfig(envName: string, configValue: string | number | boolean | undefined): void {\n if (configValue === undefined || configValue === null) return;\n if (process.env[envName] !== undefined && process.env[envName] !== \"\") return;\n process.env[envName] = String(configValue);\n}\n\nenvFromConfig(\"MCP_BROKER_PORT\", config.port);\nenvFromConfig(\"MCP_BROKER_HOST\", config.host);\nenvFromConfig(\"MCP_BROKER_PROTOCOL\", config.protocol);\nenvFromConfig(\"MCP_BROKER_LOCALE\", config.locale);\nenvFromConfig(\"MCP_BROKER_STDIO_PROVIDER\", config.stdioProvider);\nenvFromConfig(\"MCP_BROKER_PROVIDER_PATH\", config.paths?.provider);\nenvFromConfig(\"MCP_BROKER_PROVIDERS_PATH\", config.paths?.providers);\nenvFromConfig(\"MCP_BROKER_CLIENT_PATH\", config.paths?.client);\nenvFromConfig(\"MCP_BROKER_MCP_PATH\", config.paths?.mcp);\nenvFromConfig(\"MCP_BROKER_SSE_PATH\", config.paths?.sse);\nenvFromConfig(\"MCP_BROKER_MESSAGES_PATH\", config.paths?.messages);\nenvFromConfig(\"MCP_BROKER_PROVIDER_HEARTBEAT_MS\", config.providerHeartbeatIntervalMs);\nenvFromConfig(\"MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS\", config.providerRequestTimeoutMs);\nenvFromConfig(\"MCP_BROKER_PROVIDER_TAKEOVER\", config.providerTakeover);\n// `www.open` is `boolean | string`: `true` means the root, a string is a path\n// or a same-origin URL. Both travel as the env string and are resolved once,\n// by `resolveOpenTarget`, so the file and the env var cannot diverge.\nenvFromConfig(\"MCP_BROKER_OPEN\", config.www?.open === true ? \"1\" : typeof config.www?.open === \"string\" ? config.www.open : undefined);\nenvFromConfig(\"MCP_BROKER_AUTH_ENABLED\", config.auth?.enabled === true ? \"1\" : undefined);\nenvFromConfig(\"MCP_BROKER_PUBLIC_BASE_URL\", config.auth?.publicBaseUrl);\nenvFromConfig(\"MCP_BROKER_JWKS\", config.auth?.jwks);\nenvFromConfig(\"MCP_BROKER_ISSUER\", config.auth?.issuer);\nenvFromConfig(\"MCP_BROKER_PROVIDER_SECRET\", config.auth?.providerSecret);\n\nconst stdioProvider = process.env[\"MCP_BROKER_STDIO_PROVIDER\"];\n\n// In stdio mode stdout is reserved for JSON-RPC, redirect all console output to stderr.\nif (stdioProvider) {\n const toStderr = (...args: unknown[]) => process.stderr.write(args.join(\" \") + \"\\n\");\n console.log = toStderr;\n console.info = toStderr;\n console.warn = toStderr;\n console.error = toStderr;\n}\n\nconst port = parseInt(process.env[\"MCP_BROKER_PORT\"] ?? \"3000\", 10);\nconst host = process.env[\"MCP_BROKER_HOST\"];\n// ── Endpoint paths ───────────────────────────────────────────────────────────\n// All six resolve the same way (env, then config file, then the default) and all\n// six are handed to the builder. Before this, `paths.providers` and\n// `paths.messages` were read nowhere and `paths.sse` reached only the banner, so\n// setting one advertised an endpoint the router did not serve.\nconst providerPath = process.env[\"MCP_BROKER_PROVIDER_PATH\"] ?? \"/provider\";\nconst providersPath = process.env[\"MCP_BROKER_PROVIDERS_PATH\"] ?? \"/providers\";\nconst clientPath = process.env[\"MCP_BROKER_CLIENT_PATH\"] ?? \"/\";\nconst mcpPath = process.env[\"MCP_BROKER_MCP_PATH\"] ?? \"/mcp\";\nconst ssePath = process.env[\"MCP_BROKER_SSE_PATH\"] ?? \"/sse\";\nconst messagesPath = process.env[\"MCP_BROKER_MESSAGES_PATH\"] ?? \"/messages\";\n\n// ── TLS material ─────────────────────────────────────────────────────────────\n// Env var (relative to cwd) wins over config (relative to baseDir).\nconst tlsCertPath = process.env[\"MCP_BROKER_TLS_CERT\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_TLS_CERT\"]) : config.tls?.cert ? path.resolve(baseDir, config.tls.cert) : null;\nconst tlsKeyPath = process.env[\"MCP_BROKER_TLS_KEY\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_TLS_KEY\"]) : config.tls?.key ? path.resolve(baseDir, config.tls.key) : null;\n\nconst protocolOverride = process.env[\"MCP_BROKER_PROTOCOL\"]?.toLowerCase();\nif (protocolOverride !== undefined && protocolOverride !== \"http\" && protocolOverride !== \"https\") {\n console.error(`[mcp-broker] Invalid MCP_BROKER_PROTOCOL=\"${protocolOverride}\". Use \"http\" or \"https\".`);\n process.exit(1);\n}\nif (protocolOverride === \"https\" && (!tlsCertPath || !tlsKeyPath)) {\n console.error(\"[mcp-broker] MCP_BROKER_PROTOCOL=https requires TLS cert+key (via config.tls or MCP_BROKER_TLS_CERT/KEY).\");\n process.exit(1);\n}\n\nconst useTls = protocolOverride === \"http\" ? false : protocolOverride === \"https\" ? true : !!(tlsCertPath && tlsKeyPath);\n\n// ── Provider liveness knobs ──────────────────────────────────────────────────\n// The defaults are correct for nearly everyone; these exist for the operator who\n// has to tune them (long-running tools, a flaky link). An unusable value is\n// reported and ignored rather than silently coerced, so nobody believes a\n// setting is in force when it is not.\n\n/**\n * Parses a millisecond count from an env var. Returns `undefined` (keep the\n * built-in default) when unset or unusable, after saying why.\n */\nfunction millisFromEnv(envName: string): number | undefined {\n const raw = process.env[envName];\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n if (!Number.isFinite(value) || value < 0) {\n console.warn(`[mcp-broker] Ignoring ${envName}=\"${raw}\": expected a whole number of milliseconds (0 disables). Using the default.`);\n return undefined;\n }\n return Math.floor(value);\n}\n\nconst providerHeartbeatIntervalMs = millisFromEnv(\"MCP_BROKER_PROVIDER_HEARTBEAT_MS\");\nconst providerRequestTimeoutMs = millisFromEnv(\"MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS\");\n\nconst takeoverRaw = process.env[\"MCP_BROKER_PROVIDER_TAKEOVER\"]?.trim().toLowerCase();\nlet providerTakeover: ProviderTakeoverMode | undefined;\nif (takeoverRaw) {\n if (takeoverRaw === \"reject\" || takeoverRaw === \"liveness\" || takeoverRaw === \"always\") {\n providerTakeover = takeoverRaw;\n } else {\n console.warn(`[mcp-broker] Ignoring MCP_BROKER_PROVIDER_TAKEOVER=\"${takeoverRaw}\": expected \"reject\", \"liveness\" or \"always\". Using \"liveness\".`);\n }\n}\n\n// ── Allowed browser origins for the client HTTP surface ──────────────────────\n// Absent leaves the endpoint closed to browsers, which is the safe default.\n// The env var only carries the list form; a pattern needs the config file,\n// since a regular expression cannot survive comma-splitting.\nconst envOrigins = process.env[\"MCP_BROKER_ALLOWED_ORIGINS\"]\n ?.split(\",\")\n .map((origin) => origin.trim())\n .filter(Boolean);\n\nlet allowedOrigins: readonly string[] | RegExp | undefined;\nif (envOrigins?.length) {\n allowedOrigins = envOrigins;\n} else if (Array.isArray(config.allowedOrigins)) {\n allowedOrigins = config.allowedOrigins;\n} else if (config.allowedOrigins) {\n try {\n allowedOrigins = new RegExp(config.allowedOrigins.pattern, config.allowedOrigins.flags);\n } catch (err) {\n // Falling back to the closed default rather than starting with a rule\n // the operator believes is in force but which never compiled.\n console.error(`[mcp-broker] Ignoring allowedOrigins.pattern: ${(err as Error).message}`);\n }\n}\n\n/**\n * One-line rendering of the resolved origin policy for the startup banner.\n *\n * Worth a banner row because the closed default is invisible otherwise: a page\n * served by this very broker still gets a 403 on `/<slot>/mcp` unless its origin\n * is listed, and nothing else says so until the request fails.\n */\nfunction describeAllowedOrigins(): string {\n if (allowedOrigins instanceof RegExp) return `pattern ${String(allowedOrigins)}`;\n if (allowedOrigins && allowedOrigins.length > 0) return allowedOrigins.join(\", \");\n return \"none (set MCP_BROKER_ALLOWED_ORIGINS, or allowedOrigins in the config file). Requests carrying no Origin header (Claude Desktop, MCP Inspector, any server-side SDK) still pass\";\n}\n\n// ── Env-var static mount shortcuts (relative to cwd) ─────────────────────────\nconst envWwwDir = process.env[\"MCP_BROKER_WWW_DIR\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_WWW_DIR\"]) : null;\nconst envBundleDir = process.env[\"MCP_BROKER_BUNDLE_DIR\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_BUNDLE_DIR\"]) : null;\n\n/**\n * Warns when the stdio bridge is pinned to a slot this broker does not host.\n *\n * The bridge gates every frame, `initialize` included, on the slot being\n * occupied, so an MCP host that starts before the slot is claimed fails the\n * handshake and gives up: with a browser-hosted provider, which cannot be\n * connected before the host launches, this fails every single time. Naming the\n * slots the broker does have turns that into a one-line fix.\n *\n * Deliberately a warning, not an exit: a WebSocket provider may legitimately\n * claim the slot later, and a broker that refuses to start would be worse.\n */\nfunction warnIfStdioTargetUnknown(target: string): void {\n const known = new Set<string>([\n BROKER_AGGREGATE_NAME,\n BROKER_PROVIDER_NAME,\n ...(config.stdioUpstreams ?? []).map((u) => u.name),\n ...(config.mcpServers ?? []).map((s) => s.name),\n ...(config.mcpbBundles ?? []).map((b) => b.name),\n ]);\n if (known.has(target)) return;\n\n const hosted = [...known].filter((name) => name !== BROKER_AGGREGATE_NAME && name !== BROKER_PROVIDER_NAME);\n console.warn(\n `[mcp-broker] MCP_BROKER_STDIO_PROVIDER=\"${target}\" names a slot this broker does not host. ` +\n `Nothing answers on it until a WebSocket provider connects to ${providerPath}/${target} (or announces \"${target}\" on ${providersPath}), ` +\n `and until then every request from the MCP host, including the initial handshake, fails with 'Provider \"${target}\" not connected'. ` +\n `An MCP host that starts before that provider is up, which is always the case for a provider hosted in a browser page, will therefore never connect. ` +\n `Prefer MCP_BROKER_STDIO_PROVIDER=\"${BROKER_AGGREGATE_NAME}\": it exists from startup, answers the handshake itself, unions every opted-in provider, ` +\n `and pushes notifications/tools/list_changed as providers join, so a page opened later appears live. ` +\n `Slots this broker hosts right now: ${hosted.length > 0 ? hosted.map((n) => `\"${n}\"`).join(\", \") + `, plus the reserved \"${BROKER_AGGREGATE_NAME}\" and \"${BROKER_PROVIDER_NAME}\"` : `the reserved \"${BROKER_AGGREGATE_NAME}\" and \"${BROKER_PROVIDER_NAME}\" only`}.`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Server bootstrap\n// ---------------------------------------------------------------------------\n\nasync function main(): Promise<void> {\n // Local grammar overrides: when `<baseDir>/grammars/` exists, the broker\n // server merges those JSON files on top of the packaged grammars.\n const localGrammarsDir = path.join(baseDir, \"grammars\");\n const hasLocalGrammars = fs.existsSync(localGrammarsDir);\n\n const builder = new WsTunnelBuilder()\n .withPort(port)\n .withProviderPath(providerPath)\n .withProvidersPath(providersPath)\n .withClientPath(clientPath)\n .withMcpPath(mcpPath)\n .withSsePath(ssePath)\n .withMessagesPath(messagesPath);\n\n if (host) {\n builder.withHost(host);\n }\n\n if (providerHeartbeatIntervalMs !== undefined) {\n builder.withProviderHeartbeat(providerHeartbeatIntervalMs);\n }\n if (providerRequestTimeoutMs !== undefined) {\n builder.withProviderRequestTimeout(providerRequestTimeoutMs);\n }\n if (providerTakeover) {\n builder.withProviderTakeover(providerTakeover);\n }\n\n if (useTls) {\n // `withTlsFiles` reads both files synchronously and would otherwise\n // surface a bare ENOENT with no hint that TLS was on because a config\n // file mentioned it. That is the first wall a copied config template\n // hits, since the template ships `tls.cert`/`tls.key` but no `certs/`.\n try {\n builder.withTlsFiles(tlsCertPath!, tlsKeyPath!);\n } catch (err) {\n throw new Error(\n `TLS is enabled but the material could not be read: ${(err as Error).message}. ` +\n `Certificate: ${tlsCertPath}, key: ${tlsKeyPath}. ` +\n `Config-file paths are resolved against the config file's own directory, env-var paths against the current directory. ` +\n `Generate a development pair, point tls.cert/tls.key (or MCP_BROKER_TLS_CERT/MCP_BROKER_TLS_KEY) at real files, ` +\n `or run without TLS by removing the tls block and setting MCP_BROKER_PROTOCOL=http.`,\n { cause: err }\n );\n }\n }\n\n if (allowedOrigins) {\n builder.withAllowedOrigins(allowedOrigins);\n }\n\n // ── Static mounts ────────────────────────────────────────────────────────\n // First the env-var shortcuts (relative to cwd), then the config `www.mounts`\n // (relative to baseDir). Order matters: /bundle before / so the prefix router\n // can distinguish them. Subsequent registrations contribute additional mounts;\n // longest-prefix match wins at runtime.\n // Every prefix that actually got mounted, in registration order. The\n // browser-open check below tests the resolved path against this list rather\n // than against `config.www.mounts`, which would miss both env shortcuts and\n // would false-warn on a perfectly valid `open: \"/bundle/\"`.\n const mountedPrefixes: string[] = [];\n const mount = (urlPrefix: string, dir: string): void => {\n builder.withStaticMount(urlPrefix, dir);\n mountedPrefixes.push(urlPrefix);\n };\n\n if (envBundleDir && fs.existsSync(envBundleDir)) {\n mount(\"/bundle\", envBundleDir);\n }\n if (envWwwDir && fs.existsSync(envWwwDir)) {\n mount(\"/\", envWwwDir);\n }\n if (config.www?.mounts) {\n for (const entry of config.www.mounts) {\n const abs = path.resolve(baseDir, entry.dir);\n if (fs.existsSync(abs)) {\n mount(entry.urlPrefix, abs);\n } else {\n console.warn(`[mcp-broker] www.mounts entry \"${entry.urlPrefix}\" → ${abs} skipped (directory not found).`);\n }\n }\n }\n\n // ── Stdio upstreams ──────────────────────────────────────────────────────\n if (config.stdioUpstreams) {\n for (const u of config.stdioUpstreams) {\n builder.withStdioUpstream({\n name: u.name,\n command: u.command,\n args: u.args,\n env: u.env as NodeJS.ProcessEnv | undefined,\n aggregate: u.aggregate,\n });\n }\n }\n\n // ── Remote MCP server upstreams (reached by URL) ─────────────────────────\n // Config-discovered remote servers join the `_all` aggregate by default;\n // an explicit `aggregate: false` opts an entry out.\n if (config.mcpServers) {\n for (const s of config.mcpServers) {\n builder.withRemoteUpstream({ ...s, aggregate: s.aggregate ?? true });\n }\n }\n\n // ── Local `.mcpb` bundles ────────────────────────────────────────────────\n // Each bundle is signature-verified and unpacked before it is wired in as a\n // stdio upstream. A refused bundle is skipped (loadMcpbBundle logs why); it\n // never spawns a process. Bundles join `_all` by default (opt-out per entry).\n if (config.mcpbBundles) {\n for (const b of config.mcpbBundles) {\n const upstream = await loadMcpbBundle(b, baseDir);\n if (upstream) {\n builder.withStdioUpstream(upstream);\n }\n }\n }\n\n if (stdioProvider) {\n builder.withStdioClient(stdioProvider);\n warnIfStdioTargetUnknown(stdioProvider);\n }\n\n if (hasLocalGrammars) {\n builder.withBrokerLocalGrammarsDir(localGrammarsDir);\n }\n\n // ── Authorization (OAuth 2.1 resource server) ────────────────────────────\n // Opt-in: only wired when MCP_BROKER_AUTH_ENABLED / config.auth.enabled is on.\n // Env scalars win over config; array/object fields are read from config.\n const authEnabledEnv = process.env[\"MCP_BROKER_AUTH_ENABLED\"];\n const authEnabled = authEnabledEnv === \"1\" || authEnabledEnv === \"true\";\n if (authEnabled) {\n const publicBaseUrl = process.env[\"MCP_BROKER_PUBLIC_BASE_URL\"];\n const jwks = process.env[\"MCP_BROKER_JWKS\"];\n const issuer = process.env[\"MCP_BROKER_ISSUER\"];\n const authorizationServers = config.auth?.authorizationServers ?? (issuer ? [issuer] : []);\n if (!publicBaseUrl || !jwks || authorizationServers.length === 0) {\n console.error(\n \"[mcp-broker] auth.enabled requires publicBaseUrl, jwks, and at least one \" +\n \"authorizationServers entry (or issuer). Set them via config.auth or \" +\n \"MCP_BROKER_PUBLIC_BASE_URL / MCP_BROKER_JWKS / MCP_BROKER_ISSUER.\"\n );\n process.exit(1);\n }\n builder.withJwtAuth({\n publicBaseUrl,\n authorizationServers,\n jwksUri: jwks,\n issuer,\n scopesSupported: config.auth?.scopesSupported,\n requiredScopes: config.auth?.requiredScopes,\n perSlotScopes: config.auth?.perSlotScopes,\n providerScopes: config.auth?.providerScopes,\n subjectMapping: config.auth?.subjectMapping,\n roles: config.auth?.roles,\n assignments: config.auth?.assignments,\n denies: config.auth?.denies,\n slotResources: config.auth?.slotResources,\n toolCapabilities: config.auth?.toolCapabilities,\n providerToolCapabilities: config.auth?.providerToolCapabilities,\n audit: config.auth?.audit,\n });\n }\n\n // ── Provider authentication (independent of client OAuth) ────────────────\n // Requires every provider connecting to /provider/<slot> or /providers to\n // present the shared secret, closes off slot occupation by strangers.\n const providerSecret = process.env[\"MCP_BROKER_PROVIDER_SECRET\"];\n if (providerSecret) {\n builder.withProviderSecret(providerSecret);\n }\n\n const tunnel = builder.build();\n await tunnel.start();\n\n // ── Startup banner ──────────────────────────────────────────────────────\n const httpScheme = useTls ? \"https\" : \"http\";\n const wsScheme = useTls ? \"wss\" : \"ws\";\n const hr = \"─\".repeat(64);\n const localhost = `${httpScheme}://localhost:${port}`;\n const mcpSuffix = mcpPath.replace(/^\\//, \"\");\n const sseSuffix = ssePath.replace(/^\\//, \"\");\n const messagesSuffix = messagesPath.replace(/^\\//, \"\");\n\n // The two provider rows are the point of the banner: the endpoint chosen\n // decides the framing, and connecting the wrong transport to either one is\n // the single most common way an integration fails. So each row names the\n // transport class it requires, right there.\n console.log();\n console.log(`⚙️ mcp-broker started${useTls ? \" (TLS)\" : \"\"}`);\n console.log(hr);\n console.log(`📡 Provider WS direct ${wsScheme}://localhost:${port}${providerPath}/<name>`);\n console.log(` one provider per socket, plain JSON-RPC frames: use DirectTransport`);\n console.log(`🧵 Provider WS multiplex ${wsScheme}://localhost:${port}${providersPath}`);\n console.log(` many providers per socket, envelope frames: use MultiplexTransport`);\n console.log(`🔌 MCP (Streamable HTTP) ${localhost}/<name>/${mcpSuffix}`);\n console.log(`📺 Legacy SSE ${localhost}/<name>/${sseSuffix} + POST ${localhost}/<name>/${messagesSuffix}`);\n // Raw WS clients are a real, configurable route. Left off the banner it read\n // as provider-only, and `clientPath` reached the router and nothing else,\n // which is the same defect `paths.sse` had.\n console.log(`🔗 Client WS (raw) ${wsScheme}://localhost:${port}${clientPath === \"/\" ? \"/\" : clientPath}<name>`);\n console.log(` bare JSON-RPC frames, no session layer; not origin-checked`);\n console.log(`🧩 Reserved slots ${BROKER_AGGREGATE_NAME}: live aggregate of every opted-in provider`);\n console.log(` ${BROKER_PROVIDER_NAME}: broker_info, providers_list, provider_status, broker_guide, broker_diagnose`);\n if (mountedPrefixes.length > 0) {\n console.log(`📁 Static mounts ${mountedPrefixes.map((prefix) => `${localhost}${prefix === \"/\" ? \"/\" : prefix + \"/\"}`).join(\" \")}`);\n }\n if (hasLocalGrammars) {\n console.log(`🌐 Local grammars ${localGrammarsDir}`);\n }\n console.log(`🔐 Authorization ${authEnabled ? \"OAuth 2.1 (Bearer required)\" : \"disabled (trusted network only)\"}`);\n console.log(`🛡️ Provider auth ${providerSecret ? \"shared secret required\" : \"disabled\"}`);\n console.log(`🌍 Browser origins ${describeAllowedOrigins()}`);\n console.log(` enforced on /<name>/${mcpSuffix}, /<name>/${sseSuffix} and /<name>/${messagesSuffix}`);\n if (!allowedOrigins) {\n console.log(` a page this broker serves is refused too, list its origin to admit it`);\n }\n console.log(hr);\n console.log(` New here? Call broker_guide on the ${BROKER_PROVIDER_NAME} slot: ${localhost}/${BROKER_PROVIDER_NAME}/${mcpSuffix}`);\n console.log(` Press Ctrl+C to stop.`);\n console.log();\n\n // ── Auto-launch the browser ─────────────────────────────────────────────\n // Opt-in through MCP_BROKER_OPEN / www.open, and only onto a path a mount\n // actually serves: launching a browser at a 404 is worse than not launching.\n const openTarget = resolveOpenTarget(process.env[\"MCP_BROKER_OPEN\"], localhost);\n if (openTarget.error) {\n console.warn(`[mcp-broker] ${openTarget.error}`);\n } else if (openTarget.url && openTarget.path) {\n const openUrl = openTarget.url;\n const openPath = openTarget.path;\n const covered = mountedPrefixes.some((prefix) => prefix === \"/\" || openPath === prefix || openPath.startsWith(prefix.endsWith(\"/\") ? prefix : prefix + \"/\"));\n if (!covered) {\n console.warn(\n `[mcp-broker] Not opening ${openUrl}: no static mount serves \"${openPath}\", so it would 404. ` +\n (mountedPrefixes.length > 0\n ? `Mounted prefixes: ${mountedPrefixes.map((p) => `\"${p}\"`).join(\", \")}.`\n : `No directory is mounted. Add one with MCP_BROKER_WWW_DIR=<dir> (serves it at \"/\") or a www.mounts entry in the config file.`)\n );\n } else {\n console.log(`🚀 Opening browser: ${openUrl}`);\n console.log();\n try {\n await open(openUrl);\n } catch (err) {\n // The broker is listening and healthy; failing to spawn a browser\n // (a headless box, no default handler) must not take it down.\n console.warn(`[mcp-broker] Could not launch a browser for ${openUrl}: ${(err as Error).message}. The broker is running; open the URL yourself.`);\n }\n }\n }\n\n // ── Signal handlers ─────────────────────────────────────────────────────\n const shutdown = async (signal: string): Promise<void> => {\n console.log(`\\n⛔ ${signal} received, shutting down…`);\n await tunnel.stop();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\"));\n}\n\nmain().catch((err: unknown) => {\n // `tunnel.start()` now rejects on a listen failure instead of dying as an\n // uncaught EventEmitter error, so this path is live where it used to be\n // unreachable, and the rejection carries a fully worded diagnosis (for\n // EADDRINUSE: the address, the URL to attach to the broker that already\n // holds the port, and the MCP_BROKER_PORT escape). Print the sentence, not\n // the object: `console.error(\"…\", err)` renders a stack dump and buries it.\n //\n // In stdio mode console is redirected to stderr above, so this cannot\n // corrupt the JSON-RPC stream on stdout.\n const message = err instanceof Error ? err.message : String(err);\n console.error(`[mcp-broker] Cannot start: ${message}`);\n\n // A wrapped cause keeps the original errno for anyone reading a host log.\n const cause = err instanceof Error ? err.cause : undefined;\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n console.error(`[mcp-broker] Underlying error: ${code ? code + \" \" : \"\"}${cause.message}`);\n }\n\n // A bare Error with no diagnosis of its own is still worth grounding: say\n // where the broker was trying to listen, since that is the one fact the\n // reader needs to check next.\n if (!(err instanceof Error) || !message.includes(String(port))) {\n console.error(\n `[mcp-broker] Configuration in effect: host=${host ?? \"0.0.0.0\"} port=${port}. Set MCP_BROKER_PORT / MCP_BROKER_HOST, or \"port\" / \"host\" in .mcp-broker/config.json.`\n );\n }\n\n process.exit(1);\n});\n"]}
1
+ {"version":3,"sources":["../src/bin.ts"],"names":[],"mappings":";;;;;;AAyEA,IAAM,IAAA,GAAO,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AAEjC,IAAI,KAAK,QAAA,CAAS,QAAQ,KAAK,IAAA,CAAK,QAAA,CAAS,IAAI,CAAA,EAAG;AAChD,EAAA,SAAA,EAAU;AACV,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAClB;AACA,IAAI,KAAK,QAAA,CAAS,WAAW,KAAK,IAAA,CAAK,QAAA,CAAS,IAAI,CAAA,EAAG;AACnD,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA,CAAM,CAAA,EAAG,YAAY,IAAI,OAAO;AAAA,CAAI,CAAA;AACnD,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAClB;AAEA,SAAS,SAAA,GAAkB;AACvB,EAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,IACX;AAAA,EAAK,YAAY,IAAI,OAAO;AAAA;;AAAA;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;AAAA;A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AAQ,GAAA,CAAI,OAAA,GAAU,OAAO,GAAG,CAAA;AAC/D,EAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8B,OAAO,CAAA,CAAE,CAAA;AAGrD,EAAA,MAAM,KAAA,GAAQ,GAAA,YAAe,KAAA,GAAQ,GAAA,CAAI,KAAA,GAAQ,MAAA;AACjD,EAAA,IAAI,iBAAiB,KAAA,EAAO;AACxB,IAAA,MAAM,OAAQ,KAAA,CAAgC,IAAA;AAC9C,IAAA,OAAA,CAAQ,KAAA,CAAM,kCAAkC,IAAA,GAAO,IAAA,GAAO,MAAM,EAAE,CAAA,EAAG,KAAA,CAAM,OAAO,CAAA,CAAE,CAAA;AAAA,EAC5F;AAKA,EAAA,IAAI,EAAE,eAAe,KAAA,CAAA,IAAU,CAAC,QAAQ,QAAA,CAAS,MAAA,CAAO,IAAI,CAAC,CAAA,EAAG;AAC5D,IAAA,OAAA,CAAQ,KAAA;AAAA,MACJ,CAAA,2CAAA,EAA8C,IAAA,IAAQ,SAAS,CAAA,MAAA,EAAS,IAAI,CAAA,uFAAA;AAAA,KAChF;AAAA,EACJ;AAEA,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAClB,CAAC,CAAA","file":"bin.js","sourcesContent":["#!/usr/bin/env node\n/**\n * Standalone entry-point that starts the mcp-broker WebSocket server.\n *\n * ## Configuration sources (highest priority first)\n *\n * 1. Environment variables (`MCP_BROKER_*`).\n * 2. JSON config file. Resolved in order:\n * a. `MCP_BROKER_CONFIG` env var.\n * b. `./.mcp-broker/config.json` in the current working directory.\n * c. `./mcp-broker.config.json` (legacy, with a deprecation warning).\n * 3. Built-in defaults.\n *\n * ## Path resolution\n *\n * - Env-var paths (`MCP_BROKER_*_DIR`, `MCP_BROKER_TLS_*`) are resolved\n * against `process.cwd()`.\n * - Config-file paths (`tls.cert`, `www.mounts[*].dir`, `stdioUpstreams[*]`,\n * `mcpbBundles[*]`) are resolved against the **config file's directory**: so a config in\n * `./.mcp-broker/config.json` referring to `\"certs/cert.pem\"` points at\n * `./.mcp-broker/certs/cert.pem`. The folder is self-contained.\n *\n * ## Local grammar overrides\n *\n * When `.mcp-broker/grammars/<userAgent>/<locale>.json` files exist next to\n * the config file, they are merged **on top of** the packaged grammars. Lets\n * users customize tool/resource descriptions for their organization without\n * forking the package.\n *\n * ## Environment variables\n *\n * | Variable | Default | Notes |\n * |--------------------------------|----------|--------------------------------------------------------|\n * | MCP_BROKER_CONFIG | (none) | Path to a JSON config file (see above). |\n * | MCP_BROKER_PORT | 3000 | |\n * | MCP_BROKER_HOST | 0.0.0.0 | |\n * | MCP_BROKER_PROVIDER_PATH | /provider| Prefix for one-slot-per-socket providers (plain frames)|\n * | MCP_BROKER_PROVIDERS_PATH |/providers| Exact path for multiplexed providers (envelope frames) |\n * | MCP_BROKER_CLIENT_PATH | / | Prefix for raw WS clients |\n * | MCP_BROKER_MCP_PATH | /mcp | Suffix for Streamable HTTP transport |\n * | MCP_BROKER_SSE_PATH | /sse | Suffix for the legacy SSE stream (GET) |\n * | MCP_BROKER_MESSAGES_PATH | /messages| Suffix for legacy SSE JSON-RPC posts |\n * | MCP_BROKER_WWW_DIR | (none) | Ergonomic shortcut: mount this directory at \"/\" |\n * | MCP_BROKER_BUNDLE_DIR | (none) | Ergonomic shortcut: mount this directory at \"/bundle\" |\n * | MCP_BROKER_OPEN | (unset) | \"1\" for the root URL, or a path/same-origin URL to open|\n * | MCP_BROKER_TLS_CERT | (none) | Path to a PEM TLS certificate |\n * | MCP_BROKER_TLS_KEY | (none) | Path to a PEM private key |\n * | MCP_BROKER_PROTOCOL | auto | \"http\" to force plain, \"https\" to force TLS, otherwise |\n * | | | TLS is enabled iff cert+key are both set |\n * | MCP_BROKER_STDIO_PROVIDER | (none) | When set, stdin/stdout carry JSON-RPC for the named |\n * | | | provider (Claude Desktop bridge). |\n * | MCP_BROKER_LOCALE | en | Locale used for tool descriptions on the `_broker` |\n * | | | slot. ISO 639-1 base; regional variants accepted. |\n * | MCP_BROKER_ALLOWED_ORIGINS | (none) | Comma-separated browser origins allowed on the client |\n * | | | HTTP surface (`/<slot>/mcp`, `/sse`, `/messages`). |\n * | | | None means no browser origin passes. |\n * | MCP_BROKER_PROVIDER_HEARTBEAT_MS | 30000 | Provider ws ping interval; 0 disables liveness. |\n * | MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS| 60000 | Deadline for one provider answer; 0 disables. |\n * | MCP_BROKER_PROVIDER_TAKEOVER | liveness | \"reject\" | \"liveness\" | \"always\" on slot contention |\n */\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport open from \"open\";\nimport { WsTunnelBuilder, VERSION, PACKAGE_NAME, BROKER_PROVIDER_NAME, BROKER_AGGREGATE_NAME, type ProviderTakeoverMode } from \"./index\";\nimport { loadBrokerConfig, resolveOpenTarget } from \"./config\";\nimport { loadMcpbBundle } from \"./mcpb/mcpb.loader\";\n\n// ---------------------------------------------------------------------------\n// CLI flags\n// ---------------------------------------------------------------------------\n// Handled before ANY other work (config load, logging, server start) so that\n// `--help` / `--version` never boot a server or bind a port.\n\nconst argv = process.argv.slice(2);\n\nif (argv.includes(\"--help\") || argv.includes(\"-h\")) {\n printHelp();\n process.exit(0);\n}\nif (argv.includes(\"--version\") || argv.includes(\"-v\")) {\n process.stdout.write(`${PACKAGE_NAME} ${VERSION}\\n`);\n process.exit(0);\n}\n\nfunction printHelp(): void {\n process.stdout.write(\n `\\n${PACKAGE_NAME} ${VERSION}\\n` +\n `WebSocket-based Model Context Protocol broker.\\n\\n` +\n `USAGE\\n` +\n ` npx @cyanmycelium/mcp-broker Start the broker (foreground)\\n` +\n ` npx @cyanmycelium/mcp-broker --help Show this help\\n` +\n ` npx @cyanmycelium/mcp-broker --version Print the version\\n\\n` +\n `The broker takes no positional arguments. Configure it with a\\n` +\n `.mcp-broker/config.json file or MCP_BROKER_* environment variables\\n` +\n `(env vars win over the file).\\n\\n` +\n `COMMON ENVIRONMENT VARIABLES\\n` +\n ` MCP_BROKER_CONFIG Path to a JSON config file\\n` +\n ` MCP_BROKER_PORT TCP port (default 3000)\\n` +\n ` MCP_BROKER_HOST Bind interface (default 0.0.0.0)\\n` +\n ` MCP_BROKER_PROTOCOL \"http\" | \"https\" (default: auto from TLS)\\n` +\n ` MCP_BROKER_TLS_CERT PEM certificate path (enables HTTPS/WSS)\\n` +\n ` MCP_BROKER_TLS_KEY PEM private key path\\n` +\n ` MCP_BROKER_STDIO_PROVIDER Bridge stdin/stdout to this provider (\"_all\" is the safe target)\\n` +\n ` MCP_BROKER_LOCALE Locale for _broker tool descriptions (default en)\\n` +\n ` MCP_BROKER_ALLOWED_ORIGINS Comma-separated browser origins allowed on /<slot>/mcp,\\n` +\n ` /<slot>/sse and /<slot>/messages (default: none pass)\\n` +\n ` MCP_BROKER_WWW_DIR Serve this directory at \"/\"\\n` +\n ` MCP_BROKER_BUNDLE_DIR Serve this directory at \"/bundle\"\\n` +\n ` MCP_BROKER_OPEN \"1\" to open the root in a browser, or a path such as /app/\\n\\n` +\n `ENDPOINT PATHS (change these only if every peer agrees)\\n` +\n ` MCP_BROKER_PROVIDER_PATH Prefix for one provider per socket (default /provider);\\n` +\n ` connect as <prefix>/<slot> with DirectTransport (plain frames)\\n` +\n ` MCP_BROKER_PROVIDERS_PATH Exact path for many providers on one socket (default /providers);\\n` +\n ` connect with MultiplexTransport (envelope frames)\\n` +\n ` MCP_BROKER_CLIENT_PATH Prefix for raw WebSocket clients (default /)\\n` +\n ` MCP_BROKER_MCP_PATH Streamable HTTP suffix (default /mcp)\\n` +\n ` MCP_BROKER_SSE_PATH Legacy SSE stream suffix (default /sse)\\n` +\n ` MCP_BROKER_MESSAGES_PATH Legacy SSE post suffix (default /messages)\\n\\n` +\n `PROVIDER LIVENESS\\n` +\n ` MCP_BROKER_PROVIDER_HEARTBEAT_MS Ping interval per provider socket (default 30000, 0 off)\\n` +\n ` MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS Deadline for one provider answer (default 60000, 0 off)\\n` +\n ` MCP_BROKER_PROVIDER_TAKEOVER reject | liveness | always (default liveness)\\n\\n` +\n `AUTHORIZATION (OAuth 2.1, opt-in)\\n` +\n ` MCP_BROKER_AUTH_ENABLED \"1\" to require bearer tokens on client endpoints\\n` +\n ` MCP_BROKER_PUBLIC_BASE_URL Public origin, e.g. https://mcp.example.com\\n` +\n ` MCP_BROKER_JWKS Authorization server JWKS URL\\n` +\n ` MCP_BROKER_ISSUER Expected token issuer\\n` +\n ` MCP_BROKER_PROVIDER_SECRET Shared secret required from providers\\n\\n` +\n `CONFIG-FILE ONLY (no env var; .mcp-broker/config.json)\\n` +\n ` stdioUpstreams[] Local MCP servers the broker spawns. NOT in _all unless \"aggregate\": true\\n` +\n ` mcpServers[] Remote MCP servers the broker dials out to. In _all unless \"aggregate\": false\\n` +\n ` mcpbBundles[] Signed .mcpb bundles, verified then spawned. In _all unless \"aggregate\": false\\n` +\n ` www.mounts[] Several urlPrefix -> dir mappings (the env vars above mount one each)\\n` +\n ` allowedOrigins Also accepts { \"pattern\": \"<regexp>\" }; the env var takes a list only\\n` +\n ` auth.* Roles, assignments, denies, per-slot and per-provider scopes\\n` +\n ` brokerName Library-only: no builder setter exists, so the CLI cannot forward it\\n\\n` +\n `RESERVED SLOTS (always present, no provider needed)\\n` +\n ` _broker Introspection: broker_info, providers_list, provider_status,\\n` +\n ` broker_guide (integration docs), broker_diagnose (live problem report)\\n` +\n ` _all Live aggregate of every opted-in provider. The right target for\\n` +\n ` MCP_BROKER_STDIO_PROVIDER, since it exists before any provider connects.\\n\\n` +\n `Start here: call broker_guide on the _broker slot for the integration guide.\\n` +\n `Full reference: https://github.com/pandaGaume/mcp-broker/tree/main/node\\n\\n`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Configuration\n// ---------------------------------------------------------------------------\n\nconst { config, baseDir } = loadBrokerConfig();\nconst cwd = process.cwd();\n\n/**\n * Fills an env var from the config file when the env var is not already set.\n * Used for **non-path** scalars, path-bearing fields are read directly so\n * they can be resolved against `baseDir` (config file's directory) instead\n * of `cwd` (deploy environment).\n */\nfunction envFromConfig(envName: string, configValue: string | number | boolean | undefined): void {\n if (configValue === undefined || configValue === null) return;\n if (process.env[envName] !== undefined && process.env[envName] !== \"\") return;\n process.env[envName] = String(configValue);\n}\n\nenvFromConfig(\"MCP_BROKER_PORT\", config.port);\nenvFromConfig(\"MCP_BROKER_HOST\", config.host);\nenvFromConfig(\"MCP_BROKER_PROTOCOL\", config.protocol);\nenvFromConfig(\"MCP_BROKER_LOCALE\", config.locale);\nenvFromConfig(\"MCP_BROKER_STDIO_PROVIDER\", config.stdioProvider);\nenvFromConfig(\"MCP_BROKER_PROVIDER_PATH\", config.paths?.provider);\nenvFromConfig(\"MCP_BROKER_PROVIDERS_PATH\", config.paths?.providers);\nenvFromConfig(\"MCP_BROKER_CLIENT_PATH\", config.paths?.client);\nenvFromConfig(\"MCP_BROKER_MCP_PATH\", config.paths?.mcp);\nenvFromConfig(\"MCP_BROKER_SSE_PATH\", config.paths?.sse);\nenvFromConfig(\"MCP_BROKER_MESSAGES_PATH\", config.paths?.messages);\nenvFromConfig(\"MCP_BROKER_PROVIDER_HEARTBEAT_MS\", config.providerHeartbeatIntervalMs);\nenvFromConfig(\"MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS\", config.providerRequestTimeoutMs);\nenvFromConfig(\"MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT\", config.resourceSubscriptions?.maxSubscriptionsPerClient);\nenvFromConfig(\"MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT\", config.resourceSubscriptions?.maxSubscriptionsPerSlot);\nenvFromConfig(\"MCP_BROKER_MAX_RESOURCE_URI_LENGTH\", config.resourceSubscriptions?.maxResourceUriLength);\nenvFromConfig(\"MCP_BROKER_PROVIDER_TAKEOVER\", config.providerTakeover);\n// `www.open` is `boolean | string`: `true` means the root, a string is a path\n// or a same-origin URL. Both travel as the env string and are resolved once,\n// by `resolveOpenTarget`, so the file and the env var cannot diverge.\nenvFromConfig(\"MCP_BROKER_OPEN\", config.www?.open === true ? \"1\" : typeof config.www?.open === \"string\" ? config.www.open : undefined);\nenvFromConfig(\"MCP_BROKER_AUTH_ENABLED\", config.auth?.enabled === true ? \"1\" : undefined);\nenvFromConfig(\"MCP_BROKER_PUBLIC_BASE_URL\", config.auth?.publicBaseUrl);\nenvFromConfig(\"MCP_BROKER_JWKS\", config.auth?.jwks);\nenvFromConfig(\"MCP_BROKER_ISSUER\", config.auth?.issuer);\nenvFromConfig(\"MCP_BROKER_PROVIDER_SECRET\", config.auth?.providerSecret);\n\nconst stdioProvider = process.env[\"MCP_BROKER_STDIO_PROVIDER\"];\n\n// In stdio mode stdout is reserved for JSON-RPC, redirect all console output to stderr.\nif (stdioProvider) {\n const toStderr = (...args: unknown[]) => process.stderr.write(args.join(\" \") + \"\\n\");\n console.log = toStderr;\n console.info = toStderr;\n console.warn = toStderr;\n console.error = toStderr;\n}\n\nconst port = parseInt(process.env[\"MCP_BROKER_PORT\"] ?? \"3000\", 10);\nconst host = process.env[\"MCP_BROKER_HOST\"];\n// ── Endpoint paths ───────────────────────────────────────────────────────────\n// All six resolve the same way (env, then config file, then the default) and all\n// six are handed to the builder. Before this, `paths.providers` and\n// `paths.messages` were read nowhere and `paths.sse` reached only the banner, so\n// setting one advertised an endpoint the router did not serve.\nconst providerPath = process.env[\"MCP_BROKER_PROVIDER_PATH\"] ?? \"/provider\";\nconst providersPath = process.env[\"MCP_BROKER_PROVIDERS_PATH\"] ?? \"/providers\";\nconst clientPath = process.env[\"MCP_BROKER_CLIENT_PATH\"] ?? \"/\";\nconst mcpPath = process.env[\"MCP_BROKER_MCP_PATH\"] ?? \"/mcp\";\nconst ssePath = process.env[\"MCP_BROKER_SSE_PATH\"] ?? \"/sse\";\nconst messagesPath = process.env[\"MCP_BROKER_MESSAGES_PATH\"] ?? \"/messages\";\n\n// ── TLS material ─────────────────────────────────────────────────────────────\n// Env var (relative to cwd) wins over config (relative to baseDir).\nconst tlsCertPath = process.env[\"MCP_BROKER_TLS_CERT\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_TLS_CERT\"]) : config.tls?.cert ? path.resolve(baseDir, config.tls.cert) : null;\nconst tlsKeyPath = process.env[\"MCP_BROKER_TLS_KEY\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_TLS_KEY\"]) : config.tls?.key ? path.resolve(baseDir, config.tls.key) : null;\n\nconst protocolOverride = process.env[\"MCP_BROKER_PROTOCOL\"]?.toLowerCase();\nif (protocolOverride !== undefined && protocolOverride !== \"http\" && protocolOverride !== \"https\") {\n console.error(`[mcp-broker] Invalid MCP_BROKER_PROTOCOL=\"${protocolOverride}\". Use \"http\" or \"https\".`);\n process.exit(1);\n}\nif (protocolOverride === \"https\" && (!tlsCertPath || !tlsKeyPath)) {\n console.error(\"[mcp-broker] MCP_BROKER_PROTOCOL=https requires TLS cert+key (via config.tls or MCP_BROKER_TLS_CERT/KEY).\");\n process.exit(1);\n}\n\nconst useTls = protocolOverride === \"http\" ? false : protocolOverride === \"https\" ? true : !!(tlsCertPath && tlsKeyPath);\n\n// ── Provider liveness knobs ──────────────────────────────────────────────────\n// The defaults are correct for nearly everyone; these exist for the operator who\n// has to tune them (long-running tools, a flaky link). An unusable value is\n// reported and ignored rather than silently coerced, so nobody believes a\n// setting is in force when it is not.\n\n/**\n * Parses a millisecond count from an env var. Returns `undefined` (keep the\n * built-in default) when unset or unusable, after saying why.\n */\nfunction millisFromEnv(envName: string): number | undefined {\n const raw = process.env[envName];\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n if (!Number.isFinite(value) || value < 0) {\n console.warn(`[mcp-broker] Ignoring ${envName}=\"${raw}\": expected a whole number of milliseconds (0 disables). Using the default.`);\n return undefined;\n }\n return Math.floor(value);\n}\n\nconst providerHeartbeatIntervalMs = millisFromEnv(\"MCP_BROKER_PROVIDER_HEARTBEAT_MS\");\nconst providerRequestTimeoutMs = millisFromEnv(\"MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS\");\n\n/** Reads a positive whole number from the environment, or `undefined` (with a warning) for anything else. */\nfunction countFromEnv(envName: string): number | undefined {\n const raw = process.env[envName];\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1) {\n console.warn(`[mcp-broker] Ignoring ${envName}=\"${raw}\": expected a whole number of at least 1. Using the default.`);\n return undefined;\n }\n return value;\n}\n\nconst resourceSubscriptionLimits = {\n maxSubscriptionsPerClient: countFromEnv(\"MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT\"),\n maxSubscriptionsPerSlot: countFromEnv(\"MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT\"),\n maxResourceUriLength: countFromEnv(\"MCP_BROKER_MAX_RESOURCE_URI_LENGTH\"),\n};\n\nconst takeoverRaw = process.env[\"MCP_BROKER_PROVIDER_TAKEOVER\"]?.trim().toLowerCase();\nlet providerTakeover: ProviderTakeoverMode | undefined;\nif (takeoverRaw) {\n if (takeoverRaw === \"reject\" || takeoverRaw === \"liveness\" || takeoverRaw === \"always\") {\n providerTakeover = takeoverRaw;\n } else {\n console.warn(`[mcp-broker] Ignoring MCP_BROKER_PROVIDER_TAKEOVER=\"${takeoverRaw}\": expected \"reject\", \"liveness\" or \"always\". Using \"liveness\".`);\n }\n}\n\n// ── Allowed browser origins for the client HTTP surface ──────────────────────\n// Absent leaves the endpoint closed to browsers, which is the safe default.\n// The env var only carries the list form; a pattern needs the config file,\n// since a regular expression cannot survive comma-splitting.\nconst envOrigins = process.env[\"MCP_BROKER_ALLOWED_ORIGINS\"]\n ?.split(\",\")\n .map((origin) => origin.trim())\n .filter(Boolean);\n\nlet allowedOrigins: readonly string[] | RegExp | undefined;\nif (envOrigins?.length) {\n allowedOrigins = envOrigins;\n} else if (Array.isArray(config.allowedOrigins)) {\n allowedOrigins = config.allowedOrigins;\n} else if (config.allowedOrigins) {\n try {\n allowedOrigins = new RegExp(config.allowedOrigins.pattern, config.allowedOrigins.flags);\n } catch (err) {\n // Falling back to the closed default rather than starting with a rule\n // the operator believes is in force but which never compiled.\n console.error(`[mcp-broker] Ignoring allowedOrigins.pattern: ${(err as Error).message}`);\n }\n}\n\n/**\n * One-line rendering of the resolved origin policy for the startup banner.\n *\n * Worth a banner row because the closed default is invisible otherwise: a page\n * served by this very broker still gets a 403 on `/<slot>/mcp` unless its origin\n * is listed, and nothing else says so until the request fails.\n */\nfunction describeAllowedOrigins(): string {\n if (allowedOrigins instanceof RegExp) return `pattern ${String(allowedOrigins)}`;\n if (allowedOrigins && allowedOrigins.length > 0) return allowedOrigins.join(\", \");\n return \"none (set MCP_BROKER_ALLOWED_ORIGINS, or allowedOrigins in the config file). Requests carrying no Origin header (Claude Desktop, MCP Inspector, any server-side SDK) still pass\";\n}\n\n// ── Env-var static mount shortcuts (relative to cwd) ─────────────────────────\nconst envWwwDir = process.env[\"MCP_BROKER_WWW_DIR\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_WWW_DIR\"]) : null;\nconst envBundleDir = process.env[\"MCP_BROKER_BUNDLE_DIR\"] ? path.resolve(cwd, process.env[\"MCP_BROKER_BUNDLE_DIR\"]) : null;\n\n/**\n * Warns when the stdio bridge is pinned to a slot this broker does not host.\n *\n * The bridge gates every frame, `initialize` included, on the slot being\n * occupied, so an MCP host that starts before the slot is claimed fails the\n * handshake and gives up: with a browser-hosted provider, which cannot be\n * connected before the host launches, this fails every single time. Naming the\n * slots the broker does have turns that into a one-line fix.\n *\n * Deliberately a warning, not an exit: a WebSocket provider may legitimately\n * claim the slot later, and a broker that refuses to start would be worse.\n */\nfunction warnIfStdioTargetUnknown(target: string): void {\n const known = new Set<string>([\n BROKER_AGGREGATE_NAME,\n BROKER_PROVIDER_NAME,\n ...(config.stdioUpstreams ?? []).map((u) => u.name),\n ...(config.mcpServers ?? []).map((s) => s.name),\n ...(config.mcpbBundles ?? []).map((b) => b.name),\n ]);\n if (known.has(target)) return;\n\n const hosted = [...known].filter((name) => name !== BROKER_AGGREGATE_NAME && name !== BROKER_PROVIDER_NAME);\n console.warn(\n `[mcp-broker] MCP_BROKER_STDIO_PROVIDER=\"${target}\" names a slot this broker does not host. ` +\n `Nothing answers on it until a WebSocket provider connects to ${providerPath}/${target} (or announces \"${target}\" on ${providersPath}), ` +\n `and until then every request from the MCP host, including the initial handshake, fails with 'Provider \"${target}\" not connected'. ` +\n `An MCP host that starts before that provider is up, which is always the case for a provider hosted in a browser page, will therefore never connect. ` +\n `Prefer MCP_BROKER_STDIO_PROVIDER=\"${BROKER_AGGREGATE_NAME}\": it exists from startup, answers the handshake itself, unions every opted-in provider, ` +\n `and pushes notifications/tools/list_changed as providers join, so a page opened later appears live. ` +\n `Slots this broker hosts right now: ${hosted.length > 0 ? hosted.map((n) => `\"${n}\"`).join(\", \") + `, plus the reserved \"${BROKER_AGGREGATE_NAME}\" and \"${BROKER_PROVIDER_NAME}\"` : `the reserved \"${BROKER_AGGREGATE_NAME}\" and \"${BROKER_PROVIDER_NAME}\" only`}.`\n );\n}\n\n// ---------------------------------------------------------------------------\n// Server bootstrap\n// ---------------------------------------------------------------------------\n\nasync function main(): Promise<void> {\n // Local grammar overrides: when `<baseDir>/grammars/` exists, the broker\n // server merges those JSON files on top of the packaged grammars.\n const localGrammarsDir = path.join(baseDir, \"grammars\");\n const hasLocalGrammars = fs.existsSync(localGrammarsDir);\n\n const builder = new WsTunnelBuilder()\n .withPort(port)\n .withProviderPath(providerPath)\n .withProvidersPath(providersPath)\n .withClientPath(clientPath)\n .withMcpPath(mcpPath)\n .withSsePath(ssePath)\n .withMessagesPath(messagesPath);\n\n if (host) {\n builder.withHost(host);\n }\n\n if (providerHeartbeatIntervalMs !== undefined) {\n builder.withProviderHeartbeat(providerHeartbeatIntervalMs);\n }\n if (providerRequestTimeoutMs !== undefined) {\n builder.withProviderRequestTimeout(providerRequestTimeoutMs);\n }\n // Only the limits actually set: an `undefined` field would override the default.\n const limits = Object.fromEntries(Object.entries(resourceSubscriptionLimits).filter(([, v]) => v !== undefined));\n if (Object.keys(limits).length > 0) {\n builder.withResourceSubscriptionLimits(limits);\n }\n if (providerTakeover) {\n builder.withProviderTakeover(providerTakeover);\n }\n\n if (useTls) {\n // `withTlsFiles` reads both files synchronously and would otherwise\n // surface a bare ENOENT with no hint that TLS was on because a config\n // file mentioned it. That is the first wall a copied config template\n // hits, since the template ships `tls.cert`/`tls.key` but no `certs/`.\n try {\n builder.withTlsFiles(tlsCertPath!, tlsKeyPath!);\n } catch (err) {\n throw new Error(\n `TLS is enabled but the material could not be read: ${(err as Error).message}. ` +\n `Certificate: ${tlsCertPath}, key: ${tlsKeyPath}. ` +\n `Config-file paths are resolved against the config file's own directory, env-var paths against the current directory. ` +\n `Generate a development pair, point tls.cert/tls.key (or MCP_BROKER_TLS_CERT/MCP_BROKER_TLS_KEY) at real files, ` +\n `or run without TLS by removing the tls block and setting MCP_BROKER_PROTOCOL=http.`,\n { cause: err }\n );\n }\n }\n\n if (allowedOrigins) {\n builder.withAllowedOrigins(allowedOrigins);\n }\n\n // ── Static mounts ────────────────────────────────────────────────────────\n // First the env-var shortcuts (relative to cwd), then the config `www.mounts`\n // (relative to baseDir). Order matters: /bundle before / so the prefix router\n // can distinguish them. Subsequent registrations contribute additional mounts;\n // longest-prefix match wins at runtime.\n // Every prefix that actually got mounted, in registration order. The\n // browser-open check below tests the resolved path against this list rather\n // than against `config.www.mounts`, which would miss both env shortcuts and\n // would false-warn on a perfectly valid `open: \"/bundle/\"`.\n const mountedPrefixes: string[] = [];\n const mount = (urlPrefix: string, dir: string): void => {\n builder.withStaticMount(urlPrefix, dir);\n mountedPrefixes.push(urlPrefix);\n };\n\n if (envBundleDir && fs.existsSync(envBundleDir)) {\n mount(\"/bundle\", envBundleDir);\n }\n if (envWwwDir && fs.existsSync(envWwwDir)) {\n mount(\"/\", envWwwDir);\n }\n if (config.www?.mounts) {\n for (const entry of config.www.mounts) {\n const abs = path.resolve(baseDir, entry.dir);\n if (fs.existsSync(abs)) {\n mount(entry.urlPrefix, abs);\n } else {\n console.warn(`[mcp-broker] www.mounts entry \"${entry.urlPrefix}\" → ${abs} skipped (directory not found).`);\n }\n }\n }\n\n // ── Stdio upstreams ──────────────────────────────────────────────────────\n if (config.stdioUpstreams) {\n for (const u of config.stdioUpstreams) {\n builder.withStdioUpstream({\n name: u.name,\n command: u.command,\n args: u.args,\n env: u.env as NodeJS.ProcessEnv | undefined,\n aggregate: u.aggregate,\n });\n }\n }\n\n // ── Remote MCP server upstreams (reached by URL) ─────────────────────────\n // Config-discovered remote servers join the `_all` aggregate by default;\n // an explicit `aggregate: false` opts an entry out.\n if (config.mcpServers) {\n for (const s of config.mcpServers) {\n builder.withRemoteUpstream({ ...s, aggregate: s.aggregate ?? true });\n }\n }\n\n // ── Local `.mcpb` bundles ────────────────────────────────────────────────\n // Each bundle is signature-verified and unpacked before it is wired in as a\n // stdio upstream. A refused bundle is skipped (loadMcpbBundle logs why); it\n // never spawns a process. Bundles join `_all` by default (opt-out per entry).\n if (config.mcpbBundles) {\n for (const b of config.mcpbBundles) {\n const upstream = await loadMcpbBundle(b, baseDir);\n if (upstream) {\n builder.withStdioUpstream(upstream);\n }\n }\n }\n\n if (stdioProvider) {\n builder.withStdioClient(stdioProvider);\n warnIfStdioTargetUnknown(stdioProvider);\n }\n\n if (hasLocalGrammars) {\n builder.withBrokerLocalGrammarsDir(localGrammarsDir);\n }\n\n // ── Authorization (OAuth 2.1 resource server) ────────────────────────────\n // Opt-in: only wired when MCP_BROKER_AUTH_ENABLED / config.auth.enabled is on.\n // Env scalars win over config; array/object fields are read from config.\n const authEnabledEnv = process.env[\"MCP_BROKER_AUTH_ENABLED\"];\n const authEnabled = authEnabledEnv === \"1\" || authEnabledEnv === \"true\";\n if (authEnabled) {\n const publicBaseUrl = process.env[\"MCP_BROKER_PUBLIC_BASE_URL\"];\n const jwks = process.env[\"MCP_BROKER_JWKS\"];\n const issuer = process.env[\"MCP_BROKER_ISSUER\"];\n const authorizationServers = config.auth?.authorizationServers ?? (issuer ? [issuer] : []);\n if (!publicBaseUrl || !jwks || authorizationServers.length === 0) {\n console.error(\n \"[mcp-broker] auth.enabled requires publicBaseUrl, jwks, and at least one \" +\n \"authorizationServers entry (or issuer). Set them via config.auth or \" +\n \"MCP_BROKER_PUBLIC_BASE_URL / MCP_BROKER_JWKS / MCP_BROKER_ISSUER.\"\n );\n process.exit(1);\n }\n builder.withJwtAuth({\n publicBaseUrl,\n authorizationServers,\n jwksUri: jwks,\n issuer,\n scopesSupported: config.auth?.scopesSupported,\n requiredScopes: config.auth?.requiredScopes,\n perSlotScopes: config.auth?.perSlotScopes,\n providerScopes: config.auth?.providerScopes,\n subjectMapping: config.auth?.subjectMapping,\n roles: config.auth?.roles,\n assignments: config.auth?.assignments,\n denies: config.auth?.denies,\n slotResources: config.auth?.slotResources,\n toolCapabilities: config.auth?.toolCapabilities,\n providerToolCapabilities: config.auth?.providerToolCapabilities,\n audit: config.auth?.audit,\n });\n }\n\n // ── Provider authentication (independent of client OAuth) ────────────────\n // Requires every provider connecting to /provider/<slot> or /providers to\n // present the shared secret, closes off slot occupation by strangers.\n const providerSecret = process.env[\"MCP_BROKER_PROVIDER_SECRET\"];\n if (providerSecret) {\n builder.withProviderSecret(providerSecret);\n }\n\n const tunnel = builder.build();\n await tunnel.start();\n\n // ── Startup banner ──────────────────────────────────────────────────────\n const httpScheme = useTls ? \"https\" : \"http\";\n const wsScheme = useTls ? \"wss\" : \"ws\";\n const hr = \"─\".repeat(64);\n const localhost = `${httpScheme}://localhost:${port}`;\n const mcpSuffix = mcpPath.replace(/^\\//, \"\");\n const sseSuffix = ssePath.replace(/^\\//, \"\");\n const messagesSuffix = messagesPath.replace(/^\\//, \"\");\n\n // The two provider rows are the point of the banner: the endpoint chosen\n // decides the framing, and connecting the wrong transport to either one is\n // the single most common way an integration fails. So each row names the\n // transport class it requires, right there.\n console.log();\n console.log(`⚙️ mcp-broker started${useTls ? \" (TLS)\" : \"\"}`);\n console.log(hr);\n console.log(`📡 Provider WS direct ${wsScheme}://localhost:${port}${providerPath}/<name>`);\n console.log(` one provider per socket, plain JSON-RPC frames: use DirectTransport`);\n console.log(`🧵 Provider WS multiplex ${wsScheme}://localhost:${port}${providersPath}`);\n console.log(` many providers per socket, envelope frames: use MultiplexTransport`);\n console.log(`🔌 MCP (Streamable HTTP) ${localhost}/<name>/${mcpSuffix}`);\n console.log(`📺 Legacy SSE ${localhost}/<name>/${sseSuffix} + POST ${localhost}/<name>/${messagesSuffix}`);\n // Raw WS clients are a real, configurable route. Left off the banner it read\n // as provider-only, and `clientPath` reached the router and nothing else,\n // which is the same defect `paths.sse` had.\n console.log(`🔗 Client WS (raw) ${wsScheme}://localhost:${port}${clientPath === \"/\" ? \"/\" : clientPath}<name>`);\n console.log(` bare JSON-RPC frames, no session layer; not origin-checked`);\n console.log(`🧩 Reserved slots ${BROKER_AGGREGATE_NAME}: live aggregate of every opted-in provider`);\n console.log(` ${BROKER_PROVIDER_NAME}: broker_info, providers_list, provider_status, broker_guide, broker_diagnose`);\n if (mountedPrefixes.length > 0) {\n console.log(`📁 Static mounts ${mountedPrefixes.map((prefix) => `${localhost}${prefix === \"/\" ? \"/\" : prefix + \"/\"}`).join(\" \")}`);\n }\n if (hasLocalGrammars) {\n console.log(`🌐 Local grammars ${localGrammarsDir}`);\n }\n console.log(`🔐 Authorization ${authEnabled ? \"OAuth 2.1 (Bearer required)\" : \"disabled (trusted network only)\"}`);\n console.log(`🛡️ Provider auth ${providerSecret ? \"shared secret required\" : \"disabled\"}`);\n console.log(`🌍 Browser origins ${describeAllowedOrigins()}`);\n console.log(` enforced on /<name>/${mcpSuffix}, /<name>/${sseSuffix} and /<name>/${messagesSuffix}`);\n if (!allowedOrigins) {\n console.log(` a page this broker serves is refused too, list its origin to admit it`);\n }\n console.log(hr);\n console.log(` New here? Call broker_guide on the ${BROKER_PROVIDER_NAME} slot: ${localhost}/${BROKER_PROVIDER_NAME}/${mcpSuffix}`);\n console.log(` Press Ctrl+C to stop.`);\n console.log();\n\n // ── Auto-launch the browser ─────────────────────────────────────────────\n // Opt-in through MCP_BROKER_OPEN / www.open, and only onto a path a mount\n // actually serves: launching a browser at a 404 is worse than not launching.\n const openTarget = resolveOpenTarget(process.env[\"MCP_BROKER_OPEN\"], localhost);\n if (openTarget.error) {\n console.warn(`[mcp-broker] ${openTarget.error}`);\n } else if (openTarget.url && openTarget.path) {\n const openUrl = openTarget.url;\n const openPath = openTarget.path;\n const covered = mountedPrefixes.some((prefix) => prefix === \"/\" || openPath === prefix || openPath.startsWith(prefix.endsWith(\"/\") ? prefix : prefix + \"/\"));\n if (!covered) {\n console.warn(\n `[mcp-broker] Not opening ${openUrl}: no static mount serves \"${openPath}\", so it would 404. ` +\n (mountedPrefixes.length > 0\n ? `Mounted prefixes: ${mountedPrefixes.map((p) => `\"${p}\"`).join(\", \")}.`\n : `No directory is mounted. Add one with MCP_BROKER_WWW_DIR=<dir> (serves it at \"/\") or a www.mounts entry in the config file.`)\n );\n } else {\n console.log(`🚀 Opening browser: ${openUrl}`);\n console.log();\n try {\n await open(openUrl);\n } catch (err) {\n // The broker is listening and healthy; failing to spawn a browser\n // (a headless box, no default handler) must not take it down.\n console.warn(`[mcp-broker] Could not launch a browser for ${openUrl}: ${(err as Error).message}. The broker is running; open the URL yourself.`);\n }\n }\n }\n\n // ── Signal handlers ─────────────────────────────────────────────────────\n const shutdown = async (signal: string): Promise<void> => {\n console.log(`\\n⛔ ${signal} received, shutting down…`);\n await tunnel.stop();\n process.exit(0);\n };\n\n process.on(\"SIGINT\", () => void shutdown(\"SIGINT\"));\n process.on(\"SIGTERM\", () => void shutdown(\"SIGTERM\"));\n}\n\nmain().catch((err: unknown) => {\n // `tunnel.start()` now rejects on a listen failure instead of dying as an\n // uncaught EventEmitter error, so this path is live where it used to be\n // unreachable, and the rejection carries a fully worded diagnosis (for\n // EADDRINUSE: the address, the URL to attach to the broker that already\n // holds the port, and the MCP_BROKER_PORT escape). Print the sentence, not\n // the object: `console.error(\"…\", err)` renders a stack dump and buries it.\n //\n // In stdio mode console is redirected to stderr above, so this cannot\n // corrupt the JSON-RPC stream on stdout.\n const message = err instanceof Error ? err.message : String(err);\n console.error(`[mcp-broker] Cannot start: ${message}`);\n\n // A wrapped cause keeps the original errno for anyone reading a host log.\n const cause = err instanceof Error ? err.cause : undefined;\n if (cause instanceof Error) {\n const code = (cause as NodeJS.ErrnoException).code;\n console.error(`[mcp-broker] Underlying error: ${code ? code + \" \" : \"\"}${cause.message}`);\n }\n\n // A bare Error with no diagnosis of its own is still worth grounding: say\n // where the broker was trying to listen, since that is the one fact the\n // reader needs to check next.\n if (!(err instanceof Error) || !message.includes(String(port))) {\n console.error(\n `[mcp-broker] Configuration in effect: host=${host ?? \"0.0.0.0\"} port=${port}. Set MCP_BROKER_PORT / MCP_BROKER_HOST, or \"port\" / \"host\" in .mcp-broker/config.json.`\n );\n }\n\n process.exit(1);\n});\n"]}