Skip to main content
Glama

get-post-stats

Retrieve view statistics for a specific WordPress post by entering site URL, credentials, site ID, and post ID. Integrates with WordPress MCP Server for secure, programmatic access to post analytics.

Instructions

View a specific post's views

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
passwordYesWordPress application password
postIdYesPost ID to get stats for
siteIdYesWordPress site ID
siteUrlYesWordPress site URL
usernameYesWordPress username

Implementation Reference

  • The main handler function for the 'get-post-stats' tool. It makes an authenticated API request to the WordPress/Jetpack stats endpoint `/sites/{siteId}/stats/post/{postId}`, processes the response (handling total views, timeframe data, or raw JSON), formats it into a markdown text response, and handles errors.
      async ({ siteUrl, username, password, siteId, postId }) => {
        try {
          const postStats = await makeWPRequest<any>({
            siteUrl,
            endpoint: `sites/${siteId}/stats/post/${postId}`,
            auth: { username, password }
          });
          
          // Format will depend on the actual API response
          let statsText;
          
          if (postStats && typeof postStats.views !== 'undefined') {
            statsText = `
    Post #${postId} Stats:
    Total Views: ${postStats.views || 0}
    First View: ${postStats.first_view || "Unknown"}
    Most Recent View: ${postStats.most_recent_view || "Unknown"}
            `.trim();
          } else if (postStats && Array.isArray(postStats.data)) {
            // Handle timeframe data if present
            statsText = `
    Post #${postId} Views Over Time:
    ${postStats.data.map((item: WPPostStatsData) => `${item.period || "Unknown"}: ${item.views || 0} views`).join('\n')}
            `.trim();
          } else {
            statsText = `Post #${postId} Stats:\n${JSON.stringify(postStats, null, 2)}`;
          }
          
          return {
            content: [
              {
                type: "text",
                text: statsText,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error retrieving post stats: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
          };
        }
      }
  • Zod input schema defining the required parameters for the get-post-stats tool: siteUrl (URL), username (string), password (string), siteId (number), postId (number). Used for validation by the MCP server.
    {
      siteUrl: z.string().url().describe("WordPress site URL"),
      username: z.string().describe("WordPress username"),
      password: z.string().describe("WordPress application password"),
      siteId: z.number().describe("WordPress site ID"),
      postId: z.number().describe("Post ID to get stats for"),
    },
  • src/index.ts:1383-1440 (registration)
    The server.tool() registration call that defines and registers the 'get-post-stats' tool with the MCP server, including its name, description, input schema, and handler function.
    server.tool(
      "get-post-stats",
      "View a specific post's views",
      {
        siteUrl: z.string().url().describe("WordPress site URL"),
        username: z.string().describe("WordPress username"),
        password: z.string().describe("WordPress application password"),
        siteId: z.number().describe("WordPress site ID"),
        postId: z.number().describe("Post ID to get stats for"),
      },
      async ({ siteUrl, username, password, siteId, postId }) => {
        try {
          const postStats = await makeWPRequest<any>({
            siteUrl,
            endpoint: `sites/${siteId}/stats/post/${postId}`,
            auth: { username, password }
          });
          
          // Format will depend on the actual API response
          let statsText;
          
          if (postStats && typeof postStats.views !== 'undefined') {
            statsText = `
    Post #${postId} Stats:
    Total Views: ${postStats.views || 0}
    First View: ${postStats.first_view || "Unknown"}
    Most Recent View: ${postStats.most_recent_view || "Unknown"}
            `.trim();
          } else if (postStats && Array.isArray(postStats.data)) {
            // Handle timeframe data if present
            statsText = `
    Post #${postId} Views Over Time:
    ${postStats.data.map((item: WPPostStatsData) => `${item.period || "Unknown"}: ${item.views || 0} views`).join('\n')}
            `.trim();
          } else {
            statsText = `Post #${postId} Stats:\n${JSON.stringify(postStats, null, 2)}`;
          }
          
          return {
            content: [
              {
                type: "text",
                text: statsText,
              },
            ],
          };
        } catch (error) {
          return {
            content: [
              {
                type: "text",
                text: `Error retrieving post stats: ${error instanceof Error ? error.message : String(error)}`,
              },
            ],
          };
        }
      }
    );
  • The makeWPRequest helper function used by the get-post-stats handler (and other tools) to make authenticated HTTP requests to WordPress REST API endpoints using axios, with Basic Auth and error handling.
    async function makeWPRequest<T>({
      siteUrl, 
      endpoint,
      method = 'GET',
      auth,
      data = null,
      params = null
    }: {
      siteUrl: string;
      endpoint: string;
      method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
      auth: { username: string; password: string };
      data?: any;
      params?: any;
    }): Promise<T> {
      const authString = Buffer.from(`${auth.username}:${auth.password}`).toString('base64');
      
      try {
        const response = await axios({
          method,
          url: `${siteUrl}/wp-json/wp/v2/${endpoint}`,
          headers: {
            'Authorization': `Basic ${authString}`,
            'Content-Type': 'application/json',
          },
          data: data,
          params: params
        });
        
        return response.data as T;
      } catch (error) {
        if (axios.isAxiosError(error) && error.response) {
          throw new Error(`WordPress API error: ${error.response.data?.message || error.message}`);
        }
        throw error;
      }
    }
  • TypeScript interface defining the structure of post stats data points (period and views), referenced in the handler for processing timeframe data.
    interface WPPostStatsData {
      period: string;
      views: number;
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. It states 'View' which implies a read-only operation, but doesn't clarify authentication needs, rate limits, or what 'views' specifically entails (e.g., time range, metric details). The description adds minimal context beyond the basic action, leaving significant behavioral aspects undocumented.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that front-loads the core purpose. There's zero wasted language or redundancy, making it immediately scannable and appropriately sized for a simple retrieval tool.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 5 required authentication/identification parameters and no output schema, the description is insufficient. It doesn't explain the WordPress context, authentication flow, what 'views' data includes, or error conditions. With no annotations and rich parameter requirements, the description should provide more operational context to be complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, with all 5 parameters clearly documented in the schema (siteUrl, username, password, siteId, postId). The description adds no parameter-specific information beyond implying 'postId' identifies the target post. This meets the baseline of 3 since the schema does the heavy lifting, but the description doesn't compensate with additional semantic context.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the verb ('View') and resource ('a specific post's views'), making the purpose immediately understandable. It distinguishes from siblings like 'get-site-stats' or 'get-top-posts' by focusing on a single post's views. However, it doesn't explicitly mention the WordPress context or authentication requirements, which slightly reduces specificity.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives like 'get-site-stats' for overall stats or 'get-top-posts' for ranking information. It doesn't mention prerequisites (authentication) or contextual constraints, leaving the agent to infer usage from the parameter schema alone.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

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

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