Skip to main content
Glama

cache_purge_product

Purge cache for a specific product by SKU to ensure updated content displays immediately to customers.

Instructions

Purge cache for a specific product by SKU.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
paramsNoAction parameters as a JSON object

Implementation Reference

  • The main handler implementation for 'cache.purge_product' tool. Validates parameters using CachePurgeProductSchema, enforces guardrails confirmation, checks rate limits, and implements the purge logic using Fastly surrogate key purge (with fallback to Magento cache clean API if Fastly is not configured).
    // ── Purge Product ─────────────────────────────────────────────────────
    {
      name: 'cache.purge_product',
      description: 'Purge cache for a specific product by SKU.',
      riskTier: RiskTier.Risk,
      requiresAuth: true,
      handler: async (params: Record<string, unknown>, context: ActionContext) => {
        const validated = CachePurgeProductSchema.parse(params);
        guardrails.requireConfirmation(RiskTier.Risk, params);
        checkRateLimit(config);
    
        if (config.fastlyServiceId && config.fastlyApiToken) {
          // Use Fastly surrogate key purge
          const fastly = new FastlyClient(config.fastlyServiceId, config.fastlyApiToken);
    
          // Get product ID for surrogate key
          const client = context.getClient();
          const product = await client.get<Record<string, unknown>>(
            `/V1/products/${encodeURIComponent(validated.sku)}`,
          );
          const productId = product['id'];
    
          // Purge by product surrogate key (Magento/Fastly convention)
          const surrogateKey = `cat_p_${productId}`;
          const result = await fastly.purgeSurrogateKey(surrogateKey);
    
          return {
            message: `Purged cache for product ${validated.sku} (surrogate key: ${surrogateKey}).`,
            success: result.ok,
            purge_id: result.id,
          };
        }
    
        // Fallback: try Magento cache clean API if available
        try {
          const client = context.getClient();
          await client.delete('/V1/integration/cache/clean/full_page');
          return {
            message: `Requested full page cache clean (Fastly not configured). Product: ${validated.sku}.`,
            note: 'Configure Fastly for targeted product purge.',
          };
        } catch {
          return {
            message: 'Neither Fastly nor Magento cache clean API available.',
            purged: false,
          };
        }
      },
    },
  • Input validation schema for cache_purge_product tool using Zod. Defines required fields: sku (string), confirm (literal true), reason (string), and optional store_view_code (string).
    export const CachePurgeProductSchema = z.object({
      sku: z.string().min(1),
      store_view_code: z.string().optional(),
      confirm: z.literal(true),
      reason: z.string().min(1),
    });
  • src/index.ts:60-60 (registration)
    Registration point where cache actions (including cache_purge_product) are created and added to the allActions array, which is then registered as MCP tools in the server.
    ...createCacheActions(guardrails, config),
  • FastlyClient helper method 'purgeSurrogateKey' that performs the actual cache purge operation via Fastly API. Used by the cache_purge_product handler to purge cache by product surrogate key (e.g., 'cat_p_{productId}').
    async purgeSurrogateKey(key: string): Promise<FastlyPurgeResult> {
      const url = `https://api.fastly.com/service/${this.serviceId}/purge/${key}`;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          'Fastly-Key': this.apiToken,
          Accept: 'application/json',
        },
      });
      const data = await response.json() as Record<string, unknown>;
      return {
        status: response.status,
        id: data['id'] as string | undefined,
        ok: response.ok,
      };
    }
  • Guardrails helper method 'requireConfirmation' that enforces confirmation requirements for risk-tier operations. Used by the cache_purge_product handler to validate that confirm=true and a reason string is provided.
    requireConfirmation(riskTier: RiskTier, params: Record<string, unknown>): void {
      if (riskTier >= RiskTier.Risk && this.config.tier2ConfirmationRequired) {
        if (params['confirm'] !== true) {
          throw new GuardrailError(
            ErrorCodes.CONFIRMATION_REQUIRED,
            `This action requires confirm: true and a reason string (Risk Tier ${riskTier}).`,
          );
        }
        if (!params['reason'] || typeof params['reason'] !== 'string' || (params['reason'] as string).trim().length === 0) {
          throw new GuardrailError(
            ErrorCodes.CONFIRMATION_REQUIRED,
            'A non-empty reason string is required for Tier 2+ operations.',
          );
        }
      }
    }

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/thomastx05/magento-mcp'

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