export function cleanMcpList(values) {
    return [...new Set((values ?? []).map((value) => value.trim()).filter(Boolean))];
}
export function isBlankMcpValue(value) {
    return typeof value !== "string" || value.trim().length === 0;
}
export function mcpDryRunEnabled(context) {
    return context?.dryRun !== false;
}
export function mcpInvocationId(toolId, context) {
    return context?.invocationId?.trim() || `${toolId}:dry-run`;
}
export function createMcpAuditEvent(toolId, type, context, serverId, metadata) {
    return {
        type,
        toolId,
        invocationId: mcpInvocationId(toolId, context),
        dryRun: mcpDryRunEnabled(context),
        serverId,
        metadata: {
            ...(context?.auditMetadata ?? {}),
            ...(metadata ?? {}),
        },
    };
}
export function createMcpToolFailure(toolId, code, message, boundary, context, serverId) {
    return {
        ok: false,
        toolId,
        error: { code, message, boundary, publicSafe: true },
        audit: [createMcpAuditEvent(toolId, "agentCore.basicTool.mcp.rejected", context, serverId, { code })],
        events: ["basicTool.mcp.rejected"],
    };
}
export function normalizeMcpServerId(toolId, serverId, context) {
    const normalized = serverId?.trim() ?? "";
    if (isBlankMcpValue(normalized)) {
        return createMcpToolFailure(toolId, "MISSING_SERVER_ID", `${toolId} requires target.serverId`, "input", context, serverId);
    }
    return normalized;
}
export function ensureMcpServerScope(toolId, serverId, context) {
    const allowedServerIds = cleanMcpList(context?.allowedServerIds);
    if (allowedServerIds.length === 0 || allowedServerIds.includes(serverId))
        return undefined;
    return createMcpToolFailure(toolId, "SCOPE_REJECTED", `${toolId} target server is outside the allowed MCP server ids`, "scope", context, serverId);
}
export function ensureMcpToolPermissions(toolId, permissionsRequired, context, serverId) {
    const granted = cleanMcpList(context?.grantedPermissions);
    if (granted.length === 0)
        return undefined;
    const missing = permissionsRequired.filter((permission) => !granted.includes(permission));
    if (missing.length === 0)
        return undefined;
    return createMcpToolFailure(toolId, "PERMISSION_DENIED", `${toolId} is missing permissions: ${missing.join(", ")}`, "permission", context, serverId);
}
export function blockRealMcpExecution(toolId, context, serverId) {
    if (mcpDryRunEnabled(context))
        return undefined;
    return createMcpToolFailure(toolId, "REAL_EXECUTION_BLOCKED", `${toolId} only returns a guarded dry-run plan in the first implementation`, "contract", context, serverId);
}
