Skip to main content
Glama
dontsovcmc

yandex-direct

by dontsovcmc

mcp-server-yandex-direct

Version

MCP-сервер, CLI-утилита и библиотека Pydantic-моделей для Yandex Direct API v5.

  • MCP-сервер — интеграция с Claude Code, Claude Desktop и другими MCP-клиентами

  • CLI-утилита — работа с API из терминала, скрипты и автоматизация

  • Pydantic-модели — типизированные модели API для использования в своих Python-программах

Все данные остаются на вашем компьютере — токен никуда не передаётся.

Оглавление

Related MCP server: Yandex Direct MCP Server

Архитектура

Сервер использует паттерн search + execute — вместо 79 отдельных инструментов предоставляет 2:

Инструмент

Описание

yd_search

Поиск действий по описанию на естественном языке

yd_execute

Выполнение действия по ID

Как это работает

LLM: yd_search("остановить кампании")
→ [{"id": "campaigns-suspend", "params_schema": {"SelectionCriteria": {...}, ...}, ...}]

LLM: yd_execute("campaigns-suspend", '{"SelectionCriteria": {"Ids": [12345]}}')
→ {"SuspendResults": [...]}

Доступные действия (79)

Домен

Кол-во

Описание

campaigns

8

Кампании: создание, управление, архивация

adgroups

4

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

ads

9

Объявления: создание, управление, модерация

keywords

6

Ключевые слова

bidding

7

Ставки и корректировки ставок

assets

11

Быстрые ссылки, изображения, видео, расширения

audience

10

Аудитории и ретаргетинг

negkeywords

4

Общие списки минус-слов

feeds

4

Фиды для динамических объявлений

creatives

2

Креативы для медийных объявлений

research

2

Исследование ключевых слов

leads

1

Лиды из форм лидогенерации

changes

3

Отслеживание изменений

account

6

Аккаунт, справочники, клиенты агентства

turbopages

1

Турбо-страницы

reports

1

Отчёты (TSV/CSV)


MCP-сервер

Установка

Шаг 1. Получить OAuth-токен

  1. Войдите в Яндекс Директ

  2. Перейдите в НастройкиAPI

  3. Создайте OAuth-токен с нужными правами

  4. Скопируйте токен

Шаг 2. Подключить MCP-сервер

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

Способ 1: через uvx (не требует установки пакета)

Требуется uv — если не установлен:

curl -LsSf https://astral.sh/uv/install.sh | sh
claude mcp add yandex-direct \
  -e YD_TOKEN=ваш_токен \
  -- uvx mcp-server-yandex-direct

Способ 2: через pip

pip install mcp-server-yandex-direct

claude mcp add yandex-direct \
  -e YD_TOKEN=ваш_токен \
  -- python -m mcp_server_yandex_direct

Для удаления:

claude mcp remove yandex-direct

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

Добавьте в конфигурационный файл:

Клиент

ОС

Путь к файлу

Claude Code

все

~/.claude/settings.json (секция mcpServers)

Claude Desktop

macOS

~/Library/Application Support/Claude/claude_desktop_config.json

Claude Desktop

Windows

%APPDATA%\Claude\claude_desktop_config.json

Claude Desktop

Linux

~/.config/Claude/claude_desktop_config.json

Через uvx:

{
  "mcpServers": {
    "yandex-direct": {
      "command": "uvx",
      "args": ["mcp-server-yandex-direct"],
      "env": {
        "YD_TOKEN": "ваш_токен"
      }
    }
  }
}

Через pip (после pip install mcp-server-yandex-direct):

{
  "mcpServers": {
    "yandex-direct": {
      "command": "python",
      "args": ["-m", "mcp_server_yandex_direct"],
      "env": {
        "YD_TOKEN": "ваш_токен"
      }
    }
  }
}

Подключение через --mcp-config

Подключает сервер только на время одной сессии Claude, не сохраняя в настройки. Токен хранится в отдельном .env.mcp файле, а не в конфиге Claude.

Из JSON-строки:

claude --mcp-config '{"yandex-direct":{"command":"bash","args":["-c","source ~/.env.mcp && exec uvx mcp-server-yandex-direct"]}}'

Из файла:

claude --mcp-config ~/mcp-servers.json

Пример ~/mcp-servers.json:

{
  "yandex-direct": {
    "command": "bash",
    "args": ["-c", "source ~/.env.mcp && exec uvx mcp-server-yandex-direct"]
  }
}

Пример ~/.env.mcp:

YD_TOKEN=ваш_токен

Шаг 3. Проверить

Попросите Claude: «Покажи список кампаний» — он вызовет yd_search, получит схему campaigns-get, затем yd_execute.

Примеры (MCP)

Claude автоматически использует yd_search для поиска нужного действия, затем yd_execute для его выполнения:

  • «Покажи все активные кампании» → yd_search("кампании")yd_execute("campaigns-get", ...)

  • «Останови кампании 123, 456» → yd_search("остановить кампании")yd_execute("campaigns-suspend", ...)

  • «Покажи объявления кампании 789» → yd_search("объявления")yd_execute("ads-get", ...)

  • «Добавь ключевую фразу» → yd_search("ключевые слова добавить")yd_execute("keywords-add", ...)

  • «Получи справочник регионов» → yd_search("справочники")yd_execute("dictionaries-get", ...)

  • «Сделай отчёт по кампаниям за январь» → yd_search("отчёт")yd_execute("reports-get", ...)


CLI-утилита

Установка (CLI)

pip install mcp-server-yandex-direct

Переменная окружения YD_TOKEN должна быть установлена:

export YD_TOKEN=ваш_токен

Или через файл:

mcp-server-yandex-direct --env /path/to/.env <command>

Формат файла — KEY=VALUE, по одной переменной на строку, #-комментарии.

Использование (CLI)

Без аргументов запускается MCP-сервер, с командой — CLI. Все команды выводят JSON.

# Версия
mcp-server-yandex-direct --version

# Справка
mcp-server-yandex-direct --help
mcp-server-yandex-direct <command> --help

Примеры команд

# Кампании
mcp-server-yandex-direct campaigns-get '{"SelectionCriteria": {}, "FieldNames": ["Id", "Name", "State"]}'
mcp-server-yandex-direct campaigns-suspend 123,456

# Объявления
mcp-server-yandex-direct ads-get '{"SelectionCriteria": {"CampaignIds": [123]}, "FieldNames": ["Id", "Type", "State"]}'
mcp-server-yandex-direct ads-moderate 789,101

# Ключевые фразы
mcp-server-yandex-direct keywords-get '{"SelectionCriteria": {"AdGroupIds": [111]}, "FieldNames": ["Id", "Keyword", "State"]}'

# Справочники
mcp-server-yandex-direct dictionaries-get Currencies,Regions

# Отчёты
mcp-server-yandex-direct reports-get '{"params": {"SelectionCriteria": {"DateFrom": "2026-01-01", "DateTo": "2026-04-28"}, "FieldNames": ["Date", "CampaignId", "Clicks", "Cost"], "ReportName": "My Report", "ReportType": "CAMPAIGN_PERFORMANCE_REPORT", "DateRangeType": "CUSTOM_DATE", "Format": "TSV"}}'

Пример вывода

$ mcp-server-yandex-direct campaigns-get '{"SelectionCriteria": {"States": ["ON"]}, "FieldNames": ["Id", "Name"]}'
{"Campaigns": [{"Id": 12345, "Name": "Летняя распродажа"}]}

Pydantic-модели

Пакет содержит типизированные Pydantic-модели всех объектов API. Модели можно использовать в своих Python-программах для валидации данных и автодополнения в IDE.

Установка (библиотеки)

pip install mcp-server-yandex-direct

Использование в своих программах

from mcp_server_yandex_direct.models.campaigns import CampaignsGetParams, CampaignsSelectionCriteria

# Валидация данных из API
params = CampaignsGetParams(
    SelectionCriteria=CampaignsSelectionCriteria(States=["ON"]),
    FieldNames=["Id", "Name", "State"],
)
print(params.model_dump_json())

# Валидация ответа
from mcp_server_yandex_direct.models.campaigns import CampaignsGetResult

data = {"Campaigns": [{"Id": 12345, "Name": "Тест", "State": "ON"}]}
result = CampaignsGetResult.model_validate(data)
print(result.Campaigns[0].Name)  # type-safe доступ к полям

Все модели используют extra="allow" для forward compatibility — неизвестные поля API не вызывают ошибок.

Полный список моделей: models/


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

Переменная

Обязательная

По умолчанию

Описание

YD_TOKEN

да

OAuth-токен Yandex Direct API

YD_CLIENT_LOGIN

нет

Логин клиента для агентских аккаунтов

YD_LANG

нет

Язык ответов: ru, en, uk

YD_TIMEOUT

нет

30

Таймаут HTTP-запросов к API (секунды)

YD_FILE_TIMEOUT

нет

120

Таймаут отчётов Reports API (секунды)

Разработка

pip install -e ".[test]"
ruff check src/ tests/
pytest tests/ -v

Лицензия

MIT

Available Tools

2 tools
yd_executeA

Выполнить действие Yandex Direct API по ID.

Используй yd_search для получения ID и схемы параметров.

Args: action: ID действия из yd_search (например "campaigns-get", "ads-suspend") params_json: JSON-объект с параметрами согласно params_schema из yd_search

ParametersJSON Schema
NameRequiredDescriptionDefault
actionYes
params_jsonNo{}

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.2/5.0
Behavior3/5

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

Description confirms the tool is for executing actions (mutation), consistent with readOnlyHint=false. However, it does not disclose potential side effects, rate limits, or authentication requirements beyond what annotations imply. Lacks detail on return value or error behavior.

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?

Extremely concise: three sentences. First states purpose, second gives usage guidance, third explains parameters. No wasted words, front-loaded with key information.

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 that output schema exists and the tool is part of a pair with yd_search, the description is largely complete. It could briefly mention that results follow the output schema, but is sufficient for an agent using yd_search first.

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?

Despite 0% schema description coverage, the description explains both parameters: action as an ID from yd_search, and params_json as a JSON object following the schema from yd_search. This adds significant meaning beyond the bare schema structure.

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?

Description explicitly states the tool executes a Yandex Direct API action by ID, and distinguishes from yd_search by referencing it for obtaining the ID and schema. The verb 'Выполнить' clearly indicates execution.

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?

Description instructs to use yd_search first to get the action ID and parameter schema, providing clear usage context. It does not explicitly list when not to use, but the guidance effectively implies the prerequisite workflow.

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.

  1. 2 tool updatesv0.3.0
    • First observedyd_execute
    • First observedyd_search

TDQS

A4.2/5.0
Disambiguation5/5

Two tools with clearly distinct purposes: yd_search for discovering API actions and yd_execute for executing them. No overlap in functionality.

Naming Consistency5/5

Both tools follow a consistent 'yd_verb' pattern (yd_search, yd_execute), making them predictable and easy to use together.

Tool Count3/5

Only 2 tools for a large API like Yandex Direct. While the search+execute pattern is a clever abstraction, it feels thin compared to typical server scopes, but it is intentional for flexibility.

Completeness4/5

The pair covers any Yandex Direct API action through discovery and execution. No dead ends, though missing higher-level convenience tools for common operations.

Maintenance

ActivityInactive
ResponsivenessNo issues

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

Related MCP Servers

  • A
    license
    A
    quality
    A
    maintenance
    Enables managing Yandex Direct PPC campaigns, ad groups, ads, and keywords, plus pulling performance statistics via the Yandex Direct API v5.
    44
    209
    1
    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

Latest Blog Posts

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/dontsovcmc/mcp-server-yandex-direct'

If you have feedback or need assistance with the MCP directory API, please join our Discord server