Documentation
¶
Index ¶
- Variables
- func ComposeHTTPContextFuncs(funcs ...httpContextFunc) server.HTTPContextFunc
- func ComposeSSEContextFuncs(funcs ...httpContextFunc) server.SSEContextFunc
- func ComposeStdioContextFuncs(funcs ...server.StdioContextFunc) server.StdioContextFunc
- func ComposedHTTPContextFunc(config GrafanaConfig) server.HTTPContextFunc
- func ComposedSSEContextFunc(config GrafanaConfig) server.SSEContextFunc
- func ComposedStdioContextFunc(config GrafanaConfig) server.StdioContextFunc
- func ConvertTool[T any, R any](name, description string, toolHandler ToolHandlerFunc[T, R], ...) (mcp.Tool, server.ToolHandlerFunc, error)
- func GrafanaClientFromContext(ctx context.Context) *client.GrafanaHTTPAPI
- func IncidentClientFromContext(ctx context.Context) *incident.Client
- func MustWithOnBehalfOfAuth(ctx context.Context, accessToken, userToken string) context.Context
- func NewGrafanaClient(ctx context.Context, grafanaURL, apiKey string, auth *url.Userinfo) *client.GrafanaHTTPAPI
- func UserAgent() string
- func WithGrafanaClient(ctx context.Context, client *client.GrafanaHTTPAPI) context.Context
- func WithGrafanaConfig(ctx context.Context, config GrafanaConfig) context.Context
- func WithIncidentClient(ctx context.Context, client *incident.Client) context.Context
- func WithOnBehalfOfAuth(ctx context.Context, accessToken, userToken string) (context.Context, error)
- type GrafanaConfig
- type TLSConfig
- type Tool
- type ToolHandlerFunc
- type UserAgentTransport
Constants ¶
This section is empty.
Variables ¶
var ExtractGrafanaClientFromEnv server.StdioContextFunc = func(ctx context.Context) context.Context { grafanaURL, apiKey := urlAndAPIKeyFromEnv() if grafanaURL == "" { grafanaURL = defaultGrafanaURL } auth := userAndPassFromEnv() grafanaClient := NewGrafanaClient(ctx, grafanaURL, apiKey, auth) return context.WithValue(ctx, grafanaClientKey{}, grafanaClient) }
ExtractGrafanaClientFromEnv is a StdioContextFunc that creates and injects a Grafana client into the context. It uses configuration from GRAFANA_URL, GRAFANA_SERVICE_ACCOUNT_TOKEN (or deprecated GRAFANA_API_KEY), GRAFANA_USERNAME/PASSWORD environment variables to initialize the client with proper authentication.
var ExtractGrafanaClientFromHeaders httpContextFunc = func(ctx context.Context, req *http.Request) context.Context { u, apiKey, basicAuth := extractKeyGrafanaInfoFromReq(req) grafanaClient := NewGrafanaClient(ctx, u, apiKey, basicAuth) return WithGrafanaClient(ctx, grafanaClient) }
ExtractGrafanaClientFromHeaders is a HTTPContextFunc that creates and injects a Grafana client into the context. It prioritizes configuration from HTTP headers (X-Grafana-URL, X-Grafana-API-Key) over environment variables for multi-tenant scenarios.
var ExtractGrafanaInfoFromEnv server.StdioContextFunc = func(ctx context.Context) context.Context { u, apiKey, basicAuth := extractKeyGrafanaInfoFromEnv() parsedURL, err := url.Parse(u) if err != nil { panic(fmt.Errorf("invalid Grafana URL %s: %w", u, err)) } slog.Info("Using Grafana configuration", "url", parsedURL.Redacted(), "api_key_set", apiKey != "", "basic_auth_set", basicAuth != nil) config := GrafanaConfigFromContext(ctx) config.URL = u config.APIKey = apiKey config.BasicAuth = basicAuth return WithGrafanaConfig(ctx, config) }
ExtractGrafanaInfoFromEnv is a StdioContextFunc that extracts Grafana configuration from environment variables. It reads GRAFANA_URL and GRAFANA_SERVICE_ACCOUNT_TOKEN (or deprecated GRAFANA_API_KEY) environment variables and adds the configuration to the context for use by Grafana clients.
var ExtractGrafanaInfoFromHeaders httpContextFunc = func(ctx context.Context, req *http.Request) context.Context { u, apiKey, basicAuth := extractKeyGrafanaInfoFromReq(req) config := GrafanaConfigFromContext(ctx) config.URL = u config.APIKey = apiKey config.BasicAuth = basicAuth return WithGrafanaConfig(ctx, config) }
ExtractGrafanaInfoFromHeaders is a HTTPContextFunc that extracts Grafana configuration from HTTP request headers. It reads X-Grafana-URL and X-Grafana-API-Key headers, falling back to environment variables if headers are not present.
var ExtractIncidentClientFromEnv server.StdioContextFunc = func(ctx context.Context) context.Context { grafanaURL, apiKey := urlAndAPIKeyFromEnv() if grafanaURL == "" { grafanaURL = defaultGrafanaURL } incidentURL := fmt.Sprintf("%s/api/plugins/grafana-irm-app/resources/api/v1/", grafanaURL) parsedURL, err := url.Parse(incidentURL) if err != nil { panic(fmt.Errorf("invalid incident URL %s: %w", incidentURL, err)) } slog.Debug("Creating Incident client", "url", parsedURL.Redacted(), "api_key_set", apiKey != "") client := incident.NewClient(incidentURL, apiKey) if tlsConfig := GrafanaConfigFromContext(ctx).TLSConfig; tlsConfig != nil { transport, err := tlsConfig.HTTPTransport(http.DefaultTransport.(*http.Transport)) if err != nil { slog.Error("Failed to create custom transport for incident client, using default", "error", err) } else { client.HTTPClient.Transport = wrapWithUserAgent(transport) slog.Debug("Using custom TLS configuration and user agent for incident client", "cert_file", tlsConfig.CertFile, "ca_file", tlsConfig.CAFile, "skip_verify", tlsConfig.SkipVerify) } } else { client.HTTPClient.Transport = wrapWithUserAgent(http.DefaultTransport) } return context.WithValue(ctx, incidentClientKey{}, client) }
ExtractIncidentClientFromEnv is a StdioContextFunc that creates and injects a Grafana Incident client into the context. It configures the client using environment variables and applies any custom TLS settings from the context.
var ExtractIncidentClientFromHeaders httpContextFunc = func(ctx context.Context, req *http.Request) context.Context { grafanaURL, apiKey, _ := extractKeyGrafanaInfoFromReq(req) incidentURL := fmt.Sprintf("%s/api/plugins/grafana-irm-app/resources/api/v1/", grafanaURL) client := incident.NewClient(incidentURL, apiKey) if tlsConfig := GrafanaConfigFromContext(ctx).TLSConfig; tlsConfig != nil { transport, err := tlsConfig.HTTPTransport(http.DefaultTransport.(*http.Transport)) if err != nil { slog.Error("Failed to create custom transport for incident client, using default", "error", err) } else { client.HTTPClient.Transport = wrapWithUserAgent(transport) slog.Debug("Using custom TLS configuration and user agent for incident client", "cert_file", tlsConfig.CertFile, "ca_file", tlsConfig.CAFile, "skip_verify", tlsConfig.SkipVerify) } } else { client.HTTPClient.Transport = wrapWithUserAgent(http.DefaultTransport) } return context.WithValue(ctx, incidentClientKey{}, client) }
ExtractIncidentClientFromHeaders is a HTTPContextFunc that creates and injects a Grafana Incident client into the context. It uses HTTP headers for configuration with environment variable fallbacks, enabling per-request incident management configuration.
var Version = sync.OnceValue(func() string { v := "(devel)" if bi, ok := debug.ReadBuildInfo(); ok && bi.Main.Version != "" { v = bi.Main.Version } return v })
Version returns the version of the mcp-grafana binary. It uses runtime/debug to fetch version information from the build, returning "(devel)" for local development builds. The version is computed once and cached for performance.
Functions ¶
func ComposeHTTPContextFuncs ¶ added in v0.4.0
func ComposeHTTPContextFuncs(funcs ...httpContextFunc) server.HTTPContextFunc
ComposeHTTPContextFuncs composes multiple HTTPContextFuncs into a single one. This enables chaining of context modifications for HTTP transport, allowing modular setup of authentication, clients, and configuration.
func ComposeSSEContextFuncs ¶
func ComposeSSEContextFuncs(funcs ...httpContextFunc) server.SSEContextFunc
ComposeSSEContextFuncs composes multiple SSEContextFuncs into a single one. This enables chaining of context modifications for Server-Sent Events transport, such as extracting headers and setting up clients.
func ComposeStdioContextFuncs ¶
func ComposeStdioContextFuncs(funcs ...server.StdioContextFunc) server.StdioContextFunc
ComposeStdioContextFuncs composes multiple StdioContextFuncs into a single one. Functions are applied in order, allowing each to modify the context before passing it to the next.
func ComposedHTTPContextFunc ¶ added in v0.4.0
func ComposedHTTPContextFunc(config GrafanaConfig) server.HTTPContextFunc
ComposedHTTPContextFunc returns a HTTPContextFunc that comprises all predefined HTTPContextFuncs. It provides the complete context setup for HTTP transport, including header-based authentication and client configuration.
func ComposedSSEContextFunc ¶
func ComposedSSEContextFunc(config GrafanaConfig) server.SSEContextFunc
ComposedSSEContextFunc returns a SSEContextFunc that comprises all predefined SSEContextFuncs. It sets up the complete context for SSE transport, extracting configuration from HTTP headers with environment variable fallbacks.
func ComposedStdioContextFunc ¶
func ComposedStdioContextFunc(config GrafanaConfig) server.StdioContextFunc
ComposedStdioContextFunc returns a StdioContextFunc that comprises all predefined StdioContextFuncs. It sets up the complete context for stdio transport including Grafana configuration, client initialization from environment variables, and incident management support.
func ConvertTool ¶
func ConvertTool[T any, R any](name, description string, toolHandler ToolHandlerFunc[T, R], options ...mcp.ToolOption) (mcp.Tool, server.ToolHandlerFunc, error)
ConvertTool converts a toolHandler function to an MCP Tool and ToolHandlerFunc. The toolHandler must accept a context.Context and a struct with jsonschema tags for parameter documentation. The struct fields define the tool's input schema, while the return value can be a string, struct, or *mcp.CallToolResult. This function automatically generates JSON schema from the struct type and wraps the handler with OpenTelemetry instrumentation.
func GrafanaClientFromContext ¶
func GrafanaClientFromContext(ctx context.Context) *client.GrafanaHTTPAPI
GrafanaClientFromContext retrieves the Grafana client from the context. Returns nil if no client has been set, which tools should handle gracefully with appropriate error messages.
func IncidentClientFromContext ¶
IncidentClientFromContext retrieves the Grafana Incident client from the context. Returns nil if no client has been set, indicating that incident management features are not available.
func MustWithOnBehalfOfAuth ¶ added in v0.3.0
MustWithOnBehalfOfAuth adds the access and user tokens to the context, panicking if either are empty. This is a convenience wrapper around WithOnBehalfOfAuth for cases where token validation has already occurred.
func NewGrafanaClient ¶ added in v0.4.0
func NewGrafanaClient(ctx context.Context, grafanaURL, apiKey string, auth *url.Userinfo) *client.GrafanaHTTPAPI
NewGrafanaClient creates a Grafana client with the provided URL and API key. The client is automatically configured with the correct HTTP scheme, debug settings from context, custom TLS configuration if present, and OpenTelemetry instrumentation for distributed tracing.
func UserAgent ¶ added in v0.6.3
func UserAgent() string
UserAgent returns the user agent string for HTTP requests. It includes the mcp-grafana identifier and version number for proper request attribution and debugging.
func WithGrafanaClient ¶
WithGrafanaClient sets the Grafana client in the context. The client can be retrieved using GrafanaClientFromContext and will be used by all Grafana-related tools in the MCP server.
func WithGrafanaConfig ¶ added in v0.5.0
func WithGrafanaConfig(ctx context.Context, config GrafanaConfig) context.Context
WithGrafanaConfig adds Grafana configuration to the context. This configuration includes API credentials, debug settings, and TLS options that will be used by all Grafana clients created from this context.
func WithIncidentClient ¶
WithIncidentClient sets the Grafana Incident client in the context. This client is used for managing incidents, activities, and other IRM (Incident Response Management) operations.
func WithOnBehalfOfAuth ¶ added in v0.3.0
func WithOnBehalfOfAuth(ctx context.Context, accessToken, userToken string) (context.Context, error)
WithOnBehalfOfAuth adds the Grafana access token and user token to the Grafana config. These tokens enable on-behalf-of authentication in Grafana Cloud, allowing the MCP server to act on behalf of a specific user with their permissions.
Types ¶
type GrafanaConfig ¶ added in v0.5.0
type GrafanaConfig struct { // Debug enables debug mode for the Grafana client. Debug bool // IncludeArgumentsInSpans enables logging of tool arguments in OpenTelemetry spans. // This should only be enabled in non-production environments or when you're certain // the arguments don't contain PII. Defaults to false for safety. // Note: OpenTelemetry spans are always created for context propagation, but arguments // are only included when this flag is enabled. IncludeArgumentsInSpans bool // URL is the URL of the Grafana instance. URL string // APIKey is the API key or service account token for the Grafana instance. // It may be empty if we are using on-behalf-of auth. APIKey string // Credentials if user is using basic auth BasicAuth *url.Userinfo // AccessToken is the Grafana Cloud access policy token used for on-behalf-of auth in Grafana Cloud. AccessToken string // IDToken is an ID token identifying the user for the current request. // It comes from the `X-Grafana-Id` header sent from Grafana to plugin backends. // It is used for on-behalf-of auth in Grafana Cloud. IDToken string // TLSConfig holds TLS configuration for all Grafana clients. TLSConfig *TLSConfig }
GrafanaConfig represents the full configuration for Grafana clients. It includes connection details, authentication credentials, debug settings, and TLS options used throughout the MCP server's lifecycle.
func GrafanaConfigFromContext ¶ added in v0.5.0
func GrafanaConfigFromContext(ctx context.Context) GrafanaConfig
GrafanaConfigFromContext extracts Grafana configuration from the context. If no config is found, returns a zero-value GrafanaConfig. This function is typically used by internal components to access configuration set earlier in the request lifecycle.
type TLSConfig ¶ added in v0.6.0
TLSConfig holds TLS configuration for Grafana clients. It supports mutual TLS authentication with client certificates, custom CA certificates for server verification, and development options like skipping certificate verification.
func (*TLSConfig) CreateTLSConfig ¶ added in v0.6.0
CreateTLSConfig creates a *tls.Config from TLSConfig. It supports client certificates, custom CA certificates, and the option to skip TLS verification for development environments.
func (*TLSConfig) HTTPTransport ¶ added in v0.6.0
HTTPTransport creates an HTTP transport with custom TLS configuration. It clones the provided transport and applies the TLS settings, preserving other transport configurations like timeouts and connection pools.
type Tool ¶
type Tool struct { Tool mcp.Tool Handler server.ToolHandlerFunc }
Tool represents a tool definition and its handler function for the MCP server. It encapsulates both the tool metadata (name, description, schema) and the function that executes when the tool is called. The simplest way to create a Tool is to use MustTool for compile-time tool creation, or ConvertTool if you need runtime tool creation with proper error handling.
func MustTool ¶
func MustTool[T any, R any]( name, description string, toolHandler ToolHandlerFunc[T, R], options ...mcp.ToolOption, ) Tool
MustTool creates a new Tool from the given name, description, and toolHandler. It panics if the tool cannot be created, making it suitable for compile-time tool definitions where creation errors indicate programming mistakes.
type ToolHandlerFunc ¶
ToolHandlerFunc is the type of a handler function for a tool. T is the request parameter type (must be a struct with jsonschema tags), and R is the response type which can be a string, struct, or *mcp.CallToolResult.
type UserAgentTransport ¶ added in v0.6.3
type UserAgentTransport struct { UserAgent string // contains filtered or unexported fields }
UserAgentTransport wraps an http.RoundTripper to add a custom User-Agent header. This ensures all HTTP requests from the MCP server are properly identified with version information for debugging and analytics.
func NewUserAgentTransport ¶ added in v0.6.3
func NewUserAgentTransport(rt http.RoundTripper, userAgent ...string) *UserAgentTransport
NewUserAgentTransport creates a new UserAgentTransport with the specified user agent. If no user agent is provided, it uses the default UserAgent() with version information. The transport wraps the provided RoundTripper, defaulting to http.DefaultTransport if nil.