dsh-skill-pool 0.0.0-stage → 0.3.8

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/src/uploads.js ADDED
@@ -0,0 +1,222 @@
1
+ /**
2
+ * MCP imports: turn a `mcpServers` JSON payload into managed Loader rows.
3
+ *
4
+ * In v3 an import *is* pool membership: the route adds the entry to `state.mcp`
5
+ * and mounts the row in the same request, so there is no "resource library"
6
+ * step in between.
7
+ *
8
+ * Each server becomes one `rp-<serverName>` row of
9
+ * `@deepseek-ai/dsh-mcp-client`. The `rp-` prefix keeps these rows distinct
10
+ * from the ones `dsh-mcp-connector` manages (`mcp-<key>`), so the two plugins
11
+ * never fight over an entry id.
12
+ *
13
+ * Mounting can block for a long time when a server is unreachable, so the API
14
+ * never awaits it: `mountAsync` records progress in memory and the panel polls.
15
+ *
16
+ * @module dsh-skill-pool/uploads
17
+ */
18
+
19
+ /** Loader entry id prefix for servers imported here. */
20
+ export const MCP_ENTRY_PREFIX = 'rp'
21
+
22
+ /** Loader plugin that owns one MCP connection. */
23
+ export const MCP_CLIENT_PLUGIN = '@deepseek-ai/dsh-mcp-client'
24
+
25
+ /**
26
+ * Loader entry id of one managed server.
27
+ * @param {unknown} serverName - server name.
28
+ * @returns {string} entry id such as `rp-qcc`.
29
+ */
30
+ export function mcpEntryId(serverName) {
31
+ const name = slugify(serverName)
32
+ return name.length > 0 ? `${MCP_ENTRY_PREFIX}-${name}` : ''
33
+ }
34
+
35
+ /**
36
+ * Public tool-name prefix of one managed server (`mcp__<server>__`).
37
+ * @param {unknown} serverName - server name.
38
+ * @returns {string} prefix used to observe the server's registered tools.
39
+ */
40
+ export function serverToolPrefix(serverName) {
41
+ const name = slugify(serverName)
42
+ return name.length > 0 ? `mcp__${name}__` : ''
43
+ }
44
+
45
+ /**
46
+ * Normalize an arbitrary label into a kebab-case server name.
47
+ * @param {unknown} value - candidate label.
48
+ * @returns {string} kebab-case name, or ''.
49
+ */
50
+ export function slugify(value) {
51
+ if (typeof value !== 'string') return ''
52
+ return value
53
+ .trim()
54
+ .toLowerCase()
55
+ .replace(/[^a-z0-9]+/g, '-')
56
+ .replace(/^-+|-+$/g, '')
57
+ .slice(0, 64)
58
+ }
59
+
60
+ /**
61
+ * Normalize an import payload into `[serverName, definition]` pairs.
62
+ * Accepts `{ servers }`, `{ mcpServers }`, a bare `{ <name>: {...} }` map, or
63
+ * the same JSON as a string.
64
+ *
65
+ * @param {unknown} payload - request body or JSON text.
66
+ * @returns {Array<[string, object]>} entries.
67
+ */
68
+ export function normalizeMcpImport(payload) {
69
+ let source = payload
70
+ if (typeof source === 'string') {
71
+ try {
72
+ source = JSON.parse(source)
73
+ } catch {
74
+ throw new Error('JSON 解析失败')
75
+ }
76
+ }
77
+ if (source === null || typeof source !== 'object' || Array.isArray(source)) throw new Error('导入内容必须是一个对象')
78
+ const container = source.servers ?? source.mcpServers ?? source
79
+ if (container === null || typeof container !== 'object' || Array.isArray(container)) {
80
+ throw new Error('导入内容里没有 mcpServers 对象')
81
+ }
82
+ const entries = []
83
+ for (const [rawName, definition] of Object.entries(container)) {
84
+ const serverName = slugify(definition?.serverName ?? rawName)
85
+ if (serverName.length === 0) throw new Error(`服务器名 "${rawName}" 无效`)
86
+ entries.push([serverName, definition])
87
+ }
88
+ if (entries.length === 0) throw new Error('没有可导入的 MCP 服务器')
89
+ return entries
90
+ }
91
+
92
+ /**
93
+ * Build one mcp-client Loader config from an import definition.
94
+ * @param {string} serverName - stable server name (tool prefix `mcp__<serverName>__`).
95
+ * @param {object} definition - `{ url | command, ... }`.
96
+ * @returns {object} mcp-client config.
97
+ */
98
+ export function buildMcpConfig(serverName, definition) {
99
+ const source = definition !== null && typeof definition === 'object' ? definition : {}
100
+ if (typeof source.url === 'string' && source.url.trim().length > 0) {
101
+ let parsed
102
+ try {
103
+ parsed = new URL(source.url.trim())
104
+ } catch {
105
+ throw new Error(`MCP "${serverName}" 的 URL 无效`)
106
+ }
107
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
108
+ throw new Error(`MCP "${serverName}" 只支持 http/https URL`)
109
+ }
110
+ return {
111
+ transport: 'streamable-http',
112
+ serverName,
113
+ url: source.url.trim(),
114
+ ...(source.headers !== null && typeof source.headers === 'object' ? { headers: source.headers } : {}),
115
+ }
116
+ }
117
+ if (typeof source.command === 'string' && source.command.trim().length > 0) {
118
+ return {
119
+ transport: 'stdio',
120
+ serverName,
121
+ command: source.command.trim(),
122
+ args: Array.isArray(source.args) ? source.args.map((arg) => String(arg)) : [],
123
+ ...(source.env !== null && typeof source.env === 'object' ? { env: source.env } : {}),
124
+ ...(typeof source.cwd === 'string' && source.cwd.length > 0 ? { cwd: source.cwd } : {}),
125
+ }
126
+ }
127
+ throw new Error(`MCP "${serverName}" 需要 url(HTTP)或 command(stdio)`)
128
+ }
129
+
130
+ /**
131
+ * Create or update one managed mcp-client Loader row.
132
+ * @param {object} ctx - plugin context.
133
+ * @param {string} serverName - server name.
134
+ * @param {object} definition - import definition.
135
+ * @returns {Promise<{serverName: string, entryId: string, created: boolean}>} row outcome.
136
+ */
137
+ export async function upsertMcpServer(ctx, serverName, definition) {
138
+ const loader = ctx.get('loader')
139
+ if (loader === undefined || typeof loader.create !== 'function') {
140
+ throw new Error('当前部署没有 Loader,无法挂载 MCP 服务器')
141
+ }
142
+ const entryId = mcpEntryId(serverName)
143
+ if (entryId.length === 0) throw new Error('服务器名无效')
144
+ const config = buildMcpConfig(serverName, definition)
145
+ let existing
146
+ try {
147
+ existing = loader.resolve(entryId)
148
+ } catch {
149
+ existing = undefined
150
+ }
151
+ if (existing !== undefined) {
152
+ await loader.update(entryId, { config })
153
+ return { serverName, entryId, created: false }
154
+ }
155
+ await loader.create({ id: entryId, name: MCP_CLIENT_PLUGIN, config })
156
+ return { serverName, entryId, created: true }
157
+ }
158
+
159
+ /**
160
+ * Remove one managed mcp-client row. Rows owned by other plugins are refused.
161
+ * @param {object} ctx - plugin context.
162
+ * @param {string} serverName - server name.
163
+ * @returns {Promise<{serverName: string, removed: boolean}>} removal outcome.
164
+ */
165
+ export async function removeMcpServer(ctx, serverName) {
166
+ const loader = ctx.get('loader')
167
+ if (loader === undefined || typeof loader.remove !== 'function') {
168
+ throw new Error('当前部署没有 Loader,无法移除 MCP 服务器')
169
+ }
170
+ const name = slugify(serverName)
171
+ if (name.length === 0) throw new Error('服务器名无效')
172
+ const entryId = mcpEntryId(name)
173
+ try {
174
+ loader.resolve(entryId)
175
+ } catch {
176
+ throw new Error(`MCP 服务器 ${name} 不是由技能池导入的,无法在这里移除`)
177
+ }
178
+ loader.remove(entryId)
179
+ return { serverName: name, removed: true }
180
+ }
181
+
182
+ /**
183
+ * In-memory mount tracker.
184
+ *
185
+ * A mount can wait seconds to minutes on an unreachable server; the API returns
186
+ * right away and the panel polls this map, so the UI never freezes.
187
+ *
188
+ * @returns {{start: Function, status: Function, forget: Function}} tracker.
189
+ */
190
+ export function createMountTracker() {
191
+ /** @type {Map<string, {state: string, error?: string, startedAt: number}>} */
192
+ const mounts = new Map()
193
+ return {
194
+ /** Start one background mount. */
195
+ start(serverName, run) {
196
+ mounts.set(serverName, { state: 'mounting', startedAt: Date.now() })
197
+ void run()
198
+ .then(() => {
199
+ mounts.set(serverName, { state: 'ready', startedAt: mounts.get(serverName)?.startedAt ?? Date.now() })
200
+ })
201
+ .catch((error) => {
202
+ mounts.set(serverName, {
203
+ state: 'failed',
204
+ error: error instanceof Error ? error.message : String(error),
205
+ startedAt: mounts.get(serverName)?.startedAt ?? Date.now(),
206
+ })
207
+ })
208
+ },
209
+ /** Read the whole mount map. */
210
+ status() {
211
+ const out = {}
212
+ for (const [name, entry] of mounts) {
213
+ out[name] = { state: entry.state, ...(entry.error === undefined ? {} : { error: entry.error }) }
214
+ }
215
+ return out
216
+ },
217
+ /** Drop one record (after removal). */
218
+ forget(serverName) {
219
+ mounts.delete(serverName)
220
+ },
221
+ }
222
+ }