Files
MikrotikManager/backend/scripts/mcp-external-process/result-envelope-fixture.mjs
T

139 lines
7.9 KiB
JavaScript

import assert from 'node:assert/strict'
import { randomUUID } from 'node:crypto'
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio'
const limit = 1024 * 1024
const budgetMeta = 'io.mikrotikmanager/result-budget'
const comment = 'Ж'.repeat(11000)
const payloadBytes = value => Buffer.byteLength(JSON.stringify(value), 'utf8')
const tools = ['mm_servers_list', 'mm_logs_settings_update_plan', 'mm_change_apply', 'mm_operation_get']
export async function verifyResultEnvelope(endpoint, pool, jwt, bridgeFile) {
assert.equal(new URL(endpoint).hostname, '127.0.0.1')
const { rows: [{ count: existingServers }] } = await pool.query('SELECT count(*)::int AS count FROM servers')
await pool.query(`
INSERT INTO servers(name,host,enabled,comment)
SELECT 'owned-envelope-'||n, '192.0.2.'||(10+n), false, $1 FROM generate_series(1,24) AS n
`, [comment])
const { rows: servers } = await pool.query('SELECT id FROM servers ORDER BY id')
// Independently observe actual writes, including an accidental repeat with unchanged settings.
await pool.query(`
CREATE TABLE owned_log_settings_writes (interval_sec integer NOT NULL);
CREATE FUNCTION owned_count_log_settings_write() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
INSERT INTO owned_log_settings_writes VALUES (NEW.interval_sec);
RETURN NEW;
END $$;
CREATE TRIGGER owned_count_log_settings_write AFTER UPDATE ON router_log_settings
FOR EACH ROW EXECUTE FUNCTION owned_count_log_settings_write()`)
const headers = { authorization: 'Bearer ' + jwt, 'content-type': 'application/json' }
const json = async (path, body) => {
const response = await fetch(new URL(path, endpoint), {
headers, signal: AbortSignal.timeout(10000), ...(body ? { method: 'POST', body: JSON.stringify(body) } : {}),
})
assert.equal(response.status, 200, path)
return response.json()
}
const cases = []
for (const mode of ['http', 'stdio']) {
const { connection, token } = await json('/api/mcp/connections', {
name: 'Owned result envelope ' + mode, mode: 'approval', expiresAt: new Date(Date.now() + 600000).toISOString(),
permissions: ['mm:servers:read', 'mm:settings:admin'],
limits: { serversPerPlan: servers.length, mutationsPerHour: servers.length },
scope: { serverIds: servers.map(row => Number(row.id)), allowGlobal: true,
operationIds: ['servers.list', 'logs.settings.update', 'changes.apply', 'operations.read'] },
})
const client = new Client({ name: 'owned-result-envelope-' + mode, version: '1.0.0' })
const transport = mode === 'http'
? new StreamableHTTPClientTransport(new URL(endpoint), { requestInit: { headers: { authorization: 'Bearer ' + token } } })
: new StdioClientTransport({ command: process.execPath, args: ['--import', import.meta.resolve('tsx'), bridgeFile],
cwd: process.cwd(), env: { MCP_URL: endpoint, MCP_TOKEN: token }, maxBufferSize: limit + 65536, stderr: 'pipe' })
transport.stderr?.on('data', () => {})
try {
await client.connect(transport, { timeout: 10000 })
const observedTools = (await client.listTools({}, { timeout: 5000 })).tools.map(tool => tool.name)
assert.deepEqual(observedTools.sort(), [...tools].sort())
const call = async (name, args) => {
const result = await client.callTool({ name, arguments: args }, undefined, { timeout: 10000 })
assert(payloadBytes(result) <= limit, mode + ' ' + name)
return result
}
const output = result => {
if (result.isError) assert.fail(JSON.parse(result.content[0].text).code)
const text = JSON.parse(result.content[0].text)
assert.deepEqual(result.structuredContent.result, text)
return text
}
const accepted = await call('mm_servers_list', { limit: 23, offset: existingServers })
const page = output(accepted)
assert.equal(page.items.length, 23)
assert(page.items.every(item => item.comment === comment))
assert(payloadBytes(accepted) >= 1000000)
// Even without field names and framing this page's duplicated UTF-8 text exceeds 1 MiB.
assert(24 * Buffer.byteLength(comment, 'utf8') * 2 > limit)
const refused = await call('mm_servers_list', { limit: 24, offset: existingServers })
assert.equal(refused.isError, true)
assert.equal(refused.structuredContent, undefined)
assert.equal(JSON.parse(refused.content[0].text).code, 'RESULT_TOO_LARGE')
assert.deepEqual(refused._meta[budgetMeta], {
version: 1, detailsOmitted: true, reason: 'byte-budget', automaticReplay: false,
})
const before = await json('/api/logs/settings')
const intervalSec = before.intervalSec === 60 ? 61 : 60
const plan = output(await call('mm_logs_settings_update_plan', { settings: { intervalSec } }))
assert.equal(plan.state, 'awaiting-approval')
await json('/api/mcp/plans/' + plan.planId + '/decision', { approve: true })
const applyArgs = { planId: plan.planId, idempotencyKey: randomUUID() }
const operation = output(await call('mm_change_apply', applyArgs))
let terminal
for (const end = Date.now() + 10000; Date.now() < end;) {
terminal = output(await call('mm_operation_get', { operationId: operation.id }))
if (!['pending', 'running'].includes(terminal.state)) break
await new Promise(resolve => setTimeout(resolve, 100))
}
assert.equal(terminal.state, 'applied')
assert.equal(terminal.verification, 'passed')
const writes = async () => (await pool.query('SELECT count(*)::int AS n FROM owned_log_settings_writes')).rows[0].n
const checkEffect = async () => {
assert.equal(await writes(), cases.length + 1)
assert.deepEqual(await json('/api/logs/settings'), { ...before, intervalSec })
}
await checkEffect()
// Supply namespaced synthetic optional details to the actual, already applied operation.
// The ordinary runtime read and duplicate-apply paths must keep its original outcome.
const oversizedDetails = JSON.stringify(Array(24).fill(comment))
const staged = await pool.query(`
UPDATE mcp_operations SET result=jsonb_set(COALESCE(result, '{}'::jsonb), '{ownedEnvelopeDetails}', $2::jsonb)
WHERE id=$1 AND state='applied' RETURNING id`, [operation.id, oversizedDetails])
assert.equal(staged.rowCount, 1)
const compactRead = await call('mm_operation_get', { operationId: operation.id })
const compactApply = await call('mm_change_apply', applyArgs)
for (const compact of [compactRead, compactApply]) {
assert(payloadBytes(compact) < 2048)
assert.deepEqual(compact._meta[budgetMeta], refused._meta[budgetMeta])
assert.deepEqual(output(compact), {
id: operation.id, plan_id: plan.planId, state: 'applied', verification: 'passed', error_code: null,
})
}
await checkEffect()
const { rows: [counts] } = await pool.query(`
SELECT
(SELECT count(*)::int FROM mcp_operations WHERE connection_id=$1) AS operations,
(SELECT count(*)::int FROM mcp_operation_steps WHERE operation_id=$2 AND state='verified') AS verified_steps,
(SELECT count(*)::int FROM mcp_requests WHERE connection_id=$1 AND tool='mm_change_apply') AS apply_requests
`, [connection.id, operation.id])
assert.deepEqual(counts, { operations: 1, verified_steps: 1, apply_requests: 2 })
cases.push({ mode, nearLimitBytes: payloadBytes(accepted), refusalBytes: payloadBytes(refused),
compactReadBytes: payloadBytes(compactRead), compactApplyBytes: payloadBytes(compactApply),
...counts, settingsWrites: 1 })
} finally {
await client.close()
}
}
return { scope: 'complete CallToolResult from HTTP SDK and production stdio bridge on owned PostgreSQL',
limitBytes: limit, wholeGenericResultEnvelopeLimitAccepted: true, cases }
}