Skip to main content
Glama

Product Performance (ABC Analysis)

product_performance
Read-onlyIdempotent

Analyze product revenue performance with ABC classification (A=top 80%, B=next 15%, C=bottom 5%), trends, margins, and daily sales velocity to prioritize high-value items and identify underperforming products.

Instructions

Product performance report with ABC analysis. Category A = top 80% revenue, B = next 15%, C = bottom 5%. Includes trends, margins, and daily sales velocity.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
store_idYesUUID of a connected store (returned by store_connect with action="connect" or visible in store_connect with action="list" / the store_overview resource)
period_daysNoLook-back window for ABC classification, 7–90 days. Defaults to 30. Shorter windows favour recent trends; longer windows smooth seasonality.

Implementation Reference

  • src/index.ts:287-305 (registration)
    Registration of the 'product_performance' tool on the MCP server. Defines inputSchema (store_id UUID, period_days 7-90 default 30), description, and calls getProductPerformance handler.
    // ── Tool: product_performance ─────────────────────────────────────
    server.registerTool(
      'product_performance',
      {
        title: 'Product Performance (ABC Analysis)',
        description: 'Product performance report with ABC analysis. Category A = top 80% revenue, B = next 15%, C = bottom 5%. Includes trends, margins, and daily sales velocity.',
        inputSchema: z.object({
          store_id: z.string().uuid().describe('UUID of a connected store (returned by store_connect with action="connect" or visible in store_connect with action="list" / the store_overview resource)'),
          period_days: z.number().int().min(7).max(90).default(30).describe('Look-back window for ABC classification, 7–90 days. Defaults to 30. Shorter windows favour recent trends; longer windows smooth seasonality.'),
        }),
        annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
      },
      async ({ store_id, period_days }) => {
        try {
          const result = await getProductPerformance(store_id, period_days);
          return { content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }] };
        } catch (e) { return handleToolError(e); }
      }
    );
  • Core handler function getProductPerformance implementing ABC analysis. Fetches products/orders, computes per-product metrics (units sold, revenue, cost, profit, margin), determines trend (rising/stable/declining), and categorizes into A (top 80%), B (next 15%), C (bottom 5%) by cumulative revenue share.
    export async function getProductPerformance(storeId: string, periodDays = 30): Promise<ProductPerformanceSummary> {
      validateUUID(storeId, 'store');
      const store = await storage.getStoreById(storeId);
      if (!store) throw new NotFoundError('Store', storeId);
    
      const products = await storage.getProducts(storeId);
      const orders = await storage.getOrders(storeId);
    
      const now = Date.now();
      const cutoff = now - periodDays * MS_PER_DAY;
      const olderCutoff = now - 2 * periodDays * MS_PER_DAY;
    
      const recentOrders = orders.filter((o) =>
        new Date(o.created_at).getTime() >= cutoff &&
        o.status !== 'cancelled' && o.status !== 'refunded'
      );
      const olderOrders = orders.filter((o) => {
        const ts = new Date(o.created_at).getTime();
        return ts >= olderCutoff && ts < cutoff && o.status !== 'cancelled' && o.status !== 'refunded';
      });
    
      // Aggregate per-product metrics
      const productMetrics = new Map<string, { unitsSold: number; revenue: number; prevUnitsSold: number }>();
    
      for (const order of recentOrders) {
        for (const item of order.items) {
          const existing = productMetrics.get(item.product_id) ?? { unitsSold: 0, revenue: 0, prevUnitsSold: 0 };
          existing.unitsSold += item.quantity;
          existing.revenue += item.total;
          productMetrics.set(item.product_id, existing);
        }
      }
    
      for (const order of olderOrders) {
        for (const item of order.items) {
          const existing = productMetrics.get(item.product_id) ?? { unitsSold: 0, revenue: 0, prevUnitsSold: 0 };
          existing.prevUnitsSold += item.quantity;
          productMetrics.set(item.product_id, existing);
        }
      }
    
      const totalRevenue = [...productMetrics.values()].reduce((sum, m) => sum + m.revenue, 0);
    
      // Build performance records sorted by revenue
      const perfRecords: ProductPerformance[] = [];
      for (const product of products) {
        const metrics = productMetrics.get(product.id);
        if (!metrics && product.status !== 'active') continue;
    
        const unitsSold = metrics?.unitsSold ?? 0;
        const revenue = metrics?.revenue ?? 0;
        const prevUnits = metrics?.prevUnitsSold ?? 0;
        const cost = product.cost_price !== null ? product.cost_price * unitsSold : null;
        const profit = cost !== null ? revenue - cost : null;
        const marginPercent = revenue > 0 && cost !== null ? Math.round(((revenue - cost) / revenue) * 10000) / 100 : null;
    
        // Trend: compare with previous period
        let trend: 'rising' | 'stable' | 'declining';
        if (prevUnits === 0 && unitsSold > 0) trend = 'rising';
        else if (prevUnits === 0 && unitsSold === 0) trend = 'stable';
        else {
          const changeRate = (unitsSold - prevUnits) / Math.max(1, prevUnits);
          trend = changeRate > 0.15 ? 'rising' : changeRate < -0.15 ? 'declining' : 'stable';
        }
    
        perfRecords.push({
          product_id: product.id,
          product_title: product.title,
          sku: product.sku,
          units_sold: unitsSold,
          revenue: Math.round(revenue * 100) / 100,
          cost,
          profit: profit !== null ? Math.round(profit * 100) / 100 : null,
          margin_percent: marginPercent,
          abc_category: 'C', // placeholder, calculated below
          revenue_share_percent: totalRevenue > 0 ? Math.round((revenue / totalRevenue) * 10000) / 100 : 0,
          avg_daily_units: Math.round((unitsSold / periodDays) * 100) / 100,
          trend,
        });
      }
    
      // Sort by revenue descending for ABC
      perfRecords.sort((a, b) => b.revenue - a.revenue);
    
      // ABC categorization
      let cumulativeShare = 0;
      for (const rec of perfRecords) {
        cumulativeShare += rec.revenue_share_percent;
        if (cumulativeShare <= 80) rec.abc_category = 'A';
        else if (cumulativeShare <= 95) rec.abc_category = 'B';
        else rec.abc_category = 'C';
      }
    
      return {
        store_id: storeId,
        period_days: periodDays,
        total_products: perfRecords.length,
        total_revenue: Math.round(totalRevenue * 100) / 100,
        category_a: perfRecords.filter((p) => p.abc_category === 'A').length,
        category_b: perfRecords.filter((p) => p.abc_category === 'B').length,
        category_c: perfRecords.filter((p) => p.abc_category === 'C').length,
        products: perfRecords,
      };
    }
  • Type definition ProductPerformanceSummary returned by the tool, containing store metadata, total revenue, category counts, and product array.
    export interface ProductPerformanceSummary {
      store_id: string;
      period_days: number;
      total_products: number;
      total_revenue: number;
      category_a: number;
      category_b: number;
      category_c: number;
      products: ProductPerformance[];
    }
  • Zod schema ProductPerformanceSchema and ABCCategorySchema defining the per-product output structure including product_id, units_sold, revenue, cost, profit, margin_percent, abc_category, revenue_share_percent, avg_daily_units, and trend.
    // ── ABC Product Performance ───────────────────────────────────────
    export const ABCCategorySchema = z.enum(['A', 'B', 'C']);
    
    export const ProductPerformanceSchema = z.object({
      product_id: z.string(),
      product_title: z.string(),
      sku: z.string().nullable(),
      units_sold: z.number().int(),
      revenue: z.number(),
      cost: z.number().nullable(),
      profit: z.number().nullable(),
      margin_percent: z.number().nullable(),
      abc_category: ABCCategorySchema,
      revenue_share_percent: z.number(),
      avg_daily_units: z.number(),
      trend: z.enum(['rising', 'stable', 'declining']),
    });
    export type ProductPerformance = z.infer<typeof ProductPerformanceSchema>;
  • Import of getProductPerformance from './tools/products.js' used in the tool registration.
    import { getProductPerformance } from './tools/products.js';
Behavior4/5

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

The description adds useful context beyond annotations: it defines ABC thresholds (80/15/5) and the types of metrics included (trends, margins, daily sales velocity). Annotations already declare it as read-only and non-destructive, so the description enhances transparency about the output content, though it doesn't cover potential edge cases like empty stores or data recency.

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 extremely concise with two sentences, no redundant phrasing. The first sentence front-loads the core purpose, and the second sentence provides critical detail (ABC thresholds and included metrics). Every word adds value.

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

Completeness4/5

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

Given the tool has only two parameters and no output schema, the description adequately covers what the report contains (ABC classification, trends, margins, daily sales velocity). However, it does not specify the return format (e.g., list of products with scores, aggregated summary) or handling of missing data, which could be useful for completeness.

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?

The input schema already provides comprehensive descriptions for both parameters (store_id sourced from store_connect, period_days with range and default), achieving 100% coverage. The tool description does not add any additional parameter semantics beyond what the schema provides, so it meets the baseline of 3.

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

Purpose5/5

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

The description clearly states it's a 'product performance report with ABC analysis', specifying the key output (ABC categories with percentage thresholds) and additional data (trends, margins, daily sales velocity). This distinguishes it from sibling report tools like report_daily or report_weekly, which likely lack ABC analysis.

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

Usage Guidelines3/5

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

The description implicitly indicates it's for obtaining product performance with ABC classification, but does not explicitly state when to use it over alternatives (e.g., when you need ABC analysis vs. a plain sales report). No comparison with sibling tools or exclusion criteria are provided.

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

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/enzoemir1/shopops-mcp'

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