Skip to main content
Glama

system.health

Run health checks for MCP server diagnostics including tool metrics, cache statistics, service initialization, pattern services, and hardware status.

Instructions

Run MCP server health check. Checks MCP tool metrics, embedding cache stats, service initialization status, pattern services health, and returns diagnostics.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
include_metricsNoInclude MCP tool metrics (requests, errors, response times). Default: true
include_cache_statsNoInclude embedding cache statistics (hits, misses, hit rate). Default: true
include_css_analysis_cache_statsNoInclude CSS analysis cache statistics (layout.inspect/motion.detect cache hits, misses, hit rate). Default: true (MCP-CACHE-02)
include_initialization_statusNoInclude service initialization status (initialized categories, skipped, errors). Default: true (MCP-INIT-02)
include_pattern_servicesNoInclude pattern services health (patternMatcher, benchmarkService, patternDrivenEvaluation). Default: true (REFTRIX-PATTERN-01)
include_tools_statusNoInclude tool-level operational status (operational/unavailable, full/fallback mode). Default: true (REFTRIX-HEALTH-01)
include_vision_hardwareNoInclude Vision hardware status (force CPU mode, detected hardware type). Default: true (Vision CPU completion guarantee diagnostics)

Implementation Reference

  • system.health ツールハンドラーのメイン実行ロジック。システム健全性データを収集し、レスポンスを組み立てます。
    export async function systemHealthHandler(input?: unknown): Promise<SystemHealthHandlerResponse> {
      // router.tsから注入された_request_idを使用、フォールバックとして自動生成
      const requestId =
        ((input as Record<string, unknown> | null)?._request_id as string | undefined) ??
        generateRequestId();
    
      const startTime = Date.now();
    
      try {
        const options = (input as SystemHealthInput) ?? {};
        const includeMetrics = options.include_metrics !== false; // デフォルトはtrue
        const includeInitializationStatus = options.include_initialization_status !== false; // デフォルトはtrue(MCP-INIT-02)
    
        if (isDevelopment()) {
          logger.info("[MCP Tool] system.health called", {
            includeMetrics,
            includeInitializationStatus,
            requestId,
          });
        }
    
        // 初期状態は healthy、後続のチェックで degraded に下げる可能性あり
        const healthData: SystemHealthResponse = {
          status: "healthy",
          timestamp: new Date().toISOString(),
          services: {},
        };
    
        // サービス初期化状態を含める(MCP-INIT-02)
        if (includeInitializationStatus) {
          const initResult = getLastInitializationResult();
          if (initResult) {
            healthData.services.initialization = {
              initializedCategories: initResult.initializedCategories,
              skippedCategories: initResult.skippedCategories.map((s) => ({
                category: s.category,
                reason: s.reason,
              })),
              errors: initResult.errors.map((e) => ({
                category: e.category,
                error: e.error,
              })),
              // allToolDefinitionsから実際のMCPツール数を取得(17ツール)
              registeredToolCount: allToolDefinitions.length,
            };
    
            // 初期化エラーがある場合、全体ステータスを degraded に下げる
            if (initResult.errors.length > 0 && healthData.status === "healthy") {
              healthData.status = "degraded";
            }
          }
        }
    
        // メトリクス統計を含める
        if (includeMetrics) {
          const metricsStats = getToolMetricsStats();
          healthData.mcp_metrics = convertToMcpToolMetrics(metricsStats);
        }
    
        // Embeddingキャッシュ統計を含める(MCP-CACHE-01)
        const includeCacheStats = options.include_cache_stats !== false; // デフォルトはtrue
        if (includeCacheStats) {
          try {
            const cacheStats = await getEmbeddingCacheStats();
            if (cacheStats) {
              healthData.embedding_cache = {
                hits: cacheStats.hits,
                misses: cacheStats.misses,
                hit_rate: cacheStats.hitRate,
                size: cacheStats.size,
                max_size: cacheStats.maxSize,
                disk_usage_bytes: cacheStats.diskUsageBytes,
                eviction_count: cacheStats.evictionCount,
              };
            }
          } catch (cacheError) {
            if (isDevelopment()) {
              logger.warn("[MCP Tool] Failed to get embedding cache stats", {
                error: cacheError instanceof Error ? cacheError.message : "Unknown error",
                requestId,
              });
            }
          }
        }
    
        // CSS解析キャッシュ統計を含める(MCP-CACHE-02)
        const includeCssAnalysisCacheStats = options.include_css_analysis_cache_stats !== false; // デフォルトはtrue
        if (includeCssAnalysisCacheStats) {
          try {
            const cssAnalysisCacheService = getCSSAnalysisCacheService();
            const cssStats = await cssAnalysisCacheService.getStats();
            healthData.css_analysis_cache = {
              layout_inspect: {
                hits: cssStats.layoutInspect.hits,
                misses: cssStats.layoutInspect.misses,
                hit_rate: cssStats.layoutInspect.hitRate,
                size: cssStats.layoutInspect.size,
              },
              motion_detect: {
                hits: cssStats.motionDetect.hits,
                misses: cssStats.motionDetect.misses,
                hit_rate: cssStats.motionDetect.hitRate,
                size: cssStats.motionDetect.size,
              },
              total_hits: cssStats.totalHits,
              total_misses: cssStats.totalMisses,
              total_hit_rate: cssStats.totalHitRate,
              total_size: cssStats.totalSize,
              max_size: cssStats.maxSize,
              disk_usage_bytes: cssStats.diskUsageBytes,
            };
          } catch (cssAnalysisCacheError) {
            if (isDevelopment()) {
              logger.warn("[MCP Tool] Failed to get CSS analysis cache stats", {
                error:
                  cssAnalysisCacheError instanceof Error
                    ? cssAnalysisCacheError.message
                    : "Unknown error",
                requestId,
              });
            }
          }
        }
    
        // パターンサービス健全性を含める(REFTRIX-PATTERN-01)
        const includePatternServices = options.include_pattern_services !== false; // デフォルトはtrue
        if (includePatternServices) {
          const patternMatcherFactory = getPatternMatcherServiceFactory();
          const benchmarkFactory = getBenchmarkServiceFactory();
    
          const patternMatcherStatus: "healthy" | "unavailable" = patternMatcherFactory
            ? "healthy"
            : "unavailable";
          const benchmarkServiceStatus: "healthy" | "unavailable" = benchmarkFactory
            ? "healthy"
            : "unavailable";
          const patternDrivenEvaluation: "available" | "fallback_mode" =
            patternMatcherFactory && benchmarkFactory ? "available" : "fallback_mode";
    
          healthData.services.pattern_services = {
            patternMatcher: patternMatcherStatus,
            benchmarkService: benchmarkServiceStatus,
            patternDrivenEvaluation,
          };
    
          // パターンサービスが unavailable の場合、全体ステータスを degraded に下げる
          if (patternDrivenEvaluation === "fallback_mode" && healthData.status === "healthy") {
            healthData.status = "degraded";
          }
    
          if (isDevelopment()) {
            logger.info("[MCP Tool] Pattern services status", {
              patternMatcher: patternMatcherStatus,
              benchmarkService: benchmarkServiceStatus,
              patternDrivenEvaluation,
              requestId,
            });
          }
        }
    
        // ツールレベルの可用性を含める(REFTRIX-HEALTH-01)
        const includeToolsStatus = options.include_tools_status !== false; // デフォルトはtrue
        if (includeToolsStatus) {
          const toolsStatus = getToolsOperationalStatus(healthData.services.pattern_services);
          healthData.services.tools = toolsStatus;
    
          if (isDevelopment()) {
            logger.info("[MCP Tool] Tools operational status", {
              tools: Object.keys(toolsStatus),
              allOperational: Object.values(toolsStatus).every((t) => t.status === "operational"),
              requestId,
            });
          }
        }
    
        // Vision Hardware ステータスを含める(Vision CPU完走保証診断用)
        const includeVisionHardware = options.include_vision_hardware !== false; // デフォルトはtrue
        if (includeVisionHardware) {
          try {
            const hardwareDetector = new HardwareDetector();
            const hardwareInfo = await hardwareDetector.detect();
    
            // 環境変数の値を直接取得(診断用)
            const envForceCpuMode = process.env["VISION_FORCE_CPU_MODE"];
    
            healthData.vision_hardware = {
              force_cpu_mode: hardwareDetector.isForceCpuModeEnabled(),
              env_vision_force_cpu_mode: envForceCpuMode,
              detected_type: hardwareInfo.type === HardwareType.GPU ? "GPU" : "CPU",
              vram_bytes: hardwareInfo.vramBytes,
              is_gpu_available: hardwareInfo.isGpuAvailable,
              ...(hardwareInfo.error !== undefined && { detection_error: hardwareInfo.error }),
              ollama_url: "http://localhost:11434", // デフォルトOllama URL
            };
    
            // Ollama GPU不整合検出(REFTRIX-GPU-MISMATCH-01)
            const gpuMismatch = await hardwareDetector.detectGpuMismatch();
            if (gpuMismatch) {
              healthData.vision_hardware!.ollama_gpu_mismatch = true;
              healthData.vision_hardware!.nvidia_gpu_name = gpuMismatch.nvidia_gpu;
              healthData.vision_hardware!.gpu_mismatch_action = gpuMismatch.action;
    
              if (healthData.status === "healthy") {
                healthData.status = "degraded";
              }
    
              logger.warn("[MCP Tool] Ollama GPU mismatch detected", {
                nvidia_gpu: gpuMismatch.nvidia_gpu,
                ollama_vram_bytes: gpuMismatch.ollama_vram_bytes,
                action: gpuMismatch.action,
                requestId,
              });
            }
    
            if (isDevelopment()) {
              logger.info("[MCP Tool] Vision hardware status", {
                forceCpuMode: hardwareDetector.isForceCpuModeEnabled(),
                envForceCpuMode,
                detectedType: hardwareInfo.type,
                vramBytes: hardwareInfo.vramBytes,
                isGpuAvailable: hardwareInfo.isGpuAvailable,
                error: hardwareInfo.error,
                gpuMismatch: gpuMismatch?.mismatch ?? false,
                requestId,
              });
            }
          } catch (visionHardwareError) {
            if (isDevelopment()) {
              logger.warn("[MCP Tool] Failed to get vision hardware status", {
                error:
                  visionHardwareError instanceof Error ? visionHardwareError.message : "Unknown error",
                requestId,
              });
            }
            // エラー時は環境変数のみを報告
            healthData.vision_hardware = {
              force_cpu_mode: process.env["VISION_FORCE_CPU_MODE"]?.toLowerCase() === "true",
              env_vision_force_cpu_mode: process.env["VISION_FORCE_CPU_MODE"],
              detected_type: "CPU", // 安全側
              vram_bytes: 0,
              is_gpu_available: false,
              detection_error:
                visionHardwareError instanceof Error ? visionHardwareError.message : "Unknown error",
              ollama_url: "http://localhost:11434",
            };
          }
        }
    
        const processingTime = Date.now() - startTime;
    
        if (isDevelopment()) {
          logger.info("[MCP Tool] system.health completed", {
            status: healthData.status,
            totalTime: processingTime,
            hasMetrics: includeMetrics,
            hasCacheStats: includeCacheStats,
            hasCssAnalysisCacheStats: includeCssAnalysisCacheStats,
            hasInitializationStatus: includeInitializationStatus,
            hasPatternServices: includePatternServices,
            hasToolsStatus: includeToolsStatus,
            hasVisionHardware: includeVisionHardware,
            requestId,
          });
        }
    
        return createSuccessResponseWithRequestId(healthData, requestId, {
          processing_time_ms: processingTime,
        });
      } catch (error) {
        const processingTime = Date.now() - startTime;
    
        if (isDevelopment()) {
          logger.error("[MCP Tool] system.health error", {
            error: error instanceof Error ? error.message : "Unknown error",
            stack: error instanceof Error ? error.stack : undefined,
            requestId,
          });
        }
    
        return createErrorResponseWithRequestId(
          "HEALTH_CHECK_ERROR",
          `ヘルスチェック中にエラーが発生しました: ${error instanceof Error ? error.message : "Unknown error"}`,
          requestId,
          error instanceof Error ? { stack: error.stack } : undefined,
          { processing_time_ms: processingTime }
        );
      }
    }
  • system.health ツールの入力パラメータのスキーマ定義。
     * system.health入力スキーマ
     */
    export interface SystemHealthInput {
      /** メトリクスを含めるか(デフォルト: true) */
      include_metrics?: boolean;
      /** Embeddingキャッシュ統計を含めるか(デフォルト: true) */
      include_cache_stats?: boolean;
      /** CSS解析キャッシュ統計を含めるか(デフォルト: true)(MCP-CACHE-02) */
      include_css_analysis_cache_stats?: boolean;
      /** サービス初期化状態を含めるか(デフォルト: true)(MCP-INIT-02) */
      include_initialization_status?: boolean;
      /** パターンサービス健全性を含めるか(デフォルト: true)(REFTRIX-PATTERN-01) */
      include_pattern_services?: boolean;
      /** ツールレベルの可用性を含めるか(デフォルト: true)(REFTRIX-HEALTH-01) */
      include_tools_status?: boolean;
      /** Vision Hardware ステータスを含めるか(デフォルト: true)(Vision CPU完走保証診断用) */
      include_vision_hardware?: boolean;
    }
  • MCPプロトコルへの登録用ツール定義。名前、説明、入力スキーマを含みます。
    export const systemHealthToolDefinition = {
      name: "system.health",
      description:
        "Run MCP server health check. Checks MCP tool metrics, embedding cache stats, service initialization status, pattern services health, and returns diagnostics.",
      inputSchema: {
        type: "object" as const,
        properties: {
          include_metrics: {
            type: "boolean" as const,
            description: "Include MCP tool metrics (requests, errors, response times). Default: true",
            default: true,
          },
          include_cache_stats: {
            type: "boolean" as const,
            description: "Include embedding cache statistics (hits, misses, hit rate). Default: true",
            default: true,
          },
          include_css_analysis_cache_stats: {
            type: "boolean" as const,
            description:
              "Include CSS analysis cache statistics (layout.inspect/motion.detect cache hits, misses, hit rate). Default: true (MCP-CACHE-02)",
            default: true,
          },
          include_initialization_status: {
            type: "boolean" as const,
            description:
              "Include service initialization status (initialized categories, skipped, errors). Default: true (MCP-INIT-02)",
            default: true,
          },
          include_pattern_services: {
            type: "boolean" as const,
            description:
              "Include pattern services health (patternMatcher, benchmarkService, patternDrivenEvaluation). Default: true (REFTRIX-PATTERN-01)",
            default: true,
          },
          include_tools_status: {
            type: "boolean" as const,
            description:
              "Include tool-level operational status (operational/unavailable, full/fallback mode). Default: true (REFTRIX-HEALTH-01)",
            default: true,
          },
          include_vision_hardware: {
            type: "boolean" as const,
            description:
              "Include Vision hardware status (force CPU mode, detected hardware type). Default: true (Vision CPU completion guarantee diagnostics)",
            default: true,
          },
        },
        required: [],
      },
      annotations: {
        title: "System Health",
        readOnlyHint: true,
        idempotentHint: true,
        openWorldHint: false,
      },
    };

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/TKMD/reftrix-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server