Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
0c19445
[FEATURE] add Prometheus discovery and query tools
ibakshay Nov 12, 2026
a0e613d
[FEATURE] apply the settings of the Prometheus datasource
ibakshay Nov 13, 2026
88f1079
[IGNORE] explain how to narrow lists over 1 MiB
ibakshay Nov 13, 2026
35bee8f
[IGNORE] look up the metadata of the listed metrics when it is too large
ibakshay Nov 13, 2026
1286d9b
[IGNORE] address the review of the Prometheus tools
ibakshay Nov 13, 2026
1d73586
[IGNORE] keep subsecond steps and escape U__ label names
ibakshay Nov 13, 2026
8acd358
[IGNORE] keep the base URL query and fractional seconds
ibakshay Nov 13, 2026
c348903
[IGNORE] match metadata like Prometheus and drop the search fallback
ibakshay Nov 13, 2026
bcf288f
[IGNORE] show the native histogram syntax in the error
ibakshay Nov 13, 2026
b0776a7
[IGNORE] describe the list time range as approximate
ibakshay Nov 13, 2026
d63f3ee
[IGNORE] escape colons in label names for the Perses proxy
ibakshay Nov 15, 2026
66d09f0
[IGNORE] resolve the project datasources without the global read perm…
ibakshay Nov 17, 2026
6184fdf
[IGNORE] remove the expired datasources from the cache
ibakshay Nov 17, 2026
36387a4
[IGNORE] keep the status of large error pages and valid UTF-8 in errors
ibakshay Nov 17, 2026
ff6ec14
[IGNORE] don't follow redirects to other hosts
ibakshay Nov 17, 2026
1d8f104
[IGNORE] format minAt and maxAt in RFC 3339
ibakshay Nov 17, 2026
5985fef
[IGNORE] list at most 50 metrics with their metadata
ibakshay Nov 17, 2026
e318d4e
[IGNORE] use slices.SortFunc, a list request struct and subtests
ibakshay Nov 17, 2026
6b69dab
[IGNORE] don't follow https to http redirects nor redirects with a Pr…
ibakshay Nov 17, 2026
522afb6
[IGNORE] don't follow redirects to another port
ibakshay Nov 17, 2026
7315245
[IGNORE] never follow redirects
ibakshay Nov 17, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ The `resources` field accepts the following resource names (case-insensitive, co
| `migrate` | Grafana → Perses dashboard migration tool |
| `schema` | Plugin schema tools (requires Perses v0.55+) |
| `validate` | Dashboard and variable validation tools |
| `prometheus` | Prometheus metric discovery and query tools |

#### Environment Variables

Expand Down Expand Up @@ -464,6 +465,24 @@ For ephemeral dashboard configuration, see [Perses EphemeralDashboard](https://g
}
```

### Prometheus

Resource: `prometheus`

These read-only tools discover and query the metrics of Prometheus datasources through the Perses proxy and return
compact JSON: range queries return statistics per series (min, max, avg, last) instead of raw points. `datasource` is
optional: the default Prometheus datasource is used when it is omitted.

| Tool | Description | Required Parameters |
|-----------------------------------------|------------------------------------------------|---------------------|
| `perses_list_prometheus_metric_names` | List metric names | - |
| `perses_list_prometheus_label_names` | List label names | - |
| `perses_list_prometheus_label_values` | List the values of a label | `label` |
| `perses_get_prometheus_metric_metadata` | Get the type, help and unit of metrics | `metrics` |
| `perses_query_prometheus` | Run a PromQL query and get a compact result | `query` |

See [Prometheus tools](./docs/tools.md#prometheus) for details.

### Roles

| Tool | Description | Required Parameters |
Expand Down
1 change: 1 addition & 0 deletions docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ ignored. The MCP server refuses to start if a name is unknown.
| `ephemeraldashboard` | [Ephemeral dashboards](./tools.md#ephemeral-dashboards) |
| `datasource` | [Project datasources](./tools.md#datasources) |
| `globaldatasource` | [Global datasources](./tools.md#datasources) |
| `prometheus` | [Prometheus](./tools.md#prometheus) |
| `variable` | [Project variables](./tools.md#variables) |
| `globalvariable` | [Global variables](./tools.md#variables) |
| `role` | [Project roles](./tools.md#roles-and-role-bindings) |
Expand Down
4 changes: 4 additions & 0 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,10 @@ datasource or a LogQL query on a Loki datasource. The requests go through the

See [Querying datasources](./tools.md#querying-datasources) for more details.

For Prometheus datasources, [dedicated tools](./tools.md#prometheus) list the metric names, labels and label values,
get the metadata of metrics and run PromQL queries. They return compact results, for example statistics per series
instead of raw points for range queries, and use the default Prometheus datasource when none is given.

### Migrate Grafana dashboards

The tool `perses_migrate_dashboard` converts a Grafana dashboard into a Perses dashboard, using the
Expand Down
95 changes: 95 additions & 0 deletions docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,101 @@ Example of a range query on a Prometheus datasource of a project:
}
```

## Prometheus

Resource: `prometheus`

These read-only tools discover and query the metrics of the Prometheus datasources of Perses. They call the
[Prometheus HTTP API](https://prometheus.io/docs/prometheus/latest/querying/api/) through the Perses proxy, like
`perses_query_*_datasource` (credentials injected by Perses, `allowedEndpoints` enforced), but return compact JSON
instead of the raw response: a range query over 6 hours returning 61 series is about 3 KB with
`perses_query_prometheus` (top 20 series, statistics) and 240 KB with `perses_query_global_datasource` (raw points).

| Tool | Description | Required parameters | Optional parameters |
|-----------------------------------------|----------------------------------------------------------|---------------------|-------------------------------------------------------------------------------------------|
| `perses_list_prometheus_metric_names` | List metric names | - | `datasource`, `match`, `search`, `time_range`, `limit`, `include_metadata` |
| `perses_list_prometheus_label_names` | List label names | - | `datasource`, `match`, `time_range`, `limit` |
| `perses_list_prometheus_label_values` | List the values of a label | `label` | `datasource`, `match`, `search`, `time_range`, `limit` |
| `perses_get_prometheus_metric_metadata` | Get the type, help and unit of 1 to 20 metrics | `metrics` | `datasource` |
| `perses_query_prometheus` | Run a PromQL query and get a compact result | `query` | `datasource`, `type`, `time`, `time_range`, `step`, `limit`, `time_zone` |

The parameters are:

- `datasource`: `{name}` for a global datasource, `{name, project}` for a project datasource. It is optional: see
[Default datasource](#default-datasource).
- `match`: a series selector, or a list of series selectors OR-ed together, e.g. `"{job=\"prometheus\"}"`.
- `search`: a case-insensitive substring filter, applied by the MCP server to the list returned by Prometheus. It
doesn't make Prometheus return less: to narrow a large list, use `match`, e.g. `{__name__=~".*memory.*"}`.
- `time_range`: `{past_duration}` (e.g. `"6h"`, `"7d"`), or `{start, end}` in RFC 3339 (`end` defaults to now).
The past hour by default. Prometheus applies it approximately (by storage block): the lists may include series
without samples in it, e.g. series that stopped a few hours ago.
- `limit`: the maximum number of returned items. Defaults: 200 metric names (50 with `include_metadata`, also its max), 200
label names, 100 label values (max 1000), 20 series (max 100).

The list tools return `{datasource, total, returned, truncated, ...}`. A list over 1 MiB is an error that asks to
narrow it with `match` or `time_range`. With `include_metadata: true`, each metric name comes with its type
and help, shortened to 80 characters. The metadata of all the metrics is fetched in one request; when it is over
1 MiB, the metadata of the returned metrics is looked up one by one instead. When it is unavailable, the metrics are
returned without it, with a warning.

`perses_get_prometheus_metric_metadata` looks up each metric under its own name, then under the name of its family
when the family has series with this suffix, as Prometheus matches them: `_total` of counters, `_bucket`, `_count` and
`_sum` of histograms, `_bucket`, `_count`, `_sum`, `_gcount` and `_gsum` of gauge histograms, `_count` and `_sum` of
summaries, `_info` of info metrics (e.g. `http_requests_total` of the counter `http_requests`). A `_created` series
isn't matched, as it holds a timestamp, and neither is `x_total_total` with the family `x_total`.

`perses_query_prometheus` runs an instant query (`type: "instant"`, default) at `time` (default now), or a range query
(`type: "range"`) over `time_range` with `step` (default about 500 points, at least the scrape interval of the
datasource; see [Datasource settings](#datasource-settings)). It returns:

- for an instant query, the value of each series, highest first: `{resultType: "vector", time, seriesCount, returned,
commonLabels, series: [{labels, value}]}`;
- for a range query, never the raw points but the statistics of each series, highest max first: `{resultType:
"matrix", timeRange, step, seriesCount, returned, commonLabels, series: [{labels, min, max, avg, last, minAt, maxAt,
nonFinite}]}`. `min`, `max` and `avg` leave out the NaN and infinite samples, counted in `nonFinite`; `last` is the
last sample. A series that only has NaN or infinite samples is not returned, with a warning. `minAt` and `maxAt` are
in RFC 3339 with the offset of `time_zone` (default UTC).

The labels shared by all returned series are returned once in `commonLabels`. The values keep 4 significant digits,
and all the digits of their integer part, so that timestamps and large counters are not rounded (e.g. `12.35`,
`123457`, `1767355200`); NaN and infinities are returned as strings. Native histograms are not summarized: the tool
returns an error that asks to use `histogram_quantile()`, `histogram_count()` or `histogram_sum()`, without `_bucket`
or `le`, e.g. `histogram_quantile(0.99, sum(rate(x[5m])))`. The `warnings` and `infos` of
Prometheus are passed through. The errors of Prometheus are returned unchanged as tool errors, e.g. `bad_data: invalid
parameter "query": 1:9: parse error: ...`; the other HTTP errors, e.g. of Perses, with their status and message. A
response over 1 MiB is an error that asks to aggregate the query. `time` applies to instant queries only, `time_range`
and `step` to range queries only: the other combinations are errors.

Use `perses_query_*_datasource` for the other endpoints of Prometheus and for the other kinds of datasources.

### Default datasource

The parameter `datasource` of the Prometheus tools is resolved as follows:

- `{name}`: the global datasource `name`; `{name, project}`: the datasource `name` of the project. It must be a
`PrometheusDatasource`.
- `{project}`: the Prometheus datasource of the project marked as default (`spec.default: true`), else the global one.
- omitted: the global Prometheus datasource marked as default.

When no Prometheus datasource is marked as default but there is exactly one that the Perses proxy can query, it is
used. Otherwise the tool returns an error that lists the available Prometheus datasources. The resolved datasources
are cached for 30 seconds.

The tools query the datasources through the Perses proxy: a datasource with a `directUrl`, which only the browser can
reach, is an error, also when it is the default one.

### Datasource settings

Like the Perses UI, the tools apply two settings of the Prometheus datasource, which the Perses proxy doesn't:

- `queryParams` are added to every request, unless the request sets the same parameter, e.g. `dedup` or
`partial_response` for Thanos. A value with a dashboard variable (`$`) can't be resolved: it is sent as is, with a
warning.
- `scrapeInterval` (default `1m`) is the minimum default `step` of range queries. An explicit `step` isn't raised to
the scrape interval, but like the default one it is raised if needed to stay under the Prometheus limit of 11000
points per series. Before, the minimum default step was 15s: range statistics are now computed over fewer points
unless `step` is set.

## Variables

Resources: `globalvariable` for the tools `*_global_variable*`, `variable` for the tools `*_project_variable*`.
Expand Down
7 changes: 4 additions & 3 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,12 @@ require (
github.com/modelcontextprotocol/go-sdk v1.8.0
github.com/perses/common v0.33.0
github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959
github.com/perses/plugins/prometheus v0.59.1
github.com/perses/spec v0.3.0
github.com/prometheus/client_golang v1.25.0
github.com/prometheus/common v0.73.1
github.com/sirupsen/logrus v1.10.2
golang.org/x/sync v0.24.0
)

require (
Expand Down Expand Up @@ -85,9 +89,7 @@ require (
github.com/pandatix/go-abnf v0.5.3 // indirect
github.com/pb33f/ordered-map/v2 v2.3.1 // indirect
github.com/pjbgf/sha1cd v0.6.0 // indirect
github.com/prometheus/client_golang v1.25.0 // indirect
github.com/prometheus/client_model v0.6.3 // indirect
github.com/prometheus/common v0.73.1 // indirect
github.com/prometheus/procfs v0.22.0 // indirect
github.com/rivo/uniseg v0.4.7 // indirect
github.com/segmentio/asm v1.1.3 // indirect
Expand Down Expand Up @@ -119,7 +121,6 @@ require (
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/net v0.61.0 // indirect
golang.org/x/oauth2 v0.37.0 // indirect
golang.org/x/sync v0.24.0 // indirect
golang.org/x/sys v0.49.0 // indirect
golang.org/x/term v0.47.0 // indirect
golang.org/x/text v0.43.0 // indirect
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,8 @@ github.com/perses/common v0.33.0 h1:TXGYw84xn/ZeTUy6P4Gkd0iHSlb4rIO6tzcqD4pfrug=
github.com/perses/common v0.33.0/go.mod h1:WOXuYHSGjcfk50Q8pFdYlEOObIjRbpVVxB+s3Gr6pcg=
github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959 h1:2RcM+M4MOJc2C8Q+lVGEnmUy7qHvSE/i2JbE9ZR8GYc=
github.com/perses/perses v0.55.1-0.20261026072743-c4a2e03ca959/go.mod h1:Hay8084VKDe+UwcmA8y6XXhHy+OKo+JFRWYlE/b3CDM=
github.com/perses/plugins/prometheus v0.59.1 h1:BWTyfkJQK3eUn9LOOAjfmR2r2m0p5Vi/z4WICH6DRrQ=
github.com/perses/plugins/prometheus v0.59.1/go.mod h1:4GOl9brt9mAWIuAUp5L+pQKVCfuIFJGlDraQEOPPyxs=
github.com/perses/spec v0.3.0 h1:pAkpwX32lQpdz1YLmGmmAMItdgtuVDVrkAQfWEqX6ZI=
github.com/perses/spec v0.3.0/go.mod h1:bbTvfdCprae8P4JHknL2VnIkLkTLXqV4stpOlZyxibo=
github.com/pjbgf/sha1cd v0.6.0 h1:3WJ8Wz8gvDz29quX1OcEmkAlUg9diU4GxJHqs0/XiwU=
Expand Down
2 changes: 2 additions & 0 deletions internal/permcp/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import (
"github.com/perses/mcp-server/pkg/tools/migrate"
"github.com/perses/mcp-server/pkg/tools/plugin"
"github.com/perses/mcp-server/pkg/tools/project"
"github.com/perses/mcp-server/pkg/tools/prometheus"
"github.com/perses/mcp-server/pkg/tools/resource"
"github.com/perses/mcp-server/pkg/tools/role"
"github.com/perses/mcp-server/pkg/tools/rolebinding"
Expand Down Expand Up @@ -147,6 +148,7 @@ func (s *server) registerTools() {
schema.New(v1Client),
validate.New(s.persesClient),
migrate.New(s.persesClient),
prometheus.New(v1Client),
}

var allTools []*tools.Tool
Expand Down
10 changes: 9 additions & 1 deletion pkg/tools/internal/proxy/proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,14 @@ import (
apiClient "github.com/perses/perses/pkg/client/api/v1"
)

// NoRedirectClient returns a copy of client that doesn't follow redirects: the datasource APIs don't redirect, and the
// requests carry the Perses credentials, which must not be sent to another URL. A redirect is returned as the response.
func NoRedirectClient(client *http.Client) *http.Client {
noRedirect := *client
noRedirect.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
return &noRedirect
}

// maxBodyBytes caps response body size to prevent overwhelming LLM context windows.
const maxBodyBytes = 1 << 20 // 1 MiB

Expand Down Expand Up @@ -200,7 +208,7 @@ func (h *Helper) Do(ctx context.Context, input ProxyQuery) (*Response, error) {
}

// #nosec G704 -- req URL is built from configured base URL and validated above.
resp, err := restClient.Client.Do(req)
resp, err := NoRedirectClient(restClient.Client).Do(req)
if err != nil {
return nil, err
}
Expand Down
21 changes: 21 additions & 0 deletions pkg/tools/internal/proxy/proxy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,27 @@ func TestResponseText(t *testing.T) {
}
}

func TestDoDoesNotFollowRedirects(t *testing.T) {
httpServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/moved" {
t.Errorf("the redirect to %s is followed", r.URL.Path)
}
http.Redirect(w, r, "/moved", http.StatusFound)
}))
defer httpServer.Close()
client := apiclient.NewWithClient(&perseshttp.RESTClient{
BaseURL: common.MustParseURL(httpServer.URL),
Client: httpServer.Client(),
})
resp, err := New(client.V1()).Do(context.Background(), ProxyQuery{Path: GlobalDatasourceProxyPath("prom", "/api/v1/query")})
if err != nil {
t.Fatalf("Do() unexpected error: %v", err)
}
if resp.StatusCode != http.StatusFound {
t.Errorf("StatusCode = %d, want %d", resp.StatusCode, http.StatusFound)
}
}

func TestDoTruncation(t *testing.T) {
tests := []struct {
name string
Expand Down
Loading
Loading