@hediet/linkrpc-cli 0.0.3-next.20261025.4 → 0.0.3-next.20261026.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 +71 -1
- package/dist/chunks/{cli-D_nbiyek.js → cli-7lA_-BRS.js} +324 -13
- package/dist/chunks/cli-7lA_-BRS.js.map +1 -0
- package/dist/chunks/{runApprovalUi-Diol5P5a.js → runApprovalUi-iC4AMf96.js} +3 -3
- package/dist/chunks/{runApprovalUi-Diol5P5a.js.map → runApprovalUi-iC4AMf96.js.map} +1 -1
- package/dist/chunks/{runComplete-bFjlzR3Y.js → runComplete-CxpTYwUW.js} +7 -1
- package/dist/chunks/runComplete-CxpTYwUW.js.map +1 -0
- package/dist/chunks/{runUi-DDJrDeBg.js → runUi-wnO_UQPl.js} +4 -4
- package/dist/chunks/{runUi-DDJrDeBg.js.map → runUi-wnO_UQPl.js.map} +1 -1
- package/dist/chunks/{scroll-mMFXvk6E.js → scroll-DH3zgnaZ.js} +2 -2
- package/dist/chunks/{scroll-mMFXvk6E.js.map → scroll-DH3zgnaZ.js.map} +1 -1
- package/dist/chunks/{src-B71xYgEO.js → src-B21aY_0C.js} +2 -2
- package/dist/chunks/{src-B71xYgEO.js.map → src-B21aY_0C.js.map} +1 -1
- package/dist/hub.js +1 -1
- package/dist/index.js +1 -1
- package/dist/linkrpc.js +1 -1
- package/dist/rpc.js +1 -1
- package/package.json +6 -5
- package/dist/chunks/cli-D_nbiyek.js.map +0 -1
- package/dist/chunks/runComplete-bFjlzR3Y.js.map +0 -1
package/README.md
CHANGED
|
@@ -794,7 +794,7 @@ initial document:
|
|
|
794
794
|
| `connection destroy` | Stop the configured connection broker through its local overlay. |
|
|
795
795
|
| `json-rpc-stdio <serviceId> [--params <json>]` | In the Hub profile, expose `<serviceId>::jsonRpcConnection::connectRaw` as newline-delimited JSON-RPC on stdin/stdout. Diagnostics remain on stderr. |
|
|
796
796
|
| `json-rpc-export --target-endpoint <uri> --serviceId <id> --path <path> ...` | In the Hub profile, export multiple JSON-RPC factories through one authenticated raw WebSocket listener. |
|
|
797
|
-
| `http-export [--port <n>] [--host <address>]... [--base-domain <domain>]` | In the Hub profile, serve loopback ports of Hub compute nodes at `<port>.<service>.localhost` over HTTP and WebSocket
|
|
797
|
+
| `http-export [--port <n>] [--host <address>]... [--base-domain <domain>] [--auth browser\|none]` | In the Hub profile, serve loopback ports of Hub compute nodes at `<port>.<service>.localhost` over HTTP and WebSocket; browsers must be approved once unless `--auth none`. |
|
|
798
798
|
|
|
799
799
|
The inherited `--schema <path-or-url>` option also overlays static
|
|
800
800
|
`hubrpc.defaults`, `hubrpc.directory`, and `hubrpc.schemas` reflection for
|
|
@@ -880,6 +880,32 @@ bodies are not rewritten, so they fail rather than reach this machine. Bind
|
|
|
880
880
|
loopback only: anyone who can reach the listener can use the export process's
|
|
881
881
|
Hub identity to reach every forwarded port.
|
|
882
882
|
|
|
883
|
+
**Browser approval (prototype, on by default).** Browsers must be approved once
|
|
884
|
+
before they can use the gateway; `--auth none` restores the behavior above.
|
|
885
|
+
|
|
886
|
+
- A browser without approval is redirected to `http://localhost/.linkrpc/login`.
|
|
887
|
+
The gateway creates a signing key for that browser and asks the Hub's
|
|
888
|
+
approvers (`hubAccess::requestAccess`) to let it call `tcpForward` and
|
|
889
|
+
`ports::listListening` on the compute nodes. The page shows a code, the first
|
|
890
|
+
eight characters of the browser key (`id:key:AbCdEfGh…` → `AbCd-EfGh`),
|
|
891
|
+
and continues by itself once approved. Approve only requests whose principal
|
|
892
|
+
starts with the code your browser shows.
|
|
893
|
+
- The gateway then signs that browser's calls with the browser's key and
|
|
894
|
+
granted capabilities, so compute nodes authorize the browser, not the
|
|
895
|
+
gateway. A browser approved for some machines only reaches those.
|
|
896
|
+
- `localhost` keeps the browser's session cookie. Each service site
|
|
897
|
+
(`<service>.localhost`) gets its own cookie on first visit through a
|
|
898
|
+
single-use, 30-second ticket from `localhost`, bound to that site and to a
|
|
899
|
+
state cookie set by the site. Cookies are `HttpOnly`, `Secure`
|
|
900
|
+
(Chromium treats `http://*.localhost` as secure), and never reach forwarded
|
|
901
|
+
apps; apps cannot set them either.
|
|
902
|
+
- Requests without `Sec-Fetch-*` and `Origin` headers (curl, scripts, agents)
|
|
903
|
+
are not affected and keep using the gateway's identity. Browser requests
|
|
904
|
+
other than page navigations get `401` until the browser is approved.
|
|
905
|
+
- Approved sessions are kept in `--session-file` (default
|
|
906
|
+
`%LOCALAPPDATA%\linkrpc\http-export\browser-sessions-<port>.json` or
|
|
907
|
+
`$XDG_STATE_HOME/linkrpc/http-export/…`); it contains the browser keys.
|
|
908
|
+
|
|
883
909
|
The gateway's own pages (`localhost` and `<service>.localhost`, HTML and JSON)
|
|
884
910
|
show command lines, which may contain secrets. They answer only top-level
|
|
885
911
|
navigations, same-origin requests, and clients that send no `Sec-Fetch-*` or
|
|
@@ -895,6 +921,50 @@ Each service and port shares one `tcpForward.multiplex` session (up to 10
|
|
|
895
921
|
logical connections, 8 of them for pooled HTTP keep-alive), closed after five
|
|
896
922
|
idle minutes.
|
|
897
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
|
+
|
|
898
968
|
### Participant proxy
|
|
899
969
|
|
|
900
970
|
`proxy` stands in for a participant on the hub: the participant is either this
|
|
@@ -1,17 +1,18 @@
|
|
|
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-
|
|
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
|
-
import
|
|
9
|
+
import { homedir, hostname } from "node:os";
|
|
10
|
+
import path, { dirname, join } from "node:path";
|
|
10
11
|
import { spawnCommand } from "@hediet/linkrpc-hub/spawn";
|
|
11
12
|
import { tapTransport } from "@hediet/linkrpc-hub/hub/server/transit";
|
|
12
13
|
import * as net from "node:net";
|
|
13
14
|
import { mkdir, open, readFile, writeFile } from "node:fs/promises";
|
|
14
|
-
import { DEFAULT_WALK_DEPTH, HubDirectoryExplorer, fetchSchema, findCoveringCapabilities, hubGrantedServiceIdInterface } from "@hediet/linkrpc/hub/common";
|
|
15
|
+
import { DEFAULT_WALK_DEPTH, HubDirectoryExplorer, fetchSchema, findCoveringCapabilities, hubAccessInterface, hubGrantedServiceIdInterface } from "@hediet/linkrpc/hub/common";
|
|
15
16
|
import { CONSOLE_INTERFACE_TAG, ConsoleTemplate, consoleAttachResultSchema, consoleServerMessageSchema, decodeConsoleData, encodeConsoleData } from "@hediet/linkrpc-infra/console";
|
|
16
17
|
import { createInterface } from "node:readline/promises";
|
|
17
18
|
import { Command, InvalidArgumentError, Option } from "commander";
|
|
@@ -25,6 +26,10 @@ import { TopologyClient, TopologyNetworkClient, TrafficClient } from "@hediet/li
|
|
|
25
26
|
import { stdin, stdout } from "node:process";
|
|
26
27
|
import { TrafficFlowAggregator, createTerminalConsentPrompt, formatFlowSummary } from "@hediet/linkrpc-hub";
|
|
27
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";
|
|
28
33
|
import { connectJsonRpcTransports, connectRawJsonRpcTransport, createNdjsonJsonRpcTransport, jsonRpcConnectionInterface } from "@hediet/linkrpc-infra/json-rpc";
|
|
29
34
|
import { startJsonRpcWebSocketExport, validateJsonRpcExport } from "@hediet/linkrpc-infra/json-rpc/node";
|
|
30
35
|
import { computeNodePortsInterface, computeNodeTcpForwardInterface } from "@hediet/linkrpc-infra/compute-node";
|
|
@@ -409,7 +414,7 @@ function contextNamespace(reference) {
|
|
|
409
414
|
async function useLocalManagement(start, action) {
|
|
410
415
|
const home = HubHome.resolve();
|
|
411
416
|
if (start) {
|
|
412
|
-
const { startDaemon, nodeDaemonLaunch } = await import("./src-
|
|
417
|
+
const { startDaemon, nodeDaemonLaunch } = await import("./src-B21aY_0C.js");
|
|
413
418
|
if (await startDaemon({
|
|
414
419
|
home,
|
|
415
420
|
launch: nodeDaemonLaunch(home)
|
|
@@ -429,7 +434,7 @@ async function useLocalManagement(start, action) {
|
|
|
429
434
|
}
|
|
430
435
|
}
|
|
431
436
|
async function restartLocalDaemon() {
|
|
432
|
-
const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import("./src-
|
|
437
|
+
const { startDaemon, stopDaemon, nodeDaemonLaunch } = await import("./src-B21aY_0C.js");
|
|
433
438
|
const home = HubHome.resolve();
|
|
434
439
|
process.stderr.write("Restarting the local Hub daemon: clients will disconnect and managed workloads will stop. OS autostart settings are unchanged.\n");
|
|
435
440
|
await stopDaemon(home);
|
|
@@ -3489,6 +3494,260 @@ function _describe(command) {
|
|
|
3489
3494
|
return "argv" in command ? command.argv.join(" ") : command.command;
|
|
3490
3495
|
}
|
|
3491
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
|
|
3492
3751
|
//#region src/commands/jsonRpcStdio.ts
|
|
3493
3752
|
/** Expose a remote `jsonRpcConnection` service as an NDJSON stdio endpoint. */
|
|
3494
3753
|
async function jsonRpcStdioCommand(options) {
|
|
@@ -3556,12 +3815,54 @@ async function httpExportCommand(options) {
|
|
|
3556
3815
|
port: options.port
|
|
3557
3816
|
})),
|
|
3558
3817
|
baseDomain: options.baseDomain,
|
|
3559
|
-
getTcpForward: (serviceId) => connection.service(serviceId).get(computeNodeTcpForwardInterface),
|
|
3818
|
+
getTcpForward: (serviceId, caller) => connection.service(serviceId).get(computeNodeTcpForwardInterface, signedAs(caller)),
|
|
3560
3819
|
listServices: () => services.get(),
|
|
3561
|
-
listPorts: async (serviceId) => (await connection.service(serviceId).get(computeNodePortsInterface).listListening({})).ports,
|
|
3820
|
+
listPorts: async (serviceId, caller) => (await connection.service(serviceId).get(computeNodePortsInterface, signedAs(caller)).listListening({})).ports,
|
|
3821
|
+
...options.auth === "browser" ? { approval: {
|
|
3822
|
+
gatewayName: hostname(),
|
|
3823
|
+
...options.sessionFile === void 0 ? {} : { stateFile: options.sessionFile },
|
|
3824
|
+
requestAccess: (request) => requestBrowserAccess(connection, request)
|
|
3825
|
+
} } : {},
|
|
3562
3826
|
onError: options.onError
|
|
3563
3827
|
});
|
|
3564
3828
|
}
|
|
3829
|
+
/** Per-user state file for approved browser sessions of a gateway on `port`. */
|
|
3830
|
+
function defaultHttpExportSessionFile(port) {
|
|
3831
|
+
const base = process.platform === "win32" ? process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local") : process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state");
|
|
3832
|
+
return join(base, "linkrpc", "http-export", `browser-sessions-${port}.json`);
|
|
3833
|
+
}
|
|
3834
|
+
/** Signs a browser's calls with its own key and approved capabilities instead of the gateway's identity. */
|
|
3835
|
+
function signedAs(caller) {
|
|
3836
|
+
return caller ? {
|
|
3837
|
+
signerOverride: caller.signer,
|
|
3838
|
+
capsOverride: caller.capabilities
|
|
3839
|
+
} : {};
|
|
3840
|
+
}
|
|
3841
|
+
/** Asks the Hub's approvers to grant `request.permissions` to the browser's principal; resolves once decided. */
|
|
3842
|
+
async function requestBrowserAccess(connection, request) {
|
|
3843
|
+
const result = await connection.get(hubAccessInterface).requestAccess({
|
|
3844
|
+
consumer: {
|
|
3845
|
+
name: request.name,
|
|
3846
|
+
purpose: request.purpose,
|
|
3847
|
+
principal: request.principal
|
|
3848
|
+
},
|
|
3849
|
+
permissions: request.permissions.map((permission) => ({
|
|
3850
|
+
...permission,
|
|
3851
|
+
target: {
|
|
3852
|
+
...permission.target,
|
|
3853
|
+
members: [...permission.target.members]
|
|
3854
|
+
}
|
|
3855
|
+
})),
|
|
3856
|
+
duration: "persistent"
|
|
3857
|
+
});
|
|
3858
|
+
return result.status === "granted" ? {
|
|
3859
|
+
status: "granted",
|
|
3860
|
+
capabilities: result.capabilities
|
|
3861
|
+
} : {
|
|
3862
|
+
status: result.status,
|
|
3863
|
+
..."reason" in result && result.reason ? { reason: result.reason } : {}
|
|
3864
|
+
};
|
|
3865
|
+
}
|
|
3565
3866
|
/** Caches the services that implement `tcpForward`; a slow or partial walk returns what it found. */
|
|
3566
3867
|
var ForwardableServices = class {
|
|
3567
3868
|
_channel;
|
|
@@ -9090,7 +9391,7 @@ Batch options:
|
|
|
9090
9391
|
local.close();
|
|
9091
9392
|
}
|
|
9092
9393
|
});
|
|
9093
|
-
program.command("http-export").description("Serve loopback ports of Hub compute nodes at <port>.<service>.localhost over HTTP and WebSocket.").option("--port <n>", "Local port to listen on", (value) => parsePositiveInteger(value, "--port"), 80).option("--host <address>", "Local address to bind (repeatable; default 127.0.0.1 and ::1)", collectOption).option("--base-domain <domain>", "Base domain of exported hostnames", "localhost").action(async (opts) => {
|
|
9394
|
+
program.command("http-export").description("Serve loopback ports of Hub compute nodes at <port>.<service>.localhost over HTTP and WebSocket.").option("--port <n>", "Local port to listen on", (value) => parsePositiveInteger(value, "--port"), 80).option("--host <address>", "Local address to bind (repeatable; default 127.0.0.1 and ::1)", collectOption).option("--base-domain <domain>", "Base domain of exported hostnames", "localhost").addOption(new Option("--auth <mode>", "browser: browsers must be approved once through the Hub consent flow (tools without browser headers are not affected); none: no approval").choices(["browser", "none"]).default("browser")).option("--session-file <path>", "Where approved browser sessions are kept across restarts (contains browser keys)").action(async (opts) => {
|
|
9094
9395
|
const localEp = needEndpoint(endpoint);
|
|
9095
9396
|
const local = await connect(localEp, wireLog("hub"));
|
|
9096
9397
|
try {
|
|
@@ -9102,10 +9403,12 @@ Batch options:
|
|
|
9102
9403
|
port: opts.port,
|
|
9103
9404
|
hosts: opts.host ?? ["127.0.0.1", "::1"],
|
|
9104
9405
|
baseDomain: opts.baseDomain,
|
|
9406
|
+
auth: opts.auth,
|
|
9407
|
+
sessionFile: opts.sessionFile ?? defaultHttpExportSessionFile(opts.port),
|
|
9105
9408
|
onError: (error) => process.stderr.write(`linkrpc: ${error.message}\n`)
|
|
9106
9409
|
});
|
|
9107
9410
|
try {
|
|
9108
|
-
process.stderr.write(`linkrpc: HTTP export listening at ${server.urls.join(", ")}\n`);
|
|
9411
|
+
process.stderr.write(`linkrpc: HTTP export listening at ${server.urls.join(", ")}${opts.auth === "browser" ? " (browsers need approval; --auth none disables it)" : ""}\n`);
|
|
9109
9412
|
await _untilSignalled();
|
|
9110
9413
|
} finally {
|
|
9111
9414
|
await server.close();
|
|
@@ -9114,6 +9417,14 @@ Batch options:
|
|
|
9114
9417
|
local.close();
|
|
9115
9418
|
}
|
|
9116
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
|
+
});
|
|
9117
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) => {
|
|
9118
9429
|
const localEp = needEndpoint(endpoint);
|
|
9119
9430
|
let params;
|
|
@@ -9352,7 +9663,7 @@ Batch options:
|
|
|
9352
9663
|
process.once("SIGINT", onSignal);
|
|
9353
9664
|
process.once("SIGTERM", onSignal);
|
|
9354
9665
|
try {
|
|
9355
|
-
const { runApprovalUi } = await import("./runApprovalUi-
|
|
9666
|
+
const { runApprovalUi } = await import("./runApprovalUi-iC4AMf96.js");
|
|
9356
9667
|
await runApprovalUi({
|
|
9357
9668
|
client,
|
|
9358
9669
|
signal: stop.signal
|
|
@@ -9367,7 +9678,7 @@ Batch options:
|
|
|
9367
9678
|
registerViewCommands(program, (action) => withChannel(endpoint, getPrincipalSpec(), action));
|
|
9368
9679
|
program.command("ui").description("Launch the terminal UI (form-based browser of services + methods).").action(async () => {
|
|
9369
9680
|
const acquired = await acquireConnection(endpoint);
|
|
9370
|
-
const { runUi } = await import("./runUi-
|
|
9681
|
+
const { runUi } = await import("./runUi-wnO_UQPl.js");
|
|
9371
9682
|
try {
|
|
9372
9683
|
await runUi({
|
|
9373
9684
|
endpoint: acquired.ep,
|
|
@@ -9930,4 +10241,4 @@ function safeJson(value) {
|
|
|
9930
10241
|
//#endregion
|
|
9931
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 };
|
|
9932
10243
|
|
|
9933
|
-
//# sourceMappingURL=cli-
|
|
10244
|
+
//# sourceMappingURL=cli-7lA_-BRS.js.map
|