@hediet/linkrpc-cli 0.0.3-next.20261026.1 → 0.0.3-next.20261026.3

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
@@ -921,6 +921,50 @@ Each service and port shares one `tcpForward.multiplex` session (up to 10
921
921
  logical connections, 8 of them for pooled HTTP keep-alive), closed after five
922
922
  idle minutes.
923
923
 
924
+ ### Hub MCP aggregation
925
+
926
+ `linkrpc hub mcp` is a lightweight stdio MCP server that discovers services
927
+ exposing `vscode.mcp-forward` in the selected Hub and aggregates their tools.
928
+ No service IDs, filters, or principal overrides are required:
929
+
930
+ ```json
931
+ {
932
+ "servers": {
933
+ "hub-mcp": {
934
+ "type": "stdio",
935
+ "command": "linkrpc",
936
+ "args": ["hub", "mcp"]
937
+ }
938
+ }
939
+ }
940
+ ```
941
+
942
+ Endpoint/context/environment and identity selection follow the normal Hub CLI
943
+ rules. An explicit endpoint can be supplied before `mcp`, for example
944
+ `linkrpc hub --endpoint npipe://./pipe/my-hub mcp`. Signing and capability
945
+ negotiation remain enabled by default; discovery does not bypass authorization.
946
+ Inaccessible directories and failed servers are reported on stderr; stdout
947
+ contains only MCP protocol frames.
948
+
949
+ The command watches directory changes, refreshes changed tool lists (including
950
+ paginated lists), and retries failed connections while they remain advertised.
951
+ Tool names use a readable prefix and a stable hash of service ID plus tool name,
952
+ remaining unique and MCP-safe even for long service paths. Descriptions identify
953
+ the source service. Disconnecting stdio closes this client's forwarding sessions.
954
+ This version aggregates tools, not resources, prompts, or sampling.
955
+
956
+ The producer stays separate:
957
+
958
+ ```sh
959
+ linkrpc hub mcp-forward --serviceId <authorized-service-id> -- component-explorer mcp -p <config> --use-daemon --no-daemon-autostart
960
+ ```
961
+
962
+ Manage that producer and `component-explorer serve -p <same-config>` with your
963
+ workspace daemon. The aggregator opens lightweight MCP connections; it does not
964
+ start workspace builds or explorer daemons. Each forwarded connection spawns
965
+ the configured MCP child, so producers must use attach-only commands when
966
+ heavyweight services are managed separately.
967
+
924
968
  ### Participant proxy
925
969
 
926
970
  `proxy` stands in for a participant on the hub: the participant is either this
@@ -1,9 +1,9 @@
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, wt as mcpForwardInterface, xt as mergeParams, y as HubHome, yt as validateValueAgainstSchema, z as ConnectionBroker } from "./runComplete-bFjlzR3Y.js";
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, wt as mcpForwardInterface, xt as mergeParams, y as HubHome, yt as validateValueAgainstSchema, z as ConnectionBroker } from "./runComplete-CxpTYwUW.js";
2
2
  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";
3
3
  import { z } from "zod";
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";
6
- import { randomBytes, randomUUID } from "node:crypto";
6
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
7
7
  import * as fs from "node:fs";
8
8
  import { readFileSync } from "node:fs";
9
9
  import { homedir, hostname } from "node:os";
@@ -26,6 +26,10 @@ import { TopologyClient, TopologyNetworkClient, TrafficClient } from "@hediet/li
26
26
  import { stdin, stdout } from "node:process";
27
27
  import { TrafficFlowAggregator, createTerminalConsentPrompt, formatFlowSummary } from "@hediet/linkrpc-hub";
28
28
  import { loadHubConfig, printHubConfigSchema } from "@hediet/linkrpc-hub/config-file";
29
+ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
30
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
31
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
32
+ import { CallToolRequestSchema, CallToolResultSchema, JSONRPCMessageSchema, ListToolsRequestSchema, ToolListChangedNotificationSchema } from "@modelcontextprotocol/sdk/types.js";
29
33
  import { connectJsonRpcTransports, connectRawJsonRpcTransport, createNdjsonJsonRpcTransport, jsonRpcConnectionInterface } from "@hediet/linkrpc-infra/json-rpc";
30
34
  import { startJsonRpcWebSocketExport, validateJsonRpcExport } from "@hediet/linkrpc-infra/json-rpc/node";
31
35
  import { computeNodePortsInterface, computeNodeTcpForwardInterface } from "@hediet/linkrpc-infra/compute-node";
@@ -410,7 +414,7 @@ function contextNamespace(reference) {
410
414
  async function useLocalManagement(start, action) {
411
415
  const home = HubHome.resolve();
412
416
  if (start) {
413
- const { startDaemon, nodeDaemonLaunch } = await import("./src-B71xYgEO.js");
417
+ const { startDaemon, nodeDaemonLaunch } = await import("./src-B21aY_0C.js");
414
418
  if (await startDaemon({
415
419
  home,
416
420
  launch: nodeDaemonLaunch(home)
@@ -430,7 +434,7 @@ async function useLocalManagement(start, action) {
430
434
  }
431
435
  }
432
436
  async function restartLocalDaemon() {
433
- const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import("./src-B71xYgEO.js");
437
+ const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import("./src-B21aY_0C.js");
434
438
  const home = HubHome.resolve();
435
439
  process.stderr.write("Restarting the local Hub daemon: clients will disconnect and managed workloads will stop. OS autostart settings are unchanged.\n");
436
440
  await stopDaemon(home);
@@ -3490,6 +3494,260 @@ function _describe(command) {
3490
3494
  return "argv" in command ? command.argv.join(" ") : command.command;
3491
3495
  }
3492
3496
  //#endregion
3497
+ //#region src/commands/mcpTransport.ts
3498
+ /** MCP transport over the CLI's signed, capability-aware request channel. */
3499
+ var McpHubTransport = class {
3500
+ _channel;
3501
+ _serviceId;
3502
+ onmessage;
3503
+ onclose;
3504
+ onerror;
3505
+ _call;
3506
+ _closed = false;
3507
+ constructor(_channel, _serviceId) {
3508
+ this._channel = _channel;
3509
+ this._serviceId = _serviceId;
3510
+ }
3511
+ async start() {
3512
+ if (this._call || this._closed) throw new Error("MCP transport already started or closed");
3513
+ const call = this._channel.sendRequestWithStream(`${this._serviceId}::${mcpForwardInterface.info.id}::connect`, { clientInfo: {
3514
+ name: "linkrpc-hub-mcp",
3515
+ version: "1.0.0"
3516
+ } }, { onStreamMessage: (payload) => {
3517
+ const result = z.object({ frame: JSONRPCMessageSchema }).safeParse(payload);
3518
+ if (result.success) this.onmessage?.(result.data.frame);
3519
+ else {
3520
+ this.onerror?.(/* @__PURE__ */ new Error(`Invalid forwarded MCP frame: ${result.error.message}`));
3521
+ this.close().catch((error) => this.onerror?.(asError(error)));
3522
+ }
3523
+ } });
3524
+ this._call = call;
3525
+ call.result.then(() => this._end(), (error) => this._end(asError(error)));
3526
+ }
3527
+ _end(error) {
3528
+ if (this._closed) return;
3529
+ this._closed = true;
3530
+ this._call = void 0;
3531
+ if (error) this.onerror?.(error);
3532
+ this.onclose?.();
3533
+ }
3534
+ async send(message) {
3535
+ if (!this._call || this._closed) throw new Error("MCP transport is not connected");
3536
+ await this._call.send({ frame: z.json().parse(message) });
3537
+ }
3538
+ async close() {
3539
+ if (this._closed) return;
3540
+ this._closed = true;
3541
+ const call = this._call;
3542
+ this._call = void 0;
3543
+ try {
3544
+ await call?.cancel("MCP client disconnected");
3545
+ } finally {
3546
+ call?.dispose?.("MCP client disconnected");
3547
+ this.onclose?.();
3548
+ }
3549
+ }
3550
+ };
3551
+ function asError(error) {
3552
+ return error instanceof Error ? error : new Error(String(error));
3553
+ }
3554
+ //#endregion
3555
+ //#region src/commands/mcp.ts
3556
+ /** Expose tools from discoverable Hub MCP forwarders on local MCP stdio. */
3557
+ async function mcpCommand(channel, options = {}) {
3558
+ await new HubMcpServer(channel, options).run();
3559
+ }
3560
+ var HubMcpServer = class {
3561
+ _channel;
3562
+ _options;
3563
+ _server = new Server({
3564
+ name: "linkrpc-hub-mcp",
3565
+ version: "1.0.0"
3566
+ }, { capabilities: { tools: { listChanged: true } } });
3567
+ _entries = /* @__PURE__ */ new Map();
3568
+ _explorer;
3569
+ _log;
3570
+ _closed = false;
3571
+ _initialized = false;
3572
+ _initial = Promise.resolve();
3573
+ _reconciling = Promise.resolve();
3574
+ _queued = false;
3575
+ constructor(_channel, _options) {
3576
+ this._channel = _channel;
3577
+ this._options = _options;
3578
+ this._log = _options.log ?? ((message) => {
3579
+ process.stderr.write(`linkrpc mcp: ${message}\n`);
3580
+ });
3581
+ this._explorer = new HubDirectoryExplorer(_channel, {
3582
+ interfaceId: mcpForwardInterface.info.id,
3583
+ unlockGatedDirectory: _options.requestDirectoryAccess,
3584
+ log: this._log
3585
+ });
3586
+ this._server.oninitialized = () => {
3587
+ this._initialized = true;
3588
+ };
3589
+ this._server.onerror = (error) => this._log(`MCP protocol error: ${error.message}`);
3590
+ this._server.setRequestHandler(ListToolsRequestSchema, async () => {
3591
+ await this._initial;
3592
+ return { tools: [...this._entries.values()].flatMap((entry) => entry.tools.map((tool) => ({
3593
+ ...tool,
3594
+ name: toolName(entry.serviceId, tool.name),
3595
+ description: `[${entry.serviceId}] ${tool.description ?? tool.name}`
3596
+ }))) };
3597
+ });
3598
+ this._server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
3599
+ await this._initial;
3600
+ for (const entry of this._entries.values()) {
3601
+ const tool = entry.tools.find((tool) => toolName(entry.serviceId, tool.name) === request.params.name);
3602
+ if (!tool) continue;
3603
+ try {
3604
+ return await entry.client.callTool({
3605
+ ...request.params,
3606
+ name: tool.name
3607
+ }, CallToolResultSchema, { signal: extra.signal });
3608
+ } catch (error) {
3609
+ this._log(`Tool ${request.params.name} failed: ${errorMessage(error)}`);
3610
+ return {
3611
+ isError: true,
3612
+ content: [{
3613
+ type: "text",
3614
+ text: errorMessage(error)
3615
+ }]
3616
+ };
3617
+ }
3618
+ }
3619
+ throw new Error(`Unknown or disconnected Hub MCP tool: ${request.params.name}`);
3620
+ });
3621
+ }
3622
+ async run() {
3623
+ const input = this._options.input ?? process.stdin;
3624
+ const output = this._options.output ?? process.stdout;
3625
+ let stop;
3626
+ const stopped = new Promise((resolve) => {
3627
+ stop = resolve;
3628
+ });
3629
+ input.once("end", stop);
3630
+ process.once("SIGINT", stop);
3631
+ process.once("SIGTERM", stop);
3632
+ this._server.onclose = stop;
3633
+ const unsubscribe = this._explorer.subscribe((event) => {
3634
+ if (event.type === "settled") this._scheduleReconcile();
3635
+ });
3636
+ const retry = setInterval(() => this._scheduleReconcile(), 5e3);
3637
+ try {
3638
+ await this._server.connect(new StdioServerTransport(input, output));
3639
+ this._initial = (async () => {
3640
+ await this._explorer.watch(() => {});
3641
+ const root = this._explorer.graphSnapshot.root;
3642
+ if (root.inaccessibleReason) throw new Error(`Hub directory inaccessible: ${root.inaccessibleReason}`);
3643
+ await this._reconciling;
3644
+ })();
3645
+ await Promise.race([
3646
+ this._initial.then(() => this._options.stop ? Promise.race([stopped, this._options.stop]) : stopped),
3647
+ stopped,
3648
+ ...this._options.stop ? [this._options.stop] : []
3649
+ ]);
3650
+ } finally {
3651
+ this._closed = true;
3652
+ clearInterval(retry);
3653
+ unsubscribe();
3654
+ this._explorer.dispose();
3655
+ input.off("end", stop);
3656
+ process.off("SIGINT", stop);
3657
+ process.off("SIGTERM", stop);
3658
+ await Promise.all([...this._entries.values()].map((entry) => this._detach(entry)));
3659
+ await this._reconciling;
3660
+ await this._server.close();
3661
+ }
3662
+ }
3663
+ _scheduleReconcile() {
3664
+ if (this._closed || this._queued) return;
3665
+ this._queued = true;
3666
+ this._reconciling = this._reconciling.then(async () => {
3667
+ this._queued = false;
3668
+ if (this._closed) return;
3669
+ const wanted = new Set(this._explorer.result.listings.filter((item) => item.interfaceId === mcpForwardInterface.info.id).map((item) => item.serviceId));
3670
+ await Promise.all([...this._entries.values()].filter((entry) => !wanted.has(entry.serviceId)).map((entry) => this._detach(entry)));
3671
+ await Promise.all([...wanted].filter((id) => !this._entries.has(id)).map((id) => this._attach(id)));
3672
+ }).catch((error) => {
3673
+ this._log(`Discovery reconciliation failed: ${errorMessage(error)}`);
3674
+ });
3675
+ }
3676
+ async _attach(serviceId) {
3677
+ if (this._closed) return;
3678
+ const client = new Client({
3679
+ name: "linkrpc-hub-mcp",
3680
+ version: "1.0.0"
3681
+ }, { capabilities: {} });
3682
+ const entry = {
3683
+ serviceId,
3684
+ client,
3685
+ tools: [],
3686
+ refresh: Promise.resolve()
3687
+ };
3688
+ this._entries.set(serviceId, entry);
3689
+ client.onerror = (error) => this._log(`${serviceId}: ${error.message}`);
3690
+ client.onclose = () => {
3691
+ if (this._entries.get(serviceId) === entry) {
3692
+ this._log(`Disconnected from ${serviceId}; will retry while advertised`);
3693
+ this._entries.delete(serviceId);
3694
+ this._notifyChanged();
3695
+ }
3696
+ };
3697
+ client.setNotificationHandler(ToolListChangedNotificationSchema, () => this._refresh(entry));
3698
+ try {
3699
+ await client.connect(new McpHubTransport(this._channel, serviceId), { timeout: 1e4 });
3700
+ await this._refresh(entry);
3701
+ this._log(`Connected to ${serviceId}`);
3702
+ } catch (error) {
3703
+ this._log(`Cannot connect to ${serviceId}: ${errorMessage(error)}`);
3704
+ await this._detach(entry);
3705
+ }
3706
+ }
3707
+ _refresh(entry) {
3708
+ entry.refresh = entry.refresh.then(async () => {
3709
+ if (this._entries.get(entry.serviceId) !== entry) return;
3710
+ const tools = [];
3711
+ const cursors = /* @__PURE__ */ new Set();
3712
+ let cursor;
3713
+ if (entry.client.getServerCapabilities()?.tools) do {
3714
+ const page = await entry.client.listTools(cursor ? { cursor } : {}, { timeout: 1e4 });
3715
+ tools.push(...page.tools);
3716
+ cursor = page.nextCursor;
3717
+ if (cursor && cursors.has(cursor)) throw new Error("Repeated tools/list pagination cursor");
3718
+ if (cursor) cursors.add(cursor);
3719
+ } while (cursor);
3720
+ if (this._entries.get(entry.serviceId) !== entry) return;
3721
+ entry.tools = tools;
3722
+ this._notifyChanged();
3723
+ }).catch(async (error) => {
3724
+ this._log(`Cannot list tools from ${entry.serviceId}: ${errorMessage(error)}`);
3725
+ await this._detach(entry);
3726
+ });
3727
+ return entry.refresh;
3728
+ }
3729
+ async _detach(entry) {
3730
+ if (this._entries.get(entry.serviceId) === entry) {
3731
+ this._entries.delete(entry.serviceId);
3732
+ this._notifyChanged();
3733
+ }
3734
+ await entry.client.close();
3735
+ }
3736
+ _notifyChanged() {
3737
+ if (this._closed || !this._initialized) return;
3738
+ this._server.sendToolListChanged().catch((error) => {
3739
+ this._log(`Cannot notify MCP client: ${errorMessage(error)}`);
3740
+ });
3741
+ }
3742
+ };
3743
+ function toolName(serviceId, name) {
3744
+ const hash = createHash("sha256").update(JSON.stringify([serviceId, name])).digest("base64url");
3745
+ return `${name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 18)}__${hash}`;
3746
+ }
3747
+ function errorMessage(error) {
3748
+ return error instanceof Error ? error.message : String(error);
3749
+ }
3750
+ //#endregion
3493
3751
  //#region src/commands/jsonRpcStdio.ts
3494
3752
  /** Expose a remote `jsonRpcConnection` service as an NDJSON stdio endpoint. */
3495
3753
  async function jsonRpcStdioCommand(options) {
@@ -9159,6 +9417,14 @@ Batch options:
9159
9417
  local.close();
9160
9418
  }
9161
9419
  });
9420
+ program.command("mcp").description("Expose tools from all discoverable Hub MCP forwarders as one stdio MCP server.").action(async () => {
9421
+ await withChannel(endpoint, getPrincipalSpec(), async (channel, session) => {
9422
+ await mcpCommand(channel, { requestDirectoryAccess: session === void 0 ? void 0 : (serviceId) => requestDirectoryAccess(session, serviceId, { watch: true }) });
9423
+ }, {
9424
+ requestReflectionAccess: false,
9425
+ autoNegotiatePerCall: true
9426
+ });
9427
+ });
9162
9428
  program.command("json-rpc-stdio <serviceId>").description("Expose <serviceId>::jsonRpcConnection::connectRaw as a newline-delimited JSON-RPC endpoint on this process's stdin/stdout.").option("--params <json>", "JSON value passed to the remote transport factory").action(async (serviceId, opts) => {
9163
9429
  const localEp = needEndpoint(endpoint);
9164
9430
  let params;
@@ -9397,7 +9663,7 @@ Batch options:
9397
9663
  process.once("SIGINT", onSignal);
9398
9664
  process.once("SIGTERM", onSignal);
9399
9665
  try {
9400
- const { runApprovalUi } = await import("./runApprovalUi-B8Gb0cg3.js");
9666
+ const { runApprovalUi } = await import("./runApprovalUi-iC4AMf96.js");
9401
9667
  await runApprovalUi({
9402
9668
  client,
9403
9669
  signal: stop.signal
@@ -9412,7 +9678,7 @@ Batch options:
9412
9678
  registerViewCommands(program, (action) => withChannel(endpoint, getPrincipalSpec(), action));
9413
9679
  program.command("ui").description("Launch the terminal UI (form-based browser of services + methods).").action(async () => {
9414
9680
  const acquired = await acquireConnection(endpoint);
9415
- const { runUi } = await import("./runUi-BYS9ZvbD.js");
9681
+ const { runUi } = await import("./runUi-wnO_UQPl.js");
9416
9682
  try {
9417
9683
  await runUi({
9418
9684
  endpoint: acquired.ep,
@@ -9975,4 +10241,4 @@ function safeJson(value) {
9975
10241
  //#endregion
9976
10242
  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 };
9977
10243
 
9978
- //# sourceMappingURL=cli-CvfXZUzx.js.map
10244
+ //# sourceMappingURL=cli-7lA_-BRS.js.map