Skip to main content
Glama
marcusquinn

Amazon Order History CSV Download MCP

by marcusquinn

export_amazon_orders_csv

Download Amazon order history as CSV files with order details, item counts, addresses, and subscription data for analysis or record-keeping across 16 regional sites.

Instructions

Export Amazon orders summary to CSV file. Fast extraction from order list page (~0.5s per 10 orders). CSV columns: Order ID, Date, Total, Status, Item Count, Address (7 lines), Subscribe & Save, Platform, Region, Order URL. Defaults to ~/Downloads with auto-generated filename. For large accounts (500+ orders), use max_orders to batch exports and avoid timeouts.

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}-orders-{year}-{date}.csv
max_ordersNoMaximum number of orders to export. Recommended: 100-200 per batch for large accounts.

Implementation Reference

  • Core handler function that executes the CSV export logic: transforms OrderCSVData[] using predefined ORDER_CSV_COLUMNS and writes to the specified output file path.
    export async function exportOrdersCSV(
      orders: OrderCSVData[],
      outputPath: string,
    ): Promise<ExportResult> {
      try {
        const csv = toCSVWithColumns(orders, ORDER_CSV_COLUMNS);
        await writeFile(outputPath, csv, "utf-8");
    
        return {
          success: true,
          filePath: outputPath,
          rowCount: orders.length,
        };
      } catch (error) {
        return {
          success: false,
          filePath: outputPath,
          rowCount: 0,
          error: String(error),
        };
      }
    }
  • Tool definition including name, description, and input schema for validation.
      name: "export_amazon_orders_csv",
      description:
        "Export Amazon orders summary to CSV file. Fast extraction from order list page (~0.5s per 10 orders). CSV columns: Order ID, Date, Total, Status, Item Count, Address (7 lines), Subscribe & Save, Platform, Region, Order URL. Defaults to ~/Downloads with auto-generated filename. For large accounts (500+ orders), use max_orders to batch exports and avoid timeouts.",
      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}-orders-{year}-{date}.csv",
          },
          max_orders: {
            type: "number",
            description:
              "Maximum number of orders to export. Recommended: 100-200 per batch for large accounts.",
          },
        },
        required: ["region"],
      },
    },
  • MCP tool dispatcher: validates parameters, fetches orders, generates output path, calls exportOrdersCSV, computes timing estimates, and returns JSON response with file path and metadata.
    case "export_amazon_orders_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,
        "orders",
        region,
        { year, startDate, endDate },
      );
    
      const fetchResult = await fetchOrders(currentPage, amazonPlugin, {
        region,
        year,
        startDate,
        endDate,
        includeItems: false,
        includeShipments: false,
        maxOrders,
      });
    
      // Calculate time estimate for informational purposes
      const timeEstimate = estimateExtractionTime(fetchResult.orders.length, {
        includeItems: false,
        includeShipments: false,
      });
    
      const exportResult = await exportOrdersCSV(
        fetchResult.orders,
        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,
                // Include timing info for transparency
                timing: {
                  orderCount: fetchResult.orders.length,
                  estimate: timeEstimate.formattedEstimate,
                  warnings: timeEstimate.warnings,
                  recommendations: timeEstimate.recommendations,
                },
              },
              null,
              2,
            ),
          },
        ],
      };
    }
  • Defines the column structure and formatting functions for order CSV export, used by exportOrdersCSV.
    export const ORDER_CSV_COLUMNS: CSVColumn<OrderCSVData>[] = [
      // Identification
      { key: "orderId", header: "Order ID", getValue: (o) => o.id },
      { key: "date", header: "Order Date", getValue: (o) => formatDate(o.date) },
    
      // Financial - only Total is reliably available from list view
      { key: "total", header: "Total", getValue: (o) => formatMoney(o.total) },
    
      // Status
      { key: "status", header: "Status", getValue: (o) => o.status?.label || "" },
    
      // Items count (from order list page)
      {
        key: "itemCount",
        header: "Items",
        getValue: (o) => o.itemCount ?? o.items?.length ?? 0,
      },
    
      // Shipping address (up to 7 lines) - available from order card popover
      {
        key: "addressLine1",
        header: "Address Line 1",
        getValue: (o) => o.shippingAddress?.line1 || "",
      },
      {
        key: "addressLine2",
        header: "Address Line 2",
        getValue: (o) => o.shippingAddress?.line2 || "",
      },
      {
        key: "addressLine3",
        header: "Address Line 3",
        getValue: (o) => o.shippingAddress?.line3 || "",
      },
      {
        key: "addressLine4",
        header: "Address Line 4",
        getValue: (o) => o.shippingAddress?.line4 || "",
      },
      {
        key: "addressLine5",
        header: "Address Line 5",
        getValue: (o) => o.shippingAddress?.line5 || "",
      },
      {
        key: "addressLine6",
        header: "Address Line 6",
        getValue: (o) => o.shippingAddress?.line6 || "",
      },
      {
        key: "addressLine7",
        header: "Address Line 7",
        getValue: (o) => o.shippingAddress?.line7 || "",
      },
    
      // Subscribe & Save frequency (e.g., "Every 1 month")
      {
        key: "subscribeAndSave",
        header: "Subscribe & Save",
        getValue: (o) => o.subscribeAndSave || "",
      },
    
      // Platform/region
      { key: "platform", header: "Platform", getValue: (o) => o.platform || "" },
      { key: "region", header: "Region", getValue: (o) => o.region },
    
      // URL
      { key: "detailUrl", header: "Order URL", getValue: (o) => o.detailUrl },
    ];
  • Helper function to generate default output file path in ~/Downloads with descriptive filename based on region, type, and date range.
    export function getOutputPath(
      outputPath: string | undefined,
      exportType: "orders" | "items" | "shipments" | "transactions" | "gift-cards",
      region: string,
      options?: {
        year?: number;
        startDate?: string;
        endDate?: string;
      },
    ): string {
      if (outputPath) {
        return outputPath;
      }
    
      const filename = generateExportFilename(exportType, region, options);
      return join(getDefaultDownloadsPath(), filename);
    }

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