import type { PoolClient } from "pg" import { z } from "zod" import { mcpProtectedObjectSchema, mcpTemporaryGrantSchema } from "@mmapp/contracts/mcp" import { McpError } from "./security.js" // Data only. Every invocation uses the caller's existing transaction and fresh // bound values. Original grant checks and the policy decision remain in runtime. export const pollRuntimePolicySql = `/* mcp-poll:current-policy-source-v1 */ WITH protections AS MATERIALIZED ( SELECT object_ref,octet_length(object_ref::text) AS bytes FROM public.mcp_protections LIMIT 1001 ), grants AS MATERIALIZED ( SELECT payload,octet_length(payload::text) AS bytes FROM public.mcp_grants WHERE connection_id=$1 AND revoked_at IS NULL AND payload->>'credentialId'=$2 LIMIT 2 ) SELECT (SELECT count(*)::int FROM protections) AS protection_count, COALESCE((SELECT bool_or(bytes>8192) FROM protections),false) AS protection_oversize, (SELECT COALESCE(jsonb_agg(CASE WHEN bytes<=8192 THEN object_ref ELSE NULL END),'[]'::jsonb) FROM protections) AS protections, COALESCE((SELECT used FROM public.mcp_budget_buckets WHERE connection_id=$1 AND kind='calls' AND bucket=date_trunc('minute',now())),0) AS calls, COALESCE((SELECT used FROM public.mcp_budget_buckets WHERE connection_id=$1 AND kind='mutations' AND bucket=date_trunc('hour',now())),0) AS mutations, (SELECT count(*)::int FROM public.mcp_read_leases WHERE connection_id=$1 AND expires_at>now()) AS reads, COALESCE((SELECT bool_or(bytes>1048576) FROM grants),false) AS grant_oversize, (SELECT COALESCE(jsonb_agg(CASE WHEN bytes<=1048576 THEN payload ELSE NULL END),'[]'::jsonb) FROM grants) AS grants` const counter = z.number().int().nonnegative().safe() const sourceSchema = z.object({ protection_count: counter.max(1001), protection_oversize: z.boolean(), protections: z.array(z.unknown()).max(1001), calls: counter, mutations: counter, reads: counter, grant_oversize: z.boolean(), grants: z.array(z.unknown()).max(2), }).strict() export async function readPollRuntimePolicySource(client: Pick, connectionId: string, credentialId: string) { const result = await client.query(pollRuntimePolicySql, [connectionId, credentialId]) const parsed = result.rows.length === 1 && sourceSchema.safeParse(result.rows[0]) if (!parsed || !parsed.success) throw new McpError("STATE_UNAVAILABLE", "Источник проверки политики недоступен", 503) const source = parsed.data if (source.protection_count > 1000 || source.protection_count !== source.protections.length || source.protection_oversize) { throw new McpError("STATE_UNAVAILABLE", "Защиты превышают предел проверки; изменение заблокировано", 503) } const protections = source.protections.map(value => ({ object_ref: mcpProtectedObjectSchema.parse(value) })) if (source.grants.length > 1) throw new McpError("GRANT_INACTIVE", "Неоднозначный временный доступ") if (source.grant_oversize) throw new McpError("GRANT_INACTIVE", "Временный доступ превышает предел проверки") let temporaryGrant: z.infer | undefined if (source.grants.length) { const payload = z.record(z.string(), z.unknown()).parse(source.grants[0]) if (payload.credentialId !== credentialId) throw new McpError("GRANT_INACTIVE", "Временный доступ изменён") const { credentialId: _credential, ...grant } = payload temporaryGrant = mcpTemporaryGrantSchema.parse(grant) } return { protections, usage: { calls: source.calls, mutations: source.mutations, reads: source.reads }, temporaryGrant } } export type PollRuntimePolicySource = Awaited>