The post has been translated automatically. Original language: Russian
How AI is changing the way it works with monitoring. Ollama, MCP and Automation for L2 engineers
System monitoring is transformed from a set of graphs into a full-fledged observability infrastructure. The classical scheme of "a tool collects data, a person analyzes" is being replaced by a third participant, the AI layer. The model can read metrics, logs, and traces, compare data from different sources, and formulate hypotheses faster than a human can do it manually.
This is not a substitute for an engineer, but an assistant. Someone who finds correlations in seconds that take minutes for a living specialist to find. We are analyzing how this layer is arranged and how to assemble it at home.
Ollama. AI on its own hardware
Ollama is a program that runs large language models locally, without the cloud and without subscriptions. This is important for companies where monitoring data is considered sensitive. Server IP addresses, service names, query fragments — all this cannot always be sent to a cloud service based on security policy.
The installation is simple. After installation(https://ollama.com ) execute the command ollama pull llama3.1:8b the model is ready for operation. It is available via the HTTP API on port 11434, and any program can send it a request.
The minimum requirements for a 7-8 billion parameter model are 4 CPU cores and 16 GB RAM. GPU is optional, but with it, responses come in seconds instead of tens of seconds.
Which model to choose
All options are free and open-source:
- LLaMA 3.1 8B from Meta. The most popular, understands technical texts well.
- Mistral 7B. She is good at logical analysis and responds compactly.
- Gemma 2B from Google. Lightweight, it will run even on a laptop with 8 GB of RAM.
- Phi-4 14B from Microsoft. The best one for step-by-step incident analysis.
LLaMA or Mistral is enough to start. Both run on a CPU with 16 GB of RAM and provide adequate answers according to metrics and logs.
MCP. How AI gets access to Grafana
MCP (Model Context Protocol) is the protocol that the model uses to access external systems. Without it, the AI responds only from its memory. With it, he can make a request to Prometheus, read logs from Loki, watch traces in Tempo.
Example. You are asking "what is the current CPU on the web-01 server". The AI connects to Prometheus via MCP, executes the node_cpu_seconds_total{instance="web-01"} query, receives data, and formulates a response in human language. "The CPU on web-01 is now 73%, an hour ago it was 45%, the growth is stable."
There is a mcp-grafana community solution for Grafana. It gives the model access to dashboards, metrics, logs, and alerts. This is not an official Grafana Labs product, but a solution from the community, so it requires manual configuration.
Stack on Docker Compose
The entire AI layer is lifted by a single docker-compose file. Three services on the same network:
services:
ollama:
image: ollama/ollama:latest
ports: ["11434:11434"]
volumes: [ollama-data:/root/.ollama]
open-webui:
image: ghcr.io/open-webui/open-webui:main
ports: ["3000:8080"]
environment:
- OLLAMA_BASE_URL=http://ollama:11434
n8n:
image: n8nio/n8n
ports: ["5678:5678"]After docker compose up -d, we get three working components. Ollama on port 11434, Open WebUI (web interface) on 3000, n8n (automation) on 5678. We download the model with the docker exec -it command ollama ollama pull llama3.1:8b — it will be saved in volume and will survive restarts.
n8n. Routine automation
n8n is a visual automation constructor, similar to Zapier, but open-source and installed on its own server. In the context of monitoring, it solves the classic problem of linking an alert with analysis and notification.
The scenario looks like this. The Alertmanager sends an alert to n8n via a webhook. n8n generates a request to the AI with the alert context. The AI goes to Grafana via MCP, collects metrics and logs for the required period. n8n sends the finished analysis to Slack.
In the morning, the engineer opens Teams and sees not "CPU high on web-03", but a complete analysis. What happened when it started is the likely reason to check first.
What does this give the support engineer in practice?
Primary analysis without PromQL. Previously, I had to remember the syntax, confuse rate and irate, and select aggregation. Now you ask in a human way, "show the load on the web servers in an hour," and the AI itself writes the correct query.
Correlation without manual search. Previously, we opened three tabs — metrics, logs, and traces — set the same period and compared them with our eyes. Now you ask, "is there a connection between the increase in order-service latency and errors in the payment-service," and the model checks both services itself.
Escalation with ready-made data. Instead of "users are complaining about the brakes, something seems to be wrong with the base," the engineer passes on the specifics to the next level. "The latency of the order-service increased at 2:25 p.m. due to the depletion of the pool of connections to PostgreSQL. Active 100/100, in the connection pool exhausted logs, the database query takes 2.8seconds instead of 50ms. We need to check for connection leaks in the code."
Limitations to keep in mind
AI in monitoring is a powerful tool, but not a magic wand.
The model is hallucinating. AI is able to confidently write nonsense. Name a non-existent service, invent a metric, confuse servers. Conclusions are always checked against real data in the dashboard.
Local models are weaker than cloud models. LLaMA 8B responds slower and less accurately on the CPU than cloud-based Claude. It's enough for simple tasks, but it may not be enough for complex analysis.
MCP is a young technology. The protocol is less than two years old. Not all tools support it out of the box, and configuration often requires poking around in configs.
It is not a substitute for understanding the system. If the engineer does not know what a connection pool is, the AI's answer about its exhaustion will not help much. AI speeds up work, but it does not replace engineering knowledge.
Where to begin?
A simple way without the risk of breaking something:
- Install Ollama locally and download LLaMA 3.1 8B.
- Launch Open WebUI via Docker, connect to Ollama.
- Try asking monitoring questions in a chat — without MCP yet, just to understand how the model thinks.
- When you're comfortable, set up an MCP connection to Grafana and start working with real data.
Every step is valuable in itself. You don't need to install everything at once — move as you're ready.
Как AI меняет работу с мониторингом. Ollama, MCP и автоматизация для инженеров L2
Мониторинг систем превращается из набора графиков в полноценную observability-инфраструктуру. На смену классической схеме «инструмент собирает данные, человек анализирует» приходит третий участник — AI-слой. Модель умеет читать метрики, логи и трейсы, сопоставлять данные из разных источников и формулировать гипотезы быстрее, чем это делает человек вручную.
Это не замена инженера, а помощник. Тот, кто за секунды находит корреляции, на поиск которых у живого специалиста уходят минуты. Разбираем, как этот слой устроен и как собрать его у себя.
Ollama. AI на собственном железе
Ollama — программа, которая запускает большие языковые модели локально, без облака и без подписок. Это важно для компаний, где данные мониторинга считаются чувствительными. IP-адреса серверов, имена сервисов, фрагменты запросов — всё это не всегда можно отправлять в облачный сервис по политике безопасности.
Установка простая. После установки(https://ollama.com) выполняете команду ollama pull llama3.1:8b модель готова к работе. Она доступна через HTTP API на порту 11434, и любая программа может отправить ей запрос.
Минимальные требования для модели на 7-8 миллиардов параметров — 4 ядра CPU и 16 GB RAM. GPU не обязателен, но с ним ответы приходят за секунды вместо десятков секунд.
Какую модель выбрать
Все варианты бесплатные и open-source:
- LLaMA 3.1 8B от Meta. Самая популярная, хорошо понимает технические тексты.
- Mistral 7B. Сильна в логическом анализе, отвечает компактно.
- Gemma 2B от Google. Лёгкая, запустится даже на ноутбуке с 8 GB RAM.
- Phi-4 14B от Microsoft. Лучшая для пошагового разбора инцидентов.
Для старта достаточно LLaMA или Mistral. Обе работают на CPU с 16 GB RAM и дают адекватные ответы по метрикам и логам.
MCP. Как AI получает доступ к Grafana
MCP (Model Context Protocol) — протокол, через который модель ходит во внешние системы. Без него AI отвечает только из своей памяти. С ним он может выполнить запрос к Prometheus, прочитать логи из Loki, посмотреть трейсы в Tempo.
Пример. Вы спрашиваете «какой сейчас CPU на сервере web-01». AI через MCP подключается к Prometheus, выполняет запрос node_cpu_seconds_total{instance="web-01"}, получает данные и формулирует ответ человеческим языком. «CPU на web-01 сейчас 73%, час назад было 45%, рост стабильный».
Для Grafana есть community-решение mcp-grafana. Оно даёт модели доступ к дашбордам, метрикам, логам и алертам. Это не официальный продукт Grafana Labs, а решение от сообщества, поэтому требует ручной настройки.
Стек на Docker Compose
Весь AI-слой поднимается одним docker-compose файлом. Три сервиса в одной сети:
services:
ollama:
image: ollama/ollama:latest
ports: ["11434:11434"]
volumes: [ollama-data:/root/.ollama]
open-webui:
image: ghcr.io/open-webui/open-webui:main
ports: ["3000:8080"]
environment:
- OLLAMA_BASE_URL=http://ollama:11434
n8n:
image: n8nio/n8n
ports: ["5678:5678"]После docker compose up -d получаем три рабочих компонента. Ollama на порту 11434, Open WebUI (веб-интерфейс) на 3000, n8n (автоматизация) на 5678. Модель скачиваем командой docker exec -it ollama ollama pull llama3.1:8b — она сохранится в volume и переживёт перезапуски.
n8n. Автоматизация рутины
n8n — визуальный конструктор автоматизаций, аналог Zapier, но open-source и ставится на свой сервер. В контексте мониторинга он решает классическую задачу — связать алерт с анализом и уведомлением.
Сценарий выглядит так. Alertmanager отправляет алерт в n8n через webhook. n8n формирует запрос к AI с контекстом алерта. AI идёт в Grafana через MCP, собирает метрики и логи за нужный период. n8n отправляет готовый разбор в Slack.
Утром инженер открывает Teams и видит не «CPU high on web-03», а полный анализ. Что случилось, когда началось, вероятная причина, что проверять в первую очередь.
Что это даёт инженеру поддержки на практике
Первичный анализ без PromQL. Раньше приходилось вспоминать синтаксис, путать rate и irate, подбирать агрегацию. Теперь спрашиваешь по-человечески «покажи нагрузку на web-серверах за час», и AI сам пишет правильный запрос.
Корреляция без ручного поиска. Раньше открывали три вкладки — метрики, логи, трейсы — выставляли одинаковый период и сравнивали глазами. Теперь спрашиваешь «есть ли связь между ростом латентности order-service и ошибками в payment-service», и модель проверяет оба сервиса сама.
Эскалация с готовыми данными. Вместо «пользователи жалуются на тормоза, вроде что-то с базой» инженер передаёт следующему уровню конкретику. «Латентность order-service выросла в 14:25 из-за исчерпания пула соединений к PostgreSQL. Активных 100/100, в логах connection pool exhausted, запрос к БД занимает 2.8с вместо 50мс. Нужна проверка утечки соединений в коде».
Ограничения, о которых стоит помнить
AI в мониторинге — мощный инструмент, но не волшебная палочка.
Модель галлюцинирует. AI способен уверенно написать чушь. Назвать несуществующий сервис, выдумать метрику, перепутать серверы. Выводы всегда проверяются по реальным данным в дашборде.
Локальные модели слабее облачных. LLaMA 8B на CPU отвечает медленнее и менее точно, чем облачный Claude. Для простых задач хватает, для сложного анализа может не дотянуть.
MCP — молодая технология. Протоколу меньше двух лет. Не все инструменты поддерживают его из коробки, настройка часто требует ковыряния в конфигах.
Не заменяет понимание системы. Если инженер не знает, что такое connection pool, ответ AI про его исчерпание мало чем поможет. AI ускоряет работу, но не заменяет инженерные знания.
С чего начать?
Простой путь без риска что-то сломать:
- Поставьте Ollama локально и скачайте LLaMA 3.1 8B.
- Запустите Open WebUI через Docker, подключите к Ollama.
- Попробуйте задавать вопросы по мониторингу в чате — пока без MCP, просто чтобы понять, как модель думает.
- Когда освоитесь, настройте MCP-подключение к Grafana и начните работать с реальными данными.
Каждый шаг самоценен. Не нужно ставить всё сразу — двигайтесь по мере готовности.