import { registerIpsecServerDeleteActions } from "./ipsec-server-delete-actions.js" import { registerCapabilityActions } from "./capability-actions.js" import { registerIncidentActions } from "./incident-actions.js" import { registerNetworkDiagnosticActions } from "./network-diagnostic-actions.js" import { registerResilienceActions } from "./resilience-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, logSequenceInputSchema, logSettingsPatchSchema } from "@mmapp/contracts" import { appUserCreateSchema, appUserUpdateSchema, appUserRoleSchema, interfaceCatalogStateSchema, 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, getInterfaceCatalogState, projectLegacyInterfaceCatalog, 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 { ospfFilterFields, rosResources, readRosSnapshot, resourceById, routerClient, validateRosStep, splitOspfUnsetUpdate } from "./resources.js" import { registerMcpOperation } from "./registry.js" import { accessGeneration, decryptSecret, encryptSecret, fingerprint, MAX_MCP_PUBLIC_ARRAY_ITEMS, MAX_MCP_PUBLIC_STRING_LENGTH, McpError, redact } from "./security.js" import { hasUnattendedPlanAuthority } from "./policy.js" import { effectiveMcpConnection } 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 { registerBfdMoveActions } from "./bfd-move-actions.js" import { registerGreMutationActions } from "./gre-mutation-actions.js" import { registerGreIpsecPairActions } from "./gre-ipsec-pair-actions.js" import { registerGreIke2PairActions } from "./gre-ikev2-pair-actions.js" import { registerIxActions } from "./internet-exchange-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 { readRpfDependencies, 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 { registerInterfaceRenameActions } from "./interface-rename-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, ospfInterfaceResources, resolveOspfInterfaceSelectors } 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 { registerNetworkNeighborActions } from "./network-neighbor-actions.js" import { registerIpv6NdMutationActions } from "./ipv6-nd-actions.js" import { registerArpActions } from "./arp-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, 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 & Partial> & { 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) registerNetworkNeighborActions(add) registerIpv6NdMutationActions(add) registerArpActions(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(resource.path) const rows = Array.isArray(raw) ? raw : [raw], offset = Number(input.offset), limit = Number(input.limit) const page = rows.slice(offset, offset + limit) const items = resource.id === "container" ? page.map(row => { if (!row || typeof row !== "object" || Array.isArray(row)) return null const { cmd: _cmd, entrypoint: _entrypoint, env: _env, ...visible } = row as Record return visible }) : page return { items: redact(items), 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 publicFields = resource.id === "ospf_instance" ? resource.fields.omit({ "in-filter-chain": true, "out-filter-chain": true, "out-filter-select": true }) : resource.fields const schema = action === "create" || ["ip_settings", "ipv6_settings"].includes(resource.id) ? z.object({ serverId, fields: publicFields.default({}), ...(resource.id === "vrf" ? { productionAdmission: z.literal(true).optional() } : {}), ...(resource.id === "bfd_configuration" ? { placeBeforeId: z.string().regex(/^\*[a-z0-9]+$/i).max(200).optional() } : {}) }).strict() : z.object({ serverId, id: rowId.optional(), fields: publicFields.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 guardsOspfInterfaceUse = action !== "create" && !delegated && ospfInterfaceResources.includes(resource.id) const previousVersion = action === "create" ? (["ospf_template", "wireguard_peer", "wireguard", "bfd_configuration"].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" || resource.id === "ip_settings" ? 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 === "bfd_configuration" ? 4 : resource.id === "ospf_template" ? (action === "update" ? 8 : 7) : 0) + (resource.id === "vrf" ? (action === "delete" ? 3 : 2) : 0) + (resource.id === "ospf_instance" ? 2 : 0) + (["bridge", "bridge_port", "bridge_vlan", "ip_settings", "ipv6_settings"].includes(resource.id) ? 1 : 0) + (guardsOspfInterfaceUse ? 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), 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) }, 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 === "ospf_template" && action === "update" && fields["instance-id"] !== undefined) { const previousId = current?.["instance-id"] if (typeof previousId !== "string" || !/^\d+$/.test(previousId) || Number(previousId) > 255) { throw new McpError("STATE_UNAVAILABLE", "RouterOS не подтвердил исходный instance-id для обратного плана", 409) } } 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] const rpf = resource.id === "ip_settings" && fields["rp-filter"] ? await readRpfDependencies(sid, fields["rp-filter"], before.sourceProof) : undefined if (rpf) snapshots.push(...rpf.snapshots) 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 = ospfInterfaceResources 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 members = ["vrf", "ospf_template", "bfd_configuration"].includes(resource.id) ? [current?.interfaces, fields.interfaces].filter((value): value is string => typeof value === "string" && (resource.id === "ospf_template" || !["all", "none"].includes(value))).flatMap(value => value.split(",").map(name => name.trim())) : [] let resolvedOspfInterfaces: Set | undefined if (resource.id === "ospf_template" && members.length) { resolvedOspfInterfaces = await resolveOspfInterfaceSelectors(sid, [...new Set(members)], interfaces, snapshots, references) } 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, ...(resolvedOspfInterfaces ?? members), ...(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 && resolvedOspfInterfaces?.has(name)) continue if (!parent) throw new McpError("INVALID_INPUT", "Требуется явный существующий интерфейс", 400) references.push({ kind: parent.resource, id: String(parent.row[".id"]), serverId: sid }) } if (resource.id === "ospf_template" && (fields.networks || current?.networks)) { // RouterOS matches local prefixes and can use the remote endpoint on PtP links. // Include the entire known interface/address inventory in object protection. const included = new Set(references.map(object => `${object.kind}/${object.id}`)) for (const snapshot of snapshots.filter(item => [...interfaceResources, "ipv4_address", "ipv6_address"].includes(item.resource))) { for (const row of snapshot.rows) { const nativeId = row[".id"] if (typeof nativeId !== "string" || !nativeId) throw new McpError("STATE_CONFLICT", "Не подтверждён ID зависимости шаблона OSPF", 409) const key = `${snapshot.resource}/${nativeId}` if (included.has(key)) continue if (references.length >= 1000) throw new McpError("STATE_UNAVAILABLE", "Каталог зависимостей OSPF превышает предел проверки объектов", 409) included.add(key) references.push({ kind: snapshot.resource, id: nativeId, 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 (guardsOspfInterfaceUse) { const ospf = await readRosSnapshot(sid, "ospf_template", undefined, before.sourceProof) snapshots.push(ospf, await readRosSnapshot(sid, "bfd_configuration", undefined, before.sourceProof)) const selectors = ospf.rows.flatMap(row => typeof row.interfaces === "string" && row.interfaces.trim() ? row.interfaces.split(",").map(name => name.trim()) : []) if (selectors.length) { const used = await resolveOspfInterfaceSelectors(sid, [...new Set(selectors)], interfaces, snapshots, []) if (used.has(existingName)) throw new McpError("STATE_CONFLICT", "Интерфейс используется селектором шаблона OSPF", 409) const rawIndex = snapshots.findIndex(snapshot => snapshot.resource === "interface_inventory") if (rawIndex !== -1) { // The successful rename/delete changes the same interface in this raw view. // The typed target snapshot keeps its exact identity; lists and members stay sealed. const [raw] = snapshots.splice(rawIndex, 1) const matches = raw.rows.filter(row => row.name === existingName) if (matches.length !== 1) throw new McpError("STATE_UNAVAILABLE", "Не подтверждён ID изменяемого интерфейса OSPF", 409) const ids = [existingName, current?.[".id"], matches[0][".id"]] if (snapshots.find(snapshot => snapshot.resource === "interface_list_member")?.rows.some(row => ids.includes(row.interface))) { throw new McpError("STATE_CONFLICT", "Сначала удалите интерфейс из списка RouterOS", 409) } } } } const dependent = snapshots.filter(snapshot => ![resource.id, "interface_list", "interface_list_member"].includes(snapshot.resource)).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"] : input.placeBeforeId if (resource.id === "vrf" && action === "create" && typeof placeBeforeId !== "string") throw new McpError("STATE_CONFLICT", "Не подтверждён порядок существующих VRF", 409) const changesBfdMatch = action === "delete" || ["interfaces", "addresses", "address-list", "vrf", "disabled", "forbid-bfd"].some(key => fields[key] !== undefined) const bfdOrderAnchor = resource.id === "bfd_configuration" ? (action === "create" ? placeBeforeId : changesBfdMatch ? id : undefined) : undefined if (typeof bfdOrderAnchor === "string") { const ids = before.rows.map(row => row[".id"]) const position = ids.indexOf(bfdOrderAnchor) if (position < 0 || new Set(ids).size !== ids.length) throw new McpError("STATE_CONFLICT", "Не найдена однозначная позиция правила BFD", 409) const affected = ids.slice(action === "create" ? position : position + 1) if (references.length + affected.length > 1000) throw new McpError("STATE_UNAVAILABLE", "Каталог зависимостей BFD превышает предел проверки объектов", 409) for (const id of affected) { if (typeof id !== "string" || !/^\*[a-z0-9]+$/i.test(id)) throw new McpError("STATE_CONFLICT", "Не подтверждён ID правила BFD", 409) references.push({ kind: resource.id, id, serverId: sid }) } } const changesOspfExports = resource.id === "ospf_instance" && (fields.redistribute !== undefined || fields["originate-default"] !== undefined || fields["out-filter-chain"] !== undefined || fields["out-filter-select"] !== undefined) const ospfExportWarnings = changesOspfExports ? [ "Изменение может перераспределить маршруты или изменить объявление маршрута по умолчанию.", ...((fields["out-filter-chain"] ?? current?.["out-filter-chain"]) ? ["Если источники перераспределения и originate-default не заданы, выходной фильтр может обработать все активные маршруты."] : []), ...(["always", "if-installed"].includes(String(fields["originate-default"] ?? current?.["originate-default"])) ? ["Выходной фильтр не может отклонить маршрут по умолчанию, который сгенерировал OSPF."] : []), ] : [] if (resource.id === "ospf_template" && fields["instance-id"] !== undefined) ospfExportWarnings.push("Смена instance-id может разорвать соседство OSPF, если ID на обеих сторонах различаются.") return { target: { scope: "servers", serverIds: [sid] }, objects: references, snapshots, ...(resource.id === "vrf" && input.productionAdmission === true ? { vrfProductionAdmission: true as const } : {}), steps: splitOspfUnsetUpdate({ serverId: sid, resource: resource.id, action, id, fields, ...(typeof placeBeforeId === "string" ? { placeBeforeId } : {}) }).map(step => ({ kind: "ros" as const, step })), requiresHuman: true, warnings: ["Нативное изменение может затронуть управление устройством и требует подтверждения человеком.", "Автоматическое каскадное изменение зависимостей не выполняется.", ...ospfExportWarnings, ...(resource.id === "bfd_configuration" && action === "create" && fields.addresses === undefined ? ["Правило BFD без адресного фильтра может затронуть всех соседей на указанных интерфейсах."] : []), ...(rpf?.warnings ?? []), ...(resource.id === "vrf" && action === "delete" ? ["При удалении VRF RouterOS может удалить автоматический IPv6 link-local и его connected-маршрут пустого bridge; статические адреса сохраняются."] : []), ...(placeBeforeId ? [resource.id === "bfd_configuration" ? `Правило BFD создаётся перед записью ${placeBeforeId}. Порядок влияет на выбор правила.` : `VRF создаётся перед записью ${placeBeforeId}. Порядок определяет принадлежность интерфейсов.`] : [])], } }, }) } } add("routing.ospf.filter.bind", "mm_ospf_filter_binding_plan", "Привязка фильтров существующего OSPF instance", "network", ["mm:network:write", "mm:filters:read"], "write", "servers", z.object({ serverId, id: rowId, fields: ospfFilterFields.refine(fields => Object.values(fields).some(value => value !== undefined), "Укажите привязку фильтра OSPF") }).strict(), { prepare: (input, context) => findAction("mm_ospf_instance_update_plan").prepare!(input, context), }) 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) }, }) } registerCapabilityActions(add) registerIncidentActions(add) 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> | 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) }), }) const invalidInterfaceCatalog = () => new McpError("STATE_UNAVAILABLE", "Не подтверждён контекст каталога интерфейсов.", 502) async function readMcpInterfaceCatalog(serverId: number) { const state = await getInterfaceCatalogState(serverId).catch(error => { if (error instanceof UsersServiceError) { if (error.status === 404) throw new McpError("NOT_FOUND", "Сервер не найден", 404) if (error.status === 502) throw invalidInterfaceCatalog() } throw error }) const parsed = interfaceCatalogStateSchema.safeParse(state) if (!parsed.success || parsed.data.serverId !== serverId) throw invalidInterfaceCatalog() return parsed.data } function catalogueExceedsPublicLimits(value: unknown): boolean { if (typeof value === "string") return value.length > MAX_MCP_PUBLIC_STRING_LENGTH if (Array.isArray(value)) return value.length > MAX_MCP_PUBLIC_ARRAY_ITEMS || value.some(catalogueExceedsPublicLimits) return value !== null && typeof value === "object" && Object.values(value).some(catalogueExceedsPublicLimits) } function intactInterfaceCatalog(result: T): T { if (catalogueExceedsPublicLimits(result)) throw new McpError("BUDGET_EXCEEDED", "Каталог интерфейсов превышает предел ответа MCP.", 413) return result } add("users.interfaces.read", "mm_user_interfaces_list", "Каталог интерфейсов для привязок пользователей", "users", "mm:users:read", "read", "servers", z.object({ serverId }).strict(), { read: async input => intactInterfaceCatalog({ interfaces: projectLegacyInterfaceCatalog(await readMcpInterfaceCatalog(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 => intactInterfaceCatalog(await readMcpInterfaceCatalog(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, 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 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 withContext of [false, true]) add(withContext ? "logs.context" : "logs.get", withContext ? "mm_logs_context_get" : "mm_logs_get", "Запись журнала", "logs", "mm:servers:read", "read", "servers", z.object({ serverId, id: logSequenceInputSchema }).strict(), { read: async input => { const id = String(input.id), serverId = Number(input.serverId) const result = await (withContext ? readLogContext(id, serverId) : readLogEntry(id, serverId)) if (!result) throw new McpError("NOT_FOUND", "Событие не найдено", 404) return result }, }) 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 serverId = Number(input.serverId) const until = Date.now() + Number(input.waitSeconds) * 1000 const accessProof = fingerprint([context.connection.policy, context.connection.owner_permissions]) let release: (() => void) | undefined try { const generation = await accessGeneration() let filters: ReturnType 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 }) || !logSequenceInputSchema.safeParse(saved.cursor).success) 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", [serverId])).rows[0].cursor } while (true) { assertActive() const current = await effectiveMcpConnection(context.principal) assertActive() if (fingerprint([current.policy, current.owner_permissions]) !== accessProof) throw new McpError("RESET_REQUIRED", "Права или область доступа изменились; начните новое чтение", 409) const available = await pool.query("SELECT 1 FROM servers WHERE id=$1 AND enabled=true", [serverId]) assertActive() if (!available.rowCount) throw new McpError("DEVICE_UNAVAILABLE", "Сервер отключён или не найден", 409) release ??= subscribeLogDevice(serverId) const batch = await readLogStream(filters, cursor, Number(input.limit), waitSignal) 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[] 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", "Глобальная настройка сборщика затрагивает скрытые серверы") const before = await getLogSettings() const settings = logSettingsPatchSchema.parse(input.settings) const warnings: string[] = [] if (before.enabled && settings.enabled === false) warnings.push("После применения сборщик прекратит получать новые события.") if (settings.retentionDays !== undefined && settings.retentionDays < before.retentionDays) { warnings.push(`Срок хранения сокращается с ${before.retentionDays} до ${settings.retentionDays} суток. При последующей очистке удаляются записи, полученные более ${settings.retentionDays} суток назад.`) } return { target: { scope: "global" }, objects: ids.map(serverId => ({ kind: "server", id: String(serverId), serverId })), snapshots: [], before, steps: [{ kind: "service", service: "logs.settings.update", input }], warnings, } }, }) 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>, 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, hasUnattendedPlanAuthority(context.connection.policy) && plan.policy_version === context.connection.policy.version) }, }) add("changes.apply", "mm_change_apply", "Применить свой план", "mcp", null, "write", "connection", z.object({ planId: z.string().uuid(), idempotencyKey: z.string().min(1).max(200), announcedPlanDigest: z.string().regex(/^[0-9a-f]{64}$/).optional().describe("Значение announcement.digest. Передавайте только после отдельного видимого сообщения с точным планом в чате."), }).strict(), { read: async (input, context) => (await import("./runtime.js")).applyPlan(context.principal, String(input.planId), String(input.idempotencyKey), input.announcedPlanDigest as string | undefined), }) 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) registerNetworkDiagnosticActions(add) registerResilienceActions(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) registerBfdMoveActions(add) registerGreMutationActions(add) registerGreIpsecPairActions(add) registerGreIke2PairActions(add) registerIxActions(add) registerGreRevisionActions(add) registerGreNativeServices() registerVpnCatalogActions(add) registerEvoBgpActions(add) registerDatabaseRestore(add) registerDatabaseBackupActions(add) registerTerminalDiagnosticActions(add) registerEventsBatchActions(add) registerGlobalReconciliationActions(add) registerWireguardInterfaceUpdateActions(add) registerInterfaceRenameActions(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)