@@ -3,6 +3,7 @@ package mcpgrafana
33import (
44 "context"
55 "fmt"
6+ "log/slog"
67 "net/http"
78 "net/url"
89 "os"
@@ -47,6 +48,11 @@ var ExtractGrafanaInfoFromEnv server.StdioContextFunc = func(ctx context.Context
4748 if u == "" {
4849 u = defaultGrafanaURL
4950 }
51+ parsedURL , err := url .Parse (u )
52+ if err != nil {
53+ panic (fmt .Errorf ("invalid Grafana URL %s: %w" , u , err ))
54+ }
55+ slog .Info ("Using Grafana configuration" , "url" , parsedURL .Redacted (), "api_key_set" , apiKey != "" )
5056 return WithGrafanaURL (WithGrafanaAPIKey (ctx , apiKey ), u )
5157}
5258
@@ -100,22 +106,31 @@ type grafanaClientKey struct{}
100106var ExtractGrafanaClientFromEnv server.StdioContextFunc = func (ctx context.Context ) context.Context {
101107 cfg := client .DefaultTransportConfig ()
102108 // Extract transport config from env vars, and set it on the context.
103- if u , ok := os .LookupEnv (grafanaURLEnvVar ); ok {
104- url , err := url .Parse (u )
109+ var grafanaURL string
110+ var parsedURL * url.URL
111+ var ok bool
112+ var err error
113+ if grafanaURL , ok = os .LookupEnv (grafanaURLEnvVar ); ok {
114+ parsedURL , err = url .Parse (grafanaURL )
105115 if err != nil {
106116 panic (fmt .Errorf ("invalid %s: %w" , grafanaURLEnvVar , err ))
107117 }
108- cfg .Host = url .Host
118+ cfg .Host = parsedURL .Host
109119 // The Grafana client will always prefer HTTPS even if the URL is HTTP,
110120 // so we need to limit the schemes to HTTP if the URL is HTTP.
111- if url .Scheme == "http" {
121+ if parsedURL .Scheme == "http" {
112122 cfg .Schemes = []string {"http" }
113123 }
124+ } else {
125+ parsedURL , _ = url .Parse (defaultGrafanaURL )
114126 }
115- if apiKey := os .Getenv (grafanaAPIEnvVar ); apiKey != "" {
127+
128+ apiKey := os .Getenv (grafanaAPIEnvVar )
129+ if apiKey != "" {
116130 cfg .APIKey = apiKey
117131 }
118132
133+ slog .Debug ("Creating Grafana client" , "url" , parsedURL .Redacted (), "api_key_set" , apiKey != "" )
119134 client := client .NewHTTPClientWithConfig (strfmt .Default , cfg )
120135 return context .WithValue (ctx , grafanaClientKey {}, client )
121136}
@@ -161,7 +176,15 @@ type incidentClientKey struct{}
161176
162177var ExtractIncidentClientFromEnv server.StdioContextFunc = func (ctx context.Context ) context.Context {
163178 grafanaURL , apiKey := urlAndAPIKeyFromEnv ()
179+ if grafanaURL == "" {
180+ grafanaURL = defaultGrafanaURL
181+ }
164182 incidentURL := fmt .Sprintf ("%s/api/plugins/grafana-incident-app/resources/api/v1/" , grafanaURL )
183+ parsedURL , err := url .Parse (incidentURL )
184+ if err != nil {
185+ panic (fmt .Errorf ("invalid incident URL %s: %w" , incidentURL , err ))
186+ }
187+ slog .Debug ("Creating Incident client" , "url" , parsedURL .Redacted (), "api_key_set" , apiKey != "" )
165188 client := incident .NewClient (incidentURL , apiKey )
166189 return context .WithValue (ctx , incidentClientKey {}, client )
167190}
0 commit comments