Skip to main content
Glama
Yandex Direct MCP Server

Yandex Direct MCP Server

by OlegRadinuk

Yandex Direct MCP Server

Model Context Protocol (MCP) сервер, который превращает Claude в профессионального директолога. Полное управление рекламой в Яндекс.Директе через официальный API v5 — прямо из диалога с AI, с защитой от случайных денежных действий.

status python protocol api


Проблема

Управление контекстной рекламой — это рутина: десятки кампаний, сотни объявлений и ключей, ставки в неудобных микро-единицах, отчёты через асинхронный API с поллингом. Делать это руками в интерфейсе долго, а писать скрипты под каждую задачу — каждый раз заново.

Related MCP server: Yandex Direct MCP

Решение

MCP-сервер отдаёт Claude 20 инструментов поверх Yandex Direct API v5. Теперь рекламой можно управлять на естественном языке:

«Покажи кампании с расходом за неделю, найди ключи с CTR ниже 2% и предложи, какие ставки снизить.»

Claude сам выбирает нужные инструменты, строит отчёт, предлагает изменения — но никогда не вносит правки без явного подтверждения (см. dry-run ниже).

Чем это интересно как инженерная работа

  • Дизайн безопасного агентного интерфейса к деньгам: каждый мутирующий вызов по умолчанию ничего не делает, пока человек не подтвердит.

  • Работа с «неудобным» внешним API: асинхронные отчёты с поллингом, микро-единицы валюты, песочница vs прод.

  • Чистый MCP-сервер на официальном SDK, подключается и к Claude Desktop, и к Claude Code.


Архитектура

┌─────────────────┐     MCP (stdio)      ┌──────────────────────┐    HTTPS / JSON     ┌─────────────────────┐
│  Claude          │ ◄──────────────────► │  yandex-direct-mcp   │ ◄─────────────────► │  Yandex Direct       │
│  (Desktop / Code)│   20 tools           │  src/server.py       │   API v5            │  API (sandbox/prod)  │
└─────────────────┘                       └──────────────────────┘                     └─────────────────────┘
                                               │
                                               ├─ dry-run guard (confirm=False по умолчанию)
                                               ├─ micros-конвертация (1 ₽ = 1 000 000 micros)
                                               ├─ async-отчёты с поллингом (до 5 мин)
                                               └─ переключатель окружения YDIRECT_ENV (sandbox/production)
  • Транспорт: stdio MCP — сервер запускается локально, токен живёт только в env на машине пользователя, наружу не уходит.

  • Окружение: один флаг YDIRECT_ENV переключает между песочницей и боевым аккаунтом.

Стек

Python 3.11+ · MCP SDK (mcp[cli]) · httpx · Yandex Direct API v5


Инструменты (20)

Чтение — безопасно, без подтверждения

Инструмент

Что делает

list_campaigns

Кампании с фильтрами по статусу/типу

list_ad_groups

Группы объявлений по кампаниям

list_ads

Объявления по группам или кампаниям

list_keywords

Ключевые слова с текущими ставками

get_balance

Баланс и финансы аккаунта

get_report

Универсальный отчёт (async polling, до 5 мин)

Кампании — с dry-run защитой

Инструмент

Что делает

add_campaigns

Создать кампании (TEXT_CAMPAIGN, стратегии на выбор)

update_campaigns

Название, даты, бюджет, стратегия

suspend_campaigns / resume_campaigns

Пауза / возобновление

archive_campaigns

Архивировать (необратимо)

Группы, объявления, ключи — с dry-run защитой

Инструмент

Что делает

add_ad_groups

Создать группы (с геотаргетингом)

add_ads / update_ads

Создать / изменить объявления

moderate_ads / delete_ads

Модерация / удаление

add_keywords / update_keywords / delete_keywords

Управление ключами

set_keyword_bids

Массовое изменение ставок (bulk)

add_negative_keywords

Минус-слова для кампаний и групп

Защита от ошибок (ключевая фича)

Все мутирующие инструменты по умолчанию работают в dry-run (confirm=False) — показывают план запроса, но ничего не отправляют. Реальное выполнение — только с confirm=True. Claude физически не может потратить бюджет без явного подтверждения человека.

Все ставки и бюджеты — в микро-единицах (1 ₽ = 1 000 000 micros); напоминание встроено в каждый «денежный» инструмент.


Установка

git clone https://github.com/OlegRadinuk/yandex-direct-mcp.git
cd yandex-direct-mcp
uv venv && uv pip install -e .

Получение OAuth-токена

  1. На https://oauth.yandex.ru/ создать приложение, платформа «Веб-сервисы», Redirect URI https://oauth.yandex.ru/verification_code.

  2. Права: «Яндекс Директ» → direct:api.

  3. Открыть https://oauth.yandex.ru/authorize?response_type=token&client_id=ВАШ_CLIENT_ID — access_token из адресной строки и есть токен.

  4. Для песочницы — включить API-доступ к sandbox в настройках Директа.

Подключение к Claude Desktop

%APPDATA%\Claude\claude_desktop_config.json:

{
  "mcpServers": {
    "yandex-direct": {
      "command": "uv",
      "args": ["--directory", "/path/to/yandex-direct-mcp", "run", "python", "src/server.py"],
      "env": { "YDIRECT_TOKEN": "ваш_токен", "YDIRECT_ENV": "sandbox" }
    }
  }
}

Перезапустить Claude Desktop. Когда готовы к боевым кампаниям — "YDIRECT_ENV": "production".

⚠️ Токен — секрет. Хранится только в env на вашей машине, никогда не коммитьте его в репозиторий.


Примеры сессий

Запуск кампании с нуля: add_campaigns (dry-run → проверить → confirm) → add_ad_groups → add_ads → add_keywords → add_negative_keywords → moderate_ads → resume_campaigns.

Анализ и оптимизация: get_report (статистика) → list_keywords → set_keyword_bids (скорректировать ставки) → list_ads (найти низкий CTR) → update_ads.

Ограничения

  • Поддержан тип TEXT_CAMPAIGN; UNIFIED_CAMPAIGN / MOBILE_APP_CAMPAIGN — в планах.

  • Токен передаётся через env (не через параметры) — на одну конфигурацию один аккаунт.

  • Нет автотестов против sandbox (в roadmap).

  • Валидация входных данных — базовая (Pydantic-модели в планах).

Roadmap

  • keywords_research — оценка частотности (KeywordsResearch service)

  • UNIFIED_CAMPAIGN и MOBILE_APP_CAMPAIGN

  • Pydantic-модели для валидации входа

  • MCP Resources: регионы, языки, часовые пояса (справочники с кэшем)

  • Тесты против sandbox

License

MIT — см. LICENSE.

Available Tools

21 tools
add_ad_groupsA

Create ad groups inside existing campaigns.

Args: ad_groups: List of ad group objects. Each must include: - Name (str): group name (required) - CampaignId (int): parent campaign ID (required) - RegionIds (list[int]): geo targeting region IDs (required). Russia = 225, Moscow = 1, Saint-Petersburg = 2. Use get region IDs from Yandex geo tree. - Type (str, optional): "TEXT_AD_GROUP" (default), "MOBILE_APP_AD_GROUP" - NegativeKeywords (list[str], optional): minus-words for this group - TrackingParams (str, optional): UTM params appended to URLs

confirm: True to execute; False returns dry-run plan.

Inputs: ad_groups (required), confirm.

add_adsA

Create text ads in ad groups.

Args: ads: List of ad objects. Each must include: - AdGroupId (int): target ad group (required) - TextAd (dict): ad content (required for text ads): - Title (str): headline, max 35 chars (required) - Title2 (str, optional): second headline, max 30 chars - Text (str): body text, max 81 chars (required) - Href (str, optional): destination URL (can be set at group/keyword level) - Mobile (str): "YES"|"NO" — whether this is a mobile-only ad (default "NO") - DisplayUrlPath (str, optional): display URL path after domain (max 20 chars) - SitelinkSetId (int, optional): ID of sitelink extension set - VCardId (int, optional): ID of contact info card

confirm: True to execute; False returns dry-run plan.

TIPS: - Title + Title2 must fit Yandex requirements (no caps abuse, no prohibited phrases). - After creation, ads go to DRAFT status — call moderate_ads to submit for review. - Create multiple ads per group (2-3) for A/B testing — Yandex will rotate them.

Inputs: ads (required), confirm.

add_campaignsA

Create one or more TEXT_CAMPAIGN campaigns.

Args: campaigns: List of campaign objects. Each must include: - Name (str): campaign name (required) - StartDate (str): YYYY-MM-DD (required) - EndDate (str, optional): YYYY-MM-DD - DailyBudget (dict, optional): {"Amount": , "Mode": "STANDARD"|"DISTRIBUTED"} - NegativeKeywords (list[str], optional): minus-words for entire campaign - TextCampaign (dict, required for TEXT_CAMPAIGN): bidding strategy config - ManualCPC (search only, no networks): {"BiddingStrategy": { "Search": {"BiddingStrategyType": "HIGHEST_POSITION"}, "Network": {"BiddingStrategyType": "SERVING_OFF"} }} - Auto, max clicks (recommended for new campaigns): {"BiddingStrategy": { "Search": {"BiddingStrategyType": "WB_MAXIMUM_CLICKS", "WbMaximumClicks": {"WeeklySpendLimit": }}, "Network": {"BiddingStrategyType": "NETWORK_DEFAULT"} }} - Auto, target CPC: {"BiddingStrategy": { "Search": {"BiddingStrategyType": "AVERAGE_CPC", "AverageCpc": {"AverageCpc": }}, "Network": {"BiddingStrategyType": "NETWORK_DEFAULT"} }}

confirm: True to actually create campaigns; False returns dry-run plan.

MONEY NOTE: DailyBudget.Amount and all bid values are in MICROS. 1 RUB = 1_000_000 micros. 300 RUB/day = 300_000_000.

Inputs: campaigns (required), confirm.

add_keywordsA

Add keywords to ad groups.

Args: keywords: List of keyword objects. Each must include: - AdGroupId (int): target ad group (required) - Keyword (str): keyword phrase, e.g. "купить ноутбук москва" (required). Use ! to fix word form: "!купить ноутбук" Use + to fix stop words: "ноутбук +в москве" Use quotes for exact phrase: '"купить ноутбук"' Use [] to fix word order: "[купить ноутбук]" - Bid (int, optional): search bid in MICROS. 30 RUB = 30_000_000. - ContextBid (int, optional): YAN (network) bid in MICROS. - UserParam1 (str, optional): custom parameter 1 (passed in URL) - UserParam2 (str, optional): custom parameter 2 (passed in URL)

confirm: True to add keywords; False returns dry-run plan.

MONEY NOTE: Bid and ContextBid are in MICROS (1 RUB = 1_000_000). Example: 50 RUB bid = 50_000_000.

Inputs: keywords (required), confirm.

add_negative_keywordsA

Add negative (minus) keywords to campaigns or ad groups.

Sets the COMPLETE list of negative keywords — merges with existing ones. First call list_ad_groups or list_campaigns to get current NegativeKeywords, then include existing + new ones in your update.

Args: campaign_updates: List of campaign negative keyword updates: [{"Id": <campaign_id>, "NegativeKeywords": {"Items": ["слово1", "слово2"]}}] ad_group_updates: List of ad group negative keyword updates: [{"Id": <adgroup_id>, "NegativeKeywords": {"Items": ["слово1", "слово2"]}}]

confirm: True to execute; False returns dry-run plan.

IMPORTANT: This REPLACES the current negative keyword list for each object. To add incrementally: first read current list, merge, then update. SYNTAX: Negative keywords must NOT have the minus sign — just the word/phrase. E.g. Items: ["бесплатно", "своими руками", "скачать"]

Inputs: campaign_updates, ad_group_updates, confirm.

archive_campaignsA

Archive campaigns (they become read-only, stats preserved).

Campaign must be suspended first. Archived campaigns cannot be unarchived via API.

Args: campaign_ids: List of campaign IDs to archive. confirm: False (default) shows dry-run plan; True archives.

Inputs: campaign_ids (required), confirm.

delete_adsA

Permanently delete ads.

WARNING: Deletion is irreversible. Stats for deleted ads are lost. Consider archiving campaigns instead if you want to keep history.

Args: ad_ids: List of ad IDs to delete. confirm: True to delete; False returns dry-run plan.

Inputs: ad_ids (required), confirm.

delete_keywordsA

Permanently delete keywords from ad groups.

Args: keyword_ids: List of keyword IDs to delete. confirm: True to delete; False returns dry-run plan.

Inputs: keyword_ids (required), confirm.

get_balanceB

Return current account balance and key financial info.

Inputs: no named parameters.

get_reportA

Run a Reports-service query and return rows as list of dicts.

Args: report_type: CAMPAIGN_PERFORMANCE_REPORT | AD_PERFORMANCE_REPORT | KEYWORD_PERFORMANCE_REPORT | SEARCH_QUERY_PERFORMANCE_REPORT | AD_GROUP_PERFORMANCE_REPORT. date_from: YYYY-MM-DD (start of period). date_to: YYYY-MM-DD (end of period). field_names: Columns to include, e.g. ["CampaignId","CampaignName","Impressions","Clicks","Cost","Ctr","AvgCpc"]. campaign_ids: Optional — limit report to these campaigns. ad_group_ids: Optional — limit report to these ad groups.

Notes: - Cost is returned in RUB (not micros) — the server requests returnMoneyInMicros=false. - Reports API is async; this tool polls up to 5 minutes. - Popular field_names: Impressions, Clicks, Cost, Ctr, AvgCpc, Conversions, CostPerConversion, BounceRate, AvgPageviews, AvgSessionDuration.

Inputs: report_type (required), date_from (required), date_to (required), field_names (required), +2 more.

list_ad_groupsA

List ad groups for the given campaign IDs.

Args: campaign_ids: One or more campaign IDs. limit: Max results (1–10000).

Inputs: campaign_ids (required), limit.

list_adsA

List ads for given ad groups or campaigns.

Args: ad_group_ids: Filter by ad group IDs (preferred for precision). campaign_ids: Filter by campaign IDs. states: Filter by state — ON, OFF, SUSPENDED, REJECTED, ARCHIVED. limit: Max results.

At least one of ad_group_ids or campaign_ids is required.

Inputs: ad_group_ids, campaign_ids, states, limit.

list_campaignsA

List advertising campaigns on the connected account.

Args: limit: Max campaigns to return (1–10000). states: Filter by state — any of: ON, OFF, SUSPENDED, ENDED, ARCHIVED, CONVERTED. types: Filter by type — any of: TEXT_CAMPAIGN, MOBILE_APP_CAMPAIGN, CPM_BANNER_CAMPAIGN, UNIFIED_CAMPAIGN.

Returns campaign id, name, type, status, state, daily budget, funds, start date.

Inputs: limit, states, types.

list_keywordsA

List keywords with current bids.

Args: ad_group_ids: Filter by ad group IDs. campaign_ids: Filter by campaign IDs. limit: Max results (1–10000).

At least one filter is required. Note: Bids returned are in MICROS (1 RUB = 1_000_000).

Inputs: ad_group_ids, campaign_ids, limit.

moderate_adsA

Submit ads for moderation review by Yandex.

Ads must be in DRAFT or REJECTED status. Moderation usually takes a few hours. After approval the ads get ON status and start serving.

Args: ad_ids: List of ad IDs to submit. confirm: True to submit; False returns dry-run plan.

Inputs: ad_ids (required), confirm.

resume_campaignsA

Resume previously suspended campaigns.

Args: campaign_ids: List of campaign IDs to resume. confirm: False (default) shows dry-run plan; True executes.

Inputs: campaign_ids (required), confirm.

set_keyword_bidsA

Set search and/or network bids for keywords (bulk bid adjustment).

Prefer this over update_keywords when you only need to change bids — it uses the dedicated bids service and is more efficient.

Args: bids: List of bid objects: - KeywordId (int): keyword ID (required) - SearchBid (int): search network bid in MICROS (e.g. 30_000_000 = 30 RUB) - NetworkBid (int, optional): YAN bid in MICROS

confirm: True to execute; False returns dry-run plan.

MONEY NOTE: All bids are in MICROS (1 RUB = 1_000_000). 30 RUB = 30_000_000. Do NOT confuse with RUB values.

Inputs: bids (required), confirm.

suspend_campaignsA

Pause (suspend) one or more campaigns.

Args: campaign_ids: List of campaign IDs to suspend. confirm: False (default) shows dry-run plan; True actually suspends.

Inputs: campaign_ids (required), confirm.

update_adsA

Update text ads (title, text, URL, etc.).

Note: Updating an approved ad resets it to DRAFT — it must be re-moderated.

Args: ads: List of objects with Id + fields to change: - Id (int): ad ID (required) - TextAd (dict, optional): fields to update: - Title (str): new headline (max 35 chars) - Title2 (str): new second headline (max 30 chars) - Text (str): new body (max 81 chars) - Href (str): new destination URL - DisplayUrlPath (str): display path after domain (max 20 chars)

confirm: True to execute; False returns dry-run plan.

Inputs: ads (required), confirm.

update_campaignsA

Update campaign settings (name, dates, budget, negative keywords, strategy).

Args: campaigns: List of objects with Id (required) + fields to change: - Id (int): campaign ID (required) - Name (str, optional): new name - EndDate (str, optional): YYYY-MM-DD or null to remove - DailyBudget (dict, optional): {"Amount": , "Mode": "STANDARD"|"DISTRIBUTED"} - NegativeKeywords (dict, optional): {"Items": ["минус1", "минус2"]} - TextCampaign (dict, optional): update bidding strategy (same format as add_campaigns)

confirm: True to execute; False returns dry-run plan.

MONEY NOTE: DailyBudget.Amount is in MICROS (1 RUB = 1_000_000).

Inputs: campaigns (required), confirm.

update_keywordsA

Update keyword text or bids.

Args: keywords: List of objects with Id + fields to change: - Id (int): keyword ID (required) - Keyword (str, optional): new keyword phrase - Bid (int, optional): new search bid in MICROS - ContextBid (int, optional): new YAN bid in MICROS - UserParam1 (str, optional): updated custom param 1 - UserParam2 (str, optional): updated custom param 2

confirm: True to execute; False returns dry-run plan.

MONEY NOTE: Bid and ContextBid are in MICROS (1 RUB = 1_000_000).

Inputs: keywords (required), confirm.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 21 tools

    Disambiguation5/5

    Each tool targets a distinct resource or action (campaigns, ad groups, ads, keywords, negative keywords, reports, balance). No two tools overlap in purpose; for example, 'add_campaigns' and 'add_ad_groups' clearly operate on different objects.

    Naming Consistency5/5

    All tool names follow a consistent verb_noun pattern in snake_case (e.g., add_campaigns, list_ads, set_keyword_bids). The verbs are descriptive and uniform across similar operations like add, list, update, delete.

    Tool Count4/5

    21 tools cover the main advertising lifecycle (campaigns, ad groups, ads, keywords, negative keywords, reports, balance). While slightly above the typical 3-15 range, the count is justified by the domain complexity and the inclusion of dedicated tools for negative keywords and bid setting.

    Completeness4/5

    The tool set covers CRUD for campaigns, ad groups, ads, and keywords, plus moderation, reporting, and balance. Obvious gaps like standalone ad extension management (sitelinks, vcards) are partially handled inside add_ads, but separate tools are missing. Overall, it covers core workflows well.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      C
      maintenance
      MCP server for Yandex.Direct API v5 enabling management of campaigns, ad groups, ads, keywords, statistics, and account info via 12 tools.
      20
      93 npm
      4
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      Enables managing Yandex Direct PPC campaigns, ad groups, ads, and keywords, plus pulling performance statistics via the Yandex Direct API v5.
      46
      641 npm
      10
      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
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI agents to manage Yandex Direct advertising accounts via the API v5, including reports, bids, campaign management, and semantic analysis through natural language requests.
      4
      MIT