Skip to content

Commit 34092d4

Browse files
committed
return empty datasource model instead of an error if datasource name doesn't match
1 parent d0d8d94 commit 34092d4

File tree

2 files changed

+17
-2
lines changed

2 files changed

+17
-2
lines changed

tools/datasources.go

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package tools
22

33
import (
44
"context"
5+
"errors"
56
"fmt"
67
"strings"
78

@@ -12,6 +13,8 @@ import (
1213
mcpgrafana "github.com/grafana/mcp-grafana"
1314
)
1415

16+
var ErrDatasourceNotFound = errors.New("datasource not found")
17+
1518
type ListDatasourcesParams struct {
1619
Type string `json:"type,omitempty" jsonschema:"description=The type of datasources to search for. For example\\, 'prometheus'\\, 'loki'\\, 'tempo'\\, etc..."`
1720
}
@@ -81,9 +84,8 @@ func getDatasourceByUID(ctx context.Context, args GetDatasourceByUIDParams) (*mo
8184
c := mcpgrafana.GrafanaClientFromContext(ctx)
8285
datasource, err := c.Datasources.GetDataSourceByUID(args.UID)
8386
if err != nil {
84-
// Check if it's a 404 Not Found Error
8587
if strings.Contains(err.Error(), "404") {
86-
return nil, fmt.Errorf("datasource with UID '%s' not found. Please check if the datasource exists and is accessible", args.UID)
88+
return &models.DataSource{}, fmt.Errorf("%w: datasource UID '%s' does not exist or you don't have access. Use list_datasources to see available datasources", ErrDatasourceNotFound, args.UID)
8789
}
8890
return nil, fmt.Errorf("get datasource by uid %s: %w", args.UID, err)
8991
}
@@ -107,6 +109,9 @@ func getDatasourceByName(ctx context.Context, args GetDatasourceByNameParams) (*
107109
c := mcpgrafana.GrafanaClientFromContext(ctx)
108110
datasource, err := c.Datasources.GetDataSourceByName(args.Name)
109111
if err != nil {
112+
if strings.Contains(err.Error(), "404") {
113+
return &models.DataSource{}, fmt.Errorf("%w: datasource with name '%s' not found; check if the datasource exists in Grafana and you have permission to access it", ErrDatasourceNotFound, args.Name)
114+
}
110115
return nil, fmt.Errorf("get datasource by name %s: %w", args.Name, err)
111116
}
112117
return datasource.Payload, nil

tools/datasources_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,14 @@ func TestDatasourcesTools(t *testing.T) {
9292
require.NoError(t, err)
9393
assert.Equal(t, "Prometheus", result.Name)
9494
})
95+
96+
t.Run("get datasource by name - not found", func(t *testing.T) {
97+
ctx := newTestContext()
98+
result, err := getDatasourceByName(ctx, GetDatasourceByNameParams{
99+
Name: "non-existent-datasource",
100+
})
101+
require.NoError(t, err)
102+
assert.NotNil(t, result)
103+
assert.Equal(t, "", result.Name)
104+
})
95105
}

0 commit comments

Comments
 (0)