Skip to main content
Glama
vk-ads-mcp

vk-ads-mcp

vk-ads-mcp

MCP-сервер для Claude Code: отдаёт статистику и структуру рекламных кампаний VK Рекламы (новый кабинет ads.vk.com, база https://ads.vk.com/api/v2).

Только чтение. Ничего не создаёт и не меняет. Рассчитан на свой кабинет.

Под капотом — тот же движок, что у myTarget. Словарь объектов: ad_plans — кампании, ad_groups — группы объявлений, banners — объявления.

Инструменты

Инструмент

Что делает

list_campaigns

список кампаний (ad_plans), фильтр по статусу, пагинация

list_ad_groups

список групп объявлений, фильтр по кампании

list_banners

список объявлений, фильтр по группе

get_statistics

статистика по ad_plans/ad_groups/banners за период (day/summary); сам режет диапазон >92 дней и список >50 id на части

get_top_objects

топ кампаний / групп / объявлений по метрике (ctr, cpc, cpa, spent и т.д.); order=asc — для метрик стоимости

describe_fields

список допустимых полей для ad_plans/ad_groups/banners — узнаёт их у API на лету

export_to_csv

выгрузка статистики в CSV-файл

get_rate_limits

остаток квоты API для диагностики

Списочные инструменты по умолчанию отдают минимальный набор полей. Чтобы получить больше данных, передайте fields (через запятую). Какие поля доступны для объекта — подскажет describe_fields.

Related MCP server: flin-meta-ads-mcp

Ресурсы и промпт

Ресурс

Что внутри

vk-ads://metrics

справочник групп метрик статистики (base, uniques, video, events, viral, carousel, tps, romi, moat, playable) с единицами измерения

vk-ads://objects

иерархия ad_plans → ad_groups → banners и ключевые поля для анализа

Промпт campaign_analysis — пошаговый сценарий разбора кампаний на русском. Принимает необязательные date_from, date_to, objective.

Анализ и рекомендации

Сервер не только отдаёт данные, но и помогает их разобрать по схеме анализ → ранжирование → рекомендации:

  1. Анализ. list_campaigns и get_statistics дают структуру и цифры за период. Ресурсы vk-ads://metrics и vk-ads://objects объясняют, что значат метрики и поля.

  2. Ранжирование. get_top_objects показывает лучшие и худшие объекты по нужной метрике: order=desc для CTR и конверсий, order=asc для cpc/cpa, где меньше — лучше.

  3. Рекомендации. Промпт 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 + respx

Available Tools

8 tools
describe_fieldsA
Read-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_csvA
Idempotent

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_limitsA
Read-onlyIdempotent

Report remaining VK Ads API quota for diagnostics.

Combines two sources of throttling information:

  • A live GET /throttling.json call 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_statisticsA
Read-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_objectsA
Read-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_groupsA
Read-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_bannersA
Read-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_campaignsA
Read-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

    A4.5/5.0

    Scored across 8 tools

    Disambiguation5/5

    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.

    Naming Consistency5/5

    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.

    Tool Count4/5

    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.

    Completeness3/5

    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

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      B
      maintenance
      MCP server for VK Ads API enabling management of campaigns, ads, statistics, targeting, and budgets through natural language.
      8
      20 npm
      5
      MIT
    • A
      license
      B
      quality
      B
      maintenance
      Read-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.
      18
      MIT
    • A
      license
      A
      quality
      B
      maintenance
      MCP server for VK Ads API: manage ad plans, ad groups, banners, and statistics.
      23
      196 npm
      13
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      Local 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.
      1
      MIT