Skip to main content
Glama
iarbor04

yandex-direct-mcp

by iarbor04

yandex-direct-mcp

MCP-сервер для Яндекс Директ API v5. Подключает рекламный аккаунт к AI-агенту (Claude Code, Cursor и любому другому MCP-клиенту): задача ставится обычным текстом, агент сам собирает нужные вызовы API и разбирает ответ.

Ты:    посмотри, куда за август ушёл бюджет и что откручивается без конверсий
Агент: [direct_report] → 12 кампаний, 340 фраз
       Расход 214 800 ₽. Кампания «Поиск / Бренд» — 38%, CPA 610 ₽.
       17 фраз потратили 31 400 ₽ при нуле конверсий — вот они, отключаем?

Без зависимостей: один файл на Node.js, транспорт stdio, запросы через встроенный fetch.

  • Токен хранится локально в файле с правами 600 и никуда, кроме api.direct.yandex.com, не уходит.

  • Изменения — по подтверждению. MCP-клиент спрашивает разрешение на каждый вызов; плюс есть режим «только чтение», который блокирует изменяющие методы на уровне сервера.

  • Полный API, а не подмножество. Универсальный инструмент direct_call покрывает все сервисы v5 — от campaigns до keywordsresearch.

Что можно делать

Аналитика. Отчёты по любому срезу и периоду: кампании, группы, объявления, ключевые фразы, поисковые запросы, гео, устройства, время суток, пол и возраст. Расход, клики, CTR, CPC, конверсии, CPA, сравнение периодов. Разбор поисковых запросов на мусор, поиск фраз с расходом без конверсий.

Управление. Создание и правка кампаний, групп, объявлений, ключевых фраз. Ставки и дневные бюджеты — в том числе пакетно, по правилу («CPA выше 2000 ₽ → срезать ставку на 20%»). Минус-слова, включение и остановка, отправка на модерацию, корректировки ставок по гео, устройствам и аудиториям, ретаргетинг.

Семантика. Проверка частотности фраз (keywordsresearch), справочники регионов и часовых поясов (dictionaries).

Регулярные задачи. Утренняя сводка расхода за вчера, еженедельный разбор поисковых запросов, оповещение о перерасходе — если MCP-клиент умеет расписание.

Подробные сценарии с примерами запросов: docs/usage.md.

Related MCP server: Yandex MCP Server

Требования

  • Node.js 18 или новее (нужен встроенный fetch).

  • Аккаунт Яндекс Директа.

  • Зарегистрированное приложение на oauth.yandex.ru с одобренной заявкой на доступ к API. Это главный барьер, и он занимает от часа до трёх суток — начни с него: docs/registration.md.

Установка

git clone https://github.com/iarbor04/yandex-direct-mcp.git
cd yandex-direct-mcp

Зависимостей нет, npm install не нужен.

Claude Code:

claude mcp add yandex-direct --scope user -- node "$PWD/server.js"

Cursor, Windsurf и другие клиенты с JSON-конфигом:

{
  "mcpServers": {
    "yandex-direct": {
      "command": "node",
      "args": ["/абсолютный/путь/yandex-direct-mcp/server.js"]
    }
  }
}

Инструменты появляются при старте клиента — после добавления сервера перезапусти сессию.

Авторизация

Порядок важен. Если сделать не в этом порядке, получишь ошибку 58 и потеряешь время — мы потеряли.

1. Заявка на доступ к API

Регистрируешь приложение на oauth.yandex.ru и подаёшь заявку в интерфейсе Директа: «Мои заявки». Рассмотрение — в рабочие дни РФ с 10:00 до 19:00, от часа до трёх суток, в пиковые периоды до семи дней.

Что писать в форме (готовые тексты для всех полей, включая описание схемы взаимодействия и диаграмму) — docs/registration.md.

Без одобренной заявки не работает даже песочница. Проверено: api-sandbox.direct.yandex.com отдаёт ту же ошибку 58, что и боевой API. Отладиться «пока на тестовых данных» не получится.

2. Токен

./save-token.sh <CLIENT_ID>

Скрипт покажет ссылку авторизации, дождётся, пока ты вставишь адресную строку после редиректа (ввод скрытый — ни URL, ни токен не попадают в историю shell), вытащит access_token, положит в ~/.config/yandex-direct/token с правами 600 и сразу прогонит проверку доступа.

<CLIENT_ID> — идентификатор того приложения, на которое одобрена заявка. Скрипт запомнит его в config.json, дальше можно запускать без аргумента.

Вручную то же самое: открыть https://oauth.yandex.ru/authorize?response_type=token&client_id=<CLIENT_ID>, забрать токен из адресной строки после #access_token= (до &) и положить в файл.

3. Проверка

printf '%s\n' \
  '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{}}}' \
  '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"direct_status","arguments":{}}}' \
  | node server.js

Либо просто спроси у агента: «проверь доступ к Директу». Успешный ответ показывает логин, валюту аккаунта и остаток баллов.

Грабли, на которые мы напоролись

Симптом

Причина

Что делать

error 58 — «Незавершенная регистрация», хотя заявка одобрена

Токен получен под другим приложением, не тем, на которое одобрена заявка. Легко нарваться, если приложений несколько

Открой одобренную заявку, сверь Client ID, получи токен именно под ним

error 58 в песочнице

Песочница тоже требует одобренной заявки

Ждать одобрения, обходного пути нет

Повторная авторизация возвращает тот же самый токен

Яндекс отдаёт уже выданный токен, пока доступ приложению не отозван

Отозвать доступ на id.yandex.ru/personal/data-access, затем авторизоваться заново

error 53 — «Недействительный OAuth-токен»

Токен отозван, истёк или скопирован с обрезкой

Получить заново через ./save-token.sh

clients.get отвечает, но campaigns.get возвращает пустой список

Токен выдан под логином, в котором нет кампаний

Получить токен под нужным логином. Повторная заявка не нужна: она одобрена на приложение, а не на пользователя

Заявку требуется подать повторно после пересоздания приложения

Одобрение привязано к Client ID, а не к аккаунту

Не удалять одобренное приложение. Если удалил — новая заявка, в описании сослаться на прежний Client ID

Отдельно: токен нельзя вставлять в чат агента — он осядет в истории переписки. Для этого и сделан save-token.sh со скрытым вводом. Если всё же вставил — отзови доступ на id.yandex.ru/personal/data-access и получи новый.

Инструменты

Инструмент

Назначение

direct_status

Есть ли токен, какая среда, живой ли доступ (пробный clients.get), остаток баллов. Токен не раскрывается

direct_reference

Шпаргалка: сервисы, методы, примеры params, типы отчётов, единицы ставок, лимиты

direct_call

Универсальный вызов POST /json/v5/{service} с телом {method, params}

direct_report

Reports API: отправляет ReportDefinition, дожидается готовности (коды 201/202), возвращает TSV

Конфигурация

~/.config/yandex-direct/config.json:

{
  "token": "",
  "client_id": "…",
  "client_login": "",
  "sandbox": false
}

Токен читается при каждом вызове — после его замены сервер перезапускать не нужно.

Переменная окружения

Смысл

YANDEX_DIRECT_TOKEN

Токен напрямую, приоритетнее файлов

YANDEX_DIRECT_CLIENT_LOGIN

Логин клиента для агентского аккаунта (заголовок Client-Login)

YANDEX_DIRECT_SANDBOX=1

Работать с песочницей

YANDEX_DIRECT_READONLY=1

Блокировать add, update, delete, suspend, resume, moderate, set

YANDEX_DIRECT_CONFIG_DIR

Другой каталог конфигурации

Порядок поиска токена: YANDEX_DIRECT_TOKEN → config.json → ~/.config/yandex-direct/token.

Лимиты и стоимость

Каждый вызов тратит баллы (Units); остаток приходит в заголовке ответа и печатается в шапке результата. Обычный get — около 10 баллов, отчёты дороже. Суточный лимит зависит от аккаунта (у обычного клиента — порядка 160 000, на живую работу с запасом).

Метод get отдаёт максимум 10 000 объектов за раз — дальше постранично через LimitOffset. Ставки задаются в микроединицах: 30000000 = 30 ₽. У отчёта ReportName должен быть уникальным, иначе Директ вернёт ранее сформированный отчёт.

Схема взаимодействия

Схема взаимодействия с API Яндекс Директа

Исходник: docs/scheme.html — пригодится, если понадобится своя версия картинки для заявки.

Лицензия

MIT — см. LICENSE.

Available Tools

4 tools
direct_callA

Универсальный вызов Яндекс Директ API v5: POST на /json/v5/{service} с телом {method, params}. Покрывает всё управление: кампании, группы, объявления, ключевые фразы, ставки, ретаргетинг, справочники. Сначала загляни в direct_reference за именами сервисов, методов и формой params.

NameRequiredDescriptionDefault
methodYesМетод сервиса: get, add, update, delete, suspend, resume, archive, moderate, set, setAuto.
paramsNoОбъект params запроса (SelectionCriteria, FieldNames, массивы объектов и т.д.).
sandboxNotrue — бить в песочницу, false — в боевой API. По умолчанию из конфига.
serviceYesСервис API v5, например campaigns, adgroups, ads, keywords, bids, dictionaries.
client_loginNoЛогин клиента для агентского аккаунта (заголовок Client-Login). По умолчанию берётся из конфига.

TDQS

A3.9/5.0
Behavior2/5

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

With no annotations, the description must carry the behavioral burden, but it only states the HTTP mechanics and broad scope. It does not warn that this universal call can mutate or destroy production data (delete, archive, suspend are possible), nor mention sandboxing, auth needs, or side effects. 'Покрывает всё управление' hints at writes but does not disclose consequences.

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

Conciseness5/5

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

Three dense sentences with no filler. The first sentence front-loads the core call pattern, the second scopes what it covers, and the third gives a direct pointer to the reference tool. Every sentence earns its place.

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

Completeness3/5

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

The description is serviceable for a generic wrapper: it names the endpoint shape, scope, and prerequisite reference. But with no annotations or output schema, it omits auth context, sandbox behavior, and any statement about the raw response shape; those are left to schema fields, which is a noticeable gap for a tool that can perform destructive operations.

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

Parameters4/5

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

Schema coverage is 100%, so the baseline is 3. The description adds real semantic value by showing how parameters map to the request structure: service goes into the URL path and method/params form the JSON body. It also tells the agent where to find valid service/method names, though sandbox and client_login are left to the schema.

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?

The description is explicit: 'Универсальный вызов Яндекс Директ API v5' followed by the exact HTTP action 'POST на /json/v5/{service} с телом {method, params}'. It lists the covered resource domains (campaigns, adgroups, ads, keywords, bids, retargeting, dictionaries), which clarifies scope and distinguishes it from the more specialized sibling tools.

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?

The phrase 'Сначала загляни в direct_reference за именами сервисов, методов и формой params' gives a concrete prerequisite and points to an alternative tool. It clearly establishes direct_call as the universal management entry point, though it does not explicitly state when to prefer direct_status or direct_report.

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

direct_referenceA

Шпаргалка по API v5: список сервисов, методов, примеры params, типы отчётов, единицы ставок и лимиты. Вызывай перед первым direct_call, чтобы не гадать с полями.

NameRequiredDescriptionDefault

No parameters

TDQS

A4.5/5.0
Behavior4/5

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

There are no annotations, so the description carries the burden of behavioral disclosure. It does this well by listing the informational content and framing the tool as a read-only reference/cheat sheet. It does not explicitly state that it has no side effects or describe the return format, but the reference framing makes the behavior sufficiently clear.

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

Conciseness5/5

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

Two sentences with no wasted words: the first front-loads what the tool provides, and the second gives the actionable trigger. Every phrase earns its place.

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 zero-parameter reference tool, this is complete: it specifies the domain (API v5), the exact reference content, and when to call it. The lack of an output schema is mitigated by the explicit enumeration of what the cheat sheet covers.

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

Parameters4/5

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

The input schema is empty with zero parameters, so the baseline is 4. The description does not discuss this tool's parameters, but it uses the word 'params' only in the context of examples for direct_call, avoiding confusion. No additional parameter explanation is needed.

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?

The description identifies the tool as a 'cheat sheet' for API v5 and enumerates its contents: services, methods, params examples, report types, rate units, and limits. This clearly distinguishes it from sibling execution tools like direct_call and direct_report, so an agent knows exactly what this reference operation is for.

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?

It gives an explicit when-to-use instruction: call this before the first direct_call to avoid guessing fields. This is clear context, but it does not mention when not to use it or contrast it with direct_status/direct_report, so it stops short of a full 5.

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

direct_reportA

Статистика через сервис Reports API v5. Принимает ReportDefinition в params, сам дожидается готовности отчёта (коды 201/202 с повторами) и возвращает TSV.

NameRequiredDescriptionDefault
paramsYesReportDefinition: SelectionCriteria, FieldNames, ReportName (уникальное), ReportType, DateRangeType, Format: TSV, IncludeVAT, IncludeDiscount.
sandboxNoПесочница вместо боевого API.
client_loginNoЛогин клиента для агентского аккаунта.
wait_secondsNoСколько секунд ждать готовности отчёта, по умолчанию 180.
processing_modeNoРежим формирования отчёта, по умолчанию auto.

TDQS

A4/5.0
Behavior4/5

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

With no annotations, the description carries the transparency burden and discloses important behavior: it waits for report readiness, handles 201/202 retry codes, and returns TSV. It stops short of describing authentication, error conditions, or whether report generation has side effects or costs, but the main operational surprise is well covered.

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

Conciseness5/5

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

The description is a single dense sentence that front-loads the service and key behavior. It avoids repeating schema details and contains no filler, making it appropriately sized and easy to scan.

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

Completeness4/5

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

Given the rich schema coverage and the absence of an output schema, the description covers the non-obvious long-running behavior and the output format. It is mostly complete for invocation purposes, with minor gaps around error handling and explicit sibling-tool relationships.

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

Parameters3/5

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

The input schema already provides full descriptions for all parameters, including the nested ReportDefinition fields and defaults. The description adds only the high-level 'ReportDefinition' concept and TSV return format, which the schema already covers, so it contributes little beyond the structured definitions.

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

Purpose4/5

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

The description states the resource ('Reports API v5') and clarifies the operation: it accepts a ReportDefinition, waits for report readiness, and returns TSV. It is clear enough to identify the tool as a report/statistics retrieval tool, though it lacks an explicit action verb and does not directly contrast with sibling tools.

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?

The opening phrase 'Статистика через сервис Reports API v5' provides clear context for when to use the tool: to obtain statistics via Reports API v5. It states the self-waiting behavior, distinguishing it from a manual status-checking tool, but it does not explicitly list alternatives or exclusions.

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

direct_statusA

Проверить подключение к Яндекс Директу: найден ли токен, какая среда (боевая/песочница), доступен ли API (пробный clients.get) и сколько осталось баллов. Токен не раскрывается.

NameRequiredDescriptionDefault

No parameters

TDQS

A4.2/5.0
Behavior4/5

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

With no annotations, the description carries the full burden. It is transparent that the tool runs a probe API call ('пробный clients.get'), checks the token/environment/points, and explicitly states that the token is not disclosed. This covers the key behavioral facts an agent needs to know.

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

Conciseness5/5

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

A single Russian sentence front-loads the purpose and then provides a compact enumeration of checks. Every clause carries information, with no filler or repetition.

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

Completeness4/5

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

For a zero-parameter status tool with no output schema, the description gives enough context to call it correctly: it defines what is tested and what is not exposed. It does not spell out the exact return format, but this is not critical given the enumerated status categories.

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

Parameters4/5

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

The tool has zero parameters and the schema has full coverage, so there is nothing for the description to add about parameter meaning. The description's focus on connection state is consistent with requiring no input.

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?

The description names a concrete action ('Проверить подключение' – check connection) and a specific resource (Yandex Direct), and enumerates the exact diagnostics performed: token presence, environment, API availability via a trial clients.get, and remaining points. This clearly sets it apart from sibling tools like direct_call or direct_report.

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

Usage Guidelines3/5

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

The description makes it clear this is a diagnostic/health-check tool by framing the action as checking connection and listing status checks. However, it does not explicitly say 'use this when verifying setup before direct_call' or name alternatives/exclusions, so the guidance is implied rather than stated.

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 4 tool updatesv0.1.0
    • First observeddirect_call
    • First observeddirect_reference
    • First observeddirect_report
    • First observeddirect_status

TDQS

A4.3/5.0

Scored across 4 tools

Disambiguation4/5

Each tool has a clearly distinct role: status check, generic API call, report retrieval, and API reference. There is slight overlap because direct_call could theoretically hit report services or reference data, but the descriptions clearly separate async reports and reference lookups, so an agent can reliably choose the right tool.

Naming Consistency5/5

All tools share the 'direct_' prefix followed by a single concise word, creating a highly predictable and consistent naming scheme. The pattern is uniform and avoids mixed conventions or vague generic names.

Tool Count5/5

With 4 tools, the server is intentionally compact: a generic API call handles the long tail of operations, while status, report, and reference tools cover cross-cutting concerns. This is a well-scoped count for a broad but unified API surface.

Completeness5/5

The generic direct_call provides full coverage of all Yandex Direct API services and methods, so no CRUD operations are missing. direct_report adds proper handling of async report generation, and direct_reference closes the discoverability gap. The set is complete for its stated purpose.

Maintenance

ActivityStale
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    A
    maintenance
    Enables managing Yandex Direct PPC campaigns, ad groups, ads, and keywords, plus pulling performance statistics via the Yandex Direct API v5.
    46
    951 npm
    3
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables interaction with Yandex advertising and analytics APIs (Direct, Metrika, Audience, Webmaster, AdMetrica) through MCP tools, resources, and prompts for campaign management and data retrieval.
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Enables AI assistants to manage Yandex Direct advertising campaigns, ads, keywords, and reports via natural language using the Yandex Direct API v5.
    2
    1
    MIT