insert([ 'grant_id' => (int) ($entry['grant_id'] ?? 0), 'admin_id' => (int) ($entry['admin_id'] ?? 0), 'tool' => mb_substr((string) ($entry['tool'] ?? ''), 0, 64), 'resource' => mb_substr((string) ($entry['resource'] ?? ''), 0, 128), 'arguments' => $arguments === null ? null : mb_substr((string) $arguments, 0, 2000), 'result_rows' => max(0, (int) ($entry['result_rows'] ?? 0)), 'record_ids' => mb_substr(implode(',', array_slice((array) ($entry['record_ids'] ?? []), 0, 200)), 0, 1000), 'status' => mb_substr((string) ($entry['status'] ?? 'ok'), 0, 16), 'message' => mb_substr((string) ($entry['message'] ?? ''), 0, 255), 'duration_ms' => max(0, (int) ($entry['duration_ms'] ?? 0)), 'client_task_id' => mb_substr(preg_replace('/[^\w.\-:]/', '', (string) ($entry['client_task_id'] ?? '')), 0, 64), 'ip' => mb_substr((string) ($entry['ip'] ?? ''), 0, 45), 'create_time' => time(), ]); if (mt_rand(1, 500) === 1) { self::purge(); } } catch (\Throwable $e) { Log::error('[ai_mcp] 写访问日志失败: ' . $e->getMessage()); } } /** 清理超过保留期的日志(按需触发,每次最多 5000 行) */ public static function purge(): int { $before = time() - McpConfig::logRetentionDays() * 86400; return (int) Db::name('ai_access_log')->where('create_time', '<', $before)->limit(5000)->delete(); } /** 从结果行里取记录 ID,用于回答“谁看过哪个患者” */ public static function recordIds(array $rows): array { $ids = []; foreach ($rows as $row) { if (is_array($row) && isset($row['id']) && is_scalar($row['id'])) { $ids[] = (string) $row['id']; } } return $ids; } }