get_product_categories
Retrieve category information for a specific product using its SKU from a Magento 2 store.
Instructions
Get categories for a specific product by SKU
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| sku | Yes | The SKU (Stock Keeping Unit) of the product |
Implementation Reference
- mcp-server.js:460-530 (handler)Full implementation of the get_product_categories tool handler. Fetches product by SKU, extracts category_ids from custom_attributes, parses them, fetches detailed category info from Magento API /categories/{id}, handles errors, and returns JSON stringified categories.server.tool( "get_product_categories", "Get categories for a specific product by SKU", { sku: z.string().describe("The SKU (Stock Keeping Unit) of the product") }, async ({ sku }) => { try { // First get the product to find its category IDs const productData = await callMagentoApi(`/products/${sku}`); // Find category IDs in custom attributes const categoryAttribute = productData.custom_attributes?.find( attr => attr.attribute_code === 'category_ids' ); if (!categoryAttribute || !categoryAttribute.value) { return { content: [ { type: "text", text: `No categories found for product with SKU: ${sku}` } ] }; } // Parse category IDs (they might be in string format) let categoryIds = categoryAttribute.value; if (typeof categoryIds === 'string') { try { categoryIds = JSON.parse(categoryIds); } catch (e) { // If it's not valid JSON, split by comma categoryIds = categoryIds.split(',').map(id => id.trim()); } } if (!Array.isArray(categoryIds)) { categoryIds = [categoryIds]; } // Get category details for each ID const categoryPromises = categoryIds.map(id => callMagentoApi(`/categories/${id}`) .catch(err => ({ id, error: err.message })) ); const categories = await Promise.all(categoryPromises); return { content: [ { type: "text", text: JSON.stringify(categories, null, 2) } ] }; } catch (error) { return { content: [ { type: "text", text: `Error fetching product categories: ${error.message}` } ], isError: true }; } } );
- mcp-server.js:463-465 (schema)Input schema using Zod: requires 'sku' as string.{ sku: z.string().describe("The SKU (Stock Keeping Unit) of the product") },
- mcp-server.js:460-461 (registration)Registration of the tool with MCP server via server.tool call.server.tool( "get_product_categories",