Skip to main content
Glama
Yandex Metrica MCP Server

Yandex Metrica MCP Server

Статистика

get_statistics
Read-onlyIdempotent

Query Yandex Metrica statistics for a counter to retrieve visits, users, pageviews, bounce rate, and conversions, and group results by date, traffic source, or device.

Instructions

Запрашивает Reporting API Яндекс Метрики (stat/v1/data) по счётчику. ПО УМОЛЧАНИЮ возвращает одну строку, агрегированную за период (без измерений), с visits/users/pageviews/bounceRate/avgVisitDurationSeconds. dimensions разбивает результат на строки (ym:s:date — динамика по дням, ym:s:lastTrafficSource — источники трафика, ym:s:deviceCategory — устройства), metrics задаёт нужные метрики — для конверсий это ym:s:goalreaches / ym:s:goalconversionRate (идентификаторы целей даёт list_goals). Префиксы не смешиваются: ym:s:* (визиты) и ym:pv:* (просмотры страниц) в одном запросе сочетаются только через filters. Ответ 400 «Incorrectly specified attribute» значит, что такого поля нет: не перебирать варианты имени, а взять поле из списка в dimensions. В ответе есть totals (итог по ВСЕМ строкам — для вопросов «сколько всего» суммировать не нужно), total_rows и sampled/sample_share (sampled=true означает, что данные приблизительные, посчитаны по доле sample_share; для точных цифр нужно сузить период или передать accuracy=full). Ответ 400 «Query is too complicated» значит, что Метрика не успела посчитать отчёт: сократить период (длинный — запросить частями по месяцу), accuracy при этом не снижать — не помогает. users — уникальные посетители за весь период: сумма users по дням их не даёт. counterId обязателен: id счётчика даёт list_counters.

Tool call template

Replace each placeholder with a value matching the input schema. Only required parameters are included; add optional parameters as needed.

{
  "id": 1,
  "jsonrpc": "2.0",
  "method": "tools/call",
  "params": {
    "arguments": {
      "counterId": "<counterId>"
    },
    "name": "get_statistics"
  }
}

Input Schema

NameRequiredDescriptionDefault
sortNoПоле сортировки; префикс '-' — по убыванию, например -ym:s:visits.
date1NoДата начала: YYYY-MM-DD или относительная (today, yesterday, NdaysAgo). По умолчанию 7daysAgo.
date2NoДата конца: YYYY-MM-DD или относительная (today, yesterday, NdaysAgo). По умолчанию yesterday.
limitNoМаксимум строк на странице (игнорируется, если задан autoPaginate).
offsetNoСмещение по строкам для постраничной выдачи, отсчёт с 1.
filtersNoВыражение фильтра Метрики, например ym:s:deviceCategory=='mobile'.
metricsNoМетрики (не больше 20 — лимит API), например ym:s:visits, ym:s:users, ym:s:bounceRate, ym:s:goal<id>reaches. По умолчанию — типовой набор.
accuracyNoТочность (размер выборки): low, medium, high, full (без сэмплирования, медленнее) или доля от 0 до 1 — API округляет её до степени десяти (0.1, 0.01). По умолчанию medium.
maxPagesNoЛимит страниц для autoPaginate. По умолчанию 100.
counterIdYesИдентификатор счётчика из list_counters.
dimensionsNoИзмерения для группировки; без них — итог за период. Частые: ym:s:date (по дням), ym:s:startOfWeek / ym:s:startOfMonth (по неделям / месяцам), ym:s:startURL / ym:s:endURL (страница входа / выхода; ym:s:startURLPath / ym:s:endURLPath — без домена), ym:s:referer, ym:s:lastTrafficSource, ym:s:lastsignSourceEngine (конкретный источник), ym:s:lastsignDirectClickOrder (кампания Директа), ym:s:lastsignUTMCampaign, ym:s:deviceCategory. Полей ym:s:URL, ym:s:page, ym:s:pageTitle, ym:s:week нет. Все просмотренные страницы: ym:pv:URL, ym:pv:URLPath, ym:pv:title, только с метриками ym:pv:* (ym:pv:pageviews, ym:pv:users).
autoPaginateNoЗабирает все строки, листая страницами максимального для API размера (склеивает data, сохраняет totals). Игнорирует `limit`; ограничен maxPages и лимитами по строкам/байтам (при их достижении выставляет _truncated).
directClientLoginsNoЛогины клиентов Яндекс Директа — нужны метрикам расходов Директа (ym:ad:*), без них API отвечает 403 direct_client_logins.

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv0.1.2

TDQS

A4.7/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Even though annotations already declare read-only/idempotent/open-world, the description adds a wealth of behavior beyond them: default aggregation, that `totals` already sums all rows (don't re-sum), that `sampled`/`sample_share` signal approximate data, that `accuracy=full` doesn't rescue a 'too complicated' error but shortening the period does, and that `users` is unique-over-period. These are exactly the mutation/safety-adjacent traits an agent needs.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Front-loads the default behavior and most-critical semantics first, then error handling. It is dense and long, but nearly every clause carries actionable signal (totals, sampling, error recovery), so little is wasted; the density is the main knock against a 5.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a 13-parameter tool with no output schema, the description covers the return contract (totals, total_rows, sampled), the required counterId source, and failure recovery, leaving nothing an agent needs to call it correctly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters5/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Although schema coverage is 100%, the description adds meaning the schema lacks: concrete `dimensions` values with use cases, which metric forms produce conversions, the ym:s vs ym:pv prefix rule, the nonexistent-field error path, and the directClientLogins/403 relationship. This clearly exceeds the baseline-3 credit for covered schemas.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

Names a specific verb (Запрашивает), the exact endpoint (stat/v1/data), and the resource (Яндекс Метрики счётчик). It immediately establishes what the tool does and states the default return shape (one aggregated row with visits/users/pageviews/etc.), which no sibling would share.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Gives strong operational context: how `dimensions` splits rows, how `metrics` selects metrics, that goal IDs come from list_goals and counterId from list_counters, and how to react to 400 errors. It stops just short of an explicit 'use raw_request instead when...' exclusion, so not a full 5.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.