@momeidejiyi/dsh-general-mcp 0.1.5 → 0.1.6
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/lib/index.js +493 -184
- package/package.json +1 -1
- package/src/catalog.ts +2 -0
- package/src/client.ts +1 -1
- package/src/connect.ts +64 -0
- package/src/index.ts +296 -225
- package/src/sse.ts +210 -0
package/src/sse.ts
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Legacy MCP transport: HTTP+SSE (spec 2024-11-05).
|
|
3
|
+
*
|
|
4
|
+
* GET <url> opens an event stream; the server announces its message endpoint
|
|
5
|
+
* with an "endpoint" event; requests are POSTed there and replies arrive back
|
|
6
|
+
* on the stream. Spring AI's SSE starter and most pre-2025 servers speak this.
|
|
7
|
+
*/
|
|
8
|
+
export interface SseTool {
|
|
9
|
+
name: string
|
|
10
|
+
title?: string
|
|
11
|
+
description?: string
|
|
12
|
+
inputSchema?: Record<string, unknown>
|
|
13
|
+
outputSchema?: Record<string, unknown>
|
|
14
|
+
annotations?: Record<string, unknown>
|
|
15
|
+
_meta?: Record<string, unknown>
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface SseCallResult {
|
|
19
|
+
content?: unknown[]
|
|
20
|
+
structuredContent?: unknown
|
|
21
|
+
isError?: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface Pending {
|
|
25
|
+
resolve: (value: any) => void
|
|
26
|
+
reject: (error: Error) => void
|
|
27
|
+
timer: any
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export class SseClient {
|
|
31
|
+
private messageUrl: string | undefined
|
|
32
|
+
private pending = new Map<number, Pending>()
|
|
33
|
+
private nextId = 0
|
|
34
|
+
private controller = new AbortController()
|
|
35
|
+
private reader: ReadableStreamDefaultReader<Uint8Array> | undefined
|
|
36
|
+
private connected: Promise<void> | undefined
|
|
37
|
+
private closed = false
|
|
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 protocolVersion(): string | undefined {
|
|
46
|
+
return '2024-11-05'
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Open the stream and wait for the endpoint announcement. */
|
|
50
|
+
connect(): Promise<void> {
|
|
51
|
+
if (this.connected !== undefined) return this.connected
|
|
52
|
+
this.connected = (async () => {
|
|
53
|
+
const headers: Record<string, string> = { accept: 'text/event-stream', ...this.headers }
|
|
54
|
+
const response = await fetch(this.url, { headers, signal: this.controller.signal })
|
|
55
|
+
if (!response.ok) throw new Error('SSE connect failed: HTTP ' + response.status)
|
|
56
|
+
if (response.body === null) throw new Error('SSE connect returned no body')
|
|
57
|
+
this.reader = response.body.getReader()
|
|
58
|
+
const announced = new Promise<void>((resolve, reject) => {
|
|
59
|
+
const timer = setTimeout(() => reject(new Error('SSE endpoint event timed out')), this.timeoutMs)
|
|
60
|
+
this.endpointWaiter = { resolve, reject, timer }
|
|
61
|
+
})
|
|
62
|
+
void this.pump()
|
|
63
|
+
await announced
|
|
64
|
+
if (this.messageUrl === undefined) throw new Error('SSE server did not announce an endpoint')
|
|
65
|
+
})()
|
|
66
|
+
return this.connected
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
private endpointWaiter: Pending | undefined
|
|
70
|
+
|
|
71
|
+
private async pump(): Promise<void> {
|
|
72
|
+
const decoder = new TextDecoder()
|
|
73
|
+
let buffer = ''
|
|
74
|
+
try {
|
|
75
|
+
while (true) {
|
|
76
|
+
const chunk = await this.reader?.read()
|
|
77
|
+
if (chunk === undefined || chunk.done === true) break
|
|
78
|
+
buffer += decoder.decode(chunk.value, { stream: true })
|
|
79
|
+
let index = buffer.indexOf('\n\n')
|
|
80
|
+
while (index >= 0) {
|
|
81
|
+
this.handleEvent(buffer.slice(0, index))
|
|
82
|
+
buffer = buffer.slice(index + 2)
|
|
83
|
+
index = buffer.indexOf('\n\n')
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
} catch (error) {
|
|
87
|
+
if (this.closed !== true) this.failAll(new Error('SSE stream failed: ' + String((error as Error)?.message ?? error)))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
private handleEvent(raw: string): void {
|
|
92
|
+
let event = 'message'
|
|
93
|
+
const data: string[] = []
|
|
94
|
+
for (const line of raw.split(/\r?\n/)) {
|
|
95
|
+
if (line.startsWith('event:')) event = line.slice(6).trim()
|
|
96
|
+
else if (line.startsWith('data:')) data.push(line.slice(5).replace(/^ /, ''))
|
|
97
|
+
}
|
|
98
|
+
const payload = data.join('\n')
|
|
99
|
+
if (event === 'endpoint') {
|
|
100
|
+
try { this.messageUrl = new URL(payload, this.url).toString() } catch { this.messageUrl = payload }
|
|
101
|
+
const waiter = this.endpointWaiter
|
|
102
|
+
this.endpointWaiter = undefined
|
|
103
|
+
if (waiter !== undefined) { clearTimeout(waiter.timer); waiter.resolve(undefined) }
|
|
104
|
+
return
|
|
105
|
+
}
|
|
106
|
+
if (event === 'message' || event === '') {
|
|
107
|
+
let parsed: any
|
|
108
|
+
try { parsed = JSON.parse(payload) } catch { return }
|
|
109
|
+
const id = parsed?.id
|
|
110
|
+
if (typeof id === 'number') {
|
|
111
|
+
const waiter = this.pending.get(id)
|
|
112
|
+
if (waiter !== undefined) {
|
|
113
|
+
this.pending.delete(id)
|
|
114
|
+
clearTimeout(waiter.timer)
|
|
115
|
+
if (parsed.error !== undefined) waiter.reject(new Error('MCP error ' + parsed.error.code + ': ' + parsed.error.message))
|
|
116
|
+
else waiter.resolve(parsed.result)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
if (event === 'error') {
|
|
122
|
+
const waiter = this.endpointWaiter
|
|
123
|
+
this.endpointWaiter = undefined
|
|
124
|
+
if (waiter !== undefined) { clearTimeout(waiter.timer); waiter.reject(new Error('SSE error: ' + payload)) }
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
private failAll(error: Error): void {
|
|
129
|
+
for (const [id, waiter] of this.pending) {
|
|
130
|
+
clearTimeout(waiter.timer)
|
|
131
|
+
waiter.reject(error)
|
|
132
|
+
this.pending.delete(id)
|
|
133
|
+
}
|
|
134
|
+
const waiter = this.endpointWaiter
|
|
135
|
+
this.endpointWaiter = undefined
|
|
136
|
+
if (waiter !== undefined) { clearTimeout(waiter.timer); waiter.reject(error) }
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
private async request(method: string, params: Record<string, unknown>): Promise<any> {
|
|
140
|
+
await this.connect()
|
|
141
|
+
const id = (this.nextId += 1)
|
|
142
|
+
const body = JSON.stringify({ jsonrpc: '2.0', id, method, params })
|
|
143
|
+
const reply = new Promise<any>((resolve, reject) => {
|
|
144
|
+
const timer = setTimeout(() => {
|
|
145
|
+
this.pending.delete(id)
|
|
146
|
+
reject(new Error('MCP ' + method + ' timed out after ' + this.timeoutMs + 'ms'))
|
|
147
|
+
}, this.timeoutMs)
|
|
148
|
+
this.pending.set(id, { resolve, reject, timer })
|
|
149
|
+
})
|
|
150
|
+
const response = await fetch(this.messageUrl as string, {
|
|
151
|
+
method: 'POST',
|
|
152
|
+
headers: { 'content-type': 'application/json', ...this.headers },
|
|
153
|
+
body,
|
|
154
|
+
signal: this.controller.signal,
|
|
155
|
+
})
|
|
156
|
+
if (!response.ok) {
|
|
157
|
+
const pending = this.pending.get(id)
|
|
158
|
+
if (pending !== undefined) { clearTimeout(pending.timer); this.pending.delete(id) }
|
|
159
|
+
throw new Error('MCP ' + method + ' POST failed: HTTP ' + response.status)
|
|
160
|
+
}
|
|
161
|
+
return reply
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async initialize(): Promise<{ protocolVersion?: string; serverInfo?: unknown; capabilities?: unknown }> {
|
|
165
|
+
const result = await this.request('initialize', {
|
|
166
|
+
protocolVersion: '2024-11-05',
|
|
167
|
+
capabilities: {},
|
|
168
|
+
clientInfo: { name: 'dsh-general-mcp', version: '0.1.6' },
|
|
169
|
+
})
|
|
170
|
+
await this.notify('notifications/initialized', {})
|
|
171
|
+
return { ...(result ?? {}), protocolVersion: (result as any)?.protocolVersion ?? '2024-11-05' }
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
private async notify(method: string, params: Record<string, unknown>): Promise<void> {
|
|
175
|
+
await this.connect()
|
|
176
|
+
const response = await fetch(this.messageUrl as string, {
|
|
177
|
+
method: 'POST',
|
|
178
|
+
headers: { 'content-type': 'application/json', ...this.headers },
|
|
179
|
+
body: JSON.stringify({ jsonrpc: '2.0', method, params }),
|
|
180
|
+
signal: this.controller.signal,
|
|
181
|
+
})
|
|
182
|
+
if (!response.ok) throw new Error('notify ' + method + ' failed: HTTP ' + response.status)
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
async listTools(): Promise<SseTool[]> {
|
|
186
|
+
const tools: SseTool[] = []
|
|
187
|
+
let cursor: string | undefined
|
|
188
|
+
for (let page = 0; page < 100; page += 1) {
|
|
189
|
+
const result: any = await this.request('tools/list', cursor === undefined ? {} : { cursor })
|
|
190
|
+
if (!Array.isArray(result?.tools)) throw new Error('tools/list returned no tools array')
|
|
191
|
+
tools.push(...result.tools)
|
|
192
|
+
const next = typeof result.nextCursor === 'string' && result.nextCursor !== '' ? result.nextCursor : undefined
|
|
193
|
+
if (next === undefined || tools.some(tool => tool.name === '')) break
|
|
194
|
+
cursor = next
|
|
195
|
+
}
|
|
196
|
+
return tools
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async callTool(name: string, args: Record<string, unknown>): Promise<SseCallResult> {
|
|
200
|
+
const result: any = await this.request('tools/call', { name, arguments: args })
|
|
201
|
+
return (result ?? {}) as SseCallResult
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async close(): Promise<void> {
|
|
205
|
+
this.closed = true
|
|
206
|
+
this.failAll(new Error('SSE client closed'))
|
|
207
|
+
this.controller.abort()
|
|
208
|
+
try { await this.reader?.cancel() } catch {}
|
|
209
|
+
}
|
|
210
|
+
}
|