dsh-mcp-connector 0.2.113 → 0.2.115

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.
Files changed (50) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.en.md +12 -12
  3. package/README.md +11 -11
  4. package/docs/PLUGIN-UPDATE.md +16 -4
  5. package/docs/SESSION-TOOL-INJECTION.md +13 -7
  6. package/docs/STDIO-SUPPORT.md +2 -2
  7. package/docs/USER-GUIDE.md +14 -4
  8. package/docs/screenshots/01-market-overview.jpg +0 -0
  9. package/docs/screenshots/02-connector-detail.jpg +0 -0
  10. package/docs/screenshots/03-tool-discovery.jpg +0 -0
  11. package/docs/screenshots/04-json-import.jpg +0 -0
  12. package/docs/screenshots/05-unified-tool-search.png +0 -0
  13. package/docs/screenshots/06-tool-parameters.png +0 -0
  14. package/docs/screenshots/07-connection-diagnostics.png +0 -0
  15. package/docs/screenshots/08-ten-recommendations.jpg +0 -0
  16. package/docs/screenshots/README.md +1 -1
  17. package/docs/screenshots/assets.json +30 -30
  18. package/docs/screenshots/en/01-market-overview.jpg +0 -0
  19. package/docs/screenshots/en/02-connector-detail.jpg +0 -0
  20. package/docs/screenshots/en/03-tool-discovery.jpg +0 -0
  21. package/docs/screenshots/en/04-json-import.jpg +0 -0
  22. package/docs/screenshots/en/05-unified-tool-search.png +0 -0
  23. package/docs/screenshots/en/06-tool-parameters.png +0 -0
  24. package/docs/screenshots/en/07-connection-diagnostics.png +0 -0
  25. package/docs/screenshots/en/08-ten-recommendations.jpg +0 -0
  26. package/docs/screenshots/en/assets.json +30 -30
  27. package/docs/screenshots/en/demo.gif +0 -0
  28. package/docs/tutorials/FIRST-SUCCESS-SCENARIOS.md +1 -1
  29. package/lib/catalog.js +2 -2
  30. package/lib/client.js +224 -43
  31. package/lib/connection-editor.js +1 -1
  32. package/lib/connectors/json-connector.js +2 -2
  33. package/lib/connectors/manual-connector.js +2 -2
  34. package/lib/custom-oauth.js +2 -2
  35. package/lib/i18n/locales/en/client.js +16 -0
  36. package/lib/i18n/locales/en/tools.js +1 -1
  37. package/lib/i18n/locales/en/upgrade.js +1 -1
  38. package/lib/index.js +11 -5
  39. package/lib/legacy-sse-bridge.js +46 -0
  40. package/lib/legacy-sse.js +174 -0
  41. package/lib/mcp-http.js +5 -1
  42. package/lib/mcp-provision.js +12 -0
  43. package/lib/mcp-validation.js +4 -0
  44. package/lib/probe.js +30 -21
  45. package/lib/schema.js +8 -8
  46. package/lib/shareable-connection-template.js +6 -4
  47. package/lib/tools.js +1 -1
  48. package/lib/version-status.js +2 -0
  49. package/package.json +2 -2
  50. package/ui/index.html +1 -1
@@ -39,8 +39,8 @@ function coerceEnv(env, { t = tZh } = {}) {
39
39
 
40
40
  function normalizeTransport(value, hasCommand = false) {
41
41
  const raw = value ?? (hasCommand ? 'stdio' : 'streamable-http');
42
- if (raw === 'sse' || raw === 'http') return 'streamable-http';
43
- if (raw === 'streamable-http' || raw === 'stdio') return raw;
42
+ if (raw === 'streamableHttp' || raw === 'http') return 'streamable-http';
43
+ if (raw === 'streamable-http' || raw === 'stdio' || raw === 'sse') return raw;
44
44
  throw new Error(`unsupported transport: ${raw}`);
45
45
  }
46
46
 
@@ -56,8 +56,8 @@ export function buildManualRecord(params = {}, { t = tZh } = {}) {
56
56
  if (!name) throw new Error(t('name 必填'));
57
57
  const serverName = slugServerName(params.serverName ?? name);
58
58
  const rawTransport = params.transport ?? 'streamable-http';
59
- const transport = rawTransport === 'sse' ? 'streamable-http' : rawTransport;
60
- if (!['streamable-http', 'stdio'].includes(transport)) throw new Error(`unsupported transport: ${rawTransport}`);
59
+ const transport = rawTransport;
60
+ if (!['streamable-http', 'sse', 'stdio'].includes(transport)) throw new Error(`unsupported transport: ${rawTransport}`);
61
61
 
62
62
  if (transport === 'stdio') {
63
63
  const command = String(params.command ?? '').trim();
@@ -23,7 +23,7 @@ export async function prepareCustomConnections(records, { timeoutMs, t = createT
23
23
  for (const input of records) {
24
24
  const record = { ...input, pendingAuthorization: false, oauthDiscovery: undefined };
25
25
  const result = await validateConnectionRecord(record, { timeoutMs, t });
26
- const eligible = record.transport === 'streamable-http' && record.authDetection !== 'none'
26
+ const eligible = ['streamable-http', 'sse'].includes(record.transport) && record.authDetection !== 'none'
27
27
  && !record.auth && !Object.keys(record.headers ?? {}).length && !record.allowInsecurePrivateNetwork;
28
28
  if (!result.ok && result.httpStatus === 401 && eligible) {
29
29
  try {
@@ -48,5 +48,5 @@ export async function prepareCustomConnections(records, { timeoutMs, t = createT
48
48
  export function customOAuthDescriptor(record) {
49
49
  return { id: record.key, name: record.name,
50
50
  auth: { mode: 'oauth2-pkce', ...record.oauthDiscovery, clientName: 'DeepSeek Harness - MCP Connector', tokenEndpointAuthMethod: 'none', grantSharing: 'connector' },
51
- servers: [{ serverKey: record.serverName, serverName: record.serverName, url: record.url, oauthResource: record.oauthDiscovery.resource, transport: 'streamable-http' }] };
51
+ servers: [{ serverKey: record.serverName, serverName: record.serverName, url: record.url, oauthResource: record.oauthDiscovery.resource, transport: record.transport }] };
52
52
  }
@@ -71,6 +71,18 @@ export default {
71
71
  "重试更新": "Retry update",
72
72
  "检测到异常版本,正在自动回滚…": "An unexpected version was detected. Rolling back automatically…",
73
73
  "查看更新方式": "See update options",
74
+ "当前版本 v{current},发现新版本 v{target}": "Current version v{current}, new version v{target}",
75
+ "暂时无法确认 MCP 连接器是否有新版本。": "Could not check whether a new MCP Connector version is available.",
76
+ "重新检查失败,显示上次发现的版本。": "The check failed. Showing the previously found version.",
77
+ "重新检查": "Check again",
78
+ "查看手动升级命令": "View manual upgrade command",
79
+ "前往更新": "Go to update",
80
+
81
+ "npm 尚未确认此版本,暂时无法提供升级命令。": "An upgrade command will be available once npm confirms this version.",
82
+ "从插件页更新": "Update from the plugin page",
83
+ "请打开侧栏“插件” → “已安装” → dsh-mcp-connector,查看当前可用的更新。": "Open Plugins in the sidebar, select Installed, and choose dsh-mcp-connector to see available updates.",
84
+ "未能打开插件详情页。": "Could not open the plugin details page. ",
85
+ "请打开侧栏“插件” → “已安装” → dsh-mcp-connector,然后点击“更新到 v{version}”。": "Open Plugins in the sidebar, select Installed, choose dsh-mcp-connector, then click Update to v{version}.",
74
86
  "已回滚": "Rolled back",
75
87
  "已阻止异常版本并回滚": "Blocked the unexpected version and rolled back",
76
88
  "已安装 v{version}": "Installed v{version}",
@@ -89,6 +101,10 @@ export default {
89
101
  "正在准备更新…": "Preparing the update…",
90
102
  "由 {provider} 安全更新到 v{version}": "Update safely to v{version} via {provider}",
91
103
  "更新服务": "the update service",
104
+ "更新到 v{version}": "Update to v{version}",
105
+ "使用 Web 启动时的终端": "Use the terminal where you started the Web app",
106
+ "查看升级方式": "View upgrade methods",
107
+ "收起升级方式": "Hide upgrade methods",
92
108
  "一键更新到 v{version}": "Update to v{version}",
93
109
  "v{version} 已安装,重启后生效": "v{version} is installed and takes effect after a restart",
94
110
  "已复制": "Copied",
@@ -61,7 +61,7 @@ export default {
61
61
  "连接展示名": "Connection display name",
62
62
  "MCP 端点 URL(https 或回环 http;私有 IP 的 http 需显式授权)": "MCP endpoint URL (https, or http on loopback; http on private IPs requires explicit authorization)",
63
63
  "仅用于用户自建连接:显式授权 RFC1918 IPv4 / RFC4193 IPv6 ULA 字面量使用明文 HTTP;公网 HTTP 与域名仍拒绝": "For user-defined connections only: explicitly allow plain HTTP for RFC1918 IPv4 / RFC4193 IPv6 ULA literals; public HTTP and domain names are still rejected",
64
- "传输方式;sse 会兼容归一为 streamable-http": "Transport; sse is normalized to streamable-http for compatibility",
64
+ "传输方式;sse 保留旧版 HTTP + SSE 协议": "Transport; sse preserves the legacy HTTP + SSE protocol",
65
65
  "transport=stdio 时的启动命令(如 npx、uvx)": "Startup command for transport=stdio (for example npx, uvx)",
66
66
  "transport=stdio 时的参数列表": "Argument list for transport=stdio",
67
67
  "transport=stdio 时的环境变量 JSON;可能含凭据,仅保存在本机": "Environment variables as JSON for transport=stdio; may contain credentials and is stored only on this machine",
@@ -31,7 +31,7 @@ export default {
31
31
  "目录引用不在包内已审计的公开目录中": "The catalog reference is not in the audited bundled public catalog",
32
32
  "目录引用与包内已审计记录不匹配": "The catalog reference does not match the audited bundled record",
33
33
  "请明确选择一条连接": "Select one connection explicitly",
34
- "只有已归一化的 Streamable HTTP 自定义连接可生成重填模板": "Only normalized custom Streamable HTTP connections support reentry templates",
34
+ "只有 HTTP 或 SSE 自定义连接可生成重填模板": "Only custom HTTP or SSE connections support reentry templates",
35
35
  "OAuth 连接不导出本机状态;请选择对应的公开目录模板": "OAuth connections do not export local state; choose the matching public catalog template",
36
36
  "自定义 stdio 的命令、参数、env 和路径无法安全判断;请使用公开目录模板": "Custom stdio commands, arguments, environment variables, and paths cannot be safely assessed; use a public catalog template",
37
37
  "含额外 Headers 的自定义连接不可分享;无法仅凭名称证明其不含凭据": "Custom connections with additional headers cannot be shared; header names alone cannot prove they contain no credentials",
package/lib/index.js CHANGED
@@ -352,13 +352,19 @@ export async function apply(ctx, config) {
352
352
  let catalogDisposed = false;
353
353
  let catalogWrite = Promise.resolve();
354
354
 
355
- async function updateRemoteCatalog(cached) {
355
+ async function updateRemoteCatalog(cached, { preferOrigin = false } = {}) {
356
356
  catalogController?.abort();
357
357
  const controller = new AbortController();
358
358
  catalogController = controller;
359
- const fetched = await fetchRemoteCatalogWithFallback(config.catalogUrl, catalogFallbackUrls(), {
359
+ // Explicit refresh must not accept a stale-but-successful CDN response first.
360
+ // Only the built-in registry has a trusted origin; custom URLs stay unchanged.
361
+ const fallbacks = catalogFallbackUrls();
362
+ const originFirst = preferOrigin && fallbacks.length > 0;
363
+ const primaryUrl = originFirst ? fallbacks[0] : config.catalogUrl;
364
+ const otherUrls = originFirst ? [...fallbacks.slice(1), config.catalogUrl] : fallbacks;
365
+ const fetched = await fetchRemoteCatalogWithFallback(primaryUrl, otherUrls, {
360
366
  requestTimeoutMs: config.requestTimeoutMs,
361
- etag: cached?.etag,
367
+ etag: originFirst ? undefined : cached?.etag,
362
368
  signal: controller.signal,
363
369
  onSourceError: warnCatalogSourceFailure,
364
370
  });
@@ -370,7 +376,7 @@ export async function apply(ctx, config) {
370
376
  // A 304 also renews the cache freshness timestamp.
371
377
  catalogWrite = catalogWrite.then(async () => {
372
378
  if (catalogDisposed || controller.signal.aborted) return;
373
- await catalogStore.putRemote({ catalogUrl: config.catalogUrl, etag: fetched.notModified ? cached.etag : fetched.etag, connectors });
379
+ await catalogStore.putRemote({ catalogUrl: config.catalogUrl, etag: originFirst ? undefined : fetched.notModified ? cached.etag : fetched.etag, connectors });
374
380
  }).catch(() => {});
375
381
  await catalogWrite;
376
382
  }
@@ -3408,7 +3414,7 @@ export async function apply(ctx, config) {
3408
3414
  }
3409
3415
  try {
3410
3416
  clearTimeout(catalogTimer);
3411
- await updateRemoteCatalog();
3417
+ await updateRemoteCatalog(undefined, { preferOrigin: true });
3412
3418
  const visibleCount = listCatalog(state.merged, { publishedOnly: true }).length;
3413
3419
  return { ok: true, message: t(`市场已刷新,共 {count} 个连接器`, { count: visibleCount }) };
3414
3420
  } catch (error) {
@@ -0,0 +1,46 @@
1
+ /** Bundled host adapter. URL and credentials are environment-only, never argv/logs. */
2
+ import { EnvHttpProxyAgent, fetch } from 'undici';
3
+ import { LegacySseSession } from './legacy-sse.js';
4
+
5
+ const dispatcher = new EnvHttpProxyAgent();
6
+ let session;
7
+ let stopping = false;
8
+ function stop(failed = false) {
9
+ if (stopping) return;
10
+ stopping = true;
11
+ session?.close();
12
+ if (failed) process.stderr.write('Legacy SSE connection failed; no automatic retry. Check endpoint, credentials and network.\n');
13
+ void dispatcher.destroy().finally(() => process.exit(failed ? 1 : 0));
14
+ }
15
+ try {
16
+ const config = JSON.parse(process.env.DSH_LEGACY_SSE_CONFIG ?? '{}');
17
+ delete process.env.DSH_LEGACY_SSE_CONFIG;
18
+ session = new LegacySseSession(config.url, {
19
+ headers: config.headers,
20
+ fetchImpl: (url, options) => fetch(url, { ...options, dispatcher }),
21
+ onmessage: message => process.stdout.write(JSON.stringify(message) + '\n'),
22
+ onerror: () => stop(true),
23
+ });
24
+ } catch { stop(true); }
25
+
26
+ let buffer = '';
27
+ process.stdin.setEncoding('utf8');
28
+ process.stdin.on('data', chunk => {
29
+ buffer += chunk;
30
+ if (Buffer.byteLength(buffer) > 2 * 1024 * 1024) { stop(true); return; }
31
+ let end;
32
+ while ((end = buffer.indexOf('\n')) >= 0) {
33
+ const line = buffer.slice(0, end).trim();
34
+ buffer = buffer.slice(end + 1);
35
+ if (!line) continue;
36
+ try {
37
+ const message = JSON.parse(line);
38
+ if (message?.jsonrpc !== '2.0') throw new Error('Invalid JSON-RPC');
39
+ // Do not wait for a reply: server requests, notifications and cancellation must flow both ways.
40
+ void session.send(message).catch(() => stop(true));
41
+ } catch { stop(true); return; }
42
+ }
43
+ });
44
+ process.stdin.on('end', () => stop());
45
+ process.on('SIGTERM', () => stop());
46
+ process.on('SIGINT', () => stop());
@@ -0,0 +1,174 @@
1
+ /** Legacy MCP HTTP+SSE transport. No reconnection or JSON-RPC replay. */
2
+ const MAX_EVENT_BYTES = 2 * 1024 * 1024;
3
+
4
+ function httpError(status) {
5
+ const error = new Error(`Legacy SSE HTTP ${status}`);
6
+ error.status = status;
7
+ return error;
8
+ }
9
+
10
+ export class LegacySseSession {
11
+ constructor(url, { headers = {}, fetchImpl = fetch, timeoutMs = 15_000, onmessage = () => {}, onerror = () => {} } = {}) {
12
+ this.url = new URL(url);
13
+ if (!['http:', 'https:'].includes(this.url.protocol) || this.url.username || this.url.password) throw new Error('Invalid SSE URL');
14
+ this.headers = headers;
15
+ this.fetchImpl = fetchImpl;
16
+ this.timeoutMs = timeoutMs;
17
+ this.onmessage = onmessage;
18
+ this.onerror = onerror;
19
+ this.controller = new AbortController();
20
+ this.pending = new Map();
21
+ this.sendQueue = Promise.resolve();
22
+ }
23
+
24
+ start() {
25
+ if (this.closed) return Promise.reject(this.closed);
26
+ if (this.startPromise) return this.startPromise;
27
+ this.startPromise = new Promise((resolve, reject) => { this.ready = resolve; this.rejectReady = reject; });
28
+ this.startTimer = setTimeout(() => this.close(new Error('SSE endpoint timeout')), this.timeoutMs);
29
+ void this.consume().catch(error => this.close(error));
30
+ return this.startPromise;
31
+ }
32
+
33
+ async consume() {
34
+ const headers = new Headers(this.headers);
35
+ headers.set('Accept', 'text/event-stream');
36
+ const response = await this.fetchImpl(this.url.href, {
37
+ method: 'GET', headers,
38
+ signal: this.controller.signal, redirect: 'error',
39
+ });
40
+ if (!response.ok) { void response.body?.cancel().catch(() => {}); throw httpError(response.status); }
41
+ if (!(response.headers.get('content-type') ?? '').toLowerCase().includes('text/event-stream') || !response.body) {
42
+ void response.body?.cancel().catch(() => {});
43
+ throw new Error('Expected legacy SSE event stream');
44
+ }
45
+ const reader = response.body.getReader();
46
+ this.reader = reader;
47
+ const decoder = new TextDecoder();
48
+ let line = '', event = '', data = [], bytes = 0, skipLF = false;
49
+ try {
50
+ for (;;) {
51
+ const { done, value } = await reader.read();
52
+ if (done) throw new Error('Legacy SSE stream closed; requests were not retried');
53
+ const text = decoder.decode(value, { stream: true });
54
+ for (const char of text) {
55
+ if (skipLF) { skipLF = false; if (char === '\n') continue; }
56
+ bytes += Buffer.byteLength(char);
57
+ if (bytes > MAX_EVENT_BYTES) throw new Error('Legacy SSE event exceeds size limit');
58
+ if (char !== '\n' && char !== '\r') { line += char; continue; }
59
+ skipLF = char === '\r';
60
+ if (!line) {
61
+ if (data.length) this.dispatch(event, data.join('\n'));
62
+ event = ''; data = []; bytes = 0;
63
+ } else if (!line.startsWith(':')) {
64
+ const colon = line.indexOf(':');
65
+ const field = colon < 0 ? line : line.slice(0, colon);
66
+ const content = colon < 0 ? '' : line.slice(colon + 1).replace(/^ /, '');
67
+ if (field === 'event') event = content;
68
+ if (field === 'data') data.push(content);
69
+ }
70
+ line = '';
71
+ }
72
+ }
73
+ } finally {
74
+ void reader.cancel().catch(() => {});
75
+ reader.releaseLock();
76
+ }
77
+ }
78
+
79
+ dispatch(event, data) {
80
+ if (event === 'endpoint') {
81
+ if (this.endpoint) throw new Error('Repeated legacy SSE endpoint');
82
+ const endpoint = new URL(data, this.url);
83
+ // Credentials must never follow a provider-controlled redirect or origin change.
84
+ if (endpoint.origin !== this.url.origin || endpoint.username || endpoint.password || endpoint.hash) {
85
+ throw new Error('Legacy SSE endpoint origin mismatch');
86
+ }
87
+ this.endpoint = endpoint.href;
88
+ clearTimeout(this.startTimer);
89
+ this.ready();
90
+ return;
91
+ }
92
+ if (event && event !== 'message') return;
93
+ let message;
94
+ try { message = JSON.parse(data); } catch { throw new Error('Invalid legacy SSE JSON-RPC message'); }
95
+ if (!message || message.jsonrpc !== '2.0') throw new Error('Invalid legacy SSE JSON-RPC message');
96
+ if (!this.endpoint) throw new Error('Legacy SSE message received before endpoint');
97
+ const pending = this.pending.get(message.id);
98
+ if (pending && ('result' in message || 'error' in message)) {
99
+ this.pending.delete(message.id);
100
+ pending.resolve(message);
101
+ } else this.onmessage(message);
102
+ }
103
+
104
+ send(message) {
105
+ const sent = this.sendQueue.then(() => this.post(message));
106
+ // A failed send terminates this session: never replay queued business requests.
107
+ this.sendQueue = sent.catch(error => { this.close(error); });
108
+ return sent;
109
+ }
110
+
111
+ async post(message) {
112
+ await this.start();
113
+ if (this.closed) throw this.closed;
114
+ const response = await this.fetchImpl(this.endpoint, {
115
+ method: 'POST', headers: { ...this.headers, 'Content-Type': 'application/json' },
116
+ body: JSON.stringify(message), redirect: 'error',
117
+ signal: AbortSignal.any([this.controller.signal, AbortSignal.timeout(60_000)]),
118
+ });
119
+ // Legacy replies arrive on the GET stream; the POST body is an acknowledgement only.
120
+ void response.body?.cancel().catch(() => {});
121
+ if (!response.ok) throw httpError(response.status);
122
+ }
123
+
124
+ async request(message, signal) {
125
+ const abort = () => this.close(signal?.reason instanceof Error ? signal.reason : new Error('Legacy SSE request aborted'));
126
+ if (signal?.aborted) { abort(); throw this.closed; }
127
+ signal?.addEventListener('abort', abort, { once: true });
128
+ let timer;
129
+ try {
130
+ if (message.id === undefined) { await this.send(message); return undefined; }
131
+ if (this.pending.has(message.id)) throw new Error('Duplicate JSON-RPC request id');
132
+ const reply = new Promise((resolve, reject) => this.pending.set(message.id, { resolve, reject }));
133
+ // Attach rejection handling before waiting for the HTTP acknowledgement.
134
+ void reply.catch(() => {});
135
+ timer = setTimeout(() => this.close(new Error('Legacy SSE request timeout')), 60_000);
136
+ await this.send(message);
137
+ return await reply;
138
+ } finally {
139
+ clearTimeout(timer);
140
+ this.pending.delete(message.id);
141
+ signal?.removeEventListener('abort', abort);
142
+ }
143
+ }
144
+
145
+ close(error) {
146
+ if (this.closed) return;
147
+ this.closed = error ?? new Error('Legacy SSE session closed');
148
+ clearTimeout(this.startTimer);
149
+ this.controller.abort();
150
+ void this.reader?.cancel().catch(() => {});
151
+ this.rejectReady?.(this.closed);
152
+ for (const pending of this.pending.values()) pending.reject(this.closed);
153
+ this.pending.clear();
154
+ if (error) this.onerror(error);
155
+ }
156
+ }
157
+
158
+ /** Reuse the existing bounded initialize/tools-list checks for legacy sessions. */
159
+ export function legacySseFetch(url, fetchImpl) {
160
+ let session;
161
+ return {
162
+ async fetch(_url, options) {
163
+ session ??= new LegacySseSession(url, { headers: options.headers, fetchImpl });
164
+ try {
165
+ const reply = await session.request(JSON.parse(options.body), options.signal);
166
+ return reply === undefined ? new Response(null, { status: 202 }) : Response.json(reply);
167
+ } catch (error) {
168
+ if (error.status) return new Response(null, { status: error.status });
169
+ throw error;
170
+ }
171
+ },
172
+ close() { session?.close(); },
173
+ };
174
+ }
package/lib/mcp-http.js CHANGED
@@ -8,6 +8,7 @@
8
8
  import { MCP_PROTOCOL_VERSION } from './constants.js';
9
9
  import { authHeaders } from './mcp-provision.js';
10
10
  import { parseRetryAfter } from './discovery-policy.js';
11
+ import { legacySseFetch } from './legacy-sse.js';
11
12
  import { readSseResponse } from './mcp-sse.js';
12
13
  import { DEFAULT_LOCALE, createTranslator } from './i18n/index.js';
13
14
 
@@ -141,9 +142,11 @@ async function listMcpToolsOnce(record, {
141
142
  grants = new Map(),
142
143
  t = tZh,
143
144
  } = {}) {
144
- if (record.transport && record.transport !== 'streamable-http') {
145
+ if (record.transport && !['streamable-http', 'sse'].includes(record.transport)) {
145
146
  throw new McpHttpError(t('动态工具加载暂不支持 {transport} 传输', { transport: record.transport }), { kind: 'protocol' });
146
147
  }
148
+ const legacy = record.transport === 'sse' ? legacySseFetch(record.url, fetchImpl) : null;
149
+ if (legacy) fetchImpl = legacy.fetch;
147
150
  const controller = new AbortController();
148
151
  const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
149
152
  let sessionId = '';
@@ -220,6 +223,7 @@ async function listMcpToolsOnce(record, {
220
223
  throw failure;
221
224
  } finally {
222
225
  clearTimeout(timer);
226
+ legacy?.close();
223
227
  await closeSession(record, { grants, sessionId, protocolVersion, fetchImpl });
224
228
  }
225
229
  }
@@ -41,6 +41,18 @@ export function authHeaders(record, grants) {
41
41
 
42
42
  export function buildEntryConfig(record, grants, { failOnStartupError = false, startupRequestTimeoutMs } = {}) {
43
43
  record = effectiveLocalRecord(record);
44
+ if (record.transport === 'sse') {
45
+ // Keep the user record remote/SSE; adapt only the host entry, without runtime package installation.
46
+ return {
47
+ transport: 'stdio', serverName: record.serverName, command: process.execPath,
48
+ args: [fileURLToPath(new URL('./legacy-sse-bridge.js', import.meta.url))],
49
+ env: {
50
+ DSH_LEGACY_SSE_CONFIG: JSON.stringify({ url: record.url, headers: authHeaders(record, grants) }),
51
+ ...(isElectronRuntime() ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
52
+ },
53
+ cwd: process.cwd(), failOnStartupError,
54
+ };
55
+ }
44
56
  if (record.transport === 'stdio') {
45
57
  const env = { ...(record.env ?? {}) };
46
58
  if (record.auth?.mode === 'oauth' && record.oauthTokenEnv) {
@@ -6,6 +6,7 @@ import { MCP_PROTOCOL_VERSION } from './constants.js';
6
6
  import { DEFAULT_LOCALE, createTranslator } from './i18n/index.js';
7
7
  import { authHeaders } from './mcp-provision.js';
8
8
  import { parseRetryAfter } from './discovery-policy.js';
9
+ import { legacySseFetch } from './legacy-sse.js';
9
10
  import { readSseResponse } from './mcp-sse.js';
10
11
 
11
12
  /** 缺省译文:中文(既有调用点与测试无需改动)。 */
@@ -156,6 +157,8 @@ export async function validateConnectionRecord(record, {
156
157
  message: t('stdio 进程已交由 dsh-mcp-client 托管;工具可用性以 Host 注册结果为准'),
157
158
  };
158
159
  }
160
+ const legacy = record.transport === 'sse' ? legacySseFetch(record.url, fetchImpl) : null;
161
+ if (legacy) fetchImpl = legacy.fetch;
159
162
  const controller = new AbortController();
160
163
  const timer = setTimeout(() => controller.abort(new Error('timeout')), timeoutMs);
161
164
  try {
@@ -225,6 +228,7 @@ export async function validateConnectionRecord(record, {
225
228
  return failed(record, classified.kind, classified.message);
226
229
  } finally {
227
230
  clearTimeout(timer);
231
+ legacy?.close();
228
232
  }
229
233
  }
230
234
 
package/lib/probe.js CHANGED
@@ -6,6 +6,7 @@ import { auditDescriptor, auditRawDescriptor } from './catalog.js';
6
6
  import { normalizeConnectorDescriptor } from './schema.js';
7
7
  import { discoverProtectedResource, discoverServerMetadata } from './oauth.js';
8
8
  import { assertSafeUrl } from './util.js';
9
+ import { validateConnectionRecord } from './mcp-validation.js';
9
10
  import { MCP_PROTOCOL_VERSION } from './constants.js';
10
11
  import { DEFAULT_LOCALE, createTranslator } from './i18n/index.js';
11
12
 
@@ -103,27 +104,35 @@ async function probeServer(server, authMode, timeoutMs, { t = tZh } = {}) {
103
104
  tools: [],
104
105
  };
105
106
  try {
106
- const response = await fetchWithTimeout(server.url, {
107
- method: 'POST',
108
- headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
109
- body: JSON.stringify({
110
- jsonrpc: '2.0',
111
- id: 1,
112
- method: 'initialize',
113
- params: {
114
- protocolVersion: MCP_PROTOCOL_VERSION,
115
- capabilities: {},
116
- clientInfo: { name: 'dsh-mcp-connector-probe', version: '1.0' },
117
- },
118
- }),
119
- }, timeoutMs);
120
- result.httpStatus = response.status;
121
- result.reachable = response.status !== 404 && response.status < 500;
122
- const text = await response.text();
123
- const payload = parseMcpPayload(text, response.headers.get('content-type') ?? '');
124
- result.mcp = response.status === 401 || response.status === 403 || response.status === 405 || response.status === 406
125
- || payload?.jsonrpc === '2.0' || !!payload?.result?.protocolVersion || !!payload?.error;
126
- if (payload?.result?.tools) result.tools = payload.result.tools;
107
+ if (server.transport === 'sse') {
108
+ const checked = await validateConnectionRecord({ ...server, headers: {} }, { timeoutMs, t });
109
+ result.httpStatus = checked.httpStatus;
110
+ result.reachable = checked.ok || ['auth', 'rate-limit'].includes(checked.kind);
111
+ result.mcp = checked.ok || checked.kind === 'auth';
112
+ if (!result.mcp) { result.error = checked.message; result.errorKind = checked.kind; }
113
+ } else {
114
+ const response = await fetchWithTimeout(server.url, {
115
+ method: 'POST',
116
+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
117
+ body: JSON.stringify({
118
+ jsonrpc: '2.0',
119
+ id: 1,
120
+ method: 'initialize',
121
+ params: {
122
+ protocolVersion: MCP_PROTOCOL_VERSION,
123
+ capabilities: {},
124
+ clientInfo: { name: 'dsh-mcp-connector-probe', version: '1.0' },
125
+ },
126
+ }),
127
+ }, timeoutMs);
128
+ result.httpStatus = response.status;
129
+ result.reachable = response.status !== 404 && response.status < 500;
130
+ const text = await response.text();
131
+ const payload = parseMcpPayload(text, response.headers.get('content-type') ?? '');
132
+ result.mcp = response.status === 401 || response.status === 403 || response.status === 405 || response.status === 406
133
+ || payload?.jsonrpc === '2.0' || !!payload?.result?.protocolVersion || !!payload?.error;
134
+ if (payload?.result?.tools) result.tools = payload.result.tools;
135
+ }
127
136
  } catch (error) {
128
137
  const diagnostic = classifyProbeError(error);
129
138
  result.error = diagnostic.message;
package/lib/schema.js CHANGED
@@ -278,16 +278,16 @@ export function normalizeConnectorDescriptor(raw, { t = tZh } = {}) {
278
278
  const c = parsed.data;
279
279
  const servers = c.servers.map((s) => {
280
280
  const rawTransport = s.transport ?? 'streamable-http';
281
- const transport = rawTransport === 'sse' ? 'streamable-http' : rawTransport;
281
+ const transport = rawTransport;
282
282
  if (transport === 'stdio' && !s.command) {
283
283
  throw new Error(t('server "{serverKey}": transport=stdio 时 command 必填', { serverKey: s.serverKey }));
284
284
  }
285
- if (transport === 'streamable-http' && !s.url) {
285
+ if (transport !== 'stdio' && !s.url) {
286
286
  throw new Error(t('server "{serverKey}": transport=streamable-http 时 url 必填', { serverKey: s.serverKey }));
287
287
  }
288
288
  return {
289
289
  serverKey: s.serverKey,
290
- url: transport === 'streamable-http' ? s.url : undefined,
290
+ url: transport !== 'stdio' ? s.url : undefined,
291
291
  command: transport === 'stdio' ? s.command : undefined,
292
292
  args: transport === 'stdio' ? (s.args ?? []) : undefined,
293
293
  env: transport === 'stdio' ? (s.env ?? {}) : undefined,
@@ -300,7 +300,7 @@ export function normalizeConnectorDescriptor(raw, { t = tZh } = {}) {
300
300
  cwd: transport === 'stdio' ? (s.cwd ?? '') : undefined,
301
301
  serverName: s.serverName,
302
302
  transport,
303
- headers: transport === 'streamable-http' ? (s.headers ?? {}) : {},
303
+ headers: transport !== 'stdio' ? (s.headers ?? {}) : {},
304
304
  };
305
305
  });
306
306
  const authMode = c.auth?.mode ?? 'none';
@@ -374,14 +374,14 @@ export function normalizeConnectionRecord(raw, { t = tZh } = {}) {
374
374
  }
375
375
  const data = parsed.data;
376
376
  if (data.localOverrides) data.localOverrides = normalizeLocalOverrides(data, data.localOverrides);
377
- const transport = data.transport === 'sse' ? 'streamable-http' : data.transport;
377
+ const transport = data.transport;
378
378
  if (transport === 'stdio' && !data.command) {
379
379
  throw new Error(`invalid connection record: ${t('transport=stdio 时 command 必填')}`);
380
380
  }
381
- if (transport === 'streamable-http' && !data.url) {
381
+ if (transport !== 'stdio' && !data.url) {
382
382
  throw new Error(`invalid connection record: ${t('transport=streamable-http 时 url 必填')}`);
383
383
  }
384
- const parsedUrl = transport === 'streamable-http'
384
+ const parsedUrl = transport !== 'stdio'
385
385
  ? assertConnectionUrl(data.url, { allowInsecurePrivateNetwork: data.allowInsecurePrivateNetwork === true })
386
386
  : null;
387
387
  const allowInsecurePrivateNetwork = parsedUrl?.protocol === 'http:'
@@ -398,7 +398,7 @@ export function normalizeConnectionRecord(raw, { t = tZh } = {}) {
398
398
  env: transport === 'stdio' ? (data.env ?? {}) : undefined,
399
399
  oauthTokenEnv: transport === 'stdio' && data.auth?.mode === 'oauth' ? data.oauthTokenEnv : undefined,
400
400
  cwd: transport === 'stdio' ? (data.cwd ?? '') : undefined,
401
- headers: transport === 'streamable-http' ? (data.headers ?? {}) : {},
401
+ headers: transport !== 'stdio' ? (data.headers ?? {}) : {},
402
402
  auth: transport === 'stdio' && data.auth?.mode !== 'oauth' ? undefined : data.auth,
403
403
  };
404
404
  }
@@ -137,6 +137,7 @@ function shareDocument({ source, connection, catalogConnection, generatedAt = Da
137
137
  }
138
138
 
139
139
  function httpConnection({
140
+ transport = 'streamable-http',
140
141
  name,
141
142
  serverName,
142
143
  url,
@@ -148,7 +149,7 @@ function httpConnection({
148
149
  const connection = {
149
150
  name: safeName(name, serverName),
150
151
  serverName: slugServerName(serverName),
151
- transport: 'streamable-http',
152
+ transport,
152
153
  url: redactUrl ? REDACTED_VALUE : safePublicUrl(url),
153
154
  headers: {},
154
155
  authMode,
@@ -205,8 +206,8 @@ function resolvePublishedCatalogReference(connectorId, serverKey, { allowSingleS
205
206
  */
206
207
  function createShareableTemplateFromConnectionImpl(record, options = {}) {
207
208
  if (!plainObject(record)) fail('INVALID_CONNECTION', t("请明确选择一条连接"));
208
- if (record.transport !== 'streamable-http') {
209
- fail('UNSUPPORTED_TRANSPORT', t("只有已归一化的 Streamable HTTP 自定义连接可生成重填模板"));
209
+ if (!['streamable-http', 'sse'].includes(record.transport)) {
210
+ fail('UNSUPPORTED_TRANSPORT', t("只有 HTTP 或 SSE 自定义连接可生成重填模板"));
210
211
  }
211
212
  if (record.auth?.mode === 'oauth') {
212
213
  fail('CATALOG_REFERENCE_REQUIRED', t("OAuth 连接不导出本机状态;请选择对应的公开目录模板"));
@@ -222,6 +223,7 @@ function createShareableTemplateFromConnectionImpl(record, options = {}) {
222
223
  const portable = exportRedactedConnections([record], { exportedAt: options.generatedAt }).connections[0];
223
224
  if (!portable) fail('INVALID_CONNECTION', t("连接无法生成脱敏边界"));
224
225
  const connection = httpConnection({
226
+ transport: record.transport,
225
227
  // 显示名和 serverName 也可能嵌入客户/租户标识,自定义来源一律改为固定公开值。
226
228
  name: CUSTOM_CONNECTION_NAME,
227
229
  serverName: CUSTOM_SERVER_NAME,
@@ -299,7 +301,7 @@ function assertShareableConnectionTemplateImpl(input) {
299
301
  }
300
302
  for (const [index, connection] of document.connections.entries()) {
301
303
  assertOnlyKeys(connection, CONNECTION_KEYS, `$.connections[${index}]`);
302
- if (connection.transport !== 'streamable-http') fail('UNKNOWN_CLI_REFUSED', t("可导入分享模板不包含可执行 CLI"));
304
+ if (!['streamable-http', 'sse'].includes(connection.transport)) fail('UNKNOWN_CLI_REFUSED', t("可导入分享模板不包含可执行 CLI"));
303
305
  if (connection.url !== REDACTED_VALUE) {
304
306
  fail('UNREDACTED_VALUE', t("用户输入模板不得携带原始 URL;必须在目标本机重填"));
305
307
  }
package/lib/tools.js CHANGED
@@ -360,7 +360,7 @@ export function registerTools(ctx, api, { compact = false, t = createTranslator(
360
360
  type: 'boolean',
361
361
  description: t('仅用于用户自建连接:显式授权 RFC1918 IPv4 / RFC4193 IPv6 ULA 字面量使用明文 HTTP;公网 HTTP 与域名仍拒绝'),
362
362
  },
363
- transport: { type: 'string', enum: ['streamable-http', 'stdio', 'sse'], description: t('传输方式;sse 会兼容归一为 streamable-http') },
363
+ transport: { type: 'string', enum: ['streamable-http', 'stdio', 'sse'], description: t('传输方式;sse 保留旧版 HTTP + SSE 协议') },
364
364
  command: { type: 'string', description: t('transport=stdio 时的启动命令(如 npx、uvx)') },
365
365
  args: { type: 'array', items: { type: 'string' }, description: t('transport=stdio 时的参数列表') },
366
366
  envJson: { type: 'string', description: t('transport=stdio 时的环境变量 JSON;可能含凭据,仅保存在本机') },
@@ -161,7 +161,9 @@ export function createVersionStatusService({
161
161
  // npm is authoritative for an actionable update. A GitHub-only failure must not
162
162
  // turn into a five-minute retry loop against the unauthenticated GitHub API.
163
163
  const resultTtlMs = npmOk ? cacheTtlMs : failureTtlMs;
164
+ const previousOffer = cached?.updateAvailable ? cached.latestVersion : cached?.lastConfirmedUpdateVersion;
164
165
  const result = {
166
+ ...(!npmOk && previousOffer ? { lastConfirmedUpdateVersion: previousOffer } : {}),
165
167
  installedVersion,
166
168
  latestVersion: npmVersion ?? null,
167
169
  updateAvailable,