Skip to main content
Glama
ninanung
by ninanung

grafana-mcp

npm version license node

Grafana API의 일부를 MCP(Model Context Protocol) 서버로 노출하여 자연어 로그 쿼리에 집중합니다. 주요 목표는 LogQL, 레이블, 데이터 소스 UID를 직접 다룰 필요 없이 "지난 30분 동안 api 서비스에서 발생한 에러 로그를 보여줘"라고 말하고 실제 로그 라인을 받아보는 것입니다.

로그 데이터 소스, Loki 레이블, 서비스 이름과 호스팅 데이터 소스/레이블 간의 매핑은 디스크에 캐시되므로 반복 호출 시 불필요한 레이블 스캔을 건너뜁니다.

한국어 문서 / Korean README

설치 및 설정

npx (설치 불필요)

~/.mcp.json에 다음을 추가하세요.

{
  "mcpServers": {
    "grafana": {
      "command": "npx",
      "args": ["@seungje.jun/grafana-mcp"],
      "env": {
        "GRAFANA_URL": "https://grafana.example.com",
        "GRAFANA_SERVICE_ACCOUNT_TOKEN": "glsa_xxx"
      }
    }
  }
}

소스에서 빌드

git clone https://github.com/ninanung/grafana-mcp.git
cd grafana-mcp
npm install
npm run build
{
  "mcpServers": {
    "grafana": {
      "command": "node",
      "args": ["/path/to/grafana-mcp/dist/cli.js"],
      "env": {
        "GRAFANA_URL": "https://grafana.example.com",
        "GRAFANA_SERVICE_ACCOUNT_TOKEN": "glsa_xxx"
      }
    }
  }
}

Claude Code를 재시작하여 MCP 도구를 활성화하세요.

인증

다음 중 하나가 필요합니다. 아래 순서대로 확인하며, 가장 먼저 발견된 것이 적용됩니다.

변수

사용 시기

GRAFANA_SERVICE_ACCOUNT_TOKEN

Grafana 9.1+ (권장)

GRAFANA_CLOUD_ACCESS_POLICY_TOKEN

Grafana Cloud

GRAFANA_API_KEY

레거시 API 키 (10.x에서 지원 중단)

GRAFANA_USERNAME + GRAFANA_PASSWORD

기본 인증(Basic Auth) 대체

모든 Bearer 스타일 토큰은 Authorization: Bearer <token>으로 전송됩니다. 서버는 토큰의 종류를 구분하지 않으며, 설정된 토큰을 사용합니다.

환경 변수

변수

설명

GRAFANA_URL

Grafana 서버 URL (단일 인스턴스 모드, GRAFANA_INSTANCES가 설정되지 않은 경우 필수)

GRAFANA_INSTANCES

(선택 사항) 다중 인스턴스 모드를 위한 JSON 배열. 예: [{"name":"prod","url":"...","service_account_token":"..."},{"name":"dev","url":"...","api_key":"..."}]. 설정 시 도구 호출 시 instance: "prod"를 전달하여 대상을 선택하세요. 생략 시 첫 번째 항목이 기본값으로 사용됩니다.

GRAFANA_ORG_ID

(선택 사항) X-Grafana-Org-Id 헤더로 전송됩니다. 다중 조직 설정용입니다.

GRAFANA_TLS_SKIP_VERIFY

(선택 사항) true / 1 설정 시 TLS 검증을 건너뜁니다 (자체 서명된 Grafana용).

GRAFANA_MCP_LOG

(선택 사항) 로그 레벨: debug, info (기본값), warn, error, silent. MCP stdio 채널 오염을 방지하기 위해 로그는 stderr로 출력됩니다.

GRAFANA_MCP_AUDIT_LOG

(선택 사항) 감사 로그 파일 경로. 기본값은 ~/.grafana-mcp/audit.log입니다. off로 설정하여 비활성화할 수 있습니다. 각 라인은 도구 이름, 인수, 소요 시간, 상태를 포함하는 JSON 레코드입니다.

GRAFANA_MCP_CACHE

(선택 사항) off로 설정하여 디스크 로그 캐시를 비활성화합니다.

GRAFANA_MCP_CACHE_PATH

(선택 사항) 로그 캐시 파일 경로. 기본값은 ~/.grafana-mcp/log-cache.json입니다.

GRAFANA_MCP_CACHE_TTL_DATASOURCES_MS

(선택 사항) 로그 데이터 소스 목록 캐시의 TTL. 기본값 86400000 (24시간).

GRAFANA_MCP_CACHE_TTL_LABELS_MS

(선택 사항) Loki 레이블 키 캐시의 TTL. 기본값 86400000 (24시간).

GRAFANA_MCP_CACHE_TTL_LABEL_VALUES_MS

(선택 사항) Loki 레이블 값 캐시의 TTL. 기본값 3600000 (1시간).

GRAFANA_MCP_CACHE_TTL_SERVICE_MS

(선택 사항) {service → (ds_uid, label)} 해석 캐시의 TTL. 기본값 3600000 (1시간).

Related MCP server: Log Analyzer MCP Server

도구

도구

설명

self_test

진단 검사 — 연결성, 버전, 인증 및 기능 프로브(list_datasources, proxy_uid, ds_query)와 필요한 인수에 대한 안내 제공

list_datasources

구성된 모든 데이터 소스 나열

search_dashboards

쿼리/태그/유형별로 대시보드 검색

get_dashboard

uid를 사용하여 대시보드의 전체 JSON 가져오기

extract_dashboard_queries

대시보드 URL에서 datasource_uid와 함께 패널 쿼리(LogQL/PromQL) 추출. 대시보드 URL에서 query_logs.raw_logql 인수를 찾는 데 사용

list_log_datasources

로그 유형 데이터 소스(Loki, Elasticsearch, CloudWatch, OpenSearch, Splunk)만 나열. 캐시됨

list_services

Loki 레이블에서 검색 가능한 서비스 이름 나열 — query_logs 호출 전 유용

query_logs

서비스/시간 범위/레벨에 대한 로그 쿼리. 로그 데이터 소스와 서비스 레이블을 자동 감지. 다중 레이블/고급 선택기를 위한 raw_logql 지원. uid-proxy를 사용할 수 없는 경우(Grafana <9.0) /api/ds/query로 대체. 출력 모드: raw / summarize / json

get_log_cache

현재 캐시된 항목(로그 데이터 소스, 레이블, 해석된 서비스) 검사

refresh_log_cache

특정 서비스의 해석을 무효화하거나 Grafana 인스턴스의 모든 항목 삭제

export_log_cache

로그 캐시를 JSON 파일로 내보내기

import_log_cache

JSON 파일에서 로그 캐시 가져오기 (병합/교체)

사용 예시

MCP 클라이언트에 의해 조정되는 일반적인 자연어 흐름:

  1. 사용자: "지난 30분 동안 api 서비스에서 발생한 에러 로그를 보여줘."

  2. service: "api", level: "error", time_from: "now-30m"과 함께 query_logs 호출 → 서버가 service="api" 레이블을 소유한 Loki 데이터 소스를 자동 감지하고 LogQL을 실행합니다.

  3. (첫 호출 시) 서비스 → 데이터 소스/레이블 매핑이 캐시에 저장되며, 이후 호출은 감지 단계를 건너뜁니다.

  4. 사용자: "그 에러들을 패턴별로 요약해줘." → output: "summarize"와 함께 동일한 호출을 수행하면 패턴별로 그룹화된 카운트가 반환됩니다.

  5. 사용자: "다른 서비스는 뭐가 있지?" → list_services가 전체 서비스 목록을 반환합니다.

서비스 이름에 오타가 있는 경우, query_logs는 유사한 일치 항목을 제안합니다 (예: Did you mean: checkout, checkout-api?).

자동 감지 작동 방식

query_logs는 대상 데이터 소스와 레이블을 스스로 선택합니다:

  1. 모든 데이터 소스를 로그 유형(Loki/ES/CloudWatch/OpenSearch/Splunk)으로 필터링합니다.

  2. 각 Loki 데이터 소스에 대해 /loki/api/v1/labels를 가져와 일반적인 서비스 레이블 후보(service, service_name, app, app_name, application, container, job)를 먼저 확인한 다음 나머지 레이블을 확인합니다.

  3. 각 후보 레이블에 대해 값을 가져와 요청된 service 이름이 해당 목록에 있는지 확인합니다.

  4. 정확히 하나의 (datasource, label) 쌍이 일치하면 이를 사용합니다. 여러 개가 일치하면 datasource_uid를 요구하여 명확히 합니다. 일치하는 항목이 없으면 유사한 이름 제안을 반환합니다.

  5. 해석된 (service → ds_uid, label)은 캐시됩니다. refresh: true 또는 refresh_log_cache를 사용하면 재감지를 강제할 수 있습니다.

자동 감지는 현재 Loki만 지원합니다. Elasticsearch / CloudWatch / Splunk 데이터 소스의 경우 datasource_uidservice_label을 명시적으로 전달하세요 (LogQL 전용 필터는 적용되지 않을 수 있습니다).

출력 모드

query_logsoutput 인수를 허용합니다:

  • raw (기본값): <ISO timestamp> <log line> — 터미널에서 직접 읽기에 적합합니다.

  • summarize: 라인을 정규화된 패턴(숫자 → N, UUID → UUID)별로 그룹화하여 카운트와 패턴별 샘플을 제공합니다. 로그가 너무 많거나 노이즈가 심할 때 사용하세요.

  • json: 구조화된 객체 { ts, line, labels } — 다운스트림 도구용입니다.

캐시

  • 로그 캐시: ~/.grafana-mcp/log-cache.json에 저장됩니다. Grafana 기본 URL별로 키가 지정되어 여러 인스턴스가 충돌하지 않습니다.

  • 각 카테고리별로 고유한 TTL(데이터 소스 / 레이블 / 레이블 값 / 서비스 해석)이 있습니다. 위의 환경 변수 표를 참조하세요.

  • 나중에 실패하는 캐시된 서비스 해석(예: 레이블 이름 변경)은 자동으로 무효화되어 다음 호출 시 재감지됩니다.

  • get_log_cache로 검사하고, refresh_log_cache로 삭제하며, export_log_cache / import_log_cache로 팀원과 공유할 수 있습니다.

캐시 위치 및 초기화

캐시

위치

초기화

로그 캐시

~/.grafana-mcp/log-cache.json

refresh_log_cache all=true 호출 또는 파일 삭제

캐시 파일은 일반 JSON 문서이므로 직접 검사, 편집 또는 백업할 수 있습니다.

안전 및 제약 사항

  • 읽기 전용: 서버는 Grafana 상태를 변경하는 어떠한 엔드포인트도 노출하지 않습니다. 대시보드/데이터 소스 CRUD나 알림 변경은 없습니다.

  • Stdio 로그: 모든 로그는 stderr로 출력되어 MCP stdio 채널을 깨끗하게 유지합니다.

  • TLS 건너뛰기: GRAFANA_TLS_SKIP_VERIFY=true는 프로세스 전체에서 NODE_TLS_REJECT_UNAUTHORIZED=0을 설정합니다. 신뢰할 수 있는 네트워크 내의 자체 서명된 Grafana에만 사용하세요.

  • 비밀 정보 로깅 금지: 인증 토큰은 감사 로그에 기록되지 않습니다.

라이선스

MIT

Related MCP Connectors

  • An MCP server giving access to Grafana dashboards, data and more.

  • The Grafbase MCP server sits in front of a GraphQL API and exposes an MCP protocol-compliant interface that allows AI agents and LLMs to explore and query GraphQL APIs using natural language. It provides tools to search schemas, introspect types and fields, and execute GraphQL queries while minimizing context bloat by returning only relevant schema subsets, with built-in support for authentication, authorization, and configurable access control.

  • The Cortex MCP server provides read-only access to real-time engineering context from the Cortex developer portal, allowing AI coding assistants to answer natural language questions about your organization's catalog (microservices, libraries, domains, teams, infrastructure), scorecards (engineering standards and best practices), initiatives (goals and deadlines), and Engineering Intelligence metrics. It includes tools for querying documentation, tracking personal entities, and accessing AI-assisted insights across the entire Cortex ecosystem.

  • The BigQuery remote MCP server is a fully managed service that uses the Model Context Protocol to connect AI applications and LLMs to BigQuery data sources. It provides secure, standardized tools for AI agents to list datasets and tables, retrieve schemas, generate and execute SQL queries through natural language, and analyze data—enabling direct access to enterprise analytics data without requiring manual SQL coding.

Related MCP Servers

  • A
    license
    A
    quality
    D
    maintenance
    A server that enables AI assistants to access and query Grafana dashboards, metrics, logs, and configurations through an MCP protocol interface.
    10
    6
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    An MCP server for intelligent log analysis providing semantic search, error pattern clustering, and smart error detection. It enables users to process, vectorize, and query local logs to efficiently identify issues and generate AI-powered summaries.
    MIT
  • A
    license
    Not graded
    quality
    C
    maintenance
    An MCP server that enables querying logs and metrics from Graylog, Prometheus, and InfluxDB 2.x. It provides tools for executing Lucene log searches, PromQL queries, and Flux queries directly within MCP-compatible clients.
    MIT