@momeidejiyi/dsh-general-mcp 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,26 @@
1
1
  {
2
2
  "name": "@momeidejiyi/dsh-general-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.2",
4
+ "description": "Single-endpoint MCP bridge for DSH: connects one gateway and registers its tools.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "lib/index.js",
13
+ "src"
14
+ ],
15
+ "license": "MIT",
16
+ "engines": {
17
+ "node": ">=20",
18
+ "dsh": ">=0.1.7-0 <0.3.0"
19
+ },
20
+ "peerDependencies": {
21
+ "@deepseek-ai/cordis": ">=4.0.0 <5"
22
+ },
23
+ "scripts": {
24
+ "build": "node ../../build/build-host.mjs"
25
+ }
6
26
  }
package/src/catalog.ts ADDED
@@ -0,0 +1,162 @@
1
+ /** Catalog entries plus strict validation of the server contract. */
2
+ import type { McpTool } from './client.ts'
3
+
4
+ export interface ToolOverride {
5
+ title?: string
6
+ folder?: string[]
7
+ }
8
+
9
+ export interface ToolSettings {
10
+ disabled?: string[]
11
+ hidden?: string[]
12
+ overrides?: Record<string, ToolOverride>
13
+ }
14
+
15
+ export interface ToolDiagnostic {
16
+ code: 'name' | 'description' | 'input-schema' | 'folder' | 'title' | 'alias'
17
+ message: string
18
+ }
19
+
20
+ export interface CatalogEntry {
21
+ toolName: string
22
+ rawName: string
23
+ path: string
24
+ virtualPath: string
25
+ folder: string[]
26
+ title?: string
27
+ description: string
28
+ inputSchema: Record<string, unknown>
29
+ outputSchema?: Record<string, unknown>
30
+ hash: string
31
+ disabled: boolean
32
+ hidden: boolean
33
+ invalid?: ToolDiagnostic
34
+ warning?: ToolDiagnostic
35
+ }
36
+
37
+ const NAME_PATTERN = /^[A-Za-z0-9_.-]{1,128}$/
38
+ const SEGMENT_PATTERN = /^[^/.]{1,64}$/
39
+ const MAX_TITLE = 80
40
+ const MAX_FOLDER_DEPTH = 8
41
+ /** Keys a server may use; only the canonical pair drives display. */
42
+ const CANONICAL_FOLDER = 'dsh/folder'
43
+ const CANONICAL_TITLE = 'dsh/title'
44
+ const ALIAS_NAMESPACES = ['dev.dsh/tool', 'io.deepseek/tool', 'dsh/tool']
45
+
46
+ function slug(value: string): string {
47
+ return value
48
+ .trim()
49
+ .toLowerCase()
50
+ .replace(/[^a-z0-9\u4e00-\u9fa5._-]+/g, '-')
51
+ .replace(/^-+|-+$/g, '')
52
+ }
53
+
54
+ function isStringArray(value: unknown): value is string[] {
55
+ return Array.isArray(value) && value.every(item => typeof item === 'string')
56
+ }
57
+
58
+ /** Validate the parts of a tool the client interprets; anything else is ignored. */
59
+ export function validateTool(tool: McpTool): ToolDiagnostic | undefined {
60
+ if (typeof tool.name !== 'string' || !NAME_PATTERN.test(tool.name)) {
61
+ return { code: 'name', message: 'name 必须匹配 ' + NAME_PATTERN.source }
62
+ }
63
+ if (typeof tool.description !== 'string' || tool.description.trim() === '') {
64
+ return { code: 'description', message: 'description 不能为空' }
65
+ }
66
+ const schema = tool.inputSchema
67
+ if (schema === null || typeof schema !== 'object' || Array.isArray(schema) || (schema as any).type !== 'object') {
68
+ return { code: 'input-schema', message: 'inputSchema 必须是 type:"object" 的 JSON Schema' }
69
+ }
70
+ const meta = (tool._meta ?? {}) as Record<string, unknown>
71
+ const folder = meta[CANONICAL_FOLDER]
72
+ if (folder !== undefined) {
73
+ if (!isStringArray(folder) || folder.length === 0 || folder.length > MAX_FOLDER_DEPTH) {
74
+ return { code: 'folder', message: '_meta["dsh/folder"] 必须是 1..8 个字符串的数组' }
75
+ }
76
+ const bad = folder.find(segment => !SEGMENT_PATTERN.test(segment))
77
+ if (bad !== undefined) {
78
+ return { code: 'folder', message: '_meta["dsh/folder"] 段 "' + bad + '" 非法(不能含 / 或 .,长度 1..64)' }
79
+ }
80
+ }
81
+ const title = meta[CANONICAL_TITLE]
82
+ if (title !== undefined && (typeof title !== 'string' || title.length > MAX_TITLE)) {
83
+ return { code: 'title', message: '_meta["dsh/title"] 必须是不超过 ' + MAX_TITLE + ' 字的字符串' }
84
+ }
85
+ return undefined
86
+ }
87
+
88
+ /** Non-fatal: the tool uses a legacy alias instead of the canonical keys. */
89
+ export function aliasWarning(tool: McpTool): ToolDiagnostic | undefined {
90
+ const meta = (tool._meta ?? {}) as Record<string, unknown>
91
+ if (meta[CANONICAL_FOLDER] !== undefined || meta[CANONICAL_TITLE] !== undefined) return undefined
92
+ const used = ALIAS_NAMESPACES.filter(key => meta[key] !== undefined || (key === 'dsh/tool' && meta[key] !== undefined))
93
+ if (used.length === 0) return undefined
94
+ return { code: 'alias', message: '使用了非规范字段 ' + used.join(', ') + ',请改用 _meta["dsh/folder"] / _meta["dsh/title"]' }
95
+ }
96
+
97
+ function folderFromMeta(tool: McpTool): string[] | undefined {
98
+ const meta = (tool._meta ?? {}) as Record<string, unknown>
99
+ const canonical = meta[CANONICAL_FOLDER]
100
+ if (isStringArray(canonical) && canonical.length > 0) return canonical
101
+ for (const key of ALIAS_NAMESPACES) {
102
+ const nested = meta[key]
103
+ if (nested === null || typeof nested !== 'object') continue
104
+ const inner = (nested as any).folder
105
+ if (isStringArray(inner) && inner.length > 0) return inner
106
+ }
107
+ return undefined
108
+ }
109
+
110
+ function folderFromName(rawName: string): string[] {
111
+ const parts = rawName.split(/[./]/).filter(Boolean)
112
+ return parts.length > 1 ? parts.slice(0, -1) : ['uncategorized']
113
+ }
114
+
115
+ function shortHash(value: string): string {
116
+ let hash = 0x811c9dc5
117
+ for (let index = 0; index < value.length; index += 1) {
118
+ hash ^= value.charCodeAt(index)
119
+ hash = Math.imul(hash, 0x01000193) >>> 0
120
+ }
121
+ return hash.toString(16).padStart(8, '0')
122
+ }
123
+
124
+ export function buildCatalog(
125
+ serverName: string,
126
+ tools: McpTool[],
127
+ publicName: (raw: string) => string,
128
+ settings: ToolSettings = {},
129
+ ): CatalogEntry[] {
130
+ const disabled = new Set(settings.disabled ?? [])
131
+ const hidden = new Set(settings.hidden ?? [])
132
+ return tools.map(tool => {
133
+ const override = settings.overrides?.[tool.name]
134
+ const invalid = validateTool(tool)
135
+ const alias = aliasWarning(tool)
136
+ const folder = (override?.folder ?? folderFromMeta(tool) ?? folderFromName(tool.name))
137
+ .map(slug)
138
+ .filter(Boolean)
139
+ const leaf = slug(tool.name.split(/[./]/).pop() ?? tool.name) || 'tool'
140
+ const path = [...folder, leaf].join('/')
141
+ const metaTitle = typeof tool._meta?.[CANONICAL_TITLE] === 'string' ? String(tool._meta[CANONICAL_TITLE]) : undefined
142
+ const annotationTitle = typeof tool.annotations?.title === 'string' ? tool.annotations.title : undefined
143
+ const title = override?.title ?? tool.title ?? annotationTitle ?? metaTitle
144
+ const description = tool.description ?? tool.name
145
+ return {
146
+ toolName: publicName(tool.name),
147
+ rawName: tool.name,
148
+ path,
149
+ virtualPath: 'dsh-mcp://' + serverName + '/' + path,
150
+ folder,
151
+ ...(title === undefined ? {} : { title }),
152
+ description,
153
+ inputSchema: (tool.inputSchema ?? { type: 'object', properties: {} }) as Record<string, unknown>,
154
+ ...(tool.outputSchema === undefined ? {} : { outputSchema: tool.outputSchema }),
155
+ hash: shortHash(description + JSON.stringify(tool.inputSchema ?? null) + JSON.stringify(folder)),
156
+ disabled: disabled.has(tool.name),
157
+ hidden: hidden.has(tool.name),
158
+ ...(invalid !== undefined ? { invalid } : {}),
159
+ ...(invalid === undefined && alias !== undefined ? { warning: alias } : {}),
160
+ }
161
+ })
162
+ }
package/src/client.ts ADDED
@@ -0,0 +1,254 @@
1
+ /**
2
+ * MCP client over Streamable HTTP (JSON-RPC 2.0), dual-era.
3
+ *
4
+ * The 2026-07-28 revision replaced the "initialize" handshake with
5
+ * "server/discover" and added Mcp-Method / MCP-Protocol-Version headers, while
6
+ * 2025-06-18 and older still use initialize. A backend may implement either, so
7
+ * we probe the modern shape first and fall back to the legacy handshake.
8
+ */
9
+ export interface McpTool {
10
+ name: string
11
+ title?: string
12
+ annotations?: Record<string, unknown>
13
+ description?: string
14
+ inputSchema?: Record<string, unknown>
15
+ outputSchema?: Record<string, unknown>
16
+ _meta?: Record<string, unknown>
17
+ }
18
+
19
+ export interface McpCallResult {
20
+ content?: unknown[]
21
+ structuredContent?: unknown
22
+ isError?: boolean
23
+ }
24
+
25
+ const MODERN = '2026-07-28'
26
+ const LEGACY = '2025-06-18'
27
+ const META_VERSION = 'io.modelcontextprotocol/protocolVersion'
28
+ const META_CLIENT = 'io.modelcontextprotocol/clientInfo'
29
+ const META_CAPS = 'io.modelcontextprotocol/clientCapabilities'
30
+
31
+ type Era = 'modern' | 'legacy'
32
+
33
+ export class McpClient {
34
+ private nextId = 0
35
+ private sessionId: string | undefined
36
+ private protocolVersion: string | undefined
37
+ private era: Era | undefined
38
+
39
+ constructor(
40
+ private readonly url: string,
41
+ private readonly headers: Record<string, string> = {},
42
+ private readonly timeoutMs = 60_000,
43
+ ) {}
44
+
45
+ get protocol(): { era: Era | undefined; version: string | undefined } {
46
+ return { era: this.era, version: this.protocolVersion }
47
+ }
48
+
49
+ async initialize(): Promise<{ protocolVersion?: string; serverInfo?: unknown; capabilities?: unknown; era?: Era }> {
50
+ const modern = await this.tryModern()
51
+ if (modern !== undefined) {
52
+ this.era = 'modern'
53
+ this.protocolVersion = MODERN
54
+ return { ...modern, era: 'modern' }
55
+ }
56
+
57
+ this.era = 'legacy'
58
+ const result = await this.request('initialize', {
59
+ protocolVersion: LEGACY,
60
+ capabilities: {},
61
+ clientInfo: { name: 'dsh-general-mcp', version: '0.1.1' },
62
+ })
63
+ if (typeof (result as any)?.protocolVersion === 'string') this.protocolVersion = (result as any).protocolVersion
64
+ await this.notify('notifications/initialized', {})
65
+ return { ...(result ?? {}), era: 'legacy' }
66
+ }
67
+
68
+ /** The modern revision has no initialize: server/discover is the handshake. */
69
+ private async tryModern(): Promise<Record<string, unknown> | undefined> {
70
+ try {
71
+ const result = await this.request('server/discover', {}, undefined, MODERN)
72
+ if (result === undefined || result === null) return undefined
73
+ return result as Record<string, unknown>
74
+ } catch {
75
+ return undefined
76
+ }
77
+ }
78
+
79
+ async listTools(): Promise<McpTool[]> {
80
+ const tools: McpTool[] = []
81
+ const seenCursors = new Set<string>()
82
+ let cursor: string | undefined
83
+ let pages = 0
84
+ while (pages < 100) {
85
+ pages += 1
86
+ const result: any = await this.request('tools/list', cursor === undefined ? {} : { cursor })
87
+ if (!Array.isArray(result?.tools)) throw new Error('tools/list returned no tools array')
88
+ tools.push(...result.tools)
89
+ const next = typeof result.nextCursor === 'string' && result.nextCursor !== '' ? result.nextCursor : undefined
90
+ if (next === undefined) { cursor = undefined; break }
91
+ if (seenCursors.has(next)) throw new Error('tools/list repeated cursor ' + next)
92
+ seenCursors.add(next)
93
+ cursor = next
94
+ }
95
+ if (cursor !== undefined) throw new Error('tools/list did not terminate within 100 pages')
96
+ const seen = new Set<string>()
97
+ for (const tool of tools) {
98
+ if (typeof tool.name !== 'string' || tool.name === '') throw new Error('tool without a name')
99
+ if (seen.has(tool.name)) throw new Error('duplicate tool: ' + tool.name)
100
+ seen.add(tool.name)
101
+ }
102
+ return tools
103
+ }
104
+
105
+ async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<McpCallResult> {
106
+ const result: any = await this.request('tools/call', { name, arguments: args }, signal, undefined, name)
107
+ return (result ?? {}) as McpCallResult
108
+ }
109
+
110
+ async notify(method: string, params: Record<string, unknown>): Promise<void> {
111
+ const response = await this.send({ jsonrpc: '2.0', method, params }, undefined, method)
112
+ if (response.status !== 202 && response.status !== 200 && response.status !== 204) {
113
+ throw new Error('notify ' + method + ' failed: HTTP ' + response.status)
114
+ }
115
+ }
116
+
117
+ /** Terminate the session so a reconnect starts clean. */
118
+ async close(): Promise<void> {
119
+ if (this.sessionId === undefined) return
120
+ const sessionId = this.sessionId
121
+ this.sessionId = undefined
122
+ try {
123
+ await fetch(this.url, { method: 'DELETE', headers: { 'mcp-session-id': sessionId } })
124
+ } catch {}
125
+ }
126
+
127
+ private async request(
128
+ method: string,
129
+ params: Record<string, unknown>,
130
+ signal?: AbortSignal,
131
+ eraOverride?: Era,
132
+ toolName?: string,
133
+ ): Promise<any> {
134
+ if (signal?.aborted === true) throw signal.reason ?? new Error('aborted')
135
+ const era = eraOverride ?? this.era
136
+ const id = (this.nextId += 1)
137
+ const body = {
138
+ jsonrpc: '2.0',
139
+ id,
140
+ method,
141
+ params: era === 'modern'
142
+ ? { ...params, _meta: { ...(params as any)?._meta, [META_VERSION]: MODERN, [META_CLIENT]: { name: 'dsh-general-mcp', version: '0.1.1' }, [META_CAPS]: {} } }
143
+ : params,
144
+ }
145
+ let response = await this.send(body, signal, method, era, toolName)
146
+ if (response.status === 404 && this.sessionId !== undefined && method !== 'initialize') {
147
+ this.sessionId = undefined
148
+ await this.initialize()
149
+ response = await this.send(body, signal, method, this.era, toolName)
150
+ }
151
+ if (response.status === 401 || response.status === 403) {
152
+ throw new Error(method + ' failed: HTTP ' + response.status + ' (authentication rejected)')
153
+ }
154
+ const payload = response.payload
155
+ if (payload?.error) {
156
+ throw new Error('MCP ' + method + ' error ' + payload.error.code + ': ' + payload.error.message)
157
+ }
158
+ if (payload === undefined) {
159
+ throw new Error(method + ' returned no JSON-RPC payload (HTTP ' + response.status + ')')
160
+ }
161
+ return payload.result
162
+ }
163
+
164
+ private async send(
165
+ body: any,
166
+ signal: AbortSignal | undefined,
167
+ method?: string,
168
+ eraOverride?: Era,
169
+ toolName?: string,
170
+ ): Promise<{ status: number; payload?: any; headers: Headers }> {
171
+ const era = eraOverride ?? this.era
172
+ const controller = new AbortController()
173
+ const timer = setTimeout(() => {
174
+ controller.abort(new Error('MCP request timed out after ' + this.timeoutMs + 'ms'))
175
+ }, this.timeoutMs)
176
+ const forward = () => controller.abort(signal?.reason)
177
+ signal?.addEventListener('abort', forward, { once: true })
178
+ try {
179
+ const headers: Record<string, string> = {
180
+ 'content-type': 'application/json',
181
+ accept: 'application/json, text/event-stream',
182
+ ...this.headers,
183
+ }
184
+ if (this.sessionId !== undefined) headers['mcp-session-id'] = this.sessionId
185
+ if (era === 'modern') {
186
+ headers['mcp-protocol-version'] = this.protocolVersion ?? MODERN
187
+ if (method !== undefined) headers['mcp-method'] = method
188
+ if (toolName !== undefined) headers['mcp-name'] = toolName
189
+ } else if (this.protocolVersion !== undefined) {
190
+ headers['mcp-protocol-version'] = this.protocolVersion
191
+ }
192
+
193
+ const response = await fetch(this.url, { method: 'POST', headers, body: JSON.stringify(body), signal: controller.signal })
194
+ const sessionId = response.headers.get('mcp-session-id')
195
+ if (sessionId !== null && sessionId !== '') this.sessionId = sessionId
196
+
197
+ // The deadline covers the body read too: a stalled stream must not hang apply().
198
+ const contentType = response.headers.get('content-type') ?? ''
199
+ let payload: any
200
+ if (response.status === 202 || response.status === 204) {
201
+ payload = undefined
202
+ } else if (contentType.includes('text/event-stream')) {
203
+ payload = await readSseResult(response, body?.id)
204
+ } else if (response.ok) {
205
+ payload = await response.json()
206
+ } else {
207
+ const detail = await response.text().catch(() => '')
208
+ if (detail !== '') throw new Error('HTTP ' + response.status + ': ' + detail.slice(0, 300))
209
+ payload = undefined
210
+ }
211
+ return { status: response.status, payload, headers: response.headers }
212
+ } catch (error) {
213
+ const cause = (error as any)?.cause
214
+ if (controller.signal.aborted) {
215
+ const reason = controller.signal.reason
216
+ throw new Error(String((reason as Error)?.message ?? reason ?? 'MCP request aborted'))
217
+ }
218
+ if (cause !== undefined && typeof cause?.code === 'string') {
219
+ throw new Error('MCP transport failed: ' + cause.code + (cause.message ? ' - ' + cause.message : ''))
220
+ }
221
+ throw error
222
+ } finally {
223
+ clearTimeout(timer)
224
+ signal?.removeEventListener('abort', forward)
225
+ }
226
+ }
227
+ }
228
+
229
+ /** Collect one JSON-RPC reply from an SSE stream, ignoring notifications. */
230
+ async function readSseResult(response: Response, id: unknown): Promise<any> {
231
+ const text = await response.text()
232
+ const events: string[] = []
233
+ let data: string[] = []
234
+ const flush = () => {
235
+ if (data.length > 0) events.push(data.join('\n'))
236
+ data = []
237
+ }
238
+ for (const line of text.split(/\r?\n/)) {
239
+ if (line === '') { flush(); continue }
240
+ if (line.startsWith('data:')) data.push(line.slice(5).trimStart())
241
+ }
242
+ flush()
243
+
244
+ for (const event of events) {
245
+ if (event === '' || event === '[DONE]') continue
246
+ let parsed: any
247
+ try { parsed = JSON.parse(event) } catch { continue }
248
+ const candidates = Array.isArray(parsed) ? parsed : [parsed]
249
+ for (const candidate of candidates) {
250
+ if (candidate?.id === id) return candidate
251
+ }
252
+ }
253
+ throw new Error('no JSON-RPC response with the request id in the SSE stream')
254
+ }