Cloud Native 12 min read

How to Connect Large Language Models to Grafana Using MCP (Model Context Protocol)

This guide demonstrates building a Model Context Protocol (MCP) server in Python to enable large language models to query Grafana dashboards, retrieve folder lists, and return real‑time visualizations, covering installation, server definition, tool creation, and integration with Cherry Studio.

Alibaba Cloud Native
Alibaba Cloud Native
Alibaba Cloud Native
How to Connect Large Language Models to Grafana Using MCP (Model Context Protocol)

With the rapid rise of large language models (LLMs), developers seek ways for models to fetch precise data from services like Grafana. The Model Context Protocol (MCP) provides an open, standardized interface that lets LLMs request system data such as dashboard lists or weather cards.

What Is MCP?

Standardization : Defines a unified communication protocol, eliminating the need for custom integration code for each service.

Security : Includes encryption, authentication, and permission controls to protect data.

Flexibility : Supports databases, files, APIs, and Git repositories.

Cross‑platform : Works with any language (Python, TypeScript, Go, etc.).

How MCP Works

MCP follows a client‑server model. The client (embedded in an AI application such as Cherry Studio) sends requests to the MCP server, which connects to specific data sources (e.g., Grafana) and returns results. The LLM then formats the response for the user.

Developing an MCP Server for Grafana

Project Initialization

Install uv: curl -LsSf https://astral.sh/uv/install.sh | sh Create a project folder and install dependencies:

uv init grafana-mcp-example
cd grafana-mcp-example
uv add "mcp[cli]" requests

Create server.py.

Define the FastMCP Server

from mcp.server.fastmcp import FastMCP
MCP_SERVER_NAME = "grafana-mcp-server"
mcp = FastMCP(MCP_SERVER_NAME)
if __name{} == "__main__":
    mcp.run(transport='stdio')

Add Tools using the @mcp.tool() decorator:

@mcp.tool()
def listFolder() -> list[Any] | str:
    """List all Grafana folder names"""
    return GrafanaClient().listFolder()

@mcp.tool()
def listDashboard(folderName: str) -> list[Any] | str:
    """List all dashboards in a folder"""
    return GrafanaClient().listDashboard(folderName)

Implement a Simple Grafana Client

import os, requests
class GrafanaClient:
    grafanaURL = os.getenv("GRAFANA_URL")
    grafanaApiKey = os.getenv("GRAFANA_API_KEY")
    def grafanaHeader(self):
        return {"Authorization": f"Bearer {self.grafanaApiKey}", "Content-Type": "application/json"}
    def listFolder(self):
        resp = requests.get(f"{self.grafanaURL}/api/search?type=dash-folder", headers=self.grafanaHeader())
        return [{"uid": i["uid"], "name": i["title"]} for i in resp.json()] if resp.status_code == 200 else []
    def listDashboard(self, folderName):
        # Get folder UID then dashboards
        resp = requests.get(f"{self.grafanaURL}/api/search?type=dash-folder&query={folderName}", headers=self.grafanaHeader())
        if resp.status_code != 200:
            return []
        folderUid = resp.json()[0]["uid"]
        resp = requests.get(f"{self.grafanaURL}/api/search?type=dash-db&folderUIDs={folderUid}", headers=self.grafanaHeader())
        return [{"uid": i["uid"], "name": i["title"]} for i in resp.json()] if resp.status_code == 200 else []

Integrating with Cherry Studio

Configure Cherry Studio to use the Alibaba Cloud Bailei LLM (e.g., qwen‑plus) and point the MCP server to the grafana-mcp-server you created. Set environment variables GRAFANA_URL and GRAFANA_API_KEY (or Service Account Token for Grafana 10+).

Running the Server

uv run --directory /Users/youruser/grafana-mcp-example run server.py

After the server starts, ask the model questions like “Grafana folder list” or “Dashboards in folder X”. The model will invoke the MCP tools, retrieve data from Grafana, and display accurate results.

Conclusion

The example shows how MCP can turn an LLM into a smart interface for existing services, dramatically reducing integration effort. While the demo focuses on Grafana, the same pattern applies to any API, database, or file system, making MCP a versatile “USB‑C” for AI applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonLLMMCPresourceGrafanatoolfastmcpPrompt
Alibaba Cloud Native
Written by

Alibaba Cloud Native

We publish cloud-native tech news, curate in-depth content, host regular events and live streams, and share Alibaba product and user case studies. Join us to explore and share the cloud-native insights you need.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.