ymetrika-mcp

NNSTD-cloud-ru-hack-2025/ymetrika-mcp

3.2

If you are the rightful owner of ymetrika-mcp and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to dayong@mcphub.com.

The Yandex Metrika MCP Server is a Model Context Protocol server designed for querying analytics data, generating reports, and accessing insights from Yandex Metrika through a standardized MCP interface.

Tools
6
Resources
0
Prompts
0

Yandex Metrika MCP Server

Python Version FastMCP

MCP (Model Context Protocol) server for Yandex Metrika analytics and reporting. This server provides tools for querying analytics data, generating reports, and accessing Yandex Metrika insights through a standardized MCP interface.

🚀 Quick Start

Prerequisites

  • Python 3.12+
  • uv (recommended) or pip
  • Docker (optional, for containerized deployment)

Local Development

  1. Clone the repository
git clone <repository-url>
cd ymetrika-mcp
  1. Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
  1. Install dependencies
uv sync
  1. Configure environment
cp .env.example .env
# Edit .env with your configuration
  1. Run the server
uv run python src/server.py

The server will start on http://0.0.0.0:8000 by default.

Docker Deployment

  1. Build the image
docker build -t yandex-metrika-mcp .
  1. Run the container
docker run -p 8000:8000 \
  -e OTEL_ENDPOINT=http://your-otel-collector:4318/v1/traces \
  -e YANDEX_API_KEY=your_api_key_here \
  yandex-metrika-mcp

📡 Endpoints

Once running, the server exposes the following endpoints:

  • MCP Protocol: http://0.0.0.0:8000/mcp - Main MCP endpoint for tool invocations
  • Metrics: http://0.0.0.0:8000/metrics - Prometheus metrics endpoint
  • Health Check: http://0.0.0.0:8000/health - Server health status

🔧 Available Tools

ping - Hello World Validation Tool

A diagnostic tool for validating MCP server functionality.

Purpose: Verify MCP transport, logging, progress reporting, tracing, and metrics.

Parameters:

  • message (optional, string): Text message to echo back

Returns:

  • Text: "pong" or "pong: <message>"
  • Structured data with status and optional echo

Example Usage:

{
  "tool": "ping",
  "parameters": {
    "message": "hello world"
  }
}

Response:

{
  "content": [
    {
      "type": "text",
      "text": "pong: hello world"
    }
  ],
  "structured_content": {
    "status": "ok",
    "message": "pong: hello world",
    "echo": "hello world"
  }
}

Yandex Metrika Tools

The following tools provide access to Yandex Metrika analytics data:

get_account_info - Counter Information

Get account and counter information from Yandex Metrika management API.

Purpose: Retrieve counter metadata including name, site URL, status, permissions, and goals list.

Parameters:

  • counter_id (required, integer): Yandex Metrika counter identifier

Returns:

  • Text: Human-readable counter information
  • Structured data with counter metadata

Example Usage:

{
  "tool": "get_account_info",
  "parameters": {
    "counter_id": 12345678
  }
}
get_visits - Traffic Statistics

Get visit statistics from Yandex Metrika with optional date range.

Purpose: Retrieve traffic statistics including visits, users, and pageviews.

Parameters:

  • counter_id (required, integer): Yandex Metrika counter identifier
  • date_from (optional, string): Start date (YYYY-MM-DD or relative format). Default: 6daysAgo
  • date_to (optional, string): End date (YYYY-MM-DD or relative format). Default: today
  • metrics (optional, string): Comma-separated metrics. Default: ym:s:visits,ym:s:users,ym:s:pageviews

Returns:

  • Text: Human-readable visit statistics
  • Structured data with traffic metrics

Example Usage:

{
  "tool": "get_visits",
  "parameters": {
    "counter_id": 12345678,
    "date_from": "2025-12-01",
    "date_to": "2025-12-07"
  }
}
get_traffic_sources_types - Traffic Sources Analysis

Get traffic sources analysis from Yandex Metrika.

Purpose: Retrieve traffic breakdown by source type (direct, search, referral, social, etc.).

Parameters:

  • counter_id (required, integer): Yandex Metrika counter identifier
  • date_from (required, string): Start date (YYYY-MM-DD or relative format)
  • date_to (required, string): End date (YYYY-MM-DD or relative format)
  • dimensions (optional, string): Comma-separated dimensions. Default: ym:s:trafficSource
  • metrics (optional, string): Comma-separated metrics. Default: ym:s:visits,ym:s:users
  • limit (optional, integer): Maximum number of rows to return. Default: 100

Returns:

  • Text: Human-readable traffic sources breakdown
  • Structured data with source distribution

Example Usage:

{
  "tool": "get_traffic_sources_types",
  "parameters": {
    "counter_id": 12345678,
    "date_from": "2025-12-01",
    "date_to": "2025-12-07"
  }
}
get_user_demographics - User Demographics Report

Get user demographics report (gender, age distribution) from Yandex Metrika.

Purpose: Retrieve demographic data including gender distribution and age groups.

Parameters:

  • counter_id (required, integer): Yandex Metrika counter identifier
  • date_from (required, string): Start date (YYYY-MM-DD or relative format)
  • date_to (required, string): End date (YYYY-MM-DD or relative format)
  • dimensions (optional, string): Comma-separated dimensions. Default: ym:s:gender,ym:s:age
  • metrics (optional, string): Comma-separated metrics. Default: ym:s:visits,ym:s:users
  • limit (optional, integer): Maximum number of rows to return. Default: 100

Returns:

  • Text: Human-readable demographic breakdown
  • Structured data with gender and age distribution

Example Usage:

{
  "tool": "get_user_demographics",
  "parameters": {
    "counter_id": 12345678,
    "date_from": "2025-12-01",
    "date_to": "2025-12-07"
  }
}
get_goals_conversion - Goals and Conversion Rates

Get goal completion data and conversion rates from Yandex Metrika.

Purpose: Retrieve goal completion data and conversion rates using Yandex Metrika's conversion preset.

Parameters:

  • counter_id (required, integer): Yandex Metrika counter identifier
  • date_from (required, string): Start date (YYYY-MM-DD or relative format)
  • date_to (required, string): End date (YYYY-MM-DD or relative format)
  • goal_id (optional, integer): Specific goal ID to filter results
  • dimensions (optional, string): Comma-separated dimensions. Default: ym:s:goal
  • metrics (optional, string): Comma-separated metrics. Default: ym:s:sumGoalReachesAny,ym:s:anyGoalConversionRate
  • limit (optional, integer): Maximum number of rows to return. Default: 100

Returns:

  • Text: Human-readable goal performance and conversion rates
  • Structured data with goal completions and rates

Example Usage:

{
  "tool": "get_goals_conversion",
  "parameters": {
    "counter_id": 12345678,
    "date_from": "2025-12-01",
    "date_to": "2025-12-07",
    "goal_id": 174633455
  }
}

⚙️ Configuration

Environment Variables

The ENVIRONMENT variable determines the runtime mode of the application. It can be set to development (default) or production. In development mode the server runs with relaxed validation, while in production the variable must be set to production to enforce validation of YANDEX_API_KEY.

All configuration is managed through environment variables. See .env.example for a complete list.

Server Configuration
VariableTypeDefaultDescription
PORTinteger8000Server port number (1024-65535)
LOG_LEVELstringINFOLogging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
ENVIRONMENTstringdevelopmentRuntime mode (development or production)
OpenTelemetry Configuration
VariableTypeDefaultDescription
OTEL_ENDPOINTstring(empty)OTLP HTTP endpoint for traces. If not set, console exporter is used.
OTEL_SERVICE_NAMEstringyandex-metrika-mcpService name for tracing
Yandex Metrika API
VariableTypeDefaultDescription
YANDEX_API_KEYstring(empty)Yandex OAuth token (get from https://oauth.yandex.ru/)
YANDEX_COUNTER_IDstring(empty)Default Metrika counter ID
API_TIMEOUTinteger30API request timeout in seconds (1-300)
API_MAX_RETRIESinteger3Maximum retry attempts for API calls (0-10)

🔐 Yandex Metrika Authentication

To use the Yandex Metrika tools, you need to obtain an OAuth token with metrika:read scope:

  1. Get OAuth Token:

    • Visit Yandex OAuth
    • Create a new application or use an existing one
    • Request the metrika:read scope
    • Generate the OAuth token
  2. Set Environment Variable:

    export YANDEX_API_KEY=your_oauth_token_here
    
  3. Find Your Counter ID:

    • Log into Yandex Metrika
    • Select your site
    • The counter ID is visible in the URL and interface

📊 Observability

This server implements comprehensive observability following production best practices.

OpenTelemetry Tracing

All tool invocations are traced with OpenTelemetry spans containing:

  • Tool name and parameters
  • Execution status
  • Error details (if any)
  • Custom attributes per tool

Local Development: Traces are output to console Production: Configure OTEL_ENDPOINT to send traces to your collector (Jaeger, Tempo, etc.)

Prometheus Metrics

The server exposes Prometheus-compatible metrics at /metrics:

tool_calls_total

Counter for tool invocations

  • Labels: tool_name, status (started, success, validation_error, error)
calculation_errors_total

Counter for tool execution errors

  • Labels: tool_name, error_type (validation, calculation)
api_calls_total

Counter for external API calls (future tools)

  • Labels: service, endpoint, status

Logging

Structured logging with emoji indicators for easy visual parsing:

  • 🏁 Process start
  • 🔍 Validation
  • 🎯 Processing
  • 📦 Formatting
  • ✅ Success
  • ❌ Error

🏗️ Architecture

Project Structure

ymetrika-mcp/
├── src/
│   ├── mcp_instance.py      # Single FastMCP instance
│   ├── server.py            # Main entry point, tracing init
│   ├── config.py            # Configuration and environment
│   ├── metrics.py           # Prometheus metrics definitions
│   └── tools/               # MCP tools (one per file)
│       ├── __init__.py
│       ├── hello.py         # Ping tool
│       └── utils.py         # Shared utilities
├── openspec/                # OpenSpec change proposals
├── pyproject.toml           # Python project configuration
├── Dockerfile               # Container image
├── .env.example             # Environment template
├── env_options.json         # Environment documentation
├── mcp_tools.json           # Tool specifications
└── README.md                # This file

Key Design Principles

  1. Single FastMCP Instance: All tools are registered with one mcp instance in mcp_instance.py
  2. One Tool Per File: Each tool lives in its own file under src/tools/
  3. Async Everything: All tools are async functions using async def
  4. Type Safety: Pydantic Field for all parameters with validation
  5. Context Logging: All tools use ctx: Context for progress and logging
  6. Error Mapping: Standard MCP error codes via McpError:
    • -32602: Invalid parameters / validation errors
    • -32603: Internal / unexpected errors
  7. Observability First: OTel spans and Prometheus metrics on every tool
  8. Streamable HTTP Only: Transport is locked to streamable-http
  9. Security: No hardcoded secrets, non-root Docker user, no filesystem writes

🔐 Security

  • Environment variables for all configuration (no hardcoded secrets)

  • Docker container runs as non-root user (mcp, UID 1000)

  • No runtime filesystem writes

  • Input validation with Pydantic

🧪 Testing

# Run tests
uv run pytest

# Run with coverage
uv run pytest --cov=src --cov-report=html

# Type checking
uv run mypy src

# Linting
uv run ruff check src

📚 Development Guidelines

This project follows strict Agent development rules defined in AGENTS.md and .rules. Key requirements:

  • Async tool functions with async def
  • Pydantic Field for parameter validation
  • Context usage (ctx: Context) for logging and progress
  • Progress reporting at 0%, 25%, 50%, 75%, 100%
  • McpError for all errors with standard codes
  • OpenTelemetry spans wrapping tool logic
  • Prometheus metrics for observability

For detailed guidelines, see:

  • AGENTS.md - Agent development rules
  • openspec/project.md - OpenSpec workflow
  • openspec/AGENTS.md - MCP-specific standards

🗺️ Roadmap

Phase 1: Base Skeleton ✅

  • Base server with streamable-http
  • Hello-world ping tool
  • OpenTelemetry tracing
  • Prometheus metrics
  • Docker support

Phase 2: Yandex Metrika Tools ✅

  • Counter statistics (get_account_info)
  • Traffic reports (get_visits)
  • Traffic sources analysis (get_traffic_sources_types)
  • User demographics (get_user_demographics)
  • Goals and conversions (get_goals_conversion)

Phase 3: Advanced Features (Future)

  • Batch report generation
  • Data export tools
  • Custom dashboards
  • Multi-counter support

📖 References

📝 License

MIT License - see LICENSE file for details

🤝 Contributing

Contributions are welcome! Please follow the OpenSpec workflow:

  1. Create a change proposal in openspec/changes/<change-id>/
  2. Define requirements with scenarios
  3. Implement following Agent rules
  4. Update documentation (README.md, mcp_tools.json, env_options.json)
  5. Submit PR with tests

💬 Support

For issues, questions, or feature requests, please open an issue on GitHub.


Built with ❤️ using FastMCP and OpenTelemetry