Skip to main content
Glama
marcusquinn

Amazon Order History CSV Download MCP

by marcusquinn

export_amazon_items_csv

Extract detailed Amazon order items into a CSV file for expense tracking, inventory analysis, or accounting exports. Visits each order's invoice page to capture item-level data including product details, pricing, seller information, and order financials.

Instructions

Export detailed Amazon order items to CSV file. Visits each order's invoice page to extract item-level data (~2s/order). CSV columns: Order ID, Date, ASIN, Product Name, Condition, Quantity, Unit Price, Item Total, Seller, Subscribe & Save, Order financials (Subtotal, Shipping, Tax, VAT, Promotion, Total), Status, Address (7 lines), Payment Method, Product URL, Order URL, Region. Ideal for expense tracking, inventory analysis, or accounting exports.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
regionYesAmazon region code
yearNoYear to export (defaults to current year)
start_dateNoStart date in ISO format (YYYY-MM-DD)
end_dateNoEnd date in ISO format (YYYY-MM-DD)
output_pathNoFull path to save CSV file. Defaults to ~/Downloads/amazon-{region}-items-{year}-{date}.csv
max_ordersNoMaximum number of orders to process. Recommended: 50-100 per batch due to ~2s/order extraction time.

Implementation Reference

  • Top-level MCP tool handler for 'export_amazon_items_csv'. Validates region, fetches Amazon orders with detailed item extraction using fetchOrders, estimates processing time, generates output filename, exports items to CSV via exportItemsCSV, and returns success/error with timing info.
    case "export_amazon_items_csv": {
      const regionParam = args?.region as string | undefined;
      const regionError = validateRegion(regionParam, args);
      if (regionError) return regionError;
      const region = regionParam!;
    
      const currentPage = await getPage();
      const year = args?.year as number | undefined;
      const startDate = args?.start_date as string | undefined;
      const endDate = args?.end_date as string | undefined;
      const maxOrders = args?.max_orders as number | undefined;
      const outputPath = getOutputPath(
        args?.output_path as string | undefined,
        "items",
        region,
        { year, startDate, endDate },
      );
    
      // Pre-estimate time for items extraction (slower due to invoice/detail page visits)
      const preEstimate = estimateExtractionTime(maxOrders || 100, {
        includeItems: true,
        includeShipments: false,
        useInvoice: true,
      });
    
      // Warn if this might take a while
      if (preEstimate.warnings.length > 0) {
        console.error(
          `[export-items] Time estimate: ${preEstimate.formattedEstimate}`,
        );
        console.error(
          `[export-items] Warnings: ${preEstimate.warnings.join(", ")}`,
        );
      }
    
      const fetchResult = await fetchOrders(currentPage, amazonPlugin, {
        region,
        year,
        startDate,
        endDate,
        includeItems: true,
        includeShipments: false,
        maxOrders,
      });
    
      // Calculate actual time estimate based on orders found
      const timeEstimate = estimateExtractionTime(fetchResult.orders.length, {
        includeItems: true,
        includeShipments: false,
        useInvoice: true,
      });
    
      const exportResult = await exportItemsCSV(
        fetchResult.items,
        outputPath,
      );
    
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              {
                status: exportResult.success ? "success" : "error",
                params: {
                  region,
                  year,
                  startDate,
                  endDate,
                  maxOrders,
                  outputPath,
                },
                filePath: exportResult.filePath,
                rowCount: exportResult.rowCount,
                error: exportResult.error,
                fetchErrors: fetchResult.errors,
                timing: {
                  orderCount: fetchResult.orders.length,
                  itemCount: fetchResult.items.length,
                  estimate: timeEstimate.formattedEstimate,
                  warnings: timeEstimate.warnings,
                  recommendations: timeEstimate.recommendations,
                },
              },
              null,
              2,
            ),
          },
        ],
      };
    }
  • Core CSV export function for Amazon order items. Formats items using predefined ITEM_CSV_COLUMNS and writes to the specified output file path, returning export result.
    export async function exportItemsCSV(
      items: Item[],
      outputPath: string,
    ): Promise<ExportResult> {
      try {
        const csv = toCSVWithColumns(items, ITEM_CSV_COLUMNS);
        await writeFile(outputPath, csv, "utf-8");
    
        return {
          success: true,
          filePath: outputPath,
          rowCount: items.length,
        };
      } catch (error) {
        return {
          success: false,
          filePath: outputPath,
          rowCount: 0,
          error: String(error),
        };
      }
    }
  • JSON Schema defining the input parameters for the tool: region (required, enum of Amazon regions), optional year/dates for filtering, output_path, and max_orders limit.
    inputSchema: {
      type: "object",
      properties: {
        region: {
          type: "string",
          description: "Amazon region code",
          enum: getRegionCodes(),
        },
        year: {
          type: "number",
          description: "Year to export (defaults to current year)",
        },
        start_date: {
          type: "string",
          description: "Start date in ISO format (YYYY-MM-DD)",
        },
        end_date: {
          type: "string",
          description: "End date in ISO format (YYYY-MM-DD)",
        },
        output_path: {
          type: "string",
          description:
            "Full path to save CSV file. Defaults to ~/Downloads/amazon-{region}-items-{year}-{date}.csv",
        },
        max_orders: {
          type: "number",
          description:
            "Maximum number of orders to process. Recommended: 50-100 per batch due to ~2s/order extraction time.",
        },
      },
      required: ["region"],
    },
  • src/index.ts:263-300 (registration)
    Tool registration entry in the MCP tools array, including name, detailed description, and input schema. Returned by listTools endpoint.
    {
      name: "export_amazon_items_csv",
      description:
        "Export detailed Amazon order items to CSV file. Visits each order's invoice page to extract item-level data (~2s/order). CSV columns: Order ID, Date, ASIN, Product Name, Condition, Quantity, Unit Price, Item Total, Seller, Subscribe & Save, Order financials (Subtotal, Shipping, Tax, VAT, Promotion, Total), Status, Address (7 lines), Payment Method, Product URL, Order URL, Region. Ideal for expense tracking, inventory analysis, or accounting exports.",
      inputSchema: {
        type: "object",
        properties: {
          region: {
            type: "string",
            description: "Amazon region code",
            enum: getRegionCodes(),
          },
          year: {
            type: "number",
            description: "Year to export (defaults to current year)",
          },
          start_date: {
            type: "string",
            description: "Start date in ISO format (YYYY-MM-DD)",
          },
          end_date: {
            type: "string",
            description: "End date in ISO format (YYYY-MM-DD)",
          },
          output_path: {
            type: "string",
            description:
              "Full path to save CSV file. Defaults to ~/Downloads/amazon-{region}-items-{year}-{date}.csv",
          },
          max_orders: {
            type: "number",
            description:
              "Maximum number of orders to process. Recommended: 50-100 per batch due to ~2s/order extraction time.",
          },
        },
        required: ["region"],
      },
    },
  • Helper defining CSV column configuration for item exports. Maps Item type fields (with order context) to CSV headers and value extractors, enabling structured output with order details, pricing, addresses, etc.
    export const ITEM_CSV_COLUMNS: CSVColumn<Item>[] = [
      // Order identification
      { key: "orderId", header: "Order ID", getValue: (i) => i.orderHeader.id },
      {
        key: "orderDate",
        header: "Order Date",
        getValue: (i) => formatDate(i.orderHeader.date),
      },
    
      // Item identification
      { key: "asin", header: "ASIN", getValue: (i) => i.asin || "" },
      { key: "name", header: "Product Name", getValue: (i) => i.name },
      { key: "condition", header: "Condition", getValue: (i) => i.condition || "" },
    
      // Item pricing
      { key: "quantity", header: "Quantity", getValue: (i) => i.quantity },
      {
        key: "unitPrice",
        header: "Unit Price",
        getValue: (i) => formatMoney(i.unitPrice),
      },
      {
        key: "totalPrice",
        header: "Item Total",
        getValue: (i) => formatMoney(i.totalPrice),
      },
    
      // Seller info (name only - soldBy/suppliedBy require detail page)
      { key: "seller", header: "Seller", getValue: (i) => i.seller?.name || "" },
    
      // Subscription
      {
        key: "subscriptionFrequency",
        header: "Subscribe & Save",
        getValue: (i) => i.subscriptionFrequency || "",
      },
    
      // Order-level financial data
      {
        key: "orderSubtotal",
        header: "Order Subtotal",
        getValue: (i) => formatMoney(i.orderHeader.subtotal),
      },
      {
        key: "orderShipping",
        header: "Order Shipping",
        getValue: (i) => formatMoney(i.orderHeader.shipping),
      },
      {
        key: "orderTax",
        header: "Order Tax",
        getValue: (i) => formatMoney(i.orderHeader.tax),
      },
      {
        key: "orderVat",
        header: "Order VAT",
        getValue: (i) => formatMoney(i.orderHeader.vat),
      },
      {
        key: "orderPromotion",
        header: "Order Promotion",
        getValue: (i) => formatMoney(i.orderHeader.promotion),
      },
      {
        key: "orderTotal",
        header: "Order Total",
        getValue: (i) => formatMoney(i.orderHeader.total),
      },
      {
        key: "orderGrandTotal",
        header: "Order Grand Total",
        getValue: (i) => formatMoney(i.orderHeader.grandTotal),
      },
    
      // Order status
      {
        key: "orderStatus",
        header: "Order Status",
        getValue: (i) => i.orderHeader.status?.label || "",
      },
    
      // Recipient/shipping address (up to 7 lines)
      {
        key: "recipient",
        header: "Recipient",
        getValue: (i) => i.orderHeader.recipient || "",
      },
      {
        key: "addressLine1",
        header: "Address Line 1",
        getValue: (i) => i.orderHeader.shippingAddress?.line1 || "",
      },
      {
        key: "addressLine2",
        header: "Address Line 2",
        getValue: (i) => i.orderHeader.shippingAddress?.line2 || "",
      },
      {
        key: "addressLine3",
        header: "Address Line 3",
        getValue: (i) => i.orderHeader.shippingAddress?.line3 || "",
      },
      {
        key: "addressLine4",
        header: "Address Line 4",
        getValue: (i) => i.orderHeader.shippingAddress?.line4 || "",
      },
      {
        key: "addressLine5",
        header: "Address Line 5",
        getValue: (i) => i.orderHeader.shippingAddress?.line5 || "",
      },
      {
        key: "addressLine6",
        header: "Address Line 6",
        getValue: (i) => i.orderHeader.shippingAddress?.line6 || "",
      },
      {
        key: "addressLine7",
        header: "Address Line 7",
        getValue: (i) => i.orderHeader.shippingAddress?.line7 || "",
      },
    
      // Payment
      {
        key: "paymentMethod",
        header: "Payment Method",
        getValue: (i) => i.orderHeader.paymentMethod?.type || "",
      },
      {
        key: "paymentLastFour",
        header: "Card Last 4",
        getValue: (i) => i.orderHeader.paymentMethod?.lastFour || "",
      },
    
      // URLs
      { key: "productUrl", header: "Product URL", getValue: (i) => i.url || "" },
      { key: "imageUrl", header: "Image URL", getValue: (i) => i.imageUrl || "" },
      {
        key: "orderUrl",
        header: "Order URL",
        getValue: (i) => i.orderHeader.detailUrl,
      },
    
      // Region
      { key: "region", header: "Region", getValue: (i) => i.orderHeader.region },
    ];
Behavior4/5

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

With no annotations provided, the description carries full burden and does well by disclosing key behavioral traits: it visits each order's invoice page, extracts item-level data, provides performance estimate (~2s/order), and lists all CSV columns. It doesn't mention authentication requirements, rate limits, or error handling, but covers the core operation thoroughly.

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 efficiently structured with two sentences: first states the core operation with performance context, second lists CSV columns and use cases. Every element adds value without redundancy, and it's appropriately front-loaded with the most important information.

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?

For a tool with no annotations and no output schema, the description provides substantial context: operation method, performance characteristics, output format details, and use cases. It could benefit from mentioning authentication requirements (implied by sibling check_amazon_auth_status) and error scenarios, but covers the essential behavioral aspects well.

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%, so the schema already documents all parameters thoroughly. The description doesn't add meaningful parameter semantics beyond what's in the schema - it mentions CSV columns but doesn't explain how parameters like region or max_orders affect the extraction process. Baseline 3 is appropriate when schema does the heavy lifting.

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 the tool exports Amazon order items to CSV with specific details about data extraction from invoice pages (~2s/order). It distinguishes from sibling tools like export_amazon_orders_csv by focusing on item-level data rather than order-level summaries.

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

Usage Guidelines4/5

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

The description provides clear context for when to use this tool ('ideal for expense tracking, inventory analysis, or accounting exports') and mentions the performance characteristic (~2s/order). However, it doesn't explicitly contrast with alternatives like export_amazon_orders_csv or get_amazon_order_details, which could help users choose between similar tools.

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/marcusquinn/amazon-order-history-csv-download-mcp'

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