local-mcp-manager 0.5.4 → 0.9.0
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/CHANGELOG.md +51 -0
- package/README.md +46 -43
- package/THIRD_PARTY_NOTICES.md +3 -1
- package/assets/mcp-manager.svg +7 -0
- package/dist/workbench.js +2887 -0
- package/lib/config-import.js +63 -0
- package/lib/controller.js +94 -20
- package/lib/health.js +119 -0
- package/lib/index.js +162 -7
- package/lib/path-format.js +10 -0
- package/lib/registry.js +186 -0
- package/lib/resource-support.js +294 -0
- package/lib/runtime.js +294 -29
- package/lib/stats.js +144 -0
- package/lib/store.js +39 -16
- package/lib/tool-preview.js +40 -0
- package/lib/tool-trust.js +105 -0
- package/lib/web.js +863 -0
- package/lib/workbench-host.js +70 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +99 -17
- package/src/workbench/contract.js +198 -0
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { record } from './store.js'
|
|
3
|
+
|
|
4
|
+
const reserved = new Set(['__proto__', 'constructor', 'prototype'])
|
|
5
|
+
const interpolation = /\$\{[^}]*\}/
|
|
6
|
+
const transports = new Map([['stdio', 'stdio'], ['http', 'streamable-http'], ['streamable-http', 'streamable-http'], ['sse', 'sse']])
|
|
7
|
+
|
|
8
|
+
function importId(name) {
|
|
9
|
+
if (/^[A-Za-z][A-Za-z0-9_-]{0,31}$/.test(name) && !reserved.has(name)) return name
|
|
10
|
+
const slug = name.replace(/[^A-Za-z0-9_-]+/g, '-').replace(/^[^A-Za-z]+/, '') || 'mcp'
|
|
11
|
+
return `${slug.slice(0, 19)}-${createHash('sha256').update(name).digest('hex').slice(0, 12)}`
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const literal = value => {
|
|
15
|
+
if (typeof value !== 'string') throw Error('第三方配置的地址、程序、参数或凭据值须为字符串')
|
|
16
|
+
if (interpolation.test(value)) throw Error('第三方配置含变量引用;请先替换为当前 DSH 主机使用的值')
|
|
17
|
+
return value
|
|
18
|
+
}
|
|
19
|
+
const pairs = value => {
|
|
20
|
+
if (value === undefined) return []
|
|
21
|
+
if (!record(value) || Object.keys(value).length > 16) throw Error('第三方请求头或环境变量须为键值表,最多 16 项')
|
|
22
|
+
return Object.entries(value).map(([name, value]) => ({ name, value: literal(value) }))
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function adaptServer(label, raw) {
|
|
26
|
+
const name = label.trim()
|
|
27
|
+
if (!name || reserved.has(name) || !record(raw)) throw Error('第三方配置包含无效条目')
|
|
28
|
+
const hasCommand = Object.hasOwn(raw, 'command'), hasUrl = Object.hasOwn(raw, 'url')
|
|
29
|
+
const declared = raw.type ?? raw.transport
|
|
30
|
+
const transport = declared === undefined ? (hasCommand ? 'stdio' : 'streamable-http') : transports.get(declared)
|
|
31
|
+
if (!transport || hasCommand === hasUrl || (transport === 'stdio') !== hasCommand) {
|
|
32
|
+
throw Error('第三方条目须指定一个 stdio 程序或 HTTP/SSE 地址')
|
|
33
|
+
}
|
|
34
|
+
const headers = pairs(raw.headers), env = pairs(raw.env)
|
|
35
|
+
const server = { id: importId(name), name: name.slice(0, 80), transport, headers, env, enabled: false, requireApproval: true }
|
|
36
|
+
if (hasCommand) {
|
|
37
|
+
const args = raw.args ?? []
|
|
38
|
+
if (headers.length || !Array.isArray(args) || args.length > 64) throw Error('第三方 stdio 启动参数或请求头不受支持')
|
|
39
|
+
return { ...server, command: literal(raw.command), args: args.map(literal), cwd: literal(raw.cwd ?? '') }
|
|
40
|
+
}
|
|
41
|
+
if (env.length || raw.args !== undefined || raw.cwd !== undefined) throw Error('HTTP/SSE 条目不能设置本地进程参数')
|
|
42
|
+
return { ...server, url: literal(raw.url) }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function parseImportDocument(content) {
|
|
46
|
+
let document
|
|
47
|
+
try { document = JSON.parse(content.replace(/^\uFEFF/, '')) }
|
|
48
|
+
catch { throw Error('导入内容不是有效的 JSON') }
|
|
49
|
+
const usable = value => value.length >= 1 && value.length <= 32
|
|
50
|
+
if (record(document) && Array.isArray(document.servers) && !Object.hasOwn(document, 'mcpServers')) {
|
|
51
|
+
if (document.version !== undefined && document.version !== 1) throw Error('不支持该 MCP 管理器备份版本')
|
|
52
|
+
if (!usable(document.servers)) throw Error('导入文件需包含 1 到 32 个服务器')
|
|
53
|
+
return { external: false, servers: document.servers }
|
|
54
|
+
}
|
|
55
|
+
if (!record(document) || (Object.hasOwn(document, 'mcpServers') && Object.hasOwn(document, 'servers'))) {
|
|
56
|
+
throw Error('请选择本插件备份或包含 mcpServers/servers 的第三方 JSON')
|
|
57
|
+
}
|
|
58
|
+
const map = document.mcpServers ?? document.servers
|
|
59
|
+
if (!record(map)) throw Error('请选择本插件备份或包含 mcpServers/servers 的第三方 JSON')
|
|
60
|
+
const entries = Object.entries(map)
|
|
61
|
+
if (!usable(entries)) throw Error('导入文件需包含 1 到 32 个服务器')
|
|
62
|
+
return { external: true, servers: entries.map(([name, raw]) => adaptServer(name, raw)) }
|
|
63
|
+
}
|
package/lib/controller.js
CHANGED
|
@@ -2,6 +2,10 @@ import {randomUUID} from 'node:crypto'
|
|
|
2
2
|
import {normalizeServer,formPayload,record,bool,integer,pairs} from './store.js'
|
|
3
3
|
import {render,connectionView,composeView,draftServer,buildView} from './ui.js'
|
|
4
4
|
import {referenced} from './credentials.js'
|
|
5
|
+
import {createWebApi,McpWebError} from './web.js'
|
|
6
|
+
|
|
7
|
+
const refsIn=state=>new Set(state.servers.flatMap(server=>[...(server.headers??[]),...(server.env??[])])
|
|
8
|
+
.map(pair=>pair.credentialRef).filter(Boolean))
|
|
5
9
|
|
|
6
10
|
export function createController(store,runtime,options={}){
|
|
7
11
|
const screens=new Map(),listeners=new Map(),projections=new Map(),toolPositions=new Map(),listPositions=new Map(),vault=options.vault
|
|
@@ -18,7 +22,8 @@ export function createController(store,runtime,options={}){
|
|
|
18
22
|
if(['server','overview'].includes(screen.page))return {serverId:screen.serverId,detail:'tools'}
|
|
19
23
|
return {serverId:screen.serverId,detail:'summary'}
|
|
20
24
|
}
|
|
21
|
-
const
|
|
25
|
+
const project=spec=>runtime.project?runtime.project(spec):runtime.snapshot()
|
|
26
|
+
const runtimeView=screen=>project(projectOptions(screen))
|
|
22
27
|
const data=scope=>{const view=render(store.snapshot(),runtimeView(screenOf(scope)),screenOf(scope));projections.set(key(scope),view);return view}
|
|
23
28
|
const args=event=>{const raw=event?.value??{},v=record(raw)?raw:{value:raw};return {...(record(v.args)?v.args:{}),...v}}
|
|
24
29
|
const revision=(v,scope)=>{const n=v.revision??screenOf(scope).revision;if(!Number.isSafeInteger(n)||n!==store.snapshot().revision)throw Error('配置已更新,请重新打开后重试');return n}
|
|
@@ -55,12 +60,81 @@ export function createController(store,runtime,options={}){
|
|
|
55
60
|
for(const emit of subscribers)emit(wire(view))
|
|
56
61
|
}
|
|
57
62
|
}
|
|
58
|
-
const
|
|
59
|
-
const
|
|
63
|
+
const watch=work=>{Promise.resolve(work).then(notify,notify)}
|
|
64
|
+
const reconcile=()=>{
|
|
65
|
+
try {watch(runtime.reconcile())} catch { /* A persisted change stays committed. */ }
|
|
66
|
+
notify()
|
|
67
|
+
}
|
|
68
|
+
const connect=(id,force)=>watch(force?runtime.connect(id):runtime.refresh(id))
|
|
69
|
+
const dropUnused=async refs=>{
|
|
70
|
+
if(!vault)return
|
|
71
|
+
for(const ref of refs)try {
|
|
72
|
+
if(!referenced(store.snapshot(),ref))await vault.drop(ref)
|
|
73
|
+
} catch { /* Cleanup must not mask the commit outcome. */ }
|
|
74
|
+
}
|
|
75
|
+
const commit=async(rev,mutate,beforeCommit)=>{
|
|
76
|
+
if(disposed)throw new McpWebError('RUNTIME_NOT_READY')
|
|
77
|
+
const created=new Set()
|
|
78
|
+
const put=async value=>{
|
|
79
|
+
if(typeof vault?.put!=='function'||options.isVaultReady?.()===false)throw new McpWebError('VAULT_UNAVAILABLE')
|
|
80
|
+
const ref=await vault.put(value)
|
|
81
|
+
created.add(ref)
|
|
82
|
+
return ref
|
|
83
|
+
}
|
|
84
|
+
let entered=false,result,retired=[]
|
|
85
|
+
try {
|
|
86
|
+
result=await store.update(rev,async next=>{
|
|
87
|
+
entered=true
|
|
88
|
+
if(disposed)throw new McpWebError('RUNTIME_NOT_READY')
|
|
89
|
+
const prior=refsIn(next)
|
|
90
|
+
await mutate(next,put)
|
|
91
|
+
const remaining=refsIn(next)
|
|
92
|
+
retired=[...prior].filter(ref=>!remaining.has(ref))
|
|
93
|
+
},beforeCommit)
|
|
94
|
+
} catch(error) {
|
|
95
|
+
// Permissions and validation happen before the atomic replacement.
|
|
96
|
+
// No saved reference was created when a transaction is rejected.
|
|
97
|
+
await dropUnused(created)
|
|
98
|
+
if(!entered&&store.snapshot().revision!==rev)throw new McpWebError('REVISION_CONFLICT')
|
|
99
|
+
throw error
|
|
100
|
+
}
|
|
101
|
+
reconcile()
|
|
102
|
+
await dropUnused(retired)
|
|
103
|
+
return result
|
|
104
|
+
}
|
|
105
|
+
const web=createWebApi({
|
|
106
|
+
snapshot:()=>store.snapshot(),commit,connect,
|
|
107
|
+
autoConnect:options.autoConnect??(()=>true),isActive:()=>!disposed&&(options.isActive?.()??true),
|
|
108
|
+
projectTools:()=>project({detail:'tools'}),
|
|
109
|
+
// Detailed Web reads never fall back to the full runtime snapshot.
|
|
110
|
+
projectWorkbench:spec=>runtime.project?.(spec)??{},
|
|
111
|
+
discoveredToolNames:id=>runtime.discoveredToolNames?.(id),
|
|
112
|
+
discoveredToolStamps:id=>runtime.discoveredToolStamps?.(id),
|
|
113
|
+
currentToolStamp:(id,name)=>runtime.currentToolStamp?.(id,name),
|
|
114
|
+
toolAccess:(id,name)=>runtime.toolAccess?.(id,name),
|
|
115
|
+
reviewTool:(id,name,check)=>runtime.reviewTool?.(id,name,check),
|
|
116
|
+
hasLiveTool:(id,name)=>runtime.hasDiscoveredTool?.(id,name)===true,
|
|
117
|
+
hasDiscoveredTool:(id,name)=>runtime.hasDiscoveredTool
|
|
118
|
+
?runtime.hasDiscoveredTool(id,name)
|
|
119
|
+
:project({serverId:id,detail:'tool',toolName:name})[id]?.tools?.some(tool=>tool.name===name),
|
|
120
|
+
aggregate:()=>runtime.aggregate?.(),
|
|
121
|
+
invokeTool:(id,name,args,timeoutMs)=>runtime.invokeTool?.(id,name,args,timeoutMs),
|
|
122
|
+
resolveSecret:ref=>options.resolveSecret?.(ref),
|
|
123
|
+
healthStatus:()=>options.health?.status?.(),
|
|
124
|
+
healthApply:patch=>options.health?.apply?.(patch),
|
|
125
|
+
registrySearch:query=>options.registry?.search?options.registry.search(query):{servers:[],source:'',unreachable:true},
|
|
126
|
+
readResource:(id,uri)=>runtime.readResource?.(id,uri),
|
|
127
|
+
resourceWatches:id=>runtime.resourceWatches?.(id),
|
|
128
|
+
setResourceWatch:(id,uri,enabled)=>runtime.setResourceWatch?.(id,uri,enabled),
|
|
129
|
+
getPrompt:(id,name,args)=>runtime.getPrompt?.(id,name,args),
|
|
130
|
+
setLogLevel:(id,level)=>runtime.setLogLevel?.(id,level),
|
|
131
|
+
logTail:id=>runtime.logTail?.(id)??{level:null,lines:[]},
|
|
132
|
+
statsOverview: async days => { const s=options.stats; if(!s?.overview)return null; await s.loaded; return s.overview({days}) },
|
|
133
|
+
})
|
|
60
134
|
const guarded=fn=>async(scope,event={})=>{try{return await fn(scope,event)}catch(error){return {toast:error instanceof SyntaxError?'填写格式不正确,请检查':String(error.message).length<=40?error.message:'操作未完成,请重新打开后重试'}}}
|
|
61
135
|
const checkServer=(scope,id,force=false)=>{
|
|
62
136
|
const s=find(id);if(!s.enabled)return {toast:'请先启用此服务器'}
|
|
63
|
-
|
|
137
|
+
connect(id,force)
|
|
64
138
|
const screen=screenOf(scope),before=projections.get(key(scope))
|
|
65
139
|
if(before&&['settings','server','overview'].includes(screen.page)){
|
|
66
140
|
const view=composeView({...before,connection:connectionView(s,runtimeView(screen)[id])})
|
|
@@ -139,9 +213,8 @@ export function createController(store,runtime,options={}){
|
|
|
139
213
|
if(screen.page!=='delete')throw Error('请先选择要移除的服务器')
|
|
140
214
|
if(v.serverId!==screen.serverId||v.revision!==screen.revision)throw Error('确认目标已变化,请重新确认')
|
|
141
215
|
if(v.confirmed!==true)return settings(scope,screen.serverId)
|
|
142
|
-
const
|
|
143
|
-
await
|
|
144
|
-
reconcile();await dropUnused([...old.headers,...old.env].map(x=>x.credentialRef))
|
|
216
|
+
const {id}=find(screen.serverId)
|
|
217
|
+
await commit(revision(v,scope),next=>{next.servers=next.servers.filter(s=>s.id!==id)})
|
|
145
218
|
return {...navigate(scope,{page:'list'}),toast:'服务器已移除'}
|
|
146
219
|
},
|
|
147
220
|
saveServer:async(scope,event)=>{
|
|
@@ -159,17 +232,17 @@ export function createController(store,runtime,options={}){
|
|
|
159
232
|
merged.args=typeof merged.argsLines==='string'?merged.argsLines.split('\n').filter(x=>x.length):old?.args??[]
|
|
160
233
|
delete merged.argsLines
|
|
161
234
|
const server=normalizeServer(merged,old)
|
|
162
|
-
await
|
|
163
|
-
|
|
235
|
+
await commit(rev,next=>{if(old)next.servers[next.servers.findIndex(s=>s.id===id)]=server;else{if(next.servers.length>=32)throw Error('最多可添加 32 个服务器');next.servers.push(server)}})
|
|
236
|
+
return {...settings(scope,id),toast:'已保存基础设置'}
|
|
164
237
|
},
|
|
165
|
-
toggleServer:async(scope,event)=>{const v=args(event),s=find(v.serverId);await
|
|
238
|
+
toggleServer:async(scope,event)=>{const v=args(event),s=find(v.serverId);await commit(revision(v,scope),next=>{const server=next.servers.find(x=>x.id===s.id);server.enabled=!server.enabled});return settings(scope,s.id)},
|
|
166
239
|
saveTool:async(scope,event)=>{
|
|
167
240
|
const v=args(event),screen=screenOf(scope),input=formPayload(v)
|
|
168
241
|
if(screen.page!=='tool'||v.serverId&&v.serverId!==screen.serverId||v.toolName&&v.toolName!==screen.toolName)throw Error('工具目标已变化,请重新打开')
|
|
169
242
|
const s=find(screen.serverId)
|
|
170
243
|
if(!runtimeView(screen)[s.id]?.tools?.some(t=>t.name===screen.toolName))throw Error('工具列表已更新,请刷新')
|
|
171
|
-
await
|
|
172
|
-
|
|
244
|
+
await commit(revision(v,scope),next=>{next.servers.find(x=>x.id===s.id).tools[screen.toolName]={enabled:bool(input.enabled,true),requireApproval:bool(input.requireApproval,true)}})
|
|
245
|
+
return {...openTools(scope,s.id),toast:'工具设置已保存'}
|
|
173
246
|
},
|
|
174
247
|
connect:(scope,event)=>checkServer(scope,args(event).serverId,true),
|
|
175
248
|
testConnection:(scope,event)=>checkServer(scope,args(event).serverId),
|
|
@@ -190,10 +263,11 @@ export function createController(store,runtime,options={}){
|
|
|
190
263
|
const candidate=clear?{name,value:''}:value?{name,credentialRef:'MCP_PENDING'}:{...old,name}
|
|
191
264
|
const list=s[kind].slice();if(index===-1)list.push(candidate);else list[index]=candidate
|
|
192
265
|
pairs(list,kind)
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
266
|
+
await commit(rev,async(next,put)=>{
|
|
267
|
+
if(value)candidate.credentialRef=await put(value)
|
|
268
|
+
const list=next.servers.find(x=>x.id===s.id)[kind]
|
|
269
|
+
if(index===-1)list.push(candidate);else list[index]=candidate
|
|
270
|
+
})
|
|
197
271
|
return {...credentials(scope,s.id),toast:'已保存并更新连接'}
|
|
198
272
|
},
|
|
199
273
|
requestDeletePair:(scope,event)=>{const v=args(event),s=find(v.serverId),kind=v.kind==='env'?'env':'headers',index=integer(v.index,0,15,0);if(!s[kind][index])throw Error('配置项已删除');return navigate(scope,{page:'deletePair',serverId:s.id,kind,index,revision:store.snapshot().revision})},
|
|
@@ -202,10 +276,10 @@ export function createController(store,runtime,options={}){
|
|
|
202
276
|
if(screen.page!=='deletePair')throw Error('请先选择要删除的请求头')
|
|
203
277
|
if(v.serverId!==screen.serverId||v.kind!==screen.kind||v.index!==screen.index||v.revision!==screen.revision)throw Error('确认目标已变化,请重新确认')
|
|
204
278
|
if(v.confirmed!==true)return credentials(scope,screen.serverId)
|
|
205
|
-
|
|
206
|
-
await
|
|
207
|
-
|
|
279
|
+
find(screen.serverId)
|
|
280
|
+
await commit(revision(v,scope),next=>{next.servers.find(s=>s.id===screen.serverId)[screen.kind].splice(screen.index,1)})
|
|
281
|
+
return {...credentials(scope,screen.serverId),toast:'已删除并更新连接'}
|
|
208
282
|
}
|
|
209
283
|
}
|
|
210
|
-
return {notify,data,screens,actions:Object.fromEntries(Object.entries(actions).map(([id,fn])=>[id,guarded(fn)])),panel:{view:buildView,data:(scope,emit)=>{const k=key(scope),set=listeners.get(k)??new Set();set.add(emit);listeners.set(k,set);emit(wire(data(scope)));return ()=>{set.delete(emit);if(!set.size){listeners.delete(k);projections.delete(k)}}}},dispose:()=>{disposed=true;if(notifyTimer)clearTimeout(notifyTimer);listeners.clear();screens.clear();projections.clear();toolPositions.clear();listPositions.clear()}}
|
|
284
|
+
return {notify,data,screens,web,actions:Object.fromEntries(Object.entries(actions).map(([id,fn])=>[id,guarded(fn)])),panel:{view:buildView,data:(scope,emit)=>{const k=key(scope),set=listeners.get(k)??new Set();set.add(emit);listeners.set(k,set);emit(wire(data(scope)));return ()=>{set.delete(emit);if(!set.size){listeners.delete(k);projections.delete(k)}}}},dispose:()=>{disposed=true;if(notifyTimer)clearTimeout(notifyTimer);listeners.clear();screens.clear();projections.clear();toolPositions.clear();listPositions.clear()}}
|
|
211
285
|
}
|
package/lib/health.js
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// Optional background health checking for configured MCP servers.
|
|
2
|
+
// Runs in the plugin Host fiber, never spawns processes, and never writes to
|
|
3
|
+
// servers.json: its own side-car state lives in health.json (0600).
|
|
4
|
+
import {readFile, writeFile, mkdir} from 'node:fs/promises'
|
|
5
|
+
import {dirname, join} from 'node:path'
|
|
6
|
+
import {renameSync} from 'node:fs'
|
|
7
|
+
import {randomUUID} from 'node:crypto'
|
|
8
|
+
|
|
9
|
+
const LIMITS = {intervalMin: 1, intervalMax: 360, logMax: 50}
|
|
10
|
+
const DEFAULTS = {version: 1, enabled: false, intervalMinutes: 10, autoDisableAfterFaults: 0, log: [], perServer: {}}
|
|
11
|
+
|
|
12
|
+
function sanitize(input) {
|
|
13
|
+
const value = input && typeof input === 'object' && !Array.isArray(input) ? input : {}
|
|
14
|
+
const interval = Number(value.intervalMinutes)
|
|
15
|
+
return {
|
|
16
|
+
version: 1,
|
|
17
|
+
enabled: value.enabled === true,
|
|
18
|
+
intervalMinutes: Number.isFinite(interval) ? Math.min(LIMITS.intervalMax, Math.max(LIMITS.intervalMin, Math.round(interval))) : DEFAULTS.intervalMinutes,
|
|
19
|
+
autoDisableAfterFaults: Number.isFinite(value.autoDisableAfterFaults) && value.autoDisableAfterFaults > 0
|
|
20
|
+
? Math.min(10, Math.round(value.autoDisableAfterFaults)) : 0,
|
|
21
|
+
log: Array.isArray(value.log) ? value.log.filter(row => row && typeof row === 'object').slice(0, LIMITS.logMax) : [],
|
|
22
|
+
perServer: value.perServer && typeof value.perServer === 'object' && !Array.isArray(value.perServer) ? value.perServer : {},
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createHealthWatcher({dataDir, isActive, servers, project, connect, onDisable = () => {}, logger}) {
|
|
27
|
+
const path = join(dataDir, 'health.json')
|
|
28
|
+
let state = {...DEFAULTS, log: [], perServer: {}}
|
|
29
|
+
let timer = null, running = false, disposed = false
|
|
30
|
+
let loaded = readFile(path, 'utf8').then(
|
|
31
|
+
text => { state = sanitize(JSON.parse(text)) },
|
|
32
|
+
() => { /* Missing or unreadable side-car starts fresh. */ },
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
async function persist() {
|
|
36
|
+
try {
|
|
37
|
+
await mkdir(dirname(path), {recursive: true, mode: 0o700})
|
|
38
|
+
const tmp = `${path}.${randomUUID()}.tmp`
|
|
39
|
+
await writeFile(tmp, JSON.stringify(state, null, 2) + '\n', {mode: 0o600})
|
|
40
|
+
renameSync(tmp, path)
|
|
41
|
+
} catch (error) {
|
|
42
|
+
logger?.warn?.(`MCP health state not persisted: ${error?.code ?? 'unknown'}`)
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function record(serverId, kind, detail = {}) {
|
|
47
|
+
state.log.unshift({at: Date.now(), serverId, kind, ...detail})
|
|
48
|
+
state.log.length = Math.min(LIMITS.logMax, state.log.length)
|
|
49
|
+
const per = state.perServer[serverId] ?? {}
|
|
50
|
+
if (kind === 'fault') {
|
|
51
|
+
per.faults = (Number.isSafeInteger(per.faults) ? per.faults : 0) + 1
|
|
52
|
+
per.lastFaultAt = Date.now()
|
|
53
|
+
} else if (kind === 'recovered') {
|
|
54
|
+
per.faults = 0
|
|
55
|
+
per.lastOkAt = Date.now()
|
|
56
|
+
}
|
|
57
|
+
per.lastKind = kind
|
|
58
|
+
state.perServer[serverId] = per
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function tick() {
|
|
62
|
+
if (running || disposed) return
|
|
63
|
+
running = true
|
|
64
|
+
try {
|
|
65
|
+
if (!isActive() || !state.enabled) return
|
|
66
|
+
const list = servers().filter(server => server.enabled === true)
|
|
67
|
+
for (const server of list) {
|
|
68
|
+
if (disposed) break
|
|
69
|
+
const view = project({serverId: server.id, detail: 'summary'})[server.id]
|
|
70
|
+
const status = view?.status
|
|
71
|
+
const wasFaulted = state.perServer[server.id]?.lastKind === 'fault'
|
|
72
|
+
if (status === 'connected') {
|
|
73
|
+
if (wasFaulted) { record(server.id, 'recovered'); await persist() }
|
|
74
|
+
continue
|
|
75
|
+
}
|
|
76
|
+
if (status === 'connecting' || status === 'reconnecting') continue
|
|
77
|
+
record(server.id, 'fault', status === 'error' && view?.error?.code ? {code: view.error.code} : {code: status ?? 'disconnected'})
|
|
78
|
+
const faults = state.perServer[server.id]?.faults ?? 0
|
|
79
|
+
await persist()
|
|
80
|
+
if (state.autoDisableAfterFaults > 0 && faults >= state.autoDisableAfterFaults) {
|
|
81
|
+
// Persisted intent: the shared controller applies it through the CAS
|
|
82
|
+
// store on the next reconcile; no direct state mutation here.
|
|
83
|
+
record(server.id, 'auto-disabled', {faults})
|
|
84
|
+
await persist()
|
|
85
|
+
onDisable(server.id)
|
|
86
|
+
} else {
|
|
87
|
+
connect(server.id, true)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
} catch (error) {
|
|
91
|
+
logger?.warn?.(`MCP health tick failed: ${error?.code ?? 'unknown'}`)
|
|
92
|
+
} finally {
|
|
93
|
+
running = false
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function apply(next) {
|
|
98
|
+
state = {...state, ...sanitize({...state, ...next})}
|
|
99
|
+
if (timer) { clearInterval(timer); timer = null }
|
|
100
|
+
if (state.enabled && !disposed) {
|
|
101
|
+
timer = setInterval(() => { tick() }, state.intervalMinutes * 60000)
|
|
102
|
+
timer.unref?.()
|
|
103
|
+
}
|
|
104
|
+
await persist()
|
|
105
|
+
return status()
|
|
106
|
+
}
|
|
107
|
+
function status() {
|
|
108
|
+
return {enabled: state.enabled, intervalMinutes: state.intervalMinutes,
|
|
109
|
+
autoDisableAfterFaults: state.autoDisableAfterFaults,
|
|
110
|
+
log: state.log.slice(0, 20).map(row => ({...row})),
|
|
111
|
+
perServer: Object.fromEntries(Object.entries(state.perServer).map(([id, per]) => [id, {...per}])),
|
|
112
|
+
lastTickAt: state.log[0]?.at ?? null}
|
|
113
|
+
}
|
|
114
|
+
function dispose() {
|
|
115
|
+
disposed = true
|
|
116
|
+
if (timer) { clearInterval(timer); timer = null }
|
|
117
|
+
}
|
|
118
|
+
return {ready: () => loaded, apply, status, tick: () => loaded.then(() => tick()), dispose}
|
|
119
|
+
}
|
package/lib/index.js
CHANGED
|
@@ -2,14 +2,20 @@ import z from '@deepseek-ai/schemastery'
|
|
|
2
2
|
import { credentialRef } from '@deepseek-ai/dsh-credentials'
|
|
3
3
|
import { join } from 'node:path'
|
|
4
4
|
import { homedir } from 'node:os'
|
|
5
|
+
import { randomUUID } from 'node:crypto'
|
|
5
6
|
import { StateStore } from './store.js'
|
|
6
|
-
import { createRuntime } from './runtime.js'
|
|
7
|
+
import { createRuntime, publicToolName } from './runtime.js'
|
|
7
8
|
import { createController } from './controller.js'
|
|
8
9
|
import { createVault } from './credentials.js'
|
|
10
|
+
import { createHealthWatcher } from './health.js'
|
|
11
|
+
import { createStatsLedger } from './stats.js'
|
|
12
|
+
import { createRegistryClient } from './registry.js'
|
|
13
|
+
import { createToolTrust } from './tool-trust.js'
|
|
14
|
+
import { formatToolResult } from './tool-preview.js'
|
|
9
15
|
|
|
10
16
|
export const name='local-mcp-manager'
|
|
11
17
|
export const Config=z.object({
|
|
12
|
-
autoConnect:z.boolean().default(true).description('允许 MCP
|
|
18
|
+
autoConnect:z.boolean().default(true).description('允许 MCP 连接(总开关)。服务器、请求头和工具可在 MCP 管理面板中管理。'),
|
|
13
19
|
credentials:z.array(z.object({
|
|
14
20
|
ref:z.string().required(),
|
|
15
21
|
value:z.string().role('secret')
|
|
@@ -18,17 +24,166 @@ export const Config=z.object({
|
|
|
18
24
|
|
|
19
25
|
export async function apply(ctx,config={}) {
|
|
20
26
|
const root=process.env.DSH_HOME||join(homedir(),'.dsh')
|
|
21
|
-
const
|
|
27
|
+
const dataDir=join(root,'dsh-go','plugin-data',name)
|
|
28
|
+
const store=new StateStore(join(dataDir,'servers.json'))
|
|
22
29
|
await store.load()
|
|
23
30
|
let active,controller,closed=false,credentialContext=ctx
|
|
24
|
-
const
|
|
31
|
+
const autoConnect=()=>config.autoConnect!==false
|
|
32
|
+
const registrationStamps=new WeakMap()
|
|
33
|
+
const stamp=registration=>{
|
|
34
|
+
let value=registrationStamps.get(registration)
|
|
35
|
+
if(!value){value=randomUUID();registrationStamps.set(registration,value)}
|
|
36
|
+
return value
|
|
37
|
+
}
|
|
38
|
+
const liveCatalog=id=>{
|
|
39
|
+
const slot=active?.slots.get(id),generation=slot?.generation
|
|
40
|
+
return generation&&!generation.connecting&&!slot.view.refreshing&&active.live(generation)?generation:undefined
|
|
41
|
+
}
|
|
42
|
+
const runtime={
|
|
43
|
+
snapshot:()=>active?.snapshot()??{},project:options=>active?.project(options)??{},
|
|
44
|
+
reconcile:()=>active?.reconcile(),connect:id=>active?.connect(id),refresh:id=>active?.refresh(id),
|
|
45
|
+
hasDiscoveredTool(id,rawName){
|
|
46
|
+
// A retired generation's projection can outlive its registration while
|
|
47
|
+
// the runtime closes it. Only a live discovery may accept policy edits.
|
|
48
|
+
const item=active?.owned.get(publicToolName(id,rawName))
|
|
49
|
+
return !!(item&&item.rawName===rawName&&item.generation.slot.id===id
|
|
50
|
+
&&!item.generation.connecting&&active.live(item.generation))
|
|
51
|
+
},
|
|
52
|
+
discoveredToolNames(id){
|
|
53
|
+
const generation=liveCatalog(id)
|
|
54
|
+
return new Set(generation&&[...generation.registrations.values()].map(item=>item.rawName))
|
|
55
|
+
},
|
|
56
|
+
discoveredToolStamps(id){
|
|
57
|
+
const generation=liveCatalog(id)
|
|
58
|
+
return new Map(generation&&[...generation.registrations.values()].map(item=>[item.rawName,stamp(item)]))
|
|
59
|
+
},
|
|
60
|
+
toolAccess:(id,rawName)=>active?.toolAccess(id,rawName),
|
|
61
|
+
reviewTool:(id,rawName,check)=>active?.reviewTool(id,rawName,check),
|
|
62
|
+
currentToolStamp(id,rawName){
|
|
63
|
+
const current=liveCatalog(id)?.registrations.get(publicToolName(id,rawName))
|
|
64
|
+
return current?.rawName===rawName?stamp(current):undefined
|
|
65
|
+
},
|
|
66
|
+
aggregate(){
|
|
67
|
+
const instance=active
|
|
68
|
+
if(!instance)return {runtimeReady:false,generatedAt:Date.now(),configPath:store.path,servers:[],byTool:[],conflicts:[]}
|
|
69
|
+
const servers=store.snapshot().servers
|
|
70
|
+
const rows=[],toolCalls=new Map(),conflictIds=new Map()
|
|
71
|
+
for(const server of servers){
|
|
72
|
+
const slot=instance.slots.get(server.id)
|
|
73
|
+
const generation=liveCatalog(server.id)
|
|
74
|
+
const rawNames=generation?[...generation.registrations.values()].map(item=>item.rawName):[]
|
|
75
|
+
if(server.enabled){
|
|
76
|
+
for(const rawName of rawNames){
|
|
77
|
+
const ids=conflictIds.get(rawName)??new Set();ids.add(server.id);conflictIds.set(rawName,ids)
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
const history=slot?.history??[],stats=slot?.stats??{calls:0,failures:0,active:0}
|
|
81
|
+
for(const row of history){
|
|
82
|
+
const item=toolCalls.get(row.tool)??{tool:row.tool,calls:0,failures:0,lastAt:0,lastDurationMs:null}
|
|
83
|
+
item.calls++;if(!row.ok)item.failures++
|
|
84
|
+
if(row.at>item.lastAt){item.lastAt=row.at;item.lastDurationMs=row.durationMs??null}
|
|
85
|
+
toolCalls.set(row.tool,item)
|
|
86
|
+
}
|
|
87
|
+
rows.push({id:server.id,calls:Number(stats.calls)||0,failures:Number(stats.failures)||0,
|
|
88
|
+
active:Number(stats.active)||0,tools:rawNames.length})
|
|
89
|
+
}
|
|
90
|
+
return {runtimeReady:true,generatedAt:Date.now(),configPath:store.path,
|
|
91
|
+
servers:rows,
|
|
92
|
+
byTool:[...toolCalls.values()].sort((a,b)=>b.calls-a.calls||b.lastAt-a.lastAt).slice(0,24),
|
|
93
|
+
conflicts:[...conflictIds].filter(([,ids])=>ids.size>1).map(([tool,ids])=>({tool,servers:[...ids]})).slice(0,16)}
|
|
94
|
+
},
|
|
95
|
+
async invokeTool(id,rawName,args,timeoutMs){
|
|
96
|
+
const instance=active
|
|
97
|
+
if(!instance)throw Error('运行时未就绪,请稍后再试')
|
|
98
|
+
const name=publicToolName(id,rawName)
|
|
99
|
+
const item=instance.owned.get(name)
|
|
100
|
+
if(!(item&&item.rawName===rawName&&item.generation.slot.id===id
|
|
101
|
+
&&!item.generation.connecting&&instance.live(item.generation))){
|
|
102
|
+
throw Error('工具当前不可调用:服务器未连接或工具目录已更新')
|
|
103
|
+
}
|
|
104
|
+
const registration=item.generation.registrations.get(name)
|
|
105
|
+
const execute=registration?.definition?.execute
|
|
106
|
+
if(typeof execute!=='function')throw Error('工具当前不可调用:注册已失效,请刷新工具列表')
|
|
107
|
+
const timeout=Math.min(180000,Math.max(1000,Number(timeoutMs)||60000))
|
|
108
|
+
const started=Date.now()
|
|
109
|
+
const clip=(text,max=8000)=>typeof text==='string'&&text.length>max?{text:text.slice(0,max),truncated:true}:{text:text??'',truncated:false}
|
|
110
|
+
try{
|
|
111
|
+
const result=await execute(args??{},{signal:AbortSignal.timeout(timeout)})
|
|
112
|
+
const body=formatToolResult(result,value=>instance.safe(value))
|
|
113
|
+
return {durationMs:Date.now()-started,isError:false,...body}
|
|
114
|
+
}catch(error){
|
|
115
|
+
const body=clip(typeof error?.message==='string'?error.message:'调用失败')
|
|
116
|
+
return {durationMs:Date.now()-started,isError:true,code:error?.code??error?.name??'tool-failed',...body}
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
readResource(id,uri){
|
|
120
|
+
const instance=active
|
|
121
|
+
if(!instance)throw Object.assign(new Error('该服务器未提供此能力或当前未连接。'),{code:'unsupported'})
|
|
122
|
+
return instance.readResource(id,uri)
|
|
123
|
+
},
|
|
124
|
+
resourceWatches(id){return active?.resourceWatches(id)??{supported:false,rows:[]}},
|
|
125
|
+
setResourceWatch:(id,uri,enabled)=>active?.setResourceWatch(id,uri,enabled),
|
|
126
|
+
getPrompt(id,name,args){
|
|
127
|
+
const instance=active
|
|
128
|
+
if(!instance)throw Object.assign(new Error('该服务器未提供此能力或当前未连接。'),{code:'unsupported'})
|
|
129
|
+
return instance.getPrompt(id,name,args)
|
|
130
|
+
},
|
|
131
|
+
async setLogLevel(id,level){
|
|
132
|
+
const instance=active
|
|
133
|
+
if(!instance)throw Object.assign(new Error('该服务器未提供此能力或当前未连接。'),{code:'unsupported'})
|
|
134
|
+
return instance.setLogLevel(id,level)
|
|
135
|
+
},
|
|
136
|
+
logTail(id){return active?.logTail(id)??{level:null,lines:[]}},
|
|
137
|
+
}
|
|
25
138
|
const resolveSecret=async(ref,source=credentialContext)=>{
|
|
26
139
|
const entry=(config.credentials??[]).find(x=>x.ref===ref)
|
|
27
140
|
if(typeof entry?.value==='string'&&entry.value)return entry.value
|
|
28
141
|
const service=source.get('credentials')
|
|
29
142
|
return service?(await service.resolve(credentialRef(ref)))?.value:undefined
|
|
30
143
|
}
|
|
31
|
-
|
|
144
|
+
const getCredentials=()=>credentialContext.get('credentials')
|
|
145
|
+
// Persistent call ledger for the workbench trend views (side-car stats.json).
|
|
146
|
+
const stats=createStatsLedger({dataDir,logger:ctx.logger})
|
|
147
|
+
const toolTrust=createToolTrust({dataDir,logger:ctx.logger})
|
|
148
|
+
const registry=createRegistryClient({logger:ctx.logger})
|
|
149
|
+
// Optional background health watching. Off until the workbench turns it on;
|
|
150
|
+
// side-car state only, servers.json is never touched from here.
|
|
151
|
+
const health=createHealthWatcher({
|
|
152
|
+
dataDir,
|
|
153
|
+
isActive:()=>!!active&&!closed,
|
|
154
|
+
servers:()=>store.snapshot().servers,
|
|
155
|
+
project:spec=>active?.project(spec)??{},
|
|
156
|
+
connect:id=>{try{active?.connect(id)}catch{/* scheduled reconnects tolerate runtime churn */}},
|
|
157
|
+
onDisable:id=>{
|
|
158
|
+
store.update(store.snapshot().revision,state=>{
|
|
159
|
+
const server=state.servers.find(s=>s.id===id)
|
|
160
|
+
if(server)server.enabled=false
|
|
161
|
+
}).then(()=>controller.notify()).catch(()=>{/* the next tick re-flags the fault */})
|
|
162
|
+
},
|
|
163
|
+
logger:ctx.logger,
|
|
164
|
+
})
|
|
165
|
+
ctx.on('dispose',()=>{health.dispose();stats.dispose()})
|
|
166
|
+
controller=createController(store,runtime,{
|
|
167
|
+
vault:createVault(getCredentials),isVaultReady:()=>typeof getCredentials()?.set==='function',
|
|
168
|
+
autoConnect,isActive:()=>!!active&&!closed,
|
|
169
|
+
resolveSecret:ref=>resolveSecret(ref),
|
|
170
|
+
health,
|
|
171
|
+
stats,
|
|
172
|
+
registry,
|
|
173
|
+
})
|
|
174
|
+
ctx.provide?.('mcpManager',controller.web)
|
|
175
|
+
// The Web wire seat is optional. The existing native panel and data lifecycle
|
|
176
|
+
// never depend on a Web client, a Typert service, or a second installed package.
|
|
177
|
+
ctx.inject(['typert'],async child=>{
|
|
178
|
+
let disposed=false
|
|
179
|
+
child.on('dispose',()=>{disposed=true})
|
|
180
|
+
try {
|
|
181
|
+
const {mountWorkbench}=await import('./workbench-host.js')
|
|
182
|
+
if(!closed&&!disposed)await mountWorkbench(child,controller.web)
|
|
183
|
+
} catch {
|
|
184
|
+
if(!disposed)child.logger?.warn?.('MCP workbench: Host RPC registration unavailable')
|
|
185
|
+
}
|
|
186
|
+
})
|
|
32
187
|
// A credentials provider may initialize after tools. Do not attempt authenticated
|
|
33
188
|
// MCP connections until both services exist; otherwise one early miss is marked
|
|
34
189
|
// blocked and will not be retried by the ordinary list refresh.
|
|
@@ -40,8 +195,8 @@ export async function apply(ctx,config={}) {
|
|
|
40
195
|
}
|
|
41
196
|
credentialContext=child
|
|
42
197
|
const instance=createRuntime(child,{
|
|
43
|
-
getState:()=>{const state=store.snapshot();if(
|
|
44
|
-
resolveSecret:ref=>resolveSecret(ref,child),onInvalidate:()=>controller.notify()
|
|
198
|
+
getState:()=>{const state=store.snapshot();if(!autoConnect())state.servers=state.servers.map(s=>({...s,enabled:false}));return state},
|
|
199
|
+
toolTrust,resolveSecret:ref=>resolveSecret(ref,child),onInvalidate:()=>controller.notify(),onCall:event=>stats.record(event)
|
|
45
200
|
})
|
|
46
201
|
active=instance
|
|
47
202
|
instance.reconcile().catch(()=>child.logger?.warn?.('MCP startup reconciliation failed'))
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Workbench clients can be on a different OS than the DSH host. Validate the
|
|
2
|
+
// portable syntax here, then check the host's own format before any spawn.
|
|
3
|
+
export function isWindowsAbsoluteCwd(path) {
|
|
4
|
+
return /^[A-Za-z]:[\\/]/.test(path)
|
|
5
|
+
|| /^(?:\\\\|\/\/)[^\\/]+[\\/][^\\/]+(?:[\\/]|$)/.test(path)
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export function isPortableAbsoluteCwd(path) {
|
|
9
|
+
return path.startsWith('/') || isWindowsAbsoluteCwd(path)
|
|
10
|
+
}
|