diff --git a/backend/mcp-coverage.json b/backend/mcp-coverage.json index df94ca49..34aab4b6 100644 --- a/backend/mcp-coverage.json +++ b/backend/mcp-coverage.json @@ -555,6 +555,13 @@ "operations": [], "reason": "Управление самим MCP, транспорт или машинная авторизация: отдельного AI-инструмента нет." }, + { + "method": "GET", + "path": "/api/mcp/server-choices", + "status": "excluded", + "operations": [], + "reason": "Каталог выбора серверов для выдачи доступа в панели MCP." + }, { "method": "GET", "path": "/api/mcp/connections/:id/grants", diff --git a/backend/src/lib/permissions.ts b/backend/src/lib/permissions.ts index f25c91aa..6d408c05 100644 --- a/backend/src/lib/permissions.ts +++ b/backend/src/lib/permissions.ts @@ -48,6 +48,7 @@ const RULES: Rule[] = [ { methods: ["POST"], match: p => p === "/api/mcp/oauth/consent", permission: "mm:mcp:read" }, { methods: ["POST"], match: p => /^\/api\/mcp\/connections\/[^/]+\/revalidate$/.test(p), permission: "mm:mcp:read" }, { methods: ["GET"], match: p => p === "/api/mcp/catalog", permission: "mm:mcp:read" }, + { methods: ["GET"], match: p => p === "/api/mcp/server-choices", permission: "mm:mcp:read" }, { methods: ["GET"], match: p => p.startsWith("/api/mcp/devices/"), permission: "mm:mcp:read" }, { methods: ["GET"], match: p => /^\/api\/mcp\/(?:overview|connections|requests|plans|operations|protections|drift|audit|artifacts|routing-profiles)(?:\/|$)/.test(p), permission: "mm:mcp:read" }, { methods: ["POST"], match: p => /^\/api\/mcp\/plans\/(?:[^/]+)\/decision$/.test(p), permission: "mm:mcp:approve" }, diff --git a/backend/src/routes/mcp.test.ts b/backend/src/routes/mcp.test.ts index 5af9a652..9b39ea30 100644 --- a/backend/src/routes/mcp.test.ts +++ b/backend/src/routes/mcp.test.ts @@ -111,6 +111,30 @@ try { } finally { pool.query = originalQuery; pool.connect = originalConnect } // Human JWT authentication stays outside the delegated MCP credential failure. const connectionSql = "SELECT * FROM mcp_connections WHERE id=$1" + const serverChoicesUrl = "/api/mcp/server-choices" + const scopedChoicesUrl = `${serverChoicesUrl}?connectionId=${createBody.connectionId}` + const readMcp = { authorization: "Bearer " + await token(["mm:mcp:read"]) } + let catalogOwnerId = "human-admin" + const serverScopeQueries: unknown[] = [] + pool.query = (async (sql: string, values?: unknown[]) => { + if (sql === connectionSql) return { rows: [{ id: createBody.connectionId, owner_id: catalogOwnerId, policy: payload.policy }] } + assert.match(sql, /^SELECT id,name,host,enabled FROM servers/) + serverScopeQueries.push(values?.[0]) + return { rows: [{ id: "1", name: "CHR test", host: "router.example.test", enabled: true, password: "synthetic-hidden" }] } + }) as typeof pool.query + try { + assert.equal((await app.inject({ url: serverChoicesUrl })).statusCode, 401) + assert.equal((await app.inject({ url: serverChoicesUrl, headers: readMcp })).statusCode, 403) + const full = await app.inject({ url: serverChoicesUrl, headers: admin }) + const scoped = await app.inject({ url: scopedChoicesUrl, headers: readMcp }) + for (const response of [full, scoped]) { + assert.equal(response.statusCode, 200) + assert.deepEqual(response.json(), { servers: [{ id: 1, name: "CHR test", host: "router.example.test", enabled: true }] }) + } + catalogOwnerId = "another-owner" + assert.equal((await app.inject({ url: scopedChoicesUrl, headers: readMcp })).statusCode, 404) + assert.deepEqual(serverScopeQueries, [null, [1]]) + } finally { pool.query = originalQuery } const credentialSql = `SELECT c.id,c.expires_at FROM mcp_credentials c WHERE c.connection_id=$1 AND c.kind='bearer' AND c.revoked_at IS NULL AND c.expires_at>now() AND NOT EXISTS(SELECT 1 FROM mcp_grants g WHERE g.payload->>'credentialId'=c.id::text) ORDER BY c.created_at DESC LIMIT 1` diff --git a/backend/src/routes/mcp.ts b/backend/src/routes/mcp.ts index da43699c..9fd82d11 100644 --- a/backend/src/routes/mcp.ts +++ b/backend/src/routes/mcp.ts @@ -160,6 +160,21 @@ export function createMcpRoutes(checkClaims: typeof assertPortalClaimsCurrent = }) app.get("/mcp/connections", async request => ({ connections: await listMcpConnections(actorOf(request.authUser)) })) + app.get("/mcp/server-choices", async request => { + const { connectionId } = z.object({ connectionId: uuid.optional() }).strict().parse(request.query) + const actor = actorOf(request.authUser) + let serverIds: number[] | null = null + if (connectionId) { + const connection = await getConnection(connectionId) + assertConnectionVisible(connection, actor) + serverIds = connection.policy.scope.serverIds + } else if (!hasPermission(actor.permissions, "mm:mcp:admin")) { + throw new McpError("PERMISSION_DENIED", "Полный каталог доступен администратору MCP", 403) + } + const { rows } = await pool.query<{ id: string; name: string; host: string; enabled: boolean }>( + "SELECT id,name,host,enabled FROM servers WHERE $1::bigint[] IS NULL OR id=ANY($1::bigint[]) ORDER BY name,id", [serverIds]) + return { servers: rows.map(row => ({ id: Number(row.id), name: row.name, host: row.host, enabled: row.enabled })) } + }) app.post("/mcp/connections", async request => { const input = mcpConnectionCreateSchema.parse(request.body) const available = new Set(listActions().map(action => action.operation.id)) diff --git a/components/mcp/mcp-workspace.tsx b/components/mcp/mcp-workspace.tsx index cc379e03..daa0e0a1 100644 --- a/components/mcp/mcp-workspace.tsx +++ b/components/mcp/mcp-workspace.tsx @@ -4,7 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } fro import { useSearchParams } from "next/navigation" import Link from "next/link" import { useTable, type ColumnDef } from "@tanstack/react-table" -import { BotIcon, CopyIcon, PlusIcon, RefreshCwIcon, ShieldIcon, StopCircleIcon } from "lucide-react" +import { BotIcon, CheckIcon, CopyIcon, PlusIcon, RefreshCwIcon, ServerIcon, ShieldIcon, StopCircleIcon } from "lucide-react" import { toast } from "sonner" import { mcpConnectionCreateSchema, mcpPageQuerySchema, mcpTargetSchema, type McpConnection, type McpOperationDescriptor, type McpPolicyDecision } from "@mmapp/contracts/mcp" import { routeAiControllerBlockReason, routeAiProfileSchema, type RouteAiProfile } from "@mmapp/contracts/mcp-routing" @@ -25,6 +25,7 @@ import { Badge } from "@/components/reui/badge" import { Button, buttonVariants } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Checkbox } from "@/components/ui/checkbox" +import { Item, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item" import { Textarea } from "@/components/ui/textarea" import { Tabs, TabsList, TabsTrigger, TabsContent } from "@/components/ui/tabs" import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog" @@ -200,12 +201,46 @@ function OperationChoices({ operations, selected, onChange, selectAllLabel = "В } +function ServerChoices({ catalog, selected, onChange, all, onAllChange, forGrant = false }: { + catalog: { data: Awaited> | null; error: string; refresh: () => void } + selected: number[] + onChange: (ids: number[]) => void + all: boolean + onAllChange: (value: boolean) => void + forGrant?: boolean +}) { + const servers = catalog.data?.servers ?? [] + const unknown = catalog.data ? selected.filter(id => !servers.some(server => server.id === id)) : [] + return
+ {forGrant ? "Серверы временного допуска" : "Разрешённые серверы"} + + {all ? <>

{forGrant ? "Выбраны серверы, разрешённые основному подключению." : "Доступ получат все серверы, зарегистрированные на момент сохранения."}

{forGrant && } : <> +
+ {servers.map(server => { + const active = selected.includes(server.id), title = server.name || server.host + return } + onClick={() => onChange(active ? selected.filter(id => id !== server.id) : [...selected, server.id])}> + + {title}{server.host !== title ? `${server.host} · ` : ""}ID {server.id}{!server.enabled && " · отключён"} + {active && + })} + {unknown.map(id => )} +
+ {catalog.error && <>} + {!catalog.data && !catalog.error &&

Загрузка серверов…

} + {catalog.data &&

{selected.length ? `Выбрано серверов: ${selected.length}` : "Серверы не выбраны. Доступ к ним закрыт."}

} + } +
+} function ConnectionForm({ api, operations, editing, close, created }: { api: McpApi; operations: McpOperationDescriptor[]; editing?: McpConnection; close: () => void; created: (token?: string) => void }) { const [step, setStep] = useState(1), [busy, setBusy] = useState(false), [error, setError] = useState("") const [name, setName] = useState(editing?.name ?? ""), [mode, setMode] = useState(editing?.policy.mode ?? "observer") const [service, setService] = useState(editing?.policy.authority === "service") const [selectAllServers, setSelectAllServers] = useState(false) - const [serverText, setServerText] = useState(editing?.policy.scope.serverIds.join(", ") ?? ""), [selected, setSelected] = useState(editing?.policy.scope.operationIds ?? []) + const [serverIds, setServerIds] = useState(editing?.policy.scope.serverIds ?? []), [selected, setSelected] = useState(editing?.policy.scope.operationIds ?? []) + const serverCatalog = useQuery(useCallback(signal => api.serverChoices(undefined, signal), [api])) const [global, setGlobal] = useState(editing?.policy.scope.allowGlobal ?? false), [danger, setDanger] = useState(editing?.policy.dangerousPolicy ?? "approval") const [dangerIds, setDangerIds] = useState(editing?.policy.autonomousDangerousOperationIds ?? []) const [expires, setExpires] = useState(() => editing?.policy.expiresAt.slice(0, 16) ?? new Date(Date.now() + 30 * 86400000).toISOString().slice(0, 16)) @@ -218,7 +253,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp const save = async () => { setBusy(true); setError("") try { - const input = mcpConnectionCreateSchema.parse({ name, ...(service ? { authority: "service", mode: "autonomous", expiresAt: null } : { mode, expiresAt: new Date(expires + "Z").toISOString() }), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], ...(selectAllServers && { selectAllServers: true }), scope: { serverIds: selectAllServers ? [] : serverText.split(/[,\s]+/).filter(Boolean).map(Number), operationIds: selected, allowGlobal: global }, dangerousPolicy: service ? "approval" : danger, autonomousDangerousOperationIds: service || danger !== "explicit-allow" ? [] : autonomousDangerIds, limits }) + const input = mcpConnectionCreateSchema.parse({ name, ...(service ? { authority: "service", mode: "autonomous", expiresAt: null } : { mode, expiresAt: new Date(expires + "Z").toISOString() }), permissions: [...new Set(eligible.filter(operation => selected.includes(operation.id)).flatMap(operation => operation.requiredPermissions))], ...(selectAllServers && { selectAllServers: true }), scope: { serverIds: selectAllServers ? [] : serverIds, operationIds: selected, allowGlobal: global }, dangerousPolicy: service ? "approval" : danger, autonomousDangerousOperationIds: service || danger !== "explicit-allow" ? [] : autonomousDangerIds, limits }) if (editing) { await api.update(editing.id, input); created() } else { const result = await api.create(input); created(result.token) } } catch (failure) { setError(errorText(failure)) } finally { setBusy(false) } @@ -229,10 +264,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp ?

Подключение действует до отзыва. Агент выполняет разрешённые обычные операции автономно, а опасные действия требуют подтверждения.

: <> setExpires(event.target.value)} /> setMode(value as typeof mode)}>{Object.entries(modeLabels).map(([value, title]) => )}}} {step === 2 && <> - - {selectAllServers - ?

Доступ получат все серверы, зарегистрированные на момент сохранения.

- : <> setServerText(event.target.value)} placeholder="1, 2" />

Пустой список означает, что доступ к серверам закрыт.

} +

Выбор операций учитывает права владельца. Режим, список серверов и глобальный доступ задаются отдельно. Новые инструменты нужно добавлять вручную. Для применения планов выберите также инструменты просмотра и применения.

@@ -241,7 +273,7 @@ function ConnectionForm({ api, operations, editing, close, created }: { api: Mcp

В автономном режиме выбранные здесь опасные операции смогут выполняться без подтверждения, если этого не требует защита объекта или сама операция.

}}} - {step === 4 &&

{name || "Без названия"} · {service ? "Сервисное, бессрочное" : modeLabels[mode]}

Серверы: {selectAllServers ? "все на момент сохранения" : serverText || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.

{!service && mode === "autonomous" && danger === "explicit-allow" &&

Опасных операций выбрано для автономного выполнения: {autonomousDangerIds.length}.

}

Защита объектов продолжает действовать независимо от автономных разрешений.

После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».

} + {step === 4 &&

{name || "Без названия"} · {service ? "Сервисное, бессрочное" : modeLabels[mode]}

Серверы: {selectAllServers ? "все на момент сохранения" : serverIds.join(", ") || "не выбраны"}. Операций: {selected.length}. Глобальный доступ: {global ? "да" : "нет"}.

{!service && mode === "autonomous" && danger === "explicit-allow" &&

Опасных операций выбрано для автономного выполнения: {autonomousDangerIds.length}.

}

Защита объектов продолжает действовать независимо от автономных разрешений.

После сохранения проверьте конкретное действие в симуляторе на вкладке «Разрешения».

}
{step < 4 ? : }
} @@ -313,8 +345,11 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: { grantBusy: boolean }) { const [result, setResult] = useState> | null>(null) - const [operations, setOperations] = useState([]), [serverText, setServerText] = useState(""), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false) + const [serverIds, setServerIds] = useState([]), [selectAllServers, setSelectAllServers] = useState(false) + const [operations, setOperations] = useState([]), [minutes, setMinutes] = useState(60), [global, setGlobal] = useState(false) const connectionId = connection.id + const serverCatalog = useQuery(useCallback(signal => api.serverChoices(connectionId, signal), [api, connectionId]), connectionId) + const grantServers = selectAllServers ? serverCatalog.data?.servers.map(server => server.id) ?? [] : serverIds const grants = useQuery(useCallback(signal => api.grants(connectionId, signal), [api, connectionId])) const checkRevision = useRef(0) useEffect(() => () => { checkRevision.current++ }, []) @@ -335,7 +370,7 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: { try { void issue({ id: crypto.randomUUID(), startsAt: now.toISOString(), expiresAt: expires.toISOString(), - scope: { serverIds: serverText.split(",").map(value => value.trim()).filter(Boolean).map(Number), operationIds: operations, allowGlobal: global }, + scope: { serverIds: grantServers, operationIds: operations, allowGlobal: global }, }) } catch (error) { toast.error(errorText(error)) @@ -353,13 +388,11 @@ function ConnectionAccessTools({ api, connection, issue, grantBusy }: {

}
{pretty(result)}
} -
- setServerText(event.target.value)} placeholder="ID через запятую" /> - setMinutes(Number(event.target.value))} /> -
+ + setMinutes(Number(event.target.value))} /> {connection.policy.scope.allowGlobal && }
{connection.policy.scope.operationIds.map(id => setOperations(values => checked ? [...values, id] : values.filter(value => value !== id))} />)}
- + {grants.data?.grants.map(grant =>
До {date(grant.grant.expiresAt)} · {grant.revoked_at ? "отозван" : "выдан"} diff --git a/docs/mcp-enable-guide.md b/docs/mcp-enable-guide.md index 9340f31b..0a0a8f1b 100644 --- a/docs/mcp-enable-guide.md +++ b/docs/mcp-enable-guide.md @@ -66,7 +66,7 @@ - **«Режим управления»** — «Наблюдатель». Он же выбран по умолчанию. - **Серверы и операции** — только те, что нужны агенту. - «Все серверы» включает серверы, зарегистрированные на момент сохранения. Новые серверы добавляются при повторном выборе и сохранении разрешений. - - Пустой список ID при выключенной опции «Все серверы» закрывает доступ ко всем серверам. + - Для выборочного доступа отметьте карточки нужных серверов. Если «Все серверы» выключено и ни одна карточка не отмечена, доступ к серверам закрыт. - Операция, не выданная подключению, получает `OPERATION_DENIED`. - Сервер вне списка получает `SERVER_DENIED`. - Глобальные операции работают только с «Разрешить выбранные глобальные операции». diff --git a/shared/api/mcp.ts b/shared/api/mcp.ts index 62db3d78..e91ae347 100644 --- a/shared/api/mcp.ts +++ b/shared/api/mcp.ts @@ -13,6 +13,8 @@ export function mcpApi(base: string) { const get = async (path: string, schema: z.ZodType, signal?: AbortSignal): Promise => schema.parse(await requestJson(base, "/api/mcp" + path, { signal })) const send = async (path: string, body: unknown, schema: z.ZodType, method = "POST", signal?: AbortSignal): Promise => schema.parse(await requestJson(base, "/api/mcp" + path, { method, body: JSON.stringify(body), signal })) return { + serverChoices: (connectionId?: string, signal?: AbortSignal) => get(connectionId ? "/server-choices?" + new URLSearchParams({ connectionId }) : "/server-choices", + deviceCatalogSchema.pick({ servers: true }), signal), downloadArtifact: (receipt: unknown, signal?: AbortSignal) => downloadHumanArtifact(base, receipt, signal), coverage: (signal?: AbortSignal) => get("/coverage", z.object({ version: z.literal(1), routes: z.array(z.object({ method: z.string(), path: z.string(), status: z.enum(["mediated", "excluded", "pending"]), operations: z.array(z.string()), reason: z.string() })) }), signal), uploadRestoreArchive: async (file: File, signal?: AbortSignal) => restoreArchiveSchema.parse(await requestJson(base, "/api/mcp/database/archives", { method: "POST", headers: { "Content-Type": "application/octet-stream" }, body: file, signal })), diff --git a/tests/e2e/mcp-auth-context.spec.ts b/tests/e2e/mcp-auth-context.spec.ts index 7ee4a5c8..cb7a82b4 100644 --- a/tests/e2e/mcp-auth-context.spec.ts +++ b/tests/e2e/mcp-auth-context.spec.ts @@ -24,6 +24,10 @@ async function setup(page: Page, permissions: string[], access: { expiresAt?: st if (method !== 'GET') mutations.push({ path, body: request.postDataJSON() }) if (path === '/api/auth/config') return json({ required: true }) if (path === '/api/mcp/catalog') return json({ stage: 'runtime', executionAvailable: true, operations: [read, forbidden] }) + if (path === '/api/mcp/server-choices') return json({ servers: [ + { id: 1, name: 'CHR WAN', host: 'wan.example.test', enabled: true }, + { id: 2, name: 'CHR LAN', host: 'lan.example.test', enabled: true }, + ] }) if (path === '/api/mcp/overview') return json({ connections: 1, calls: 3, errors: 1, approvals: 0, running: 0, enabled, observedAt: at }) if (path === '/api/mcp/connections') { connectionReads++; const visible = { ...connection, ownerValidUntil }; return json(method === 'POST' ? { connection: visible, token: 'synthetic-one-time-token' } : { connections: [visible] }) } if (path === `/api/mcp/connections/${id}` && method === 'PUT') { @@ -305,7 +309,10 @@ test('synthetic: issue only selected server/read permission and hide one-time to await dialog.getByLabel('Название', { exact: true }).fill('Ограниченная диагностика') await dialog.getByRole('button', { name: 'Далее', exact: true }).click() await expect(dialog.getByRole('checkbox', { name: forbidden.title, exact: true })).toHaveCount(0) - await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1') + const wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true }) + await wan.click() + await expect(wan).toHaveAttribute('aria-pressed', 'true') + await expect(dialog.getByRole('button', { name: 'CHR LAN', exact: true })).toHaveAttribute('aria-pressed', 'false') await dialog.getByRole('button', { name: 'Выбрать все операции' }).click() await expect(dialog.getByRole('status')).toHaveText('Выбрано 3') await dialog.getByRole('button', { name: 'Снять все' }).click() @@ -350,13 +357,13 @@ test('synthetic: edit autonomous dangerous operations by group or all at once', await dialog.getByLabel('Режим управления', { exact: true }).selectOption('autonomous') await next.click() const allServers = dialog.getByRole('checkbox', { name: 'Все серверы', exact: true }) - const serverIds = dialog.getByLabel('ID разрешённых серверов через запятую') + const wan = dialog.getByRole('button', { name: 'CHR WAN', exact: true }) await expect(allServers).not.toBeChecked() - await expect(serverIds).toHaveValue('1') + await expect(wan).toHaveAttribute('aria-pressed', 'true') await allServers.check() - await expect(serverIds).toHaveCount(0) + await expect(wan).toHaveCount(0) await allServers.uncheck() - await expect(serverIds).toHaveValue('1') + await expect(wan).toHaveAttribute('aria-pressed', 'true') await allServers.check() await dialog.getByRole('button', { name: 'Выбрать все операции', exact: true }).click() await dialog.locator('summary').filter({ hasText: 'Сеть и маршрутизация' }).click() @@ -392,7 +399,7 @@ test('synthetic: issue service access with no expiry and mandatory approval of d await dialog.getByLabel('Тип подключения', { exact: true }).selectOption('service') await expect(dialog.getByLabel('Срок действия (UTC)', { exact: true })).toHaveCount(0) await next.click() - await dialog.getByLabel('ID разрешённых серверов через запятую').fill('1') + await dialog.getByRole('button', { name: 'CHR WAN', exact: true }).click() await dialog.getByRole('checkbox', { name: 'Все операции группы «Журналы»' }).check() await next.click() await expect(dialog.getByText('Опасные действия всегда требуют подтверждения.')).toBeVisible() diff --git a/tests/e2e/mcp-context.spec.ts b/tests/e2e/mcp-context.spec.ts index c4779c6d..c45a26ae 100644 --- a/tests/e2e/mcp-context.spec.ts +++ b/tests/e2e/mcp-context.spec.ts @@ -17,6 +17,7 @@ async function setup(page: Page, fail = false) { const json = (body: unknown) => route.fulfill({ headers, json: body }) if (path === "/api/auth/config") return json({ required: false }) if (path === "/api/mcp/catalog") return json({ stage: "runtime", executionAvailable: true, operations: [operation] }) + if (path === "/api/mcp/server-choices") return json({ servers: [{ id: 1, name: "CHR lab", host: "192.0.2.1", enabled: true }] }) if (path === "/api/mcp/coverage") return json({ version: 1, routes: [{ method: "POST", path: "/api/geoip/update", status: "pending", operations: [], reason: "Нужен отдельный сервисный адаптер" }] }) if (path === "/api/mcp/overview") return fail ? route.fulfill({ headers, status: 503, json: { error: "Аудит временно недоступен" } }) : json({ connections: 1, calls: 7, errors: 1, approvals: 1, running: 0, enabled: true, observedAt: at }) if (path === "/api/mcp/connections") return json(method === "POST" ? { connection, token: "test-one-time-secret" } : { connections: [connection] }) @@ -414,7 +415,7 @@ test("MCP: доступ, проверка подключения, выдача await page.getByRole("button", { name: "Выдать доступ", exact: true }).click() await page.getByLabel("Название", { exact: true }).fill("Новый AI клиент") await page.getByRole("button", { name: "Далее", exact: true }).click() - await page.getByLabel("ID разрешённых серверов через запятую").fill("1") + await page.getByRole("button", { name: "CHR lab", exact: true }).click() await page.locator("summary").filter({ hasText: "Журналы" }).click() await page.getByRole("checkbox", { name: "Поиск логов", exact: true }).check() await page.getByRole("button", { name: "Далее", exact: true }).click() @@ -478,13 +479,19 @@ test("MCP: временные допуски и результаты прове await expect(revoke).toBeVisible() await Promise.all([page.waitForRequest(`**/api/mcp/connections/${id}/check`), check.click()]) await page.getByRole("checkbox", { name: "logs.query", exact: true }).check() - await Promise.all([ + const serverCard = page.getByRole("button", { name: "CHR lab", exact: true }) + await serverCard.click() + await expect(serverCard).toHaveAttribute("aria-pressed", "true") + await page.getByRole("checkbox", { name: "Все серверы подключения", exact: true }).check() + const [issuedRequest] = await Promise.all([ page.waitForRequest(request => request.method() === "POST" && request.url().endsWith(`/connections/${id}/grants`)), create.click(), ]) + expect(issuedRequest.postDataJSON().scope.serverIds).toEqual([1]) await Promise.all([page.waitForRequest(`**/api/mcp/connections/${otherId}/grants`), selection.selectOption(otherId)]) await expect(revoke).toHaveCount(0) + await expect(serverCard).toHaveAttribute("aria-pressed", "false") await page.getByRole("checkbox", { name: "logs.query", exact: true }).check() await expect(create).toBeDisabled() releaseOtherGrants()