Expand MCP controls and add cached system resource telemetry
CI / verify (push) Canceled after 0s

This commit is contained in:
Sucukdeluxe committed 2026-10-20 13:12:21 +02:00
1 parent d3cba015b5
commit c4439480bd
6 files changed
+224 -17

No files matched your search

+42 -7
View File
@@ -1,9 +1,11 @@
const { randomUUID } = require('node:crypto');
const path = require('node:path');
const { McpAccessError, resolveGrantedFile } = require('./mcp-access');
const { createMcpFiles } = require('./mcp-files');
const { createMcpTransfers } = require('./mcp-transfers');
const { createMcpDiagnostics } = require('./mcp-diagnostics');
const { createMcpSanitizer } = require('./mcp-security');
const { MCP_TOOLS, requiresMcpConfirmation } = require('./mcp-tools');
const { redactLogText, collectSecretValues } = require('./support-bundle');
function page(items, args) {
@@ -13,7 +15,7 @@ function page(items, args) {
}
function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel, ...args) => invoke(channel, ...args), renderer, collectors, getGrants, trashFile, canWrite,
getCapabilities, getProtectedPaths, getInstallationId, getDiagnosticSources, getRuntimeDiagnostics = () => null, getPerformance = () => null, updates }) {
getCapabilities, getProtectedPaths, getInstallationId, getDiagnosticSources, getRuntimeDiagnostics = () => null, getPerformance = () => null, getSystemMetrics = () => null, updates }) {
const transfers = createMcpTransfers({ getGrants, getCapabilities, getProtectedPaths, getInstallationId });
const sanitize = createMcpSanitizer(loadConfig);
const guard = context => {
@@ -48,16 +50,33 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
};
const saveGlobal = async (patch, context) => {
canWrite(); guard(context);
await invoke('save-global-settings', { ...loadConfig().globalSettings, ...patch });
const current = loadConfig().globalSettings;
await invoke('save-global-settings', { ...current, ...patch, ...(patch.scramble ? { scramble: { ...current.scramble, ...patch.scramble } } : {}) });
await refresh(context);
return { saved: true };
};
const automationAction = async (channel, code, context) => {
canWrite(); guard(context);
const result = await invoke(channel);
if (result?.error || result?.monitorError) throw new McpAccessError(code);
return result;
};
const handlers = {
...createMcpFiles({ getGrants, trashFile }),
...transfers.handlers,
...createMcpDiagnostics({ getSources: getDiagnosticSources, redact: text => sanitize(redactLogText(text, collectSecretValues(loadConfig()))) }),
mhu_app_info: () => invoke('get-app-info'),
mhu_capabilities: () => {
const permissions = getCapabilities?.() || [];
const settings = loadConfig().globalSettings;
return { permissions, tools: MCP_TOOLS.filter(tool => tool.requiredScopes.every(scope => permissions.includes(scope))).map(tool => ({
name: tool.name, readOnly: tool.annotations.readOnlyHint, requiredScopes: tool.requiredScopes,
localConfirmation: tool.destructive || requiresMcpConfirmation(tool.name, {}, settings),
conditionalConfirmation: tool.name === 'mhu_settings_update'
})), boundaries: ['Permissions and directory grants can only be changed locally.', 'Destructive actions require an exact local confirmation; MCP cannot approve it.', 'No arbitrary shell, SQL, mouse/keyboard or screen control.', 'Paused automation is resumed with mhu_automation_resume. A disabled monitor requires mhu_automation_start.'] };
},
mhu_performance_get: () => getPerformance(),
mhu_system_metrics: args => getSystemMetrics(args),
mhu_app_state: async (args, context) => ({ ...(await renderer('state', {}, context)), automation: await invoke('automation:get-status') }),
mhu_queue_list: (args, context) => renderer('queue-list', args, context),
mhu_queue_job_log: async args => page(await invoke('get-job-log', args.jobId), args),
@@ -69,8 +88,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
return renderer('queue-add', { paths: files, hosters: args.hosters }, context);
},
mhu_queue_start: (args, context) => renderer('queue-start', args, context),
mhu_queue_pause: () => invoke('automation:pause-after-active'),
mhu_queue_resume: async (args, context) => { guard(context); return invoke('automation:resume'); },
mhu_queue_pause: (args, context) => automationAction('automation:pause-after-active', 'AUTOMATION_PAUSE_FAILED', context),
mhu_queue_resume: (args, context) => automationAction('automation:resume', 'AUTOMATION_RESUME_FAILED', context),
mhu_queue_retry: (args, context) => renderer('queue-retry', args, context),
mhu_queue_cancel: (args, context) => renderer('queue-cancel', args, context),
mhu_queue_remove: (args, context) => renderer('queue-remove', args, context),
@@ -110,7 +129,11 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
mhu_accounts_remove: (args, context) => saveAccount(args.accountId, {}, context, true),
mhu_accounts_reset_failure: args => { const account = find(args.accountId); return invoke('reset-session-failed-account', { hoster: account.hoster, accountId: args.accountId }); },
mhu_settings_get: () => { const config = loadConfig(); const settings = { ...config.globalSettings }; delete settings.pendingQueue; delete settings.uploadRecovery; return { globalSettings: settings, hosterSettings: config.hosterSettings }; },
mhu_settings_update: (args, context) => saveGlobal(args, context),
mhu_settings_update: async (args, context) => {
const result = await saveGlobal(args, context);
if (Object.hasOwn(args, 'shutdownAfterFinish')) await invoke('set-shutdown-after-finish', args.shutdownAfterFinish);
return result;
},
mhu_hoster_settings_update: async ({ hoster, ...patch }, context) => {
canWrite(); guard(context);
const current = loadConfig().hosterSettings;
@@ -119,6 +142,8 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
return { saved: true };
},
mhu_automation_status: () => invoke('automation:get-status'),
mhu_automation_pause: (args, context) => automationAction('automation:pause-after-active', 'AUTOMATION_PAUSE_FAILED', context),
mhu_automation_resume: (args, context) => automationAction('automation:resume', 'AUTOMATION_RESUME_FAILED', context),
mhu_automation_update: async ({ rootId, ...patch }, context) => {
const folder = await resolveGrantedFile(getGrants(), rootId, '');
if (!folder.stat.isDirectory()) throw new McpAccessError('NOT_A_DIRECTORY');
@@ -128,9 +153,13 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
},
mhu_automation_start: async (args, context) => {
const settings = loadConfig().globalSettings.folderMonitor;
if (!getGrants().some(grant => grant.path === settings.folderPath)) throw new McpAccessError('PATH_NOT_GRANTED');
if (settings.paused === true) throw new McpAccessError('AUTOMATION_PAUSED');
const normalize = value => process.platform === 'win32' ? path.resolve(value).toLowerCase() : path.resolve(value);
if (!settings.folderPath || !getGrants().some(grant => normalize(grant.path) === normalize(settings.folderPath))) throw new McpAccessError('PATH_NOT_GRANTED');
await saveGlobal({ folderMonitor: { ...settings, enabled: true } }, context); guard(context);
return invoke('folder-monitor:start', { ...settings, enabled: true });
const result = await invoke('folder-monitor:start', { ...settings, enabled: true });
if (result?.error) throw new McpAccessError('AUTOMATION_START_FAILED');
return result;
},
mhu_automation_stop: async (args, context) => { await saveGlobal({ folderMonitor: { ...loadConfig().globalSettings.folderMonitor, enabled: false } }, context); return invoke('folder-monitor:stop'); },
mhu_automation_scan: () => invoke('folder-monitor:test-scan'),
@@ -163,6 +192,12 @@ function createMcpApp({ loadConfig, invoke, invokeGuarded = (_context, channel,
mhu_update_status: (args, context) => updates.status(args, context),
mhu_app_restart: () => invoke('app:restart'),
mhu_app_quit: () => invoke('app:quit'),
mhu_shutdown_cancel: async (args, context) => {
canWrite(); guard(context);
await invoke('cancel-shutdown');
await saveGlobal({ shutdownAfterFinish: 'nothing' }, context);
return { cancelled: true, shutdownAfterFinish: 'nothing' };
},
mhu_secrets_read: args => { const { password, apiKey } = find(args.accountId); return { accountId: args.accountId, password: password || '', apiKey: apiKey || '' }; }
};
Object.defineProperty(handlers, 'dispose', { value: () => transfers.dispose() });
+20 -4
View File
@@ -17,7 +17,9 @@ const file = { rootId: id, relativePath: text() };
const definitions = [
['app_info', 'Read application version and runtime information.', 'read', {}, []],
['capabilities', 'Read effective permissions, the supported action catalog and local security boundaries. This cannot grant permissions or approve actions.', 'read', {}, []],
['performance_get', 'Read bounded in-memory main-thread, renderer, CPU, memory, I/O and transfer-slot measurements. Missing samples do not prove a freeze.', 'read', {}, []],
['system_metrics', 'Read cached system CPU, RAM, disk activity, read/write throughput, cumulative byte counters and volume capacity. No shell commands. Samples every 10 seconds; null or stale values are not freeze evidence.', 'read', { limit: integer(1, 60) }, []],
['app_state', 'Read live transfer and automation summary.', 'read', {}, []],
['queue_list', 'Read a bounded page of upload jobs.', 'read', { ...page, status: text(40) }, []],
['queue_job_log', 'Read a bounded, secret-filtered log for one upload job.', 'read', { jobId: id, ...page }, ['jobId']],
@@ -44,12 +46,15 @@ const definitions = [
language: enumeration(['de', 'en']), globalMaxSpeedKbs: integer(0, 100000000), parallelUploadCount: integer(0, 100),
autoRetryRounds: integer(0, 5), autoRetryDelayMin: integer(1, 1440), autoHealthCheckEnabled: boolean,
resumeQueueOnLaunch: boolean, autoStartRestoredQueue: boolean, removeFromQueueOnDone: boolean,
logMode: enumeration(['single', 'daily', 'session']), logVerbose: boolean
logMode: enumeration(['single', 'daily', 'session']), logVerbose: boolean,
scaleParallelUploads: boolean, historyRetention: retention,
deleteSourceAfterSuccessfulUpload: boolean, shutdownAfterFinish: enumeration(['nothing', 'sleep', 'shutdown', 'restart']),
scramble: object({ active: boolean, prefix: text(200), suffix: text(200), chars: enumeration(['letters', 'numbers', 'both']), length: integer(0, 200) })
}, []],
['hoster_settings_update', 'Update one hoster transfer configuration.', 'settings', {
hoster, retries: integer(0, 20), parallelCount: integer(1, 100), maxSpeedKbs: integer(0, 100000000),
restartBelowKbs: integer(0, 100000000), timeIntervalSec: integer(0, 86400), maxSizeMb: integer(0, 100000000),
rotateAccounts: boolean, logToFile: boolean
rotateAccounts: boolean, logToFile: boolean, sizeMemoEnabled: boolean
}, ['hoster']],
['automation_status', 'Read folder-monitor and automatic retry state.', 'read', {}, []],
['automation_update', 'Configure monitoring for an explicitly granted directory.', 'settings', {
@@ -58,6 +63,8 @@ const definitions = [
queueLimitJobs: integer(0, 100000), reconcileIntervalMinutes: integer(1, 1440)
}, ['rootId'], true],
['automation_start', 'Start configured folder monitoring.', 'control', {}, []],
['automation_pause', 'Pause the shared upload queue and folder automation after active transfers. Does not disable the configured monitor.', 'control', {}, []],
['automation_resume', 'Resume the shared upload queue and configured folder automation. Use this for paused=true, not automation_start. Does not enable a disabled monitor.', 'control', {}, []],
['automation_stop', 'Stop folder monitoring without removing queued jobs.', 'control', {}, []],
['automation_scan', 'Run a read-only folder monitoring test scan.', 'read', {}, []],
['automation_reconcile', 'Reconcile the monitored directory with the queue.', 'control', {}, []],
@@ -99,6 +106,7 @@ const definitions = [
['update_status', 'Read an owned persistent update job, including progress and post-restart version verification.', 'read', { jobId: id }, []],
['app_restart', 'Restart the application after persisting its state.', 'lifecycle', {}, [], true],
['app_quit', 'Close the application after persisting its state.', 'lifecycle', {}, [], true],
['shutdown_cancel', 'Cancel a pending automatic shutdown/restart/sleep countdown and persist the disabled completion action.', 'control', {}, []],
['secrets_read', 'Explicitly reveal credentials for one account; disabled by default.', 'secrets.read', account, ['accountId']]
];
@@ -107,7 +115,7 @@ const MCP_TOOLS = Object.freeze(definitions.map(([name, description, scope, prop
name: 'mhu_' + name, description, scope: capabilities[scope] || scope, destructive, inputSchema: object(properties, required),
requiredScopes: [...new Set([capabilities[scope] || scope, ...(['queue_add', 'automation_update'].includes(name) ? ['files'] : []), ...(name === 'files_delete' ? ['control'] : []), ...(name.startsWith('files_transfer_') ? ['read'] : [])])],
annotations: { readOnlyHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && !['files_transfer_open', 'files_transfer_close'].includes(name), destructiveHint: destructive,
idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && name !== 'files_transfer_open', openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|reconcile)|cloud_|backup_|update_)/.test(name) }
idempotentHint: ['read', 'diagnostics', 'files', 'secrets.read'].includes(scope) && name !== 'files_transfer_open', openWorldHint: /^(?:queue_(?:start|retry|resume)|accounts_(?:check|otp|request_otp)|automation_(?:start|resume|reconcile)|cloud_|backup_|update_)/.test(name) }
})));
function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit = () => {}, getCapabilities, requiresConfirmation = () => false }) {
@@ -160,4 +168,12 @@ function createMcpToolAdapter({ handlers, authorizeConfirmation, sanitize, audit
return { list: () => MCP_TOOLS.filter(tool => typeof handlers[tool.name] === 'function'), call };
}
module.exports = { MCP_TOOLS, createMcpToolAdapter };
function requiresMcpConfirmation(name, args, settings) {
if (name === 'mhu_settings_update') return args.deleteSourceAfterSuccessfulUpload === true
|| (Object.hasOwn(args, 'shutdownAfterFinish') && args.shutdownAfterFinish !== 'nothing')
|| (Object.hasOwn(args, 'historyRetention') && args.historyRetention !== 'all');
if (!['mhu_queue_start', 'mhu_queue_retry', 'mhu_automation_start', 'mhu_automation_reconcile'].includes(name)) return false;
return settings.deleteSourceAfterSuccessfulUpload === true || !['nothing', undefined, null].includes(settings.shutdownAfterFinish);
}
module.exports = { MCP_TOOLS, createMcpToolAdapter, requiresMcpConfirmation };
+147
View File
@@ -0,0 +1,147 @@
const os = require('node:os');
const { execFile } = require('node:child_process');
const { promisify } = require('node:util');
const WINDOWS_PROBE = "$ErrorActionPreference='Stop'; $ProgressPreference='SilentlyContinue'; $d=@(Get-CimInstance Win32_PerfRawData_PerfDisk_PhysicalDisk | ForEach-Object { @{ Name=$_.Name; Timestamp_PerfTime=[string]$_.Timestamp_PerfTime; Frequency_PerfTime=[string]$_.Frequency_PerfTime; Timestamp_Sys100NS=[string]$_.Timestamp_Sys100NS; PercentIdleTime=[string]$_.PercentIdleTime; DiskReadBytesPersec=[string]$_.DiskReadBytesPersec; DiskWriteBytesPersec=[string]$_.DiskWriteBytesPersec; DiskReadsPersec=[string]$_.DiskReadsPersec; DiskWritesPersec=[string]$_.DiskWritesPersec; CurrentDiskQueueLength=[string]$_.CurrentDiskQueueLength } }); $v=@(Get-CimInstance Win32_LogicalDisk -Filter 'DriveType=3' | ForEach-Object { @{ DeviceID=$_.DeviceID; Size=[string]$_.Size; FreeSpace=[string]$_.FreeSpace } }); @{disks=$d;volumes=$v} | ConvertTo-Json -Depth 4 -Compress";
async function readWindowsCounters({ runner = promisify(execFile), signal } = {}) {
const { stdout } = await runner('C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',
['-NoLogo', '-NoProfile', '-NonInteractive', '-Command', WINDOWS_PROBE],
{ windowsHide: true, shell: false, timeout: 8000, maxBuffer: 1024 * 1024, encoding: 'utf8', signal });
const value = JSON.parse(stdout.replace(/^\uFEFF/, ''));
if (!Array.isArray(value.disks) || !Array.isArray(value.volumes) || value.disks.length > 256 || value.volumes.length > 256) throw Error('INVALID_METRICS');
return value;
}
function counter(value) {
return /^\d{1,24}$/.test(String(value)) ? BigInt(value) : null;
}
function delta(current, previous) {
const a = counter(current), b = counter(previous);
return a !== null && b !== null && a >= b ? Number(a - b) : null;
}
function diskSample(current, previous) {
const ticks = delta(current.Timestamp_PerfTime, previous?.Timestamp_PerfTime);
const frequency = Number(current.Frequency_PerfTime);
const seconds = ticks > 0 && frequency > 0 ? ticks / frequency : null;
const rate = key => {
const difference = delta(current[key], previous?.[key]);
return seconds && difference !== null ? difference / seconds : null;
};
const idle = delta(current.PercentIdleTime, previous?.PercentIdleTime);
const time = delta(current.Timestamp_Sys100NS, previous?.Timestamp_Sys100NS);
const read = rate('DiskReadBytesPersec'), write = rate('DiskWriteBytesPersec');
const readTotal = counter(current.DiskReadBytesPersec), writeTotal = counter(current.DiskWriteBytesPersec);
return {
id: String(current.Name).slice(0, 256), intervalMs: seconds ? seconds * 1000 : null,
readBytesPerSecond: read, writeBytesPerSecond: write, totalBytesPerSecond: read !== null && write !== null ? read + write : null,
readOperationsPerSecond: rate('DiskReadsPersec'), writeOperationsPerSecond: rate('DiskWritesPersec'),
readBytesTotal: readTotal?.toString() ?? null, writeBytesTotal: writeTotal?.toString() ?? null,
totalBytes: readTotal !== null && writeTotal !== null ? (readTotal + writeTotal).toString() : null,
busyPercent: time > 0 && idle !== null ? Math.max(0, Math.min(100, (1 - idle / time) * 100)) : null,
queueLength: counter(current.CurrentDiskQueueLength) !== null ? Number(current.CurrentDiskQueueLength) : null
};
}
class SystemMetrics {
constructor(options = {}) {
this.os = options.os || os;
this.now = options.now || Date.now;
this.processCpu = options.processCpu || process.cpuUsage;
this.processMemory = options.processMemory || process.memoryUsage;
this.shouldCollect = options.shouldCollect || (() => true);
this.readDisks = options.readDisks || (process.platform === 'win32' ? readWindowsCounters : null);
this.limit = Math.max(1, Math.min(60, options.limit || 60));
this.samples = [];
this.previous = null;
this.previousDisks = new Map();
this.storage = { available: false, sampledAt: null, disks: [], volumes: [] };
this.stopped = false;
}
start() {
if (this.timer) return;
this.stopped = false;
void this.sample();
this.timer = setInterval(() => { void this.sample(); }, 10000);
this.timer.unref?.();
}
stop() {
this.stopped = true;
clearInterval(this.timer);
this.timer = null;
this.controller?.abort();
}
sample() {
if (this.pending) return this.pending;
if (this.stopped || !this.shouldCollect()) return Promise.resolve();
this.pending = this.capture().finally(() => { this.pending = null; });
return this.pending;
}
async capture() {
const startedAt = this.now();
this.controller = new AbortController();
let available = false;
try {
if (this.readDisks) {
const raw = await this.readDisks({ signal: this.controller.signal });
if (this.stopped) return;
const disks = raw.disks.map(disk => diskSample(disk, this.previousDisks.get(disk.Name)));
this.previousDisks = new Map(raw.disks.map(disk => [disk.Name, disk]));
const volumes = raw.volumes.map(volume => {
const total = counter(volume.Size), free = counter(volume.FreeSpace);
const valid = total !== null && free !== null && free <= total;
return { id: String(volume.DeviceID).slice(0, 16), totalBytes: valid ? Number(total) : null, freeBytes: valid ? Number(free) : null,
usedBytes: valid ? Number(total - free) : null, usedPercent: valid && total > 0n ? Number(total - free) / Number(total) * 100 : null };
});
this.storage = { sampledAt: this.now(), disks, volumes };
available = true;
}
} catch {}
if (this.stopped) return;
const now = this.now(), cpus = this.os.cpus();
const totals = cpus.reduce((sum, cpu) => {
sum.idle += cpu.times.idle;
sum.total += Object.values(cpu.times).reduce((a, b) => a + b, 0);
return sum;
}, { idle: 0, total: 0 });
const cpu = this.processCpu(), memory = this.processMemory();
const elapsed = this.previous ? now - this.previous.at : null;
const totalDelta = this.previous && totals.total - this.previous.totals.total;
const cpuDelta = this.previous && cpu.user + cpu.system - this.previous.cpu.user - this.previous.cpu.system;
const totalMemory = this.os.totalmem(), freeMemory = this.os.freemem();
const sample = {
at: now, intervalMs: elapsed, collectionDurationMs: now - startedAt,
system: { logicalCpuCount: cpus.length, cpuPercent: totalDelta > 0 ? Math.max(0, Math.min(100, 100 * (1 - (totals.idle - this.previous.totals.idle) / totalDelta))) : null,
memory: { totalBytes: totalMemory, freeBytes: freeMemory, usedBytes: totalMemory - freeMemory, usedPercent: totalMemory > 0 ? (totalMemory - freeMemory) / totalMemory * 100 : null }, uptimeSeconds: this.os.uptime() },
process: { cpuPercentOneCore: elapsed > 0 && cpuDelta >= 0 ? cpuDelta / (elapsed * 10) : null, rssBytes: memory.rss, heapUsedBytes: memory.heapUsed ?? null, heapTotalBytes: memory.heapTotal ?? null, externalBytes: memory.external ?? null },
storage: { ...this.storage, available, stale: !available, error: available ? null : this.readDisks ? 'STORAGE_METRICS_UNAVAILABLE' : 'STORAGE_METRICS_UNSUPPORTED' }
};
this.previous = { at: now, totals, cpu };
this.samples.push(sample);
if (this.samples.length > this.limit) this.samples.shift();
}
snapshot({ limit = 1 } = {}) {
const now = this.now(), latest = this.samples.at(-1) || null;
const requested = Math.max(1, Math.min(60, limit));
const samples = [];
let bytes = 0;
for (const sample of this.samples.slice(-requested).reverse()) {
bytes += Buffer.byteLength(JSON.stringify(sample));
if (bytes > 384 * 1024) break;
samples.unshift(sample);
}
return { at: now, intervalMs: 10000, collecting: !!this.pending, stale: !latest || now - latest.at > 30000,
ageMs: latest ? now - latest.at : null, latest, samples, returnedSamples: samples.length,
truncated: samples.length < Math.min(requested, this.samples.length),
notes: ['System CPU is normalized to 0–100%; process CPU uses one logical core as 100%.', 'Storage counters cover the whole system, not only this application. Byte totals are cumulative provider counters encoded as decimal strings.', 'Null rates require another valid sample. Missing or stale samples are not evidence of a freeze.'] };
}
}
module.exports = { SystemMetrics, diskSample, readWindowsCounters };