Skip to main content
Glama

wp_performance_stats

Retrieve real-time WordPress performance metrics to monitor site health, analyze requests, cache efficiency, and system resources for optimization.

Instructions

Get real-time performance statistics and metrics

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
siteNoSpecific site ID for multi-site setups (optional for single site)
categoryNoCategory of metrics to return (overview, requests, cache, system, tools, all)
formatNoDetail level of the response (summary, detailed, raw)

Implementation Reference

  • The main handler function `getPerformanceStats` that implements the core logic of the `wp_performance_stats` tool. It parses input parameters (site, category, format), collects real-time metrics from MetricsCollector and PerformanceMonitor, filters and formats data by category (overview, requests, cache, system, tools), computes derived values using helper functions, handles site-specific data, and returns a structured success response with metadata.
    private async getPerformanceStats(_client: WordPressClient, params: Record<string, unknown>): Promise<unknown> {
      return toolWrapper(async () => {
        const {
          site,
          category = "overview",
          format = "summary",
        } = params as { site?: string; category?: string; format?: string };
    
        // Get current metrics
        const metrics = this.collector.collectCurrentMetrics();
    
        // Get site-specific metrics if requested
        let siteMetrics = null;
        if (site) {
          siteMetrics = this.collector.getSiteMetrics(site as string);
        }
    
        // Filter by category
        const result: Record<string, unknown> = {};
    
        if (category === "overview" || category === "all") {
          result.overview = {
            overallHealth: calculateHealthStatus(metrics),
            performanceScore: calculatePerformanceScore(metrics),
            totalRequests: metrics.requests.total,
            averageResponseTime: `${metrics.requests.averageResponseTime.toFixed(0)}ms`,
            cacheHitRate: `${(metrics.cache.hitRate * 100).toFixed(1)}%`,
            errorRate: `${((metrics.requests.failed / Math.max(metrics.requests.total, 1)) * 100).toFixed(2)}%`,
            uptime: formatUptime(metrics.system.uptime),
          };
        }
    
        if (category === "requests" || category === "all") {
          result.requests = {
            ...metrics.requests,
            requestsPerSecond: metrics.requests.requestsPerSecond.toFixed(2),
            p50ResponseTime: `${metrics.requests.p50ResponseTime}ms`,
            p95ResponseTime: `${metrics.requests.p95ResponseTime}ms`,
            p99ResponseTime: `${metrics.requests.p99ResponseTime}ms`,
          };
        }
    
        if (category === "cache" || category === "all") {
          result.cache = {
            ...metrics.cache,
            hitRate: `${(metrics.cache.hitRate * 100).toFixed(1)}%`,
            memoryUsage: `${metrics.cache.memoryUsageMB.toFixed(1)}MB`,
            efficiency: calculateCacheEfficiency(metrics.cache),
          };
        }
    
        if (category === "system" || category === "all") {
          result.system = {
            ...metrics.system,
            memoryUsage: `${metrics.system.memoryUsage}%`,
            cpuUsage: `${metrics.system.cpuUsage}%`,
            uptime: formatUptime(metrics.system.uptime),
          };
        }
    
        if (category === "tools" || category === "all") {
          result.tools = {
            mostUsedTool: metrics.tools.mostUsedTool,
            totalToolCalls: Object.values(metrics.tools.toolUsageCount).reduce(
              (sum: number, count: unknown) => sum + (typeof count === "number" ? count : 0),
              0,
            ),
            topTools: Object.entries(metrics.tools.toolUsageCount)
              .sort(([, a], [, b]) => (b as number) - (a as number))
              .slice(0, 5)
              .map(([tool, count]) => ({ tool, count })),
            toolPerformance: format === "detailed" ? metrics.tools.toolPerformance : undefined,
          };
        }
    
        // Add site-specific data if requested
        if (siteMetrics && siteMetrics.isActive) {
          result.siteSpecific = {
            siteId: site,
            cache: siteMetrics.cache,
            client: siteMetrics.client,
          };
        }
    
        // Add metadata
        result.metadata = {
          timestamp: new Date().toISOString(),
          category,
          format,
          site: site || "all",
          monitoringEnabled: true,
        };
    
        return {
          success: true,
          data: result,
        };
      });
    }
  • Local tool registration/definition within `PerformanceTools.getTools()` method. Specifies the tool name `wp_performance_stats`, description, input parameters schema (site, category, format), and binds the `getPerformanceStats` handler.
    {
      name: "wp_performance_stats",
      description: "Get real-time performance statistics and metrics",
      parameters: [
        {
          name: "site",
          type: "string",
          description: "Specific site ID for multi-site setups (optional for single site)",
          required: false,
        },
        {
          name: "category",
          type: "string",
          description: "Category of metrics to return (overview, requests, cache, system, tools, all)",
          required: false,
        },
        {
          name: "format",
          type: "string",
          description: "Detail level of the response (summary, detailed, raw)",
          required: false,
        },
      ],
      handler: this.getPerformanceStats.bind(this),
    },
  • Global MCP tool registration in `ToolRegistry.registerAllTools()`. Dynamically imports tool classes from `tools/index.js`, instantiates `PerformanceTools` with WordPress clients map (lines 51-52), retrieves tool definitions via `getTools()`, and registers each tool (including `wp_performance_stats`) with the MCP server using `registerTool()`.
    // Register all tools from the tools directory
    Object.values(Tools).forEach((ToolClass) => {
      let toolInstance: { getTools(): unknown[] };
    
      // Cache and Performance tools need the clients map
      if (ToolClass.name === "CacheTools" || ToolClass.name === "PerformanceTools") {
        toolInstance = new ToolClass(this.wordpressClients);
      } else {
        toolInstance = new (ToolClass as new () => { getTools(): unknown[] })();
      }
    
      const tools = toolInstance.getTools();
    
      tools.forEach((tool: unknown) => {
        this.registerTool(tool as ToolDefinition);
      });
    });
  • Input schema/parameters definition for the tool: site (optional string), category (optional string: overview/requests/cache/system/tools/all), format (optional string: summary/detailed/raw). Used by ToolRegistry for Zod validation.
    parameters: [
      {
        name: "site",
        type: "string",
        description: "Specific site ID for multi-site setups (optional for single site)",
        required: false,
      },
      {
        name: "category",
        type: "string",
        description: "Category of metrics to return (overview, requests, cache, system, tools, all)",
        required: false,
      },
      {
        name: "format",
        type: "string",
        description: "Detail level of the response (summary, detailed, raw)",
        required: false,
      },
    ],
  • Supporting `calculateHealthStatus` helper function used in the handler's overview section to compute overall health status (Excellent/Good/Fair/Poor/Critical) based on response time, error rate, cache hit rate, and memory usage.
    export function calculateHealthStatus(metrics: PerformanceMetrics): string {
      let score = 100;
    
      if (metrics.requests.averageResponseTime > 2000) score -= 30;
      else if (metrics.requests.averageResponseTime > 1000) score -= 15;
    
      const errorRate = metrics.requests.failed / Math.max(metrics.requests.total, 1);
      if (errorRate > 0.05) score -= 30;
      else if (errorRate > 0.02) score -= 15;
    
      if (metrics.cache.hitRate < 0.7) score -= 25;
      else if (metrics.cache.hitRate < 0.85) score -= 10;
    
      if (metrics.system.memoryUsage > 85) score -= 15;
    
      if (score >= 90) return "Excellent";
      if (score >= 75) return "Good";
      if (score >= 60) return "Fair";
      if (score >= 40) return "Poor";
      return "Critical";
    }

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/docdyhr/mcp-wordpress'

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