NNSTD-cloud-ru-hack-2025/ymetrika-mcp
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.
Yandex Metrika MCP Server
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
- Clone the repository
git clone <repository-url>
cd ymetrika-mcp
- Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh
- Install dependencies
uv sync
- Configure environment
cp .env.example .env
# Edit .env with your configuration
- Run the server
uv run python src/server.py
The server will start on http://0.0.0.0:8000 by default.
Docker Deployment
- Build the image
docker build -t yandex-metrika-mcp .
- 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 identifierdate_from(optional, string): Start date (YYYY-MM-DD or relative format). Default: 6daysAgodate_to(optional, string): End date (YYYY-MM-DD or relative format). Default: todaymetrics(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 identifierdate_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:trafficSourcemetrics(optional, string): Comma-separated metrics. Default: ym:s:visits,ym:s:userslimit(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 identifierdate_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:agemetrics(optional, string): Comma-separated metrics. Default: ym:s:visits,ym:s:userslimit(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 identifierdate_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 resultsdimensions(optional, string): Comma-separated dimensions. Default: ym:s:goalmetrics(optional, string): Comma-separated metrics. Default: ym:s:sumGoalReachesAny,ym:s:anyGoalConversionRatelimit(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
| Variable | Type | Default | Description |
|---|---|---|---|
PORT | integer | 8000 | Server port number (1024-65535) |
LOG_LEVEL | string | INFO | Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL) |
ENVIRONMENT | string | development | Runtime mode (development or production) |
OpenTelemetry Configuration
| Variable | Type | Default | Description |
|---|---|---|---|
OTEL_ENDPOINT | string | (empty) | OTLP HTTP endpoint for traces. If not set, console exporter is used. |
OTEL_SERVICE_NAME | string | yandex-metrika-mcp | Service name for tracing |
Yandex Metrika API
| Variable | Type | Default | Description |
|---|---|---|---|
YANDEX_API_KEY | string | (empty) | Yandex OAuth token (get from https://oauth.yandex.ru/) |
YANDEX_COUNTER_ID | string | (empty) | Default Metrika counter ID |
API_TIMEOUT | integer | 30 | API request timeout in seconds (1-300) |
API_MAX_RETRIES | integer | 3 | Maximum 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:
-
Get OAuth Token:
- Visit Yandex OAuth
- Create a new application or use an existing one
- Request the
metrika:readscope - Generate the OAuth token
-
Set Environment Variable:
export YANDEX_API_KEY=your_oauth_token_here -
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
- Single FastMCP Instance: All tools are registered with one
mcpinstance inmcp_instance.py - One Tool Per File: Each tool lives in its own file under
src/tools/ - Async Everything: All tools are async functions using
async def - Type Safety: Pydantic
Fieldfor all parameters with validation - Context Logging: All tools use
ctx: Contextfor progress and logging - Error Mapping: Standard MCP error codes via
McpError:-32602: Invalid parameters / validation errors-32603: Internal / unexpected errors
- Observability First: OTel spans and Prometheus metrics on every tool
- Streamable HTTP Only: Transport is locked to
streamable-http - 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 rulesopenspec/project.md- OpenSpec workflowopenspec/AGENTS.md- MCP-specific standards
🗺️ Roadmap
Phase 1: Base Skeleton ✅
- Base server with streamable-http
- Hello-world
pingtool - 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
- Model Context Protocol (MCP)
- FastMCP Framework
- Yandex Metrika API
- OpenTelemetry Python
- Prometheus Client Python
📝 License
MIT License - see LICENSE file for details
🤝 Contributing
Contributions are welcome! Please follow the OpenSpec workflow:
- Create a change proposal in
openspec/changes/<change-id>/ - Define requirements with scenarios
- Implement following Agent rules
- Update documentation (
README.md,mcp_tools.json,env_options.json) - Submit PR with tests
💬 Support
For issues, questions, or feature requests, please open an issue on GitHub.
Built with ❤️ using FastMCP and OpenTelemetry