yandex-direct
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@yandex-directlist my active advertising campaigns"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
mcp-server-yandex-direct
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:
Инструмент | Описание |
| Поиск действий по описанию на естественном языке |
| Выполнение действия по ID |
Как это работает
LLM: yd_search("остановить кампании")
→ [{"id": "campaigns-suspend", "params_schema": {"SelectionCriteria": {...}, ...}, ...}]
LLM: yd_execute("campaigns-suspend", '{"SelectionCriteria": {"Ids": [12345]}}')
→ {"SuspendResults": [...]}Доступные действия (79)
Домен | Кол-во | Описание |
8 | Кампании: создание, управление, архивация | |
4 | Группы объявлений | |
9 | Объявления: создание, управление, модерация | |
6 | Ключевые слова | |
7 | Ставки и корректировки ставок | |
11 | Быстрые ссылки, изображения, видео, расширения | |
10 | Аудитории и ретаргетинг | |
4 | Общие списки минус-слов | |
4 | Фиды для динамических объявлений | |
2 | Креативы для медийных объявлений | |
2 | Исследование ключевых слов | |
1 | Лиды из форм лидогенерации | |
3 | Отслеживание изменений | |
6 | Аккаунт, справочники, клиенты агентства | |
1 | Турбо-страницы | |
1 | Отчёты (TSV/CSV) |
MCP-сервер
Установка
Шаг 1. Получить OAuth-токен
Войдите в Яндекс Директ
Перейдите в Настройки → API
Создайте OAuth-токен с нужными правами
Скопируйте токен
Шаг 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 Desktop | macOS |
|
Claude Desktop | Windows |
|
Claude Desktop | Linux |
|
Через 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/
Переменные окружения
Переменная | Обязательная | По умолчанию | Описание |
| да | — | OAuth-токен Yandex Direct API |
| нет | — | Логин клиента для агентских аккаунтов |
| нет | — | Язык ответов: |
| нет |
| Таймаут HTTP-запросов к API (секунды) |
| нет |
| Таймаут отчётов Reports API (секунды) |
Разработка
pip install -e ".[test]"
ruff check src/ tests/
pytest tests/ -vЛицензия
MIT
Available Tools
2 toolsyd_executeA
Выполнить действие Yandex Direct API по ID.
Используй yd_search для получения ID и схемы параметров.
Args: action: ID действия из yd_search (например "campaigns-get", "ads-suspend") params_json: JSON-объект с параметрами согласно params_schema из yd_search
| Name | Required | Description | Default |
|---|---|---|---|
| action | Yes | ||
| params_json | No | {} |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
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.
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.
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.
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.
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.
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.
yd_searchARead-only
Найти действия Yandex Direct API по намерению. Вызывай первым.
Args: query: что нужно сделать (на русском или английском) domain: фильтр домена (campaigns, adgroups, ads, keywords, bidding, assets, audience, negkeywords, feeds, creatives, research, changes, account, leads, turbopages, reports) limit: максимум результатов (по умолчанию 10)
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| query | Yes | ||
| domain | No |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
The annotation indicates readOnlyHint=true, and the description aligns by describing a search (read) operation. The description adds no further behavioral details beyond the annotation, so it does not significantly enhance transparency.
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 concise, front-loading the core purpose and usage hint, followed by parameter descriptions. Every sentence is necessary and adds value with no redundancy.
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 (3 parameters, read-only, output schema present), the description covers purpose, usage order, and parameter meanings. It could include a brief example but overall is sufficient for correct invocation.
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 explain parameters. It does so clearly: query ('what needs to be done'), domain (lists possible values), limit (maximum results). This adds meaningful context beyond the schema's type/default values.
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 states the tool's purpose: 'Find Yandex Direct API actions by intent.' The verb 'find' and resource 'actions' are specific. The hint 'Call first' distinguishes it from the sibling tool 'yd_execute' by implying a discovery-first workflow.
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 advises 'Call first,' indicating it should be used before 'yd_execute.' It provides context for when to use it (search by intent) but does not explicitly exclude scenarios where it should not be used or mention alternatives.
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.
2 tool updates
v0.3.0- First observed
yd_execute - First observed
yd_search
TDQS
Two tools with clearly distinct purposes: yd_search for discovering API actions and yd_execute for executing them. No overlap in functionality.
Both tools follow a consistent 'yd_verb' pattern (yd_search, yd_execute), making them predictable and easy to use together.
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.
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
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
Build, edit and sync Google, Microsoft, Reddit and Meta ad campaigns from your assistant.
Manage ad campaigns across Google, Meta, LinkedIn, Reddit, TikTok, and more via AI.
Manage ad campaigns across Google, Meta, LinkedIn, Reddit, TikTok, and more via AI.
Related MCP Servers
- AlicenseAqualityAmaintenanceEnables managing Yandex Direct PPC campaigns, ad groups, ads, and keywords, plus pulling performance statistics via the Yandex Direct API v5.442091MIT
- AlicenseAqualityCmaintenanceIntegrates with Yandex Direct API v5 to manage ads via 20 tools, with dry-run protection preventing accidental spending.21MIT
- AlicenseNot gradedqualityBmaintenanceEnables 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
- 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/dontsovcmc/mcp-server-yandex-direct'
If you have feedback or need assistance with the MCP directory API, please join our Discord server