@hediet/linkrpc-cli 0.0.3-next.20261101.1 → 0.0.3-next.20261102.2

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.
package/README.md CHANGED
@@ -579,7 +579,7 @@ it**. Pick one of:
579
579
  | Flag / env | Meaning |
580
580
  | -------------------------------- | ---------------------------------------------------------------------------------------------------------- |
581
581
  | `--endpoint <uri>` | A strict endpoint URI (see below). |
582
- | `--endpoint-cmd <command>` | Spawn a _server_, hand it a fresh socket + token via `LINKRPC_ENDPOINT`/`LINKRPC_TOKEN`, then connect to it. |
582
+ | `--endpoint-cmd <command>` | Spawn a _server_, hand it a fresh socket + token via `LINKRPC_ENDPOINT`/`LINKRPC_TOKEN`, then connect to it. With the hub profile, the server is a participant of an in-process hub and must claim its granted namespace (`local`) within 30 seconds. |
583
583
  | `--endpoint-cmd-stdio <command>` | Spawn a child and talk linkrpc over its stdio. |
584
584
  | `LINKRPC_ENDPOINT` (env) | A URI, or a legacy bare socket path / `ws://` URL. Token from `LINKRPC_TOKEN`; enabled by default in the Hub profile and with `--use-env` in the RPC profile. |
585
585
 
@@ -962,10 +962,14 @@ consent apply per tool; a forwarded server needs one capability for all its
962
962
  tools. Inaccessible directories and failed servers are reported on stderr;
963
963
  stdout contains only MCP protocol frames.
964
964
 
965
- `--scripts` additionally serves the LinkRPC script tools (`runLinkRpcScript`,
966
- `awaitLinkRpcTask`, `cancelLinkRpcTask`) of `@hediet/linkrpc-mcp` on the same
967
- connection, so one MCP entry gives both the hub's MCP tools and scripted access
968
- to every hub service.
965
+ `--mcp-identity <serviceId>=<identity>` (repeatable) uses another account of a
966
+ published MCP server than its default and lists only that account's tools.
967
+
968
+ The same MCP server also serves the LinkRPC script tools (`runLinkRpcScript`,
969
+ `awaitLinkRpcTask`, `cancelLinkRpcTask`) of `@hediet/linkrpc-mcp`, so one MCP
970
+ entry gives both the hub's MCP tools and scripted access to every hub service.
971
+ `--no-scripts` serves only the aggregated MCP tools and does not load the script
972
+ sandbox.
969
973
 
970
974
  The command watches directory changes, refreshes changed tool lists (including
971
975
  paginated lists), and retries failed connections while they remain advertised.
@@ -977,13 +981,21 @@ This version aggregates tools, not resources, prompts, or sampling.
977
981
  ### Publishing MCP servers
978
982
 
979
983
  Producers stay separate. `mcp-publish` publishes one MCP server, given as a
980
- command after `--`, as a Streamable HTTP `--url` (with repeatable `--header`),
981
- or (forward only) as `--stdio`:
984
+ command after `--`, as a Streamable HTTP `--url` (with repeatable `--header`,
985
+ or `--header-env <header>=<ENV_VAR>` to read a secret from the environment),
986
+ as `--mcp-config <file>`, or (forward only) as `--stdio`:
982
987
 
983
988
  ```sh
984
- linkrpc hub mcp-publish --service --forward --serviceId <authorized-service-id> -- npx -y @modelcontextprotocol/server-everything
989
+ linkrpc hub mcp-publish --service --forward --serviceId ./everything -- npx -y @modelcontextprotocol/server-everything
985
990
  ```
986
991
 
992
+ `--serviceId ./<name>` is relative: it claims `<granted namespace>/<name>` for
993
+ free when the connection has a granted serviceId namespace, and otherwise
994
+ requests `<user>@<host>/<name>` from the hub (an approval prompt). The command
995
+ logs the resolved service id. Without `--serviceId`, the granted namespace
996
+ itself is claimed; `tunnel` accepts relative service ids too. The command stops,
997
+ with a non-zero exit code, when its hub connection closes.
998
+
987
999
  - `--service` publishes the MCP server as a LinkRPC service: every MCP tool is
988
1000
  a method of a generated `mcp.tools.<name>` interface (`--name`, derived from
989
1001
  the service ID by default), and `mcp.tools::listTools`/`callTool` list and
@@ -994,6 +1006,24 @@ linkrpc hub mcp-publish --service --forward --serviceId <authorized-service-id>
994
1006
  `--group admin=delete,merge`.
995
1007
  - `--forward` relays MCP verbatim over `mcp.forward`. Each connection gets its
996
1008
  own MCP session: a fresh child process, or a new HTTP session.
1009
+ - `--mcp-config <file>` reads the server from JSON: `transport`, optional
1010
+ `identities` (accounts), `description`, `id`, and `expose` (flags override
1011
+ `expose`). Each identity adds env vars (stdio) or headers (HTTP); values can be
1012
+ `{ "fromEnv": "NAME" }`. Calls select an account with `mcpIdentity`:
1013
+
1014
+ ```json
1015
+ {
1016
+ "transport": { "kind": "streamable-http", "url": "https://api.githubcopilot.com/mcp/" },
1017
+ "identities": [
1018
+ { "id": "work", "headers": { "Authorization": { "fromEnv": "GITHUB_WORK_AUTHORIZATION" } } },
1019
+ { "id": "personal", "default": true, "headers": { "Authorization": { "fromEnv": "GITHUB_AUTHORIZATION" } } }
1020
+ ],
1021
+ "expose": { "service": {} }
1022
+ }
1023
+ ```
1024
+
1025
+ A capability pins an account with the parameter matcher
1026
+ `mcpIdentity: { "exact": "work" }`.
997
1027
  - `--stdio` forwards an MCP server that is already running and attached to this
998
1028
  process's stdin/stdout, one connection at a time. Later connections reach the
999
1029
  same server; the command exits when stdin ends.
@@ -1001,7 +1031,7 @@ linkrpc hub mcp-publish --service --forward --serviceId <authorized-service-id>
1001
1031
  `mcp-forward` is shorthand for `mcp-publish --forward`:
1002
1032
 
1003
1033
  ```sh
1004
- linkrpc hub mcp-forward --serviceId <authorized-service-id> -- component-explorer mcp -p <config> --use-daemon --no-daemon-autostart
1034
+ linkrpc hub mcp-forward --serviceId ./component-explorer -- component-explorer mcp -p <config> --use-daemon --no-daemon-autostart
1005
1035
  ```
1006
1036
 
1007
1037
  To forward a server that must not be restarted per connection, start it
@@ -1015,6 +1045,21 @@ the configured MCP child, so producers must use attach-only commands when
1015
1045
  heavyweight services are managed separately. Children inherit the producer's
1016
1046
  environment plus `--env` values.
1017
1047
 
1048
+ ### MCP servers without a running hub
1049
+
1050
+ With the hub profile, `--endpoint-cmd` runs the command as a participant of an
1051
+ in-process hub, so a publisher needs no hub daemon. Every hub client works
1052
+ against it, including the terminal UI:
1053
+
1054
+ ```sh
1055
+ linkrpc hub ui --endpoint-cmd "linkrpc hub mcp-publish --service -- npx -y @modelcontextprotocol/server-everything"
1056
+ linkrpc hub call local::mcp.tools.demo::echo --p:message=hi --endpoint-cmd "linkrpc hub mcp-publish --service --name demo -- node server.mjs"
1057
+ ```
1058
+
1059
+ The publisher claims the in-process hub's namespace `local`; its tools appear
1060
+ as methods of `local::mcp.tools.<name>`, with forms built from their input
1061
+ schemas. `mcp-publish` stops when its hub connection closes.
1062
+
1018
1063
  ### Participant proxy
1019
1064
 
1020
1065
  `proxy` stands in for a participant on the hub: the participant is either this
@@ -1,5 +1,5 @@
1
- import { $ as requestTopologyAccess, B as proxyCommand, Ct as MethodRefWithOptHash, F as disconnectBroker, G as parseDuration, H as withStaticHubReflection, I as getBrokerStatus, L as readBrokerNotifications, M as readEndpointDiscovery, N as ContextStore, P as formatContextReference, Q as requestReflectionAccess, R as stopConnectionBroker, St as parseParamOverride, U as parseConnectionLimit, V as tunnelCommand, W as parseConnectionLimitMilliseconds, _t as describeSchema, a as resolveInvocationEndpoint, c as resolveLocalEndpoint, ct as readCliIdentity, dt as connect, et as setupSigning, ft as connectViaRootOverlay, gt as describeObjectParams, ht as resolvedEndpointToConfig, i as resolveInvocationContext, it as walkHub, lt as formatPrincipalSource, m as managedEndpointsInterface, mt as resolveTargetEndpoint, n as loadStaticHubSchema, nt as fetchSchema$1, o as resolveSigning, ot as cliIdentityTarget, pt as connectViaTransport, q as resolveCliInvocation, r as resolveStaticHubSchemaSource, rt as findMethodInSchema, s as validationDefault, st as deleteCliIdentity, t as completeForLine, tt as fetchDefaults, ut as parsePrincipalSpec, vt as explainValidation, xt as mergeParams, y as HubHome, yt as validateValueAgainstSchema, z as ConnectionBroker } from "./runComplete-haCYSPzH.js";
2
- import { HubMcpAggregator, McpToolHost, hostMcpServer, mcpServerConfigSchema, serveMcpForwardInstance, streamInstanceTransport } from "@hediet/linkrpc-mcp/hub";
1
+ import { B as proxyCommand, Ct as mergeParams, F as disconnectBroker, G as parseConnectionLimit, H as claimServiceId, I as getBrokerStatus, K as parseConnectionLimitMilliseconds, L as readBrokerNotifications, M as readEndpointDiscovery, N as ContextStore, P as formatContextReference, R as stopConnectionBroker, Tt as MethodRefWithOptHash, U as resolveServiceIdToClaim, V as tunnelCommand, W as withStaticHubReflection, Y as resolveCliInvocation, _t as resolvedEndpointToConfig, a as resolveInvocationEndpoint, at as findMethodInSchema, bt as explainValidation, c as resolveLocalEndpoint, ct as cliIdentityTarget, dt as formatPrincipalSource, et as requestReflectionAccess, ft as parsePrincipalSpec, gt as resolveTargetEndpoint, ht as connectViaTransport, i as resolveInvocationContext, it as fetchSchema$1, lt as deleteCliIdentity, m as managedEndpointsInterface, mt as connectViaRootOverlay, n as loadStaticHubSchema, nt as setupSigning, o as resolveSigning, ot as walkHub, pt as connect, q as parseDuration, r as resolveStaticHubSchemaSource, rt as fetchDefaults, s as validationDefault, t as completeForLine, tt as requestTopologyAccess, ut as readCliIdentity, vt as describeObjectParams, wt as parseParamOverride, xt as validateValueAgainstSchema, y as HubHome, yt as describeSchema, z as ConnectionBroker } from "./runComplete-BWhPmSgi.js";
2
+ import { HubMcpAggregator, McpToolHost, hostMcpServer, mcpExposeConfigSchema, mcpServerConfigSchema, serveMcpForwardInstance, streamInstanceTransport } from "@hediet/linkrpc-mcp/hub";
3
3
  import { ErrorCode, INTERFACE_TEMPLATES_EXTENSION, LinkRpcConnection, RpcError, computeInterfaceHash, connectTransports, createSchemaToZod, directoryInterface, exportStaticHubSchema, generateTsContract, generateTsInterface, interfaceTemplateArgumentsEquivalent, interfaceTemplateMemberName, interfaceTemplatesEqual, isAssignable, jcsCanonicalize, matchParams, schemaToZod, validateInterfaceTemplates } from "@hediet/linkrpc";
4
4
  import { WebSocketTransport, connectNdjson, connectToHub, formatEndpointUri, isHubEndpoint, openWebSocket, parseEndpointUri, runInitializeHandshake, traceMessageTransport as traceMessageTransport$1 } from "@hediet/linkrpc/node";
5
5
  import { SocketServer } from "@hediet/linkrpc-hub/hub/server/node";
@@ -412,7 +412,7 @@ function contextNamespace(reference) {
412
412
  async function useLocalManagement(start, action) {
413
413
  const home = HubHome.resolve();
414
414
  if (start) {
415
- const { startDaemon, nodeDaemonLaunch } = await import("./src-DSdS3hm7.js");
415
+ const { startDaemon, nodeDaemonLaunch } = await import("./src-DIsGc3Ft.js");
416
416
  if (await startDaemon({
417
417
  home,
418
418
  launch: nodeDaemonLaunch(home)
@@ -432,7 +432,7 @@ async function useLocalManagement(start, action) {
432
432
  }
433
433
  }
434
434
  async function restartLocalDaemon() {
435
- const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import("./src-DSdS3hm7.js");
435
+ const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import("./src-DIsGc3Ft.js");
436
436
  const home = HubHome.resolve();
437
437
  process.stderr.write("Restarting the local Hub daemon: clients will disconnect and managed workloads will stop. OS autostart settings are unchanged.\n");
438
438
  await stopDaemon(home);
@@ -3382,21 +3382,18 @@ function _unlink(socketPath) {
3382
3382
  //#endregion
3383
3383
  //#region src/commands/mcpPublish.ts
3384
3384
  /**
3385
- * Front door for claiming a serviceId within the connection's granted
3386
- * namespace — interface-form `hubGrantedServiceId::register`. Same claim the
3387
- * `tunnel` command uses.
3388
- */
3389
- const CLAIM_METHOD = `${hubGrantedServiceIdInterface.info.id}::register`;
3390
- /** Read-only connection facts — `hubGrantedServiceId::get`. */
3391
- const INFO_METHOD = `${hubGrantedServiceIdInterface.info.id}::get`;
3392
- /**
3393
3385
  * Publish one MCP server on the hub until stopped: as a service (one LinkRPC
3394
3386
  * method per tool plus generic `mcp.tools`, one shared MCP session), forwarded
3395
3387
  * (verbatim MCP over `mcp.forward`), or both.
3396
3388
  */
3397
3389
  async function mcpPublishCommand(opts) {
3398
3390
  const log = opts.log ?? ((line) => process.stderr.write(line + "\n"));
3399
- const serviceId = opts.serviceId ?? await _resolveGrantedServiceId(opts.local);
3391
+ const stop = Promise.race([opts.stop ?? _untilSignalled$1(), opts.local.closed.then(() => {
3392
+ log("mcp-publish: the hub connection closed");
3393
+ process.exitCode = 1;
3394
+ })]);
3395
+ const resolved = await resolveServiceIdToClaim(opts.local, opts.serviceId);
3396
+ const serviceId = resolved.serviceId;
3400
3397
  const connection = new LinkRpcConnection(opts.local.rpcChannel);
3401
3398
  if (opts.transport.kind === "own-stdio") {
3402
3399
  if (opts.expose.service !== void 0 || opts.expose.forward === void 0) throw new Error("mcp-publish: an MCP server on this process's stdio can only be forwarded.");
@@ -3407,9 +3404,9 @@ async function mcpPublishCommand(opts) {
3407
3404
  log
3408
3405
  });
3409
3406
  try {
3410
- await opts.local.channel.sendRequest(CLAIM_METHOD, { serviceId });
3407
+ await claimServiceId(opts.local, serviceId);
3411
3408
  log(`mcp-publish: claimed '${serviceId}' — forwarding the MCP server on stdio to one connection at a time`);
3412
- await Promise.race([instance.closed, opts.stop ?? _untilSignalled$1()]);
3409
+ await Promise.race([instance.closed, stop]);
3413
3410
  log("mcp-publish: stopping");
3414
3411
  } finally {
3415
3412
  instance.dispose();
@@ -3421,33 +3418,46 @@ async function mcpPublishCommand(opts) {
3421
3418
  connection,
3422
3419
  serviceId,
3423
3420
  server: mcpServerConfigSchema.parse({
3424
- id: opts.name ?? interfaceNameFor(serviceId),
3421
+ id: opts.name ?? interfaceNameFor(resolved.relative ?? serviceId),
3422
+ ...opts.description !== void 0 ? { description: opts.description } : {},
3425
3423
  transport,
3424
+ ...opts.identities !== void 0 ? { identities: opts.identities } : {},
3426
3425
  expose: opts.expose
3427
3426
  }),
3428
3427
  log,
3429
3428
  onRefreshError: (error) => log(`mcp-publish: tool refresh failed: ${error instanceof Error ? error.message : String(error)}`)
3430
3429
  });
3431
3430
  try {
3432
- await opts.local.channel.sendRequest(CLAIM_METHOD, { serviceId });
3431
+ await claimServiceId(opts.local, serviceId);
3433
3432
  const modes = [opts.expose.service && "as a service", opts.expose.forward && "forwarded"].filter(Boolean).join(" and ");
3434
3433
  log(`mcp-publish: claimed '${serviceId}' — publishing ${_describe(transport)} ${modes}`);
3435
- await (opts.stop ?? _untilSignalled$1());
3434
+ await stop;
3436
3435
  log("mcp-publish: stopping");
3437
3436
  } finally {
3438
3437
  await hosted.dispose();
3439
3438
  }
3440
3439
  }
3440
+ /** `mcp-publish --mcp-config` file: a server config whose `id` and `expose` may come from flags. */
3441
+ const mcpPublishConfigSchema = mcpServerConfigSchema.extend({
3442
+ id: mcpServerConfigSchema.shape.id.optional(),
3443
+ expose: mcpExposeConfigSchema.optional()
3444
+ });
3445
+ async function readMcpPublishConfig(path) {
3446
+ let json;
3447
+ try {
3448
+ json = JSON.parse(await readFile(path, "utf8"));
3449
+ } catch (error) {
3450
+ throw new Error(`mcp-publish: cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`);
3451
+ }
3452
+ const parsed = mcpPublishConfigSchema.safeParse(json);
3453
+ if (!parsed.success) throw new Error(`mcp-publish: invalid ${path}: ${parsed.error.message}`);
3454
+ return parsed.data;
3455
+ }
3441
3456
  /** A valid `mcp.tools.<name>` suffix for `serviceId`, e.g. `my/MCP_server` → `my.mcp-server`. */
3442
3457
  function interfaceNameFor(serviceId) {
3443
3458
  const name = serviceId.toLowerCase().replace(/[^a-z0-9.-]+/g, ".").replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, "");
3444
3459
  return name.length > 0 ? name : "server";
3445
3460
  }
3446
- async function _resolveGrantedServiceId(local) {
3447
- const granted = (await local.channel.sendRequest(INFO_METHOD, {}))?.grantedServiceIdNamespace ?? "";
3448
- if (granted.length === 0) throw new Error("mcp-publish: this connection has no granted serviceId namespace to claim; pass an explicit --serviceId.");
3449
- return granted;
3450
- }
3451
3461
  function _untilSignalled$1() {
3452
3462
  return new Promise((resolve) => {
3453
3463
  const done = () => {
@@ -3479,7 +3489,8 @@ async function mcpCommand(channel, options = {}) {
3479
3489
  const aggregatorOptions = {
3480
3490
  requestDirectoryAccess: options.requestDirectoryAccess,
3481
3491
  log,
3482
- clientInfo
3492
+ clientInfo,
3493
+ ...options.mcpIdentities !== void 0 ? { mcpIdentityFor: (serviceId) => options.mcpIdentities?.[serviceId] } : {}
3483
3494
  };
3484
3495
  const transport = new StdioServerTransport(options.input ?? process.stdin, options.output ?? process.stdout);
3485
3496
  const input = options.input ?? process.stdin;
@@ -9168,6 +9179,75 @@ Batch options:
9168
9179
  process.stdout.write(out + "\n");
9169
9180
  });
9170
9181
  });
9182
+ /** Options that select the MCP server: a command after `--`, --url, or --mcp-config. */
9183
+ const mcpSourceOptions = (command) => command.option("--url <url>", "a Streamable HTTP MCP server instead of a command after `--`").option("--header <key=value>", "HTTP header sent to the --url server (repeatable)", collectKeyValue).option("--header-env <key=ENV_VAR>", "HTTP header read from an environment variable when a session opens, e.g. `Authorization=SLACK_AUTHORIZATION` (repeatable)", collectKeyValue).option("--mcp-config <file>", "JSON file with the MCP server: `transport`, optional `identities` (accounts), `description`, and `expose`").option("--env <key=value>", "env var for the spawned MCP server child (repeatable)", collectKeyValue);
9184
+ const mcpExposeOptions = (command) => command.option("--service", "publish the MCP server as a LinkRPC service").option("--forward", "relay MCP verbatim over mcp.forward").option("--name <name>", "generated interface name, `mcp.tools.<name>` (default: derived from the serviceId)").option("--group <name=keywords>", "move tools whose name contains one of the comma-separated keywords into `mcp.tools.<name>.<group>` (repeatable; first match wins)", collectKeyValue);
9185
+ const exposeFromFlags = (commandName, cmdOpts) => {
9186
+ if (!cmdOpts.service && !cmdOpts.forward && cmdOpts.mcpConfig === void 0) {
9187
+ process.stderr.write(`linkrpc: ${commandName} requires --service, --forward, or both.\n`);
9188
+ process.exit(2);
9189
+ }
9190
+ if (cmdOpts.group && !cmdOpts.service) {
9191
+ process.stderr.write(`linkrpc: ${commandName} --group requires --service.\n`);
9192
+ process.exit(2);
9193
+ }
9194
+ if (!cmdOpts.service && !cmdOpts.forward) return void 0;
9195
+ const groups = Object.entries(cmdOpts.group ?? {}).map(([groupName, keywords]) => ({
9196
+ name: groupName,
9197
+ keywords: keywords.split(",").filter(Boolean)
9198
+ }));
9199
+ return {
9200
+ ...cmdOpts.service ? { service: groups.length > 0 ? { groups } : {} } : {},
9201
+ ...cmdOpts.forward ? { forward: { sharing: "exclusive" } } : {}
9202
+ };
9203
+ };
9204
+ /** Validate the MCP server source flags; exits with usage errors. */
9205
+ const resolveMcpSource = async (commandName, mcpCommand, cmdOpts, expose) => {
9206
+ if ([
9207
+ mcpCommand !== void 0 && mcpCommand.length > 0,
9208
+ cmdOpts.url !== void 0,
9209
+ cmdOpts.stdio === true,
9210
+ cmdOpts.mcpConfig !== void 0
9211
+ ].filter(Boolean).length !== 1) {
9212
+ process.stderr.write(`linkrpc: ${commandName} requires exactly one of an MCP server command after \`--\`, --url, --stdio, or --mcp-config, e.g. \`${commandName} -- npx -y @modelcontextprotocol/server-everything\`.\n`);
9213
+ process.exit(2);
9214
+ }
9215
+ if (cmdOpts.stdio && expose?.service !== void 0) {
9216
+ process.stderr.write(`linkrpc: ${commandName} --stdio supports only --forward.\n`);
9217
+ process.exit(2);
9218
+ }
9219
+ if (cmdOpts.headerEnv !== void 0 && cmdOpts.url === void 0) {
9220
+ process.stderr.write(`linkrpc: ${commandName} --header-env requires --url.\n`);
9221
+ process.exit(2);
9222
+ }
9223
+ const file = cmdOpts.mcpConfig === void 0 ? void 0 : await readMcpPublishConfig(cmdOpts.mcpConfig);
9224
+ const resolvedExpose = expose ?? file?.expose;
9225
+ if (resolvedExpose === void 0) {
9226
+ process.stderr.write(`linkrpc: ${commandName} requires --service, --forward, or \`expose\` in --mcp-config.\n`);
9227
+ process.exit(2);
9228
+ }
9229
+ const headers = {
9230
+ ...cmdOpts.header,
9231
+ ...Object.fromEntries(Object.entries(cmdOpts.headerEnv ?? {}).map(([key, variable]) => [key, { fromEnv: variable }]))
9232
+ };
9233
+ return {
9234
+ transport: file !== void 0 ? file.transport : cmdOpts.stdio ? { kind: "own-stdio" } : cmdOpts.url !== void 0 ? {
9235
+ kind: "streamable-http",
9236
+ url: cmdOpts.url,
9237
+ ...Object.keys(headers).length > 0 ? { headers } : {}
9238
+ } : {
9239
+ kind: "stdio",
9240
+ command: mcpCommand[0],
9241
+ args: mcpCommand.slice(1),
9242
+ env: {
9243
+ ...definedEnv(process.env),
9244
+ ...cmdOpts.env
9245
+ }
9246
+ },
9247
+ expose: resolvedExpose,
9248
+ file
9249
+ };
9250
+ };
9171
9251
  if (profile === "hub") {
9172
9252
  const exportRoutes = new JsonRpcExportRoutes();
9173
9253
  program.command("json-rpc-export").description("Export Hub JSON-RPC services through one authenticated raw WebSocket listener.").requiredOption("--target-endpoint <uri>", "Listener URI, e.g. listen:ws://127.0.0.1:8123").option("--target-token <token>", "Local client authentication token (or put token in target URI)").option("--target-token-query-param <name>", "Accepted token query parameter (repeatable; replaces defaults tkn and token)", collectOption).option("--serviceId <id>", "Begin a route; follow each occurrence with --path", (value) => {
@@ -9229,11 +9309,12 @@ Batch options:
9229
9309
  local.close();
9230
9310
  }
9231
9311
  });
9232
- program.command("mcp").description("Expose the tools of all MCP servers published on the Hub (MCP services and forwarded servers) as one stdio MCP server.").option("--scripts", "also serve the LinkRPC script tools (runLinkRpcScript, awaitLinkRpcTask, cancelLinkRpcTask)").action(async (cmdOpts) => {
9312
+ program.command("mcp").description("Expose the tools of all MCP servers published on the Hub (MCP services and forwarded servers) as one stdio MCP server, together with the LinkRPC script tools (runLinkRpcScript, awaitLinkRpcTask, cancelLinkRpcTask).").option("--no-scripts", "serve only the aggregated MCP tools, without loading the script sandbox").option("--mcp-identity <serviceId=identity>", "use this MCP identity (account) of a published MCP server instead of its default (repeatable)", collectKeyValue).action(async (cmdOpts) => {
9233
9313
  await withChannel(endpoint, getPrincipalSpec(), async (channel, session) => {
9234
9314
  await mcpCommand(channel, {
9315
+ ...cmdOpts.mcpIdentity !== void 0 ? { mcpIdentities: cmdOpts.mcpIdentity } : {},
9235
9316
  requestDirectoryAccess: session === void 0 ? void 0 : (serviceId) => requestDirectoryAccess(session, serviceId, { watch: true }),
9236
- ...cmdOpts.scripts ? {
9317
+ ...cmdOpts.scripts !== false ? {
9237
9318
  scripts: true,
9238
9319
  ...session !== void 0 ? { access: session } : {}
9239
9320
  } : {}
@@ -9278,9 +9359,10 @@ Batch options:
9278
9359
  logMessages: g_logMessages
9279
9360
  });
9280
9361
  });
9281
- addTargetEndpointOptions(program.command("tunnel <serviceId>").description("Claim <serviceId> on the source hub (--endpoint*) and forward every request it routes here to a target endpoint over a second connection. The target endpoint is set via --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio; when it is --target-endpoint-cmd, the spawned child sees `hubGrantedServiceId::get().grantedServiceIdNamespace` = <serviceId> from its local hub, and global --provision-identity[-slot] applies to it. With `-c, --config`, the source hub is instead appended to the config as an endpoint claiming <serviceId>, and the in-process hub serves it (the config provides the target). Runs until Ctrl-C.")).option("--bidi", "also forward every request/notification the target endpoint emits back to the source hub, exposing the hub to the endpoint (forwards everything, unsigned)").action(async (serviceId, cmdOpts) => {
9362
+ addTargetEndpointOptions(program.command("tunnel <serviceId>").description("Claim <serviceId> (`./<name>`: relative to the granted namespace) on the source hub (--endpoint*) and forward every request it routes here to a target endpoint over a second connection. The target endpoint is set via --target-endpoint / --target-endpoint-cmd / --target-endpoint-cmd-stdio; when it is --target-endpoint-cmd, the spawned child sees `hubGrantedServiceId::get().grantedServiceIdNamespace` = <serviceId> from its local hub, and global --provision-identity[-slot] applies to it. With `-c, --config`, the source hub is instead appended to the config as an endpoint claiming <serviceId>, and the in-process hub serves it (the config provides the target). Runs until Ctrl-C.")).option("--bidi", "also forward every request/notification the target endpoint emits back to the source hub, exposing the hub to the endpoint (forwards everything, unsigned)").action(async (serviceId, cmdOpts) => {
9282
9363
  const localEp = needEndpoint(endpoint);
9283
9364
  if (g_hubConfigPath !== void 0) {
9365
+ if (serviceId.startsWith("./")) throw new InvalidArgumentError("relative service ids (./<name>) are not supported with --config");
9284
9366
  const baseConfig = loadHubConfig(g_hubConfigPath);
9285
9367
  const claimEndpoint = resolvedEndpointToConfig(localEp, { claimServiceIds: [serviceId] });
9286
9368
  const running = await runHub({
@@ -9304,6 +9386,7 @@ Batch options:
9304
9386
  }
9305
9387
  const targetEp = resolveTargetEndpointOrExit(cmdOpts, program.opts(), "tunnel");
9306
9388
  const local = await connect(localEp, wireLog("source"));
9389
+ serviceId = (await resolveServiceIdToClaim(local, serviceId)).serviceId;
9307
9390
  const remote = await connectTargetEndpoint(targetEp, serviceId);
9308
9391
  try {
9309
9392
  reportIdentity(await setupSigning(local.channel, local.signing, getPrincipalSpec(), { negotiateHubCaps: isHubEndpoint(localEp) }));
@@ -9423,43 +9506,22 @@ Batch options:
9423
9506
  broker.close();
9424
9507
  }
9425
9508
  });
9426
- const mcpUpstreamOptions = (command) => command.option("--serviceId <serviceId>", "serviceId prefix to claim (default: the connection's granted serviceId namespace)").option("--url <url>", "publish a Streamable HTTP MCP server instead of a command after `--`").option("--header <key=value>", "HTTP header sent to the --url server (repeatable)", collectKeyValue).option("--env <key=value>", "env var for the spawned MCP server child (repeatable)", collectKeyValue).option("--stdio", "forward the running MCP server attached to this process's stdin/stdout, one connection at a time");
9509
+ const mcpUpstreamOptions = (command) => mcpSourceOptions(command).option("--serviceId <serviceId>", "serviceId to claim; `./<name>` is relative to the connection's granted namespace (or a namespace for this user and host, requested from the hub). Default: the granted namespace").option("--stdio", "forward the running MCP server attached to this process's stdin/stdout, one connection at a time");
9427
9510
  const runMcpPublish = async (commandName, mcpCommand, cmdOpts, expose, name) => {
9428
9511
  const localEp = needEndpoint(endpoint);
9429
- if ([
9430
- mcpCommand !== void 0 && mcpCommand.length > 0,
9431
- cmdOpts.url !== void 0,
9432
- cmdOpts.stdio === true
9433
- ].filter(Boolean).length !== 1) {
9434
- process.stderr.write(`linkrpc: ${commandName} requires exactly one of an MCP server command after \`--\`, --url, or --stdio, e.g. \`${commandName} -- npx -y @modelcontextprotocol/server-everything\`.\n`);
9435
- process.exit(2);
9436
- }
9437
- if (cmdOpts.stdio && expose.service !== void 0) {
9438
- process.stderr.write(`linkrpc: ${commandName} --stdio supports only --forward.\n`);
9439
- process.exit(2);
9440
- }
9441
- const transport = cmdOpts.stdio ? { kind: "own-stdio" } : cmdOpts.url !== void 0 ? {
9442
- kind: "streamable-http",
9443
- url: cmdOpts.url,
9444
- ...cmdOpts.header ? { headers: cmdOpts.header } : {}
9445
- } : {
9446
- kind: "stdio",
9447
- command: mcpCommand[0],
9448
- args: mcpCommand.slice(1),
9449
- env: {
9450
- ...definedEnv(process.env),
9451
- ...cmdOpts.env
9452
- }
9453
- };
9512
+ const source = await resolveMcpSource(commandName, mcpCommand, cmdOpts, expose);
9454
9513
  const local = await connect(localEp, wireLog("hub"));
9455
9514
  try {
9456
9515
  reportIdentity(await setupSigning(local.channel, local.signing, getPrincipalSpec(), { negotiateHubCaps: isHubEndpoint(localEp) }));
9516
+ const id = name ?? source.file?.id;
9457
9517
  await mcpPublishCommand({
9458
9518
  ...cmdOpts.serviceId !== void 0 ? { serviceId: cmdOpts.serviceId } : {},
9459
- ...name !== void 0 ? { name } : {},
9519
+ ...id !== void 0 ? { name: id } : {},
9520
+ ...source.file?.identities !== void 0 ? { identities: source.file.identities } : {},
9521
+ ...source.file?.description !== void 0 ? { description: source.file.description } : {},
9460
9522
  local,
9461
- transport,
9462
- expose
9523
+ transport: source.transport,
9524
+ expose: source.expose
9463
9525
  });
9464
9526
  } finally {
9465
9527
  local.close();
@@ -9468,23 +9530,8 @@ Batch options:
9468
9530
  mcpUpstreamOptions(program.command("mcp-forward [mcpCommand...]").description("Shorthand for `mcp-publish --forward`: relay an MCP server verbatim through the hub (--endpoint*) over `mcp.forward`. The MCP server is a command after `--` (a fresh process per connection), --url (a new HTTP session per connection), or --stdio (the running server attached to this process's stdin/stdout, one connection at a time). By default it claims this connection's granted serviceId namespace. Runs until Ctrl-C.")).action(async (mcpCommand, cmdOpts) => {
9469
9531
  await runMcpPublish("mcp-forward", mcpCommand, cmdOpts, { forward: { sharing: "exclusive" } }, void 0);
9470
9532
  });
9471
- mcpUpstreamOptions(program.command("mcp-publish [mcpCommand...]").description("Publish an MCP server through the hub (--endpoint*). --service publishes it as a LinkRPC service: one method per tool on generated `mcp.tools.<name>` interfaces (split with --group), generic `mcp.tools::listTools`/`callTool`, and `mcp.server`; callers share one MCP session. --forward relays verbatim MCP over `mcp.forward`. Pass one or both. The MCP server is a command after `--`, --url, or (forward only) --stdio. Runs until Ctrl-C.")).option("--service", "publish the MCP server as a LinkRPC service").option("--forward", "relay MCP verbatim over mcp.forward").option("--name <name>", "generated interface name, `mcp.tools.<name>` (default: derived from the serviceId)").option("--group <name=keywords>", "move tools whose name contains one of the comma-separated keywords into `mcp.tools.<name>.<group>` (repeatable; first match wins)", collectKeyValue).action(async (mcpCommand, cmdOpts) => {
9472
- if (!cmdOpts.service && !cmdOpts.forward) {
9473
- process.stderr.write("linkrpc: mcp-publish requires --service, --forward, or both.\n");
9474
- process.exit(2);
9475
- }
9476
- if (cmdOpts.group && !cmdOpts.service) {
9477
- process.stderr.write("linkrpc: mcp-publish --group requires --service.\n");
9478
- process.exit(2);
9479
- }
9480
- const groups = Object.entries(cmdOpts.group ?? {}).map(([groupName, keywords]) => ({
9481
- name: groupName,
9482
- keywords: keywords.split(",").filter(Boolean)
9483
- }));
9484
- await runMcpPublish("mcp-publish", mcpCommand, cmdOpts, {
9485
- ...cmdOpts.service ? { service: groups.length > 0 ? { groups } : {} } : {},
9486
- ...cmdOpts.forward ? { forward: { sharing: "exclusive" } } : {}
9487
- }, cmdOpts.name);
9533
+ mcpExposeOptions(mcpUpstreamOptions(program.command("mcp-publish [mcpCommand...]").description("Publish an MCP server through the hub (--endpoint*). --service publishes it as a LinkRPC service: one method per tool on generated `mcp.tools.<name>` interfaces (split with --group), generic `mcp.tools::listTools`/`callTool`, and `mcp.server`; callers share one MCP session. --forward relays verbatim MCP over `mcp.forward`. Pass one or both. The MCP server is a command after `--`, --url, or (forward only) --stdio. Runs until Ctrl-C."))).action(async (mcpCommand, cmdOpts) => {
9534
+ await runMcpPublish("mcp-publish", mcpCommand, cmdOpts, exposeFromFlags("mcp-publish", cmdOpts), cmdOpts.name);
9488
9535
  });
9489
9536
  program.command("identity").description("Inspect the persistent principal used by connected CLI commands.").command("show").description("Print the resolved persistent CLI identity.").option("--json", "stable machine-readable JSON output").action(async (opts) => {
9490
9537
  await withResolvedSigning(endpoint, getPrincipalSpec(), async (_conn, session) => {
@@ -9519,7 +9566,7 @@ Batch options:
9519
9566
  process.once("SIGINT", onSignal);
9520
9567
  process.once("SIGTERM", onSignal);
9521
9568
  try {
9522
- const { runApprovalUi } = await import("./runApprovalUi-BHomYhFQ.js");
9569
+ const { runApprovalUi } = await import("./runApprovalUi-5soIqxOS.js");
9523
9570
  await runApprovalUi({
9524
9571
  client,
9525
9572
  signal: stop.signal
@@ -9534,7 +9581,7 @@ Batch options:
9534
9581
  registerViewCommands(program, (action) => withChannel(endpoint, getPrincipalSpec(), action));
9535
9582
  program.command("ui").description("Launch the terminal UI (form-based browser of services + methods).").action(async () => {
9536
9583
  const acquired = await acquireConnection(endpoint);
9537
- const { runUi } = await import("./runUi-cl0J7cZB.js");
9584
+ const { runUi } = await import("./runUi-Dkm-6D6s.js");
9538
9585
  try {
9539
9586
  await runUi({
9540
9587
  endpoint: acquired.ep,
@@ -9790,7 +9837,7 @@ function hasEndpointOverrides(values) {
9790
9837
  async function withChannel(endpoint, principalSpec, fn, opts = {}) {
9791
9838
  const sign = resolveSigning(g_invocation?.profile ?? "rpc", g_invocation?.values ?? {}, opts.requireSigning);
9792
9839
  const acquired = await acquireConnection(endpoint);
9793
- const conn = await connect(acquired.ep, acquired.running === void 0 ? wireLog("hub") : void 0);
9840
+ const conn = await connect(acquired.ep, acquired.running === void 0 ? wireLog("hub") : void 0, { cmdEnvLocalHub: g_invocation?.profile === "hub" });
9794
9841
  try {
9795
9842
  const schemaSource = g_invocation?.values.schema;
9796
9843
  const channel = schemaSource === void 0 ? conn.channel : withStaticHubReflection(conn.channel, await loadStaticHubSchema(schemaSource));
@@ -10114,4 +10161,4 @@ function definedEnv(env) {
10114
10161
  //#endregion
10115
10162
  export { formatCondition as _, formatCommandLegend as a, targetId as b, safeTerminalText as c, ObservablePromise as d, observableValue as f, resolveViewTarget as g, Disposable as h, dispatchHostKey as i, approvalDetailLines as l, derived as m, views as n, hostCommands as o, autorun as p, ViewFrame as r, matchesKey as s, runCli as t, ObservableLazyPromise as u, interfaceTarget as v, matchesTarget as y };
10116
10163
 
10117
- //# sourceMappingURL=cli-CUctSk0X.js.map
10164
+ //# sourceMappingURL=cli-BY9fXhpJ.js.map