@mcpjam/cli 3.5.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1035 -3
- package/dist/index.js.map +1 -1
- package/package.json +5 -3
package/dist/index.js
CHANGED
|
@@ -2,18 +2,22 @@
|
|
|
2
2
|
import { Command, CommanderError } from 'commander';
|
|
3
3
|
import { realpathSync, readFileSync, existsSync, closeSync, mkdirSync, writeFileSync, renameSync, statSync, openSync } from 'fs';
|
|
4
4
|
import { pathToFileURL, fileURLToPath } from 'url';
|
|
5
|
-
import { probeMcpServer, redactSensitiveValue, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listPrompts, getPrompt, MCPAppsConformanceTest, MCPAppsConformanceSuite, runOAuthLogin, OAuthConformanceTest, OAuthConformanceSuite, MCPConformanceTest, MCPConformanceSuite, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, toConformanceReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, openUrlInBrowser, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, OAuthProxyError, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS } from '@mcpjam/sdk';
|
|
5
|
+
import { probeMcpServer, redactSensitiveValue, runServerDoctor, collectServerSnapshot, serializeStableServerSnapshot, serializeServerSnapshot, buildServerDiffReport, validateToolCallResult, isCallToolResultError, buildToolCallValidationReport, listResources, readResource, listPrompts, getPrompt, MCPAppsConformanceTest, MCPAppsConformanceSuite, runOAuthLogin, OAuthConformanceTest, OAuthConformanceSuite, MCPConformanceTest, MCPConformanceSuite, withEphemeralClient, diffServerSnapshots, ServerSnapshotFormatError, renderStructuredRunJUnitXml, renderStructuredRunJson, toConformanceReport, renderConformanceReportJUnitXml, renderConformanceReportJson, formatOAuthConformanceHuman, formatOAuthConformanceSuiteHuman, fetchOAuthMetadata, executeOAuthProxy, executeDebugOAuthProxy, generateRandomString, generateCodeChallenge, createInteractiveAuthorizationSession, openUrlInBrowser, MCPClientManager, MCP_APPS_CHECK_CATEGORIES, MCP_APPS_CHECK_IDS, OAuthProxyError, MCP_CHECK_CATEGORIES, MCP_CHECK_IDS } from '@mcpjam/sdk';
|
|
6
6
|
import { mkdir, writeFile, readFile, chmod, rename, rm } from 'fs/promises';
|
|
7
7
|
import path2, { join, dirname, basename } from 'path';
|
|
8
8
|
import { randomUUID } from 'crypto';
|
|
9
9
|
import os, { homedir } from 'os';
|
|
10
|
-
import { DEFAULT_PLATFORM_API_BASE_URL, PlatformApiClient, isPlatformApiError, PlatformApiError, listProjectsOperation, listProjectServersOperation, showServersOperation } from '@mcpjam/sdk/platform';
|
|
10
|
+
import { createTunnelOperation, DEFAULT_PLATFORM_API_BASE_URL, PlatformApiClient, isPlatformApiError, PlatformApiError, listProjectsOperation, listProjectServersOperation, showServersOperation } from '@mcpjam/sdk/platform';
|
|
11
11
|
import { PostHog } from 'posthog-node';
|
|
12
12
|
import { spawn } from 'child_process';
|
|
13
|
+
import http from 'http';
|
|
14
|
+
import https from 'https';
|
|
15
|
+
import { once } from 'events';
|
|
16
|
+
import { WebSocket } from 'ws';
|
|
13
17
|
|
|
14
18
|
// package.json
|
|
15
19
|
var package_default = {
|
|
16
|
-
version: "3.
|
|
20
|
+
version: "3.6.0"};
|
|
17
21
|
|
|
18
22
|
// src/lib/output.ts
|
|
19
23
|
var DEFAULT_OUTPUT_FORMAT = "json";
|
|
@@ -5836,6 +5840,1033 @@ function isCompactInspectorCommandStatus(value) {
|
|
|
5836
5840
|
function isRecord(value) {
|
|
5837
5841
|
return Boolean(value && typeof value === "object" && !Array.isArray(value));
|
|
5838
5842
|
}
|
|
5843
|
+
function tunnelPathPrefix(serverId) {
|
|
5844
|
+
return `/api/mcp/adapter-http/${encodeURIComponent(serverId)}`;
|
|
5845
|
+
}
|
|
5846
|
+
var NON_FORWARDED_REQUEST_HEADERS = /* @__PURE__ */ new Set([
|
|
5847
|
+
"host",
|
|
5848
|
+
"connection",
|
|
5849
|
+
"keep-alive",
|
|
5850
|
+
"proxy-authenticate",
|
|
5851
|
+
"proxy-authorization",
|
|
5852
|
+
"proxy-connection",
|
|
5853
|
+
"te",
|
|
5854
|
+
"trailer",
|
|
5855
|
+
"transfer-encoding",
|
|
5856
|
+
"upgrade"
|
|
5857
|
+
]);
|
|
5858
|
+
var NON_FORWARDED_RESPONSE_HEADERS = /* @__PURE__ */ new Set([
|
|
5859
|
+
"connection",
|
|
5860
|
+
"keep-alive",
|
|
5861
|
+
"transfer-encoding"
|
|
5862
|
+
]);
|
|
5863
|
+
function writeJson(res, status, payload) {
|
|
5864
|
+
const body = JSON.stringify(payload);
|
|
5865
|
+
res.writeHead(status, {
|
|
5866
|
+
"content-type": "application/json",
|
|
5867
|
+
"content-length": Buffer.byteLength(body)
|
|
5868
|
+
});
|
|
5869
|
+
res.end(body);
|
|
5870
|
+
}
|
|
5871
|
+
function matchTunnelPath(serverId, pathname) {
|
|
5872
|
+
const prefix = tunnelPathPrefix(serverId);
|
|
5873
|
+
if (pathname === prefix) return "";
|
|
5874
|
+
if (pathname.startsWith(`${prefix}/`)) return pathname.slice(prefix.length);
|
|
5875
|
+
return null;
|
|
5876
|
+
}
|
|
5877
|
+
function stripTunnelSecret(search) {
|
|
5878
|
+
const params = new URLSearchParams(search);
|
|
5879
|
+
params.delete("k");
|
|
5880
|
+
return params;
|
|
5881
|
+
}
|
|
5882
|
+
function buildUpstreamUrl(targetUrl, remainderPath, callerParams) {
|
|
5883
|
+
const upstream = new URL(targetUrl.toString());
|
|
5884
|
+
const basePath = upstream.pathname.replace(/\/+$/, "");
|
|
5885
|
+
upstream.pathname = remainderPath ? `${basePath}${remainderPath}` : upstream.pathname;
|
|
5886
|
+
for (const [name, value] of callerParams) {
|
|
5887
|
+
upstream.searchParams.append(name, value);
|
|
5888
|
+
}
|
|
5889
|
+
return upstream;
|
|
5890
|
+
}
|
|
5891
|
+
function proxyHttpRequest(req, res, upstreamUrl) {
|
|
5892
|
+
const requestFn = upstreamUrl.protocol === "https:" ? https.request : http.request;
|
|
5893
|
+
const headers = {};
|
|
5894
|
+
for (const [name, value] of Object.entries(req.headers)) {
|
|
5895
|
+
if (value === void 0 || NON_FORWARDED_REQUEST_HEADERS.has(name)) continue;
|
|
5896
|
+
headers[name] = value;
|
|
5897
|
+
}
|
|
5898
|
+
const upstream = requestFn(
|
|
5899
|
+
upstreamUrl,
|
|
5900
|
+
{ method: req.method, headers },
|
|
5901
|
+
(upstreamRes) => {
|
|
5902
|
+
const responseHeaders = {};
|
|
5903
|
+
for (const [name, value] of Object.entries(upstreamRes.headers)) {
|
|
5904
|
+
if (value === void 0 || NON_FORWARDED_RESPONSE_HEADERS.has(name)) {
|
|
5905
|
+
continue;
|
|
5906
|
+
}
|
|
5907
|
+
responseHeaders[name] = value;
|
|
5908
|
+
}
|
|
5909
|
+
res.writeHead(upstreamRes.statusCode ?? 502, responseHeaders);
|
|
5910
|
+
upstreamRes.pipe(res);
|
|
5911
|
+
upstreamRes.on("error", () => res.destroy());
|
|
5912
|
+
}
|
|
5913
|
+
);
|
|
5914
|
+
upstream.on("error", (error) => {
|
|
5915
|
+
if (res.headersSent) {
|
|
5916
|
+
res.destroy();
|
|
5917
|
+
return;
|
|
5918
|
+
}
|
|
5919
|
+
writeJson(res, 502, {
|
|
5920
|
+
error: `Local target unreachable: ${error.message}`
|
|
5921
|
+
});
|
|
5922
|
+
});
|
|
5923
|
+
res.on("close", () => upstream.destroy());
|
|
5924
|
+
req.pipe(upstream);
|
|
5925
|
+
}
|
|
5926
|
+
async function handleFacadeJsonRpc(serverId, body, manager) {
|
|
5927
|
+
const id = body?.id ?? null;
|
|
5928
|
+
const method = body?.method;
|
|
5929
|
+
const params = body?.params ?? {};
|
|
5930
|
+
const respond = (payload) => ({
|
|
5931
|
+
jsonrpc: "2.0",
|
|
5932
|
+
id,
|
|
5933
|
+
...payload
|
|
5934
|
+
});
|
|
5935
|
+
if (typeof method !== "string" || method.length === 0) {
|
|
5936
|
+
return respond({
|
|
5937
|
+
error: { code: -32600, message: "Invalid Request" }
|
|
5938
|
+
});
|
|
5939
|
+
}
|
|
5940
|
+
if (method.startsWith("notifications/")) {
|
|
5941
|
+
return null;
|
|
5942
|
+
}
|
|
5943
|
+
const respondError = (error) => respond({
|
|
5944
|
+
error: {
|
|
5945
|
+
code: typeof error?.code === "number" ? error.code : -32e3,
|
|
5946
|
+
message: error instanceof Error ? error.message : String(error)
|
|
5947
|
+
}
|
|
5948
|
+
});
|
|
5949
|
+
try {
|
|
5950
|
+
if (method === "ping") {
|
|
5951
|
+
return respond({ result: {} });
|
|
5952
|
+
}
|
|
5953
|
+
if (method === "initialize") {
|
|
5954
|
+
const info = manager.getInitializationInfo(serverId);
|
|
5955
|
+
const requested = typeof params?.protocolVersion === "string" ? params.protocolVersion : "2025-06-18";
|
|
5956
|
+
const result2 = {
|
|
5957
|
+
protocolVersion: info?.protocolVersion ?? requested,
|
|
5958
|
+
capabilities: info?.serverCapabilities ?? {},
|
|
5959
|
+
serverInfo: info?.serverVersion ?? {
|
|
5960
|
+
name: serverId,
|
|
5961
|
+
version: "mcpjam-tunnel"
|
|
5962
|
+
}
|
|
5963
|
+
};
|
|
5964
|
+
if (info?.instructions !== void 0) {
|
|
5965
|
+
result2.instructions = info.instructions;
|
|
5966
|
+
}
|
|
5967
|
+
return respond({ result: result2 });
|
|
5968
|
+
}
|
|
5969
|
+
const managed = manager.getManagedClient(serverId);
|
|
5970
|
+
if (!managed) {
|
|
5971
|
+
return respond({
|
|
5972
|
+
error: {
|
|
5973
|
+
code: -32e3,
|
|
5974
|
+
message: "Local MCP server is not connected (did the process exit?)"
|
|
5975
|
+
}
|
|
5976
|
+
});
|
|
5977
|
+
}
|
|
5978
|
+
const result = await managed.request({ method, params });
|
|
5979
|
+
return respond({ result: result ?? {} });
|
|
5980
|
+
} catch (error) {
|
|
5981
|
+
return respondError(error);
|
|
5982
|
+
}
|
|
5983
|
+
}
|
|
5984
|
+
async function readRequestBody(req) {
|
|
5985
|
+
const chunks = [];
|
|
5986
|
+
for await (const chunk of req) {
|
|
5987
|
+
chunks.push(chunk);
|
|
5988
|
+
}
|
|
5989
|
+
return Buffer.concat(chunks);
|
|
5990
|
+
}
|
|
5991
|
+
function handleStdioRequest(serverId, manager, req, res) {
|
|
5992
|
+
if (req.method !== "POST") {
|
|
5993
|
+
res.writeHead(405, { allow: "POST" });
|
|
5994
|
+
res.end();
|
|
5995
|
+
return;
|
|
5996
|
+
}
|
|
5997
|
+
void (async () => {
|
|
5998
|
+
let body;
|
|
5999
|
+
try {
|
|
6000
|
+
const raw = await readRequestBody(req);
|
|
6001
|
+
body = raw.byteLength > 0 ? JSON.parse(raw.toString("utf8")) : {};
|
|
6002
|
+
} catch {
|
|
6003
|
+
writeJson(res, 400, {
|
|
6004
|
+
jsonrpc: "2.0",
|
|
6005
|
+
id: null,
|
|
6006
|
+
error: { code: -32700, message: "Parse error" }
|
|
6007
|
+
});
|
|
6008
|
+
return;
|
|
6009
|
+
}
|
|
6010
|
+
if (Array.isArray(body)) {
|
|
6011
|
+
writeJson(res, 400, {
|
|
6012
|
+
jsonrpc: "2.0",
|
|
6013
|
+
id: null,
|
|
6014
|
+
error: { code: -32600, message: "Batch requests are not supported" }
|
|
6015
|
+
});
|
|
6016
|
+
return;
|
|
6017
|
+
}
|
|
6018
|
+
const response = await handleFacadeJsonRpc(
|
|
6019
|
+
serverId,
|
|
6020
|
+
body,
|
|
6021
|
+
manager
|
|
6022
|
+
);
|
|
6023
|
+
if (!response) {
|
|
6024
|
+
res.writeHead(202);
|
|
6025
|
+
res.end("Accepted");
|
|
6026
|
+
return;
|
|
6027
|
+
}
|
|
6028
|
+
writeJson(res, 200, response);
|
|
6029
|
+
})().catch(() => {
|
|
6030
|
+
if (!res.headersSent) {
|
|
6031
|
+
writeJson(res, 500, { error: "Bridge failure" });
|
|
6032
|
+
} else {
|
|
6033
|
+
res.destroy();
|
|
6034
|
+
}
|
|
6035
|
+
});
|
|
6036
|
+
}
|
|
6037
|
+
async function startLocalBridge(options) {
|
|
6038
|
+
const { serverId, target } = options;
|
|
6039
|
+
let manager = null;
|
|
6040
|
+
if (target.kind === "stdio") {
|
|
6041
|
+
if (options.connectStdio) {
|
|
6042
|
+
manager = await options.connectStdio(serverId, target.config);
|
|
6043
|
+
} else {
|
|
6044
|
+
manager = new MCPClientManager(
|
|
6045
|
+
{},
|
|
6046
|
+
{
|
|
6047
|
+
defaultTimeout: options.timeoutMs ?? 3e4,
|
|
6048
|
+
defaultClientName: "mcpjam-tunnel",
|
|
6049
|
+
lazyConnect: true
|
|
6050
|
+
}
|
|
6051
|
+
);
|
|
6052
|
+
try {
|
|
6053
|
+
await manager.connectToServer(serverId, target.config);
|
|
6054
|
+
} catch (error) {
|
|
6055
|
+
await manager.disconnectAllServers().catch(() => {
|
|
6056
|
+
});
|
|
6057
|
+
throw error;
|
|
6058
|
+
}
|
|
6059
|
+
}
|
|
6060
|
+
}
|
|
6061
|
+
const server = http.createServer((req, res) => {
|
|
6062
|
+
let url;
|
|
6063
|
+
try {
|
|
6064
|
+
url = new URL(req.url ?? "/", "http://bridge.invalid");
|
|
6065
|
+
} catch {
|
|
6066
|
+
writeJson(res, 400, { error: "Bad request" });
|
|
6067
|
+
return;
|
|
6068
|
+
}
|
|
6069
|
+
const remainder = matchTunnelPath(serverId, url.pathname);
|
|
6070
|
+
if (remainder === null) {
|
|
6071
|
+
writeJson(res, 404, { error: "Not found" });
|
|
6072
|
+
return;
|
|
6073
|
+
}
|
|
6074
|
+
const callerParams = stripTunnelSecret(url.searchParams);
|
|
6075
|
+
if (target.kind === "http") {
|
|
6076
|
+
const upstreamUrl = buildUpstreamUrl(
|
|
6077
|
+
new URL(target.url),
|
|
6078
|
+
remainder,
|
|
6079
|
+
callerParams
|
|
6080
|
+
);
|
|
6081
|
+
proxyHttpRequest(req, res, upstreamUrl);
|
|
6082
|
+
return;
|
|
6083
|
+
}
|
|
6084
|
+
handleStdioRequest(serverId, manager, req, res);
|
|
6085
|
+
});
|
|
6086
|
+
try {
|
|
6087
|
+
server.listen(0, "127.0.0.1");
|
|
6088
|
+
await once(server, "listening");
|
|
6089
|
+
} catch (error) {
|
|
6090
|
+
await manager?.disconnectAllServers().catch(() => {
|
|
6091
|
+
});
|
|
6092
|
+
throw error;
|
|
6093
|
+
}
|
|
6094
|
+
const address = server.address();
|
|
6095
|
+
if (!address || typeof address === "string") {
|
|
6096
|
+
server.close();
|
|
6097
|
+
await manager?.disconnectAllServers().catch(() => {
|
|
6098
|
+
});
|
|
6099
|
+
throw new Error("Failed to bind the local bridge address");
|
|
6100
|
+
}
|
|
6101
|
+
return {
|
|
6102
|
+
localAddr: `http://127.0.0.1:${address.port}`,
|
|
6103
|
+
async close() {
|
|
6104
|
+
await new Promise((resolve) => {
|
|
6105
|
+
server.close(() => resolve());
|
|
6106
|
+
server.closeAllConnections?.();
|
|
6107
|
+
});
|
|
6108
|
+
if (manager) {
|
|
6109
|
+
await manager.disconnectAllServers().catch(() => {
|
|
6110
|
+
});
|
|
6111
|
+
}
|
|
6112
|
+
}
|
|
6113
|
+
};
|
|
6114
|
+
}
|
|
6115
|
+
var RELAY_SUBPROTOCOL = "mcpjam-tunnel.v1";
|
|
6116
|
+
var CHUNK_BYTES = 64 * 1024;
|
|
6117
|
+
var HEARTBEAT_INTERVAL_MS = 25e3;
|
|
6118
|
+
var HEARTBEAT_MISSED_LIMIT = 2;
|
|
6119
|
+
var WS_BACKPRESSURE_HIGH_WATER_BYTES = 1024 * 1024;
|
|
6120
|
+
var RECONNECT_MIN_MS = 1e3;
|
|
6121
|
+
var RECONNECT_MAX_MS = 3e4;
|
|
6122
|
+
var CONNECT_TIMEOUT_MS = 15e3;
|
|
6123
|
+
var CLOSE_BAD_TOKEN = 4e3;
|
|
6124
|
+
var CLOSE_REPLACED = 4001;
|
|
6125
|
+
var CLOSE_CONTROL_PLANE = 4002;
|
|
6126
|
+
var CLOSE_EDGE_RESTART = 1012;
|
|
6127
|
+
var BIN_REQ_CHUNK = 1;
|
|
6128
|
+
var BIN_RES_CHUNK = 2;
|
|
6129
|
+
function encodeBinaryFrame(kind, id, payload) {
|
|
6130
|
+
const buf = Buffer.allocUnsafe(5 + payload.byteLength);
|
|
6131
|
+
buf.writeUInt8(kind, 0);
|
|
6132
|
+
buf.writeUInt32BE(id >>> 0, 1);
|
|
6133
|
+
Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength).copy(
|
|
6134
|
+
buf,
|
|
6135
|
+
5
|
|
6136
|
+
);
|
|
6137
|
+
return buf;
|
|
6138
|
+
}
|
|
6139
|
+
function decodeBinaryFrame(data) {
|
|
6140
|
+
if (data.byteLength < 5) return null;
|
|
6141
|
+
return {
|
|
6142
|
+
kind: data.readUInt8(0),
|
|
6143
|
+
id: data.readUInt32BE(1),
|
|
6144
|
+
payload: data.subarray(5)
|
|
6145
|
+
};
|
|
6146
|
+
}
|
|
6147
|
+
var NOOP_LOGGER = { info: () => {
|
|
6148
|
+
}, warn: () => {
|
|
6149
|
+
} };
|
|
6150
|
+
var RelayConnection = class {
|
|
6151
|
+
constructor(options) {
|
|
6152
|
+
this.options = options;
|
|
6153
|
+
this.logger = options.logger ?? NOOP_LOGGER;
|
|
6154
|
+
}
|
|
6155
|
+
ws = null;
|
|
6156
|
+
local = /* @__PURE__ */ new Map();
|
|
6157
|
+
heartbeatTimer = null;
|
|
6158
|
+
missedPongs = 0;
|
|
6159
|
+
reconnectDelayMs = RECONNECT_MIN_MS;
|
|
6160
|
+
reconnectTimer = null;
|
|
6161
|
+
closedByUs = false;
|
|
6162
|
+
permanent = null;
|
|
6163
|
+
logger;
|
|
6164
|
+
/** Resolves on the first successful hello; rejects on permanent failure. */
|
|
6165
|
+
connect() {
|
|
6166
|
+
return new Promise((resolve, reject) => {
|
|
6167
|
+
let settled = false;
|
|
6168
|
+
const timeout = setTimeout(() => {
|
|
6169
|
+
if (!settled) {
|
|
6170
|
+
settled = true;
|
|
6171
|
+
this.close();
|
|
6172
|
+
reject(new Error("Timed out connecting to the tunnel relay"));
|
|
6173
|
+
}
|
|
6174
|
+
}, CONNECT_TIMEOUT_MS);
|
|
6175
|
+
this.dial(
|
|
6176
|
+
() => {
|
|
6177
|
+
if (!settled) {
|
|
6178
|
+
settled = true;
|
|
6179
|
+
clearTimeout(timeout);
|
|
6180
|
+
resolve();
|
|
6181
|
+
}
|
|
6182
|
+
},
|
|
6183
|
+
(reason) => {
|
|
6184
|
+
if (!settled) {
|
|
6185
|
+
settled = true;
|
|
6186
|
+
clearTimeout(timeout);
|
|
6187
|
+
reject(new Error(reason));
|
|
6188
|
+
}
|
|
6189
|
+
}
|
|
6190
|
+
);
|
|
6191
|
+
});
|
|
6192
|
+
}
|
|
6193
|
+
get isConnected() {
|
|
6194
|
+
return this.ws?.readyState === WebSocket.OPEN;
|
|
6195
|
+
}
|
|
6196
|
+
get permanentFailure() {
|
|
6197
|
+
return this.permanent;
|
|
6198
|
+
}
|
|
6199
|
+
dial(onHello, onPermanent) {
|
|
6200
|
+
if (this.closedByUs || this.permanent) return;
|
|
6201
|
+
const ws = new WebSocket(this.options.relayWsUrl, RELAY_SUBPROTOCOL, {
|
|
6202
|
+
headers: { Authorization: `Bearer ${this.options.connectToken}` }
|
|
6203
|
+
});
|
|
6204
|
+
this.ws = ws;
|
|
6205
|
+
ws.on("message", (data, isBinary) => {
|
|
6206
|
+
if (isBinary) {
|
|
6207
|
+
this.handleBinary(data);
|
|
6208
|
+
return;
|
|
6209
|
+
}
|
|
6210
|
+
let frame = null;
|
|
6211
|
+
try {
|
|
6212
|
+
frame = JSON.parse(String(data));
|
|
6213
|
+
} catch {
|
|
6214
|
+
return;
|
|
6215
|
+
}
|
|
6216
|
+
if (frame.t === "hello") {
|
|
6217
|
+
this.reconnectDelayMs = RECONNECT_MIN_MS;
|
|
6218
|
+
this.logger.info(
|
|
6219
|
+
`Tunnel relay connected (${this.options.serverId}): ${this.options.publicHost}`
|
|
6220
|
+
);
|
|
6221
|
+
onHello?.();
|
|
6222
|
+
return;
|
|
6223
|
+
}
|
|
6224
|
+
this.handleControl(frame);
|
|
6225
|
+
});
|
|
6226
|
+
ws.on("pong", () => {
|
|
6227
|
+
this.missedPongs = 0;
|
|
6228
|
+
});
|
|
6229
|
+
ws.on("error", () => {
|
|
6230
|
+
});
|
|
6231
|
+
ws.on("open", () => this.startHeartbeat());
|
|
6232
|
+
ws.on("close", (code, reasonBuf) => {
|
|
6233
|
+
this.stopHeartbeat();
|
|
6234
|
+
this.abortAllLocal();
|
|
6235
|
+
if (this.closedByUs) return;
|
|
6236
|
+
const reason = reasonBuf.toString() || `relay closed (${code})`;
|
|
6237
|
+
if (code === CLOSE_BAD_TOKEN || code === CLOSE_REPLACED || code === CLOSE_CONTROL_PLANE) {
|
|
6238
|
+
const why = code === CLOSE_REPLACED ? "Tunnel taken over by another session \u2014 re-run `mcpjam tunnel` to take it back" : code === CLOSE_CONTROL_PLANE ? "Tunnel was closed or its secret rotated elsewhere \u2014 re-run `mcpjam tunnel` to recreate it" : "Tunnel session expired \u2014 recreate the tunnel";
|
|
6239
|
+
this.permanent = why;
|
|
6240
|
+
this.logger.warn(`Tunnel relay closed permanently (${code}): ${reason}`);
|
|
6241
|
+
onPermanent?.(why);
|
|
6242
|
+
this.options.onPermanentFailure?.(why, code);
|
|
6243
|
+
return;
|
|
6244
|
+
}
|
|
6245
|
+
const delay2 = code === CLOSE_EDGE_RESTART ? 0 : Math.floor(this.reconnectDelayMs * (0.5 + Math.random() * 0.5));
|
|
6246
|
+
this.reconnectDelayMs = Math.min(
|
|
6247
|
+
this.reconnectDelayMs * 2,
|
|
6248
|
+
RECONNECT_MAX_MS
|
|
6249
|
+
);
|
|
6250
|
+
this.logger.warn(
|
|
6251
|
+
`Tunnel relay disconnected (${code}); reconnecting in ${delay2}ms`
|
|
6252
|
+
);
|
|
6253
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
6254
|
+
this.reconnectTimer = setTimeout(
|
|
6255
|
+
() => this.dial(onHello, onPermanent),
|
|
6256
|
+
delay2
|
|
6257
|
+
);
|
|
6258
|
+
});
|
|
6259
|
+
}
|
|
6260
|
+
close() {
|
|
6261
|
+
this.closedByUs = true;
|
|
6262
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
6263
|
+
this.stopHeartbeat();
|
|
6264
|
+
this.abortAllLocal();
|
|
6265
|
+
try {
|
|
6266
|
+
this.ws?.close();
|
|
6267
|
+
} catch {
|
|
6268
|
+
this.ws?.terminate();
|
|
6269
|
+
}
|
|
6270
|
+
this.ws = null;
|
|
6271
|
+
}
|
|
6272
|
+
// ── Edge frames → local bridge ─────────────────────────────────────────────
|
|
6273
|
+
handleControl(frame) {
|
|
6274
|
+
if (frame.t === "req") {
|
|
6275
|
+
this.startLocalRequest(frame);
|
|
6276
|
+
} else if (frame.t === "req_end") {
|
|
6277
|
+
this.local.get(frame.id)?.req.end();
|
|
6278
|
+
} else if (frame.t === "abort") {
|
|
6279
|
+
const entry = this.local.get(frame.id);
|
|
6280
|
+
if (entry) {
|
|
6281
|
+
entry.req.destroy();
|
|
6282
|
+
this.cleanupLocal(frame.id);
|
|
6283
|
+
}
|
|
6284
|
+
}
|
|
6285
|
+
}
|
|
6286
|
+
handleBinary(data) {
|
|
6287
|
+
const frame = decodeBinaryFrame(data);
|
|
6288
|
+
if (!frame || frame.kind !== BIN_REQ_CHUNK) return;
|
|
6289
|
+
this.local.get(frame.id)?.req.write(frame.payload);
|
|
6290
|
+
}
|
|
6291
|
+
startLocalRequest(frame) {
|
|
6292
|
+
const base = new URL(this.options.localAddr);
|
|
6293
|
+
const headers = {};
|
|
6294
|
+
for (const [name, value] of frame.headers) {
|
|
6295
|
+
const existing = headers[name];
|
|
6296
|
+
if (existing === void 0) headers[name] = value;
|
|
6297
|
+
else if (Array.isArray(existing)) existing.push(value);
|
|
6298
|
+
else headers[name] = [existing, value];
|
|
6299
|
+
}
|
|
6300
|
+
const req = http.request({
|
|
6301
|
+
host: base.hostname,
|
|
6302
|
+
port: base.port || 80,
|
|
6303
|
+
method: frame.method,
|
|
6304
|
+
// Forwarded verbatim by the edge (?k= included): the bridge owns
|
|
6305
|
+
// stripping the bearer secret before it reaches the local target.
|
|
6306
|
+
path: frame.url,
|
|
6307
|
+
headers
|
|
6308
|
+
});
|
|
6309
|
+
this.local.set(frame.id, { req, resumePoll: null });
|
|
6310
|
+
req.on("response", (res) => {
|
|
6311
|
+
const responseHeaders = [];
|
|
6312
|
+
for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) {
|
|
6313
|
+
responseHeaders.push([
|
|
6314
|
+
res.rawHeaders[i],
|
|
6315
|
+
res.rawHeaders[i + 1]
|
|
6316
|
+
]);
|
|
6317
|
+
}
|
|
6318
|
+
this.sendControl({
|
|
6319
|
+
t: "res",
|
|
6320
|
+
id: frame.id,
|
|
6321
|
+
status: res.statusCode ?? 502,
|
|
6322
|
+
headers: responseHeaders
|
|
6323
|
+
});
|
|
6324
|
+
res.on("data", (chunk) => {
|
|
6325
|
+
const ws = this.ws;
|
|
6326
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) {
|
|
6327
|
+
res.destroy();
|
|
6328
|
+
return;
|
|
6329
|
+
}
|
|
6330
|
+
for (let off = 0; off < chunk.byteLength; off += CHUNK_BYTES) {
|
|
6331
|
+
ws.send(
|
|
6332
|
+
encodeBinaryFrame(
|
|
6333
|
+
BIN_RES_CHUNK,
|
|
6334
|
+
frame.id,
|
|
6335
|
+
chunk.subarray(off, off + CHUNK_BYTES)
|
|
6336
|
+
)
|
|
6337
|
+
);
|
|
6338
|
+
}
|
|
6339
|
+
if (ws.bufferedAmount > WS_BACKPRESSURE_HIGH_WATER_BYTES) {
|
|
6340
|
+
res.pause();
|
|
6341
|
+
const entry = this.local.get(frame.id);
|
|
6342
|
+
if (entry && !entry.resumePoll) {
|
|
6343
|
+
entry.resumePoll = setInterval(() => {
|
|
6344
|
+
if (ws.bufferedAmount < WS_BACKPRESSURE_HIGH_WATER_BYTES / 2) {
|
|
6345
|
+
if (entry.resumePoll) clearInterval(entry.resumePoll);
|
|
6346
|
+
entry.resumePoll = null;
|
|
6347
|
+
res.resume();
|
|
6348
|
+
}
|
|
6349
|
+
}, 25);
|
|
6350
|
+
}
|
|
6351
|
+
}
|
|
6352
|
+
});
|
|
6353
|
+
res.on("end", () => {
|
|
6354
|
+
this.sendControl({ t: "res_end", id: frame.id });
|
|
6355
|
+
this.cleanupLocal(frame.id);
|
|
6356
|
+
});
|
|
6357
|
+
res.on("error", () => {
|
|
6358
|
+
this.sendControl({
|
|
6359
|
+
t: "abort",
|
|
6360
|
+
id: frame.id,
|
|
6361
|
+
code: "upstream_error"
|
|
6362
|
+
});
|
|
6363
|
+
this.cleanupLocal(frame.id);
|
|
6364
|
+
});
|
|
6365
|
+
});
|
|
6366
|
+
req.on("error", () => {
|
|
6367
|
+
this.sendControl({ t: "abort", id: frame.id, code: "upstream_error" });
|
|
6368
|
+
this.cleanupLocal(frame.id);
|
|
6369
|
+
});
|
|
6370
|
+
if (!frame.hasBody) req.end();
|
|
6371
|
+
}
|
|
6372
|
+
cleanupLocal(id) {
|
|
6373
|
+
const entry = this.local.get(id);
|
|
6374
|
+
if (entry?.resumePoll) clearInterval(entry.resumePoll);
|
|
6375
|
+
this.local.delete(id);
|
|
6376
|
+
}
|
|
6377
|
+
abortAllLocal() {
|
|
6378
|
+
for (const [id, entry] of [...this.local]) {
|
|
6379
|
+
entry.req.destroy();
|
|
6380
|
+
this.cleanupLocal(id);
|
|
6381
|
+
}
|
|
6382
|
+
}
|
|
6383
|
+
sendControl(frame) {
|
|
6384
|
+
try {
|
|
6385
|
+
this.ws?.send(JSON.stringify(frame));
|
|
6386
|
+
} catch {
|
|
6387
|
+
}
|
|
6388
|
+
}
|
|
6389
|
+
startHeartbeat() {
|
|
6390
|
+
this.stopHeartbeat();
|
|
6391
|
+
this.missedPongs = 0;
|
|
6392
|
+
this.heartbeatTimer = setInterval(() => {
|
|
6393
|
+
const ws = this.ws;
|
|
6394
|
+
if (!ws || ws.readyState !== WebSocket.OPEN) return;
|
|
6395
|
+
if (this.missedPongs >= HEARTBEAT_MISSED_LIMIT) {
|
|
6396
|
+
ws.terminate();
|
|
6397
|
+
return;
|
|
6398
|
+
}
|
|
6399
|
+
this.missedPongs++;
|
|
6400
|
+
try {
|
|
6401
|
+
ws.ping();
|
|
6402
|
+
} catch {
|
|
6403
|
+
}
|
|
6404
|
+
}, HEARTBEAT_INTERVAL_MS);
|
|
6405
|
+
}
|
|
6406
|
+
stopHeartbeat() {
|
|
6407
|
+
if (this.heartbeatTimer) {
|
|
6408
|
+
clearInterval(this.heartbeatTimer);
|
|
6409
|
+
this.heartbeatTimer = null;
|
|
6410
|
+
}
|
|
6411
|
+
}
|
|
6412
|
+
};
|
|
6413
|
+
|
|
6414
|
+
// src/lib/tunnel/tunnel-session.ts
|
|
6415
|
+
var MAX_REMINT_ATTEMPTS = 3;
|
|
6416
|
+
var REMINT_RESET_WINDOW_MS = 6e4;
|
|
6417
|
+
var CLOSE_GRANT_TIMEOUT_MS = 5e3;
|
|
6418
|
+
function permanentCloseMessage(reason, closeCode) {
|
|
6419
|
+
if (closeCode === CLOSE_REPLACED) {
|
|
6420
|
+
return "Tunnel taken over: another session registered a tunnel for this server. Re-run `mcpjam tunnel` here to take it back.";
|
|
6421
|
+
}
|
|
6422
|
+
if (closeCode === CLOSE_CONTROL_PLANE) {
|
|
6423
|
+
return "Tunnel closed or re-created elsewhere (another `mcpjam tunnel` session for this server, or closed from the platform). Re-run `mcpjam tunnel` to recreate it.";
|
|
6424
|
+
}
|
|
6425
|
+
return reason;
|
|
6426
|
+
}
|
|
6427
|
+
async function withTimeout2(promise, ms) {
|
|
6428
|
+
let timer;
|
|
6429
|
+
try {
|
|
6430
|
+
return await Promise.race([
|
|
6431
|
+
promise,
|
|
6432
|
+
new Promise((_, reject) => {
|
|
6433
|
+
timer = setTimeout(
|
|
6434
|
+
() => reject(new Error(`Timed out after ${ms}ms`)),
|
|
6435
|
+
ms
|
|
6436
|
+
);
|
|
6437
|
+
})
|
|
6438
|
+
]);
|
|
6439
|
+
} finally {
|
|
6440
|
+
if (timer) clearTimeout(timer);
|
|
6441
|
+
}
|
|
6442
|
+
}
|
|
6443
|
+
var TunnelSession = class {
|
|
6444
|
+
constructor(deps) {
|
|
6445
|
+
this.deps = deps;
|
|
6446
|
+
this.closed = new Promise((resolve) => {
|
|
6447
|
+
this.settle = (result) => {
|
|
6448
|
+
if (this.settled) return;
|
|
6449
|
+
this.settled = true;
|
|
6450
|
+
resolve(result);
|
|
6451
|
+
};
|
|
6452
|
+
});
|
|
6453
|
+
}
|
|
6454
|
+
grantResult = null;
|
|
6455
|
+
bridge = null;
|
|
6456
|
+
connection = null;
|
|
6457
|
+
remintAttempts = 0;
|
|
6458
|
+
lastRemintAt = null;
|
|
6459
|
+
started = false;
|
|
6460
|
+
stopped = false;
|
|
6461
|
+
/** True while start()/remint own a connect() — its error path drives. */
|
|
6462
|
+
dialing = false;
|
|
6463
|
+
/** True while a remint is rotating; a second 4000 must not start another. */
|
|
6464
|
+
reminting = false;
|
|
6465
|
+
/**
|
|
6466
|
+
* Permanent close that arrived while we couldn't act on it (mid-dial or
|
|
6467
|
+
* pre-start). Consumed by dial()'s post-handshake check or flushed once
|
|
6468
|
+
* the session is live, so no event is ever silently dropped.
|
|
6469
|
+
*/
|
|
6470
|
+
pendingPermanent = null;
|
|
6471
|
+
/** Aborts an in-flight grant mint when stop() lands during one. */
|
|
6472
|
+
mintAborter = null;
|
|
6473
|
+
settled = false;
|
|
6474
|
+
settle;
|
|
6475
|
+
closed;
|
|
6476
|
+
/**
|
|
6477
|
+
* Create the grant, start the bridge, and connect the relay. Resolves
|
|
6478
|
+
* with the grant once the relay handshake succeeded; throws on startup
|
|
6479
|
+
* failure (after cleaning up whatever was started).
|
|
6480
|
+
*/
|
|
6481
|
+
async start() {
|
|
6482
|
+
try {
|
|
6483
|
+
const result = await this.mintGrant();
|
|
6484
|
+
this.grantResult = result;
|
|
6485
|
+
this.assertNotStopped();
|
|
6486
|
+
this.bridge = await this.deps.startBridge(result.grant.serverId);
|
|
6487
|
+
this.assertNotStopped();
|
|
6488
|
+
await this.dial(result);
|
|
6489
|
+
this.assertNotStopped();
|
|
6490
|
+
this.started = true;
|
|
6491
|
+
this.deps.onGrant?.(result, false);
|
|
6492
|
+
this.flushPendingPermanent();
|
|
6493
|
+
return result;
|
|
6494
|
+
} catch (error) {
|
|
6495
|
+
await this.cleanup();
|
|
6496
|
+
await this.revokeGrantBestEffort();
|
|
6497
|
+
throw error;
|
|
6498
|
+
}
|
|
6499
|
+
}
|
|
6500
|
+
async mintGrant() {
|
|
6501
|
+
const aborter = new AbortController();
|
|
6502
|
+
this.mintAborter = aborter;
|
|
6503
|
+
try {
|
|
6504
|
+
return await this.deps.createGrant(aborter.signal);
|
|
6505
|
+
} finally {
|
|
6506
|
+
if (this.mintAborter === aborter) {
|
|
6507
|
+
this.mintAborter = null;
|
|
6508
|
+
}
|
|
6509
|
+
}
|
|
6510
|
+
}
|
|
6511
|
+
/**
|
|
6512
|
+
* A stop() that lands mid-startup owns the session: abandon the bring-up
|
|
6513
|
+
* here so start()'s catch tears down and revokes whatever exists by now —
|
|
6514
|
+
* including a grant whose mint resolved after stop() already ran its own
|
|
6515
|
+
* (then-empty) revocation.
|
|
6516
|
+
*/
|
|
6517
|
+
assertNotStopped() {
|
|
6518
|
+
if (this.stopped || this.settled) {
|
|
6519
|
+
throw new Error("Tunnel startup interrupted");
|
|
6520
|
+
}
|
|
6521
|
+
}
|
|
6522
|
+
async revokeGrantBestEffort() {
|
|
6523
|
+
if (!this.grantResult) return;
|
|
6524
|
+
const aborter = new AbortController();
|
|
6525
|
+
try {
|
|
6526
|
+
await withTimeout2(
|
|
6527
|
+
this.deps.closeGrant(this.grantResult, aborter.signal),
|
|
6528
|
+
this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
|
|
6529
|
+
);
|
|
6530
|
+
} catch {
|
|
6531
|
+
aborter.abort();
|
|
6532
|
+
}
|
|
6533
|
+
}
|
|
6534
|
+
waitUntilClosed() {
|
|
6535
|
+
return this.closed;
|
|
6536
|
+
}
|
|
6537
|
+
/** Ctrl-C path: close everything, best-effort revoke, exit 0. */
|
|
6538
|
+
async stop() {
|
|
6539
|
+
if (this.stopped) return;
|
|
6540
|
+
this.stopped = true;
|
|
6541
|
+
this.mintAborter?.abort();
|
|
6542
|
+
await this.cleanup();
|
|
6543
|
+
if (this.grantResult) {
|
|
6544
|
+
const aborter = new AbortController();
|
|
6545
|
+
try {
|
|
6546
|
+
await withTimeout2(
|
|
6547
|
+
this.deps.closeGrant(this.grantResult, aborter.signal),
|
|
6548
|
+
this.deps.closeGrantTimeoutMs ?? CLOSE_GRANT_TIMEOUT_MS
|
|
6549
|
+
);
|
|
6550
|
+
this.deps.log("Tunnel grant revoked.");
|
|
6551
|
+
} catch (error) {
|
|
6552
|
+
aborter.abort();
|
|
6553
|
+
this.deps.log(
|
|
6554
|
+
`Could not revoke the tunnel grant (${error instanceof Error ? error.message : String(error)}); it dies with the next create or its own expiry.`
|
|
6555
|
+
);
|
|
6556
|
+
}
|
|
6557
|
+
}
|
|
6558
|
+
this.settle({ exitCode: 0 });
|
|
6559
|
+
}
|
|
6560
|
+
async dial(result) {
|
|
6561
|
+
this.dialing = true;
|
|
6562
|
+
this.pendingPermanent = null;
|
|
6563
|
+
try {
|
|
6564
|
+
const connection = this.deps.connectRelay({
|
|
6565
|
+
grant: result.grant,
|
|
6566
|
+
localAddr: this.bridge.localAddr,
|
|
6567
|
+
onPermanentFailure: (reason, closeCode) => this.handlePermanentFailure(reason, closeCode)
|
|
6568
|
+
});
|
|
6569
|
+
this.connection = connection;
|
|
6570
|
+
await connection.connect();
|
|
6571
|
+
const pending = this.pendingPermanent;
|
|
6572
|
+
if (connection.permanentFailure || pending) {
|
|
6573
|
+
this.pendingPermanent = null;
|
|
6574
|
+
connection.close();
|
|
6575
|
+
throw new Error(connection.permanentFailure ?? pending.reason);
|
|
6576
|
+
}
|
|
6577
|
+
} finally {
|
|
6578
|
+
this.dialing = false;
|
|
6579
|
+
}
|
|
6580
|
+
}
|
|
6581
|
+
handlePermanentFailure(reason, closeCode) {
|
|
6582
|
+
if (this.stopped || this.settled) return;
|
|
6583
|
+
if (this.dialing || !this.started) {
|
|
6584
|
+
this.pendingPermanent = { reason, closeCode };
|
|
6585
|
+
return;
|
|
6586
|
+
}
|
|
6587
|
+
this.dispatchPermanentFailure(reason, closeCode);
|
|
6588
|
+
}
|
|
6589
|
+
flushPendingPermanent() {
|
|
6590
|
+
const pending = this.pendingPermanent;
|
|
6591
|
+
if (!pending || this.stopped || this.settled) return;
|
|
6592
|
+
this.pendingPermanent = null;
|
|
6593
|
+
this.dispatchPermanentFailure(pending.reason, pending.closeCode);
|
|
6594
|
+
}
|
|
6595
|
+
dispatchPermanentFailure(reason, closeCode) {
|
|
6596
|
+
if (closeCode === CLOSE_BAD_TOKEN) {
|
|
6597
|
+
if (!this.reminting) {
|
|
6598
|
+
void this.remint();
|
|
6599
|
+
}
|
|
6600
|
+
return;
|
|
6601
|
+
}
|
|
6602
|
+
void this.fail(permanentCloseMessage(reason, closeCode));
|
|
6603
|
+
}
|
|
6604
|
+
async remint() {
|
|
6605
|
+
if (this.reminting) return;
|
|
6606
|
+
this.reminting = true;
|
|
6607
|
+
try {
|
|
6608
|
+
const now = this.deps.now?.() ?? Date.now();
|
|
6609
|
+
if (this.lastRemintAt !== null && now - this.lastRemintAt > REMINT_RESET_WINDOW_MS) {
|
|
6610
|
+
this.remintAttempts = 0;
|
|
6611
|
+
}
|
|
6612
|
+
this.lastRemintAt = now;
|
|
6613
|
+
this.remintAttempts += 1;
|
|
6614
|
+
if (this.remintAttempts > MAX_REMINT_ATTEMPTS) {
|
|
6615
|
+
await this.fail(
|
|
6616
|
+
`Tunnel session expired and could not be renewed after ${MAX_REMINT_ATTEMPTS} rapid attempts.`
|
|
6617
|
+
);
|
|
6618
|
+
return;
|
|
6619
|
+
}
|
|
6620
|
+
this.deps.log(
|
|
6621
|
+
`Tunnel session expired; renewing the grant (attempt ${this.remintAttempts}/${MAX_REMINT_ATTEMPTS})...`
|
|
6622
|
+
);
|
|
6623
|
+
try {
|
|
6624
|
+
this.connection?.close();
|
|
6625
|
+
const result = await this.mintGrant();
|
|
6626
|
+
this.grantResult = result;
|
|
6627
|
+
if (this.stopped || this.settled) {
|
|
6628
|
+
await this.revokeGrantBestEffort();
|
|
6629
|
+
return;
|
|
6630
|
+
}
|
|
6631
|
+
await this.dial(result);
|
|
6632
|
+
this.deps.onGrant?.(result, true);
|
|
6633
|
+
} catch (error) {
|
|
6634
|
+
await this.revokeGrantBestEffort();
|
|
6635
|
+
if (this.stopped || this.settled) return;
|
|
6636
|
+
await this.fail(
|
|
6637
|
+
`Failed to renew the tunnel: ${error instanceof Error ? error.message : String(error)}`
|
|
6638
|
+
);
|
|
6639
|
+
}
|
|
6640
|
+
} finally {
|
|
6641
|
+
this.reminting = false;
|
|
6642
|
+
this.flushPendingPermanent();
|
|
6643
|
+
}
|
|
6644
|
+
}
|
|
6645
|
+
async fail(reason) {
|
|
6646
|
+
await this.cleanup();
|
|
6647
|
+
this.settle({ exitCode: 1, reason });
|
|
6648
|
+
}
|
|
6649
|
+
async cleanup() {
|
|
6650
|
+
this.connection?.close();
|
|
6651
|
+
this.connection = null;
|
|
6652
|
+
if (this.bridge) {
|
|
6653
|
+
const bridge = this.bridge;
|
|
6654
|
+
this.bridge = null;
|
|
6655
|
+
await bridge.close().catch(() => {
|
|
6656
|
+
});
|
|
6657
|
+
}
|
|
6658
|
+
}
|
|
6659
|
+
};
|
|
6660
|
+
|
|
6661
|
+
// src/commands/tunnel.ts
|
|
6662
|
+
function parseTunnelTarget(tokens) {
|
|
6663
|
+
const isUrl = (token) => /^https?:\/\//i.test(token);
|
|
6664
|
+
if (tokens.length === 0) {
|
|
6665
|
+
throw usageError(
|
|
6666
|
+
"Specify a target: a local server URL (mcpjam tunnel http://localhost:9090/mcp --id my-server) or a stdio command (mcpjam tunnel --id my-server -- npx -y @modelcontextprotocol/server-everything)."
|
|
6667
|
+
);
|
|
6668
|
+
}
|
|
6669
|
+
if (isUrl(tokens[0])) {
|
|
6670
|
+
if (tokens.length > 1) {
|
|
6671
|
+
throw usageError(
|
|
6672
|
+
"Pass either a URL or a stdio command (after --), not both."
|
|
6673
|
+
);
|
|
6674
|
+
}
|
|
6675
|
+
try {
|
|
6676
|
+
new URL(tokens[0]);
|
|
6677
|
+
} catch {
|
|
6678
|
+
throw usageError(`Invalid URL: ${tokens[0]}`);
|
|
6679
|
+
}
|
|
6680
|
+
return { kind: "http", url: tokens[0] };
|
|
6681
|
+
}
|
|
6682
|
+
return { kind: "stdio", command: tokens[0], args: tokens.slice(1) };
|
|
6683
|
+
}
|
|
6684
|
+
function overwriteWarning(result) {
|
|
6685
|
+
const grant = result.grant;
|
|
6686
|
+
if (!grant.existed) return void 0;
|
|
6687
|
+
if (grant.previousTransportType === "stdio") {
|
|
6688
|
+
return `WARNING: server "${grant.name ?? grant.serverId}" already existed as a stdio server \u2014 its config was converted to an HTTP server pointing at this tunnel.`;
|
|
6689
|
+
}
|
|
6690
|
+
if (grant.previousUrl) {
|
|
6691
|
+
return `WARNING: server "${grant.name ?? grant.serverId}" already existed \u2014 its URL was overwritten (was: ${grant.previousUrl}).`;
|
|
6692
|
+
}
|
|
6693
|
+
return void 0;
|
|
6694
|
+
}
|
|
6695
|
+
function publicHost(url) {
|
|
6696
|
+
try {
|
|
6697
|
+
return new URL(url).host || url;
|
|
6698
|
+
} catch {
|
|
6699
|
+
return url;
|
|
6700
|
+
}
|
|
6701
|
+
}
|
|
6702
|
+
function registerTunnelCommands(program) {
|
|
6703
|
+
program.command("tunnel").description(
|
|
6704
|
+
"Expose a local MCP server through an MCPJam tunnel and register it as a server in your project"
|
|
6705
|
+
).argument(
|
|
6706
|
+
"[target...]",
|
|
6707
|
+
"Local http(s) MCP server URL, or a stdio command after `--`"
|
|
6708
|
+
).requiredOption(
|
|
6709
|
+
"--id <name>",
|
|
6710
|
+
"Server name to register in the project (an existing server with this name is pointed at the tunnel)"
|
|
6711
|
+
).option(
|
|
6712
|
+
"--project <id-or-name>",
|
|
6713
|
+
"Project name or ID (defaults to the most recently updated project)"
|
|
6714
|
+
).option("--api-key <key>", "MCPJam sk_ API key (overrides MCPJAM_API_KEY)").option(
|
|
6715
|
+
"--api-url <url>",
|
|
6716
|
+
"MCPJam API base URL (defaults to https://app.mcpjam.com/api/v1)"
|
|
6717
|
+
).option(
|
|
6718
|
+
"-e, --env <env...>",
|
|
6719
|
+
'Stdio environment assignment in "KEY=VALUE" format. Pass multiple values or repeat the flag.'
|
|
6720
|
+
).option("--cwd <path>", "Working directory for the stdio MCP server process").action(
|
|
6721
|
+
async (target, options, command) => {
|
|
6722
|
+
const globalOptions = getGlobalOptions(command);
|
|
6723
|
+
const parsedTarget = parseTunnelTarget(target);
|
|
6724
|
+
if (parsedTarget.kind === "http" && ((options.env?.length ?? 0) > 0 || options.cwd)) {
|
|
6725
|
+
throw usageError(
|
|
6726
|
+
"--env and --cwd can only be used with a stdio command target."
|
|
6727
|
+
);
|
|
6728
|
+
}
|
|
6729
|
+
const status = (message) => {
|
|
6730
|
+
process.stderr.write(`${message}
|
|
6731
|
+
`);
|
|
6732
|
+
};
|
|
6733
|
+
const bridgeTarget = parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
|
|
6734
|
+
kind: "stdio",
|
|
6735
|
+
config: parseServerConfig({
|
|
6736
|
+
transport: "stdio",
|
|
6737
|
+
command: parsedTarget.command,
|
|
6738
|
+
args: parsedTarget.args,
|
|
6739
|
+
env: options.env,
|
|
6740
|
+
cwd: options.cwd,
|
|
6741
|
+
timeout: globalOptions.timeout
|
|
6742
|
+
})
|
|
6743
|
+
};
|
|
6744
|
+
let client;
|
|
6745
|
+
try {
|
|
6746
|
+
({ client } = buildPlatformClient({
|
|
6747
|
+
apiKey: options.apiKey,
|
|
6748
|
+
apiUrl: options.apiUrl,
|
|
6749
|
+
timeoutMs: globalOptions.timeout
|
|
6750
|
+
}));
|
|
6751
|
+
} catch (error) {
|
|
6752
|
+
throw toCliError(error);
|
|
6753
|
+
}
|
|
6754
|
+
const printStartup = (result) => {
|
|
6755
|
+
const warning = overwriteWarning(result);
|
|
6756
|
+
if (warning) status(warning);
|
|
6757
|
+
if (globalOptions.format === "human") {
|
|
6758
|
+
process.stdout.write(
|
|
6759
|
+
`Tunnel live: ${result.grant.url}
|
|
6760
|
+
Registered server "${result.grant.name ?? options.id}" in project "${result.project.name}" (${result.grant.serverId})
|
|
6761
|
+
`
|
|
6762
|
+
);
|
|
6763
|
+
status("Press Ctrl-C to stop the tunnel.");
|
|
6764
|
+
} else {
|
|
6765
|
+
writeResult(
|
|
6766
|
+
{
|
|
6767
|
+
url: result.grant.url,
|
|
6768
|
+
serverId: result.grant.serverId,
|
|
6769
|
+
name: result.grant.name ?? options.id,
|
|
6770
|
+
slug: result.grant.slug,
|
|
6771
|
+
project: result.project,
|
|
6772
|
+
existed: result.grant.existed ?? false,
|
|
6773
|
+
...result.grant.previousUrl ? { previousUrl: result.grant.previousUrl } : {},
|
|
6774
|
+
...result.grant.previousTransportType ? { previousTransportType: result.grant.previousTransportType } : {},
|
|
6775
|
+
...result.grant.secretVersion !== void 0 ? { secretVersion: result.grant.secretVersion } : {},
|
|
6776
|
+
target: parsedTarget.kind === "http" ? { kind: "http", url: parsedTarget.url } : {
|
|
6777
|
+
kind: "stdio",
|
|
6778
|
+
command: parsedTarget.command,
|
|
6779
|
+
args: parsedTarget.args
|
|
6780
|
+
}
|
|
6781
|
+
},
|
|
6782
|
+
globalOptions.format
|
|
6783
|
+
);
|
|
6784
|
+
}
|
|
6785
|
+
};
|
|
6786
|
+
const session = new TunnelSession({
|
|
6787
|
+
createGrant: (signal) => createTunnelOperation.execute(
|
|
6788
|
+
{ project: options.project, name: options.id },
|
|
6789
|
+
{ client, signal }
|
|
6790
|
+
),
|
|
6791
|
+
closeGrant: async (result, signal) => {
|
|
6792
|
+
await client.closeTunnel(
|
|
6793
|
+
{
|
|
6794
|
+
projectId: result.project.id,
|
|
6795
|
+
serverId: result.grant.serverId
|
|
6796
|
+
},
|
|
6797
|
+
{ signal }
|
|
6798
|
+
);
|
|
6799
|
+
},
|
|
6800
|
+
startBridge: (serverId) => startLocalBridge({
|
|
6801
|
+
serverId,
|
|
6802
|
+
target: bridgeTarget,
|
|
6803
|
+
timeoutMs: globalOptions.timeout,
|
|
6804
|
+
log: status
|
|
6805
|
+
}),
|
|
6806
|
+
connectRelay: ({ grant, localAddr, onPermanentFailure }) => new RelayConnection({
|
|
6807
|
+
serverId: grant.serverId,
|
|
6808
|
+
slug: grant.slug,
|
|
6809
|
+
relayWsUrl: grant.relayWsUrl,
|
|
6810
|
+
connectToken: grant.connectToken,
|
|
6811
|
+
localAddr,
|
|
6812
|
+
publicHost: publicHost(grant.url),
|
|
6813
|
+
logger: { info: status, warn: status },
|
|
6814
|
+
onPermanentFailure
|
|
6815
|
+
}),
|
|
6816
|
+
log: status,
|
|
6817
|
+
onGrant: (result, rotated) => {
|
|
6818
|
+
if (rotated) {
|
|
6819
|
+
status(`Tunnel secret rotated; new URL: ${result.grant.url}`);
|
|
6820
|
+
return;
|
|
6821
|
+
}
|
|
6822
|
+
printStartup(result);
|
|
6823
|
+
}
|
|
6824
|
+
});
|
|
6825
|
+
if (parsedTarget.kind === "stdio") {
|
|
6826
|
+
status(
|
|
6827
|
+
`Starting stdio server: ${parsedTarget.command}${parsedTarget.args.length ? ` ${parsedTarget.args.join(" ")}` : ""}`
|
|
6828
|
+
);
|
|
6829
|
+
}
|
|
6830
|
+
let sigints = 0;
|
|
6831
|
+
const onSignal = () => {
|
|
6832
|
+
sigints += 1;
|
|
6833
|
+
if (sigints === 1) {
|
|
6834
|
+
status("Shutting down tunnel... (Ctrl-C again to force quit)");
|
|
6835
|
+
void session.stop();
|
|
6836
|
+
return;
|
|
6837
|
+
}
|
|
6838
|
+
process.exit(130);
|
|
6839
|
+
};
|
|
6840
|
+
process.on("SIGINT", onSignal);
|
|
6841
|
+
process.on("SIGTERM", onSignal);
|
|
6842
|
+
try {
|
|
6843
|
+
const startPromise = session.start();
|
|
6844
|
+
try {
|
|
6845
|
+
await Promise.race([startPromise, session.waitUntilClosed()]);
|
|
6846
|
+
} catch (error) {
|
|
6847
|
+
if (sigints === 0) {
|
|
6848
|
+
throw toCliError(error);
|
|
6849
|
+
}
|
|
6850
|
+
}
|
|
6851
|
+
if (sigints > 0) {
|
|
6852
|
+
startPromise.catch(() => {
|
|
6853
|
+
});
|
|
6854
|
+
}
|
|
6855
|
+
const result = await session.waitUntilClosed();
|
|
6856
|
+
if (result.exitCode !== 0) {
|
|
6857
|
+
throw cliError(
|
|
6858
|
+
"TUNNEL_CLOSED",
|
|
6859
|
+
result.reason ?? "Tunnel closed",
|
|
6860
|
+
result.exitCode
|
|
6861
|
+
);
|
|
6862
|
+
}
|
|
6863
|
+
} finally {
|
|
6864
|
+
process.removeListener("SIGINT", onSignal);
|
|
6865
|
+
process.removeListener("SIGTERM", onSignal);
|
|
6866
|
+
}
|
|
6867
|
+
}
|
|
6868
|
+
);
|
|
6869
|
+
}
|
|
5839
6870
|
|
|
5840
6871
|
// src/commands/inspector.ts
|
|
5841
6872
|
function addInspectorUrlOption(command) {
|
|
@@ -5934,6 +6965,7 @@ async function main(argv = process.argv, dependencies = {}) {
|
|
|
5934
6965
|
registerProtocolCommands(program);
|
|
5935
6966
|
registerAuthCommands(program);
|
|
5936
6967
|
registerProjectsCommands(program);
|
|
6968
|
+
registerTunnelCommands(program);
|
|
5937
6969
|
registerInspectorCommands(program);
|
|
5938
6970
|
registerTelemetryCommands(program, dependencies.telemetry);
|
|
5939
6971
|
if (argv.length <= 2) {
|