Files
MikrotikManager/backend/src/modules/mcp/result-delivery.ts
T

52 lines
3.5 KiB
TypeScript

import type { CallToolResult } from "@modelcontextprotocol/server"
import { boundedToolError, boundedToolResult, MCP_CALL_RESULT_BYTES, RESULT_BUDGET_META, type ResultProjection } from "./result-budget.js"
/** Constructed only from a registered action, never from request arguments. */
export interface RegisteredResultContract {
id: string
effect: "read" | "write" | "diagnostic"
hasRead: boolean
hasPrepare: boolean
}
export function registeredResultProjection(contract: RegisteredResultContract): ResultProjection | undefined {
// Match runtime ordering: a read closure wins over prepare if both exist.
if (!contract.hasRead && contract.hasPrepare) return "plan"
if (!contract.hasRead) return undefined
if (contract.id === "changes.apply") return contract.effect === "write" ? "operation" : undefined
if (contract.id === "operations.read") return contract.effect === "read" ? "operation" : undefined
if (contract.id === "changes.cancel") return contract.effect === "read" ? "cancel-plan" : undefined
if (contract.id === "servers.probes.cancel") return contract.effect === "write" ? "cancel-probe" : undefined
return contract.effect === "read" ? "read" : undefined
}
/**
* Only invocation errors enter invocationError. Delivery is outside that catch:
* serialization/size failure cannot turn a known applied result into a failed call.
* The impossible-for-current-source receipt-required branch is a delivery-only
* invariant notice, with no invented execution state, isError, counts or retry.
*/
export async function deliverRegisteredToolResult(contract: RegisteredResultContract, invoke: () => Promise<unknown>,
invocationError: (error: unknown) => CallToolResult, onBytes?: (bytes: number) => void, readByteLimit?: number): Promise<CallToolResult> {
const projection = registeredResultProjection(contract)
if (!projection) return boundedToolError("UNSUPPORTED_CAPABILITY", "Для действия не определена безопасная форма квитанции; выполнение не начато")
// Only a trusted read may have a smaller delivery allowance. Fail before invoke.
if (readByteLimit !== undefined && (projection !== "read" || !Number.isSafeInteger(readByteLimit) || readByteLimit < 8192 || readByteLimit > MCP_CALL_RESULT_BYTES)) {
return boundedToolError("UNSUPPORTED_CAPABILITY", "Допуск размера ответа чтения не подтверждён; выполнение не начато")
}
let output: unknown
try { output = await invoke() } catch (error) {
const result = invocationError(error)
onBytes?.(Buffer.byteLength(JSON.stringify(result)))
return result
}
const decision = boundedToolResult(output, projection, undefined, readByteLimit)
const result: CallToolResult = decision.kind === "result" ? decision.result : {
content: [{ type: "text", text: "Квитанция не доставлена из-за нарушения внутреннего формата. Это не новый исход операции. Не повторяйте изменение; проверьте существующую операцию в приложении." }],
_meta: { [RESULT_BUDGET_META]: { version: 1, detailsOmitted: true, reason: decision.reason, automaticReplay: false, receiptUnavailable: true } },
}
// Resource accounting callback is intentionally outside invocationError too.
// Existing response owner can reject a read; it cannot rewrite an effectful call.
onBytes?.(Buffer.byteLength(JSON.stringify(result)))
return result
}