Skip to main content
Glama
marcusquinn

Amazon Order History CSV Download MCP

by marcusquinn

export_amazon_shipments_csv

Export Amazon shipment tracking data to CSV for delivery monitoring and shipment reconciliation. Extracts tracking information, status, and delivery details from order history.

Instructions

Export Amazon shipment tracking data to CSV file. Visits each order's detail page to extract tracking info (~4s/order). CSV columns: Order ID, Date, Shipment ID, Status, Delivered (Yes/No/Unknown), Tracking ID, Tracking URL, Items in Shipment, Item Names, Payment Amount, Refund. Useful for tracking deliveries and reconciling shipments.

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}-shipments-{year}-{date}.csv
max_ordersNoMaximum number of orders to process. Recommended: 25-50 per batch due to ~4s/order extraction time.
fetch_tracking_numbersNoExtract actual carrier tracking numbers (e.g., AZ218181365JE) by visiting each shipment's 'Track package' page. Adds ~2s per shipment.

Implementation Reference

  • src/index.ts:301-344 (registration)
    Tool registration including name, description, and input schema definition.
    {
      name: "export_amazon_shipments_csv",
      description:
        "Export Amazon shipment tracking data to CSV file. Visits each order's detail page to extract tracking info (~4s/order). CSV columns: Order ID, Date, Shipment ID, Status, Delivered (Yes/No/Unknown), Tracking ID, Tracking URL, Items in Shipment, Item Names, Payment Amount, Refund. Useful for tracking deliveries and reconciling shipments.",
      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}-shipments-{year}-{date}.csv",
          },
          max_orders: {
            type: "number",
            description:
              "Maximum number of orders to process. Recommended: 25-50 per batch due to ~4s/order extraction time.",
          },
          fetch_tracking_numbers: {
            type: "boolean",
            description:
              "Extract actual carrier tracking numbers (e.g., AZ218181365JE) by visiting each shipment's 'Track package' page. Adds ~2s per shipment.",
            default: false,
          },
        },
        required: ["region"],
      },
    },
  • Main MCP tool handler: validates input, fetches orders with shipment details, exports to CSV, returns file path and stats.
    case "export_amazon_shipments_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 fetchTrackingNumbers = args?.fetch_tracking_numbers as
        | boolean
        | undefined;
      const outputPath = getOutputPath(
        args?.output_path as string | undefined,
        "shipments",
        region,
        { year, startDate, endDate },
      );
    
      const fetchResult = await fetchOrders(currentPage, amazonPlugin, {
        region,
        year,
        startDate,
        endDate,
        includeItems: false,
        includeShipments: true,
        fetchTrackingNumbers: fetchTrackingNumbers ?? false,
        maxOrders,
      });
    
      const timeEstimate = estimateExtractionTime(fetchResult.orders.length, {
        includeItems: false,
        includeShipments: true,
      });
    
      const exportResult = await exportShipmentsCSV(
        fetchResult.shipments,
        outputPath,
      );
    
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              {
                status: exportResult.success ? "success" : "error",
                params: {
                  region,
                  year,
                  startDate,
                  endDate,
                  maxOrders,
                  fetchTrackingNumbers,
                  outputPath,
                },
                filePath: exportResult.filePath,
                rowCount: exportResult.rowCount,
                error: exportResult.error,
                fetchErrors: fetchResult.errors,
                timing: {
                  orderCount: fetchResult.orders.length,
                  shipmentCount: fetchResult.shipments.length,
                  estimate: timeEstimate.formattedEstimate,
                  warnings: timeEstimate.warnings,
                  recommendations: timeEstimate.recommendations,
                },
              },
              null,
              2,
            ),
          },
        ],
      };
    }
  • Core CSV export function for shipments: converts shipment data to CSV using predefined columns and writes to file.
    export async function exportShipmentsCSV(
      shipments: Shipment[],
      outputPath: string,
    ): Promise<ExportResult> {
      try {
        const csv = toCSVWithColumns(shipments, SHIPMENT_CSV_COLUMNS);
        await writeFile(outputPath, csv, "utf-8");
    
        return {
          success: true,
          filePath: outputPath,
          rowCount: shipments.length,
        };
      } catch (error) {
        return {
          success: false,
          filePath: outputPath,
          rowCount: 0,
          error: String(error),
        };
      }
    }
  • CSV column definitions and formatters specific to shipment data export.
    export const SHIPMENT_CSV_COLUMNS: CSVColumn<Shipment>[] = [
      { key: "orderId", header: "Order ID", getValue: (s) => s.orderHeader.id },
      {
        key: "orderDate",
        header: "Order Date",
        getValue: (s) => formatDate(s.orderHeader.date),
      },
      { key: "shipmentId", header: "Shipment ID", getValue: (s) => s.shipmentId },
      { key: "status", header: "Status", getValue: (s) => s.status },
      {
        key: "delivered",
        header: "Delivered",
        getValue: (s) => {
          switch (s.delivered) {
            case DeliveryStatus.YES:
              return "Yes";
            case DeliveryStatus.NO:
              return "No";
            default:
              return "Unknown";
          }
        },
      },
      { key: "trackingId", header: "Tracking ID", getValue: (s) => s.trackingId },
      { key: "carrier", header: "Carrier", getValue: (s) => s.carrier || "" },
      {
        key: "trackingLink",
        header: "Tracking URL",
        getValue: (s) => s.trackingLink,
      },
      {
        key: "itemCount",
        header: "Items in Shipment",
        getValue: (s) => s.items.length,
      },
      {
        key: "itemNames",
        header: "Item Names",
        getValue: (s) => s.items.map((i) => i.name).join("; "),
      },
      {
        key: "paymentAmount",
        header: "Payment Amount",
        getValue: (s) =>
          formatMoney(s.transaction?.paymentAmount) ||
          formatMoney(s.orderHeader.total),
      },
      { key: "refund", header: "Refund", getValue: (s) => formatMoney(s.refund) },
      { key: "region", header: "Region", getValue: (s) => s.orderHeader.region },
    ];
  • Generates default output file path for shipments CSV (used in main handler).
    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 full burden and does well by disclosing key behavioral traits: it reveals the operation visits each order's detail page (~4s/order), mentions the optional tracking number extraction adds ~2s per shipment, and describes the CSV output format. However, it doesn't cover error handling, authentication requirements, or rate limits.

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 appropriately sized and front-loaded: the first sentence states the core purpose, subsequent sentences add important behavioral context (processing time, CSV columns), and the final sentence provides usage context. Every sentence earns its place with zero waste.

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 complexity (7 parameters, no annotations, no output schema), the description provides good context about the operation's behavior, timing, and output format. However, it doesn't explain what happens on failure, whether authentication is required, or provide examples of the CSV output. For a tool with no annotations or output schema, it could be more complete about error cases.

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 7 parameters thoroughly. The description doesn't add any parameter-specific information beyond what's in the schema descriptions. It mentions CSV columns which relate to output, not input parameters. 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's purpose with specific verbs ('export', 'extract') and resources ('Amazon shipment tracking data', 'CSV file'), and distinguishes it from siblings by focusing on shipment tracking rather than orders, transactions, or gift cards. It specifies the data source (order detail pages) and processing characteristics.

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 ('useful for tracking deliveries and reconciling shipments'), but doesn't explicitly state when not to use it or name alternatives among sibling tools. It implies usage for CSV export of shipment data but lacks explicit comparison with other export 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