convez.ai
MCP ServerDevOps & InfraestruturaAvançado
nikogura

Diagnostic Bot

nikogura/diagnostic-bot

Investigação de infraestrutura e segurança via IA com análise de causa raiz

Ver no GitHub
InicialPluginScore · de 0 a 100

MCP Server que automatiza investigação e análise de causa raiz em infraestrutura e segurança. Integra-se com Slack ou clientes MCP para consultar logs, métricas, traces e repositórios, gerando relatórios PDF com achados estruturados.

Instalação

$npx convez-ai nikogura/diagnostic-bot

1 comando no terminal: detecta o formato do repositório (marketplace ou plugin avulso) e instala via Claude Code. Requer Node 18+ e o Claude Code instalado.

Métricas

Estrelas
0
Forks
0
Acompanhando
0
Saúde
42%
Último commit
há 2 semanas
Versão
v2.6.0
Issues abertas
0
Contribuidores
1

Casos de uso

  • Diagnóstico de erros em produção (ex: 403s, timeouts)
  • Análise de mudanças antes de incidentes
  • Investigação de dashboards Grafana
  • Rastreamento de logs através de múltiplas fontes (Loki, CloudWatch)
  • Investigação de performance com métricas Prometheus e traces Tempo

Veredito

Ferramenta robusta para teams de SRE/DevOps que precisam de investigação assistida por IA em infraestrutura complexa. Excelente para reduzir MTTR ao abstrair consultas diretas em múltiplas ferramentas (Loki, Prometheus, Grafana, K8s, CloudWatch), mas requer configuração inicial extensiva e familiarity com o stack observability da organização.

README

A tradução para o português deste README ainda está na fila.

Diagnostic Bot

Diagnostic Bot is a collection of curated investigative skills — expert investigation procedures, written once and packaged so anyone can run them. It investigates across logs, metrics, traces, databases, source repositories, and container scans, and returns a written analysis with an optional PDF report.

A skill is reached by describing the problem, not by picking one from a list. The matching skill runs and gathers the data it needs, so someone can get a thorough investigation without direct access to the underlying data sources or familiarity with the query tools. It answers questions such as "why is this service returning 403s", "what changed before this incident", or "explain what this Grafana dashboard is showing".

Access is read-only, with one exception: when asked, it can create or correct Grafana dashboards. Example skills are included; the intent is to write your own for your own infrastructure.

How It Works

A request is matched to an investigation skill — a YAML template that defines the trigger patterns and the prompt. The agent gathers data with the tools that are configured, reasons over the results, and produces findings. Tool output is gathered and analyzed; it is never executed.

There are two ways to reach the same toolset:

  • Slack — mention the bot with a question. It runs the investigation and replies in the thread, attaching any generated PDF. Threads support follow-up questions. To stop a chatty thread from attaching a report on every reply, say something like "disable reports" (also "stop making pdfs", "no more reports"); "resume reports" / "enable pdf" turns them back on. PDFs can also be disabled globally with PDF_DISABLED.
  • MCP server — exposes the same tools to any MCP client (Claude Code, Claude Desktop, and other MCP-compatible clients) over Streamable HTTP.

Tools

All tools are read-only except the Grafana dashboard-management tools. Each group is registered only when its backing service is configured.

GroupToolsEnabled by
Logs (Loki)query_lokiLOKI_ENDPOINT
Logs (CloudWatch)cloudwatch_logs_query, cloudwatch_logs_list_groups, cloudwatch_logs_get_eventsCLOUDWATCH_ACCOUNTS or CLOUDWATCH_ASSUME_ROLE
Metrics (Prometheus)prometheus_query, prometheus_query_range, prometheus_series, prometheus_label_values, prometheus_list_endpointsPROMETHEUS_URL / PROMETHEUS_<NAME>_URL
Traces (Tempo)tempo_get_trace, tempo_search_traces, tempo_list_endpointsTEMPO_URL / TEMPO_<NAME>_URL
Grafana (read)grafana_list_dashboards, grafana_get_dashboard, grafana_get_dashboard_versionGRAFANA_URL + GRAFANA_API_KEY
Grafana (write)grafana_create_dashboard, grafana_update_dashboard, grafana_patch_dashboard, grafana_restore_dashboard_version, grafana_delete_dashboard, grafana_create_folderGRAFANA_URL + GRAFANA_API_KEY (disabled by READ_ONLY)
Databasedatabase_query (SELECT/SHOW/DESCRIBE/EXPLAIN only), database_listDATABASE_URL / DATABASE_<NAME>_URL
Kubernetes (read-only)k8s_get_resource (configmap/deployment/service/pod/Flux/Atlas CRDs — never Secrets), k8s_pod_logs, k8s_list_pods, k8s_get_eventsin-cluster ServiceAccount, or KUBECONFIG
GitHubgithub_get_file, github_list_directory, github_search_codeGITHUB_TOKEN
GitLabgitlab_get_file, gitlab_list_directory, gitlab_search_codeGITLAB_TOKEN
AWS (read)sts_get_caller_identity, iam_list_roles, iam_get_role, ec2_describe_vpcs, ec2_describe_subnets, ec2_describe_security_groups, ec2_describe_nat_gateways, route53_list_hosted_zones, route53_list_records, s3_list_buckets, s3_get_bucket_policyAWS credentials
Container scans (ECR)ecr_scan_resultsAWS_REGION / AWS_DEFAULT_REGION
GraphQLgraphql_query, graphql_list_endpointsGRAPHQL_URL / GRAPHQL_<NAME>_URL
Utilitywhois_lookup, generate_pdfalways available
Third-party APIsgenerated per YAML configAPI_CONFIG_DIR

Database access is restricted to read-only statements. The Kubernetes tools are read-only (get/list) and target only the cluster the bot runs in (or the one named by KUBECONFIG); they cannot read Secrets — secret is excluded from the resource allowlist, the supplied RBAC withholds the secrets verb, and all output is secret-scrubbed. Setting READ_ONLY=true removes every write tool from the toolset and rejects any write call at dispatch.

Investigation Skills

Skills are YAML files in INVESTIGATION_DIR (default ./investigations). A message is routed to the first skill whose trigger_patterns match.

name: "Investigation Name"
description: "What this investigation does"
trigger_patterns:
  - "pattern1"
  - "pattern2.*regex"
initial_prompt: |
  The prompt that defines the investigation: role, methodology, which tools to
  use, and the expected output format.
FieldPurpose
nameDisplay name
descriptionShort summary
trigger_patternsRegexes matched against the request to select the skill
initial_promptInvestigation instructions and methodology

Four example skills ship in investigations/: modsecurity-block, atlas-migration, ecr-vulnerability-scan, and general-diagnostic. They contain substitution placeholders for adapting to a specific environment.

Third-Party API Integrations

Read-only HTTP APIs can be added as tools without code. Drop a YAML file in API_CONFIG_DIR (default ./apis) describing the base URL, authentication, and endpoints; each endpoint becomes a tool. The generic client handles auth, retries, rate limiting, path-parameter validation, and JSON field redaction. See apis/bitgo.yaml for an example.

Configuration

All configuration is via environment variables.

Required

VariablePurpose
SLACK_BOT_TOKENSlack bot OAuth token (xoxb-…)
SLACK_APP_TOKENSlack app-level token for Socket Mode (xapp-…)
ANTHROPIC_API_KEYClaude API key (sk-ant-…)

Core

VariableDefaultPurpose
CLAUDE_MODELclaude-sonnet-4-5-20250929Model used for investigations
READ_ONLYfalseWhen true/1/yes/on, disables all write tools (Grafana) on both interfaces
INVESTIGATION_DIR./investigationsSkill directory
COMPANY_NAMECompanyBranding on PDF reports
FILE_RETENTION24hGenerated-file cleanup interval
API_CONFIG_DIR./apisThird-party API config directory
PDF_FONThelveticaReport font: helvetica, times, or courier (code blocks are always monospace)
PDF_DISABLEDfalseGlobally disable PDF report generation (text-only responses)

MCP Server

VariableDefaultPurpose
MCP_HTTP_ENABLEDfalseServe the MCP HTTP (Streamable) endpoint
MCP_HTTP_PORT8090Port for the MCP HTTP server
MCP_PUBLIC_URL—Externally reachable base URL (required for Google OAuth)
MCP_AUDIT_USEROS userIdentity stamped on Grafana writes
MCP_MAX_TOOL_OUTPUT_BYTES1000000Cap on a single tool result returned to any caller; oversized output is truncated with a notice

Observability

VariableDefaultPurpose
METRICS_PORT9090Admin port for /metrics and health probes (always separate from the MCP port)
OTEL_EXPORTER_OTLP_ENDPOINT—OTLP endpoint for traces; tracing is a no-op when unset

Backing Services

VariableEnables
LOKI_ENDPOINT, LOKI_DEFAULT_ORG_ID, LOKI_ORG_IDSLoki log queries
CLOUDWATCH_ACCOUNTS or CLOUDWATCH_ASSUME_ROLE, CLOUDWATCH_EXTERNAL_IDCloudWatch Logs
PROMETHEUS_URL / PROMETHEUS_<NAME>_URLPrometheus queries
TEMPO_URL / TEMPO_<NAME>_URLTempo trace lookups
GRAFANA_URL, GRAFANA_API_KEYGrafana dashboard tools
DATABASE_URL / DATABASE_<NAME>_URLRead-only SQL
in-cluster ServiceAccount or KUBECONFIG (+ optional K8S_ENABLED=false to disable, K8S_CLUSTER_NAME to name it)Read-only Kubernetes tools for the bot's own cluster
GITHUB_TOKENGitHub file/search tools
GITLAB_TOKEN, GITLAB_URLGitLab file/search tools
AWS_REGION / AWS_DEFAULT_REGION + AWS credentialsECR scans and AWS read tools
GRAPHQL_URL (+ GRAPHQL_TOKEN or GRAPHQL_CLIENT_ID/GRAPHQL_CLIENT_SECRET/GRAPHQL_AUTH_URL/GRAPHQL_AUDIENCE)GraphQL queries

List-valued variables (e.g. LOKI_ORG_IDS) accept commas and newlines, so a YAML block scalar stays readable:

- name: LOKI_ORG_IDS
  value: |-
    monitoring
    cloudtrail
    self-monitoring

MCP Server Authentication

The MCP HTTP endpoint is unauthenticated by default (intended for VPC-internal use). One or more of the following methods can be enabled. OIDC and Google OAuth are mutually exclusive — setting both is a startup error.

MethodKey variables
Static bearer tokenMCP_AUTH_TOKEN
JWTMCP_JWT_SECRET, MCP_JWT_ALGORITHM (HS256/RS256)
API keysMCP_API_KEYS (key1:user1,key2:user2)
OIDC / JWKSMCP_OIDC_ISSUER, MCP_OIDC_AUDIENCE, MCP_OIDC_ALLOWED_GROUPS, MCP_OIDC_ALLOWED_HOSTED_DOMAINS, MCP_OIDC_ALLOWED_EMAILS (+ _FILE variants), MCP_OIDC_JWKS_CACHE_SECONDS
Google OAuthGOOGLE_OAUTH_CLIENT_ID, GOOGLE_ALLOWED_HOSTED_DOMAINS, GOOGLE_ALLOWED_EMAILS (+ _FILE variants), MCP_PUBLIC_URL
Mutual TLSMCP_MTLS_CA_CERT_PATH, MCP_MTLS_VERIFY_CLIENT

For OIDC and Google, the allowlist variables restrict access by group, hosted domain, and email. The _FILE variants read the allowlist from a file (typically a mounted ConfigMap), re-read per request with an mtime cache, so edits take effect without a restart.

Observability

Instrumentation is OpenTelemetry: metrics are exported in Prometheus format, traces over OTLP, and logs are JSON with trace correlation. The metrics and health server listens on METRICS_PORT (default :9090), separate from the MCP HTTP port.

Endpoints: /metrics, /healthz (liveness), /readyz (readiness), /health (detailed).

Metrics:

MetricTypeLabels
investigations_started_totalcountertype
investigations_resolved_totalcountertype
investigation_duration_secondshistogramtype, status
investigations_in_flightgauge—
tool_executions_totalcountertool_name, status
injection_defangs_totalcountercategory
claude_api_calls_totalcounterstatus
claude_api_tokens_totalcountertoken_type
k8s_queries_totalcounternamespace, resource_type
loki_queries_totalcounterstatus
conversations_activegauge—

Traces cover the investigation path and each tool call (investigation, tool.<name>), with W3C trace-context propagation, exported via OTLP when OTEL_EXPORTER_OTLP_ENDPOINT is set. Logs are emitted as JSON and carry trace_id/span_id when a span is active.

A Grafana dashboard is provided at dashboards/diagnostic-bot.json. It uses ${prometheus}/${loki}/${tempo} datasource variables (no hardcoded UIDs) and includes traffic, error, latency, and saturation panels, a logs panel, a traces panel, and Kubernetes resource panels (CPU and memory as a percentage of both request and limit, plus CPU throttling). Import it with whatever dashboard provisioning you use. make dashboard-check validates it is well-formed JSON.

Deployment

Run as a single-replica Deployment (state is held in memory) under a non-root user. Both distribution forms ship a PodMonitor, a ServiceMonitor, and — for the in-cluster Kubernetes tools — a read-only ClusterRole (get/list/watch on diagnostic resources, no secrets, no write verbs) bound to the ServiceAccount. The RBAC is gated by rbac.create in the chart; remove clusterrole.yaml/clusterrolebinding.yaml from the Kustomize example if the bot has no Kubernetes tools.

  • Kustomize — kubernetes/: kustomize build kubernetes/

  • Helm — charts/diagnostic-bot/, also published to oci://ghcr.io/nikogura/charts on release:

    helm install diagnostic-bot charts/diagnostic-bot \
      --set existingSecret=diagnostic-bot-secrets \
      --set config.LOKI_ENDPOINT=http://loki-gateway.monitoring.svc:80
    

    Set --set mcpHttp.enabled=true to serve the MCP HTTP endpoint, and --set config.extraEnv.READ_ONLY=true to disable writes.

Building

make build    # compile cmd/bot into bin/
make lint     # namedreturns + golangci-lint
make test     # unit tests (race + coverage) and Kustomize/Helm renders

The binary is a pure-Go static build with no external-binary dependencies — whois and PDF rendering are in-process — so the image is distroless (gcr.io/distroless/static-debian12) and multi-architecture (amd64, arm64):

docker pull ghcr.io/nikogura/diagnostic-bot:latest

CI/CD

GitHub Actions (.github/workflows/ci.yml) runs on every push and pull request: it installs the lint and render tooling (namedreturns, golangci-lint, kustomize, helm), then runs make lint and make test. On a push to main, the publish job builds and pushes the multi-arch image, packages and pushes the Helm chart to GHCR, tags the repository, and creates a GitHub Release.

Project Structure

cmd/
  bot/                 # Slack bot + optional MCP HTTP server + metrics server
pkg/
  bot/                 # Slack handling and the investigation agent loop
  claude/              # Anthropic API client and prompt construction
  investigations/      # skill loading and request matching
  k8s/                 # Loki and whois clients, input/output sanitizers
  mcp/                 # tool definitions, handlers, transports, auth
  metrics/             # OpenTelemetry instruments
  observability/       # OTel metrics/tracing/log-correlation setup
  apiconfig/           # third-party API tool generation
dashboards/            # Grafana dashboard JSON
kubernetes/            # Kustomize deployment
charts/diagnostic-bot/ # Helm chart
investigations/        # example skills
apis/                  # example third-party API configs

License

See LICENSE.

Contributing

All code must pass make lint (namedreturns + golangci-lint) and make test. New features require tests.

Maintainer

Nik Ogura

Ver o original no GitHub

Bom para

Relacionados