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);
    }
Behavior4/5

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

With no annotations provided, the description carries the full burden and does well by disclosing performance traits ('~0.5s per 10 orders'), output details (CSV columns and default save location), and operational constraints (batching advice for large accounts to avoid timeouts). It doesn't mention authentication requirements or error handling, leaving some gaps.

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 front-loaded with the core purpose, followed by performance details, output specifics, and usage advice in three efficient sentences. Every sentence adds value without redundancy, making it appropriately sized and well-structured.

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's moderate complexity (6 parameters, no output schema, no annotations), the description is largely complete: it covers purpose, performance, output format, defaults, and scaling advice. However, it lacks details on authentication, error cases, or what happens on failure, which would be helpful for a tool with no annotations.

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 adds marginal value by explaining the default filename pattern and batching recommendation for max_orders, but doesn't provide additional semantic context beyond what's in the schema descriptions.

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 specific action ('Export Amazon orders summary to CSV file') and resource ('Amazon orders'), distinguishing it from siblings like export_amazon_items_csv or export_amazon_transactions_csv by focusing on orders summary rather than items, transactions, or other data types.

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 ('Fast extraction from order list page') and includes an explicit alternative for large accounts ('use max_orders to batch exports and avoid timeouts'), but it doesn't explicitly state when NOT to use it versus other sibling tools like get_amazon_orders or export_amazon_items_csv.

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