# Countly Mcp Server

> MCP Server for Countly Digital Analytics

- **Type:** MCP server
- **Install:** `agentstack add mcp-countly-countly-mcp-server`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [Countly](https://agentstack.voostack.com/s/countly)
- **Installs:** 0
- **Category:** [Data & Analytics](https://agentstack.voostack.com/c/data-and-analytics)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [Countly](https://github.com/Countly)
- **Source:** https://github.com/Countly/countly-mcp-server

## Install

```sh
agentstack add mcp-countly-countly-mcp-server
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Countly MCP Server

A Model Context Protocol (MCP) server for [Countly Analytics Platform](https://countly.com). This server enables AI assistants and MCP clients to interact with Countly's analytics data, manage applications, view dashboards, track events, and perform comprehensive analytics operations.

## About Countly

Countly is an open-source, enterprise-grade product analytics platform. It helps track user behavior, monitor application performance, and gain insights into user engagement. This MCP server provides programmatic access to all major Countly features through a standard protocol interface.

## What is MCP?

The Model Context Protocol (MCP) is an open protocol that enables seamless integration between AI applications and external data sources. This server implements MCP to allow AI assistants like Claude to interact with your Countly analytics data naturally through conversation.

## Requirements

### Server Requirements
- **Node.js 18+** (for local installation) OR **Docker** (recommended)
- **Countly Server**: Access to a Countly instance (cloud or self-hosted)
- **Auth Token**: Valid Countly authentication token with appropriate permissions

### Client Requirements
- **MCP Protocol Version**: `2025-03-26` (Streamable HTTP specification)
- **Compatible Clients**:
  - VS Code MCP Extension (latest version)
  - Claude Desktop (recent versions supporting 2025-03-26 spec)
  - Any MCP client implementing the Streamable HTTP transport protocol

> ⚠️ **Note**: For SSE type this server uses `StreamableHTTPServerTransport` which implements the modern MCP specification (2025-03-26). Older MCP clients that only support the legacy SSE protocol (2024-11-05) are not compatible. Please ensure your MCP client is up-to-date.

## Features

- **151 Tools** across 33 categories for comprehensive Countly operations
- **Resources** for AI context - Access read-only Countly data (app configs, event schemas, analytics overviews)
- **Prompts** for common tasks - Pre-built templates for crash analysis, engagement reports, and more
- **Multiple Transport Options**: Supports both stdio (recommended) and HTTP/SSE connections
- **Flexible Authentication**: Environment variables, HTTP headers, URL parameters, or token files
- **Plugin-Aware**: Automatically detects and enables tools based on available Countly plugins
- **Docker Support**: Pre-built Docker images with multi-architecture support (amd64, arm64)
- **Anonymous Analytics**: Optional usage tracking (disabled by default) to help improve the server
-

## MCP Capabilities

This server implements the full MCP specification with support for:

### Tools (151 available)
Execute Countly operations like analytics queries, app management, crash analysis, etc.

### Resources
Read-only access to Countly data for AI context:
- `countly://app/{app_id}/config` - Application configuration and metadata
- `countly://app/{app_id}/events` - Event definitions and schemas  
- `countly://app/{app_id}/overview` - Current analytics overview with key metrics

Resources provide AI assistants with context without requiring tool calls, making conversations more efficient.

### Prompts
Pre-built analysis templates exposed as slash commands:
- `analyze_crash_trends` - Analyze crash and error patterns
- `generate_engagement_report` - Comprehensive user engagement analysis
- `compare_app_versions` - Compare performance between versions
- `user_retention_analysis` - Analyze retention patterns and cohorts
- `funnel_optimization` - Conversion funnel analysis and suggestions
- `event_health_check` - Event tracking implementation quality check
- `identify_churn_risk` - Find users showing decreased engagement
- `performance_dashboard` - Comprehensive performance overview

Prompts guide AI assistants through complex multi-step workflows automatically.

- 🔐 Multiple authentication methods (HTTP headers, environment variables, file-based)
- 📊 Comprehensive Countly API access
- ⚙️ Fine-grained tools configuration with CRUD operation control per category
- 🐳 Docker support with production-ready configuration
- 🔄 Support for both stdio and HTTP transports
- 🏥 Built-in health checks
- 🔒 Secure token handling with cryptographically secure session IDs
- 🌐 Multi-client support with per-client credential passing
- 🚨 **Enhanced error handling** with detailed API error messages

## Quick Start

### Prerequisites

Before starting, ensure you have:
- Access to a Countly instance (cloud or self-hosted)
- Valid Countly authentication token with appropriate permissions
- Node.js 18+ (for local installation) OR Docker (recommended)
- MCP client supporting protocol version 2025-03-26 (Streamable HTTP)

### Using npx (No Installation)

Run the published package directly with `npx` — no clone or build required:

```bash
# stdio mode (for MCP clients like Claude Desktop, VS Code)
COUNTLY_SERVER_URL=https://your-countly-instance.com \
COUNTLY_AUTH_TOKEN=your-countly-auth-token \
npx -y countly-mcp-server

# HTTP mode
COUNTLY_SERVER_URL=https://your-countly-instance.com \
COUNTLY_AUTH_TOKEN=your-countly-auth-token \
npx -y countly-mcp-server --http
```

Example MCP client configuration (stdio):

```json
{
  "mcpServers": {
    "countly": {
      "command": "npx",
      "args": ["-y", "countly-mcp-server"],
      "env": {
        "COUNTLY_SERVER_URL": "https://your-countly-instance.com",
        "COUNTLY_AUTH_TOKEN": "your-countly-auth-token"
      }
    }
  }
}
```

### Using Docker (Recommended)

1. **Create a token file:**
   ```bash
   echo "your-countly-auth-token" > countly_token.txt
   ```

2. **Create a `.env` file:**
   ```bash
   cp .env.example .env
   # Edit .env and set your COUNTLY_SERVER_URL
   ```

3. **Run with Docker Compose:**
   ```bash
   docker-compose up -d
   ```

4. **Access the server:**
   - HTTP/SSE mode: `http://localhost:3000/mcp`
   - Health check: `http://localhost:3000/health`
   - Default port: 3000 (configurable)

### Using Docker Run

```bash
docker run -d \
  --name countly-mcp-server \
  -p 3000:3000 \
  -e COUNTLY_SERVER_URL=https://your-countly-instance.com \
  -e COUNTLY_AUTH_TOKEN_FILE=/run/secrets/countly_token \
  -v $(pwd)/countly_token.txt:/run/secrets/countly_token:ro \
  countly-mcp-server
```

### Using Node.js

1. **Install dependencies:**
   ```bash
   npm install
   ```

2. **Build the project:**
   ```bash
   npm run build
   ```

3. **Configure environment:**
   ```bash
   cp .env.example .env
   # Edit .env with your settings
   ```

4. **Run the server:**
   ```bash
   # HTTP mode
   npm start
   
   # stdio mode (for MCP clients)
   npm run start:stdio
   ```

## Authentication

The server supports multiple authentication methods (in priority order):

1. **HTTP Headers** (recommended for HTTP/SSE transport)
   - Pass via `X-Countly-Server-Url` and `X-Countly-Auth-Token` headers
   - Supported by VS Code MCP extension and other HTTP clients
   - See [VS Code MCP Configuration](examples/vscode-mcp.md) for details

2. **URL Parameters** (alternative for HTTP/SSE transport)
   - Pass as query string: `?server_url=https://your-server.count.ly&auth_token=your-api-key`
   - Useful for quick testing or tools that don't support custom headers
   - Less secure than headers, use headers when possible

3. **Tool Arguments**
   - Passed as `countly_auth_token` parameter in individual tool calls

4. **Environment Variable**
   - Set `COUNTLY_AUTH_TOKEN` in environment
   - Recommended for stdio transport mode

5. **Token File** (recommended for production)
   - Set `COUNTLY_AUTH_TOKEN_FILE` pointing to a file containing the token
   - Useful with Docker secrets

## Configuration

### Environment Variables

| Variable | Required | Default | Description |
|----------|----------|---------|-------------|
| `COUNTLY_SERVER_URL` | Yes | `https://api.count.ly` | Your Countly server URL |
| `COUNTLY_AUTH_TOKEN` | No* | - | Authentication token (direct) |
| `COUNTLY_AUTH_TOKEN_FILE` | No* | - | Path to file containing auth token |
| `COUNTLY_TIMEOUT` | No | `30000` | Request timeout in milliseconds |
| `ENABLE_ANALYTICS` | No | `false` | Enable anonymous usage analytics (set to `true` to opt in) |
| `COUNTLY_TOOLS_{CATEGORY}` | No | `ALL` | Control available tools per category (see below) |
| `COUNTLY_TOOLS_ALL` | No | `ALL` | Default permission for all categories |
| `COUNTLY_CORS_ALLOWED_ORIGINS` | No | `*` | Comma-separated list of allowed CORS origins (HTTP transport). Leave unset or `*` for wide-open; use specific origins in production (e.g. `https://app.example.com,https://dash.example.com`). |
| `COUNTLY_RATE_LIMIT_RPM` | No | `120` | Per-IP requests per minute on the `/mcp` endpoint (HTTP transport). Set to `0` to disable. |
| `COUNTLY_TRUST_PROXY` | No | `false` | When `true`, use `X-Forwarded-For` for the rate-limit client IP. Only enable when the server is behind a trusted reverse proxy that sets this header. |
| `COUNTLY_MAX_BODY_BYTES` | No | `1048576` | Maximum request-body size accepted on `/mcp` (HTTP transport). Requests over the limit get `413 Payload Too Large`. Set to `0` to disable. |
| `COUNTLY_MAX_CONCURRENT_PER_IP` | No | `50` | Maximum simultaneous TCP connections per client IP (HTTP transport). Over-limit connections are dropped. Set to `0` to disable. |
| `COUNTLY_REQUEST_LOG` | No | `false` | When `true`, emit one NDJSON line per request to stderr (`{ts, ip, method, path, status, durationMs, rateLimitHit}`). Useful for piping into a log aggregator to spot abuse patterns. |

*At least one authentication method must be configured

### Analytics Tracking (Optional)

The MCP server includes optional anonymous usage analytics to help improve the product. Analytics are **disabled by default** and can be opted into via the `ENABLE_ANALYTICS=true` environment variable.

**What is tracked:**
- Transport type used (stdio vs HTTP)
- Tool execution metrics (success/failure, duration, tool names)
- Authentication methods used (headers, env, file, args)
- HTTP endpoint access patterns
- Error occurrences (type and message, NO sensitive data)
- Server start/stop events
- A **truncated opaque hash** of your Countly server URL (64-bit SHA-256 prefix), attached as the `server` segment on every event — used for distinct-server aggregation. The raw URL is never sent.

**What is NOT tracked:**
- Authentication tokens or credentials
- Raw Countly server URLs or domains (only the opaque `server` hash above)
- User data or analytics content
- Personal information
- IP addresses or client identifiers
- Tool arguments or request/response bodies

**Privacy & Device ID:**
All analytics are aggregated under a single device ID `"mcp"` — Countly cannot distinguish individual operators from the device ID alone. The only per-deployment signal is the `server` hash on events, which is a truncated SHA-256 of the normalized server URL. The hash is intentionally coarse (64 bits) and the server URL is low-entropy, so do not assume the hash is unguessable for cloud patterns; it is meant for aggregation, not secrecy.

**To opt in:**
```bash
export ENABLE_ANALYTICS=true
```

Or in your `.env` file:
```
ENABLE_ANALYTICS=true
```

### Tools Configuration

The server supports fine-grained control over which MCP tools are available and which CRUD operations they can perform. This is useful for security, governance, or creating read-only deployments.

Configure tools by category using environment variables:

```bash
# Format: COUNTLY_TOOLS_{CATEGORY}=CRUD
# Where CRUD letters represent: Create, Read, Update, Delete operations

# Examples:
COUNTLY_TOOLS_APPS=CR          # Apps: Create and Read only
COUNTLY_TOOLS_DATABASE=R       # Database: Read-only access
COUNTLY_TOOLS_CRASHES=CRUD     # Crashes: Full access
COUNTLY_TOOLS_ALERTS=NONE      # Alerts: Completely disabled

# Set default for all categories:
COUNTLY_TOOLS_ALL=R            # Read-only mode for all tools
```

**Available Categories** (subset — see TOOLS_CONFIGURATION.md for all 33):
- `CORE` - Core tools (ping, get_version, get_plugins) (3 tools)
- `APPS` - Application management (6 tools)
- `ANALYTICS` - Analytics data retrieval (7 tools)
- `CRASHES` - Crash analytics and management (10 tools)
- `NOTES` - Notes management (3 tools)
- `EVENTS` - Event configuration (1 tool)
- `ALERTS` - Alert management (3 tools)
- `VIEWS` - Views analytics (3 tools)
- `DATABASE` - Direct database access (6 tools)
- `DASHBOARD_USERS` - Dashboard user management (1 tool)
- `APP_USERS` - App user management (3 tools)

For complete documentation, examples, and per-tool CRUD mappings, see **[TOOLS_CONFIGURATION.md](TOOLS_CONFIGURATION.md)**.

## Security & Production Hardening

The HTTP transport is designed to be usable both as a public-facing MCP
endpoint (e.g. `mcp.count.ly`) and as a self-hosted single-tenant server.
The defaults favor compatibility; operators should opt into the tighter
settings below based on their deployment model.

### Multi-tenant isolation

The HTTP transport is safe to use with multiple concurrent clients using
different Countly auth tokens. Each request gets its own outbound axios
instance with the `countly-token` header baked in, and each tenant's apps
cache is keyed by SHA-256(token) so one tenant's apps cannot leak into
another tenant's `resolveAppId` lookup.

No operator configuration is required for this.

### SSRF

Caller-supplied server URLs (via `X-Countly-Server-Url` header or
`?server_url=` query param) are validated against an SSRF denylist —
loopback, link-local, RFC 1918, carrier-grade NAT, cloud metadata
endpoints (`169.254.169.254`), `.local`/`.localhost`, and non-HTTP(S)
schemes are rejected with a 400. This is a syntactic check; defense
against DNS-rebinding still requires egress firewalling the server.

### Credentials in URLs are deprecated

Passing the auth token via `?auth_token=` is supported for backward
compatibility but emits a rate-limited security warning to stderr.
Tokens in URLs leak into access logs, browser history, and Referer
headers. Migrate callers to `X-Countly-Auth-Token` — URL-param support
will be removed in a future release.

### Rate limiting

The `/mcp` endpoint has a per-IP sliding-window rate limiter, defaulting
to 120 requests per minute. Tune via `COUNTLY_RATE_LIMIT_RPM=`
(set to `0` to disable). Behind a trusted reverse proxy, set
`COUNTLY_TRUST_PROXY=true` so the first `X-Forwarded-For` hop is used as
the client IP.

### Resource-exhaustion defenses

Additional protections layered on top of the application-level rate limit:

- **Request body cap** (`COUNTLY_MAX_BODY_BYTES`, default 1 MiB) — `413
  Payload Too Large` + socket destroyed for oversize bodies. Checked both
  upfront via `Content-Length` and streamingly (for chunked / lying
  clients).
- **Per-IP concurrent connection cap** (`COUNTLY_MAX_CONCURRENT_PER_IP`,
  default 50) — over-limit TCP connections are dropped before the TLS
  handshake, closing the slow-loris amplification.
- **Server timeouts** — `requestTimeout=30s`, `headersTimeout=10s`,
  `keepAliveTimeout=5s`, `timeout=60s`. Slow clients can't keep sockets
  open indefinitely.

For operators that want per-request audit logs for abuse detection, set
`COUNTLY_REQUEST_LOG=true`. The server will emit one NDJSON line per
request to stderr, containing only the fields listed in the env-var
table — no auth tokens, no bodies, no headers.

### CORS

The default is `Access-Control-Allow-Origin: *` so browser-based MCP
clients from any origin can connect. If your deployment only needs to
serve specific origins, lock it down:

```bash
COUNTLY_CORS_ALLOWED_ORIGINS="https://dash.example.com,https://ops.example.com"
```

The server will then echo only allowed origins and add `Vary: Origin`.
Pre-flight requests from disallowed origins get a 403.

### Self-hosted single-tenant deployments

If you're running this as a single-tenant server (e.g. `docker run` on a
VPS for your own AI assistant), prefer one of:

- **Bind to localhost only** and tunnel through SSH:
  `docke

…

## Source & license

This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [Countly](https://github.com/Countly)
- **Source:** [Countly/countly-mcp-server](https://github.com/Countly/countly-mcp-server)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** yes
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** yes
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/mcp-countly-countly-mcp-server
- Seller: https://agentstack.voostack.com/s/countly
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
