Yandex Metrica MCP
Connects an AI client to Yandex Metrica for authenticated analytics and limited raw API access.
Check connection status, token source/expiry, and credentials file location without exposing the token.
Start and finish OAuth/PKCE login from chat, save the token locally, and verify access.
Log out by deleting the locally saved token; environment-provided tokens are untouched.
List available Metrica counters with search and pagination.
List goals/conversions configured for a counter.
Query Metrica statistics/reports with metrics such as visits, users, pageviews, bounce rate, visit duration, and goal conversions.
Group reports by dimensions such as date, traffic source, and device; use filters, sorting, pagination, auto-pagination, and accuracy/sampling controls.
Make arbitrary Metrica API GET requests; POST/DELETE requests are allowed only with
confirmWrite=trueand can modify real objects.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@Yandex Metrica MCP Покажи посещаемость за последнюю неделю по источникам."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
Яндекс Метрика MCP
Яндекс Метрика MCP connects an AI application to your website's web analytics. Ask in natural language where visitors come from, how conversion changes, or where the bounce rate is growing — the assistant will pull data from your counter and explain the result. Connection starts right in the conversation: no need to create a token or edit configuration in advance.
Eight tools. Metrica counters, goals, and reports, connecting and disconnecting access, plus one universal API request.
Reports and conversions. Visits, users, pageviews, bounces, visit duration, sources, devices, and goals for a selected period.
Connection in chat. Yandex opens a login page; the one-time code is valid for 10 minutes, and the server checks access to counters right after connection.
Regular requests are read-only. Specialized tools do not change counters, goals, or Metrica data.
No silent truncation. The report shows totals and a sampling flag; when the result is large, the server notes if it hit the limit.
Try with your first message:
How many visits, users, and bounces did my site have in the last week?
Connect server · See scenarios · Open technical documentation
See it work in a minute
You: Connect Яндекс Метрику.
Assistant: Gives a link to sign in to Yandex. Open it under an account that has access to the needed counters, confirm access, and send back the shown code.
You: Sends the code from the Yandex page.
Assistant: Connects Metrica, checks whether counters are visible, and reports the result. No need to restart the application.
You: For the last 30 days, show traffic sources and conversion for the “Checkout” goal.
Assistant: Finds the goal, builds a report by sources, and shows visits, goal achievements, and conversion. If Metrica applied sampling, it notes that the numbers are approximate.
Related MCP server: ya-metrics-mcp
Contents
Quick start
You need Node.js 20 or newer. The server runs via npx, so no separate package installation is required.
Add the server to your AI application — an example for Codex is open below, other applications are collected in collapsible instructions.
Write: “Connect Яндекс Метрику”. The assistant will walk you through Yandex login and immediately check that it can see your counters.
Ask your first question, for example: “Which sources gave the most visits last month?”
Through the application interface:
Open Settings → Plugins → MCP servers.
Click Add server.
Add the launch command
npx -y mcp-yandex-metrica@latest.
Through the command line:
codex mcp add yandex-metrica -- npx -y mcp-yandex-metrica@latestCheck the connection:
codex mcp listThen in the Codex chat ask: “Connect Яндекс Метрику”.
claude mcp add --transport stdio --scope user yandex-metrica -- npx -y mcp-yandex-metrica@latestCheck the server with the command:
claude mcp listThen start the conversation by asking to connect Metrica.
Open Settings → Developer → Edit Config and add the server to claude_desktop_config.json:
{
"mcpServers": {
"yandex-metrica": {
"command": "npx",
"args": ["-y", "mcp-yandex-metrica@latest"]
}
}
}After saving, open a new conversation and ask to connect Metrica.
For all projects create ~/.cursor/mcp.json; for the current project only — .cursor/mcp.json:
{
"mcpServers": {
"yandex-metrica": {
"command": "npx",
"args": ["-y", "mcp-yandex-metrica@latest"]
}
}
}In the Cursor chat, the server will appear among available tools. Ask to connect Metrica and go through Yandex login.
Open the command palette and run MCP: Open User Configuration. Add to mcp.json:
{
"servers": {
"yandex-metrica": {
"type": "stdio",
"command": "npx",
"args": ["-y", "mcp-yandex-metrica@latest"]
}
}
}Check the launch with the command MCP: List Servers, then open the chat and ask to connect Metrica.
What you can ask for
Understand what's happening with the site
“How many visits, users, and pageviews were there in the last week?”
“Show daily traffic dynamics for June.”
“On which devices is the bounce rate higher?”
Find the traffic source and evaluate its quality
“Show traffic sources for the month and sort by visits.”
“Compare organic search and ads by users and bounces.”
“Which sources gave the most clicks this week?”
Work with conversions
“What goals are set up in the counter?”
“What is the conversion for the “Checkout” goal over 30 days?”
“Show the sources that brought the most goal achievements.”
Check access and data accuracy
“Which counters are available to me?”
“Show the connection status to Metrica.”
“Are the data in this report accurate or did Metrica use sampling?”
How it works
The server works with three familiar entities:
Entity | What you can find out |
Counter | The site name, its identifier, and availability for your account. |
Goal | Conversions configured on the counter and their identifiers. |
Report | Metrics and slices for a period: for example, visits by day, source, or device. |
Usually the assistant first finds an available counter, then — if needed — a goal, and only then builds a report. The Metrica response includes a total across all rows, the output size, and a sampling flag.
What can change data
Action | What happens |
List of counters, goals, and reports | Read-only access to Metrica data. |
Connection | Saves the access token locally on your computer and verifies it by reading counters. Does not change anything in Metrica. |
Disconnection | Removes only the token saved on the computer. The application's access in Yandex ID remains; you can revoke it separately there. |
Arbitrary API request |
|
The server marks an arbitrary write as a potentially destructive action. How exactly the AI application requests confirmation depends on the application itself; before such a request, check the path, method, and data.
Connection and configuration
For normal use, no token is needed in advance:
In the chat, ask to connect Яндекс Метрику.
Open the Yandex OAuth link under an account with access to the needed counters.
Confirm access and send the code to the assistant. It is valid for 10 minutes and is exchanged for a token only inside the running server.
The server uses PKCE: the code from the chat cannot be exchanged for a token on its own. The received token is stored locally in ~/.config/mcp-yandex-metrica/credentials.json with owner-only permissions. If a refresh token is saved, access is renewed automatically.
For CI and non-standard setups, configuration via environment variables is available:
Variable | Purpose |
| Ready OAuth token with |
| Default counter for requests without |
| Client ID of your own OAuth application instead of the Ask Ads application. |
| Language of labels in API responses; default is |
| Request timeout; default is 60,000 ms. |
| Number of retries on temporary errors; default is 3. |
| API base URL; default is |
If you use your own OAuth application, request the permission “Getting statistics, reading parameters of your own and trusted counters” (metrika:read) in it.
Data and telemetry
By default, the server sends anonymous technical telemetry: a random installation identifier, event or tool name, server version, Node.js version, OS, and information about the connected AI client. It does not include the token, counter data, tool arguments, your messages, or environment variable values.
To disable telemetry for Ask Ads MCP servers, set the environment variable:
ASKADS_TELEMETRY=0Limitations
Metrica sampling. On large periods or complex reports, the API may return approximate data. Check the
sampledandsample_sharefields; for a more accurate calculation, narrow the period or useaccuracy: "full".Report size. A single request returns up to 10,000 rows. Automatic pagination stops at no more than 100 pages, 100,000 rows, or roughly 1 MB of data and marks an incomplete response with the
_truncatedfield.Request retries. The timeout for one request is 60 seconds. The server makes up to three retries on temporary errors: for
GET— on network errors,429, and5xx; forPOSTandDELETE— only on429, to avoid repeating a modifying action. The delay respectsRetry-Afterand does not exceed 30 seconds.Production data. Metrica has no sandbox. Specialized tools read data, but
POSTandDELETEthrough an arbitrary request change real objects.No background monitoring. The server works when called by the AI application and does not track metrics on its own. If the application supports scheduled tasks, you can set up a periodic report request in it.
Technical documentation
MCP capabilities catalog — pages by user tasks for each tool.
All tools — parameters, responses, and limits for each tool.
Development documentation — project structure and working with the demo.
Support
Found a bug or missing a scenario? Create an issue or write to Telegram.
Available Tools
8 toolsauth_statusСтатус подключения к МетрикеARead-onlyIdempotent
Показывает, подключена ли Яндекс Метрика: есть ли токен, откуда он взят (переменная окружения YANDEX_METRIKA_TOKEN или сохранённый вход), когда истекает и где лежит файл с сохранёнными данными. Ничего не отправляет в сеть и не показывает сам токен. Вызовите это, если инструменты Метрики отвечают, что подключение не настроено.
Inputs: no named parameters.
finish_loginЗавершить подключение МетрикиAIdempotent
Второй шаг подключения: обменивает код подтверждения из start_login на токен доступа, сохраняет его в файл только для владельца (0600) и сразу проверяет живым запросом к Метрике. После успеха остальные инструменты работают немедленно — перезапускать клиент не нужно. Код одноразовый и живёт 10 минут: если он не принят, вызовите start_login заново и попросите свежий.
Inputs: code (required).
get_statisticsСтатистикаARead-onlyIdempotent
Запрашивает 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.
Inputs: counterId (required), sort, date1, date2, +9 more.
list_countersСписок счётчиков МетрикиARead-onlyIdempotent
Возвращает счётчики Яндекс Метрики, доступные токену (Management API). У каждого счётчика есть id, name и site2 (домен сайта) — id используется в get_statistics и list_goals. Фильтр по подстроке имени или сайта задаётся параметром search. На один сайт бывает несколько счётчиков (старый и новый, тестовый, отдельный для поддомена) — у каждого свои данные.
Inputs: offset, search, perPage.
list_goalsСписок целей счётчикаARead-onlyIdempotent
Возвращает цели (конверсии), настроенные на счётчике Метрики (Management API). Идентификаторы целей нужны, чтобы запросить метрики конверсий (ym:s:goalreaches / ym:s:goalconversionRate) в get_statistics. counterId обязателен: id счётчика даёт list_counters.
Inputs: counterId (required).
logoutОтключить МетрикуADestructive
Удаляет сохранённый токен Метрики с диска. Токен, заданный переменной окружения YANDEX_METRIKA_TOKEN, не трогает — его нужно убирать из конфигурации клиента вручную. Доступ, выданный приложению, остаётся активным на стороне Яндекса: отозвать его можно в Яндекс ID.
Inputs: no named parameters.
raw_requestПроизвольный запрос к API Яндекс МетрикиADestructive
Универсальный запрос: обращается напрямую к любому пути API Яндекс Метрики — например "management/v1/counters", "management/v1/counter/{id}/goals", "stat/v1/data". Нужен для эндпоинтов, у которых нет отдельного инструмента. query уходит в строку запроса, body отправляется как JSON для POST. GET выполняется свободно; POST и DELETE — это запись, им нужен confirmWrite=true.
Inputs: path (required), body, query, method, +1 more.
start_loginНачать подключение МетрикиARead-onlyIdempotent
Первый шаг подключения Яндекс Метрики без правки конфигурации и без перезапуска клиента. Возвращает ссылку на страницу Яндекс OAuth. Покажите ссылку пользователю целиком и попросите: открыть её в браузере под аккаунтом, у которого есть доступ к нужным счётчикам, подтвердить доступ и прислать показанный код подтверждения. Полученный код передайте в finish_login. Код действует 10 минут. Сам по себе код бесполезен для постороннего: обменять его может только этот сервер.
Inputs: no named parameters.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Most tools target clearly distinct operations: reporting (get_statistics), discovery (list_counters, list_goals), auth lifecycle (start_login/finish_login/auth_status/logout), and one escape hatch (raw_request). The only real overlap is that raw_request can hit stat/v1/data and management endpoints, duplicating get_statistics/list_counters, but its description frames it as a fallback for endpoints lacking a dedicated tool.
Core tools follow a clean verb_noun snake_case pattern (get_statistics, list_counters, list_goals, start_login, finish_login). Minor deviations are auth_status (noun_phrase) and raw_request/logout, but all remain readable and predictable.
Eight tools is well-scoped for a Yandex Metrica reporting server: reporting, two discovery tools, four auth-lifecycle tools, and a generic fallback. Nothing feels padded or missing at the count level.
Read-oriented coverage is solid and the auth lifecycle is complete (status, login start/finish, logout), with raw_request covering write/edge endpoints. Minor gaps: no tool to enumerate valid dimension/metric fields despite references to such a list, no counter/goal detail or write operations, and logout doesn't revoke the token server-side.
Maintenance
Related MCP Connectors
Read-only Yandex Metrika MCP. Query visits, sources, geo, devices and more in plain language.
Cookie-free web analytics MCP server: read stats, create UTM links, goals and ad costs.
MCP for Yandex Direct: manage ad campaigns & analytics from Claude or ChatGPT
MCP server for querying and analyzing data from ad platforms, analytics tools, and spreadsheets
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceA Model Context Protocol (MCP) server that provides access to Yandex Metrika analytics data through various tools and functions. This server allows AI assistants and applications to retrieve comprehensive analytics data from Yandex Metrika accounts.1-
- AlicenseCqualityDmaintenanceMCP server for Yandex Metrika analytics, enabling AI assistants to access traffic, content, demographics, conversion, e-commerce, and drill-down reports.312MIT
- AlicenseNot gradedqualityDmaintenanceRead-only MCP server for Yandex Metrika analytics, enabling report retrieval via MCP clients like Claude Code or Cursor without modifying any data.150 npmMIT
- AlicenseAqualityBmaintenanceMCP server for Yandex Metrica — query your web analytics in plain language from Claude, Cursor, and other AI agents. Secretless one-command login (PKCE), read-only, TypeScript.12499 npm15MIT