### Helm Chart Installation Examples
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Installing the Prometheus MCP Server using Helm, with options for basic setup, bearer token authentication, and stateless HTTP for HA deployments.
```bash
# Basic install
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--version 1.1.0 \
--set prometheus.url="http://prometheus:9090"
# With bearer token and stateless HTTP for HA
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--version 1.1.0 \
--set prometheus.url="http://prometheus:9090" \
--set auth.token="my-bearer-token" \
--set mcp.statelessHttp=true \
--set replicaCount=3
```
--------------------------------
### Docker Installation Examples
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Running the Prometheus MCP Server using Docker with different configurations for transport and authentication.
```bash
# stdio transport — used by Claude Desktop / Claude Code
docker run -i --rm \
-e PROMETHEUS_URL="http://prometheus:9090" \
ghcr.io/pab1it0/prometheus-mcp-server:latest
# With basic auth
docker run -i --rm \
-e PROMETHEUS_URL="http://prometheus:9090" \
-e PROMETHEUS_USERNAME="admin" \
-e PROMETHEUS_PASSWORD="secret" \
ghcr.io/pab1it0/prometheus-mcp-server:latest
# HTTP transport — for networked access
docker run -p 8080:8080 \
-e PROMETHEUS_URL="http://prometheus:9090" \
-e PROMETHEUS_MCP_SERVER_TRANSPORT="http" \
ghcr.io/pab1it0/prometheus-mcp-server:latest
```
--------------------------------
### Python Installation and Running from Source
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Steps to install and run the Prometheus MCP Server from source using `uv` for environment management.
```bash
# Install with uv
curl -LsSf https://astral.sh/uv/install.sh | sh
uv venv && source .venv/bin/activate
uv pip install -e .
# Run
PROMETHEUS_URL=http://localhost:9090 prometheus-mcp-server
```
--------------------------------
### Install Prometheus MCP Server from Source
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
Install the Prometheus MCP Server Helm chart by cloning the source repository. Navigate into the cloned directory and use the local chart path for installation. Set the Prometheus URL using the --set flag.
```bash
git clone https://github.com/pab1it0/prometheus-mcp-server.git
cd prometheus-mcp-server
helm install prometheus-mcp-server ./charts/prometheus-mcp-server \
--set prometheus.url=http://prometheus:9090
```
--------------------------------
### Install project dependencies with uv
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Installs the project's main and development dependencies using uv. The -e flag installs the project in editable mode.
```bash
uv pip install -e .
uv pip install -e ".[dev]"
```
--------------------------------
### Install uv
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Installs the uv dependency manager. Ensure you have Python 3.10+ and Git.
```bash
curl -LsSf https://astral.sh/uv/install.sh | sh
```
--------------------------------
### Install Project Dependencies
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Installs the project in editable mode with development dependencies using uv.
```bash
uv pip install -e ".[dev]"
```
--------------------------------
### Prometheus MCP Server Installation with Basic Auth
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
Installs the Prometheus MCP Server with basic authentication enabled. Provide the Prometheus URL, username, and password.
```bash
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--set prometheus.url=https://prometheus.example.com \
--set auth.username=admin \
--set auth.password=secret
```
--------------------------------
### Helm Install with Production Values File
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
Installs the Prometheus MCP Server using a custom values file for production settings. Ensure the values-production.yaml file is correctly configured.
```bash
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
-f values-production.yaml
```
--------------------------------
### Install Prometheus MCP Server from OCI Registry
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
Install the Prometheus MCP Server Helm chart from an OCI registry. Ensure your Prometheus instance is accessible and set the Prometheus URL using the --set flag.
```bash
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--set prometheus.url=http://prometheus:9090
```
--------------------------------
### Example Commit Message
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Follow this format for clear and informative commit messages. Reference issues using 'Fixes #issue_number'.
```text
feat: add support for custom headers in Prometheus requests
- Adds PROMETHEUS_CUSTOM_HEADERS environment variable
- Updates documentation with usage examples
- Includes tests for header validation
Fixes #106
```
--------------------------------
### Prometheus MCP Server Configuration Examples
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Environment variables for configuring the Prometheus MCP Server, including Prometheus URL, security settings, authentication, multi-tenancy, behavior, custom headers, transport, and tool prefix.
```bash
# Minimal — only PROMETHEUS_URL is required
PROMETHEUS_URL=http://prometheus:9090
# TLS / security
PROMETHEUS_URL_SSL_VERIFY=True # set False to skip SSL cert check (insecure)
REQUESTS_CA_BUNDLE=/etc/ssl/ca.crt # custom CA bundle path (requests library standard)
PROMETHEUS_CLIENT_CERT=/certs/client.crt
PROMETHEUS_CLIENT_KEY=/certs/client.key
# Authentication — pick one method
PROMETHEUS_USERNAME=admin
PROMETHEUS_PASSWORD=secret
# — OR —
PROMETHEUS_TOKEN=eyJhbGciOiJSUzI1NiJ9...
# Multi-tenancy (Grafana Mimir / Cortex / Thanos)
ORG_ID=my-org
# Behaviour
PROMETHEUS_DISABLE_LINKS=False # True saves context tokens by omitting UI links
PROMETHEUS_REQUEST_TIMEOUT=30 # seconds; protects against slow Prometheus
# Custom headers injected into every Prometheus request
PROMETHEUS_CUSTOM_HEADERS='{"X-Forwarded-User":"claude","X-Env":"prod"}'
# Transport — stdio | http | sse (stdio is default)
PROMETHEUS_MCP_SERVER_TRANSPORT=stdio
PROMETHEUS_MCP_BIND_HOST=127.0.0.1
PROMETHEUS_MCP_BIND_PORT=8080
PROMETHEUS_MCP_STATELESS_HTTP=False # True for multi-replica HTTP deployments
# Tool name prefix — useful when running two instances in one MCP client
TOOL_PREFIX=staging # results in tool names like staging_execute_query
```
--------------------------------
### Manual Docker Setup for Prometheus MCP Server
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Run the Prometheus MCP server directly using Docker. Supports setting Prometheus URL and authentication credentials via environment variables.
```bash
# With environment variables
docker run -i --rm \
-e PROMETHEUS_URL="http://your-prometheus:9090" \
ghcr.io/pab1it0/prometheus-mcp-server:latest
```
```bash
# With authentication
docker run -i --rm \
-e PROMETHEUS_URL="http://your-prometheus:9090" \
-e PROMETHEUS_USERNAME="admin" \
-e PROMETHEUS_PASSWORD="password" \
ghcr.io/pab1it0/prometheus-mcp-server:latest
```
--------------------------------
### Prometheus MCP Server Installation with Existing Secret
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
Installs the Prometheus MCP Server using an existing Kubernetes secret for authentication. The secret must contain PROMETHEUS_USERNAME and PROMETHEUS_PASSWORD.
```bash
# Create the secret first
kubectl create secret generic prometheus-auth \
--from-literal=PROMETHEUS_USERNAME=admin \
--from-literal=PROMETHEUS_PASSWORD=secret
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--set prometheus.url=https://prometheus.example.com \
--set auth.existingSecret=prometheus-auth
```
--------------------------------
### Install Prometheus MCP Server via Claude Code CLI
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Use the Claude Code CLI to add the Prometheus MCP server. This command sets the PROMETHEUS_URL environment variable and specifies the Docker image to run.
```bash
claude mcp add prometheus --env PROMETHEUS_URL=http://your-prometheus:9090 -- docker run -i --rm -e PROMETHEUS_URL ghcr.io/pab1it0/prometheus-mcp-server:latest
```
--------------------------------
### HTTP Transport Health Check
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Perform a simple HTTP GET request to the `/health` endpoint for load-balancer health checks. This returns a basic JSON status.
```bash
# HTTP transport health check (liveness probe)
curl -s http://localhost:8080/health
# {"status": "ok"}
```
--------------------------------
### Execute PromQL Range Query
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Execute a PromQL range query using `execute_range_query` to retrieve a time-series matrix. This tool supports progress notifications for long-running queries. Both RFC3339 timestamps and Unix timestamps are accepted for `start` and `end` parameters.
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
result = await client.call_tool("execute_range_query", {{
"query": "rate(node_cpu_seconds_total{mode='idle'}[1m])",
"start": "2024-01-15T00:00:00Z",
"end": "2024-01-15T01:00:00Z",
"step": "1m" # resolution: 15s, 1m, 5m, 1h, etc.
}})
print(result.data)
# {{
# "resultType": "matrix",
# "result": [
# {{
# "metric": {{"cpu": "0", "instance": "node:9100", "mode": "idle"}},
# "values": [
# [1705276800, "0.9832"],
# [1705276860, "0.9841"],
# ...
# ]
# }}
# ],
# "links": [
# {{
# "href": "http://prometheus:9090/graph?g0.expr=rate%28...%29&g0.tab=0&...",
# "rel": "prometheus-ui",
# "title": "View in Prometheus UI"
# }}
# ]
# }
# Unix timestamps are equally valid
result_unix = await client.call_tool("execute_range_query", {{
"query": "up",
"start": "1705276800",
"end": "1705280400",
"step": "60s"
}})
asyncio.run(main())
```
--------------------------------
### Check MCP Server Health Status
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Use this Python client method to get the live health status of the MCP server and its Prometheus connection. This is useful for container readiness/liveness probes and system diagnostics.
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
result = await client.call_tool("health_check", {{}})
print(result.data)
# {{
# "status": "healthy", # or "degraded" / "unhealthy"
# "service": "prometheus-mcp-server",
# "version": "1.6.1",
# "timestamp": "2024-01-15T10:30:00.000000",
# "transport": "stdio",
# "configuration": {{
# "prometheus_url_configured": True,
# "authentication_configured": False,
# "org_id_configured": False
# }},
# "prometheus_connectivity": "healthy",
# "prometheus_url": "http://prometheus:9090"
# }}
asyncio.run(main())
```
--------------------------------
### Set Up Environment Variables
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Copies the environment template and prompts to edit it with Prometheus URL and credentials.
```bash
cp .env.template .env
# Edit .env with your Prometheus URL and credentials
```
--------------------------------
### Create and Activate Virtual Environment
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Creates a virtual environment using uv and activates it. Use the appropriate command for your operating system.
```bash
uv venv
source .venv/bin/activate # On Unix/macOS
.venv\Scripts\activate # On Windows
```
--------------------------------
### Configure Structured JSON Logging
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Set up structured JSON logging using `setup_logging` which configures `structlog` to output to stderr. Retrieve the configured logger instance anywhere using `get_logger`.
```python
from prometheus_mcp_server.logging_config import setup_logging, get_logger
# setup_logging() is called once at server startup in main.py
logger = setup_logging()
# Anywhere else, get the same configured logger
logger = get_logger()
logger.info("Query executed", query="up", result_type="vector", result_count=5)
# stderr output (JSON):
# {"level": "info", "timestamp": "2024-01-15T10:30:00.000Z",
# "event": "Query executed", "query": "up",
# "result_type": "vector", "result_count": 5}
logger.error("Prometheus unreachable", url="http://prometheus:9090", error="Connection refused")
# {"level": "error", "timestamp": "...", "event": "Prometheus unreachable",
# "url": "http://prometheus:9090", "error": "Connection refused"}
```
--------------------------------
### Run Prometheus MCP Server with Docker Desktop
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Instructions for adding the Prometheus MCP server to Docker Desktop via the MCP Catalog or MCP Toolkit. Configuration requires setting environment variables for Prometheus connection.
```html
```
--------------------------------
### Claude Desktop Configuration
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Configuration for integrating the Prometheus MCP Server with Claude Desktop via its `mcpServers` setting.
```json
{
"mcpServers": {
"prometheus": {
"command": "docker",
"args": [
"run", "-i", "--rm",
"-e", "PROMETHEUS_URL",
"ghcr.io/pab1it0/prometheus-mcp-server:latest"
],
"env": {
"PROMETHEUS_URL": "http://your-prometheus:9090"
}
}
}
}
```
--------------------------------
### Clone Repository
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Clones your forked repository. Replace YOUR_USERNAME with your GitHub username.
```bash
git clone https://github.com/YOUR_USERNAME/prometheus-mcp-server.git
cd prometheus-mcp-server
```
--------------------------------
### Add Prometheus MCP Server to Claude Desktop
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Configure Claude Desktop to connect to the Prometheus MCP server. Ensure PROMETHEUS_URL is set to your Prometheus instance.
```json
{
"mcpServers": {
"prometheus": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"PROMETHEUS_URL",
"ghcr.io/pab1it0/prometheus-mcp-server:latest"
],
"env": {
"PROMETHEUS_URL": ""
}
}
}
}
```
--------------------------------
### Execute PromQL Instant Query
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Use the `execute_query` tool to run an instant PromQL query against Prometheus. The result type can be `vector`, `scalar`, or `string`. A deep-link URL to the Prometheus UI is included by default.
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
# Current instant query
result = await client.call_tool("execute_query", {{
"query": "rate(http_requests_total{job='api-server'}[5m])"
}})
print(result.data)
# {{
# "resultType": "vector",
# "result": [
# {{
# "metric": {{"__name__": "http_requests_total", "job": "api-server", "instance": "10.0.0.1:8080"}},
# "value": [1700000000.0, "12.5"]
# }}
# ],
# "links": [
# {{
# "href": "http://prometheus:9090/graph?g0.expr=rate%28...%29&g0.tab=0",
# "rel": "prometheus-ui",
# "title": "View in Prometheus UI"
# }}
# ]
# }
# Historical instant query at a specific RFC3339 timestamp
result_at = await client.call_tool("execute_query", {{
"query": "up",
"time": "2024-01-01T00:00:00Z"
}})
print(result_at.data["resultType"]) # "vector"
asyncio.run(main())
```
--------------------------------
### Deploy Prometheus MCP Server with Helm Chart
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Deploy the Prometheus MCP server to Kubernetes using its Helm chart. Configuration can be done via command-line arguments or a custom values file.
```bash
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--version 1.0.0 \
--set prometheus.url="http://prometheus:9090"
```
```bash
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--version 1.0.0 \
--set prometheus.url="http://prometheus:9090" \
--set auth.username="admin" \
--set auth.password="secret"
```
```bash
helm install prometheus-mcp-server \
oci://ghcr.io/pab1it0/charts/prometheus-mcp-server \
--version 1.0.0 \
-f values.yaml
```
--------------------------------
### Running Pytest Commands
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Use these pytest commands to run tests locally. Include coverage reports for better insight into test completeness.
```bash
# Run all tests
pytest
```
```bash
# Run with coverage report
pytest --cov=src --cov-report=term-missing
```
```bash
# Run specific test file
pytest tests/test_specific.py
```
```bash
# Run tests matching a pattern
pytest -k "test_pattern"
```
--------------------------------
### Add Prometheus MCP Server to VS Code/Cursor/Windsurf MCP Settings
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Configure MCP settings in VS Code, Cursor, or Windsurf to integrate with the Prometheus MCP server. PROMETHEUS_URL should be updated with your Prometheus instance URL.
```json
{
"prometheus": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"PROMETHEUS_URL",
"ghcr.io/pab1it0/prometheus-mcp-server:latest"
],
"env": {
"PROMETHEUS_URL": ""
}
}
}
```
--------------------------------
### Prometheus MCP Server Production Configuration with Ingress and TLS
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
A comprehensive configuration for production environments, including Prometheus settings, authentication via existing secret, ingress enablement with TLS, and resource requests/limits.
```yaml
# values-production.yaml
prometheus:
url: "https://prometheus.internal:9090"
disableLinks: "true"
auth:
existingSecret: prometheus-credentials
mcp:
transport: "http"
toolPrefix: "prod"
ingress:
enabled: true
ingressClassName: nginx
annotations:
cert-manager.io/cluster-issuer: letsencrypt
hosts:
- host: mcp.example.com
paths:
- path: /
pathType: Prefix
tls:
- secretName: mcp-tls
hosts:
- mcp.example.com
resources:
requests:
cpu: 100m
memory: 128Mi
limits:
cpu: 200m
memory: 256Mi
serviceMonitor:
enabled: true
labels:
release: prometheus
```
--------------------------------
### Running Tests Locally Before PR
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Ensure all tests pass locally with coverage before submitting a pull request. This helps catch issues early.
```bash
pytest --cov=src --cov-report=term-missing
```
--------------------------------
### Claude Code CLI Integration
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Adding the Prometheus MCP Server as an MCP tool using the Claude Code CLI.
```bash
claude mcp add prometheus \
--env PROMETHEUS_URL=http://your-prometheus:9090 \
-- docker run -i --rm -e PROMETHEUS_URL \
ghcr.io/pab1it0/prometheus-mcp-server:latest
```
--------------------------------
### execute_query
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Executes a PromQL instant query against Prometheus (`/api/v1/query`). Returns a result of type `vector`, `scalar`, or `string`, along with a deep-link URL to the Prometheus UI.
```APIDOC
## Tool: `execute_query`
### Description
Executes a PromQL instant query against Prometheus (`/api/v1/query`). Returns a result of type `vector`, `scalar`, or `string`, along with a deep-link URL to the Prometheus UI (unless `PROMETHEUS_DISABLE_LINKS=True`).
### Parameters
- **query** (string) - Required - The PromQL query to execute.
- **time** (string) - Optional - An RFC3339 timestamp to execute the query at. If not provided, the current time is used.
### Python Client Example
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
# Current instant query
result = await client.call_tool("execute_query", {{
"query": "rate(http_requests_total{job='api-server'}[5m])"
}})
print(result.data)
# Historical instant query at a specific RFC3339 timestamp
result_at = await client.call_tool("execute_query", {{
"query": "up",
"time": "2024-01-01T00:00:00Z"
}})
print(result_at.data["resultType"])
asyncio.run(main())
```
### Response Example (Python Client)
```json
{
"resultType": "vector",
"result": [
{
"metric": {"__name__": "http_requests_total", "job": "api-server", "instance": "10.0.0.1:8080"},
"value": [1700000000.0, "12.5"]
}
],
"links": [
{
"href": "http://prometheus:9090/graph?g0.expr=rate%28...%29&g0.tab=0",
"rel": "prometheus-ui",
"title": "View in Prometheus UI"
}
]
}
```
```
--------------------------------
### Run tests with pytest
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/README.md
Executes the project's test suite using pytest. This command ensures code functionality and helps prevent regressions.
```bash
pytest
```
--------------------------------
### Git Commands for Contribution Workflow
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Execute these git commands to update your fork, create a feature branch, and push your changes before creating a pull request.
```bash
git fetch upstream
git rebase upstream/main
```
```bash
git checkout -b feature/your-feature-name
```
```bash
git push origin feature/your-feature-name
```
--------------------------------
### List Prometheus Metrics with Pagination and Filtering
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Use `list_metrics` to retrieve metric names. Supports pagination with `limit` and `offset`, substring filtering via `filter_pattern`, and cache refreshing with `refresh_cache`.
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
# List all metrics (paginated — first 100)
result = await client.call_tool("list_metrics", {
"limit": 100,
"offset": 0
})
print(result.data)
# {
# "metrics": ["go_goroutines", "http_requests_total", "node_cpu_seconds_total", ...],
# "total_count": 823,
# "returned_count": 100,
# "offset": 0,
# "has_more": True
# }
# Filter by substring (case-insensitive)
http_metrics = await client.call_tool("list_metrics", {
"filter_pattern": "http"
})
print(http_metrics.data["metrics"])
# ["http_requests_total", "http_response_size_bytes", "http_server_duration_seconds"]
# Force cache refresh to pick up newly scraped metrics
fresh = await client.call_tool("list_metrics", {
"refresh_cache": True
})
print(fresh.data["total_count"])
asyncio.run(main())
```
--------------------------------
### Retrieve Metric Metadata (Single and Bulk)
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Use `get_metric_metadata` for single metric lookups or bulk retrieval. Supports filtering by metric name or help text using `filter_pattern` in bulk mode.
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
# Single metric lookup
result = await client.call_tool("get_metric_metadata", {
"metric": "http_requests_total"
})
print(result.data)
# [
# {
# "type": "counter",
# "help": "Total number of HTTP requests made.",
# "unit": ""
# }
# ]
# Bulk mode — all metrics (paginated)
bulk = await client.call_tool("get_metric_metadata", {
"limit": 50,
"offset": 0
})
print(bulk.data)
# {
# "metadata": {
# "http_requests_total": [{"type": "counter", "help": "Total HTTP requests", "unit": ""}],
# "node_cpu_seconds_total": [{"type": "counter", "help": "CPU time by mode", "unit": "seconds"}],
# ...
# },
# "total_count": 823,
# "returned_count": 50,
# "offset": 0,
# "has_more": True
# }
# Search by description keyword (bulk mode with filter)
tls_meta = await client.call_tool("get_metric_metadata", {
"filter_pattern": "certificate"
})
print(list(tls_meta.data["metadata"].keys()))
# ["tls_expiry_seconds"] — matched help text "Seconds until certificate expiry"
asyncio.run(main())
```
--------------------------------
### Accessing Prometheus MCP Server via Port-Forward
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/charts/prometheus-mcp-server/README.md
Forwards traffic from your local machine to the Prometheus MCP Server service. This allows access to the MCP endpoint at http://127.0.0.1:8080/sse.
```bash
kubectl port-forward svc/prometheus-mcp-server 8080:8080
```
--------------------------------
### execute_range_query
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Executes a PromQL range query (`/api/v1/query_range`) returning a time-series matrix. Supports progress notifications.
```APIDOC
## Tool: `execute_range_query`
### Description
Executes a PromQL range query (`/api/v1/query_range`) returning a time-series matrix. Supports progress notifications so MCP clients can display progress indicators during long-running queries.
### Parameters
- **query** (string) - Required - The PromQL query to execute.
- **start** (string) - Required - The start time for the range query (RFC3339 or Unix timestamp).
- **end** (string) - Required - The end time for the range query (RFC3339 or Unix timestamp).
- **step** (string) - Required - The resolution or step for the range query (e.g., `15s`, `1m`, `1h`).
### Python Client Example
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
result = await client.call_tool("execute_range_query", {{
"query": "rate(node_cpu_seconds_total{mode='idle'}[1m])",
"start": "2024-01-15T00:00:00Z",
"end": "2024-01-15T01:00:00Z",
"step": "1m"
}})
print(result.data)
# Unix timestamps are equally valid
result_unix = await client.call_tool("execute_range_query", {{
"query": "up",
"start": "1705276800",
"end": "1705280400",
"step": "60s"
}})
asyncio.run(main())
```
### Response Example (Python Client)
```json
{
"resultType": "matrix",
"result": [
{
"metric": {"cpu": "0", "instance": "node:9100", "mode": "idle"},
"values": [
[1705276800, "0.9832"],
[1705276860, "0.9841"],
...
]
}
],
"links": [
{
"href": "http://prometheus:9090/graph?g0.expr=rate%28...%29&g0.tab=0&...",
"rel": "prometheus-ui",
"title": "View in Prometheus UI"
}
]
}
```
```
--------------------------------
### Execute Prometheus API Call
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Use `make_prometheus_request` for direct Prometheus API calls. Configure server URL, authentication token, organization ID, and request timeout before use. Handles various Prometheus query types and returns the 'data' field of the JSON response.
```python
from unittest.mock import patch, MagicMock
from prometheus_mcp_server.server import make_prometheus_request, config
# Direct usage (e.g., in tests or extensions)
config.url = "http://prometheus:9090"
config.token = "my-bearer-token"
config.org_id = "my-tenant"
config.request_timeout = 15
# Returns the `data` field of the Prometheus JSON response
data = make_prometheus_request("query", params={"query": "up", "time": "1700000000"})
# {"resultType": "vector", "result": [...]}
data = make_prometheus_request("label/__name__/values")
# ["go_goroutines", "http_requests_total", ...]
# Error handling
import requests
try:
make_prometheus_request("query", params={"query": "invalid{{"})
except ValueError as e:
print(f"PromQL error: {e}") # Prometheus API returned error: ...
except requests.Timeout:
print("Request timed out")
except requests.ConnectionError:
print("Cannot reach Prometheus")
```
--------------------------------
### health_check
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Returns the live health status of the MCP server and its Prometheus connection. Useful for container readiness/liveness probes and AI-driven system diagnostics.
```APIDOC
## Tool: `health_check`
### Description
Returns the live health status of the MCP server and its Prometheus connection. Useful for container readiness/liveness probes and AI-driven system diagnostics. The HTTP transport also exposes `GET /health` returning `{"status":"ok"}` for load-balancer health checks.
### Python Client Example
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
result = await client.call_tool("health_check", {{}})
print(result.data)
asyncio.run(main())
```
### Response Example (Python Client)
```json
{
"status": "healthy",
"service": "prometheus-mcp-server",
"version": "1.6.1",
"timestamp": "2024-01-15T10:30:00.000000",
"transport": "stdio",
"configuration": {
"prometheus_url_configured": True,
"authentication_configured": False,
"org_id_configured": False
},
"prometheus_connectivity": "healthy",
"prometheus_url": "http://prometheus:9090"
}
```
### HTTP Transport Health Check
#### Method
GET
#### Endpoint
`/health`
#### Description
Provides a simple health check for load balancers.
#### Response Example (HTTP)
```json
{"status": "ok"}
```
```
--------------------------------
### Pytest Test Structure
Source: https://github.com/pab1it0/prometheus-mcp-server/blob/main/CONTRIBUTING.md
Organize your tests using the Arrange-Act-Assert pattern within functions. Ensure tests are isolated and mock external dependencies.
```python
def test_feature_description():
"""Test that feature does what it should."""
# Arrange - Set up test conditions
# Act - Execute the functionality being tested
# Assert - Verify the results
```
--------------------------------
### Retrieve Prometheus Scrape Target Information
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Use `get_targets` to fetch details of active and dropped Prometheus scrape targets, including labels, health status, and scrape errors. Can be used to summarize target health.
```python
import asyncio
from fastmcp import Client
from prometheus_mcp_server.server import mcp
async def main():
async with Client(mcp) as client:
result = await client.call_tool("get_targets", {})
print(result.data)
# {
# "activeTargets": [
# {
# "discoveredLabels": {
# "__address__": "node-exporter:9100",
# "__metrics_path__": "/metrics",
# "__scheme__": "http",
# "job": "node"
# },
# "labels": {"instance": "node-exporter:9100", "job": "node"},
# "scrapePool": "node",
# "scrapeUrl": "http://node-exporter:9100/metrics",
# "globalUrl": "http://node-exporter:9100/metrics",
# "lastError": "",
# "lastScrape": "2024-01-15T10:29:45.123Z",
# "lastScrapeDuration": 0.0123,
# "health": "up"
# }
# ],
# "droppedTargets": [
# {
# "discoveredLabels": {"__address__": "old-host:9090", "job": "prometheus"},
# "droppedReason": "relabeled to empty target"
# }
# ]
# }
# Summarise target health
active = result.data["activeTargets"]
up = sum(1 for t in active if t["health"] == "up")
down = sum(1 for t in active if t["health"] == "down")
print(f"{up} up, {down} down out of {len(active)} active targets")
asyncio.run(main())
```
--------------------------------
### Manage Prometheus Metrics Cache
Source: https://context7.com/pab1it0/prometheus-mcp-server/llms.txt
Utilize `get_cached_metrics` for a 5-minute TTL in-memory cache of metric names, preventing redundant API calls. Use `clear_metrics_cache` to manually invalidate the cache.
```python
from prometheus_mcp_server.server import (
get_cached_metrics, clear_metrics_cache,
_metrics_cache, _CACHE_TTL
)
print(_CACHE_TTL) # 300 (seconds)
# Fetch with automatic caching — second call is served from memory
metrics_1 = get_cached_metrics() # hits Prometheus API
metrics_2 = get_cached_metrics() # served from cache (no HTTP call)
assert metrics_1 == metrics_2
# Force cache invalidation
clear_metrics_cache()
assert _metrics_cache["data"] is None
assert _metrics_cache["timestamp"] == 0
metrics_3 = get_cached_metrics() # hits Prometheus API again
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.