vk-ads-mcp
Click on "Deploy 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., "@vk-ads-mcp get top 5 ad groups by CTR in campaign 456"
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.
vk-ads-mcp
MCP-сервер для Claude Code: отдаёт статистику и структуру рекламных кампаний
VK Рекламы (новый кабинет ads.vk.com, база https://ads.vk.com/api/v2).
Только чтение. Ничего не создаёт и не меняет. Рассчитан на свой кабинет.
Под капотом — тот же движок, что у myTarget. Словарь объектов:
ad_plans — кампании, ad_groups — группы объявлений, banners — объявления.
Инструменты
Инструмент | Что делает |
| список кампаний ( |
| список групп объявлений, фильтр по кампании |
| список объявлений, фильтр по группе |
| статистика по |
| топ кампаний / групп / объявлений по метрике ( |
| список допустимых полей для |
| выгрузка статистики в CSV-файл |
| остаток квоты API для диагностики |
Списочные инструменты по умолчанию отдают минимальный набор полей. Чтобы получить
больше данных, передайте fields (через запятую). Какие поля доступны для объекта —
подскажет describe_fields.
Related MCP server: flin-meta-ads-mcp
Ресурсы и промпт
Ресурс | Что внутри |
| справочник групп метрик статистики ( |
| иерархия |
Промпт campaign_analysis — пошаговый сценарий разбора кампаний на русском.
Принимает необязательные date_from, date_to, objective.
Анализ и рекомендации
Сервер не только отдаёт данные, но и помогает их разобрать по схеме анализ → ранжирование → рекомендации:
Анализ.
list_campaignsиget_statisticsдают структуру и цифры за период. Ресурсыvk-ads://metricsиvk-ads://objectsобъясняют, что значат метрики и поля.Ранжирование.
get_top_objectsпоказывает лучшие и худшие объекты по нужной метрике:order=descдля CTR и конверсий,order=ascдляcpc/cpa, где меньше — лучше.Рекомендации. Промпт
campaign_analysisсобирает шаги в готовый сценарий: на что смотреть, что отключить, где поднять ставку.
Доступ к API
client_id/client_secret не выдаются автоматически. В кабинете VK Рекламы:
Настройки → Доступ к API → Запросить доступ к API (или письмо на
ads_api@vk.team). client_secret показывают один раз. Подробнее —
в исходном обзоре ../Open-Source решения для MCP Server VK Ads — полный обзор.md.
Настройка
Скопируйте .env.example в .env и задайте пару из кабинета:
VK_ADS_CLIENT_ID=...
VK_ADS_CLIENT_SECRET=...Сервер сам получит и обновит токен через grant_type=client_credentials
(и перезапросит при 401). Если когда-нибудь окажется готовый Bearer-токен —
можно вместо пары задать VK_ADS_TOKEN, тогда OAuth не используется.
.env в git не попадает. .mcp.json хранит только плейсхолдеры
${VK_ADS_CLIENT_ID} / ${VK_ADS_CLIENT_SECRET}.
VK ограничивает кабинет 5 живыми токенами на client_id, а Claude Code часто
перезапускает сервер. Поэтому токен кешируется на диск
(~/.cache/vk-ads-mcp/token.json, права 0600) и переиспользуется между
перезапусками — новый токен не выпускается, пока старый не истёк. Путь меняется
через VK_ADS_TOKEN_CACHE.
Подключение к Claude Code
claude mcp add vk-ads --scope project \
--env VK_ADS_CLIENT_ID=$VK_ADS_CLIENT_ID \
--env VK_ADS_CLIENT_SECRET=$VK_ADS_CLIENT_SECRET \
-- uv run --with fastmcp fastmcp run src/vk_ads_mcp/server.pyКоманда дописывает .mcp.json в корень проекта (он уже здесь). Реальный токен
берётся из окружения при запуске, в репозиторий не коммитится.
Разработка
uv sync --all-extras --dev
uv run pytest -q # тесты, сеть не нужна (httpx замокан через respx)
uv run ruff check . # линт
uv run ruff format . # форматированиеОтладка вручную
uv run fastmcp dev src/vk_ads_mcp/server.pyПоднимает MCP Inspector — можно дёргать инструменты руками и смотреть ответы.
Структура
src/vk_ads_mcp/
app.py общий FastMCP-инстанс + ленивый клиент
config.py чтение env
auth.py OAuth2 client_credentials + refresh / Bearer-override
client.py весь HTTP: пагинация, чанкинг 92 дней / 50 id, бэкофф на 429
models.py pydantic-модели ответов
tools/ по файлу на инструмент
resources.py ресурсы vk-ads://metrics и vk-ads://objects
prompts.py промпт campaign_analysis
server.py точка входа (регистрирует инструменты, ресурсы, промпт, запускает stdio)
tests/ pytest + respxAvailable Tools
8 toolsdescribe_fieldsARead-onlyIdempotent
Discover which fields a VK Ads resource accepts. Call this FIRST.
Call this before the list tools to learn which fields you can request, then
pass the ones you need as the fields argument of list_campaigns,
list_ad_groups or list_banners. The valid set is discovered live
against the cabinet, so it always reflects the real API.
How it works: the tool sends a request carrying one deliberately-invalid field. The API rejects it with HTTP 400 and a body listing every allowed field, which this tool parses and returns.
Inputs: resource (required). Returns: object
export_to_csvAIdempotent
Export VK Ads statistics to a CSV file on disk.
Fetches statistics for the given object type and date range via the shared
client (which transparently splits ranges longer than 92 days and id lists
longer than 50 into multiple requests), flattens each returned item into a
CSV row using the stdlib :mod:csv module, and writes the result to
output_path. Read-only: it never mutates any ad object.
The CSV header is the union of every key seen across all items, in first-seen order. Missing values for a given row are written as empty cells. All values are stringified.
Inputs: object_type (required), date_from (required), date_to (required), output_path (required), +2 more. Returns: result
get_rate_limitsARead-onlyIdempotent
Report remaining VK Ads API quota for diagnostics.
Combines two sources of throttling information:
A live
GET /throttling.jsoncall returning the API's current view of remaining requests per second, per hour, and per day (throttling).The last
X-RateLimit-*header values observed on any prior request, cached on the shared client (last_seen).
Use this to check how much API budget is left before issuing further listing or statistics requests, or to debug HTTP 429 rate-limit errors.
Returns: A dict with two keys:
* ``throttling``: the decoded ``/throttling.json`` body (remaining and
limit values for rps/hourly/daily quotas, as returned by the API).
* ``last_seen``: the most recent rate-limit header values observed by
the client (``rps_remaining``, ``hourly_remaining``,
``daily_remaining``); values are ``None`` until a request has run.Inputs: no named parameters. Returns: object
get_statisticsARead-onlyIdempotent
Fetch performance statistics for VK Ads objects.
Retrieves statistics from GET /statistics/{object_type}/{period}.json and
returns a merged {"items": [...]} payload. The underlying client
transparently handles the API's hard limits: date ranges longer than 92 days
are split into multiple inclusive windows, and id lists longer than 50 are
chunked, with all responses merged into a single result. The caller never has
to worry about those limits.
Inputs: object_type (required), date_from, date_to, period, +2 more. Returns: object
get_top_objectsARead-onlyIdempotent
Rank VK Ads objects by a performance metric and return the top N.
Fetches statistics via the shared client, reads the chosen metric from
each object's total.base aggregate, sorts the objects, and returns the
best (or worst) limit of them. Use this to pick the best-performing (or
worst-performing) campaigns, ad groups or banners.
Inputs: object_type (required), metric (required), date_from, date_to, +4 more. Returns: result
list_ad_groupsARead-onlyIdempotent
List ad groups (VK Ads ad_group objects) in the connected cabinet.
Ad groups live inside campaigns (ad_plan objects) and contain the
individual banners (creatives). This read-only tool drains every page of
the /ad_groups.json listing endpoint and returns the RAW item dicts so
every requested field reaches you for analysis.
By default the API returns a MINIMAL field set. Pass fields to get rich
data, e.g. "id,name,status,targetings,utm,banners,package_id". The
targetings field exposes age/gender/geo/interests. Call the
describe_fields tool with resource="ad_groups" first to learn the
full set of valid field names.
Inputs: ad_plan_id, fields, status, sorting, +1 more. Returns: result
list_bannersARead-onlyIdempotent
List banners (creatives) in the own VK Ads cabinet.
Fetches every banner from GET /banners.json, transparently paginating
over all result pages, and returns the RAW item dicts so every requested
field reaches you for analysis. Read-only.
By default the API returns a MINIMAL field set. Pass fields to get rich
creative data, e.g. "id,status,content,textblocks,urls,moderation_status".
The content field carries the creative variants/urls. Call the
describe_fields tool with resource="banners" first to learn the full
set of valid field names.
Inputs: ad_group_id, fields, status, sorting, +1 more. Returns: result
list_campaignsARead-onlyIdempotent
List ad campaigns (VK Ads ad_plans) for the authenticated cabinet.
Fetches every campaign from GET /ad_plans.json, transparently walking
the offset-based pagination, and returns the RAW item dicts so every field
you request reaches you for analysis.
By default the API returns a MINIMAL field set. To get rich data pass
fields with the columns you need, e.g.
"id,name,status,objective,budget_limit,budget_limit_day,autobidding_mode," "max_price,priced_goal,delivery,efficiency_status,date_start,date_end".
Call the describe_fields tool with resource="ad_plans" first to learn
the full set of valid field names for this resource.
Inputs: fields, status, sorting, limit. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 8 tools
Every tool targets a distinct resource or operation (field discovery, listing campaigns/ad groups/banners, statistics, export, rate limits). No two tools overlap in functionality, so an agent can easily distinguish them.
All tools follow a consistent verb_noun pattern in snake_case (e.g., describe_fields, get_statistics, list_campaigns). The naming is predictable and clear.
With 8 tools, the set is well-scoped for a read-only analytics-oriented VK Ads server. It covers listing, statistics, export, and diagnostics without being too sparse or overly bloated.
The tools cover listing, statistics, and export well, but lack any write operations (create, update, delete) for campaigns, ad groups, or banners. For a full ad management server, this is a notable gap, though the set is coherent for read-only analytics.
Maintenance
Related MCP Connectors
Google Ads MCP server — manage campaigns, keywords, and metrics.
Reddit Ads MCP server: 9 tools for subreddit reports, targeting, diagnosis. Read-only by default.
MCP server for querying and analyzing data from ad platforms, analytics tools, and spreadsheets
Pinterest Ads MCP server: read campaign analytics and draft campaign changes from AI.
Related MCP Servers
- AlicenseBqualityBmaintenanceMCP server for VK Ads API enabling management of campaigns, ads, statistics, targeting, and budgets through natural language.820 npm5MIT
- AlicenseBqualityBmaintenanceRead-only MCP server for Meta Ads that lists and reads ad accounts, campaigns, ad sets, ads, ad images, creatives, and fetches insights at various levels.18MIT
- AlicenseAqualityBmaintenanceMCP server for VK Ads API: manage ad plans, ad groups, banners, and statistics.23196 npm13MIT
- AlicenseNot gradedqualityCmaintenanceLocal MCP server that integrates with VK Ads API and Core VK API, providing 128 tools for managing ad campaigns, audiences, creatives, statistics, and analyzing VK communities.1MIT