596 lines
51 KiB
TypeScript
596 lines
51 KiB
TypeScript
import { registerIpsecServerDeleteActions } from "./ipsec-server-delete-actions.js"
|
|
import { registerIpsecServerInitActions } from "./ipsec-server-init-actions.js"
|
|
import { registerIpsecRevisionActions } from "./ipsec-revision-actions.js"
|
|
import { registerWireguardRevisionActions } from "./wireguard-revision-actions.js"
|
|
import { registerFlowHostKeysActions } from "./flow-host-keys-actions.js"
|
|
import { registerIpsecUserCreateActions } from "./ipsec-user-create-actions.js"
|
|
import { registerFlowSettingsActions } from "./flow-settings-actions.js"
|
|
import { registerIpsecExistingCertificateExportActions } from "./ipsec-existing-certificate-export-registration.js"
|
|
import { registerIpsecUserUpdateActions } from "./ipsec-user-update-actions.js"
|
|
import { prepareIpsecNativeWrite } from "./ipsec-native-write-actions.js"
|
|
import { isIP } from "node:net"
|
|
import { setTimeout as sleep } from "node:timers/promises"
|
|
import { logsFollowCancellation } from "./logs-follow-cancellation.js"
|
|
import { z } from "zod"
|
|
import { logFiltersSchema, logSettingsPatchSchema } from "@mmapp/contracts"
|
|
import { appUserCreateSchema, appUserUpdateSchema, appUserRoleSchema, sectionPermSchema, serverPermSchema, userBindingCreateSchema } from "@mmapp/contracts/users"
|
|
import type { McpOperationDescriptor } from "@mmapp/contracts/mcp"
|
|
import { hasPermission } from "../../lib/permissions.js"
|
|
import { assertOperationReplayScope, findOperationReplayTombstone, operationHistoryExpired } from "./operation-replay-tombstones.js"
|
|
import { pool } from "../../db/index.js"
|
|
import { getServerReadById } from "../servers/service/servers-service.js"
|
|
import { listUsers, getUserById, listInterfaceCatalog, getInterfaceCatalogState, validateUserBindingCreate, UsersServiceError } from "../users/service/users-service.js"
|
|
import { getLogSettings } from "../../services/router-logs-collector.js"
|
|
import { readLogPage, readLogSummary, readLogContext, readLogEntry } from "../../services/router-logs-query.js"
|
|
import { logWhere } from "../../services/router-logs-model.js"
|
|
import { readBoundedLogExportRows, serializeLogExport, withLogExportSlot, LogExportLimitError, LogExportBusyError } from "../../services/router-logs-export.js"
|
|
import { assertLogExportAccess, createLogExportArtifact, registerLogArtifactActions } from "./log-artifacts.js"
|
|
import { registerAlertsOutboxActions } from "./alerts-outbox-actions.js"
|
|
import { gatewayReferencesTable, isDynamicRouteInsideTable } from "../../services/routing-gateway-reference.js"
|
|
import { readLogStream } from "../../services/router-logs-query.js"
|
|
import { subscribeLogDevice } from "../../services/router-logs-collector.js"
|
|
import { rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfPassiveUpdate } from "./resources.js"
|
|
import { registerMcpOperation, listMcpOperations } from "./registry.js"
|
|
import { accessGeneration, decryptSecret, encryptSecret, fingerprint, McpError, redact } from "./security.js"
|
|
import { validatePrincipal } from "./store.js"
|
|
import type { McpAction, ActionContext, ChangeEvidence } from "./action-types.js"
|
|
import { registerRoutingActions } from "./routing-actions.js"
|
|
import { registerApplicationActions } from "./application-actions.js"
|
|
import { registerProbeActions } from "./probe-actions.js"
|
|
import { registerServerProbeActions } from "./server-probe-registration.js"
|
|
import { registerServerPollAction } from "./server-poll-registration.js"
|
|
import { registerSpeedTestActions } from "./speed-test-actions.js"
|
|
import { registerManualApiPingActions } from "./manual-api-ping-actions.js"
|
|
import { registerManualUptimeActions } from "./manual-uptime-actions.js"
|
|
import { registerManualPingGroupActions } from "./manual-ping-group-actions.js"
|
|
import { registerManualTrafficActions } from "./manual-traffic-actions.js"
|
|
import { registerTrafficLiveActions } from "./traffic-live-actions.js"
|
|
import { registerTrafficHistoryActions } from "./traffic-history-actions.js"
|
|
import { registerSidebarCountsActions } from "./sidebar-counts-actions.js"
|
|
import { registerTrafficUserHistoryActions } from "./traffic-user-history-actions.js"
|
|
import { registerBgpExportActions } from "./bgp-export-actions.js"
|
|
import { registerBgpPrefixActions } from "./bgp-prefix-actions.js"
|
|
import { registerFilterWriteActions } from "./filter-write-actions.js"
|
|
import { registerFlowCatalogActions } from "./flow-catalog-actions.js"
|
|
import { registerFlowAnalyticsActions } from "./flow-analytics-actions.js"
|
|
import { registerFlowMapActions } from "./flow-map-actions.js"
|
|
import { registerFlowLiveActions } from "./flow-live-actions.js"
|
|
import { registerAcmeTestActions } from "./acme-test-actions.js"
|
|
import { registerAcmeSettingsActions } from "./acme-settings-actions.js"
|
|
import { registerGeoipUpdateActions } from "./geoip-update-actions.js"
|
|
import { registerBackupDownloadActions } from "./backup-download-actions.js"
|
|
import { registerFlowOverlayActions } from "./flow-overlay-actions.js"
|
|
import { registerWireguardInterfaceCreateActions } from "./wireguard-interface-create-actions.js"
|
|
import { registerWireguardPeerCreateActions } from "./wireguard-peer-create-actions.js"
|
|
import { registerHostFilesActions } from "./host-files-actions.js"
|
|
import { registerTelegramSettingsActions } from "./telegram-settings-actions.js"
|
|
import { registerTelegramTestActions } from "./telegram-test-actions.js"
|
|
import { registerOspfStateActions } from "./ospf-state-actions.js"
|
|
import { registerOspfRouteProofActions } from "./ospf-route-proof-actions.js"
|
|
import { registerLegacyOspfActions } from "./ospf-legacy-actions.js"
|
|
import { prepareWireguardInterfaceDeletion, registerWireguardInterfaceDeleteActions } from "./wireguard-interface-delete-actions.js"
|
|
import { prepareWireguardPeerUpdate, registerWireguardPeerUpdateActions } from "./wireguard-peer-update-actions.js"
|
|
import { wireguardPeerNativeUpdate } from "../../services/wireguard-peer-update.js"
|
|
import { prepareWireguardPeerDeletion, registerWireguardPeerDeleteActions } from "./wireguard-peer-delete-actions.js"
|
|
import { registerFirewallActions } from "./firewall-actions.js"
|
|
import { registerGreMutationActions } from "./gre-mutation-actions.js"
|
|
import { registerGreRevisionActions } from "./gre-revision-actions.js"
|
|
import { prepareGreNativeChange, registerGreNativeServices } from "./gre-native-actions.js"
|
|
import { registerVpnCatalogActions } from "./vpn-catalog-actions.js"
|
|
import { registerEvoBgpActions } from "./evobgp-actions.js"
|
|
import { registerRoutingProfileActions } from "./routing-profiles.js"
|
|
import { registerRoutingControls } from "./routing-controls.js"
|
|
import { registerLifecycleActions } from "./lifecycle-actions.js"
|
|
import { registerRecoveryActions } from "./recovery-actions.js"
|
|
import { registerPathActions } from "./path-verification.js"
|
|
import { registerDatabaseRestore } from "./database-restore.js"
|
|
import { registerDatabaseBackupActions } from "./database-backup-actions.js"
|
|
import { registerTerminalDiagnosticActions } from "./terminal-diagnostic-actions.js"
|
|
import { registerEventsBatchActions } from "./events-batch-actions.js"
|
|
import { registerGlobalReconciliationActions } from "./global-reconciliation-actions.js"
|
|
import { registerWireguardInterfaceUpdateActions } from "./wireguard-interface-update-actions.js"
|
|
import { registerWireguardImportActions } from "./wireguard-import-actions.js"
|
|
import { registerWireguardExportActions } from "./wireguard-export-actions.js"
|
|
import { registerServerConnectionActions } from "./server-connection-actions.js"
|
|
import { prepareIpsecPeerDeletion, registerIpsecPeerDeleteActions } from "./ipsec-peer-delete-actions.js"
|
|
import { registerIpsecUserDeleteActions } from "./ipsec-user-delete-actions.js"
|
|
import { prepareNativeIpsecCertificateDeletion, registerIpsecCertificateDeleteActions } from "./ipsec-certificate-delete-actions.js"
|
|
import { prepareNativeIpsecPeerUpdate, registerIpsecPeerUpdateActions } from "./ipsec-peer-update-actions.js"
|
|
import { registerFlowPurgeActions } from "./flow-purge-actions.js"
|
|
import { registerFlowFactsRebuildActions } from "./flow-facts-rebuild-actions.js"
|
|
import { wireguardInterfaceNativeUpdate } from "../../services/wireguard-interface-update.js"
|
|
import { addRoutingDependencies } from "./routing-dependencies.js"
|
|
import { registerConfigHistory } from "./config-history.js"
|
|
import { registerDeviceCatalogActions } from "./device-catalog-actions.js"
|
|
import { registerRecursiveRecovery } from "./recursive-recovery.js"
|
|
import { registerNetworkHostActions } from "./network-host-actions.js"
|
|
import { registerBgpFilterBindingActions } from "./bgp-filter-binding-actions.js"
|
|
import { registerBgpCommunityPolicyActions } from "./bgp-community-policy-actions.js"
|
|
import { registerBridgeVlanActions, prepareGenericBridgeVlanChange } from "./bridge-vlan-actions.js"
|
|
|
|
const serverId = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
|
|
const rowId = z.string().trim().min(1).max(200)
|
|
const paging = { limit: z.number().int().min(1).max(500).default(100), offset: z.number().int().min(0).max(1000000).default(0) }
|
|
const scope = (input: Record<string, unknown>, context: ActionContext) => ({ scope: "servers" as const, serverIds: typeof input.serverId === "number" ? [input.serverId] : context.connection.policy.scope.serverIds })
|
|
const actions: McpAction[] = []
|
|
export function add(id: string, toolName: string, title: string, section: string, permission: string | readonly string[] | null, effect: McpOperationDescriptor["effect"], targetScope: McpOperationDescriptor["scope"], schema: z.ZodObject, handlers: Pick<McpAction, "read" | "prepare"> & Partial<Pick<McpAction, "target">> & { version?: number }) {
|
|
const { version = 1, ...implementationHandlers } = handlers
|
|
const operation: McpOperationDescriptor = {
|
|
id, toolName, title, section, effect, scope: targetScope, risk: effect === "read" ? "ordinary" : "dangerous",
|
|
version, implementation: "available", requiredPermissions: typeof permission === "string" ? [permission] : permission ? [...permission] : [],
|
|
annotations: { readOnlyHint: effect === "read", destructiveHint: effect === "write", idempotentHint: effect === "read", openWorldHint: true },
|
|
}
|
|
registerMcpOperation(operation)
|
|
actions.push({ operation, schema, target: targetScope === "servers" ? scope : () => ({ scope: targetScope }), ...implementationHandlers })
|
|
}
|
|
|
|
registerConfigHistory(add)
|
|
registerDeviceCatalogActions(add)
|
|
registerRecursiveRecovery(add)
|
|
registerNetworkHostActions(add)
|
|
registerBgpFilterBindingActions(add)
|
|
registerBgpCommunityPolicyActions(add)
|
|
registerBridgeVlanActions(add)
|
|
registerTrafficHistoryActions(add)
|
|
registerSidebarCountsActions(add)
|
|
registerLogArtifactActions(add)
|
|
registerWireguardExportActions(add)
|
|
registerAlertsOutboxActions(add)
|
|
registerTrafficUserHistoryActions(add)
|
|
registerBgpExportActions(add)
|
|
registerBgpPrefixActions(add)
|
|
registerFilterWriteActions(add)
|
|
|
|
for (const resource of rosResources) {
|
|
add(`ros.${resource.id}.list`, `mm_${resource.id}_list`, resource.title, resource.permission.split(":")[1], resource.permission + ":read", "read", "servers", z.object({ serverId, ...paging }).strict(), {
|
|
read: async input => {
|
|
const { client } = await routerClient(Number(input.serverId)), raw = await client.get<unknown>(resource.path)
|
|
const rows = Array.isArray(raw) ? raw : [raw], offset = Number(input.offset), limit = Number(input.limit)
|
|
return { items: redact(rows.slice(offset, offset + limit)), total: rows.length, nextOffset: offset + limit < rows.length ? offset + limit : null, observedAt: new Date().toISOString() }
|
|
},
|
|
})
|
|
if (resource.readOnly) continue
|
|
for (const action of ["create", "update", "delete"] as const) {
|
|
if (action === "create" && !resource.create || action === "delete" && !resource.remove) continue
|
|
const schema = action === "create" || ["ip_settings", "ipv6_settings"].includes(resource.id)
|
|
? z.object({ serverId, fields: resource.fields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
|
|
: z.object({ serverId, id: rowId.optional(), fields: resource.fields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}) }).strict()
|
|
const delegated = resource.id === "wireguard" && action !== "create" || resource.id === "wireguard_peer" || resource.id === "gre" && action !== "create" || resource.id === "ipsec_peer" && action !== "create" || resource.id === "certificate" && action === "delete" || resource.id === "container" && action === "delete"
|
|
const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard"].includes(resource.id) ? 3 : 2) : resource.id === "ipsec_peer" || resource.id === "certificate" && action === "delete" ? 2 : resource.id === "wireguard" && action === "update" ? 3 : resource.id === "ospf_template" && action !== "delete" || resource.id === "wireguard_peer" || resource.id === "wireguard" ? 2 : 1
|
|
add(`ros.${resource.id}.${action}`, `mm_${resource.id}_${action}_plan`, `${resource.title}: ${action}`, resource.permission.split(":")[1], resource.id === "certificate" && action === "update" ? ["mm:certificates:write", "mm:network:write"] : resource.permission + ":write", "write", "servers", schema, {
|
|
version: resource.id === "ipsec_peer" ? (action === "create" ? 5 : 3) : resource.id === "certificate" ? (action === "update" ? 4 : 3) : previousVersion + (delegated ? 0 : 1) + (resource.id === "ospf_template" ? 1 : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (["bridge", "bridge_port", "bridge_vlan"].includes(resource.id) ? 1 : 0),
|
|
prepare: async (input, context) => {
|
|
if (resource.id === "vrf" && input.productionAdmission !== true) throw new McpError("UNSUPPORTED_CAPABILITY", "VRF требует явного productionAdmission:true для проверенного native executor; raw план недоступен", 409)
|
|
const sid = Number(input.serverId), id = input.id as string | undefined
|
|
const fields = validateRosStep(resource, action, input.fields, id)
|
|
if (resource.id === "ipsec_peer" && action === "create") return prepareIpsecNativeWrite("ros.ipsec_peer.create", sid, undefined, input.fields, context)
|
|
if (resource.id === "certificate" && action === "update") return prepareIpsecNativeWrite("ros.certificate.update", sid, id, input.fields, context)
|
|
if (resource.id === "ipsec_peer" && action === "delete") return prepareIpsecPeerDeletion(sid, String(id), context, false)
|
|
if (resource.id === "ipsec_peer" && action === "update") return prepareNativeIpsecPeerUpdate(sid, String(id), input.fields, context)
|
|
if (resource.id === "certificate" && action === "delete") return prepareNativeIpsecCertificateDeletion(sid, String(id), context)
|
|
if (resource.id === "wireguard" && action === "delete") return prepareWireguardInterfaceDeletion(sid, String(id), context, false)
|
|
if (resource.id === "wireguard_peer" && action === "delete") return prepareWireguardPeerDeletion(sid, String(id), context)
|
|
if (resource.id === "wireguard_peer" && action === "update") return prepareWireguardPeerUpdate(sid, String(id), wireguardPeerNativeUpdate(input.fields as Record<string, unknown>), context)
|
|
if (resource.id === "wireguard" && action === "update") return findAction("mm_wireguard_interface_edit_plan").prepare!({ serverId: sid, interfaceId: String(id), patch: wireguardInterfaceNativeUpdate(input.fields as Record<string, unknown>) }, context)
|
|
if (resource.id === "wireguard_peer" && action === "create") {
|
|
const { interface: parentReference, ...peerFields } = fields
|
|
const parents = (await readRosSnapshot(sid, "wireguard")).rows.filter(row => row[".id"] === parentReference || row.name === parentReference)
|
|
if (parents.length !== 1 || typeof parents[0].name !== "string") throw new McpError("STATE_CONFLICT", "Родитель WireGuard не найден однозначно", 409)
|
|
return findAction("mm_wireguard_peer_add_plan").prepare!({ serverId: sid, interfaceName: parents[0].name, ...wireguardPeerNativeUpdate(peerFields) }, context)
|
|
}
|
|
if (resource.id === "container" && action === "delete") return findAction("mm_container_remove_plan").prepare!({ serverId: sid, id }, context)
|
|
if (resource.id === "gre" && action !== "create") return prepareGreNativeChange(sid,action,id,input.fields)
|
|
for (const key of ["address", "dst-address"] as const) {
|
|
if (fields[key]) {
|
|
const [ip, prefix] = fields[key].split("/")
|
|
const expected = resource.id.startsWith("ipv6") ? 6 : 4
|
|
if (isIP(ip) !== expected || prefix !== undefined && (!/^\d+$/.test(prefix) || Number(prefix) > (expected === 6 ? 128 : 32))) throw new McpError("INVALID_INPUT", "Некорректный IP-префикс", 400)
|
|
}
|
|
}
|
|
const before = await readRosSnapshot(sid, resource.id)
|
|
const current = action === "create" ? undefined : id ? before.rows.find(row => row[".id"] === id) : before.rows[0]
|
|
if (action !== "create" && !current) throw new McpError("NOT_FOUND", "Объект RouterOS не найден", 404)
|
|
if (action !== "create" && (current?.dynamic === "true" || current?.builtin === "true" || current?.default === "true")) throw new McpError("PROTECTED_OBJECT", "Системный или динамический объект нельзя изменять")
|
|
if (resource.id.endsWith("settings") && Object.keys(fields).some(key => !(key in (current ?? {})))) throw new McpError("UNSUPPORTED_CAPABILITY", "Устройство не подтвердило поддержку свойства", 409)
|
|
const references: ChangeEvidence["objects"] = [{ kind: resource.id, id: id ?? String(fields.name ?? "new"), serverId: sid }]
|
|
if (resource.id.endsWith("settings")) references.push({ kind: resource.id, id: "singleton", serverId: sid })
|
|
const snapshots = [before]
|
|
if (["ospf_instance", "ospf_area", "ospf_template", "bfd_configuration", "bgp_instance", "bgp_connection", "vrf"].includes(resource.id)) await addRoutingDependencies(sid, resource.id, action, current, fields, snapshots, references)
|
|
if (["ipv4_route", "ipv6_route", "routing_rule", "bgp_connection"].includes(resource.id)) {
|
|
const tables = await readRosSnapshot(sid, "routing_table")
|
|
snapshots.push(tables)
|
|
const tableNames = new Set([current?.["routing-table"], fields["routing-table"], resource.id === "routing_rule" ? current?.table : undefined, resource.id === "routing_rule" ? fields.table : undefined].filter(value => typeof value === "string" && value.length))
|
|
if (["ipv4_route", "ipv6_route"].includes(resource.id) && !tableNames.size) tableNames.add("main")
|
|
for (const name of tableNames) {
|
|
const table = tables.rows.find(row => row.name === name)
|
|
if (!table || table.disabled === "true") throw new McpError("STATE_CONFLICT", "Таблица маршрутизации отсутствует или отключена", 409)
|
|
references.push({ kind: "routing_table", id: String(table[".id"]), serverId: sid })
|
|
}
|
|
}
|
|
if (resource.id === "routing_table" && action !== "create" && (action === "delete" || fields.name && fields.name !== current?.name || fields.disabled === "true")) {
|
|
// Keep exact dependency snapshots in the sealed plan: a route/rule added
|
|
// after approval must also prevent deleting or renaming its table.
|
|
const tableName = String(current?.name ?? "")
|
|
if (!tableName) throw new McpError("STATE_UNAVAILABLE", "Не подтверждено имя таблицы маршрутизации", 409)
|
|
for (const dependency of ["ipv4_route", "ipv6_route", "routing_rule", "vrf", "ospf_instance", "bgp_instance", "bgp_connection"]) {
|
|
const snapshot = await readRosSnapshot(sid, dependency)
|
|
snapshots.push(snapshot)
|
|
let inUse: boolean
|
|
try { inUse = snapshot.rows.some(row => row["routing-table"] === tableName || dependency === "routing_rule" && row.table === tableName || dependency === "vrf" && row.name === tableName || ["ipv4_route", "ipv6_route"].includes(dependency) && gatewayReferencesTable(row.gateway, [tableName, String(current?.[".id"])])) }
|
|
catch { throw new McpError("STATE_UNAVAILABLE", "Не подтверждены gateway dependencies таблицы", 409) }
|
|
if (inUse) throw new McpError("STATE_CONFLICT", "Таблица используется маршрутом, gateway, правилом, VRF или протоколом маршрутизации", 409)
|
|
}
|
|
}
|
|
// Inventory proves references and captures dependency changes between preview and apply.
|
|
const interfaceResources = ["ethernet", "bridge", "vlan", "gre", "wireguard", "vxlan"]
|
|
if ([...interfaceResources, "bridge_port", "bridge_vlan", "vrf", "ipv4_address", "ipv6_address", "ospf_template", "bfd_configuration"].includes(resource.id)) {
|
|
for (const dependency of [...interfaceResources, "bridge_port", "bridge_vlan", "ipv4_address", "ipv6_address", "vrf"]) {
|
|
if (dependency === resource.id || snapshots.some(snapshot => snapshot.resource === dependency)) continue
|
|
try { snapshots.push(await readRosSnapshot(sid, dependency)) }
|
|
catch { throw new McpError("STATE_CONFLICT", "Не удалось подтвердить зависимости интерфейса", 409) }
|
|
}
|
|
const inventory = snapshots.filter(snapshot => interfaceResources.includes(snapshot.resource)).flatMap(snapshot => snapshot.rows.map(row => ({ resource: snapshot.resource, row })))
|
|
const interfaces = new Set(inventory.map(item => String(item.row.name)))
|
|
for (const field of ["interface", "bridge"] as const) if (fields[field] && !interfaces.has(fields[field])) throw new McpError("INVALID_INPUT", "Неизвестный родительский интерфейс", 400)
|
|
const vrfMembers = ["vrf", "ospf_template", "bfd_configuration"].includes(resource.id) ? [current?.interfaces, fields.interfaces].filter((value): value is string => typeof value === "string" && !["all", "none"].includes(value)).flatMap(value => value.split(",")) : []
|
|
if (resource.id === "vrf" && fields.interfaces !== undefined && (!fields.interfaces.trim() || fields.interfaces.split(",").includes("all"))) throw new McpError("INVALID_INPUT", "Выберите конкретные интерфейсы VRF или none", 400)
|
|
const referenced = [current?.interface, current?.bridge, fields.interface, fields.bridge, ...vrfMembers, ...(resource.id === "bridge_vlan" ? [fields.tagged, fields.untagged].filter(Boolean).flatMap(value => value.split(",")) : [])].filter((value): value is string => typeof value === "string" && value.length > 0).map(value => value.trim())
|
|
for (const name of new Set(referenced)) {
|
|
const parent = inventory.find(item => item.row.name === name)
|
|
if (!parent) throw new McpError("INVALID_INPUT", "Требуется явный существующий интерфейс", 400)
|
|
references.push({ kind: parent.resource, id: String(parent.row[".id"]), serverId: sid })
|
|
}
|
|
if (resource.id === "bridge_vlan") {
|
|
for (const iface of [fields.tagged, fields.untagged].filter(Boolean).flatMap(value => value.split(","))) if (!interfaces.has(iface.trim())) throw new McpError("INVALID_INPUT", "Неизвестный участник VLAN", 400)
|
|
if (fields.tagged?.split(",").some(iface => fields.untagged?.split(",").includes(iface))) throw new McpError("INVALID_INPUT", "Порт не может быть одновременно tagged и untagged", 400)
|
|
}
|
|
const existingName = String(current?.name ?? "")
|
|
if ((action === "delete" || fields.name && fields.name !== existingName) && existingName) {
|
|
if (interfaceResources.includes(resource.id)) for (const dependency of ["ospf_template", "bfd_configuration"]) snapshots.push(await readRosSnapshot(sid, dependency))
|
|
const dependent = snapshots.filter(snapshot => snapshot.resource !== resource.id).some(snapshot => snapshot.rows.some(row => {
|
|
if (resource.id === "vrf" && ["ipv4_route", "ipv6_route"].includes(snapshot.resource) && isDynamicRouteInsideTable(row, [existingName, String(current?.[".id"])])) return false
|
|
return Object.values(row).some(value => typeof value === "string" && value.split(",").includes(existingName))
|
|
}))
|
|
if (dependent) throw new McpError("STATE_CONFLICT", "Объект используется: сначала подготовьте явное изменение зависимостей", 409)
|
|
}
|
|
}
|
|
const linkedVlan = await prepareGenericBridgeVlanChange({ serverId: sid, resource: resource.id, action, id, fields }, context)
|
|
if (linkedVlan) {
|
|
const captured = new Map(snapshots.map(snapshot => [snapshot.resource, snapshot]))
|
|
for (const snapshot of linkedVlan.snapshots) {
|
|
const previous = captured.get(snapshot.resource)
|
|
if (previous && (previous.fingerprint !== snapshot.fingerprint || previous.sourceProof !== snapshot.sourceProof)) throw new McpError("STATE_CONFLICT", "Зависимости VLAN изменились во время подготовки", 409)
|
|
captured.set(snapshot.resource, snapshot)
|
|
}
|
|
const objects = new Map([...references, ...linkedVlan.objects].map(object => [`${object.serverId}/${object.kind}/${object.id}`, object]))
|
|
return { ...linkedVlan, snapshots: [...captured.values()], objects: [...objects.values()] }
|
|
}
|
|
const placeBeforeId = resource.id === "vrf" && action === "create" ? before.rows[0]?.[".id"] : undefined
|
|
if (resource.id === "vrf" && action === "create" && typeof placeBeforeId !== "string") throw new McpError("STATE_CONFLICT", "Не подтверждён порядок существующих VRF", 409)
|
|
return { target: { scope: "servers", serverIds: [sid] }, objects: references, snapshots,
|
|
...(resource.id === "vrf" && input.productionAdmission === true ? { vrfProductionAdmission: true as const } : {}),
|
|
steps: splitOspfPassiveUpdate({ serverId: sid, resource: resource.id, action, id, fields, ...(typeof placeBeforeId === "string" ? { placeBeforeId } : {}) }).map(step => ({ kind: "ros" as const, step })),
|
|
requiresHuman: true,
|
|
warnings: ["Нативное изменение может затронуть управление устройством и требует подтверждения человеком.", "Автоматическое каскадное изменение зависимостей не выполняется.", ...(resource.id === "vrf" && action === "delete" ? ["При удалении VRF RouterOS может удалить автоматический IPv6 link-local и его connected-маршрут пустого bridge; статические адреса сохраняются."] : []), ...(placeBeforeId ? [`VRF создаётся перед записью ${placeBeforeId}; порядок определяет принадлежность интерфейсов.`] : [])],
|
|
}
|
|
},
|
|
})
|
|
}
|
|
}
|
|
|
|
for (const definition of [
|
|
{ id: "interfaces.update", tool: "mm_interfaces_update_plan", title: "План изменения интерфейса", resources: ["ethernet", "bridge", "bridge_port", "bridge_vlan", "vlan", "gre", "wireguard", "vxlan"] },
|
|
{ id: "firewall.update", tool: "mm_firewall_rule_update_plan", title: "План изменения правила firewall", resources: ["ip_filter", "ip_nat", "ip_mangle", "ip_raw", "ipv6_filter", "ipv6_nat", "ipv6_mangle", "ipv6_raw"] },
|
|
] as const) {
|
|
add(definition.id, definition.tool, definition.title, "network", "mm:network:write", "write", "servers", z.object({ serverId, resource: z.enum(definition.resources), id: rowId, fields: z.record(z.string().max(100), z.union([z.string().max(1000), z.number().finite(), z.boolean()])) }).strict(), {
|
|
version: definition.id === "interfaces.update" ? 5 : 2,
|
|
prepare: async (input, context) => {
|
|
const resource = resourceById(String(input.resource)), fields = resource.fields.safeParse(input.fields)
|
|
if (!fields.success) throw new McpError("INVALID_INPUT", "Поля не соответствуют типизированной схеме выбранного объекта", 400)
|
|
const handler = actions.find(action => action.operation.id === `ros.${resource.id}.update`)
|
|
if (!handler?.prepare) throw new McpError("UNSUPPORTED_CAPABILITY", "Этот объект не поддерживает изменение", 409)
|
|
return handler.prepare({ serverId: input.serverId, id: input.id, fields: fields.data }, context)
|
|
},
|
|
})
|
|
}
|
|
|
|
add("capabilities.read", "mm_capabilities_get", "Доступные возможности", "mcp", null, "read", "connection", z.object({}).strict(), {
|
|
read: async (_input, context) => ({ operations: listMcpOperations().filter(operation => operation.implementation === "available" && context.connection.policy.scope.operationIds.includes(operation.id)), schemaVersion: 1 }),
|
|
})
|
|
add("servers.list", "mm_servers_list", "Серверы", "servers", "mm:servers:read", "read", "servers", z.object({ serverId: serverId.optional(), ...paging }).strict(), {
|
|
read: async (input, context) => {
|
|
const ids = typeof input.serverId === "number" ? [input.serverId] : context.connection.policy.scope.serverIds
|
|
const { rows } = await pool.query<{ id: number }>("SELECT id FROM servers WHERE id=ANY($1::bigint[]) ORDER BY id LIMIT $2 OFFSET $3", [ids, input.limit, input.offset])
|
|
return { items: await Promise.all(rows.map(row => getServerReadById(Number(row.id)))), observedAt: new Date().toISOString() }
|
|
},
|
|
})
|
|
function scopedUser(user: Awaited<ReturnType<typeof getUserById>> | null, context: ActionContext) {
|
|
if (!user) throw new McpError("NOT_FOUND", "Пользователь не найден", 404)
|
|
const allowed = context.connection.policy.scope.serverIds
|
|
const hidden = user.bindings.some(binding => !allowed.includes(binding.serverId)) || user.servers.some(server => !allowed.includes(Number(server.serverId)))
|
|
return { ...user, bindings: user.bindings.filter(binding => allowed.includes(binding.serverId)), servers: user.servers.filter(server => allowed.includes(Number(server.serverId))), incomplete: hidden }
|
|
}
|
|
add("users.list", "mm_users_list", "Пользователи", "users", "mm:users:read", "read", "global", z.object(paging).strict(), {
|
|
read: async (input, context) => ({ items: (await listUsers()).slice(Number(input.offset), Number(input.offset) + Number(input.limit)).map(user => scopedUser(user, context)) }),
|
|
})
|
|
add("users.get", "mm_users_get", "Пользователь по ID", "users", "mm:users:read", "read", "global", z.object({ id: rowId }).strict(), {
|
|
read: async (input, context) => ({ user: scopedUser(await getUserById(String(input.id)), context) }),
|
|
})
|
|
add("users.interfaces.read", "mm_user_interfaces_list", "Каталог интерфейсов для привязок пользователей", "users", "mm:users:read", "read", "servers", z.object({ serverId }).strict(), {
|
|
read: async input => ({ interfaces: await listInterfaceCatalog(Number(input.serverId)) }),
|
|
})
|
|
add("users.interfaces.state", "mm_user_interfaces_state_get", "Состояние каталога интерфейсов для привязок", "users", "mm:users:read", "read", "servers", z.object({ serverId }).strict(), {
|
|
read: async input => getInterfaceCatalogState(Number(input.serverId)),
|
|
})
|
|
for (const action of ["create", "update", "delete", "binding_add", "binding_remove"] as const) {
|
|
const schema = action === "create" ? z.object({ user: appUserCreateSchema.omit({ role: true, sections: true, servers: true }).strict() }).strict()
|
|
: action === "update" ? z.object({ id: rowId, user: appUserUpdateSchema.omit({ role: true, sections: true, servers: true }).strict() }).strict()
|
|
: action === "binding_add" ? z.object({ id: rowId, binding: userBindingCreateSchema }).strict()
|
|
: action === "binding_remove" ? z.object({ id: rowId, bindingId: rowId }).strict()
|
|
: z.object({ id: rowId }).strict()
|
|
add(`users.${action}`, `mm_users_${action}_plan`, `Пользователи: ${action}`, "users", "mm:users:write", "write", "global", schema, {
|
|
prepare: async (input, context) => {
|
|
const before = input.id ? await getUserById(String(input.id)) : null
|
|
if (input.id && scopedUser(before, context).incomplete) throw new McpError("SERVER_DENIED", "Есть зависимости за пределами доступа")
|
|
const user = input.user as { servers?: { serverId: string }[] } | undefined
|
|
const binding = input.binding as { serverId?: number } | undefined
|
|
const ids = [...new Set([...(user?.servers ?? []).map(server => Number(server.serverId)), ...(binding?.serverId ? [binding.serverId] : []),
|
|
...(before?.bindings ?? []).map(binding => binding.serverId), ...(before?.servers ?? []).map(server => Number(server.serverId))])]
|
|
if (ids.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Сервер не разрешён")
|
|
if (action === "binding_remove" && !before?.bindings.some(binding => binding.id === input.bindingId)) {
|
|
throw new McpError("NOT_FOUND", "Привязка не найдена", 404)
|
|
}
|
|
if (action === "binding_add") {
|
|
try {
|
|
await validateUserBindingCreate(String(input.id), userBindingCreateSchema.parse(input.binding), { signal: context.signal })
|
|
} catch (error) {
|
|
if (error instanceof UsersServiceError) {
|
|
if (error.status === 409) throw new McpError("STATE_CONFLICT", error.message, 409)
|
|
if (error.status === 400) throw new McpError("INVALID_INPUT", error.message, 400)
|
|
if (error.status === 404) throw new McpError("NOT_FOUND", error.message, 404)
|
|
}
|
|
throw error
|
|
}
|
|
}
|
|
return { target: { scope: "global" }, objects: [{ kind: "user", id: String(input.id ?? "new") }, ...ids.map(id => ({ kind: "server", id: String(id), serverId: id }))], snapshots: [], before,
|
|
steps: [{ kind: "service", service: `users.${action}`, input }], warnings: ["Изменение /users не меняет JWT-права портала."] }
|
|
},
|
|
})
|
|
}
|
|
|
|
add("users.permissions.update", "mm_users_permissions_update_plan", "Роль и права каталога /users", "users", "mm:settings:admin", "write", "global", z.object({ id: rowId, permissions: z.object({ role: appUserRoleSchema.optional(), sections: z.array(sectionPermSchema.strict()).max(100).optional(), servers: z.array(serverPermSchema.strict()).max(1000).optional() }).strict().refine(value => Object.keys(value).length > 0, "Нет изменений прав") }).strict(), {
|
|
prepare: async (input, context) => {
|
|
const before = await getUserById(String(input.id)), visible = scopedUser(before, context)
|
|
if (visible.incomplete) throw new McpError("SERVER_DENIED", "Права пользователя затрагивают скрытые серверы")
|
|
const permissions = input.permissions as { servers?: { serverId: string }[] }
|
|
const serverIds = [...new Set([...(before?.servers ?? []).map(server => Number(server.serverId)), ...(before?.bindings ?? []).map(binding => binding.serverId), ...(permissions.servers ?? []).map(server => Number(server.serverId))])]
|
|
if (serverIds.some(serverId => !Number.isSafeInteger(serverId) || !context.connection.policy.scope.serverIds.includes(serverId))) throw new McpError("SERVER_DENIED", "Назначаемые права выходят за область подключения")
|
|
if (serverIds.length && (await pool.query("SELECT id FROM servers WHERE id=ANY($1::bigint[])", [serverIds])).rows.length !== serverIds.length) throw new McpError("NOT_FOUND", "Назначаемый сервер отсутствует", 404)
|
|
return { target: { scope: "global" }, objects: [{ kind: "user", id: String(input.id) }, ...serverIds.map(serverId => ({ kind: "server", id: String(serverId), serverId }))], snapshots: [], before, requiresHuman: true, steps: [{ kind: "service", service: "users.update", input: { id: input.id, user: input.permissions } }], warnings: ["Роль и права относятся к каталогу /users и не изменяют JWT или аккаунты портала."] }
|
|
},
|
|
})
|
|
|
|
const logInput = z.object({ serverId: serverId.optional(), from: z.string().datetime({ offset: true }).optional(), to: z.string().datetime({ offset: true }).optional(),
|
|
levels: z.array(z.enum(["critical", "error", "warning", "info", "debug", "unknown"])).max(6).default([]), topics: z.array(z.string().max(100)).max(30).default([]),
|
|
q: z.string().max(500).default(""), preset: z.enum(["", "login-failure", "interfaces", "routing", "firewall"]).default(""),
|
|
limit: z.number().int().min(1).max(200).default(100), cursor: z.string().max(3000).optional(),
|
|
}).strict()
|
|
function logFilters(input: Record<string, unknown>, context: ActionContext) {
|
|
return { ...logFiltersSchema.parse({ ...input, levels: (input.levels as string[]).join(","), topics: (input.topics as string[]).join(",") }), allowedServerIds: context.connection.policy.scope.serverIds }
|
|
}
|
|
add("logs.query", "mm_logs_query", "История логов", "logs", "mm:servers:read", "read", "servers", logInput, {
|
|
read: async (input, context) => {
|
|
const generation = await accessGeneration()
|
|
let filters: ReturnType<typeof logFilters>
|
|
let cursor: string | undefined, watermark: string | undefined
|
|
if (input.cursor) {
|
|
try {
|
|
const state = JSON.parse(await decryptSecret(String(input.cursor))) as { generation: string; scope: string; cursor: string; watermark: string; from: string }
|
|
filters = logFilters({ ...input, from: input.from ?? state.from }, context)
|
|
if (state.generation !== generation || state.scope !== fingerprint({ filters, connection: context.connection.id })) throw new Error("cursor")
|
|
cursor = state.cursor; watermark = state.watermark
|
|
} catch { throw new McpError("RESET_REQUIRED", "Курсор устарел или относится к другим фильтрам", 409) }
|
|
} else filters = logFilters(input, context)
|
|
const result = await readLogPage(filters, { cursor, watermark, limit: Number(input.limit) })
|
|
return { ...result, nextCursor: result.nextCursor ? await encryptSecret(JSON.stringify({ generation, scope: fingerprint({ filters, connection: context.connection.id }), cursor: result.nextCursor, watermark: result.watermark, from: filters.from })) : null }
|
|
},
|
|
})
|
|
add("logs.summary", "mm_logs_summary_get", "Статистика логов", "logs", "mm:servers:read", "read", "servers", logInput, {
|
|
read: async (input, context) => { const { settings: _settings, ...summary } = await readLogSummary(logFilters(input, context)); return summary },
|
|
})
|
|
for (const context of [false, true]) add(context ? "logs.context" : "logs.get", context ? "mm_logs_context_get" : "mm_logs_get", "Запись журнала", "logs", "mm:servers:read", "read", "servers", z.object({ serverId, id: z.string().regex(/^\d{1,20}$/) }).strict(), {
|
|
read: async input => {
|
|
const entry = await readLogEntry(String(input.id))
|
|
if (!entry || entry.serverId !== input.serverId) throw new McpError("NOT_FOUND", "Событие не найдено", 404)
|
|
return context ? readLogContext(String(input.id)) : entry
|
|
},
|
|
})
|
|
add("logs.follow", "mm_logs_follow", "Новые события", "logs", "mm:servers:read", "read", "servers", logInput.safeExtend({ serverId, limit: logInput.shape.limit.default(200), cursor: z.string().max(8192).optional(), waitSeconds: z.number().int().min(0).max(30).default(30) }), {
|
|
read: async (input, context) => {
|
|
const maintenance = context.logsFollowMaintenance
|
|
const signal = context.signal
|
|
const waitSignal = maintenance && signal ? AbortSignal.any([maintenance, signal]) : maintenance ?? signal
|
|
const assertActive = () => { const failure = logsFollowCancellation(maintenance, signal); if (failure) throw failure }
|
|
assertActive()
|
|
const { server } = await routerClient(Number(input.serverId)); void server
|
|
assertActive()
|
|
const release = subscribeLogDevice(Number(input.serverId)), until = Date.now() + Number(input.waitSeconds) * 1000
|
|
try {
|
|
const generation = await accessGeneration()
|
|
let filters: ReturnType<typeof logFilters>
|
|
let cursor = "0"
|
|
if (input.cursor) {
|
|
try {
|
|
const saved = JSON.parse(await decryptSecret(String(input.cursor)))
|
|
filters = logFilters({ ...input, from: input.from ?? saved.from }, context)
|
|
if (saved.kind !== "follow" || saved.generation !== generation || saved.scope !== fingerprint({ filters, connection: context.connection.id }) || !/^\d{1,20}$/.test(saved.cursor)) throw new Error("cursor")
|
|
cursor = saved.cursor
|
|
} catch { throw new McpError("RESET_REQUIRED", "Курсор follow устарел или относится к другим фильтрам", 409) }
|
|
} else {
|
|
filters = logFilters(input, context)
|
|
cursor = (await pool.query("SELECT COALESCE(max(id),0)::text AS cursor FROM router_log_entries WHERE server_id=$1", [input.serverId])).rows[0].cursor
|
|
}
|
|
while (true) {
|
|
assertActive()
|
|
const current = await validatePrincipal(context.principal)
|
|
assertActive()
|
|
if (current.policy.version !== context.connection.policy.version) throw new McpError("RESET_REQUIRED", "Права или область доступа изменились; начните новое чтение", 409)
|
|
const batch = await readLogStream(filters, cursor, Number(input.limit))
|
|
assertActive()
|
|
cursor = batch.cursor
|
|
if (batch.entries.length || !batch.enabled || Date.now() >= until) return { ...batch, cursor: await encryptSecret(JSON.stringify({ kind: "follow", generation, scope: fingerprint({ filters, connection: context.connection.id }), cursor, from: filters.from })) }
|
|
await sleep(1000, undefined, { signal: waitSignal })
|
|
}
|
|
} finally { release() }
|
|
},
|
|
})
|
|
add("logs.export", "mm_logs_export", "Экспорт логов", "logs", "mm:servers:read", "read", "servers", logInput.safeExtend({ format: z.enum(["csv", "json"]).default("json") }), {
|
|
read: async (input, context) => {
|
|
const where = logWhere(logFilters(input, context))
|
|
const serverIds = input.serverId ? [Number(input.serverId)] : context.connection.policy.scope.serverIds
|
|
await assertLogExportAccess(context, serverIds)
|
|
try {
|
|
return await withLogExportSlot(async () => {
|
|
const rows = await readBoundedLogExportRows(where)
|
|
await assertLogExportAccess(context, serverIds)
|
|
const masked = rows.map(row => redact(row)) as Record<string, unknown>[]
|
|
const format = input.format as "json" | "csv", content = serializeLogExport(masked, format, false)
|
|
return { ...await createLogExportArtifact(content, format, serverIds, context), rows: rows.length }
|
|
})
|
|
} catch (error) { await assertLogExportAccess(context, serverIds); if (error instanceof LogExportLimitError) throw new McpError("EXPORT_LIMIT", error.message, 422); if (error instanceof LogExportBusyError) throw new McpError("EXPORT_BUSY", error.message, 429); throw error }
|
|
},
|
|
})
|
|
add("logs.settings.read", "mm_logs_settings_get", "Настройки логов", "logs", "mm:settings:admin", "read", "global", z.object({}).strict(), { read: async () => getLogSettings() })
|
|
add("logs.settings.update", "mm_logs_settings_update_plan", "Изменение сборщика логов", "logs", "mm:settings:admin", "write", "global", z.object({ settings: logSettingsPatchSchema }).strict(), {
|
|
prepare: async (input, context) => {
|
|
const ids = (await pool.query<{ id: number }>("SELECT id FROM servers")).rows.map(row => Number(row.id))
|
|
if (ids.some(id => !context.connection.policy.scope.serverIds.includes(id))) throw new McpError("SERVER_DENIED", "Глобальная настройка сборщика затрагивает скрытые серверы")
|
|
return { target: { scope: "global" }, objects: ids.map(serverId => ({ kind: "server", id: String(serverId), serverId })), snapshots: [], before: await getLogSettings(), steps: [{ kind: "service", service: "logs.settings.update", input }], warnings: ["Отключение сбора и уменьшение retention влияют на последующую доступность истории."] }
|
|
},
|
|
})
|
|
|
|
export function listActions(): readonly McpAction[] { return actions }
|
|
export function findAction(toolName: string): McpAction {
|
|
const action = actions.find(candidate => candidate.operation.toolName === toolName)
|
|
if (!action) throw new McpError("UNKNOWN_OPERATION", "Инструмент не реализован", 404)
|
|
return action
|
|
}
|
|
export function findActionByOperation(id: string): McpAction {
|
|
const action = actions.find(candidate => candidate.operation.id === id)
|
|
if (!action) throw new McpError("UNKNOWN_OPERATION", "Операция не реализована", 404)
|
|
return action
|
|
}
|
|
|
|
async function assertPlanReadScope(plan: Awaited<ReturnType<typeof import("./runtime.js")["loadPlan"]>>, context: ActionContext) {
|
|
if (plan.connection_id !== context.connection.id) throw new McpError("NOT_FOUND", "План не найден", 404)
|
|
if (!context.connection.policy.scope.operationIds.includes(plan.operation_id)) throw new McpError("OPERATION_DENIED", "Исходное действие не входит в текущий допуск")
|
|
const source = findActionByOperation(plan.operation_id)
|
|
if (source.operation.requiredPermissions.some(permission => !hasPermission(context.connection.policy.permissions, permission) || !hasPermission(context.connection.owner_permissions, permission))) throw new McpError("PERMISSION_DENIED", "Право исходного действия отозвано")
|
|
const evidence = JSON.parse(await decryptSecret(plan.evidence.sealed)) as ChangeEvidence
|
|
const ids = [...(evidence.target.scope === "servers" ? evidence.target.serverIds : []), ...evidence.objects.flatMap(object => object.serverId === undefined ? [] : [object.serverId])]
|
|
if (ids.some(id => !context.connection.policy.scope.serverIds.includes(id)) || evidence.target.scope === "global" && !context.connection.policy.scope.allowGlobal) throw new McpError("SERVER_DENIED", "План находится вне текущего допуска")
|
|
}
|
|
add("changes.read", "mm_change_get", "Просмотр своего плана", "mcp", null, "read", "connection", z.object({ planId: z.string().uuid() }).strict(), {
|
|
read: async (input, context) => {
|
|
const { loadPlan, publicPlan } = await import("./runtime.js")
|
|
const plan = await loadPlan(String(input.planId))
|
|
await assertPlanReadScope(plan, context)
|
|
return publicPlan(plan)
|
|
},
|
|
})
|
|
add("changes.apply", "mm_change_apply", "Применить свой план", "mcp", null, "write", "connection", z.object({ planId: z.string().uuid(), idempotencyKey: z.string().min(1).max(200) }).strict(), {
|
|
read: async (input, context) => (await import("./runtime.js")).applyPlan(context.principal, String(input.planId), String(input.idempotencyKey)),
|
|
})
|
|
add("changes.cancel", "mm_change_cancel", "Отменить свой незапущенный план", "mcp", null, "read", "connection", z.object({ planId: z.string().uuid() }).strict(), {
|
|
read: async (input, context) => {
|
|
const { transaction, audit } = await import("./store.js")
|
|
await assertPlanReadScope(await (await import("./runtime.js")).loadPlan(String(input.planId)), context)
|
|
return transaction(async client => {
|
|
const { rows } = await client.query("UPDATE mcp_plans SET state='cancelled' WHERE id=$1 AND connection_id=$2 AND state IN ('draft','awaiting-approval','approved') RETURNING id", [input.planId, context.connection.id])
|
|
if (!rows.length) throw new McpError("STATE_CONFLICT", "План не найден или уже запущен", 409)
|
|
await audit(client, context.connection.owner_id, "plan.cancel", context.connection.id, { planId: input.planId })
|
|
return { cancelled: true }
|
|
})
|
|
},
|
|
})
|
|
add("operations.read", "mm_operation_get", "Результат своей операции", "mcp", null, "read", "connection", z.object({ operationId: z.string().uuid() }).strict(), {
|
|
read: async (input, context) => {
|
|
const { rows: [operation] } = await pool.query("SELECT * FROM mcp_operations WHERE id=$1 AND connection_id=$2", [input.operationId, context.connection.id])
|
|
if (!operation) {
|
|
const tombstone = await findOperationReplayTombstone(pool, context.connection.id, String(input.operationId))
|
|
if (!tombstone) throw new McpError("NOT_FOUND", "Операция не найдена", 404)
|
|
assertOperationReplayScope(tombstone, context.connection)
|
|
operationHistoryExpired()
|
|
}
|
|
await assertPlanReadScope(await (await import("./runtime.js")).loadPlan(operation.plan_id), context)
|
|
const { rows: steps } = await pool.query("SELECT * FROM mcp_operation_steps WHERE operation_id=$1 ORDER BY step_index", [input.operationId])
|
|
return { ...operation, steps }
|
|
},
|
|
})
|
|
|
|
registerRoutingActions(add)
|
|
registerRoutingProfileActions(add)
|
|
registerRoutingControls(add)
|
|
registerLifecycleActions(add)
|
|
registerRecoveryActions(add)
|
|
registerPathActions(add)
|
|
registerApplicationActions(add)
|
|
registerProbeActions(add)
|
|
registerServerProbeActions(add)
|
|
registerServerPollAction(add)
|
|
registerSpeedTestActions(add)
|
|
registerManualApiPingActions(add)
|
|
registerManualUptimeActions(add)
|
|
registerManualPingGroupActions(add)
|
|
registerManualTrafficActions(add)
|
|
registerTrafficLiveActions(add)
|
|
registerFlowCatalogActions(add)
|
|
registerFlowAnalyticsActions(add)
|
|
registerFlowMapActions(add)
|
|
registerFlowLiveActions(add)
|
|
registerAcmeTestActions(add)
|
|
registerAcmeSettingsActions(add)
|
|
registerGeoipUpdateActions(add)
|
|
registerBackupDownloadActions(add)
|
|
registerFlowOverlayActions(add)
|
|
registerWireguardInterfaceCreateActions(add)
|
|
registerWireguardPeerCreateActions(add)
|
|
registerHostFilesActions(add)
|
|
registerTelegramSettingsActions(add)
|
|
registerTelegramTestActions(add)
|
|
registerOspfStateActions(add)
|
|
registerOspfRouteProofActions(add)
|
|
registerLegacyOspfActions(add)
|
|
registerWireguardPeerDeleteActions(add)
|
|
registerWireguardPeerUpdateActions(add)
|
|
registerWireguardInterfaceDeleteActions(add)
|
|
registerFirewallActions(add)
|
|
registerGreMutationActions(add)
|
|
registerGreRevisionActions(add)
|
|
registerGreNativeServices()
|
|
registerVpnCatalogActions(add)
|
|
registerEvoBgpActions(add)
|
|
registerDatabaseRestore(add)
|
|
registerDatabaseBackupActions(add)
|
|
registerTerminalDiagnosticActions(add)
|
|
registerEventsBatchActions(add)
|
|
registerGlobalReconciliationActions(add)
|
|
registerWireguardInterfaceUpdateActions(add)
|
|
registerWireguardImportActions(add)
|
|
registerServerConnectionActions(add)
|
|
registerIpsecPeerDeleteActions(add)
|
|
registerIpsecUserDeleteActions(add)
|
|
registerIpsecUserUpdateActions(add)
|
|
registerIpsecServerDeleteActions(add)
|
|
registerIpsecServerInitActions(add)
|
|
registerIpsecRevisionActions(add)
|
|
registerWireguardRevisionActions(add)
|
|
registerIpsecCertificateDeleteActions(add)
|
|
registerIpsecPeerUpdateActions(add)
|
|
registerFlowPurgeActions(add)
|
|
registerFlowFactsRebuildActions(add)
|
|
registerFlowHostKeysActions(add)
|
|
registerIpsecUserCreateActions(add)
|
|
registerFlowSettingsActions(add)
|
|
registerIpsecExistingCertificateExportActions(add)
|