A Model Context Protocol (MCP) server for Countly Analytics Platform. 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.
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.
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.
- Node.js 18+ (for local installation) OR Docker (recommended)
- Countly Server: Access to a Countly instance (cloud or self-hosted): Countly Lite, Countly Enterprise or Countly Platform (see Supported Countly Editions)
- Auth Token: Valid Countly authentication token with appropriate permissions
- 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 usesStreamableHTTPServerTransportwhich 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.
- 209 Tools across 43 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
- Edition-Aware: Detects Countly Lite, Enterprise or Platform on connection and only exposes the tools that server and the connected user can use
- Docker Support: Pre-built Docker images with multi-architecture support (amd64, arm64)
- Usage Analytics: Usage reporting to stats.count.ly under your Countly server's domain (on by default;
ENABLE_ANALYTICS=falseopts out)
The server works with every Countly flavor and detects which one it is talking to on the first request for a server URL and token. The result is cached for 10 minutes.
| Edition | What it is | How it is detected |
|---|---|---|
| Countly Lite | countly-server |
No /v2 API, no enterprise plugins |
| Countly Enterprise | countly-server + enterprise plugins |
No /v2 API, enterprise plugins present (drill, funnels, cohorts, …) |
| Countly Platform | countly-platform, the new architecture |
Answers the /v2 API (new UI), or Platform-only endpoints/plugins when running without it |
Based on the detection, tools/list only contains tools that will work:
- Plugins: tools whose Countly plugin is not enabled are hidden (e.g. cohorts on Lite, server logs on Platform). Global admins read the real plugin list. For other users the edition's default plugin set is assumed, because Countly only shows the plugin list to global admins.
- User permissions: tools the connected user could never run are hidden, based on the user's feature permissions (create/read/update/delete per app, app admin, global admin), including group permissions. A read-only user sees roughly half the tools.
- Explanations instead of failures: calling a hidden tool returns an error naming the missing plugin or permission, so the assistant can tell the user what is missing.
Detection never hides tools on a guess: if the server cannot be reached or the user's permissions cannot be read, the configured tools stay available. get_version reports the detected edition. Set COUNTLY_AUTO_DETECT=false to turn detection off. Details are in TOOLS_CONFIGURATION.md.
This server implements the full MCP specification with support for:
Execute Countly operations like analytics queries, app management, crash analysis, etc. Each connection only sees the tools its Countly edition, plugins and user permissions support (see Supported Countly Editions).
Read-only access to Countly data for AI context:
countly://app/{app_id}/config- Application configuration and metadatacountly://app/{app_id}/events- Event definitions and schemascountly://app/{app_id}/overview- Current analytics overview with key metrics
Resources provide AI assistants with context without requiring tool calls, making conversations more efficient.
Pre-built analysis templates exposed as slash commands:
analyze_crash_trends- Analyze crash and error patternsgenerate_engagement_report- Comprehensive user engagement analysiscompare_app_versions- Compare performance between versionsuser_retention_analysis- Analyze retention patterns and cohortsfunnel_optimization- Conversion funnel analysis and suggestionsevent_health_check- Event tracking implementation quality checkidentify_churn_risk- Find users showing decreased engagementperformance_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
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)
Run the published package directly with npx — no clone or build required:
# 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 (binds localhost; see "Server-side token in HTTP mode" before exposing it)
COUNTLY_SERVER_URL=https://your-countly-instance.com \
COUNTLY_AUTH_TOKEN=your-countly-auth-token \
npx -y countly-mcp-server --httpExample MCP client configuration (stdio):
{
"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"
}
}
}
}-
Create a token file:
echo "your-countly-auth-token" > countly_token.txt
-
Create a
.envfile:cp .env.example .env # Edit .env and set your COUNTLY_SERVER_URL -
Run with Docker Compose:
docker-compose up -d
-
Access the server:
- HTTP/SSE mode:
http://localhost:3000/mcp - Health check:
http://localhost:3000/health - Default port: 3000 (configurable)
- HTTP/SSE mode:
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-
Install dependencies:
npm install
-
Build the project:
npm run build
-
Configure environment:
cp .env.example .env # Edit .env with your settings -
Run the server:
# HTTP mode npm start # stdio mode (for MCP clients) npm run start:stdio
The server supports multiple authentication methods (in priority order):
-
Tool Arguments
- Passed as
countly_auth_tokenparameter in individual tool calls - Overrides every other source for that call
- Passed as
-
HTTP Headers (recommended for HTTP/SSE transport)
- Pass via
X-Countly-Server-UrlandX-Countly-Auth-Tokenheaders - Supported by VS Code MCP extension and other HTTP clients
- See VS Code MCP Configuration for details
- Pass via
-
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
- Pass as query string:
-
Environment Variable
- Set
COUNTLY_AUTH_TOKENin environment - Recommended for stdio transport mode
- Set
-
Token File (recommended for production)
- Set
COUNTLY_AUTH_TOKEN_FILEpointing to a file containing the token - Useful with Docker secrets
- Set
A token the caller supplies (1–3) always wins over the server's own (4–5); the server-side token is only used for a request that brings none.
| 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 | true |
Usage analytics to stats.count.ly under your Countly server's domain (set to false to opt out) |
COUNTLY_AUTO_DETECT |
No | true |
Detect Countly Lite / Enterprise / Platform and hide tools the server doesn't support (set to false to always show all configured tools) |
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). When a server-side token is configured, browser requests to /mcp are refused unless their origin is listed here explicitly; * does not count. |
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
The MCP server reports usage analytics to stats.count.ly to help improve the product, the same way the Countly platform reports its own server telemetry. Analytics are enabled by default; opt out with ENABLE_ANALYTICS=false.
Device ID: your Countly server's domain. Events are reported under the domain of the Countly server the MCP server talks to (COUNTLY_SERVER_URL, or the per-request server URL in multi-tenant HTTP mode), with the scheme and trailing slashes removed, e.g. countly.example.com or countly.example.com:8443/countly. This is the same device ID the Countly platform uses for its own telemetry, so both line up on the stats server. Usage goes to the Countly server telemetry app on stats.count.ly (the app the Countly platform itself reports to), so MCP usage and the server's own telemetry sit under one device.
When there is no usable domain (no server URL, or localhost), nothing is reported. In multi-tenant HTTP mode with no COUNTLY_SERVER_URL, that means visits to the welcome page, health checks, favicon and manifest requests, server start and the session are not reported; only MCP requests, which carry their server URL, are.
What is tracked:
- Your Countly server's domain (as the device ID, above)
- 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 (the error type and tool name only, no message)
- Server start events
- A truncated hash of the server URL, attached as the
serversegment on every event
What is NOT tracked:
- Authentication tokens or credentials
- User data or analytics content
- Personal information
- Tool arguments or request/response bodies
To opt out:
export ENABLE_ANALYTICS=falseOr in your .env file:
ENABLE_ANALYTICS=false
When the tools are embedded in another process through countly-mcp-server/library, the host decides whether and under which device ID usage is reported (see "Embedding in another process").
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:
# 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 toolsAvailable Categories (subset — see TOOLS_CONFIGURATION.md for all 42):
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 (5 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.
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.
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.
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.
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.
The /mcp endpoint has a per-IP sliding-window rate limiter, defaulting
to 120 requests per minute. Tune via COUNTLY_RATE_LIMIT_RPM=<n>
(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.
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 viaContent-Lengthand 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.
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:
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.
When the server holds its own token (COUNTLY_AUTH_TOKEN or
COUNTLY_AUTH_TOKEN_FILE), /mcp refuses every request that carries an
Origin header with a 403, unless that origin is listed explicitly in
COUNTLY_CORS_ALLOWED_ORIGINS (the * default does not count). MCP
clients such as Claude Desktop, Claude Code, VS Code and Cursor send no
Origin header and are unaffected. This stops a web page open in the
operator's browser, including one using DNS rebinding, from driving a
server that holds a token. Servers without a configured token, where every
caller brings its own, are not affected by this rule.
COUNTLY_AUTH_TOKEN and COUNTLY_AUTH_TOKEN_FILE exist for stdio mode,
where the MCP client launches the server as its own child process. In HTTP
mode the server does not authenticate its callers: when one is set,
any caller that reaches /mcp without supplying its own token acts with
the configured one, with all the permissions that token carries.
Only configure a server-side token in HTTP mode when the endpoint is
reachable from a trusted network alone: bound to localhost, behind a
firewall, or behind a reverse proxy that authenticates callers. The server
logs a warning at startup when it runs this way. For a shared or
internet-facing deployment, leave both variables unset and have each
client send its own token in the X-Countly-Auth-Token header.
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:
docker run -p 127.0.0.1:3000:3000 ... - Bind behind a reverse proxy (Caddy, Nginx, Traefik) that terminates
TLS, adds authentication if needed, and sets a trusted
X-Forwarded-For(then setCOUNTLY_TRUST_PROXY=true).
The default Dockerfile binds to 0.0.0.0:3000 so it works inside a
container without extra flags. This means docker run -p 3000:3000 ...
exposes the MCP endpoint to the public internet — use an explicit local
bind, a reverse proxy, or an external firewall if that's not what you
want. This matters most when the container is given a server-side token:
see Server-side token in HTTP mode.
Analytics are enabled by default and report under your Countly server's
domain; opt out with ENABLE_ANALYTICS=false. No authentication tokens,
tool arguments or error messages are ever sent to stats.count.ly; an error
is reported as its type and the tool it came from.
Pull the image from Docker Hub:
docker pull countly/countly-mcp-server:latestdocker build -t countly-mcp-server .The included docker-compose.yml provides a production-ready setup with:
- Docker secrets for secure token storage
- Health checks
- Resource limits
- Automatic restart
- Proper logging configuration
For orchestrated deployments, use external secrets:
Docker Swarm:
# Create secret
echo "your-token" | docker secret create countly_token -
# Deploy stack
docker stack deploy -c docker-compose.yml countlyKubernetes:
apiVersion: v1
kind: Secret
metadata:
name: countly-token
type: Opaque
stringData:
token: your-countly-auth-token
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: countly-mcp-server
spec:
replicas: 1
selector:
matchLabels:
app: countly-mcp-server
template:
metadata:
labels:
app: countly-mcp-server
spec:
containers:
- name: countly-mcp-server
image: countly-mcp-server:latest
ports:
- containerPort: 3000
env:
- name: COUNTLY_SERVER_URL
value: "https://your-countly-instance.com"
- name: COUNTLY_AUTH_TOKEN_FILE
value: "/run/secrets/countly_token"
volumeMounts:
- name: token
mountPath: /run/secrets
readOnly: true
volumes:
- name: token
secret:
secretName: countly-token
items:
- key: token
path: countly_tokenThe most common use case is with Claude Desktop. Add to your Claude configuration file:
Location:
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Using Docker:
{
"mcpServers": {
"countly": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e", "COUNTLY_SERVER_URL=https://your-countly-instance.com",
"-e", "COUNTLY_AUTH_TOKEN=your-token-here",
"countly-mcp-server",
"node", "build/index.js"
]
}
}
}Using local installation:
{
"mcpServers": {
"countly": {
"command": "node",
"args": ["/path/to/countly-mcp-server/build/index.js"],
"env": {
"COUNTLY_SERVER_URL": "https://your-countly-instance.com",
"COUNTLY_AUTH_TOKEN": "your-token-here"
}
}
}
}Using environment variable for token (alternative):
{
"mcpServers": {
"countly": {
"command": "node",
"args": ["/path/to/countly-mcp-server/build/index.js"],
"env": {
"COUNTLY_SERVER_URL": "https://your-countly-instance.com",
"COUNTLY_AUTH_TOKEN": "your-token-here"
}
}
}
}This server is compatible with any MCP client that supports:
- stdio transport (default) - For local/desktop clients (uses environment variables for auth)
- HTTP/SSE transport - For web-based or remote clients (uses HTTP headers for auth)
For HTTP mode, clients should connect to: http://your-server:3000/mcp
The server provides 209 tools across 43 categories for comprehensive Countly integration. Tools marked (Platform) exist only on Countly Platform with its /v2 API. Tools marked (v2 on Platform) use the richer Platform /v2 endpoints there, and the classic endpoints on Lite and Enterprise.
ping- Check if Countly server is healthy and reachableget_version- Check what version of Countly is running on the serverget_plugins- Get list of installed plugins on the server
apps_list(v2 on Platform) - List all applications; on Platform with your role (admin/user) per appapps_get_by_name(v2 on Platform) - Get app details by nameapps_create- Create new applicationapps_update- Update app settingsapps_delete- Delete applicationapps_reset- Reset app data
query_data- Analytics data by predefined methods (locations, carriers, devices, etc.), event data, or drill segmentation. On Platform, usedrill_queryfor metrics, formulas and cohortsapp_analytics_summary- General app summary and analytics overviewslipping_users- Identify inactive app userssession_frequency- Session frequency distribution across time buckets (f=0: first session, f=1: 1-24h, f=2: 1 day, through f=11: 30+ days)user_loyalty- User loyalty data showing session count distribution across loyalty buckets (1 session, 2 sessions, 3-5, 6-9, 10-19, 20-49, 50-99, 100-499, 500+)session_durations- Session duration distribution across duration buckets (0-10 sec, 11-30 sec, 31-60 sec, 1-3 min, 3-10 min, 10-30 min, 30-60 min, 1+ hour)
events_create- Define event with metadata and configurationevents_list(v2 on Platform) - List all events and their segments, including internal Countly events with exact database structure; on Platform with search, paging, display names and drill-only eventsevents_summary(Platform) - All custom events with count, sum, duration and per-occurrence averages for a periodevents_top(Platform) - Events ranked by count, average sum and average durationevents_movers(Platform) - Fastest-growing and newly appearing events vs the previous period, with daily seriesevents_delete- Delete events and their data
dashboard_users(v2 on Platform) - List all dashboard users (admin/management users who access the Countly dashboard); on Platform as compact rows with role and app access
app_users_create- Create app user (end-user being tracked in your application)app_users_delete- Delete app users (end-users) matching a queryapp_users_update- Update app user properties
alerts_create- Create alert configurationalerts_delete- Delete alertalerts_list- List all alerts
notes_list(v2 on Platform) - List all dashboard notesnotes_create(v2 on Platform) - Create note; on Platform with private/shared/global visibility and optional event scope (hidden from the legacy dashboard)notes_update(Platform) - Edit a note's text, time, color, visibility or event scopenotes_delete(v2 on Platform) - Delete note
databases_list- List available databasesdatabases_query- Query database collectionsdatabases_document- Get specific documentcollections_aggregate- Run aggregation pipelinescollections_indexes- View collection indexes
crash_groups_list(v2 on Platform) - List crash groups for an app; on Platform with server-side search and sortingcrashes_stats_get- Get crash statistics and graphscrashes_get- View crash detailscrash_group_breakdown(Platform) - Distribution of a crash group over a field (OS version, device, app version, …)crash_group_users(Platform) - Users affected by a crash groupcrash_jira_issues(Platform, requirescrashes-jiraplugin) - Jira issues linked to crash groupscrashes_resolve(v2 on Platform) - Mark crash as resolvedcrashes_unresolve(v2 on Platform) - Mark crash as unresolvedcrashes_hide(v2 on Platform) - Hide crash from viewcrashes_show(v2 on Platform) - Show hidden crashcrashes_comment_add- Add comment to crashcrashes_comment_update- Edit crash commentcrashes_comment_delete- Delete crash comment
drill_query(Platform) - Ad-hoc analytics over raw events: count, unique users, sum, average, percentiles, cohort and formula metrics, filters, breakdowns, time series and pagingqueriable_fields_list(v2 on Platform) - Get available properties for segmentationmetadata_get(v2 on Platform) - Event definitions, segments and system fields for building queriesdrill_bookmarks_list(v2 on Platform) - List saved segmentation queries; on Platform all saved queries of an app (or all yours), including old-UI bookmarksdrill_bookmarks_create(v2 on Platform) - Save a segmentation query; on Platform also anydrill_querymetrics, filter and breakdownsdrill_bookmarks_delete(v2 on Platform) - Delete a saved querydrill_saved_query_run(Platform) - Run a saved drill query, optionally over another perioddrill_property_values(Platform) - Distinct values of a user property, custom property or event segment, for building filters
user_profiles_query(v2 on Platform) - Query users with MongoDB filters; on Platform also free-text search, sorting, paging and totalsuser_profiles_breakdown(v2 on Platform) - Break down user counts by a property; on Platform with a top-N limit and each value's shareuser_profiles_get- Get specific user details by UID
cohorts_list- List all user cohorts with filteringcohorts_data- Get cohort data over a periodcohorts_create- Create behavioral cohort based on user actionscohorts_update- Update cohort configurationcohorts_delete- Delete a cohort
funnels_list(v2 on Platform) - List all conversion funnelsfunnels_data(v2 on Platform) - Get funnel analytics data with filtering; on Platform adds median and p95 time between stepsfunnels_step_users(v2 on Platform) - Get users who reached a specific step; on Platform with full profilesfunnels_dropoff_users(v2 on Platform) - Get users who dropped off between steps; on Platform with full profilesfunnels_create- Create conversion funnel with event sequencefunnels_update- Update funnel configurationfunnels_delete- Delete a funnelfunnels_breakdown(Platform) - Users who reached a step, split by a propertyfunnels_trends(Platform) - Daily entered, completed and conversion ratefunnels_user_progress(Platform) - How far one user got in every funnel
formulas_run- Run mathematical formulas on metrics (sessions, events, users) with filters and segmentsformulas_list- List all saved formulasformulas_save- Create or update a saved formulaformulas_delete- Delete a saved formula
live_users(v2 on Platform) - Get current online user count and new users at this momentlive_metrics- Get breakdown by countries, devices and carriers for users currently onlinelive_last_hour(v2 on Platform) - Get minute-by-minute data for the last hour (60 data points)live_last_day(v2 on Platform) - Get hour-by-hour data for the last day (24 data points)live_last_30_days(v2 on Platform) - Get daily data for the last 30 days (30 data points)live_overall- Get maximum values for online users (peak concurrent usage records)
retention- Get retention data showing consecutive event streaks. Supports three types: Full (strict - breaks on first skip), Classic (Day N - specific days independently), Unbounded (lenient - any return counts)
remote_configs_list- List all remote config parameters and conditionsremote_config_conditions_add- Add user segmentation condition using MongoDB queriesremote_config_conditions_update- Update existing condition criteriaremote_config_conditions_delete- Delete a condition (if not in use)remote_config_parameters_add- Add parameter with default and conditional valuesremote_config_parameters_update- Update parameter values, conditions, or statusremote_config_parameters_delete- Delete a parameter
ab_experiments_list- List all A/B testing experiments with statuses and resultsab_experiments_details- Get detailed experiment info including variants and statistical significanceab_experiments_create- Create new experiment with variants, user targeting, and goalsab_experiments_start- Start experiment to begin collecting dataab_experiments_stop- Stop running experimentab_experiments_delete- Delete experiment and all its data
sdk_logs_list(v2 on Platform) - List incoming data logs sent by SDK to the server for debugging and monitoring; on Platform with paging and filters by request type, SDK, time range and problem requests
sdk_stats_get- Get statistics about SDKs sending data (names, versions, request types, health checks)sdk_config_get- Get SDK configuration settings controlling SDK behavior and enabled features
consents_stats- Get aggregated consent statistics showing which consents users gave and whenconsents_list- List specific users and their consent statusconsents_history_search- Search consent history records with detailed audit trail
filtering_rules_list- List all blocking rules that filter incoming requestsfiltering_rules_create- Create rule to block requests based on MongoDB conditions (IP, version, device properties)filtering_rules_update- Update existing blocking rule configurationfiltering_rules_toggle_status- Enable or disable a blocking rulefiltering_rules_delete- Delete a blocking rule
datapoints_stats- Get data points collected per app per datapoint type. Data points measure collected data and are tied to server specs and billing.datapoints_top_apps- Get top apps ranked by data point collection for understanding data usage and billingdatapoints_punch_card- Get hourly data point breakdown punchcard showing server load patterns for capacity planning
server_logs_files_list- List available server log files (only available in non-Docker deployments)server_logs_contents- Get contents of a specific server log file for debugging and monitoring (only available in non-Docker deployments)
email_reports_list(v2 on Platform) - List all email reports configured for an app; on Platform across apps with an optional app and title filteremail_reports_core_create(v2 on Platform) - Create a core email report with metrics like analytics, events, crashes, and star-ratingemail_reports_dashboard_create(v2 on Platform) - Create a dashboard email report for specific dashboards; on Platform for new-UI dashboardsemail_reports_update(v2 on Platform) - Update an existing email report configurationemail_reports_preview(v2 on Platform) - Preview an email report to see what it will look like before sending; on Platform as readable textemail_reports_send(v2 on Platform) - Manually trigger sending an email report immediatelyemail_reports_delete(v2 on Platform) - Delete an email report configuration
views_table- Per-view metrics table (views, users, duration, bounces, exits)views_data- View metrics over timeviews_top(Platform) - Top views per metric (count, duration, bounce rate, landings, exits, scroll depth)
On Countly Platform with the new UI, the dashboard tools work with the new-UI dashboards (v2). Their widgets use the Platform widget format (drill, funnel, retention, profiles, active and online users), and dashboards_data returns each widget's results.
dashboards_list- List all available dashboards (with optional schema-only parameter)dashboards_data- Get widgets and data for a specific dashboard with time period filteringdashboards_create- Create a new dashboard with sharing settings, auto-refresh configuration, and themedashboards_update- Update dashboard configuration (name, sharing, refresh rate, theme)dashboards_delete- Delete a dashboard by IDdashboards_widget_add- Add a widget to a dashboard with full configuration (title, feature, widget type, apps, metrics, visualization)dashboards_widget_update- Update a widget on a dashboarddashboards_widget_remove- Remove a widget from a dashboard
times_of_day- Get user behavior patterns in their local time for a specific event. Shows when users are most active throughout the day (by hour) and week (by day). Useful for understanding optimal engagement times and scheduling.
hooks_list(v2 on Platform) - List all webhooks/hooks configured for an app. Shows triggers, effects, and configuration details. On Platform also across apps, with enabled/text filters, paging and run counters.hooks_get(Platform) - Get one hook with its configuration, run counters and its last failed runs with error messages.hooks_test(v2 on Platform) - Test a hook configuration with mock data before creating it. Useful for validating trigger conditions and effect actions.hooks_create(v2 on Platform) - Create a new webhook/hook with various trigger types (IncomingDataTrigger, APIEndPointTrigger, InternalEventTrigger, ScheduledTrigger) and effects (HTTPEffect, EmailEffect, CustomCodeEffect).hooks_update(v2 on Platform) - Update an existing webhook/hook configuration.hooks_delete(v2 on Platform) - Delete a webhook/hook by its ID.
On Countly Platform all journey tools use the /v2 API. Its first write on a journey created in the old dashboard moves that journey to the new UI.
journeys_list(v2 on Platform) - List journeys with status, versions and usage counters; on Platform with status/search filters, paging and counts per statusjourneys_get(v2 on Platform) - Get one journey with its versions and block graphjourneys_create(v2 on Platform) - Create a new journey (definition plus first draft version) from a block graph; on Platform also with a description and conversion goaljourneys_update(v2 on Platform) - Update a journey's name, per-user limit and/or the blocks of one of its versions; on Platform also description and goaljourneys_delete(v2 on Platform) - Soft-delete a journey and all its versionsjourneys_publish(v2 on Platform) - Publish (activate) a journey version; on Lite/Enterprise it can also unpublish to draftjourneys_pause(v2 on Platform) - Pause an active journey version and its running instancesjourneys_resume(v2 on Platform) - Resume a paused journey versionjourneys_complete(Platform) - End an active or paused journey for goodjourneys_block_reference- Get the journey block JSON schema reference (block types, per-subtype fields, validation rules, sample graphs) for authoring blocksjourneys_templates(Platform) - Ready-made journey templates with their block graphsjourneys_stats_summary(v2 on Platform) - Summary KPIs for a journey (users entered/engaged/completed/dropped off) with period-over-period change; on Platform also goal conversionjourneys_stats_table(v2 on Platform) - Journey instances (one row per user run) with paginationjourneys_stats_performance(v2 on Platform) - Time-series journey performance data for trend chartsjourneys_stats_uids(v2 on Platform) - List user UIDs behind a journey metric (entered, completed, dropped off, goal converted, ...)journeys_stats_blocks(Platform) - Per-block funnel: users who entered and completed each blockjourneys_stats_content(Platform) - In-app content engagement per message: shown, interacted, button clicksjourneys_stats_active_users(Platform) - Users active in a journey, with a daily/weekly/monthly breakdown
On Countly Platform these tools manage the new content messages (popup, banner, carousel, survey, push). Legacy content blocks are listed too, and can be read, previewed and deleted, but not edited.
content_blocks_list(v2 on Platform) - List content for an app; on Platform with search, status and format filters and pagingcontent_blocks_get(v2 on Platform) - Get one content block / message with its full definitioncontent_blocks_preview(v2 on Platform) - Get a browser preview URL showing the content rendered exactly as end users see itcontent_blocks_create(v2 on Platform) - Create content that can be delivered through journeys; on Platform a content message built from slidescontent_blocks_update(v2 on Platform) - Update existing content (on Lite/Enterprise: title, type, blocks, favorite; on Platform: name, status, slides, styling, placement, translations)content_blocks_delete(v2 on Platform) - Delete content (fails while it is still used in a journey or campaign)content_assets_list(v2 on Platform) - List uploaded content images with metadata; on Platform with search, tags and pagingcontent_assets_upload(v2 on Platform) - Upload an image asset (base64; max 5MB, or 10MB on Platform)content_assets_update(v2 on Platform) - Update an asset's name and/or tagscontent_assets_delete(v2 on Platform) - Delete an uploaded content assetcontent_langs_list- List languages eligible for content translations
flows_list(Platform) - List saved user flows with anchor, direction, period and statusflows_get(Platform) - Definition of one saved flowflows_data(Platform) - Top events per step from the anchor event, with the strongest transitionsflows_dropoff(Platform) - What users did instead of an expected next step
ratings_widgets_list(Platform) - Rating widgets with status, times shown, responses and average ratingratings_stats(Platform) - Responses, average and 1-5 distribution of one widget for a periodratings_comments(Platform) - Individual responses (rating, comment, email, user) of one widget
campaigns_list(Platform) - Push, in-app, survey and rating campaigns with status and delivery counterscampaigns_get(Platform) - Full definition of one campaigncampaigns_results(Platform) - Delivery funnel of one campaign (events and users per stage)
ai_assistants_analytics(Platform) - LLM assistant analytics: overview, conversations, tools, models, quality, cost, performance, adoption
tasks_list(Platform) - Background tasks and long-running reports with status and timingtask_result(Platform) - Stored result of a finished background tasknotifications_list(Platform) - The connected user's dashboard notifications and unread count
geo_locations_list(Platform, requiresgeoplugin) - Saved geo locations (geofences)revenue_iap_events(Platform, requiresrevenueplugin) - Events configured as in-app purchases
stage_reference(Platform) - Scene and demo company format: looks, themes, steps, delivery modes, layers, paper sizes, accepted piece idsstage_status(Platform) - Whether the server serves Stage's public host, on which name, and why notstage_pieces_list(Platform) - Pieces the server accepts in scene layers, with what each renders and when to use itstage_pieces_get(Platform) - One piece's props (kinds, options, defaults), example start props and data gridstage_templates_list(Platform) - Starters and Library examples to start from: decks, one-pagers, responsive sections, patternsstage_templates_get(Platform) - One template's outline or full scenestage_scenarios_list(Platform) - Recorded product walkthroughs an app page plays, with their chaptersstage_scenarios_get(Platform) - One scenario's chapters and, optionally, its script stepsstage_scenes_list(Platform) - Scenes with canvas size, revision, authors and publishing statestage_scenes_get(Platform) - One scene: outline (look, delivery, steps, layers) or full JSON, versions, public URLs and embed snippetstage_scenes_create(Platform) - Create a scene draft from a template, from JSON, or empty with name, look, theme, delivery and size (A4 / Letter)stage_scenes_update(Platform) - Save a scene draft: replace its JSON or change single fields; concurrent saves are refusedstage_scenes_edit(Platform) - Build or change a scene with operations: layers, steps, scenarios played, delivery, responsive fit and breakpoints; checked before savingstage_scenes_validate(Platform) - Dry-run a scene: would it save and publish, what the server drops, which props pieces ignorestage_scenes_delete(Platform) - Delete a never-published scenestage_scenes_publish(Platform) - Publish the saved scene as a new immutable version; returns URLs and embed snippets per delivery (presentation, player, single page)stage_scenes_set_latest(Platform) - Roll the published scene back or forward to a stored versionstage_scenes_unpublish(Platform) - Hide a published scene (pinned version URLs keep working)stage_scenes_restore(Platform) - Show an unpublished scene againstage_companies_list(Platform) - Demo companies with public / referenced statestage_companies_get(Platform) - One demo company: base project, colours, renames, volume scalestage_companies_create(Platform) - Create a demo company that dresses a mock project for a prospectstage_companies_update(Platform) - Change a demo company (refused once a published version names it)
All tools support flexible app identification via either app_id or app_name parameter.
The package also ships a library entry point for hosts that authenticate callers themselves and want to serve the tools in-process (Countly mounts it at /v2/mcp). It never reads credentials from the environment, headers, query parameters or tool arguments: the host supplies them per request.
import { createMcpHandler, requiredOperations, getToolCatalog } from 'countly-mcp-server/library';
const mcp = createMcpHandler({
countlyUrl: 'http://127.0.0.1:3001', // trusted, used as-is
onToolCall: (report) => recordStats(report), // optional; errors are swallowed
});
// Express route, body already parsed:
app.post('/v2/mcp', async (req, res) => {
await mcp.handle(req, res, req.body, {
upstreamToken, // sent as the countly-token header
grantId, // keys the per-connection app cache
operations: ['R'], // CRUD operations the grant allows
admin: false, // hides adminOnly tools
});
});getToolCatalog() returns each tool's category, CRUD operation, possibleOperations, area, and adminOnly flag. Library mode lists and calls tools through the same pipeline as the standalone modes: the server is detected once per grant, so on Countly Platform tools use the /v2 API and tools the server cannot serve are hidden. Tools outside the grant are not listed; calling one is an unknown-tool error, and a call the grant does not allow comes back as an isError result the assistant can read, without contacting Countly. Per-grant caches are bounded, so a long-running host keeps a fixed amount of memory.
Some tools write depending on their arguments: formulas_run with a mode other than "unsaved" and retention with save_report also need C, alerts_create with an alert_config._id is an update (U), and events_create can overwrite an existing event so it needs C and U. Each call is checked against the operations its own arguments need. requiredOperations(body) returns them for every tools/call in a JSON-RPC body ({ tool, operation, adminOnly }[]), so the host can answer 403 insufficient_scope before handing the request over; toolsCalledIn(body) still returns just the tool names.
The tools act with the upstream token's own rights: which apps a call can reach is decided by Countly, as for any other API request.
Usage analytics in library mode are driven by the host. Pass analytics to report tool usage to the Countly server telemetry app on stats.count.ly, with the same events the standalone modes send (server_started, transport_used, tool_executed, tool_execution_time, tool_category_used, error_occurred):
createMcpHandler({
countlyUrl,
analytics: {
isEnabled: () => hostTrackingIsOn(), // read before every event and every send
deviceId: () => hostDeviceId(), // report under the host's own identity
host: 'countly', // optional label, sent as a segment
},
});The host decides when reporting is allowed and under which device id; nothing is sent without both. Library mode never initializes the global Countly SDK (a host may already use it for its own telemetry) and never loads the standalone modes' analytics module. No URLs, tokens, arguments or error messages are sent, only tool names, categories, outcomes and durations.
The server includes a health check endpoint at /health (HTTP mode only):
curl http://localhost:3000/healthResponse:
{
"status": "healthy",
"timestamp": "2025-10-10T12:00:00.000Z"
}The server provides a .well-known discovery endpoint for automated configuration (HTTP mode only):
curl http://localhost:3000/.well-known/mcp-manifest.jsonThis manifest provides server metadata including:
- Server name, version, and description
- Supported MCP protocol version
- Available endpoints (MCP, health, etc.)
- Supported transports (stdio, HTTP/SSE)
- Server capabilities (tool count, categories, features)
- Authentication methods
- Documentation links
- Repository information
This endpoint can be used by MCP clients for automatic server discovery and capability detection.
When running in HTTP mode, the MCP protocol endpoint is available at:
- Path:
/mcp - Transport: Server-Sent Events (SSE)
- Full URL:
http://localhost:3000/mcp
This endpoint handles all MCP protocol communication using the SSE transport method.
countly-mcp-server/
├── src/
│ └── index.ts # Main server implementation
├── build/ # Compiled JavaScript output
├── docs/ # Additional documentation
├── .env.example # Environment configuration template
├── docker-compose.yml # Docker Compose configuration
├── Dockerfile # Docker image definition
├── DOCKER.md # Detailed Docker deployment guide
└── README.md # This file
npm run devRun automated tests:
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm run test:coverage
# Run tests for CI
npm run test:ciTesting Documentation:
- See docs/TESTING.md for complete testing guide
- See docs/TESTING_SUMMARY.md for testing strategy
Current Coverage:
- Authentication and credential handling
- Tool handlers and parameter validation
- HTTP client configuration
- Transport layer (stdio and HTTP/SSE)
- End-to-end server connectivity
- Error handling
- Never commit tokens to version control
- Use Docker secrets or environment variables for production
- Restrict file permissions on token files (
chmod 600) - Use HTTPS for Countly server connections
- Rotate tokens regularly
- Use read-only mounts for token files in Docker
# Test connectivity
curl https://your-countly-instance.com/o/apps/mine?auth_token=your-token
# Check Docker logs
docker logs countly-mcp-server
# Check container health
docker psVerify your token and ensure it has proper permissions in Countly.
MIT
For issues and questions:
- GitHub Issues: countly/countly-mcp-server
- Countly Community: https://community.count.ly
This project uses GitHub Actions for automated testing and deployment:
- Automated Tests: Run on every pull request and push to main/develop
- Tests across Node.js 18, 20, and 22
- TypeScript compilation verification
- Test coverage reporting
- Build smoke tests
- Docker Publishing: Automated builds on version tags (
v*.*.*)- Multi-architecture support (amd64, arm64)
- Automatic latest tag updates
- Tests must pass before publishing
See .github/AUTOMATED_TESTING.md for details.
Contributions are welcome! Please read our contributing guidelines before submitting PRs.
Development Workflow:
- Fork the repository
- Create a feature branch
- Make your changes and add tests
- Run
npm testlocally - Submit a pull request
- GitHub Actions will automatically run tests
- Address any feedback and ensure tests pass