import assert from 'node:assert/strict' import { createHash } from 'node:crypto' import { Client, StreamableHTTPClientTransport } from '@modelcontextprotocol/client' import { resumeMcpSteps } from '../acceptance/mcp-step-journal.mjs' async function withClient(endpoint, token, run) { const client = new Client({ name: 'owned-logs-sdk', version: '1.0.0' }) try { await client.connect(new StreamableHTTPClientTransport(endpoint, { requestInit: { headers: { authorization: 'Bearer ' + token } }, }), { timeout: 5000 }) return await run(async (name, args = {}) => { const reply = await client.callTool({ name, arguments: args }, undefined, { timeout: 5000 }) assert(!reply.isError, name + ' failed') return reply.structuredContent.result }) } finally { await client.close() } } export async function verifyLogsHistory(endpoint, token, serverId, entries, journal, fixture, appendEvent) { assert.equal(endpoint.hostname, '127.0.0.1') const [newest, oldest] = entries const filters = { serverId, q: 'external-sdk-log-', levels: ['info'] } const config = { journal, fixture, steps: [ { id: 'mm_logs_query', async check(call) { const first = await call('mm_logs_query', { ...filters, limit: 1 }) assert.deepEqual(first.entries.map(entry => entry.id), [newest.id]) assert.ok(first.nextCursor) const next = await call('mm_logs_query', { ...filters, limit: 1, cursor: first.nextCursor }) assert.deepEqual(next.entries.map(entry => entry.id), [oldest.id]) assert.equal(next.nextCursor, null) } }, { id: 'mm_logs_summary_get', async check(call) { const summary = await call('mm_logs_summary_get', filters) assert.equal(summary.total, 2) assert.equal(summary.levels.info, 2) } }, { id: 'mm_logs_get', async check(call) { const entry = await call('mm_logs_get', { serverId, id: newest.id }) assert.equal(entry.id, newest.id) assert.equal(entry.serverId, serverId) assert.equal(entry.message, newest.message) } }, { id: 'mm_logs_context_get', async check(call) { const context = await call('mm_logs_context_get', { serverId, id: newest.id }) assert.equal(context.entry.id, newest.id) assert.deepEqual(context.before.map(entry => [entry.serverId, entry.id]), [[serverId, oldest.id]]) assert.deepEqual(context.after, []) } }, { id: 'mm_logs_follow', async check(call) { const args = { ...filters, limit: 1, waitSeconds: 0 } const first = await call('mm_logs_follow', args) assert.deepEqual(first.entries, [], 'Initial follow starts at the current watermark') assert.ok(first.cursor) const id = await appendEvent() const next = await call('mm_logs_follow', { ...args, cursor: first.cursor }) assert.deepEqual(next.entries.map(entry => entry.id), [id]) const end = await call('mm_logs_follow', { ...args, cursor: next.cursor }) assert.deepEqual(end.entries, []) } }, ].map(({ id, check }) => ({ id, kind: 'read', async run() { await withClient(endpoint, token, check) return null } })) } const result = await resumeMcpSteps(config) assert.equal(result.status, 'passed', JSON.stringify(result)) return config.steps.map(step => step.id) } export async function verifyLogsSettingsPlan(endpoint, token, connectionId, ownerJwt, journal, fixture) { assert.equal(endpoint.hostname, '127.0.0.1') const owner = async (path, body) => { const response = await fetch(new URL(path, endpoint), { headers: { authorization: 'Bearer ' + ownerJwt, 'content-type': 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(5000), ...(body && { method: 'POST', body: JSON.stringify(body) }), }) assert.equal(response.status, 200, path) return response.json() } const settingsPath = '/api/logs/settings' const before = await owner(settingsPath) const intervalSec = before.intervalSec === 60 ? 61 : 60 return withClient(endpoint, token, async call => { const planStep = 'mm_logs_settings_update_plan' const applyStep = 'mm_change_apply' const config = { journal, fixture, steps: [ { id: planStep, kind: 'plan', async run({ accept }) { const plan = await call(planStep, { settings: { intervalSec } }) accept(plan.planId) assert.equal(plan.state, 'awaiting-approval') return plan.planId } }, { id: 'owner.decision', kind: 'apply', async run({ evidence, accept }) { const planId = evidence.get(planStep) const path = '/api/mcp/plans/' + planId const plan = await owner(path) assert.equal(plan.id, planId) assert.equal(plan.operationId, 'logs.settings.update') assert.equal(plan.connectionId, connectionId) assert.equal(plan.state, 'awaiting-approval') assert.deepEqual(plan.input.settings, { intervalSec }) assert.deepEqual(await owner(settingsPath), before) assert.deepEqual(await owner(path + '/decision', { approve: true }), { ok: true }) accept(planId) return planId }, async reconcile({ evidence }) { const planId = evidence.get(planStep) const plan = await owner('/api/mcp/plans/' + planId) return plan.state === 'approved' && plan.connectionId === connectionId ? { state: 'verified', evidence: planId } : { state: 'unknown' } } }, { id: applyStep, kind: 'apply', async run({ evidence, idempotencyKey, accept }) { const operation = await call(applyStep, { planId: evidence.get(planStep), idempotencyKey }) accept(operation.id) return operation.id } }, { id: 'mm_operation_get', kind: 'read', async run({ evidence, attempt }) { if (attempt === 1) throw Object.assign(new Error('Simulated interruption before status read'), { code: 'FIXTURE_INTERRUPTED' }) const operationId = evidence.get(applyStep) const deadline = Date.now() + 10000 let operation do { operation = await call('mm_operation_get', { operationId }) assert.equal(operation.id, operationId) assert.equal(operation.plan_id, evidence.get(planStep)) assert.equal(operation.connection_id, connectionId) if (!['pending', 'running'].includes(operation.state)) break await new Promise(resolve => setTimeout(resolve, 100)) } while (Date.now() < deadline) assert.equal(operation.state, 'applied') assert.equal(operation.verification, 'passed') assert.deepEqual(await owner(settingsPath), { ...before, intervalSec }) return operationId } }, ] } assert.deepEqual(await resumeMcpSteps(config), { status: 'failed', step: 'mm_operation_get' }, journal) assert.deepEqual(await resumeMcpSteps(config), { status: 'passed' }, journal) return config.steps.map(step => step.id) }) } export async function verifyLogsReads(endpoint, serverId, exportToken, settingsToken, ownerJwt, journal, fixture) { assert.equal(endpoint.hostname, '127.0.0.1') const publish = async (call, accept) => { const artifact = await call('mm_logs_export', { serverId, q: 'external-sdk-log-1', format: 'json' }) accept(artifact.artifactId) assert.equal(artifact.rows, 1) return artifact.artifactId } const read = async (call, artifactId) => { const first = await call('mm_logs_export_read', { artifactId, limit: 16 }) assert(Number.isSafeInteger(first.bytes) && first.bytes > 16 && first.bytes <= 8192) assert.equal(first.offset, 0) assert.equal(first.nextOffset, 16) assert.equal(first.complete, false) const last = await call('mm_logs_export_read', { artifactId, offset: first.nextOffset }) assert.equal(last.offset, 16) assert.equal(last.nextOffset, null) assert.equal(last.complete, true) for (const part of [first, last]) { assert.equal(part.artifactId, artifactId) assert.equal(part.sha256, first.sha256) assert.equal(part.bytes, first.bytes) } const content = Buffer.concat([first, last].map(part => Buffer.from(part.dataBase64, 'base64'))) assert.equal(content.length, first.bytes) assert.equal(createHash('sha256').update(content).digest('hex'), first.sha256) assert.match(content.toString('utf8'), /external-sdk-log-1/) assert.doesNotMatch(content.toString('utf8'), /external-sdk-log-2/) return artifactId } const config = { journal, fixture, steps: [ { id: 'mm_logs_export', kind: 'apply', run: ({ accept }) => withClient(endpoint, exportToken, call => publish(call, accept)), // An unknown publication has no idempotency key. Stop for reconciliation. }, { id: 'mm_logs_export_read', kind: 'read', run: ({ evidence }) => withClient(endpoint, exportToken, call => read(call, evidence.get('mm_logs_export'))), }, { id: 'mm_logs_settings_get', kind: 'read', async run({ attempt }) { if (attempt === 1) throw Object.assign(new Error('Simulated interruption before settings read'), { code: 'FIXTURE_INTERRUPTED', }) await withClient(endpoint, settingsToken, async call => { const response = await fetch(new URL('/api/logs/settings', endpoint), { headers: { authorization: 'Bearer ' + ownerJwt }, redirect: 'error', signal: AbortSignal.timeout(5000), }) assert.equal(response.status, 200) const expected = await response.json() assert.equal(expected.enabled, false) assert.deepEqual(await call('mm_logs_settings_get'), expected) }) return null } }, ] } assert.deepEqual(await resumeMcpSteps(config), { status: 'failed', step: 'mm_logs_settings_get' }, journal) assert.deepEqual(await resumeMcpSteps(config), { status: 'passed' }, journal) return config.steps.map(step => step.id) }