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
package/lib/stats.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
// Persistent tool-call ledger for fleet-wide trends. Side-car stats.json
|
|
2
|
+
// (0600, atomic replace), sibling of health.json; servers.json stays untouched.
|
|
3
|
+
// Privacy: entries carry tool name, timing and status category only — never
|
|
4
|
+
// arguments or result bodies, mirroring the in-memory activity views.
|
|
5
|
+
import {readFile, writeFile, mkdir} from 'node:fs/promises'
|
|
6
|
+
import {dirname, join} from 'node:path'
|
|
7
|
+
import {renameSync} from 'node:fs'
|
|
8
|
+
import {randomUUID} from 'node:crypto'
|
|
9
|
+
|
|
10
|
+
const LIMITS = {rawMax: 2000, daysMax: 30, toolsPerDay: 48, flushMs: 4000, topMax: 12, slowMax: 8, beatServers: 32, beatsPerServer: 12}
|
|
11
|
+
|
|
12
|
+
function dayKey(at) {
|
|
13
|
+
const day = new Date(at)
|
|
14
|
+
return `${day.getFullYear()}-${String(day.getMonth() + 1).padStart(2, '0')}-${String(day.getDate()).padStart(2, '0')}`
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function count(value) { return Number.isSafeInteger(value) && value >= 0 ? value : 0 }
|
|
18
|
+
|
|
19
|
+
function isEvent(event) {
|
|
20
|
+
return event && typeof event === 'object'
|
|
21
|
+
&& typeof event.serverId === 'string' && event.serverId.length > 0 && event.serverId.length <= 64
|
|
22
|
+
&& typeof event.tool === 'string' && event.tool.length > 0 && event.tool.length <= 256
|
|
23
|
+
&& Number.isFinite(event.at) && event.at >= 0 && Number.isFinite(event.durationMs) && event.durationMs >= 0
|
|
24
|
+
&& (event.ok === true || (event.ok === false && typeof event.code === 'string' && event.code.length > 0))
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function sanitizeDay(day) {
|
|
28
|
+
const tools = {}
|
|
29
|
+
const source = day?.tools && typeof day.tools === 'object' && !Array.isArray(day.tools) ? day.tools : {}
|
|
30
|
+
for (const [tool, stat] of Object.entries(source).slice(0, LIMITS.toolsPerDay)) {
|
|
31
|
+
if (typeof tool !== 'string' || !tool || tool.length > 256 || !stat || typeof stat !== 'object' || Array.isArray(stat)) continue
|
|
32
|
+
tools[tool] = {calls: count(stat.calls), failures: count(stat.failures), durationMs: count(stat.durationMs), maxMs: count(stat.maxMs)}
|
|
33
|
+
}
|
|
34
|
+
return {calls: count(day?.calls), failures: count(day?.failures), durationMs: count(day?.durationMs), tools}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function sanitizeState(value) {
|
|
38
|
+
const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {}
|
|
39
|
+
const days = {}
|
|
40
|
+
const keys = source.days && typeof source.days === 'object' && !Array.isArray(source.days)
|
|
41
|
+
? Object.keys(source.days).filter(key => /^\d{4}-\d{2}-\d{2}$/.test(key)).sort().reverse().slice(0, LIMITS.daysMax) : []
|
|
42
|
+
for (const key of keys) days[key] = sanitizeDay(source.days[key])
|
|
43
|
+
const raw = Array.isArray(source.raw) ? source.raw.filter(isEvent).slice(0, LIMITS.rawMax) : []
|
|
44
|
+
return {version: 1, days, raw}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createStatsLedger({dataDir, logger, flushMs = LIMITS.flushMs} = {}) {
|
|
48
|
+
if (typeof dataDir !== 'string' || !dataDir) throw new Error('stats: dataDir required')
|
|
49
|
+
const path = join(dataDir, 'stats.json')
|
|
50
|
+
let state = {version: 1, days: {}, raw: []}
|
|
51
|
+
let ready = false, disposed = false, pending = false, timer = null
|
|
52
|
+
const queue = []
|
|
53
|
+
const loaded = readFile(path, 'utf8').then(
|
|
54
|
+
text => { state = sanitizeState(JSON.parse(text)); drain() },
|
|
55
|
+
() => { drain() },
|
|
56
|
+
)
|
|
57
|
+
function drain() {
|
|
58
|
+
ready = true
|
|
59
|
+
for (const event of queue.splice(0, LIMITS.rawMax)) apply(event)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function flush() {
|
|
63
|
+
if (!pending) return
|
|
64
|
+
pending = false
|
|
65
|
+
const keys = Object.keys(state.days).sort().reverse()
|
|
66
|
+
for (const key of keys.slice(LIMITS.daysMax)) delete state.days[key]
|
|
67
|
+
if (state.raw.length > LIMITS.rawMax) state.raw.length = LIMITS.rawMax
|
|
68
|
+
try {
|
|
69
|
+
await mkdir(dirname(path), {recursive: true, mode: 0o700})
|
|
70
|
+
const tmp = `${path}.${randomUUID()}.tmp`
|
|
71
|
+
await writeFile(tmp, JSON.stringify(state) + '\n', {mode: 0o600})
|
|
72
|
+
renameSync(tmp, path)
|
|
73
|
+
} catch (error) {
|
|
74
|
+
logger?.warn?.(`MCP stats not persisted: ${error?.code ?? 'unknown'}`)
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function schedule() {
|
|
78
|
+
pending = true
|
|
79
|
+
if (timer || disposed) return
|
|
80
|
+
timer = setTimeout(() => { timer = null; void flush() }, flushMs)
|
|
81
|
+
timer.unref?.()
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function apply(event) {
|
|
85
|
+
const at = Math.round(event.at), durationMs = Math.round(event.durationMs)
|
|
86
|
+
const ok = event.ok === true
|
|
87
|
+
state.raw.unshift({serverId: event.serverId, tool: event.tool, at, durationMs, ok, ...(ok ? {} : {code: String(event.code).slice(0, 64)})})
|
|
88
|
+
if (state.raw.length > LIMITS.rawMax) state.raw.length = LIMITS.rawMax
|
|
89
|
+
const day = state.days[dayKey(at)] ??= {calls: 0, failures: 0, durationMs: 0, maxMs: 0, tools: {}}
|
|
90
|
+
day.calls++; if (!ok) day.failures++
|
|
91
|
+
day.durationMs += durationMs; day.maxMs = Math.max(day.maxMs, durationMs)
|
|
92
|
+
const tool = day.tools[event.tool] ??= {calls: 0, failures: 0, durationMs: 0, maxMs: 0}
|
|
93
|
+
tool.calls++; if (!ok) tool.failures++
|
|
94
|
+
tool.durationMs += durationMs; tool.maxMs = Math.max(tool.maxMs, durationMs)
|
|
95
|
+
schedule()
|
|
96
|
+
}
|
|
97
|
+
function record(event) {
|
|
98
|
+
if (disposed) return
|
|
99
|
+
if (!isEvent(event)) return
|
|
100
|
+
if (!ready) { queue.push(event); return }
|
|
101
|
+
apply(event)
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function overview({days = 14} = {}) {
|
|
105
|
+
const range = Math.min(LIMITS.daysMax, Math.max(1, Math.round(days) || 14))
|
|
106
|
+
const keys = Object.keys(state.days).sort().reverse().slice(0, range).sort()
|
|
107
|
+
const series = keys.map(key => ({date: key, calls: state.days[key].calls, failures: state.days[key].failures}))
|
|
108
|
+
const totals = series.reduce((acc, row) => ({calls: acc.calls + row.calls, failures: acc.failures + row.failures}), {calls: 0, failures: 0})
|
|
109
|
+
const start = keys.length ? new Date(`${keys[0]}T00:00:00`).getTime() : Infinity
|
|
110
|
+
const tools = new Map()
|
|
111
|
+
for (const key of keys) for (const [tool, stat] of Object.entries(state.days[key].tools)) {
|
|
112
|
+
const sum = tools.get(tool) ?? {tool, calls: 0, failures: 0, durationMs: 0, maxMs: 0}
|
|
113
|
+
sum.calls += stat.calls; sum.failures += stat.failures; sum.durationMs += stat.durationMs
|
|
114
|
+
sum.maxMs = Math.max(sum.maxMs, stat.maxMs)
|
|
115
|
+
tools.set(tool, sum)
|
|
116
|
+
}
|
|
117
|
+
const top = [...tools.values()].sort((a, b) => b.calls - a.calls).slice(0, LIMITS.topMax)
|
|
118
|
+
.map(row => ({...row, avgMs: row.calls ? Math.round(row.durationMs / row.calls) : 0}))
|
|
119
|
+
const slow = state.raw.filter(row => row.at >= start)
|
|
120
|
+
.slice().sort((a, b) => b.durationMs - a.durationMs).slice(0, LIMITS.slowMax)
|
|
121
|
+
.map(row => ({tool: row.tool, serverId: row.serverId, at: row.at, durationMs: row.durationMs, ok: row.ok}))
|
|
122
|
+
// Heartbeat material for the workbench list: the newest few outcomes per
|
|
123
|
+
// server, oldest first. Raw entries only carry time and result, so nothing
|
|
124
|
+
// new leaves the ledger through this view.
|
|
125
|
+
const beats = new Map()
|
|
126
|
+
for (const row of state.raw) {
|
|
127
|
+
const list = beats.get(row.serverId)
|
|
128
|
+
if (list) { if (list.length < LIMITS.beatsPerServer) list.push({at: row.at, ok: row.ok}) }
|
|
129
|
+
else if (beats.size < LIMITS.beatServers) beats.set(row.serverId, [{at: row.at, ok: row.ok}])
|
|
130
|
+
}
|
|
131
|
+
const servers = [...beats].map(([id, recent]) => ({id, recent: recent.reverse()}))
|
|
132
|
+
return {days: series, totals: {...totals, durationMs: series.reduce((sum, row) => sum + state.days[row.date].durationMs, 0)},
|
|
133
|
+
failureRate: totals.calls ? Math.round(totals.failures / totals.calls * 1000) / 1000 : 0, top, slow, servers}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function dispose() {
|
|
137
|
+
disposed = true
|
|
138
|
+
if (timer) { clearTimeout(timer); timer = null }
|
|
139
|
+
try { await loaded } catch { /* Drain queued events regardless of load outcome. */ }
|
|
140
|
+
for (const event of queue.splice(0, LIMITS.rawMax)) apply(event)
|
|
141
|
+
await flush()
|
|
142
|
+
}
|
|
143
|
+
return {record, overview, dispose, loaded, path}
|
|
144
|
+
}
|
package/lib/store.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
-
import { readFile, mkdir,
|
|
1
|
+
import { readFile, mkdir, open, rm } from 'node:fs/promises'
|
|
2
|
+
import { renameSync } from 'node:fs'
|
|
2
3
|
import { dirname } from 'node:path'
|
|
3
4
|
import { randomUUID } from 'node:crypto'
|
|
5
|
+
import { isPortableAbsoluteCwd } from './path-format.js'
|
|
4
6
|
|
|
5
7
|
const BAD = new Set(['__proto__', 'constructor', 'prototype'])
|
|
6
8
|
export function record(x) { return x !== null && typeof x === 'object' && !Array.isArray(x) }
|
|
@@ -45,7 +47,7 @@ export function normalizeServer(input, previous) {
|
|
|
45
47
|
args = parseList(input.argsText ?? input.args)
|
|
46
48
|
if (args.length > 64 || args.some(x => typeof x !== 'string' || x.length > 2000 || x.includes('\0'))) throw Error('程序参数格式不正确')
|
|
47
49
|
cwd = text(input.cwd ?? '', 1000)
|
|
48
|
-
if (cwd && !cwd
|
|
50
|
+
if (cwd && !isPortableAbsoluteCwd(cwd)) throw Error('工作目录须为绝对路径')
|
|
49
51
|
} else {
|
|
50
52
|
url = text(input.url ?? '', 2000)
|
|
51
53
|
let parsed; try { parsed = new URL(url) } catch { throw Error('请输入完整的服务器 URL') }
|
|
@@ -54,23 +56,33 @@ export function normalizeServer(input, previous) {
|
|
|
54
56
|
}
|
|
55
57
|
const headers = pairs(input.headersText ?? input.headers, 'headers')
|
|
56
58
|
const env = pairs(input.envText ?? input.env, 'env')
|
|
57
|
-
|
|
59
|
+
const tagsIn = input.tags !== undefined ? parseList(input.tags) : previous?.tags
|
|
60
|
+
const tags = []
|
|
61
|
+
for (const tag of Array.isArray(tagsIn) ? tagsIn.slice(0, 8) : []) {
|
|
62
|
+
const value = text(tag, 24)
|
|
63
|
+
if (!tags.some(x => x.toLowerCase() === value.toLowerCase())) tags.push(value)
|
|
64
|
+
}
|
|
65
|
+
return { id,name,transport,url,command,args,cwd,headers,env,tags,
|
|
58
66
|
enabled: bool(input.enabled, previous?.enabled ?? false),
|
|
59
67
|
requireApproval: bool(input.requireApproval, previous?.requireApproval ?? true),
|
|
60
68
|
timeoutMs: integer(input.timeoutMs,1000,180000,60000),
|
|
61
69
|
tools: structuredClone(previous?.tools ?? {}) }
|
|
62
70
|
}
|
|
71
|
+
export function normalizeServerEntry(input) {
|
|
72
|
+
const server = normalizeServer(input)
|
|
73
|
+
if (input.tools !== undefined && !record(input.tools)) throw Error('工具设置不正确')
|
|
74
|
+
for (const [name,policy] of Object.entries(input.tools ?? {})) {
|
|
75
|
+
if (!name || name.length > 256 || BAD.has(name) || !record(policy)) throw Error('工具设置不正确')
|
|
76
|
+
server.tools[name] = {enabled:bool(policy.enabled,true),requireApproval:bool(policy.requireApproval,server.requireApproval)}
|
|
77
|
+
}
|
|
78
|
+
return server
|
|
79
|
+
}
|
|
63
80
|
export function normalizeState(input) {
|
|
64
81
|
if (!record(input) || input.version !== 1 || !Array.isArray(input.servers) || input.servers.length > 32) throw Error('MCP 配置文件格式不正确')
|
|
65
82
|
const ids = new Set()
|
|
66
83
|
const servers = input.servers.map(s => {
|
|
67
|
-
const server =
|
|
84
|
+
const server = normalizeServerEntry(s)
|
|
68
85
|
if (ids.has(server.id)) throw Error('服务器 ID 重复'); ids.add(server.id)
|
|
69
|
-
if (s.tools !== undefined && !record(s.tools)) throw Error('工具设置不正确')
|
|
70
|
-
for (const [name,policy] of Object.entries(s.tools ?? {})) {
|
|
71
|
-
if (!name || name.length > 256 || BAD.has(name) || !record(policy)) throw Error('工具设置不正确')
|
|
72
|
-
server.tools[name] = {enabled:bool(policy.enabled,true),requireApproval:bool(policy.requireApproval,server.requireApproval)}
|
|
73
|
-
}
|
|
74
86
|
return server
|
|
75
87
|
})
|
|
76
88
|
return {version:1,revision:integer(input.revision,0,Number.MAX_SAFE_INTEGER,0),servers}
|
|
@@ -83,17 +95,28 @@ export class StateStore {
|
|
|
83
95
|
return this.snapshot()
|
|
84
96
|
}
|
|
85
97
|
snapshot() { return structuredClone(this.value) }
|
|
86
|
-
async update(revision, mutate) {
|
|
98
|
+
async update(revision, mutate, beforeCommit) {
|
|
87
99
|
const run = this.queue.then(async()=>{
|
|
88
100
|
if (revision !== this.value.revision) throw Error('配置已更新,请刷新后重试')
|
|
89
|
-
const next
|
|
90
|
-
const checked
|
|
101
|
+
const next=this.snapshot(); await mutate(next); next.revision++
|
|
102
|
+
const checked=normalizeState(next)
|
|
91
103
|
await mkdir(dirname(this.path),{recursive:true,mode:0o700})
|
|
92
104
|
const tmp=this.path+'.'+randomUUID()+'.tmp'
|
|
93
|
-
await
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
105
|
+
const fd=await open(tmp,'wx',0o600)
|
|
106
|
+
let committed=false
|
|
107
|
+
try {
|
|
108
|
+
try { await fd.writeFile(JSON.stringify(checked,null,2)+'\n'); await fd.chmod(0o600) }
|
|
109
|
+
finally { await fd.close() }
|
|
110
|
+
// A changing runtime precondition is synchronous and observes the last
|
|
111
|
+
// possible instant before the same-directory rename. Do not yield here.
|
|
112
|
+
beforeCommit?.()
|
|
113
|
+
renameSync(tmp,this.path)
|
|
114
|
+
committed=true
|
|
115
|
+
this.value=checked
|
|
116
|
+
return this.snapshot()
|
|
117
|
+
} finally {
|
|
118
|
+
if(!committed)await rm(tmp,{force:true}).catch(()=>{})
|
|
119
|
+
}
|
|
97
120
|
})
|
|
98
121
|
this.queue=run.catch(()=>{}); return run
|
|
99
122
|
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Produce a workbench-sized, display-only JSON preview. Redact strings and
|
|
2
|
+
// keys before emitting them; never serialize the complete upstream payload.
|
|
3
|
+
export function formatToolResult(result, redact, limit = 8000) {
|
|
4
|
+
let text = '', truncated = false
|
|
5
|
+
const append = part => {
|
|
6
|
+
const room = Math.max(0, limit - text.length)
|
|
7
|
+
if (part.length <= room) { text += part; return true }
|
|
8
|
+
const tail = part.charCodeAt(room - 1)
|
|
9
|
+
if (room) text += part.slice(0, tail >= 0xd800 && tail <= 0xdbff ? room - 1 : room)
|
|
10
|
+
truncated = true
|
|
11
|
+
return false
|
|
12
|
+
}
|
|
13
|
+
const emit = (value, depth) => {
|
|
14
|
+
if (depth > 24) { truncated = true; return false }
|
|
15
|
+
if (typeof value === 'string') return append(JSON.stringify(redact(value)))
|
|
16
|
+
if (value === null || typeof value !== 'object') return append(JSON.stringify(value) ?? 'null')
|
|
17
|
+
const array = Array.isArray(value), entries = array ? value.entries() : Object.entries(value)
|
|
18
|
+
if (!append(array ? '[' : '{')) return false
|
|
19
|
+
let first = true
|
|
20
|
+
for (const [key, item] of entries) {
|
|
21
|
+
if (!append((first ? '\n' : ',\n') + ' '.repeat(depth + 1))) return false
|
|
22
|
+
if (!array && !append(JSON.stringify(redact(key)) + ': ')) return false
|
|
23
|
+
if (!emit(item, depth + 1)) return false
|
|
24
|
+
first = false
|
|
25
|
+
}
|
|
26
|
+
return append((first ? '' : '\n' + ' '.repeat(depth)) + (array ? ']' : '}'))
|
|
27
|
+
}
|
|
28
|
+
if (result?.structuredContent && typeof result.structuredContent === 'object') {
|
|
29
|
+
emit(result.structuredContent, 0)
|
|
30
|
+
return {text, truncated, structured: true}
|
|
31
|
+
}
|
|
32
|
+
for (const block of Array.isArray(result?.content) ? result.content : []) {
|
|
33
|
+
if (typeof block?.text !== 'string') continue
|
|
34
|
+
const body = redact(block.text).trim()
|
|
35
|
+
if (!body) continue
|
|
36
|
+
if (text && !append('\n')) break
|
|
37
|
+
if (!append(body)) break
|
|
38
|
+
}
|
|
39
|
+
return {text, truncated}
|
|
40
|
+
}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { renameSync } from 'node:fs'
|
|
3
|
+
import { mkdir, open, rm } from 'node:fs/promises'
|
|
4
|
+
import { join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
const digest = value => createHash('sha256').update(value).digest('hex')
|
|
7
|
+
const isDigest = value => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)
|
|
8
|
+
const MAX_TARGETS = 64, MAX_TOOLS = 1000, MAX_BYTES = 10 * 1024 * 1024
|
|
9
|
+
const ordered = (_key, value) => value && typeof value === 'object' && !Array.isArray(value)
|
|
10
|
+
? Object.fromEntries(Object.keys(value).sort().map(key => [key, value[key]])) : value
|
|
11
|
+
|
|
12
|
+
export function toolFingerprint(tool) {
|
|
13
|
+
return digest(JSON.stringify([tool.name, tool.description ?? '', tool.inputSchema,
|
|
14
|
+
tool.outputSchema, tool.annotations, tool.execution?.taskSupport], ordered))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function toolIdentity(rawName) { return digest(rawName) }
|
|
18
|
+
|
|
19
|
+
export function toolTarget(server) {
|
|
20
|
+
// A token rotation or timeout change is not a new trust decision. A new
|
|
21
|
+
// endpoint or launch program is; the server namespace is always part of it.
|
|
22
|
+
const address = server.transport === 'stdio' ? [server.command, server.args ?? [], server.cwd || ''] : [new URL(server.url).href]
|
|
23
|
+
return digest(JSON.stringify([server.id, server.transport, address]))
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function toolHint(annotations) {
|
|
27
|
+
if (annotations?.destructiveHint === true) return 'destructive'
|
|
28
|
+
if (annotations?.readOnlyHint === true) return 'read-only'
|
|
29
|
+
return undefined
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function load(path) {
|
|
33
|
+
let fd
|
|
34
|
+
try { fd = await open(path, 'r') }
|
|
35
|
+
catch (error) { if (error.code === 'ENOENT') return new Map(); throw error }
|
|
36
|
+
try {
|
|
37
|
+
if ((await fd.stat()).size > MAX_BYTES) throw Error('Tool review ledger too large.')
|
|
38
|
+
const file = JSON.parse(await fd.readFile('utf8'))
|
|
39
|
+
if (file?.version !== 1 || !Array.isArray(file.targets) || file.targets.length > MAX_TARGETS) throw Error('Invalid review ledger.')
|
|
40
|
+
const rows = new Map()
|
|
41
|
+
for (const row of file.targets) {
|
|
42
|
+
if (!Array.isArray(row) || !isDigest(row[0]) || rows.has(row[0]) || !Array.isArray(row[1]) || row[1].length > MAX_TOOLS) throw Error('Invalid target.')
|
|
43
|
+
const tools = new Map()
|
|
44
|
+
for (const pair of row[1]) {
|
|
45
|
+
if (!Array.isArray(pair) || !isDigest(pair[0]) || !isDigest(pair[1]) || tools.has(pair[0])) throw Error('Invalid digest.')
|
|
46
|
+
tools.set(pair[0], pair[1])
|
|
47
|
+
}
|
|
48
|
+
rows.set(row[0], tools)
|
|
49
|
+
}
|
|
50
|
+
return rows
|
|
51
|
+
} finally { await fd.close() }
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// This ledger holds hashes only. First discovery establishes the baseline;
|
|
55
|
+
// a later definition cannot overwrite it without a current, explicit review.
|
|
56
|
+
export function createToolTrust({dataDir, logger} = {}) {
|
|
57
|
+
const path = dataDir ? join(dataDir, 'tool-trust.json') : null
|
|
58
|
+
let rows = new Map(), queue = Promise.resolve(), damaged = false, warned = false
|
|
59
|
+
const warn = () => {
|
|
60
|
+
if (!warned) logger?.warn?.('MCP tool trust ledger unavailable; new definitions need review.')
|
|
61
|
+
warned = true
|
|
62
|
+
}
|
|
63
|
+
const loaded = path ? load(path).then(value => { rows = value }, () => { damaged = true; warn() }) : Promise.resolve()
|
|
64
|
+
const enqueue = operation => {
|
|
65
|
+
const task = queue.then(async () => { await loaded; return operation() })
|
|
66
|
+
queue = task.catch(() => {})
|
|
67
|
+
return task
|
|
68
|
+
}
|
|
69
|
+
const save = async (target, tools, check) => {
|
|
70
|
+
const next = new Map(rows).set(target, tools)
|
|
71
|
+
if (!path) { check?.(); rows = next; return }
|
|
72
|
+
await mkdir(dataDir, {recursive: true, mode: 0o700})
|
|
73
|
+
const file = `${path}.${randomUUID()}.tmp`
|
|
74
|
+
const entries = [...next].map(([key, inner]) => [key, [...inner]])
|
|
75
|
+
let moved = false
|
|
76
|
+
try {
|
|
77
|
+
const fd = await open(file, 'wx', 0o600)
|
|
78
|
+
try { await fd.writeFile(JSON.stringify({version: 1, targets: entries}) + '\n') }
|
|
79
|
+
finally { await fd.close() }
|
|
80
|
+
check?.()
|
|
81
|
+
renameSync(file, path)
|
|
82
|
+
rows = next
|
|
83
|
+
moved = true
|
|
84
|
+
} finally { if (!moved) await rm(file, {force: true}).catch(() => {}) }
|
|
85
|
+
}
|
|
86
|
+
return Object.freeze({
|
|
87
|
+
isAccepted: (target, name, signature) => rows.get(target)?.get(name) === signature,
|
|
88
|
+
observe(target, definitions, assertCurrent) {
|
|
89
|
+
return enqueue(async () => {
|
|
90
|
+
if (damaged || rows.has(target) || rows.size >= MAX_TARGETS) return
|
|
91
|
+
try { await save(target, new Map(definitions), assertCurrent) }
|
|
92
|
+
catch { warn() }
|
|
93
|
+
})
|
|
94
|
+
},
|
|
95
|
+
accept(target, name, signature, assertCurrent) {
|
|
96
|
+
return enqueue(async () => {
|
|
97
|
+
assertCurrent()
|
|
98
|
+
if (damaged || (!rows.has(target) && rows.size >= MAX_TARGETS)) throw Error('Tool trust storage unavailable.')
|
|
99
|
+
const tools = new Map(rows.get(target))
|
|
100
|
+
if (!tools.has(name) && tools.size >= MAX_TOOLS) throw Error('Tool trust capacity reached.')
|
|
101
|
+
if (tools.get(name) !== signature) await save(target, tools.set(name, signature), assertCurrent)
|
|
102
|
+
})
|
|
103
|
+
},
|
|
104
|
+
})
|
|
105
|
+
}
|