返回 AiToEarn
mcp.js
1 // Minimal MCP Streamable HTTP client used by the plugin.
2 //
3 // The DSH MCP client bridge only supports static headers, so OAuth tokens
4 // (which expire and refresh) cannot be injected through cordis config. This
5 // client owns the Authorization header per request and retries once after a
6 // refresh when the server answers 401/403.
7 import { dirname, join } from 'node:path'
8 import { fileURLToPath } from 'node:url'
9 import { getAccessToken } from './oauth.js'
10
11 const LOGIN_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), '..', 'scripts', 'aitoearn.mjs')
12
13 export const MCP_PROTOCOL_VERSION = '2025-06-18'
14 const DEFAULT_TIMEOUT_MS = 60_000
15
16 export class McpAuthError extends Error {
17 constructor(message, { cause } = {}) {
18 super(message, cause === undefined ? undefined : { cause })
19 this.name = 'McpAuthError'
20 this.code = 'mcp_auth_required'
21 }
22 }
23
24 export class McpRequestError extends Error {
25 constructor(message, { code = 'mcp_request_failed', cause } = {}) {
26 super(message, cause === undefined ? undefined : { cause })
27 this.name = 'McpRequestError'
28 this.code = code
29 }
30 }
31
32 /** OAuth token provider. */
33 export function createTokenProvider(url) {
34 return {
35 async get(forceRefresh = false) {
36 const oauthToken = await getAccessToken(url, { forceRefresh }).catch(() => null)
37 if (oauthToken) return { token: oauthToken, source: 'oauth' }
38 return { token: null, source: 'none' }
39 },
40 }
41 }
42
43 function safeJson(text) {
44 try { return JSON.parse(text) } catch { return null }
45 }
46
47 function parseSse(body) {
48 const events = []
49 for (const block of body.split(/\r?\n\r?\n/)) {
50 for (const line of block.split(/\r?\n/)) {
51 if (!line.startsWith('data:')) continue
52 const data = line.slice(5).trim()
53 if (!data || data === '[DONE]') continue
54 const parsed = safeJson(data)
55 if (parsed && typeof parsed === 'object') events.push(parsed)
56 }
57 }
58 return events
59 }
60
61 export class McpHttpClient {
62 constructor({ url, serverName = 'aitoearn', tokenProvider = createTokenProvider(url), timeoutMs = DEFAULT_TIMEOUT_MS }) {
63 this.url = url
64 this.serverName = serverName
65 this.tokenProvider = tokenProvider
66 this.timeoutMs = timeoutMs
67 this.sessionId = ''
68 this.protocolVersion = MCP_PROTOCOL_VERSION
69 this.nextId = 1
70 this.initialized = false
71 }
72
73 async #headers(extra = {}) {
74 const { token } = await this.tokenProvider.get(false)
75 const headers = {
76 'Content-Type': 'application/json',
77 Accept: 'application/json, text/event-stream',
78 ...extra,
79 }
80 if (token) headers.Authorization = `Bearer ${token}`
81 if (this.sessionId) headers['mcp-session-id'] = this.sessionId
82 if (this.initialized) headers['mcp-protocol-version'] = this.protocolVersion
83 return headers
84 }
85
86 async #post(payload, { signal } = {}) {
87 const controller = new AbortController()
88 const timeout = setTimeout(() => controller.abort(), this.timeoutMs)
89 const onAbort = () => controller.abort()
90 if (signal) {
91 if (signal.aborted) controller.abort()
92 else signal.addEventListener('abort', onAbort, { once: true })
93 }
94 try {
95 const res = await fetch(this.url, {
96 method: 'POST',
97 headers: await this.#headers(),
98 body: JSON.stringify(payload),
99 signal: controller.signal,
100 })
101 const session = res.headers.get('mcp-session-id')
102 if (session) this.sessionId = session
103 const text = await res.text()
104 return { res, text }
105 } finally {
106 clearTimeout(timeout)
107 if (signal) signal.removeEventListener('abort', onAbort)
108 }
109 }
110
111 /** Send one JSON-RPC message and return its response (or null for 202/204). */
112 async request(method, params, { signal, id = this.nextId++ } = {}) {
113 const payload = { jsonrpc: '2.0', id, method, ...(params === undefined ? {} : { params }) }
114 let { res, text } = await this.#post(payload, { signal })
115
116 if (res.status === 401 || res.status === 403) {
117 const refreshed = await this.tokenProvider.get(true)
118 if (refreshed.token) {
119 ;({ res, text } = await this.#post(payload, { signal }))
120 }
121 if (res.status === 401 || res.status === 403) {
122 throw new McpAuthError(
123 'AiToEarn 拒绝了鉴权(HTTP ' + res.status + ')。请完成 OAuth 授权:' +
124 `node "${LOGIN_SCRIPT}" login`,
125 { cause: new Error(text.slice(0, 300)) },
126 )
127 }
128 }
129
130 if (res.status === 202 || res.status === 204) return null
131 if (!res.ok) {
132 throw new McpRequestError(`AiToEarn MCP 请求失败(HTTP ${res.status}):${text.slice(0, 300)}`)
133 }
134
135 const contentType = (res.headers.get('content-type') || '').toLowerCase()
136 const messages = contentType.includes('text/event-stream') ? parseSse(text) : [safeJson(text)]
137 const reply = messages.find((m) => m && m.id === id)
138 ?? messages.filter((m) => m && m.result !== undefined).pop()
139 ?? messages.filter((m) => m && m.error !== undefined).pop()
140 ?? null
141
142 if (!reply) throw new McpRequestError('AiToEarn MCP 返回了空响应')
143 if (reply.error) {
144 throw new McpRequestError(`AiToEarn MCP 错误 ${reply.error.code ?? ''}: ${reply.error.message ?? 'unknown'}`)
145 }
146 return reply.result ?? reply
147 }
148
149 async notify(method, params) {
150 const headers = await this.#headers()
151 await fetch(this.url, {
152 method: 'POST',
153 headers,
154 body: JSON.stringify({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) }),
155 signal: AbortSignal.timeout(this.timeoutMs),
156 }).catch(() => { /* notifications are best effort */ })
157 }
158
159 /** MCP initialize + initialized handshake. */
160 async initialize() {
161 const result = await this.request('initialize', {
162 protocolVersion: MCP_PROTOCOL_VERSION,
163 capabilities: {},
164 clientInfo: { name: 'dsh-plugin-aitoearn', version: '0.1.0' },
165 })
166 this.protocolVersion = result?.protocolVersion || MCP_PROTOCOL_VERSION
167 this.initialized = true
168 await this.notify('notifications/initialized')
169 }
170
171 async listTools() {
172 const tools = []
173 let cursor
174 do {
175 const result = await this.request('tools/list', cursor === undefined ? {} : { cursor })
176 if (!Array.isArray(result?.tools)) {
177 throw new McpRequestError('AiToEarn MCP 返回的 tools/list 格式不正确')
178 }
179 tools.push(...result.tools)
180 cursor = result.nextCursor
181 } while (cursor)
182 return tools
183 }
184
185 callTool(name, args, { signal } = {}) {
186 return this.request('tools/call', { name, arguments: args }, { signal })
187 }
188
189 async close() {
190 this.initialized = false
191 this.sessionId = ''
192 }
193 }
194
194 lines JAVASCRIPT