dsh-mcp 1.13.0 → 1.14.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/CHANGELOG.en.md +26 -1
- package/CHANGELOG.md +26 -1
- package/README.en.md +42 -15
- package/README.md +36 -13
- package/lib/client.js +327 -19
- package/lib/index.js +179 -14
- package/lib/oauth.js +187 -10
- package/lib/probe.js +7 -1
- package/lib/system-ca.js +166 -0
- package/lib/transport.js +16 -0
- package/package.json +2 -2
- package/scripts/test.mjs +1 -0
- package/src/client/McpSettingsSection.module.css +21 -0
- package/src/client/McpSettingsSection.tsx +215 -4
- package/src/client/ServerForm.module.css +19 -0
- package/src/client/ServerForm.tsx +78 -10
- package/src/client/index.ts +27 -0
- package/src/client/locales.ts +28 -4
- package/src/client/remote-contribution.js +98 -0
- package/src/client/types.ts +49 -1
package/lib/index.js
CHANGED
|
@@ -2,7 +2,8 @@ import { randomBytes } from "node:crypto";
|
|
|
2
2
|
import { Service } from "@deepseek-ai/cordis";
|
|
3
3
|
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
4
4
|
import * as mcpClient from "./mcp-client.js";
|
|
5
|
-
import { createOAuthProvider, oauthCredentialRefs } from "./oauth.js";
|
|
5
|
+
import { clearAuthorizationResult, createOAuthProvider, createToolAuthorizationUrl, hasPendingAuthorization, isOAuthRequired, lastAuthorizationError, OAUTH_REQUIRED_CODE, oauthCredentialRefs, oauthTokenStatus, openAuthorizationUrl, pendingAuthorizationUrl } from "./oauth.js";
|
|
6
|
+
import { ensureSystemCaTrust } from "./system-ca.js";
|
|
6
7
|
import { probeConnection } from "./probe.js";
|
|
7
8
|
import { Remote, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
|
|
8
9
|
import { hostText } from "./host-locales.js";
|
|
@@ -384,6 +385,8 @@ let McpManagerService = (() => {
|
|
|
384
385
|
let _envSet_decorators;
|
|
385
386
|
let _adopt_decorators;
|
|
386
387
|
let _release_decorators;
|
|
388
|
+
let _oauthStart_decorators;
|
|
389
|
+
let _oauthStatus_decorators;
|
|
387
390
|
return class McpManagerService extends _classSuper {
|
|
388
391
|
static {
|
|
389
392
|
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
|
|
@@ -399,6 +402,8 @@ let McpManagerService = (() => {
|
|
|
399
402
|
_envSet_decorators = [Remote("envSet")];
|
|
400
403
|
_adopt_decorators = [Remote("adopt")];
|
|
401
404
|
_release_decorators = [Remote("release")];
|
|
405
|
+
_oauthStart_decorators = [Remote("oauthStart")];
|
|
406
|
+
_oauthStatus_decorators = [Remote("oauthStatus")];
|
|
402
407
|
__esDecorate(this, null, _list_decorators, {
|
|
403
408
|
kind: "method",
|
|
404
409
|
name: "list",
|
|
@@ -531,6 +536,28 @@ let McpManagerService = (() => {
|
|
|
531
536
|
},
|
|
532
537
|
metadata: _metadata
|
|
533
538
|
}, null, _instanceExtraInitializers);
|
|
539
|
+
__esDecorate(this, null, _oauthStart_decorators, {
|
|
540
|
+
kind: "method",
|
|
541
|
+
name: "oauthStart",
|
|
542
|
+
static: false,
|
|
543
|
+
private: false,
|
|
544
|
+
access: {
|
|
545
|
+
has: (obj) => "oauthStart" in obj,
|
|
546
|
+
get: (obj) => obj.oauthStart
|
|
547
|
+
},
|
|
548
|
+
metadata: _metadata
|
|
549
|
+
}, null, _instanceExtraInitializers);
|
|
550
|
+
__esDecorate(this, null, _oauthStatus_decorators, {
|
|
551
|
+
kind: "method",
|
|
552
|
+
name: "oauthStatus",
|
|
553
|
+
static: false,
|
|
554
|
+
private: false,
|
|
555
|
+
access: {
|
|
556
|
+
has: (obj) => "oauthStatus" in obj,
|
|
557
|
+
get: (obj) => obj.oauthStatus
|
|
558
|
+
},
|
|
559
|
+
metadata: _metadata
|
|
560
|
+
}, null, _instanceExtraInitializers);
|
|
534
561
|
if (_metadata) Object.defineProperty(this, Symbol.metadata, {
|
|
535
562
|
enumerable: true,
|
|
536
563
|
configurable: true,
|
|
@@ -580,6 +607,13 @@ let McpManagerService = (() => {
|
|
|
580
607
|
probeTimeoutMs;
|
|
581
608
|
/** Whether mounts may open the browser for OAuth authorization (see {@link Config.allowBrowserOnMount}). */
|
|
582
609
|
allowBrowserOnMount;
|
|
610
|
+
/**
|
|
611
|
+
* Opens the authorization page in the user's browser for the settings
|
|
612
|
+
* page's button. A host-side field so tests (and embedders) can replace
|
|
613
|
+
* it: a client-side `window.open` is denied or flashes-and-closes inside
|
|
614
|
+
* the DSH shell, while this runs `open`/`xdg-open`/`start` detached.
|
|
615
|
+
*/
|
|
616
|
+
openAuthorizationPage = openAuthorizationUrl;
|
|
583
617
|
/** Per-tool enable switches: a stored `false` disables that tool; absent means enabled. */
|
|
584
618
|
toolSwitches = /* @__PURE__ */ new Map();
|
|
585
619
|
/** Injection mode: `search` (default) injects only resident + hot tools; `full` injects every enabled tool. */
|
|
@@ -599,6 +633,14 @@ let McpManagerService = (() => {
|
|
|
599
633
|
}
|
|
600
634
|
/** Open the storage domain, mount stored servers, and subscribe to secret changes. */
|
|
601
635
|
async [Service.init]() {
|
|
636
|
+
// HTTPS MCP endpoints are verified against the operating-system trust
|
|
637
|
+
// store in addition to Node's bundled roots (see lib/system-ca.js):
|
|
638
|
+
// corporate/internal CAs exist only in the OS store, while both the
|
|
639
|
+
// streamable-http transport and the OAuth discovery/registration/token
|
|
640
|
+
// calls go through the process-wide fetch.
|
|
641
|
+
const caTrust = ensureSystemCaTrust();
|
|
642
|
+
if (caTrust.applied) this.ctx.logger.info(`mcp-manager: merged ${caTrust.added} system CA certificate(s) into the default TLS trust store`);
|
|
643
|
+
else this.ctx.logger.debug(`mcp-manager: system CA trust unchanged (${caTrust.reason})`);
|
|
602
644
|
const domain = await this.ctx.storageDomain.open(mcpServersDomainSpec);
|
|
603
645
|
this.ctx.effect(() => async () => {
|
|
604
646
|
await this.teardownAll();
|
|
@@ -1134,7 +1176,9 @@ let McpManagerService = (() => {
|
|
|
1134
1176
|
await this.disposeMount(id);
|
|
1135
1177
|
const entry = {
|
|
1136
1178
|
phase: "mounting",
|
|
1137
|
-
error: void 0
|
|
1179
|
+
error: void 0,
|
|
1180
|
+
/** True when the mount only failed because the user still has to authorize. */
|
|
1181
|
+
oauthRequired: false
|
|
1138
1182
|
};
|
|
1139
1183
|
this.mounts.set(id, entry);
|
|
1140
1184
|
let handle;
|
|
@@ -1151,13 +1195,24 @@ let McpManagerService = (() => {
|
|
|
1151
1195
|
const authProvider = this.wantsOAuthProvider(row)
|
|
1152
1196
|
? createOAuthProvider(row.serverName, this.ctx, {
|
|
1153
1197
|
allowBrowser: this.allowBrowserOnMount && this.claimAutoBrowser(row.serverName),
|
|
1154
|
-
serverUrl: row.url
|
|
1198
|
+
serverUrl: row.url,
|
|
1199
|
+
// The mcp-client wrapper replaces the thrown error, so
|
|
1200
|
+
// record the pending authorization here: the settings page
|
|
1201
|
+
// then shows "waiting for authorization" (plus the button)
|
|
1202
|
+
// instead of a red mount failure.
|
|
1203
|
+
onAuthorizationRequired: () => {
|
|
1204
|
+
entry.oauthRequired = true;
|
|
1205
|
+
}
|
|
1155
1206
|
})
|
|
1156
1207
|
: void 0;
|
|
1157
1208
|
handle = this.ctx.plugin(MCP_CLIENT_PLUGIN, { ...config, ...authProvider === void 0 ? {} : { authProvider } });
|
|
1158
1209
|
} catch (error) {
|
|
1159
1210
|
entry.phase = "failed";
|
|
1160
1211
|
entry.error = errorText(error);
|
|
1212
|
+
// The provider may already have flagged the pending
|
|
1213
|
+
// authorization (it knows before the error gets wrapped);
|
|
1214
|
+
// never clear that here.
|
|
1215
|
+
entry.oauthRequired = entry.oauthRequired || isOAuthRequired(error);
|
|
1161
1216
|
this.ctx.logger.error(`mcp-manager(${id}): mount failed: ${entry.error}`);
|
|
1162
1217
|
return;
|
|
1163
1218
|
}
|
|
@@ -1165,9 +1220,11 @@ let McpManagerService = (() => {
|
|
|
1165
1220
|
handle.await().then(() => {
|
|
1166
1221
|
entry.phase = "live";
|
|
1167
1222
|
entry.error = void 0;
|
|
1223
|
+
entry.oauthRequired = false;
|
|
1168
1224
|
}, (error) => {
|
|
1169
1225
|
entry.phase = "failed";
|
|
1170
1226
|
entry.error = errorText(error);
|
|
1227
|
+
entry.oauthRequired = entry.oauthRequired || isOAuthRequired(error);
|
|
1171
1228
|
this.ctx.logger.error(`mcp-manager(${id}): mount failed: ${entry.error}`);
|
|
1172
1229
|
});
|
|
1173
1230
|
});
|
|
@@ -1239,6 +1296,10 @@ let McpManagerService = (() => {
|
|
|
1239
1296
|
});
|
|
1240
1297
|
}
|
|
1241
1298
|
const mirrorNeedsPlugin = mirror ? this.declarationNeedsPlugin(row.transport, row.headers) : false;
|
|
1299
|
+
// OAuth state of a managed row: the settings page can show the
|
|
1300
|
+
// authorization button/badge without a second round trip, and a mount
|
|
1301
|
+
// that only waits for authorization is not rendered as a defect.
|
|
1302
|
+
const oauthState = !mirror && row.oauth === true ? await oauthTokenStatus(row.serverName, this.ctx) : void 0;
|
|
1242
1303
|
return {
|
|
1243
1304
|
id,
|
|
1244
1305
|
serverName: row.serverName,
|
|
@@ -1256,6 +1317,7 @@ let McpManagerService = (() => {
|
|
|
1256
1317
|
toolCallTimeoutMs: row.toolCallTimeoutMs,
|
|
1257
1318
|
failOnStartupError: row.failOnStartupError,
|
|
1258
1319
|
...(mirror ? {} : { oauth: row.oauth === true }),
|
|
1320
|
+
...(oauthState === void 0 ? {} : { oauthAuthorized: oauthState.authorized }),
|
|
1259
1321
|
...(mirrorNeedsPlugin ? { needsPlugin: true } : {}),
|
|
1260
1322
|
status: {
|
|
1261
1323
|
// A mirror never mounts here: its phase follows the declaration
|
|
@@ -1269,6 +1331,7 @@ let McpManagerService = (() => {
|
|
|
1269
1331
|
: mount?.phase ?? "stopped",
|
|
1270
1332
|
tools,
|
|
1271
1333
|
...(mount?.error === void 0 ? {} : { error: mount.error }),
|
|
1334
|
+
...(mount?.oauthRequired === true ? { oauthRequired: true } : {}),
|
|
1272
1335
|
...(mirror && mirrorNeedsPlugin && tools.length === 0 && row.enabled ? { error: "组合无法认证该声明(需要 OAuth 或 ${VAR} 占位符解析):请点「接管」,否则不会有工具" } : {})
|
|
1273
1336
|
},
|
|
1274
1337
|
source: mirror ? "cordis" : "plugin",
|
|
@@ -1663,21 +1726,28 @@ let McpManagerService = (() => {
|
|
|
1663
1726
|
} else if (entry.value !== void 0) env[entry.name] = entry.value;
|
|
1664
1727
|
const startedAt = Date.now();
|
|
1665
1728
|
// Test connection also supports OAuth: an OAuth-protected server
|
|
1666
|
-
//
|
|
1667
|
-
//
|
|
1729
|
+
// starts the authorization flow (tokens are keyed by serverName,
|
|
1730
|
+
// matching the mount path). The user asked for this probe, so a
|
|
1731
|
+
// server without the explicit switch still skips the provider — a
|
|
1732
|
+
// 401 from it reports an authentication failure instead of starting
|
|
1733
|
+
// a bogus flow.
|
|
1734
|
+
//
|
|
1735
|
+
// Test connection never opens the browser on its own any more: the
|
|
1736
|
+
// settings page owns an explicit "open the authorization page"
|
|
1737
|
+
// button, and a probe that needs authorization returns the pending
|
|
1738
|
+
// marker (plus the loopback listener the flow started) instead of
|
|
1739
|
+
// popping a tab or blocking for the interactive budget. The page then
|
|
1740
|
+
// polls oauthStatus every 5s and never renders a pre-authorization
|
|
1741
|
+
// failure.
|
|
1668
1742
|
const globalEnv = await this.resolveGlobalEnv();
|
|
1669
1743
|
const probeConfig = this.toClientConfig(request.server, env, globalEnv);
|
|
1670
|
-
// Test connection also supports OAuth: an OAuth-protected server
|
|
1671
|
-
// opens the browser for authorization and the probe continues after
|
|
1672
|
-
// tokens are stored (keyed by serverName, matching the mount path).
|
|
1673
|
-
// The user asked for this probe, so it may open the browser even
|
|
1674
|
-
// when the mount-time circuit breaker already fired; servers without
|
|
1675
|
-
// the explicit switch skip the provider so a 401 reports an
|
|
1676
|
-
// authentication failure instead of starting a bogus flow.
|
|
1677
1744
|
const probe = await probeConnection(probeConfig, {
|
|
1678
1745
|
timeoutMs: this.probeTimeoutMs,
|
|
1679
1746
|
...(this.wantsOAuthProvider(request.server)
|
|
1680
|
-
? { authProvider: createOAuthProvider(request.server.serverName, this.ctx, {
|
|
1747
|
+
? { authProvider: createOAuthProvider(request.server.serverName, this.ctx, {
|
|
1748
|
+
serverUrl: request.server.url,
|
|
1749
|
+
allowBrowser: false
|
|
1750
|
+
}) }
|
|
1681
1751
|
: {})
|
|
1682
1752
|
});
|
|
1683
1753
|
const elapsedMs = Date.now() - startedAt;
|
|
@@ -1688,11 +1758,106 @@ let McpManagerService = (() => {
|
|
|
1688
1758
|
tools: probe.tools
|
|
1689
1759
|
} : {
|
|
1690
1760
|
ok: false,
|
|
1691
|
-
message: probe.message
|
|
1761
|
+
message: probe.message,
|
|
1762
|
+
...(probe.code === OAUTH_REQUIRED_CODE ? { oauthRequired: true } : {})
|
|
1692
1763
|
},
|
|
1693
1764
|
elapsedMs
|
|
1694
1765
|
};
|
|
1695
1766
|
}
|
|
1767
|
+
/**
|
|
1768
|
+
* Start (or reuse) one server's OAuth authorization flow and return the
|
|
1769
|
+
* authorization URL for the settings page's button. The browser is opened
|
|
1770
|
+
* by the caller, never here, so the tab follows the user's click; a mount
|
|
1771
|
+
* or an earlier click already listening for this server returns the same
|
|
1772
|
+
* URL.
|
|
1773
|
+
* @param request - The server name plus the draft URL, or the stored row id.
|
|
1774
|
+
* @returns the authorization URL, or an explicit failure.
|
|
1775
|
+
*/
|
|
1776
|
+
async oauthStart(request) {
|
|
1777
|
+
const serverName = typeof request?.serverName === "string" ? request.serverName.trim() : "";
|
|
1778
|
+
if (serverName.length === 0 || !serverNameSchema.safeParse(serverName).success) return {
|
|
1779
|
+
ok: false,
|
|
1780
|
+
error: {
|
|
1781
|
+
code: "MCP_OAUTH_INVALID",
|
|
1782
|
+
message: "oauthStart requires a valid serverName"
|
|
1783
|
+
}
|
|
1784
|
+
};
|
|
1785
|
+
let url = typeof request?.url === "string" ? request.url.trim() : "";
|
|
1786
|
+
if (url.length === 0 && typeof request?.id === "string") url = this.requireTable().get(request.id)?.url ?? "";
|
|
1787
|
+
try {
|
|
1788
|
+
const parsed = new URL(url);
|
|
1789
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") throw new Error("non-http protocol");
|
|
1790
|
+
} catch {
|
|
1791
|
+
return {
|
|
1792
|
+
ok: false,
|
|
1793
|
+
error: {
|
|
1794
|
+
code: "MCP_OAUTH_INVALID",
|
|
1795
|
+
message: "oauthStart requires the server's absolute http(s) URL"
|
|
1796
|
+
}
|
|
1797
|
+
};
|
|
1798
|
+
}
|
|
1799
|
+
try {
|
|
1800
|
+
// A fresh attempt must not surface the previous flow's failure.
|
|
1801
|
+
clearAuthorizationResult(serverName);
|
|
1802
|
+
const authorizationUrl = await createToolAuthorizationUrl(serverName, this.ctx, url);
|
|
1803
|
+
// The click is the user's intent: open the system browser from
|
|
1804
|
+
// the host, where `open`/`xdg-open`/`start` works, instead of
|
|
1805
|
+
// relying on the shell's window.open policy. Best effort — the
|
|
1806
|
+
// page also renders the URL as a link.
|
|
1807
|
+
try {
|
|
1808
|
+
this.openAuthorizationPage(authorizationUrl);
|
|
1809
|
+
} catch (openError) {
|
|
1810
|
+
this.ctx.logger.warn(`mcp-manager: could not open the browser for "${serverName}": ${errorText(openError)}`);
|
|
1811
|
+
}
|
|
1812
|
+
return {
|
|
1813
|
+
ok: true,
|
|
1814
|
+
serverName,
|
|
1815
|
+
url: authorizationUrl
|
|
1816
|
+
};
|
|
1817
|
+
} catch (error) {
|
|
1818
|
+
return {
|
|
1819
|
+
ok: false,
|
|
1820
|
+
error: {
|
|
1821
|
+
code: "MCP_OAUTH_START_FAILED",
|
|
1822
|
+
message: errorText(error)
|
|
1823
|
+
}
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
/**
|
|
1828
|
+
* Poll one server's authorization state — the settings page calls this
|
|
1829
|
+
* every 5s while its flow is pending, instead of showing a failure before
|
|
1830
|
+
* the user authorized.
|
|
1831
|
+
* @param request - The server name.
|
|
1832
|
+
* @returns whether valid stored tokens exist, whether a callback listener is pending,
|
|
1833
|
+
* and the pending flow's authorization URL when there is one.
|
|
1834
|
+
*/
|
|
1835
|
+
async oauthStatus(request) {
|
|
1836
|
+
const serverName = typeof request?.serverName === "string" ? request.serverName.trim() : "";
|
|
1837
|
+
if (serverName.length === 0) return {
|
|
1838
|
+
ok: false,
|
|
1839
|
+
error: {
|
|
1840
|
+
code: "MCP_OAUTH_INVALID",
|
|
1841
|
+
message: "oauthStatus requires a serverName"
|
|
1842
|
+
}
|
|
1843
|
+
};
|
|
1844
|
+
const status = await oauthTokenStatus(serverName, this.ctx);
|
|
1845
|
+
const pending = hasPendingAuthorization(serverName);
|
|
1846
|
+
const authorizationUrl = pending ? pendingAuthorizationUrl(serverName) : void 0;
|
|
1847
|
+
// The last flow's failure (e.g. `access_denied` from the
|
|
1848
|
+
// authorization server, or a token exchange error), so the settings
|
|
1849
|
+
// page can say what happened instead of going quiet.
|
|
1850
|
+
const lastError = status.authorized ? void 0 : lastAuthorizationError(serverName);
|
|
1851
|
+
return {
|
|
1852
|
+
ok: true,
|
|
1853
|
+
serverName,
|
|
1854
|
+
authorized: status.authorized,
|
|
1855
|
+
pending,
|
|
1856
|
+
...(status.expiresAt === void 0 ? {} : { expiresAt: status.expiresAt }),
|
|
1857
|
+
...(authorizationUrl === void 0 ? {} : { url: authorizationUrl }),
|
|
1858
|
+
...(lastError === void 0 ? {} : { error: lastError })
|
|
1859
|
+
};
|
|
1860
|
+
}
|
|
1696
1861
|
/** Server namespace of one `mcp__<server>__<tool>` public name. */
|
|
1697
1862
|
serverOf(name) {
|
|
1698
1863
|
const rest = name.slice(5);
|
package/lib/oauth.js
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
} from "@modelcontextprotocol/client";
|
|
23
23
|
import { credentialRef } from "@deepseek-ai/dsh-credentials";
|
|
24
24
|
import { hostText } from "./host-locales.js";
|
|
25
|
+
import { systemFetch } from "./system-ca.js";
|
|
25
26
|
|
|
26
27
|
/**
|
|
27
28
|
* Error code marking an "OAuth authorization required" failure. Throwers set
|
|
@@ -101,6 +102,17 @@ function openBrowser(url) {
|
|
|
101
102
|
child.unref();
|
|
102
103
|
}
|
|
103
104
|
|
|
105
|
+
/**
|
|
106
|
+
* Open the authorization page in the user's browser. The host does this for a
|
|
107
|
+
* user-clicked "authorize" button: a client-side `window.open` is denied (or
|
|
108
|
+
* flashes and closes) inside the DSH shell, while the host's own opener starts
|
|
109
|
+
* the system browser reliably — the same path `allowBrowserOnMount` uses.
|
|
110
|
+
* @param url - the authorization URL.
|
|
111
|
+
*/
|
|
112
|
+
export function openAuthorizationUrl(url) {
|
|
113
|
+
openBrowser(url);
|
|
114
|
+
}
|
|
115
|
+
|
|
104
116
|
/**
|
|
105
117
|
* Extract the `exp` claim from a JWT access token, when it is a JWT.
|
|
106
118
|
* @param accessToken - The access token string.
|
|
@@ -161,6 +173,13 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
161
173
|
let savedClientInfo = null;
|
|
162
174
|
const allowBrowser = options.allowBrowser !== false;
|
|
163
175
|
const serverUrl = options.serverUrl;
|
|
176
|
+
// Called whenever the flow hands over to the user (URL known, tokens still
|
|
177
|
+
// missing). Mounts use it to mark their entry "waiting for authorization":
|
|
178
|
+
// the mcp-client wrapper replaces the thrown error, so the stable code does
|
|
179
|
+
// not survive to the caller.
|
|
180
|
+
const onAuthorizationRequired = typeof options.onAuthorizationRequired === "function"
|
|
181
|
+
? options.onAuthorizationRequired
|
|
182
|
+
: undefined;
|
|
164
183
|
const port = stablePort(serverId);
|
|
165
184
|
const redirectUrl = `http://127.0.0.1:${port}/callback`;
|
|
166
185
|
const log = ctx?.logger ?? console;
|
|
@@ -253,6 +272,17 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
253
272
|
return codeVerifierValue;
|
|
254
273
|
},
|
|
255
274
|
async redirectToAuthorization(authorizationUrl) {
|
|
275
|
+
if (!allowBrowser && serverUrl !== void 0) {
|
|
276
|
+
// Non-interactive attempt (a mount with browser prompts disabled, or a
|
|
277
|
+
// test connection): never open a browser and never queue behind another
|
|
278
|
+
// server's interactive flow — just make sure this server's pending
|
|
279
|
+
// listener exists and hand its URL to the caller, who owns the button
|
|
280
|
+
// and the status polling.
|
|
281
|
+
const url = await createToolAuthorizationUrl(serverId, ctx, serverUrl);
|
|
282
|
+
log.info(`${tag}: authorization required, not opening browser`);
|
|
283
|
+
onAuthorizationRequired?.(url);
|
|
284
|
+
throw oauthRequired(new Error(hostText(ctx, "oauthNeedLink", { serverId, url })));
|
|
285
|
+
}
|
|
256
286
|
// Global serialization: at most one browser authorization runs at a
|
|
257
287
|
// time (stable per-server ports would otherwise collide, and several
|
|
258
288
|
// OAuth servers at startup would open many tabs at once).
|
|
@@ -280,6 +310,7 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
280
310
|
// instead of both binding the stable port (an unhandled EADDRINUSE
|
|
281
311
|
// on listen would crash the Host).
|
|
282
312
|
const url = await createToolAuthorizationUrl(serverId, ctx, serverUrl);
|
|
313
|
+
onAuthorizationRequired?.(url);
|
|
283
314
|
if (!allowBrowser) {
|
|
284
315
|
// Mount-time connections must not pop the browser on their own;
|
|
285
316
|
// fail with the clickable authorization link. The shared
|
|
@@ -304,8 +335,12 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
304
335
|
const code = url.searchParams.get("code");
|
|
305
336
|
const error = url.searchParams.get("error");
|
|
306
337
|
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
338
|
+
// No keep-alive: the stable port may be reused by the next flow (see
|
|
339
|
+
// closeCallbackServer).
|
|
340
|
+
res.setHeader("connection", "close");
|
|
307
341
|
if (error) {
|
|
308
342
|
res.end(hostText(ctx, "oauthFailPage", { error }));
|
|
343
|
+
recordAuthResult(serverId, error);
|
|
309
344
|
log.error(`${tag}: callback rejected: ${error}`);
|
|
310
345
|
resolveResult({ error });
|
|
311
346
|
return;
|
|
@@ -326,7 +361,7 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
326
361
|
if (result.error) throw oauthRequired(new Error(hostText(ctx, "oauthExchangeFail", { error: result.error })));
|
|
327
362
|
const authServerUrl = new URL(authorizationUrl.origin);
|
|
328
363
|
log.info(`${tag}: discovering authorization server metadata at ${authServerUrl}`);
|
|
329
|
-
const metadata = await discoverAuthorizationServerMetadata(authServerUrl);
|
|
364
|
+
const metadata = await discoverAuthorizationServerMetadata(authServerUrl, { fetchFn: systemFetch() });
|
|
330
365
|
log.info(`${tag}: exchanging authorization code for tokens`);
|
|
331
366
|
// Use the provider accessors, not the closure fields: when the
|
|
332
367
|
// client was loaded from persistence the SDK never calls
|
|
@@ -340,14 +375,17 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
340
375
|
authorizationCode: result.code,
|
|
341
376
|
codeVerifier,
|
|
342
377
|
redirectUri: redirectUrl,
|
|
378
|
+
fetchFn: systemFetch(),
|
|
343
379
|
});
|
|
344
380
|
await this.saveTokens(tokens);
|
|
381
|
+
recordAuthResult(serverId);
|
|
345
382
|
log.info(`${tag}: tokens saved`);
|
|
346
383
|
} catch (error) {
|
|
384
|
+
recordAuthResult(serverId, error instanceof Error ? error.message : String(error));
|
|
347
385
|
log.error(`${tag}: OAuth exchange failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
348
386
|
throw error;
|
|
349
387
|
} finally {
|
|
350
|
-
server
|
|
388
|
+
closeCallbackServer(server);
|
|
351
389
|
log.info(`${tag}: callback server closed`);
|
|
352
390
|
}
|
|
353
391
|
});
|
|
@@ -355,9 +393,65 @@ export function createOAuthProvider(serverId, ctx, options = {}) {
|
|
|
355
393
|
};
|
|
356
394
|
}
|
|
357
395
|
|
|
396
|
+
/**
|
|
397
|
+
* Stop one loopback callback listener for good: stop accepting, then drop any
|
|
398
|
+
* connection still open (a graceful `close()` alone waits for keep-alive
|
|
399
|
+
* sockets and can leave the stable port bound across a retry).
|
|
400
|
+
* @param server - the loopback http server.
|
|
401
|
+
*/
|
|
402
|
+
function closeCallbackServer(server) {
|
|
403
|
+
try {
|
|
404
|
+
server.close();
|
|
405
|
+
} catch {
|
|
406
|
+
/* already closed */
|
|
407
|
+
}
|
|
408
|
+
server.closeAllConnections?.();
|
|
409
|
+
}
|
|
410
|
+
|
|
358
411
|
/** Pending background authorization callbacks per server (one at a time). */
|
|
359
412
|
const pendingCallbacks = /* @__PURE__ */ new Map();
|
|
360
413
|
|
|
414
|
+
/**
|
|
415
|
+
* In-flight authorization-URL creations per server. Two callers (a mount and a
|
|
416
|
+
* test connection, or the settings-page button) can ask for the same server's
|
|
417
|
+
* URL at once; without this they would both run discovery/registration and
|
|
418
|
+
* both bind the stable loopback port.
|
|
419
|
+
*/
|
|
420
|
+
const pendingCreations = /* @__PURE__ */ new Map();
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Outcome of the most recent authorization flow per server: the `error` the
|
|
424
|
+
* authorization server reported on the callback (e.g. `access_denied`), or the
|
|
425
|
+
* token exchange failure. The settings page polls this so "did authorization
|
|
426
|
+
* fail, and why" is visible instead of silence.
|
|
427
|
+
*/
|
|
428
|
+
const lastAuthResults = /* @__PURE__ */ new Map();
|
|
429
|
+
|
|
430
|
+
/** Record one flow's outcome (no error = the flow completed). */
|
|
431
|
+
function recordAuthResult(serverId, error) {
|
|
432
|
+
lastAuthResults.set(serverId, {
|
|
433
|
+
...error === undefined ? {} : { error: String(error) },
|
|
434
|
+
at: Date.now()
|
|
435
|
+
});
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* The error of the most recent authorization flow, when it failed.
|
|
440
|
+
* @param serverId - managed server id / server name the flow is keyed by.
|
|
441
|
+
*/
|
|
442
|
+
export function lastAuthorizationError(serverId) {
|
|
443
|
+
return lastAuthResults.get(serverId)?.error;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/**
|
|
447
|
+
* Forget the previous flow outcome so a fresh attempt does not report a stale
|
|
448
|
+
* failure while it is still running.
|
|
449
|
+
* @param serverId - managed server id / server name the flow is keyed by.
|
|
450
|
+
*/
|
|
451
|
+
export function clearAuthorizationResult(serverId) {
|
|
452
|
+
lastAuthResults.delete(serverId);
|
|
453
|
+
}
|
|
454
|
+
|
|
361
455
|
/**
|
|
362
456
|
* Build an authorization URL for a tool call that needs authorization and
|
|
363
457
|
* start a background loopback listener that completes the flow when the user
|
|
@@ -370,14 +464,27 @@ const pendingCallbacks = /* @__PURE__ */ new Map();
|
|
|
370
464
|
* @returns the authorization URL to present to the user.
|
|
371
465
|
*/
|
|
372
466
|
export async function createToolAuthorizationUrl(serverId, ctx, serverUrl) {
|
|
467
|
+
const existing = pendingCallbacks.get(serverId);
|
|
468
|
+
if (existing !== void 0) return existing.url;
|
|
469
|
+
const inFlight = pendingCreations.get(serverId);
|
|
470
|
+
if (inFlight !== void 0) return inFlight;
|
|
471
|
+
const creation = createToolAuthorizationUrlOnce(serverId, ctx, serverUrl);
|
|
472
|
+
pendingCreations.set(serverId, creation);
|
|
473
|
+
try {
|
|
474
|
+
return await creation;
|
|
475
|
+
} finally {
|
|
476
|
+
pendingCreations.delete(serverId);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** One server's flow, created at most once at a time (see createToolAuthorizationUrl). */
|
|
481
|
+
async function createToolAuthorizationUrlOnce(serverId, ctx, serverUrl) {
|
|
373
482
|
const port = stablePort(serverId);
|
|
374
483
|
const redirectUrl = `http://127.0.0.1:${port}/callback`;
|
|
375
484
|
const log = ctx?.logger ?? console;
|
|
376
485
|
const tag = `mcp-oauth(${serverId})`;
|
|
377
|
-
const existing = pendingCallbacks.get(serverId);
|
|
378
|
-
if (existing !== void 0) return existing.url;
|
|
379
486
|
|
|
380
|
-
const info = await discoverOAuthServerInfo(serverUrl, { fetchFn:
|
|
487
|
+
const info = await discoverOAuthServerInfo(serverUrl, { fetchFn: systemFetch() });
|
|
381
488
|
let clientInfo = await ctx.credentials.resolve(oauthClientRef(serverId));
|
|
382
489
|
if (clientInfo !== void 0) {
|
|
383
490
|
try {
|
|
@@ -396,7 +503,7 @@ export async function createToolAuthorizationUrl(serverId, ctx, serverUrl) {
|
|
|
396
503
|
client_name: "dsh-mcp",
|
|
397
504
|
redirect_uris: [redirectUrl],
|
|
398
505
|
},
|
|
399
|
-
fetchFn:
|
|
506
|
+
fetchFn: systemFetch(),
|
|
400
507
|
});
|
|
401
508
|
await ctx.credentials.set(oauthClientRef(serverId), JSON.stringify(clientInfo));
|
|
402
509
|
}
|
|
@@ -423,32 +530,41 @@ export async function createToolAuthorizationUrl(serverId, ctx, serverUrl) {
|
|
|
423
530
|
const code = callbackUrl.searchParams.get("code");
|
|
424
531
|
const error = callbackUrl.searchParams.get("error");
|
|
425
532
|
res.setHeader("content-type", "text/html; charset=utf-8");
|
|
533
|
+
// Never keep the callback connection alive: the stable loopback port is
|
|
534
|
+
// reused by the next flow, and a pooled keep-alive socket would deliver
|
|
535
|
+
// its callback to THIS (already closing) listener instead of the new
|
|
536
|
+
// one — the retry would then poll forever.
|
|
537
|
+
res.setHeader("connection", "close");
|
|
426
538
|
if (error) {
|
|
427
539
|
res.end(hostText(ctx, "oauthFailPage", { error }));
|
|
540
|
+
recordAuthResult(serverId, error);
|
|
428
541
|
log.error(`${tag}: callback rejected: ${error}`);
|
|
429
542
|
resolve();
|
|
430
|
-
server
|
|
543
|
+
closeCallbackServer(server);
|
|
431
544
|
return;
|
|
432
545
|
}
|
|
433
546
|
res.end(hostText(ctx, "oauthOkPage"));
|
|
434
547
|
log.info(`${tag}: tool-auth callback received (code)`);
|
|
435
548
|
try {
|
|
436
549
|
const authServerUrl = new URL(authorizationUrl.origin);
|
|
437
|
-
const metadata = await discoverAuthorizationServerMetadata(authServerUrl);
|
|
550
|
+
const metadata = await discoverAuthorizationServerMetadata(authServerUrl, { fetchFn: systemFetch() });
|
|
438
551
|
const tokens = await exchangeAuthorization(authServerUrl, {
|
|
439
552
|
metadata,
|
|
440
553
|
clientInformation: clientInfo,
|
|
441
554
|
authorizationCode: code,
|
|
442
555
|
codeVerifier,
|
|
443
556
|
redirectUri: redirectUrl,
|
|
557
|
+
fetchFn: systemFetch(),
|
|
444
558
|
});
|
|
445
559
|
await ctx.credentials.set(oauthTokenRef(serverId), JSON.stringify(tokens));
|
|
560
|
+
recordAuthResult(serverId);
|
|
446
561
|
log.info(`${tag}: tool-auth tokens saved`);
|
|
447
562
|
} catch (exchangeError) {
|
|
563
|
+
recordAuthResult(serverId, exchangeError instanceof Error ? exchangeError.message : String(exchangeError));
|
|
448
564
|
log.error(`${tag}: tool-auth exchange failed: ${exchangeError instanceof Error ? exchangeError.message : String(exchangeError)}`);
|
|
449
565
|
}
|
|
450
566
|
resolve();
|
|
451
|
-
server
|
|
567
|
+
closeCallbackServer(server);
|
|
452
568
|
});
|
|
453
569
|
// Never let a bind failure crash the Host: resolve the pending flow so
|
|
454
570
|
// callers surface a readable error instead of an unhandled event.
|
|
@@ -462,7 +578,7 @@ export async function createToolAuthorizationUrl(serverId, ctx, serverUrl) {
|
|
|
462
578
|
// Give up after 5 minutes so the listener never leaks.
|
|
463
579
|
const timer = setTimeout(() => {
|
|
464
580
|
log.info(`${tag}: tool-auth listener expired`);
|
|
465
|
-
server
|
|
581
|
+
closeCallbackServer(server);
|
|
466
582
|
resolve();
|
|
467
583
|
}, 5 * 60e3);
|
|
468
584
|
timer.unref?.();
|
|
@@ -474,3 +590,64 @@ export async function createToolAuthorizationUrl(serverId, ctx, serverUrl) {
|
|
|
474
590
|
});
|
|
475
591
|
return url;
|
|
476
592
|
}
|
|
593
|
+
|
|
594
|
+
/**
|
|
595
|
+
* Whether a failure means "the user still has to authorize" rather than a real
|
|
596
|
+
* connection failure. Two shapes reach the caller: our own marker error
|
|
597
|
+
* (`MCP_OAUTH_REQUIRED`, thrown when the flow is handed over without opening a
|
|
598
|
+
* browser), and the SDK's `UnauthorizedError` raised right after
|
|
599
|
+
* `redirectToAuthorization` returned (the browser flow is running and this
|
|
600
|
+
* attempt is expected to fail).
|
|
601
|
+
* @param error - the thrown value.
|
|
602
|
+
* @returns true when the failure is a pending authorization, not a defect.
|
|
603
|
+
*/
|
|
604
|
+
export function isOAuthRequired(error) {
|
|
605
|
+
if (error === null || typeof error !== "object") return false;
|
|
606
|
+
if (error.code === OAUTH_REQUIRED_CODE) return true;
|
|
607
|
+
return error.mcpBrand === "mcp.UnauthorizedError" || error.name === "UnauthorizedError";
|
|
608
|
+
}
|
|
609
|
+
|
|
610
|
+
/**
|
|
611
|
+
* The stored-token state of one server, without touching the network. An
|
|
612
|
+
* expired access token counts as not authorized (the provider clears it so the
|
|
613
|
+
* SDK starts a fresh browser flow), which is what a polling settings page must
|
|
614
|
+
* see before showing "authorization complete".
|
|
615
|
+
* @param serverId - managed server id / server name the tokens are keyed by.
|
|
616
|
+
* @param ctx - host context carrying the credentials service.
|
|
617
|
+
* @returns `authorized`, plus the JWT expiry (ms) when one is known.
|
|
618
|
+
*/
|
|
619
|
+
export async function oauthTokenStatus(serverId, ctx) {
|
|
620
|
+
let hit;
|
|
621
|
+
try {
|
|
622
|
+
hit = await ctx.credentials.resolve(oauthTokenRef(serverId));
|
|
623
|
+
} catch {
|
|
624
|
+
return { authorized: false };
|
|
625
|
+
}
|
|
626
|
+
if (hit === undefined || hit === null) return { authorized: false };
|
|
627
|
+
let tokens;
|
|
628
|
+
try {
|
|
629
|
+
tokens = JSON.parse(hit.value);
|
|
630
|
+
} catch {
|
|
631
|
+
return { authorized: false };
|
|
632
|
+
}
|
|
633
|
+
const exp = jwtExp(tokens?.access_token);
|
|
634
|
+
if (exp !== undefined && Date.now() / 1000 >= exp) return { authorized: false, expiresAt: exp * 1000 };
|
|
635
|
+
return { authorized: true, ...(exp === undefined ? {} : { expiresAt: exp * 1000 }) };
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
/**
|
|
639
|
+
* Whether a background authorization callback is currently listening for one
|
|
640
|
+
* server (a mount attempt or a test connection started the flow).
|
|
641
|
+
* @param serverId - managed server id / server name the flow is keyed by.
|
|
642
|
+
*/
|
|
643
|
+
export function hasPendingAuthorization(serverId) {
|
|
644
|
+
return pendingCallbacks.has(serverId);
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
/**
|
|
648
|
+
* The authorization URL of a running pending flow, when there is one.
|
|
649
|
+
* @param serverId - managed server id / server name the flow is keyed by.
|
|
650
|
+
*/
|
|
651
|
+
export function pendingAuthorizationUrl(serverId) {
|
|
652
|
+
return pendingCallbacks.get(serverId)?.url;
|
|
653
|
+
}
|
package/lib/probe.js
CHANGED
|
@@ -55,7 +55,13 @@ async function probeConnection(config, options = {}) {
|
|
|
55
55
|
};
|
|
56
56
|
return await Promise.race([runProbe(client, transportConfig), timeout]);
|
|
57
57
|
} catch (error) {
|
|
58
|
-
return {
|
|
58
|
+
return {
|
|
59
|
+
ok: false,
|
|
60
|
+
message: probeErrorMessage(error),
|
|
61
|
+
// Stable code for callers that must branch on the failure kind (OAuth
|
|
62
|
+
// authorization pending vs a real connection failure); never parse text.
|
|
63
|
+
...typeof error?.code === "string" ? { code: error.code } : {}
|
|
64
|
+
};
|
|
59
65
|
} finally {
|
|
60
66
|
try {
|
|
61
67
|
await client.close();
|