148 lines
8.0 KiB
JavaScript
148 lines
8.0 KiB
JavaScript
import assert from 'node:assert/strict'
|
|
import { createServer } from 'node:http'
|
|
import { join } from 'node:path'
|
|
import { setTimeout as delay } from 'node:timers/promises'
|
|
import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client'
|
|
import { resumeServerPoll } from '../acceptance/mcp-server-poll-steps.mjs'
|
|
|
|
export async function verifyPollSteps(endpoint, pool, jwt, output) {
|
|
assert.equal(endpoint.hostname, '127.0.0.1')
|
|
const replies = {
|
|
'/rest/system/identity': { name: 'Owned synthetic router' },
|
|
'/rest/system/resource': { version: '7.owned', 'board-name': 'Owned', uptime: '1h', 'cpu-load': '2', 'free-memory': '1024', 'total-memory': '2048' },
|
|
'/rest/interface': [{ name: 'ether1', type: 'ether' }],
|
|
'/rest/ip/address': [{ interface: 'ether1', address: '192.0.2.1/24' }],
|
|
}
|
|
const native = []
|
|
const router = createServer((request, response) => {
|
|
native.push(request.url)
|
|
if (request.method !== 'GET' || !Object.hasOwn(replies, request.url)) return response.writeHead(403).end()
|
|
response.setHeader('content-type', 'application/json')
|
|
response.end(JSON.stringify(replies[request.url]))
|
|
})
|
|
let client
|
|
try {
|
|
await new Promise((resolve, reject) => router.once('error', reject).listen(0, '127.0.0.1', resolve))
|
|
const { rows: [server] } = await pool.query(`INSERT INTO servers(name,host,port,use_ssl,verify_ssl,enabled,username,password)
|
|
VALUES('Owned poll','127.0.0.1',$1,false,false,true,'owned-router','fixture') RETURNING id`, [router.address().port])
|
|
const serverId = Number(server.id)
|
|
const { rows: catalogue } = await pool.query('SELECT id FROM servers ORDER BY id')
|
|
const owner = async (path, body) => {
|
|
const response = await fetch(new URL(path, endpoint), {
|
|
headers: { authorization: 'Bearer ' + jwt, 'content-type': 'application/json' },
|
|
...(body && { method: 'POST', body: JSON.stringify(body) }),
|
|
redirect: 'error', signal: AbortSignal.timeout(5000),
|
|
})
|
|
assert.equal(response.status, 200, path)
|
|
return response.json()
|
|
}
|
|
const { connection, token } = await owner('/api/mcp/connections', {
|
|
name: 'Owned poll steps', mode: 'approval', expiresAt: new Date(Date.now() + 180000).toISOString(),
|
|
permissions: ['mm:servers:read', 'mm:servers:write', 'mm:settings:admin'],
|
|
scope: { serverIds: catalogue.map(row => Number(row.id)), operationIds: ['servers.poll', 'changes.apply', 'operations.read'], allowGlobal: true },
|
|
limits: { callsPerMinute: 120, mutationsPerHour: 10000, objectsPerPlan: 10000 },
|
|
})
|
|
const connect = async () => {
|
|
await client?.close()
|
|
client = new Client({ name: 'owned-poll-steps', version: '1.0.0' })
|
|
await client.connect(new StreamableHTTPClientTransport(endpoint, {
|
|
requestInit: { headers: { authorization: 'Bearer ' + token } },
|
|
}), { timeout: 5000 })
|
|
}
|
|
await connect()
|
|
const journal = join(output, 'poll-' + connection.id + '.jsonl')
|
|
let planId
|
|
let approvedExpiresAt
|
|
let operationId
|
|
let operation
|
|
let interruptStatus = true
|
|
let applyKey
|
|
const config = {
|
|
journal, fixture: 'owned-poll', serverId, connectionId: connection.id,
|
|
async findAcceptedOperation({ connectionId: scope, planId: plan, idempotencyKey }) {
|
|
assert.equal(operationId, undefined)
|
|
assert.equal(scope, connection.id)
|
|
assert.equal(plan, planId)
|
|
assert.equal(idempotencyKey, applyKey)
|
|
const { rows } = await pool.query(`SELECT id FROM mcp_operations
|
|
WHERE connection_id=$1 AND plan_id=$2 AND idempotency_key=$3`, [scope, plan, idempotencyKey])
|
|
assert.equal(rows.length, 1)
|
|
operationId = rows[0].id
|
|
return operationId
|
|
},
|
|
async call(name, args) {
|
|
if (name === 'mm_operation_get' && interruptStatus) {
|
|
interruptStatus = false
|
|
assert.equal(args.operationId, operationId)
|
|
throw Object.assign(new Error('Simulated interruption before reading status'), { code: 'FIXTURE_INTERRUPTED' })
|
|
}
|
|
const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: name === 'mm_server_poll_plan' ? 45000 : 5000 })
|
|
if (reply.isError) {
|
|
const error = JSON.parse(reply.content.find(item => item.type === 'text').text)
|
|
const code = /^[A-Z0-9_]{1,64}$/.test(error.code) ? error.code : 'POLL_SDK_ERROR'
|
|
console.error('Owned SDK tool refused:', name, code)
|
|
throw Object.assign(new Error(name + ' failed'), { code })
|
|
}
|
|
const result = reply.structuredContent.result
|
|
if (name === 'mm_server_poll_plan') planId = result.planId
|
|
if (name === 'mm_change_apply') {
|
|
assert.equal(applyKey, undefined, 'Apply cannot be sent twice')
|
|
applyKey = args.idempotencyKey
|
|
// The endpoint accepted the request, but the journal never sees its response.
|
|
throw Object.assign(new Error('Simulated lost apply response'), { code: 'FIXTURE_LOST_APPLY' })
|
|
}
|
|
if (name === 'mm_operation_get') operation = result
|
|
return result
|
|
},
|
|
async assertApproved(id) {
|
|
const plan = await owner('/api/mcp/plans/' + id)
|
|
assert.equal(plan.connectionId, connection.id)
|
|
assert.equal(plan.operationId, 'servers.poll')
|
|
if (plan.state !== 'approved') throw Object.assign(new Error('Waiting for owner approval'), { code: 'POLL_AWAITING_APPROVAL' })
|
|
const expiresAt = Date.parse(plan.expiresAt)
|
|
assert(expiresAt > Date.now(), 'Approved poll must have a live expiry')
|
|
approvedExpiresAt = expiresAt
|
|
},
|
|
}
|
|
assert.deepEqual(await resumeServerPoll(config), { status: 'failed', step: 'manager.plan-approved' }, journal)
|
|
assert.ok(planId)
|
|
assert.deepEqual(await owner('/api/mcp/plans/' + planId + '/decision', { approve: true }), { ok: true })
|
|
assert.deepEqual(await resumeServerPoll(config), { status: 'failed', step: 'mm_change_apply' }, journal)
|
|
assert.ok(applyKey)
|
|
assert.equal(operationId, undefined)
|
|
await connect()
|
|
assert.deepEqual(await resumeServerPoll(config), { status: 'failed', step: 'mm_operation_get' }, journal)
|
|
assert.ok(operationId)
|
|
await connect()
|
|
const observationStartedAt = Date.now()
|
|
let state
|
|
while (true) {
|
|
const { rows } = await pool.query('SELECT state FROM mcp_operations WHERE id=$1 AND connection_id=$2', [operationId, connection.id])
|
|
state = rows[0]?.state
|
|
const remaining = approvedExpiresAt - Date.now()
|
|
if (!['pending', 'running'].includes(state) || remaining <= 0) break
|
|
await delay(Math.min(500, remaining))
|
|
}
|
|
const observedMs = Date.now() - observationStartedAt
|
|
const approvedLifetimeRemainingAtStartMs = approvedExpiresAt - observationStartedAt
|
|
assert.deepEqual(await resumeServerPoll(config), { status: 'passed' },
|
|
`${journal} DB state ${state} after ${observedMs} ms (original approval window ${approvedLifetimeRemainingAtStartMs} ms at start)`)
|
|
assert.equal(operation.id, operationId)
|
|
const receipt = operation.steps[0].result
|
|
assert.equal(receipt.snapshot.status, 'online')
|
|
assert.deepEqual(native.sort(), Object.keys(replies).sort())
|
|
const { rows } = await pool.query(`SELECT tool,count(*)::int AS count FROM mcp_requests
|
|
WHERE connection_id=$1 AND tool IN ('mm_server_poll_plan','mm_change_apply','mm_operation_get') GROUP BY tool`, [connection.id])
|
|
const calls = Object.fromEntries(rows.map(row => [row.tool, row.count]))
|
|
assert.equal(calls.mm_server_poll_plan, 1)
|
|
assert.equal(calls.mm_change_apply, 1)
|
|
assert.equal(calls.mm_operation_get, 1)
|
|
return { journal, operationId, calls, reconciledLostApply: true, sdkReconnects: 2, nativeReads: native.length, publications: receipt.completedPublications,
|
|
state: operation.state, verification: operation.verification, localPostgres: true, sdkHttp: true,
|
|
approvedExpiresAt: new Date(approvedExpiresAt).toISOString(), approvedLifetimeRemainingAtStartMs, observedMs }
|
|
} finally {
|
|
await client?.close()
|
|
if (router.listening) await new Promise((resolve, reject) => router.close(error => error ? reject(error) : resolve()))
|
|
}
|
|
}
|