@capyclaw/windows-control 0.0.0-stage → 0.1.3
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/LICENSE +21 -0
- package/README.md +142 -2
- package/THIRD_PARTY_NOTICES.md +20 -0
- package/cordis.patch.yml +32 -0
- package/lib/config.mjs +126 -0
- package/lib/mcp-json.mjs +80 -0
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
- package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/node_modules/@capyclaw/portal/README.md +70 -0
- package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
- package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
- package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
- package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
- package/node_modules/@capyclaw/portal/package.json +40 -0
- package/node_modules/@capyclaw/service-broker/README.md +104 -0
- package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
- package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
- package/node_modules/@capyclaw/service-broker/lib/control.mjs +209 -0
- package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
- package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
- package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
- package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
- package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
- package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -0
- package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
- package/node_modules/@capyclaw/service-broker/package.json +65 -0
- package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
- package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
- package/node_modules/@capyclaw/service-broker/services.json +3 -0
- package/package.json +65 -4
- package/plugin.mjs +32 -0
- package/server/relay.mjs +752 -0
package/server/relay.mjs
ADDED
|
@@ -0,0 +1,752 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* windows-control relay:给 windows-mcp 补一层 DSH 需要的壳。
|
|
4
|
+
*
|
|
5
|
+
* 职责只有四件事:
|
|
6
|
+
* 1. 拉起并守护 `uvx --from windows-mcp windows-mcp serve`(Python 3.14);
|
|
7
|
+
* 2. 对外暴露固定端口的 Streamable HTTP `/mcp`,原样代理 JSON-RPC;
|
|
8
|
+
* 3. 补 `/healthz`(service-broker 的存活判据,带自报 pid);
|
|
9
|
+
* 4. 注入本地工具 `windows_capabilities`(suite 契约检查要 contractVersion)。
|
|
10
|
+
*
|
|
11
|
+
* 端口分工:对外端口由 foundation runtime-driver 固定(39660);
|
|
12
|
+
* 上游端口每次启动临时分配,避免与用户已有的 windows-mcp 实例抢端口。
|
|
13
|
+
*/
|
|
14
|
+
import http from 'node:http'
|
|
15
|
+
import fs from 'node:fs'
|
|
16
|
+
import net from 'node:net'
|
|
17
|
+
import os from 'node:os'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import { spawn, spawnSync } from 'node:child_process'
|
|
20
|
+
import { createRequire } from 'node:module'
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
buildUpstreamArgs,
|
|
24
|
+
buildUpstreamEnv,
|
|
25
|
+
readConfig,
|
|
26
|
+
} from '../lib/config.mjs'
|
|
27
|
+
import {
|
|
28
|
+
augmentToolsList,
|
|
29
|
+
capabilityResult,
|
|
30
|
+
isCapabilityCall,
|
|
31
|
+
parseSseOrJson,
|
|
32
|
+
rpcError,
|
|
33
|
+
toolNamesFrom,
|
|
34
|
+
} from '../lib/mcp-json.mjs'
|
|
35
|
+
|
|
36
|
+
const require = createRequire(import.meta.url)
|
|
37
|
+
const pkg = require('../package.json')
|
|
38
|
+
|
|
39
|
+
const PLUGIN_NAME = 'windows-control'
|
|
40
|
+
const CONTRACT_VERSION = '1.0.0'
|
|
41
|
+
const MAX_REQUEST_BYTES = 8 * 1024 * 1024
|
|
42
|
+
const LOG_ROTATE_BYTES = 2 * 1024 * 1024
|
|
43
|
+
|
|
44
|
+
const startedAt = Date.now()
|
|
45
|
+
const stats = { forwarded: 0, local: 0, errors: 0, restarts: 0 }
|
|
46
|
+
|
|
47
|
+
/* ------------------------------------------------------------------ *
|
|
48
|
+
* 启动参数与配置
|
|
49
|
+
* ------------------------------------------------------------------ */
|
|
50
|
+
|
|
51
|
+
function parseArgv(argv) {
|
|
52
|
+
const out = {}
|
|
53
|
+
for (let i = 0; i < argv.length; i++) {
|
|
54
|
+
if (argv[i] === '--port') out.port = Number(argv[++i])
|
|
55
|
+
else if (argv[i] === '--host') out.host = argv[++i]
|
|
56
|
+
}
|
|
57
|
+
return out
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const cli = parseArgv(process.argv.slice(2))
|
|
61
|
+
const config = {
|
|
62
|
+
...readConfig(process.env),
|
|
63
|
+
version: process.env.DSH_WINDOWS_MCP_VERSION || pkg.version || '0.0.0',
|
|
64
|
+
}
|
|
65
|
+
if (Number.isInteger(cli.port) && cli.port > 0) config.port = cli.port
|
|
66
|
+
if (cli.host) config.host = cli.host
|
|
67
|
+
if (!config.logDir) config.logDir = path.join(os.homedir(), '.dsh-windows-control')
|
|
68
|
+
|
|
69
|
+
/* ------------------------------------------------------------------ *
|
|
70
|
+
* 日志:broker 用 stdio:'ignore' 拉起本进程,控制台输出会丢;落一份文件。
|
|
71
|
+
* ------------------------------------------------------------------ */
|
|
72
|
+
|
|
73
|
+
let logBytes = 0
|
|
74
|
+
|
|
75
|
+
function writeLog(line) {
|
|
76
|
+
process.stderr.write(line)
|
|
77
|
+
try {
|
|
78
|
+
fs.mkdirSync(config.logDir, { recursive: true })
|
|
79
|
+
const file = path.join(config.logDir, 'relay.log')
|
|
80
|
+
if (logBytes === 0) {
|
|
81
|
+
try { logBytes = fs.statSync(file).size } catch { logBytes = 0 }
|
|
82
|
+
}
|
|
83
|
+
if (logBytes > LOG_ROTATE_BYTES) {
|
|
84
|
+
try { fs.renameSync(file, `${file}.1`) } catch { /* 轮转失败不阻塞 */ }
|
|
85
|
+
logBytes = 0
|
|
86
|
+
}
|
|
87
|
+
fs.appendFileSync(file, line)
|
|
88
|
+
logBytes += Buffer.byteLength(line)
|
|
89
|
+
} catch { /* 日志失败不影响主链路 */ }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function log(level, message) {
|
|
93
|
+
writeLog(`${new Date().toISOString()} [${level}] ${message}\n`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/* ------------------------------------------------------------------ *
|
|
97
|
+
* 上游进程
|
|
98
|
+
* ------------------------------------------------------------------ */
|
|
99
|
+
|
|
100
|
+
const upstream = {
|
|
101
|
+
state: 'starting', // starting | ready | failed | stopped
|
|
102
|
+
port: null,
|
|
103
|
+
pid: null,
|
|
104
|
+
child: null,
|
|
105
|
+
restarts: 0,
|
|
106
|
+
lastError: null,
|
|
107
|
+
tools: [],
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
let shuttingDown = false
|
|
111
|
+
let pollTimer = null
|
|
112
|
+
let restartTimer = null
|
|
113
|
+
let readinessWaiters = []
|
|
114
|
+
|
|
115
|
+
function resolveReadinessWaiters(error) {
|
|
116
|
+
const waiters = readinessWaiters
|
|
117
|
+
readinessWaiters = []
|
|
118
|
+
for (const waiter of waiters) {
|
|
119
|
+
if (error) waiter.reject(error)
|
|
120
|
+
else waiter.resolve()
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function setState(state) {
|
|
125
|
+
upstream.state = state
|
|
126
|
+
if (state === 'ready') resolveReadinessWaiters(null)
|
|
127
|
+
if (state === 'failed' || state === 'stopped') {
|
|
128
|
+
resolveReadinessWaiters(new Error(upstream.lastError || `windows-mcp ${state}`))
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function freePort() {
|
|
133
|
+
return new Promise((resolve, reject) => {
|
|
134
|
+
const probe = net.createServer()
|
|
135
|
+
probe.unref()
|
|
136
|
+
probe.once('error', reject)
|
|
137
|
+
probe.listen(0, '127.0.0.1', () => {
|
|
138
|
+
const { port } = probe.address()
|
|
139
|
+
probe.close(() => resolve(port))
|
|
140
|
+
})
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async function probeUpstream() {
|
|
145
|
+
const controller = new AbortController()
|
|
146
|
+
const timer = setTimeout(() => controller.abort(), 4000)
|
|
147
|
+
try {
|
|
148
|
+
const res = await fetch(`http://127.0.0.1:${upstream.port}/mcp`, {
|
|
149
|
+
method: 'POST',
|
|
150
|
+
headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' },
|
|
151
|
+
body: JSON.stringify({
|
|
152
|
+
jsonrpc: '2.0',
|
|
153
|
+
id: 'ready-probe',
|
|
154
|
+
method: 'initialize',
|
|
155
|
+
params: {
|
|
156
|
+
protocolVersion: '2025-06-18',
|
|
157
|
+
capabilities: {},
|
|
158
|
+
clientInfo: { name: 'dsh-windows-control', version: config.version },
|
|
159
|
+
},
|
|
160
|
+
}),
|
|
161
|
+
signal: controller.signal,
|
|
162
|
+
})
|
|
163
|
+
if (!res.ok) return false
|
|
164
|
+
await res.arrayBuffer()
|
|
165
|
+
return true
|
|
166
|
+
} catch {
|
|
167
|
+
return false
|
|
168
|
+
} finally {
|
|
169
|
+
clearTimeout(timer)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function startReadinessLoop() {
|
|
174
|
+
clearTimeout(pollTimer)
|
|
175
|
+
const deadline = Date.now() + config.startupTimeoutMs
|
|
176
|
+
let warned = false
|
|
177
|
+
|
|
178
|
+
const tick = async () => {
|
|
179
|
+
if (shuttingDown || !upstream.child) return
|
|
180
|
+
if (upstream.state === 'ready' || upstream.state === 'failed') return
|
|
181
|
+
if (await probeUpstream()) {
|
|
182
|
+
setState('ready')
|
|
183
|
+
log('info', `windows-mcp 就绪(pid ${upstream.pid}, 上游端口 ${upstream.port})`)
|
|
184
|
+
return
|
|
185
|
+
}
|
|
186
|
+
if (Date.now() > deadline && !warned) {
|
|
187
|
+
warned = true
|
|
188
|
+
upstream.lastError = `windows-mcp 在 ${config.startupTimeoutMs}ms 内未就绪`
|
|
189
|
+
log('warn', upstream.lastError)
|
|
190
|
+
}
|
|
191
|
+
pollTimer = setTimeout(tick, warned ? 2000 : 400)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
tick()
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function scheduleRestart(reason) {
|
|
198
|
+
if (shuttingDown) return
|
|
199
|
+
if (upstream.restarts >= config.maxRestarts) {
|
|
200
|
+
upstream.lastError = `${reason};已达最大重启次数 ${config.maxRestarts}`
|
|
201
|
+
setState('failed')
|
|
202
|
+
log('error', upstream.lastError)
|
|
203
|
+
return
|
|
204
|
+
}
|
|
205
|
+
upstream.restarts += 1
|
|
206
|
+
stats.restarts += 1
|
|
207
|
+
const delay = Math.min(1000 * 2 ** (upstream.restarts - 1), 8000)
|
|
208
|
+
setState('starting')
|
|
209
|
+
log('warn', `${reason};${delay}ms 后第 ${upstream.restarts} 次重启`)
|
|
210
|
+
restartTimer = setTimeout(() => {
|
|
211
|
+
restartTimer = null
|
|
212
|
+
startUpstream().catch((error) => {
|
|
213
|
+
upstream.lastError = String(error?.message || error)
|
|
214
|
+
scheduleRestart(`重启失败:${upstream.lastError}`)
|
|
215
|
+
})
|
|
216
|
+
}, delay)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function startUpstream() {
|
|
220
|
+
if (shuttingDown || upstream.child) return
|
|
221
|
+
upstream.port = await freePort()
|
|
222
|
+
upstream.lastError = null
|
|
223
|
+
upstream.tools = []
|
|
224
|
+
setState('starting')
|
|
225
|
+
|
|
226
|
+
const args = buildUpstreamArgs(config, upstream.port)
|
|
227
|
+
const env = buildUpstreamEnv(config)
|
|
228
|
+
log('info', `拉起上游:${config.uvx} ${args.join(' ')}`)
|
|
229
|
+
|
|
230
|
+
let child
|
|
231
|
+
try {
|
|
232
|
+
child = spawn(config.uvx, args, { env, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
233
|
+
} catch (error) {
|
|
234
|
+
upstream.lastError = `spawn ${config.uvx} 失败:${error.message}`
|
|
235
|
+
setState('failed')
|
|
236
|
+
log('error', upstream.lastError)
|
|
237
|
+
return
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
upstream.child = child
|
|
241
|
+
upstream.pid = child.pid ?? null
|
|
242
|
+
|
|
243
|
+
const forward = (stream, level) => {
|
|
244
|
+
stream.setEncoding('utf8')
|
|
245
|
+
let buffer = ''
|
|
246
|
+
stream.on('data', (chunk) => {
|
|
247
|
+
buffer += chunk
|
|
248
|
+
const lines = buffer.split(/\r?\n/)
|
|
249
|
+
buffer = lines.pop() ?? ''
|
|
250
|
+
for (const line of lines) if (line.trim()) log(level, `[upstream] ${line}`)
|
|
251
|
+
})
|
|
252
|
+
}
|
|
253
|
+
forward(child.stdout, 'info')
|
|
254
|
+
forward(child.stderr, 'error')
|
|
255
|
+
|
|
256
|
+
child.on('error', (error) => {
|
|
257
|
+
upstream.lastError = `windows-mcp 进程错误:${error.message}`
|
|
258
|
+
log('error', upstream.lastError)
|
|
259
|
+
upstream.child = null
|
|
260
|
+
upstream.pid = null
|
|
261
|
+
if (error.code === 'ENOENT') setState('failed')
|
|
262
|
+
else scheduleRestart(upstream.lastError)
|
|
263
|
+
})
|
|
264
|
+
|
|
265
|
+
child.on('exit', (code, signal) => {
|
|
266
|
+
upstream.child = null
|
|
267
|
+
upstream.pid = null
|
|
268
|
+
clearTimeout(pollTimer)
|
|
269
|
+
if (shuttingDown) {
|
|
270
|
+
setState('stopped')
|
|
271
|
+
return
|
|
272
|
+
}
|
|
273
|
+
const reason = `windows-mcp 退出(code=${code ?? 'null'}, signal=${signal ?? 'null'})`
|
|
274
|
+
log('warn', reason)
|
|
275
|
+
upstream.lastError = reason
|
|
276
|
+
scheduleRestart(reason)
|
|
277
|
+
})
|
|
278
|
+
|
|
279
|
+
startReadinessLoop()
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** 等上游就绪;starting 会一直等,failed 立即失败。 */
|
|
283
|
+
function waitForReady(timeoutMs) {
|
|
284
|
+
if (upstream.state === 'ready') return Promise.resolve()
|
|
285
|
+
if (upstream.state === 'failed') {
|
|
286
|
+
return Promise.reject(new Error(upstream.lastError || 'windows-mcp 启动失败'))
|
|
287
|
+
}
|
|
288
|
+
if (shuttingDown) return Promise.reject(new Error('relay 正在关闭'))
|
|
289
|
+
return new Promise((resolve, reject) => {
|
|
290
|
+
const timer = setTimeout(() => {
|
|
291
|
+
readinessWaiters = readinessWaiters.filter((waiter) => waiter !== entry)
|
|
292
|
+
reject(new Error(`windows-mcp 在 ${timeoutMs}ms 内未就绪`))
|
|
293
|
+
}, timeoutMs)
|
|
294
|
+
const entry = {
|
|
295
|
+
resolve: () => { clearTimeout(timer); resolve() },
|
|
296
|
+
reject: (error) => { clearTimeout(timer); reject(error) },
|
|
297
|
+
}
|
|
298
|
+
readinessWaiters.push(entry)
|
|
299
|
+
})
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/* ------------------------------------------------------------------ *
|
|
303
|
+
* HTTP 工具
|
|
304
|
+
* ------------------------------------------------------------------ */
|
|
305
|
+
|
|
306
|
+
function sendJson(res, status, body, headers = {}) {
|
|
307
|
+
if (res.destroyed) return
|
|
308
|
+
const text = JSON.stringify(body)
|
|
309
|
+
res.writeHead(status, {
|
|
310
|
+
'content-type': 'application/json; charset=utf-8',
|
|
311
|
+
'content-length': Buffer.byteLength(text),
|
|
312
|
+
...headers,
|
|
313
|
+
})
|
|
314
|
+
res.end(text)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
function sendRaw(res, status, text, contentType = 'text/plain; charset=utf-8') {
|
|
318
|
+
if (res.destroyed) return
|
|
319
|
+
res.writeHead(status, {
|
|
320
|
+
'content-type': contentType,
|
|
321
|
+
'content-length': Buffer.byteLength(text),
|
|
322
|
+
})
|
|
323
|
+
res.end(text)
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function sendRpcError(res, id, code, message) {
|
|
327
|
+
return sendJson(res, 200, rpcError(id, code, message))
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/** MCP 通知/仅通知批量:202 且无正文。 */
|
|
331
|
+
function sendAccepted(res) {
|
|
332
|
+
if (res.destroyed) return
|
|
333
|
+
res.writeHead(202, { 'content-length': 0 })
|
|
334
|
+
res.end()
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
function readBody(req) {
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
const chunks = []
|
|
340
|
+
let size = 0
|
|
341
|
+
req.on('data', (chunk) => {
|
|
342
|
+
size += chunk.length
|
|
343
|
+
if (size > MAX_REQUEST_BYTES) {
|
|
344
|
+
const error = new Error('请求体过大')
|
|
345
|
+
error.code = 'BODY_TOO_LARGE'
|
|
346
|
+
req.destroy()
|
|
347
|
+
reject(error)
|
|
348
|
+
return
|
|
349
|
+
}
|
|
350
|
+
chunks.push(chunk)
|
|
351
|
+
})
|
|
352
|
+
req.on('end', () => resolve(Buffer.concat(chunks)))
|
|
353
|
+
req.on('error', reject)
|
|
354
|
+
})
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
const REQUEST_HEADER_BLOCKLIST = new Set(['host', 'connection', 'keep-alive', 'transfer-encoding', 'content-length', 'upgrade'])
|
|
358
|
+
const RESPONSE_HEADER_BLOCKLIST = new Set(['connection', 'keep-alive', 'transfer-encoding', 'upgrade', 'content-length'])
|
|
359
|
+
|
|
360
|
+
function filteredHeaders(headers, blocklist) {
|
|
361
|
+
const out = {}
|
|
362
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
363
|
+
if (value === undefined || blocklist.has(key.toLowerCase())) continue
|
|
364
|
+
out[key] = value
|
|
365
|
+
}
|
|
366
|
+
return out
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function upstreamHeaders(req) {
|
|
370
|
+
return filteredHeaders(req.headers, REQUEST_HEADER_BLOCKLIST)
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/* ------------------------------------------------------------------ *
|
|
374
|
+
* 上游请求
|
|
375
|
+
* ------------------------------------------------------------------ */
|
|
376
|
+
|
|
377
|
+
function requestUpstream(payload, sessionId = '') {
|
|
378
|
+
const body = Buffer.from(JSON.stringify(payload))
|
|
379
|
+
const target = `http://127.0.0.1:${upstream.port}`
|
|
380
|
+
const headers = {
|
|
381
|
+
'content-type': 'application/json',
|
|
382
|
+
accept: 'application/json, text/event-stream',
|
|
383
|
+
'content-length': String(body.length),
|
|
384
|
+
}
|
|
385
|
+
// stateful 模式下 tools/list 必须带调用方的会话;stateless 下带了也无害。
|
|
386
|
+
if (sessionId) headers['mcp-session-id'] = sessionId
|
|
387
|
+
return new Promise((resolve, reject) => {
|
|
388
|
+
const req = http.request({
|
|
389
|
+
host: '127.0.0.1',
|
|
390
|
+
port: upstream.port,
|
|
391
|
+
path: '/mcp',
|
|
392
|
+
method: 'POST',
|
|
393
|
+
headers,
|
|
394
|
+
}, (res) => {
|
|
395
|
+
const chunks = []
|
|
396
|
+
res.on('data', (chunk) => chunks.push(chunk))
|
|
397
|
+
res.on('end', () => resolve({
|
|
398
|
+
status: res.statusCode || 502,
|
|
399
|
+
headers: res.headers,
|
|
400
|
+
text: Buffer.concat(chunks).toString('utf8'),
|
|
401
|
+
url: target,
|
|
402
|
+
}))
|
|
403
|
+
res.on('error', reject)
|
|
404
|
+
})
|
|
405
|
+
req.setTimeout(config.requestTimeoutMs, () => req.destroy(new Error(`上游 ${config.requestTimeoutMs}ms 未响应`)))
|
|
406
|
+
req.on('error', reject)
|
|
407
|
+
req.end(body)
|
|
408
|
+
})
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function streamProxy(req, res, body) {
|
|
412
|
+
const target = `http://127.0.0.1:${upstream.port}`
|
|
413
|
+
const headers = upstreamHeaders(req)
|
|
414
|
+
if (body) headers['content-length'] = String(body.length)
|
|
415
|
+
|
|
416
|
+
const upstreamReq = http.request({
|
|
417
|
+
host: '127.0.0.1',
|
|
418
|
+
port: upstream.port,
|
|
419
|
+
path: '/mcp',
|
|
420
|
+
method: req.method,
|
|
421
|
+
headers,
|
|
422
|
+
}, (upstreamRes) => {
|
|
423
|
+
if (res.destroyed) { upstreamRes.destroy(); return }
|
|
424
|
+
res.writeHead(upstreamRes.statusCode || 502, filteredHeaders(upstreamRes.headers, RESPONSE_HEADER_BLOCKLIST))
|
|
425
|
+
upstreamRes.pipe(res)
|
|
426
|
+
upstreamRes.on('error', () => res.destroy())
|
|
427
|
+
})
|
|
428
|
+
|
|
429
|
+
upstreamReq.setTimeout(config.requestTimeoutMs, () => upstreamReq.destroy(new Error(`上游 ${config.requestTimeoutMs}ms 未响应`)))
|
|
430
|
+
upstreamReq.on('error', (error) => {
|
|
431
|
+
stats.errors += 1
|
|
432
|
+
log('error', `代理 ${req.method} /mcp 失败:${error.message}(${target})`)
|
|
433
|
+
if (!res.headersSent) sendRpcError(res, null, -32000, `windows-mcp 不可达:${error.message}`)
|
|
434
|
+
else res.destroy()
|
|
435
|
+
})
|
|
436
|
+
upstreamReq.end(body ?? undefined)
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/* ------------------------------------------------------------------ *
|
|
440
|
+
* 契约工具
|
|
441
|
+
* ------------------------------------------------------------------ */
|
|
442
|
+
|
|
443
|
+
let refreshPromise = null
|
|
444
|
+
|
|
445
|
+
async function refreshTools(sessionId = '') {
|
|
446
|
+
if (upstream.state !== 'ready') return upstream.tools
|
|
447
|
+
if (refreshPromise) return refreshPromise
|
|
448
|
+
refreshPromise = (async () => {
|
|
449
|
+
try {
|
|
450
|
+
const result = await requestUpstream({ jsonrpc: '2.0', id: 'capabilities-refresh', method: 'tools/list' }, sessionId)
|
|
451
|
+
if (result.status >= 400) return upstream.tools
|
|
452
|
+
const parsed = parseSseOrJson(result.text)
|
|
453
|
+
const list = Array.isArray(parsed) ? parsed : [parsed]
|
|
454
|
+
for (const message of list) {
|
|
455
|
+
const names = toolNamesFrom(message)
|
|
456
|
+
if (names) upstream.tools = names
|
|
457
|
+
}
|
|
458
|
+
} catch (error) {
|
|
459
|
+
log('warn', `刷新工具清单失败:${error.message}`)
|
|
460
|
+
} finally {
|
|
461
|
+
refreshPromise = null
|
|
462
|
+
}
|
|
463
|
+
return upstream.tools
|
|
464
|
+
})()
|
|
465
|
+
return refreshPromise
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
function capabilityPayload() {
|
|
469
|
+
return {
|
|
470
|
+
contractVersion: CONTRACT_VERSION,
|
|
471
|
+
plugin: { name: PLUGIN_NAME, version: config.version },
|
|
472
|
+
upstream: {
|
|
473
|
+
state: upstream.state,
|
|
474
|
+
package: config.packageSpec,
|
|
475
|
+
python: config.python,
|
|
476
|
+
port: upstream.port,
|
|
477
|
+
pid: upstream.pid,
|
|
478
|
+
restarts: upstream.restarts,
|
|
479
|
+
lastError: upstream.lastError,
|
|
480
|
+
},
|
|
481
|
+
tools: upstream.tools,
|
|
482
|
+
toolCount: upstream.tools.length,
|
|
483
|
+
policy: {
|
|
484
|
+
tools: config.tools,
|
|
485
|
+
excludeTools: config.excludeTools,
|
|
486
|
+
telemetry: config.telemetry,
|
|
487
|
+
screenshotFlash: config.screenshotFlash,
|
|
488
|
+
stateless: config.stateless,
|
|
489
|
+
},
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
async function localCapabilityResponse(message, sessionId = '') {
|
|
494
|
+
if (message?.id === undefined || message?.id === null) return null
|
|
495
|
+
try {
|
|
496
|
+
await waitForReady(10000)
|
|
497
|
+
} catch { /* 未就绪也返回契约,让调用方看到状态 */ }
|
|
498
|
+
await refreshTools(sessionId)
|
|
499
|
+
return capabilityResult(message, capabilityPayload())
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/* ------------------------------------------------------------------ *
|
|
503
|
+
* /mcp 代理
|
|
504
|
+
* ------------------------------------------------------------------ */
|
|
505
|
+
|
|
506
|
+
async function handleMcp(req, res) {
|
|
507
|
+
if (req.method !== 'POST') {
|
|
508
|
+
// Streamable HTTP 的 GET(SSE 流)与 DELETE(结束会话)原样转发。
|
|
509
|
+
try {
|
|
510
|
+
await waitForReady(config.startupTimeoutMs)
|
|
511
|
+
} catch (error) {
|
|
512
|
+
return sendJson(res, 503, { error: String(error.message || error) })
|
|
513
|
+
}
|
|
514
|
+
return streamProxy(req, res, null)
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
let body
|
|
518
|
+
try {
|
|
519
|
+
body = await readBody(req)
|
|
520
|
+
} catch (error) {
|
|
521
|
+
return sendRpcError(res, null, -32600, error.code === 'BODY_TOO_LARGE' ? '请求体过大' : '读取请求失败')
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
let payload
|
|
525
|
+
try {
|
|
526
|
+
payload = JSON.parse(body.toString('utf8'))
|
|
527
|
+
} catch {
|
|
528
|
+
return sendRpcError(res, null, -32700, 'Parse error')
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const batch = Array.isArray(payload)
|
|
532
|
+
const messages = batch ? payload : [payload]
|
|
533
|
+
if (batch && messages.length === 0) return sendRpcError(res, null, -32600, 'Invalid Request')
|
|
534
|
+
|
|
535
|
+
const rawSession = req.headers['mcp-session-id']
|
|
536
|
+
const sessionId = Array.isArray(rawSession) ? rawSession[0] : (rawSession || '')
|
|
537
|
+
|
|
538
|
+
const local = new Set()
|
|
539
|
+
let remoteCount = 0
|
|
540
|
+
let needsBuffer = false
|
|
541
|
+
for (const [index, message] of messages.entries()) {
|
|
542
|
+
if (isCapabilityCall(message)) {
|
|
543
|
+
local.add(index)
|
|
544
|
+
continue
|
|
545
|
+
}
|
|
546
|
+
remoteCount += 1
|
|
547
|
+
if (message?.method === 'tools/list') needsBuffer = true
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
if (remoteCount === 0) {
|
|
551
|
+
stats.local += 1
|
|
552
|
+
const responses = []
|
|
553
|
+
for (const index of local) {
|
|
554
|
+
const response = await localCapabilityResponse(messages[index], sessionId)
|
|
555
|
+
if (response) responses.push(response)
|
|
556
|
+
}
|
|
557
|
+
if (!responses.length) return sendAccepted(res)
|
|
558
|
+
return sendJson(res, 200, batch ? responses : responses[0])
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
try {
|
|
562
|
+
await waitForReady(config.startupTimeoutMs)
|
|
563
|
+
} catch (error) {
|
|
564
|
+
stats.errors += 1
|
|
565
|
+
return sendRpcError(res, null, -32000, String(error.message || error))
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
// 无本地调用、无需改写工具列表:直接流式转发,截图等大响应不落内存。
|
|
569
|
+
if (!local.size && !needsBuffer) {
|
|
570
|
+
stats.forwarded += 1
|
|
571
|
+
return streamProxy(req, res, body)
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const remoteMessages = messages.filter((_, index) => !local.has(index))
|
|
575
|
+
const remotePayload = batch ? remoteMessages : remoteMessages[0]
|
|
576
|
+
|
|
577
|
+
let result
|
|
578
|
+
try {
|
|
579
|
+
result = await requestUpstream(remotePayload, sessionId)
|
|
580
|
+
} catch (error) {
|
|
581
|
+
stats.errors += 1
|
|
582
|
+
log('error', `上游请求失败:${error.message}`)
|
|
583
|
+
return sendRpcError(res, null, -32000, `windows-mcp 不可达:${error.message}`)
|
|
584
|
+
}
|
|
585
|
+
stats.forwarded += 1
|
|
586
|
+
|
|
587
|
+
if (result.status >= 400) {
|
|
588
|
+
return sendRaw(res, result.status, result.text || `上游 HTTP ${result.status}`)
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
let parsed
|
|
592
|
+
try {
|
|
593
|
+
parsed = parseSseOrJson(result.text)
|
|
594
|
+
} catch (error) {
|
|
595
|
+
stats.errors += 1
|
|
596
|
+
return sendRpcError(res, null, -32700, `上游响应无法解析:${error.message}`)
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
if (parsed === null || parsed === undefined) {
|
|
600
|
+
if (!local.size) return sendJson(res, result.status, {})
|
|
601
|
+
parsed = []
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
const remoteResponses = Array.isArray(parsed) ? parsed : [parsed]
|
|
605
|
+
for (const message of remoteResponses) {
|
|
606
|
+
augmentToolsList(message)
|
|
607
|
+
const names = toolNamesFrom(message)
|
|
608
|
+
if (names) upstream.tools = names
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
const forwardHeaders = result.headers['mcp-session-id']
|
|
612
|
+
? { 'mcp-session-id': result.headers['mcp-session-id'] }
|
|
613
|
+
: {}
|
|
614
|
+
|
|
615
|
+
if (!local.size) {
|
|
616
|
+
return sendJson(res, result.status, parsed, forwardHeaders)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
const byId = new Map()
|
|
620
|
+
for (const message of remoteResponses) {
|
|
621
|
+
if (message && message.id !== undefined && message.id !== null) byId.set(String(message.id), message)
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
const merged = []
|
|
625
|
+
for (const [index, message] of messages.entries()) {
|
|
626
|
+
if (local.has(index)) {
|
|
627
|
+
stats.local += 1
|
|
628
|
+
const response = await localCapabilityResponse(message, sessionId)
|
|
629
|
+
if (response) merged.push(response)
|
|
630
|
+
continue
|
|
631
|
+
}
|
|
632
|
+
if (message?.id === undefined || message?.id === null) continue
|
|
633
|
+
const response = byId.get(String(message.id))
|
|
634
|
+
if (response) merged.push(response)
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
if (!merged.length) return sendAccepted(res)
|
|
638
|
+
return sendJson(res, 200, batch ? merged : merged[0], forwardHeaders)
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/* ------------------------------------------------------------------ *
|
|
642
|
+
* HTTP 服务
|
|
643
|
+
* ------------------------------------------------------------------ */
|
|
644
|
+
|
|
645
|
+
const server = http.createServer((req, res) => {
|
|
646
|
+
const url = new URL(req.url, `http://${req.headers.host || '127.0.0.1'}`)
|
|
647
|
+
const pathname = url.pathname.replace(/\/{2,}/g, '/')
|
|
648
|
+
|
|
649
|
+
if (pathname === '/healthz' && (req.method === 'GET' || req.method === 'HEAD')) {
|
|
650
|
+
const ok = upstream.state !== 'failed'
|
|
651
|
+
return sendJson(res, ok ? 200 : 503, {
|
|
652
|
+
ok,
|
|
653
|
+
pid: process.pid,
|
|
654
|
+
name: PLUGIN_NAME,
|
|
655
|
+
version: config.version,
|
|
656
|
+
contractVersion: CONTRACT_VERSION,
|
|
657
|
+
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
|
658
|
+
upstream: {
|
|
659
|
+
state: upstream.state,
|
|
660
|
+
ready: upstream.state === 'ready',
|
|
661
|
+
package: config.packageSpec,
|
|
662
|
+
python: config.python,
|
|
663
|
+
pid: upstream.pid,
|
|
664
|
+
port: upstream.port,
|
|
665
|
+
restarts: upstream.restarts,
|
|
666
|
+
lastError: upstream.lastError,
|
|
667
|
+
},
|
|
668
|
+
tools: { count: upstream.tools.length },
|
|
669
|
+
})
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
if (pathname === '/metrics' && req.method === 'GET') {
|
|
673
|
+
return sendJson(res, 200, {
|
|
674
|
+
uptimeSec: Math.round((Date.now() - startedAt) / 1000),
|
|
675
|
+
...stats,
|
|
676
|
+
upstream: {
|
|
677
|
+
state: upstream.state,
|
|
678
|
+
pid: upstream.pid,
|
|
679
|
+
port: upstream.port,
|
|
680
|
+
restarts: upstream.restarts,
|
|
681
|
+
toolCount: upstream.tools.length,
|
|
682
|
+
},
|
|
683
|
+
})
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
if (pathname === '/mcp') {
|
|
687
|
+
handleMcp(req, res).catch((error) => {
|
|
688
|
+
stats.errors += 1
|
|
689
|
+
log('error', `处理 /mcp 失败:${error.stack || error.message}`)
|
|
690
|
+
if (!res.headersSent) sendJson(res, 500, rpcError(null, -32603, 'Internal error'))
|
|
691
|
+
else res.destroy()
|
|
692
|
+
})
|
|
693
|
+
return
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
sendJson(res, 404, { error: `未知路径:${pathname}` })
|
|
697
|
+
})
|
|
698
|
+
|
|
699
|
+
// 这个端点等价于整机操作权,只允许回环绑定。
|
|
700
|
+
const LOOPBACK_HOSTS = new Set(['127.0.0.1', '::1', 'localhost'])
|
|
701
|
+
if (!LOOPBACK_HOSTS.has(config.host)) {
|
|
702
|
+
log('warn', `拒绝绑定非回环地址 ${config.host},强制改为 127.0.0.1`)
|
|
703
|
+
config.host = '127.0.0.1'
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
server.on('error', (error) => {
|
|
707
|
+
log('error', `relay 监听 ${config.host}:${config.port} 失败:${error.message}`)
|
|
708
|
+
process.exit(1)
|
|
709
|
+
})
|
|
710
|
+
|
|
711
|
+
server.listen(config.port, config.host, () => {
|
|
712
|
+
log('info', `relay 已监听 http://${config.host}:${config.port}(contract v${CONTRACT_VERSION})`)
|
|
713
|
+
startUpstream().catch((error) => {
|
|
714
|
+
upstream.lastError = String(error?.message || error)
|
|
715
|
+
setState('failed')
|
|
716
|
+
log('error', `启动上游失败:${upstream.lastError}`)
|
|
717
|
+
})
|
|
718
|
+
})
|
|
719
|
+
|
|
720
|
+
/* ------------------------------------------------------------------ *
|
|
721
|
+
* 退出
|
|
722
|
+
* ------------------------------------------------------------------ */
|
|
723
|
+
|
|
724
|
+
function killUpstream() {
|
|
725
|
+
const pid = upstream.child?.pid ?? upstream.pid
|
|
726
|
+
if (!pid) return
|
|
727
|
+
try {
|
|
728
|
+
if (process.platform === 'win32') {
|
|
729
|
+
spawnSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
|
|
730
|
+
} else {
|
|
731
|
+
try { process.kill(pid, 'SIGTERM') } catch { /* 已退出 */ }
|
|
732
|
+
}
|
|
733
|
+
} catch { /* 回收失败不阻塞退出 */ }
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
function shutdown(signal) {
|
|
737
|
+
if (shuttingDown) return
|
|
738
|
+
shuttingDown = true
|
|
739
|
+
log('info', `收到 ${signal},正在关闭`)
|
|
740
|
+
clearTimeout(pollTimer)
|
|
741
|
+
clearTimeout(restartTimer)
|
|
742
|
+
killUpstream()
|
|
743
|
+
setState('stopped')
|
|
744
|
+
server.close()
|
|
745
|
+
setTimeout(() => process.exit(0), 600).unref()
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
process.on('SIGINT', () => shutdown('SIGINT'))
|
|
749
|
+
process.on('SIGTERM', () => shutdown('SIGTERM'))
|
|
750
|
+
process.on('unhandledRejection', (error) => log('error', `未处理的 Promise 拒绝:${error?.stack || error}`))
|
|
751
|
+
|
|
752
|
+
export { server, config }
|