yadirect-mcp
Yandex Direct MCP Server — отчёты и безопасное создание кампаний для AI-агентов
yadirect-mcp — локальный MCP-сервер для Яндекс Директа, который подключает рекламную отчётность и защищённую настройку кампаний к Claude Code, OpenAI Codex, Hermes Agent, ZCode и другим MCP-совместимым AI-агентам.
Вместо десятков низкоуровневых методов API агент получает семь понятных инструментов для аналитики и один опциональный инструмент для создания кампании. Инструмент здесь соответствует задаче, а не методу API: например, direct_account_settings за один вызов читает корректировки, ретаргетинг и общие минус-фразы — три сервиса, которые в разборе кампании нужны вместе. Большие отчёты сохраняются в TSV, а в контекст модели возвращаются только сводка и preview — это экономит токены и не обрезает данные.
По умолчанию сервер работает в режимеreport: все доступные инструменты только читают данные. Режим создания кампаний включается явно через YD_MODE=campaign_setup, требует preview и точного подтверждения и никогда автоматически не запускает показы.
Для чего нужен yadirect-mcp
Выгружать статистику Яндекс Директа естественным языком прямо из AI-агента.
Получать список клиентов агентства и кампаний рекламодателя.
Строить отчёты по показам, кликам, расходу, CTR, CPC, конверсиям и другим полям Reports API.
Читать настройки, которых в отчётах нет: корректировки ставок, условия ретаргетинга, общие наборы минус-фраз.
Видеть, куда ведёт реклама: посадочные страницы объявлений, их UTM-разметку и заполненность дополнений.
Проверять коды регионов до того, как они уедут в кампанию или в запрос частотности.
Сохранять полные выгрузки на диск и читать их постранично без повторного расхода баллов API.
Подготавливать текстово-графическую кампанию с группами, объявлениями и ключевыми фразами.
Проверять план кампании до записи и создавать объекты только после явного согласия пользователя.
Ограничивать доступ AI-агента белым списком клиентских логинов.
Проект полезен агентствам, PPC-специалистам, performance-маркетологам, аналитикам и разработчикам AI-автоматизаций для Яндекс Директа.
Related MCP server: yandex-marketing-mcp
Ключевые возможности
Возможность | Как реализовано |
Безопасный режим по умолчанию | В |
Агентский токен, много клиентов |
|
Большие отчёты без переполнения контекста | Полный TSV сохраняется на диск, модель получает totals и первые строки |
Частотность Вордстата |
|
Настройки мимо отчётов |
|
Посадочные страницы и UTM |
|
Гео без угадывания |
|
Корректные агрегаты | CTR, CPC и CR пересчитываются из суммарных метрик, а не складываются по строкам |
Онлайн- и офлайн-отчёты | Поддержаны ответы |
Контроль очереди | Семафор на логин и лимит |
Видимость баллов API | Заголовок |
Защита от чужого кабинета |
|
Защищённая запись | Preview → точная confirmation-фраза → последовательное создание объектов |
Без неожиданного запуска рекламы | Сервер не вызывает |
Как это работает
flowchart LR
U["Пользователь"] --> A["Claude Code / Codex / Hermes / ZCode"]
A <-->|"MCP over stdio"| M["yadirect-mcp"]
M <-->|"JSON API v5 / Reports API / Вордстат v4"| Y["Яндекс Директ"]
M -->|"полный TSV"| F["Локальная папка отчётов"]
M -->|"totals + preview + path"| AСервер использует локальный stdio-транспорт. MCP-клиент сам запускает Python-процесс, передаёт ему переменные окружения и завершает его вместе с сессией. Логи пишутся только в stderr, потому что stdout зарезервирован протоколом MCP.
Инструменты MCP
direct_list_clients
Возвращает логины клиентов агентства, ClientId, название и валюту. Метод использует agencyclients.get без заголовка Client-Login.
Параметр:
limit— максимум клиентов, по умолчанию1000.
direct_campaigns
Возвращает ID, имя, тип, состояние и статус кампаний клиента.
Параметры:
client_login— логин рекламодателя;include_archived— включить архивные кампании, по умолчаниюfalse.
direct_regions
Справочник регионов Директа (dictionaries.get, словарь GeoRegions): поиск кода по названию и обратная проверка готовых кодов.
Параметры:
query— часть названия, напримерМосква,Ростов,Татарстан; регистр и «ё» не важны;ids— коды для обратной проверки;client_login— нужен только агентскому токену: Директ требует заголовокClient-Loginна клиентских методах;limit— сколько совпадений вернуть, от1до200.
Нужен хотя бы один из query / ids: справочник целиком инструмент не отдаёт — это тысячи записей в контекст модели. Сам справочник загружается один раз на процесс, повторные вызовы баллов не тратят.
Смысл инструмента в том, что Директ коды регионов не проверяет. geo_ids: [999999] не вызовет ошибку — Вордстат вернёт частотность не по тому региону, а неверный RegionIds так же молча сузит показы. Поэтому каждое совпадение приходит с путём до корня: «Москва» — это и город 213, и «Москва и область» 1, и без родителей их не различить. Коды, которых нет в справочнике, возвращаются отдельным списком unknown_ids с предупреждением.
{
"query": "москва",
"matches": [
{"id": 213, "name": "Москва", "type": "City", "parent_id": 1,
"path": ["Весь мир", "Россия", "Москва и область"]},
{"id": 1, "name": "Москва и область", "type": "Region", "parent_id": 225,
"path": ["Весь мир", "Россия"]}
],
"total_matches": 2,
"truncated": false
}direct_account_settings
Настройки кабинета, которых нет в Reports API: корректировки ставок (bidmodifiers.get), условия ретаргетинга (retargetinglists.get) и общие наборы минус-фраз (negativekeywordsharedsets.get).
Параметры:
client_login— логин рекламодателя;sections— какие секции читать:bid_modifiers,retargeting_lists,negative_keyword_sets; пусто — все три;campaign_ids— для каких кампаний смотреть корректировки; пусто — сервер сам возьмёт неархивные кампании клиента, но не более 50.
Инструмент закрывает разрыв в диагностике: отчёт покажет статистику в разрезе Device, Gender, Age, но не покажет выставленный коэффициент, а «нет мобильных конверсий» и «на мобильные стоит −100%» — это разные диагнозы. То же с общими минус-фразами: набор применён ко всем группам и не виден ни в одном отчёте.
Секции независимы: ошибка в одной приходит полем error внутри неё, остальные возвращаются как есть — нет доступа к ретаргетингу не должно означать потерю уже прочитанных корректировок. bidmodifiers.get принимает не более 10 кампаний за вызов, поэтому список режется на пачки автоматически. Если кампаний больше 50, ответ содержит truncated и campaigns_total, а не молча усечённую выборку. Длинные наборы минус-фраз приходят с полным keywords_count и первыми 50 фразами.
direct_ads
Объявления вместе с посадочными страницами (ads.get): куда ведёт реклама, что в заголовках и текстах, размечены ли ссылки UTM.
Параметры:
client_login— логин рекламодателя;campaign_ids,ad_group_ids,ad_ids— чем сузить выборку; пусто — все объявления клиента;include_archived— включить архивные, по умолчаниюfalse;limit— сколько объявлений забрать за вызов,1–10000.
Ссылки объявления в Reports API нет ни в одном типе отчёта: поле Href существует только здесь, а запрос его в отчёте отваливается с error_code=8000. Без него разбор упирается в стену на самом частом вопросе — на какую страницу идёт группа и одна ли это главная на весь аккаунт.
Кроме списка объявлений инструмент возвращает landing_pages — сводку по уникальным URL с числом объявлений, кампаниями и разобранными UTM, — а также domains и счётчики ads_without_href и ads_without_utm. Динамические параметры Директа ({campaign_id} и прочие) остаются в сводке шаблонами: «метка есть» и «метка работает» должны различаться. Дополнения приходят фактом наличия (sitelinks, vcard, image), а не идентификаторами — за содержимым нужен отдельный вызов, и в каждом ответе оно не нужно.
Пустой SelectionCriteria метод не принимает, поэтому без явной выборки сервер сам читает кампании клиента и отправляет CampaignIds пачками по 10, как требует API; при более чем 50 кампаниях ответ содержит truncated и campaigns_total. Архивные отсеиваются по полю State, а не через критерий отбора. Запрашивается блок TextAd: у графических, видео и смарт-объявлений href придёт пустым, и это видно в ads_without_href, а не выглядит как «ссылок нет».
direct_report
Формирует отчёт через Reports API, сохраняет TSV и возвращает путь, число строк, колонки, итоги и preview.
Основные параметры:
client_login— логин рекламодателя;date_from,date_to— период в форматеYYYY-MM-DD;fields— поля отчёта, напримерDate,CampaignName,Impressions,Clicks,Cost;report_type— тип отчёта, по умолчаниюCUSTOM_REPORT;goals— ID целей Метрики;attribution_models— модели атрибуции;filters— фильтры Reports API;order_by— сортировка;limit— ограничение числа строк;include_vat— суммы с НДС или без него.
Поддерживаемые типы включают CUSTOM_REPORT, ACCOUNT_PERFORMANCE_REPORT, CAMPAIGN_PERFORMANCE_REPORT, ADGROUP_PERFORMANCE_REPORT, AD_PERFORMANCE_REPORT, CRITERIA_PERFORMANCE_REPORT, SEARCH_QUERY_PERFORMANCE_REPORT и REACH_AND_FREQUENCY_PERFORMANCE_REPORT.
Пример результата:
{
"path": "D:/yadirect-reports/client1_2026-06-01_2026-06-30_r_8f3a1c9d.tsv",
"rows": 18234,
"columns": ["Date", "CampaignName", "Impressions", "Clicks", "Cost"],
"totals": {
"Impressions": 1204331,
"Clicks": 43012,
"Cost": 1250430.5,
"Ctr": 3.57,
"AvgCpc": 29.07
},
"preview": [{"Date": "2026-06-01", "CampaignName": "Поиск | Москва"}],
"preview_truncated": true,
"units": {"spent": 12, "rest": 23695, "daily": 64000}
}direct_read_report
Читает ранее сохранённый TSV без нового обращения к API. Доступ разрешён только внутри YD_OUT_DIR и только для файлов .tsv.
Параметры:
path— абсолютный путь из ответаdirect_report;offset— первая строка, начиная с0;limit— размер страницы от1до1000.
direct_wordstat
Частотность Яндекс Вордстата: сколько раз за месяц искали фразу, какие запросы искали вместе с ней и какие похожие. Нужен на сборке семантики, при разборе статуса «Мало показов» и когда в отчёте надо отделить падение спроса от падения кампании.
Параметры:
phrases— до 50 фраз за вызов; операторы Директа работают (!, кавычки,+);geo_ids— регионы Директа, например[225]— Россия,[213]— Москва; пусто — без ограничения по региону;min_shows— отбросить подсказки с частотностью ниже порога;top— сколько подсказок каждого вида показать в ответе, от1до100.
Полный список уходит в YD_OUT_DIR тем же TSV, что и отчёты, и читается через direct_read_report. В ответ приходит сводка по каждой фразе: частотность самой фразы, количество вложенных и похожих запросов, топ тех и других.
client_login не нужен — данные Вордстата общие для всех кабинетов. Shows означает спрос в поиске за месяц, а не прогноз показов кампании: shows: 0 — спроса нет, shows: null вместе с полем note — Вордстат не ответил по этой фразе.
Метод живёт в устаревшем API v4, потому что аналога в v5 нет. Отсюда два следствия: в песочнице (YD_SANDBOX) инструмент недоступен, а баллы v4 считаются отдельно от v5 и в поле units не попадают. Отчёты Вордстата удаляются из очереди аккаунта сразу после выгрузки, в том числе когда вызов завершился ошибкой.
direct_campaign_setup
Доступен только при YD_MODE=campaign_setup. Создаёт одну новую TextCampaign, группы, текстовые объявления и ключевые фразы.
Параметры:
client_login— логин рекламодателя;campaign— объектCampaignAddItemбезId;ad_groups— группы безCampaignId, с локальными массивамиAdsиKeywords;confirmation— точная строка изconfirmation_requiredпосле одобрения preview.
Первый вызов всегда выполняется без confirmation и ничего не записывает. После проверки плана пользователь явно подтверждает операцию, и агент повторяет тот же вызов с полученной строкой.
Ресурсы MCP: база знаний по Директу
Правил настройки кампании гораздо больше, чем помещается в инструкции сервера, а инструкции едут в каждый запрос. Поэтому сервер отдаёт базу знаний ресурсами, которые модель читает по требованию: в инструкциях остаётся только то, без чего ошибка происходит молча (микроединицы, обязательный автотаргетинг, порядок подтверждения).
direct://kb— оглавление;direct://kb/<имя>— документ.
Документ | О чём |
| Что тулы сервера умеют и чего не делают, обход для автотаргетинга, порядок работы |
| Чек-лист первичной настройки: вводные от клиента, структура аккаунта, кампания, группы, объявления, UTM |
| Лимиты символов и фраз, требования модерации |
| Обязательные поля |
| Единая перфоманс-кампания, режим совместимости API v5 |
| Стратегии, обучение, минимальные бюджеты, оплата за конверсии |
| Счётчик и цели Метрики, ценность конверсии, модели атрибуции |
| Операторы фраз, правила минусовки, статус «Мало показов» |
| Автотаргетинг, корректировки ставок, ретаргетинг |
| Донастройка: порядок разбора, пороги по CPA, частота проверок |
| Наборы полей |
Источники — официальная справка Яндекс Директа и документация API v5, материалы eLama, публичная практика агентств. Ресурсы доступны в обоих режимах, включая report.
Требования
Windows 10/11, Linux или другая ОС с Python.
Python 3.11 или новее.
OAuth-токен Яндекс Директа с разрешением
direct:api.Доступ приложения к API Яндекс Директа.
MCP-клиент с поддержкой локального
stdio.
Для агентского сценария нужен токен представителя агентства. Официальные инструкции: регистрация приложения, получение OAuth-токена и авторизационные токены.
OAuth-токен даёт доступ к реальным данным и действиям пользователя Яндекс Директа. Не добавляйте токен в Git, README, issue, логи или скриншоты.
Установка на Windows
1. Получите исходный код
Скачайте архив из GitHub Releases или клонируйте репозиторий:
git clone https://github.com/Lermont/yamcp.git
Set-Location yamcp2. Создайте виртуальное окружение
py -3.11 -m venv .venv
.\.venv\Scripts\python.exe -m pip install --upgrade pip
.\.venv\Scripts\python.exe -m pip install .Если команда py -3.11 недоступна, проверьте установленные версии через py -0p или используйте python -m venv .venv.
3. Подготовьте каталоги и секрет
Для текущей PowerShell-сессии:
$env:YD_TOKEN = "y0_your_token"
$env:YD_OUT_DIR = "D:/yadirect-reports"
$env:YD_MODE = "report"
New-Item -ItemType Directory -Force $env:YD_OUT_DIRВ cmd.exe:
set YD_TOKEN=y0_your_token
set YD_OUT_DIR=D:\yadirect-reports
set YD_MODE=reportФайл .env.example — только документированный шаблон. Приложение намеренно не загружает .env автоматически: переменные передаёт оболочка или MCP-клиент.
Установка на Linux
Для Debian/Ubuntu при необходимости установите Python и модуль venv:
sudo apt-get update
sudo apt-get install -y python3 python3-venv gitЗатем установите сервер в изолированное окружение:
git clone https://github.com/Lermont/yamcp.git
cd yamcp
python3 -m venv .venv
.venv/bin/python -m pip install --upgrade pip
.venv/bin/python -m pip install .
mkdir -p "$HOME/yadirect-reports"Для текущей shell-сессии:
export YD_TOKEN='y0_your_token'
export YD_OUT_DIR="$HOME/yadirect-reports"
export YD_MODE='report'Для сервера или CI храните токен в секрет-хранилище, а не в репозитории. Не запускайте MCP-процесс как публичный сетевой сервис: текущая реализация рассчитана на локальный stdio.
Настройка переменных окружения
Переменная | Обязательна | По умолчанию | Назначение |
| Да | — | OAuth-токен с доступом к Яндекс Директ API |
| Нет | — | Логин агентства; информационная настройка |
| Нет | пусто | Разрешённые клиентские логины через запятую; пусто — любые |
| Нет |
| Каталог полных TSV-отчётов |
| Нет |
| Одновременные офлайн-отчёты на логин, от |
| Нет |
| Строки preview в MCP-ответе, от |
| Нет |
| Максимальное ожидание отчёта в секундах |
| Нет |
| Использовать sandbox API Яндекс Директа |
| Нет |
| Язык ошибок API: |
| Нет |
|
|
| Нет | пусто | Недельный бюджет кампании по умолчанию, в валюте кабинета; попадает в инструкции сервера |
Рекомендуемая production-конфигурация начинается с YD_MODE=report и непустого YD_ALLOWED_LOGINS.
Подключение к Claude Code
Claude Code запускает локальные MCP-серверы по stdio. Все параметры Claude должны стоять до имени сервера, а команда запуска — после --.
Windows PowerShell
claude mcp add --scope user --transport stdio `
--env "YD_TOKEN=y0_your_token" `
--env "YD_AGENCY_LOGIN=my-agency" `
--env "YD_ALLOWED_LOGINS=client-1,client-2" `
--env "YD_OUT_DIR=D:/yadirect-reports" `
--env "YD_MODE=report" `
yandex-direct -- `
"D:/path/to/yamcp/.venv/Scripts/python.exe" -m yadirect_mcpLinux
claude mcp add --scope user --transport stdio \
--env "YD_TOKEN=$YD_TOKEN" \
--env "YD_AGENCY_LOGIN=my-agency" \
--env "YD_ALLOWED_LOGINS=client-1,client-2" \
--env "YD_OUT_DIR=$HOME/yadirect-reports" \
--env "YD_MODE=report" \
yandex-direct -- \
/absolute/path/to/yamcp/.venv/bin/python -m yadirect_mcpПроверка:
claude mcp list
claude mcp get yandex-directВ интерактивной сессии выполните /mcp. Для командных отчётов, которые могут ждать очередь API, при необходимости добавьте в .mcp.json поле "timeout": 660000.
Официальная документация: Connect Claude Code to tools via MCP.
Подключение к OpenAI Codex
Codex CLI, IDE extension и Codex desktop используют общую MCP-конфигурацию config.toml. Пользовательский файл находится в ~/.codex/config.toml; конфигурацию одного доверенного проекта можно хранить в .codex/config.toml.
Windows
[mcp_servers.yandex-direct]
command = "D:/path/to/yamcp/.venv/Scripts/python.exe"
args = ["-m", "yadirect_mcp"]
cwd = "D:/path/to/yamcp"
startup_timeout_sec = 20
tool_timeout_sec = 660
default_tools_approval_mode = "writes"
env_vars = ["YD_TOKEN"]
[mcp_servers.yandex-direct.env]
YD_AGENCY_LOGIN = "my-agency"
YD_ALLOWED_LOGINS = "client-1,client-2"
YD_OUT_DIR = "D:/yadirect-reports"
YD_MODE = "report"
YD_LANG = "ru"Перед запуском Codex задайте секрет в PowerShell:
$env:YD_TOKEN = "y0_your_token"
codexLinux
[mcp_servers.yandex-direct]
command = "/absolute/path/to/yamcp/.venv/bin/python"
args = ["-m", "yadirect_mcp"]
cwd = "/absolute/path/to/yamcp"
startup_timeout_sec = 20
tool_timeout_sec = 660
default_tools_approval_mode = "writes"
env_vars = ["YD_TOKEN"]
[mcp_servers.yandex-direct.env]
YD_AGENCY_LOGIN = "my-agency"
YD_ALLOWED_LOGINS = "client-1,client-2"
YD_OUT_DIR = "/home/user/yadirect-reports"
YD_MODE = "report"
YD_LANG = "ru"Проверьте сервер командой codex mcp list, а активные инструменты — командой /mcp внутри Codex. В desktop/IDE можно также открыть Settings → MCP servers, добавить STDIO-сервер и перезапустить клиент.
Официальная документация: Model Context Protocol in Codex.
Подключение к Hermes Agent
Hermes читает MCP-настройки из ~/.hermes/config.yaml. Для stdio-серверов Hermes передаёт только явно перечисленные переменные окружения, поэтому укажите все настройки в блоке env.
Linux
mcp_servers:
yandex-direct:
command: "/absolute/path/to/yamcp/.venv/bin/python"
args: ["-m", "yadirect_mcp"]
env:
YD_TOKEN: "y0_your_token"
YD_AGENCY_LOGIN: "my-agency"
YD_ALLOWED_LOGINS: "client-1,client-2"
YD_OUT_DIR: "/home/user/yadirect-reports"
YD_MODE: "report"
YD_LANG: "ru"
timeout: 660
connect_timeout: 20
enabled: trueWindows
mcp_servers:
yandex-direct:
command: "D:/path/to/yamcp/.venv/Scripts/python.exe"
args: ["-m", "yadirect_mcp"]
env:
YD_TOKEN: "y0_your_token"
YD_OUT_DIR: "D:/yadirect-reports"
YD_MODE: "report"
timeout: 660
connect_timeout: 20
enabled: trueПосле изменения конфигурации запустите hermes chat или выполните /reload-mcp в активной сессии. Инструменты будут зарегистрированы с префиксом вида mcp_yandex_direct_*.
Ограничьте доступ к файлу конфигурации и не публикуйте его, если внутри находится токен. Официальная документация: Hermes Agent — MCP.
Подключение к ZCode
Откройте Settings → MCP Servers → New MCP Server и задайте:
Scope:
UserилиWorkspace.Type:
stdio.Command: абсолютный путь к Python из
.venv.Arguments:
-mиyadirect_mcpкак два отдельных аргумента.Environment variables: минимум
YD_TOKEN,YD_OUT_DIRиYD_MODE=report.
В режиме Full configuration можно вставить JSON:
{
"mcpServers": {
"yandex-direct": {
"type": "stdio",
"command": "D:/path/to/yamcp/.venv/Scripts/python.exe",
"args": ["-m", "yadirect_mcp"],
"env": {
"YD_TOKEN": "y0_your_token",
"YD_AGENCY_LOGIN": "my-agency",
"YD_ALLOWED_LOGINS": "client-1,client-2",
"YD_OUT_DIR": "D:/yadirect-reports",
"YD_MODE": "report",
"YD_LANG": "ru"
}
}
}
}ZCode также умеет импортировать MCP-серверы из конфигураций Claude Code, Codex CLI, OpenCode и generic .agents. Официальная документация: ZCode MCP Servers.
Другие MCP-клиенты
Cursor, Windsurf, Cline, Continue, OpenCode, VS Code и другие клиенты обычно принимают JSON-конфигурацию формата mcpServers. Названия меню и расположение файла отличаются, но параметры процесса одинаковы:
{
"mcpServers": {
"yandex-direct": {
"command": "/absolute/path/to/yamcp/.venv/bin/python",
"args": ["-m", "yadirect_mcp"],
"env": {
"YD_TOKEN": "y0_your_token",
"YD_OUT_DIR": "/absolute/path/to/yadirect-reports",
"YD_MODE": "report"
}
}
}
}Универсальные правила:
используйте абсолютный путь к Python из виртуального окружения;
выбирайте транспорт
stdio, не HTTP и не SSE;не добавляйте вывод в
stdoutмежду клиентом и сервером;передавайте токен через секреты или окружение;
установите timeout вызова не меньше
YD_REPORT_DEADLINE + 60секунд;после изменения режима перезапустите MCP-сервер, потому что набор инструментов определяется при старте.
Первый запрос к агенту
После подключения начните с безопасной проверки:
Используй yandex-direct. Покажи доступных клиентов агентства, ничего не изменяй.Затем запросите отчёт:
Выгрузи для client-login статистику кампаний за июнь 2026:
дата, кампания, показы, клики и расход. Суммы нужны с НДС.
Покажи итоги и 10 первых строк, полный файл не вставляй в чат.Для дальнейшего чтения:
Прочитай следующие 100 строк сохранённого отчёта через direct_read_report.
Не отправляй новый запрос в API.Частотность для новой кампании:
Собери спрос по фразам «пластиковые окна», «остекление балкона», «окна пвх»
по Москве через direct_wordstat, отсеки всё ниже 100 показов.
Покажи сводку и скажи, что стоит брать в семантику, а что нет.Создание кампании: безопасный сценарий
Остановите активный MCP-процесс.
Установите
YD_MODE=campaign_setup.Желательно задайте один или несколько логинов в
YD_ALLOWED_LOGINS.Перезапустите MCP-клиент и убедитесь, что появился
direct_campaign_setup.Попросите агента собрать недостающие данные и сформировать preview.
Проверьте бюджет, стратегию, регионы, даты, ссылки, тексты, ключевые фразы и минус-слова.
Явно подтвердите создание только после проверки.
После ответа проверьте
status, созданные ID, warnings и errors.Проверьте кампанию в интерфейсе Яндекс Директа. Сервер не запускает показы.
Пример безопасного запроса:
Подготовь новую текстово-графическую кампанию для client-login.
Сначала задай вопросы о цели, географии, бюджете, сроках, стратегии,
счётчиках и целях Метрики, семантике, минус-словах и объявлениях.
Затем вызови direct_campaign_setup без confirmation и покажи полный preview.
Ничего не создавай без моего отдельного подтверждения.Денежные поля JSON API при создании передаются в микроединицах: сумма в валюте × 1_000_000. Входные поля используют официальный регистр API: Name, StartDate, TextCampaign, RegionIds, TextAd, Keyword и т. д.
Операция API не атомарна. Если дочерний этап завершился ошибкой, ответ сохраняет уже созданные ID. Не повторяйте весь запрос вслепую: это может создать дубликат кампании.
Технические решения
Стабильный ReportName
Имя отчёта — хеш спецификации. Оно остаётся одинаковым между попытками polling, иначе каждый повтор мог бы создать новый офлайн-отчёт. Разные поля и фильтры получают разные имена.
Корректное ожидание Reports API
Сервер различает:
200— отчёт готов;201— отчёт поставлен в очередь;202— отчёт ещё формируется;400— ошибка параметров или лимитов;500— ошибка сервера Яндекс Директа.
Для 201 и 202 сервер читает retryIn, повторяет идентичный запрос и контролирует общий deadline. Лимиты Reports API описаны в официальной документации: одновременно в очереди может быть не больше пяти офлайн-отчётов на пользователя.
Экономия контекста модели
Полный TSV не возвращается в MCP-ответе. direct_report отдаёт:
абсолютный путь к файлу;
количество строк и названия колонок;
пересчитанные totals;
ограниченный preview;
информацию о баллах API.
Остальные строки читаются через direct_read_report без API-вызова.
Ограничения
Проект не является официальным продуктом Яндекса.
Нет Яндекс Метрики: токен Директа к её API доступа не даёт, нужен отдельный с правом
metrika:read. Конверсии по целям при этом доступны — их отдаётdirect_reportпо параметруgoals.Вордстат работает через устаревший API v4 (в v5 аналога нет) и недоступен в песочнице.
Нет пакетной выгрузки сразу по всем логинам.
Не создаются ЕПК, медийные и мобильные кампании.
Не редактируются и не удаляются существующие объекты: корректировки ставок и условия ретаргетинга читаются, но не задаются.
Правила отбора условий ретаргетинга (
Rules) не возвращаются — только состав списка, его тип и доступность.Не выполняются
resume, автоматический запуск показов и rollback.Сервер предоставляет локальный stdio-транспорт, а не удалённый HTTP endpoint.
Диагностика
MCP-клиент не видит сервер
Убедитесь, что путь в
commandабсолютный и файл существует.Выполните
"<python>" -c "import yadirect_mcp; print('ok')"в той же среде.Проверьте наличие
YD_TOKENименно в окружении MCP-процесса.Проверьте, что аргументы переданы как
-m,yadirect_mcp.Перезапустите клиент после изменения конфигурации.
YD_TOKEN не задан
Сервер не получил токен. .env автоматически не читается. Добавьте YD_TOKEN в env конфигурации MCP или экспортируйте переменную до запуска клиента.
Отчёт завершается по timeout клиента
Увеличьте timeout инструмента. Рекомендуемое значение — YD_REPORT_DEADLINE + 60 секунд. Для стандартного deadline 600 используйте 660 секунд или 660000 миллисекунд — в зависимости от формата клиента.
Логин заблокирован
Если ответ содержит Логин ... не разрешён, добавьте точный логин в YD_ALLOWED_LOGINS через запятую или исправьте опечатку. Для production не рекомендуется отключать whitelist без необходимости.
Ошибка Яндекс Директа
Ответ инструмента содержит error, а для DirectError также error_code и request_id. Сохраните request_id для обращения в поддержку и проверьте совместимость выбранных полей, типа отчёта и фильтров.
Разработка
Установите dev-зависимости:
python -m venv .venv
python -m pip install -e ".[dev]"Запустите проверки:
python -m ruff check .
python -m pytest -q
python -m build
python -m twine check dist/*Тесты покрывают polling 201 → 202 → 200, стабильность ReportName, заголовки API, обработку 400, пересчёт итогов, whitelist, проверку конфигурации, регистрацию read/write-инструментов по режиму, безопасный preview, валидацию родительских ID, передачу созданных ID и частичные ошибки. Для Вордстата отдельно проверяются транспорт v4 (токен в теле, ошибка с HTTP 200), разбиение длинного списка фраз на отчёты, удаление отчётов из очереди даже после сбоя и различение нулевого спроса от отсутствующего ответа. Для справочника регионов — ранжирование совпадений, нормализация «ё», путь до корня при битой и зацикленной ссылке на родителя, явный список неизвестных кодов и однократная загрузка словаря. Для настроек кабинета — разбиение кампаний на пачки по 10, изоляция упавшей секции, сохранность значения при неизвестном типе корректировки и видимость усечения выборки.
Правила участия описаны в CONTRIBUTING.md, выпуск версии — в RELEASING.md, политика безопасности — в SECURITY.md.
Roadmap
Яндекс Метрика: выгрузка на диск плюс компактная сводка.
Переезд Вордстата с устаревшего API v4 на Yandex Cloud Search API.
direct_report_batchдля нескольких логинов с общим контролем очереди.Дисковый кеш закрытых периодов с TTL по дате.
Экспорт Parquet для BI и аналитических пайплайнов.
Опциональный удалённый Streamable HTTP transport с отдельной аутентификацией.
Лицензия
Проект распространяется по лицензии MIT.
Названия Яндекс, Яндекс Директ, Claude, Codex, Hermes и ZCode принадлежат соответствующим правообладателям. Этот независимый проект не аффилирован с Яндексом, Anthropic, OpenAI, Nous Research или Zhipu AI.
Ключевые слова: Яндекс Директ MCP, Yandex Direct MCP server, API Яндекс Директа, Claude Code MCP, OpenAI Codex MCP, Hermes Agent MCP, ZCode MCP, AI-агент для контекстной рекламы, автоматизация PPC, отчёты Яндекс Директ, управление рекламными кампаниями.
Available Tools
8 toolsdirect_account_settingsARead-only
Настройки кабинета, которых нет в отчётах: корректировки ставок, условия ретаргетинга, общие наборы минус-фраз.
Нужен при разборе «почему кампания не работает» и перед выводами по срезам отчёта. Reports API покажет статистику по Device, Gender, Age, но не покажет выставленный коэффициент, а это разные диагнозы: «нет мобильных конверсий» и «на мобильные стоит −100%».
sections: какие секции читать. Доступны bid_modifiers, retargeting_lists, negative_keyword_sets. Пусто — все три. campaign_ids: для каких кампаний смотреть корректировки. Пусто — сервер сам возьмёт неархивные кампании клиента, но не более 50; если их больше, в ответе будет truncated и число пропущенных.
Секции независимы: ошибка в одной приходит полем error внутри неё, а остальные возвращаются как есть. Корректировки перемножаются между собой — как их читать, описано в direct://kb/targeting-adjustments.
| Name | Required | Description | Default |
|---|---|---|---|
| sections | No | ||
| campaign_ids | No | ||
| client_login | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Beyond the readOnlyHint annotation, the description discloses meaningful behavioral details: sections are independent and errors arrive per-section in an 'error' field while other sections still return, empty campaign_ids triggers server-side selection of up to 50 non-archived campaigns with a truncated signal, and bid adjustments multiply with each other. This is exactly the kind of non-obvious behavior 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.
Is the description appropriately sized, front-loaded, and free of redundancy?
Every sentence adds information: purpose, usage context, parameter semantics, and behavioral caveats. The structure is front-loaded with the core purpose, then parameters, then edge-case behavior, with no filler or repetition of schema-visible facts.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with three parameters and an output schema, the description covers all essential operational information: what sections exist, what empty campaign_ids means, the 50-campaign limitation, truncation signaling, partial error behavior, and the multiplicative semantics of adjustments. The output schema can handle return-value details, so nothing needed for correct invocation is missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Despite 0% schema description coverage, the description fully compensates: it enumerates the valid section values (bid_modifiers, retargeting_lists, negative_keyword_sets), explains the empty/default behavior for sections, and describes the server-side default behavior and 50-campaign cap for campaign_ids. The required client_login needs no further explanation due to the schema.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly identifies the tool as reading account settings absent from reports: bid adjustments, retargeting conditions, and negative keyword sets. It explicitly contrasts with Reports API data ('Reports API покажет статистику... но не покажет выставленный коэффициент'), distinguishing it from the sibling reporting tools.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
It gives explicit when-to-use guidance: 'Нужен при разборе «почему кампания не работает» и перед выводами по срезам отчёта.' It also explains why Reports API alone is insufficient and that this tool supplies the missing diagnostic context, making the choice between this tool and reporting siblings clear.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_adsARead-only
Объявления и посадочные страницы: куда ведёт реклама, что в заголовках, размечены ли ссылки UTM.
Ссылки в отчётах не существует ни в одном типе: поле Href есть только здесь. Вызывать, когда разбор дошёл до вопросов «на какую страницу идёт группа», «одна ли это главная на весь аккаунт», «есть ли метки» — и перед любыми выводами про конверсию, потому что дорогой клик на нерелевантной странице выглядит в отчёте так же, как дорогой клик вообще.
campaign_ids / ad_group_ids / ad_ids: чем сузить выборку. Пусто — все объявления клиента. include_archived: включить архивные, по умолчанию нет. limit: сколько объявлений забрать за вызов, 1–10000.
В ответе landing_pages — сводка по уникальным URL с числом объявлений, кампаниями и разобранными UTM; domains — домены, на которые идёт реклама. Запрашивается блок TextAd: у графических, видео и смарт-объявлений href придёт пустым, их число видно в ads_without_href.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| ad_ids | No | ||
| ad_group_ids | No | ||
| campaign_ids | No | ||
| client_login | Yes | ||
| include_archived | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations only declare readOnlyHint=true, so the description carries the burden of behavioral disclosure. It reveals that Href appears only for text ads and is empty for graphic, video, and smart ads, with the count shown in ads_without_href. It also explains defaults for include_archived and limit range, transcending the annotation.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is well-structured with a summary line, usage rationale, parameter list, and response caveat. It is somewhat repetitive about Href being present only here, but the repetition occurs in different contexts (differentiation and response behavior) and reinforces a critical point.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given an output schema exists and readOnlyHint is present, the description is remarkably complete. It covers purpose, when to use, parameter semantics, and a subtle data caveat (empty Href for non-text ads). An agent has enough context to invoke the tool correctly and interpret results appropriately.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, and the description compensates by explaining the filter parameters (campaign_ids, ad_group_ids, ad_ids) as narrowing the selection with empty meaning all client ads. It also clarifies include_archived defaults and limit's 1–1000 range. client_login is not explained but is a self-evident required identifier.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a clear statement of the tool's content: ads and landing pages — where ads lead, what's in headlines, whether UTM links are marked. It explicitly distinguishes itself from other report types by stating that the Href field exists only here and nowhere else, so an agent can differentiate it from siblings like direct_report.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
It provides explicit when-to-use guidance: call it when analysis reaches questions about which page a group goes to, whether it's one main page for the account, and whether there are labels — and before any conversion conclusions. It also warns about the misleading similarity of expensive clicks on irrelevant pages, which gives a concrete reason for preferring this tool.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_campaignsARead-only
Кампании клиента: id, имя, тип, статус. Нужен для маппинга CampaignId → имя и чтобы понять, какие кампании вообще стоит тянуть в отчёт.
| Name | Required | Description | Default |
|---|---|---|---|
| client_login | Yes | ||
| include_archived | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The readOnlyHint annotation already covers safety. The description adds a little context about the returned data shape (id, name, type, status) and the mapping purpose, but doesn't explain behavior like archived inclusion, pagination, or response size. This is adequate but not rich, so a 3 is appropriate.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
Two terse sentences: the first states the payload fields, the second states the purpose. Every word is useful and front-loaded, with no filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple read-only list with an output schema and two fairly self-explanatory parameters, the description covers the resource, the fields, and the purpose. The main gaps are that include_archived's effect on deciding 'which campaigns to pull' is left to inference and sibling differentiation is absent, but an agent still has enough context to invoke it correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, and the description contains no parameter-specific guidance. 'Кампании клиента' only implies the client_login parameter, while include_archived is not addressed at all, so the description does not compensate for the schema gaps.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly identifies the resource ('client campaigns') and enumerates the useful fields (id, name, type, status), and states the mapping purpose. It lacks an explicit verb like 'lists/retrieves' and doesn't explicitly differentiate from sibling tools such as direct_ads or direct_report, so it is not a 5.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
It gives a concrete use case: mapping CampaignId → campaign name and deciding which campaigns are worth including in a report. This is clear context for when to call the tool, but it doesn't mention when not to use it or name an alternative, so it stops short of a 5.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_list_clientsARead-only
Список клиентских логинов агентства с валютой и остатком средств.
Отсюда берётся client_login для остальных тулов. Вызывается без заголовка Client-Login — это агентский метод.
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations declare readOnlyHint=true, and the description adds useful behavioral context by specifying the authentication/header expectation: it is called without a Client-Login header because it is an agency method. This goes beyond the annotation and helps the agent invoke it correctly in the broader tool workflow.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact and front-loaded: the first sentence states the purpose, the second explains how it fits into the workflow and how it should be called. Every sentence earns its place with no filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the tool's simplicity, one optional parameter, the readOnlyHint annotation, and the presence of an output schema, the description covers everything an agent needs: what the tool returns, where it fits in the workflow, and the required call context.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, and the description does not mention the limit parameter at all. The schema provides a name, type, and default, so the parameter is not opaque, but the description fails to add any meaning or guidance beyond that.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action (list) and resource (agency client logins), and adds scope by mentioning currency and balance. It also distinguishes itself from sibling tools by explaining that this is where client_login is obtained for other tools, and that it is an agency-level method.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives clear usage context: it is the source of client_login for other tools and must be called without the Client-Login header, identifying it as an agency method. It does not name specific alternatives or explicitly say when not to use it, but the positioning is clear enough for an agent to route correctly.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_read_reportARead-only
Постранично прочитать уже выгруженный отчёт по пути из direct_report. Без повторного обращения к API и без расхода баллов.
| Name | Required | Description | Default |
|---|---|---|---|
| path | Yes | ||
| limit | No | ||
| offset | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations already mark the tool as readOnlyHint=true; the description adds the key behavioral facts that no API request is made and no credits are consumed. This goes beyond the annotation and helps agents select the tool for cost-free local reads, though it does not cover edge-case behaviors like invalid paths.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is two short sentences with no filler. The core action, object, and distinguishing benefit are front-loaded, making it easy for an agent to parse quickly.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the simple three-parameter shape, an output schema, and readOnly annotation, the description covers the essential workflow: reading an existing report from a direct_report path without extra cost. Minor gaps such as explicit prerequisites and pagination parameter details are not severe.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate, but it only explains the source of 'path' and vaguely suggests pagination via 'page by page'. The limit and offset parameters are not explicitly tied to pagination semantics, maximum values, or behavior when omitted beyond schema defaults.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Постранично прочитать' — read page by page) and a specific resource ('уже выгруженный отчёт по пути из direct_report'). It clearly distinguishes this tool from sibling direct_report by stating it reads an already exported report without re-calling the API.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives clear context: use this tool after a report has been exported via direct_report, when you want to read it without another API call or credit cost. It does not explicitly state exclusions or compare with alternatives beyond direct_report, but the intended workflow is clear.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_regionsARead-only
Коды регионов Директа по названию и обратная проверка готовых кодов.
Вызывать всегда, когда в geo_ids (direct_wordstat) или RegionIds (direct_campaign_setup) уходит регион: Директ коды НЕ проверяет. Неверный код не вызовет ошибку — он молча даст данные и показы не по тому региону, и заметно это станет только по статистике.
query: часть названия, например "Москва", "Ростов", "Татарстан". Регистр и «ё» не важны. Совпадения возвращаются с путём до корня (path), потому что названия неуникальны: «Москва» — это и город 213, и «Москва и область» 1. ids: коды для обратной проверки. Вернёт названия, а отсутствующие в справочнике коды — отдельным списком unknown_ids. client_login: нужен только агентскому токену — Директ требует заголовок Client-Login на клиентских методах. Подойдёт любой логин из direct_list_clients. limit: сколько совпадений вернуть, 1–200.
Нужен хотя бы один из query / ids: справочник целиком тул не отдаёт. Загружается он один раз на процесс, повторные вызовы баллов не тратят.
| Name | Required | Description | Default |
|---|---|---|---|
| ids | No | ||
| limit | No | ||
| query | No | ||
| client_login | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Even with readOnlyHint=true, the description adds substantial behavioral detail: Direct does not check region codes so invalid codes cause silent wrong-region data, matches include a path to root because names are non-unique, invalid ids are returned as unknown_ids, the full directory is not returned, and the reference is loaded once per process so repeated calls do not consume points. This goes far beyond the annotation and fully informs the agent of expected edge cases.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is dense but well organized: a short purpose plus a critical warning up front, then per-parameter explanations in a consistent format, and a final constraint note. Every sentence adds operational value, and the structure makes it easy to scan.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
The description is complete for an agent to invoke the tool correctly: it covers when to call, why it matters, all parameters and their constraints, expected special return behavior (unknown_ids, path), and a prerequisite about agency tokens. Since an output schema exists, return values beyond what is described do not need to be spelled out.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, but the description compensates by thoroughly explaining each parameter: query with examples and case/ё-insensitivity, ids with the unknown_ids output, client_login with a clear condition and source, and limit with a 1–200 range. It also clarifies the logical constraint that at least one of query/ids is required, which the schema does not convey.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a clear statement of what the tool does: returns Direct region codes by name and reverses-validates existing codes. It is unambiguous and distinct from all sibling tools, which are about clients, campaigns, wordstat, ads, and reports, none of which provide region reference lookups.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description explicitly states when to use this tool: 'Вызывать всегда, когда в geo_ids (direct_wordstat) или RegionIds (direct_campaign_setup) уходит регион'. It also explains why this is critical (Direct does not validate codes and silently returns wrong-region data), gives the requirement that at least one of query/ids is needed, and clarifies that client_login is only required for agency tokens and can be taken from direct_list_clients.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_reportARead-only
Выгрузить статистику через Reports API. Пишет TSV на диск, возвращает путь + итоги + первые строки.
client_login: клиентский логин (см. direct_list_clients) date_from / date_to: YYYY-MM-DD. Статистика доступна за 3 последних года. fields: колонки отчёта, например ["Date","CampaignName","Impressions","Clicks","Cost"]. Набор допустимых полей зависит от report_type. Внимание: поля разных классов — сегмент (даёт группировку), метрика, атрибут, фильтр (используется только в filters и в отчёт не выводится, напр. Keyword). report_type: CUSTOM_REPORT (самый общий, по умолчанию) | ACCOUNT_PERFORMANCE_REPORT | CAMPAIGN_PERFORMANCE_REPORT | ADGROUP_PERFORMANCE_REPORT | AD_PERFORMANCE_REPORT | CRITERIA_PERFORMANCE_REPORT | SEARCH_QUERY_PERFORMANCE_REPORT | REACH_AND_FREQUENCY_PERFORMANCE_REPORT goals: ID целей Метрики, например ["12345678"]. Без них не будет Conversions. attribution_models: FC | LC | LSC | LYDC | FCCD | LSCCD | LYDCCD | AUTO. Работает только вместе с goals; по умолчанию LSC. Несколько моделей → данные выводятся по каждой отдельно. filters: [{"Field":"CampaignId","Operator":"IN","Values":["123","456"]}] order_by: [{"Field":"Cost","SortOrder":"DESCENDING"}] limit: ограничение строк. Требует сортировки — если не задана, подставим по первому полю. include_vat: суммы с НДС (True) или без (False).
| Name | Required | Description | Default |
|---|---|---|---|
| goals | No | ||
| limit | No | ||
| fields | Yes | ||
| date_to | Yes | ||
| filters | No | ||
| order_by | No | ||
| date_from | Yes | ||
| include_vat | No | ||
| report_type | No | CUSTOM_REPORT | |
| client_login | Yes | ||
| attribution_models | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
Annotations only say readOnlyHint=true; the description goes further by disclosing that the tool writes a TSV to disk, returns path/totals/first rows, only has data for the last 3 years, and that multiple attribution_models produce per-model rows. It also explains field classes and the limit/order_by interaction. No contradiction with readOnlyHint.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is long but each sentence adds information needed to call the tool correctly; the main behavior is front-loaded and parameter details are organized. There is no filler or repeated schema content.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with 11 parameters and no schema-level descriptions, this covers all parameters, the side effect, output shape, and key API behaviors; the output schema fills in the remaining return-type details. No critical calling information is missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
With 0% schema description coverage, the description must carry the documentation burden, and it does: every parameter is explained with formats, examples, allowed values, and constraints. It even gives the filter/order_by JSON structure and warns which field classes are not output columns.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description uses a specific verb ('Выгрузить статистику') and names the resource (Reports API), then distinguishes the tool by its side effect: it writes a TSV to disk and returns the path, totals, and first rows. This is enough to distinguish it from siblings like direct_read_report.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description gives context and constraints, such as data availability for 3 years, required client_login, and that conversions require goals, but it never explicitly states when to use this tool instead of direct_read_report or direct_campaigns. Usage must be inferred from the output-on-disk behavior, so guidance is implied rather than explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
direct_wordstatARead-only
Частотность Вордстата: сколько раз за месяц искали фразу, что искали вместе с ней и что искали похожего. Пишет полный список на диск, возвращает сводку по каждой запрошенной фразе.
Нужен на сборке семантики (что брать в кампанию, где спрос есть, а где нет), на разборе «мало показов» и когда в отчёте надо отделить падение спроса от падения кампании.
phrases: до 50 фраз за вызов. Операторы Директа работают: «!» фиксирует словоформу, кавычки ограничивают фразу, «+» держит стоп-слово. geo_ids: регионы Директа, например [225] — Россия, [213] — Москва. Пусто — без ограничения по региону. Директ коды не проверяет: неверный код молча вернёт данные не по тому региону. min_shows: отбросить подсказки с частотностью ниже порога. top: сколько подсказок каждого вида показать в ответе, 1–100.
client_login не нужен: данные Вордстата общие для всех кабинетов. Значение Shows — спрос в поиске за месяц, а не прогноз показов кампании. В песочнице метод недоступен.
| Name | Required | Description | Default |
|---|---|---|---|
| top | No | ||
| geo_ids | No | ||
| phrases | Yes | ||
| min_shows | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The description goes well beyond the readOnlyHint annotation: it mentions writing a full list to disk, returning only a summary, that client_login is unnecessary, that Shows is monthly search demand rather than a campaign forecast, that invalid geo codes fail silently, and that the method is unavailable in sandbox. This is rich behavioral disclosure with no contradiction.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is long but every sentence adds value, especially because the schema provides no parameter descriptions. It is well organized: behavior first, then use cases, then parameter details, then caveats. Nothing is redundant or filler.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with a 4-parameter schema and no schema descriptions, this description covers purpose, use cases, all parameters, caveats, and environment limitations. An output schema exists, so the lighter treatment of return structure is acceptable. Nothing important is missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, and the description compensates fully: phrases explains the 50-phrase limit and Yandex operators, geo_ids gives examples and default behavior, min_shows and top are both explained with meaning and bounds. Every parameter receives practical context that the schema lacks.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description names the exact resource (Yandex Wordstat) and the specific output: monthly search frequency, co-occurring queries, and similar queries, plus a summary per phrase. This clearly distinguishes it from siblings like direct_report or direct_regions, even without explicit sibling comparisons.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The second paragraph gives explicit use cases: semantic collection, diagnosing low impressions, and separating demand decline from campaign decline. It does not name alternative tools or state when not to use it, so it stops short of a 5.
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. Dates show when Glama detected each change.
8 tool updates
v0.2.0- First observed
direct_account_settings - First observed
direct_ads - First observed
direct_campaigns - First observed
direct_list_clients - First observed
direct_read_report - First observed
direct_regions - First observed
direct_report - First observed
direct_wordstat
TDQS
Each tool targets a distinct resource or stage: clients, campaigns, wordstat, regions, account settings, ads, report export, and report reading. report and read_report are clearly separated as fetch vs read saved output, so there is no real overlap.
All tools share the direct_ prefix and use snake_case, making the family identifiable. Most are direct_<noun> (direct_campaigns, direct_ads), while direct_list_clients and direct_read_report use verb_noun, a minor but visible deviation.
Eight tools is a well-scoped count for a Yandex Direct analysis/read-only API surface. Each tool addresses a distinct need without redundancy or bloat.
The set covers the main read/analysis workflows: client selection, campaign/ads/settings inspection, wordstat and region lookups, plus report generation and paginated reading. Minor gaps exist—no goal-list retrieval or management operations—but the core analytical workflow is not dead-ended.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Connectors
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
MCP server for building and testing AI agents with multi-model experimentation and insights.
MCP-native ad server. Monetize AI chatbots and agents with conversational ads.
Related MCP Servers
- AlicenseCqualityDmaintenanceMCP server for Yandex Metrika analytics, enabling AI assistants to access traffic, content, demographics, conversion, e-commerce, and drill-down reports.312MIT
- AlicenseBqualityBmaintenanceMCP server for managing Yandex Direct advertising, Yandex Metrica analytics, Wordstat keyword research, and Yandex Webmaster SEO tools, with self-configuring OAuth; provides 153 tools for complete ad and search workflows from AI assistants.100191MIT
- AlicenseAqualityAmaintenanceMCP server for Yandex Metrica analytics: query web analytics metrics, goals, conversions, and raw API data using natural language from AI clients like Claude and Cursor.81131MIT
- AlicenseNot gradedqualityAmaintenanceAn MCP server that gives AI agents direct access to the Yandex Direct API to manage campaigns, groups, ads, keywords, bids, and reports via natural language.1176Apache 2.0
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/Lermont/yamcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server