Skip to main content
Glama
marcusquinn

Amazon Order History CSV Download MCP

by marcusquinn

get_amazon_gift_card_balance

Check Amazon gift card balance and view transaction history across multiple pages for any supported Amazon region.

Instructions

Get current Amazon gift card balance and transaction history. Returns: current balance, last updated timestamp, and paginated transaction history (date, description, amount, closing balance, type, associated order ID, claim code, serial number). Supports fetching complete history across multiple pages.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
regionYesAmazon region code
max_pagesNoMaximum pages of transaction history to fetch. Default: 10. Set to 0 for unlimited.
fetch_all_pagesNoAutomatically paginate through all available transaction history. Default: true.

Implementation Reference

  • src/index.ts:411-438 (registration)
    MCP tool registration including name, description, and input schema for get_amazon_gift_card_balance.
    {
      name: "get_amazon_gift_card_balance",
      description:
        "Get current Amazon gift card balance and transaction history. Returns: current balance, last updated timestamp, and paginated transaction history (date, description, amount, closing balance, type, associated order ID, claim code, serial number). Supports fetching complete history across multiple pages.",
      inputSchema: {
        type: "object",
        properties: {
          region: {
            type: "string",
            description: "Amazon region code",
            enum: getRegionCodes(),
          },
          max_pages: {
            type: "number",
            description:
              "Maximum pages of transaction history to fetch. Default: 10. Set to 0 for unlimited.",
            default: 10,
          },
          fetch_all_pages: {
            type: "boolean",
            description:
              "Automatically paginate through all available transaction history. Default: true.",
            default: true,
          },
        },
        required: ["region"],
      },
    },
  • MCP server handler for the tool call: validates input, calls extractGiftCardData, formats response as JSON.
    case "get_amazon_gift_card_balance": {
      const regionParam = args?.region as string | undefined;
      const regionError = validateRegion(regionParam, args);
      if (regionError) return regionError;
      const region = regionParam!;
    
      const currentPage = await getPage();
      const maxPages = (args?.max_pages as number) ?? 10;
      const fetchAllPages = (args?.fetch_all_pages as boolean) ?? true;
    
      const giftCardData = await extractGiftCardData(currentPage, region, {
        maxPages,
        fetchAllPages,
      });
    
      return {
        content: [
          {
            type: "text",
            text: JSON.stringify(
              {
                status: "success",
                params: {
                  region,
                  maxPages,
                  fetchAllPages,
                },
                balance: giftCardData.balance.balance,
                lastUpdated: giftCardData.balance.lastUpdated.toISOString(),
                transactionCount: giftCardData.transactions.length,
                transactions: giftCardData.transactions.map((t) => ({
                  date: t.date.toISOString(),
                  description: t.description,
                  amount: t.amount,
                  closingBalance: t.closingBalance,
                  type: t.type,
                  orderId: t.orderId,
                  claimCode: t.claimCode,
                  serialNumber: t.serialNumber,
                })),
              },
              null,
              2,
            ),
          },
        ],
      };
    }
  • Core tool handler: navigates to Amazon gift card balance page (/gc/balance), extracts current balance, loops through paginated transaction table extracting dates, descriptions, amounts, closing balances, order IDs, claim codes, serial numbers, and transaction types.
    export async function extractGiftCardData(
      page: Page,
      region: string,
      options: GiftCardExtractionOptions = {},
    ): Promise<GiftCardData> {
      const { maxPages = 10, fetchAllPages = true } = options;
      const regionConfig = getRegionByCode(region);
      const currency = regionConfig?.currency || "USD";
      const url = getGiftCardPageUrl(region);
    
      // Navigate to gift card balance page
      await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30000 });
    
      // Wait for the balance table to load
      await page
        .waitForSelector(
          'table.a-bordered tbody tr, [data-testid="gc-balance"], #gc-balance',
          { timeout: 10000 },
        )
        .catch(() => {});
    
      // Extract balance (from first row's closing balance, or dedicated element)
      const balance = await extractBalance(page, currency);
    
      // Extract transactions from all pages
      const allTransactions: GiftCardTransaction[] = [];
      let pageCount = 0;
    
      let hasMorePages = true;
      while (hasMorePages) {
        pageCount++;
    
        // Extract transactions from current page
        const pageTransactions = await extractTransactionsFromTable(page, currency);
        allTransactions.push(...pageTransactions);
    
        // Check if we should continue to next page
        if (!fetchAllPages) {
          hasMorePages = false;
          continue;
        }
        if (maxPages > 0 && pageCount >= maxPages) {
          hasMorePages = false;
          continue;
        }
    
        // Check for and click "Next" pagination button
        hasMorePages = await goToNextGiftCardPage(page);
    
        // Wait for the new page content to load
        await page.waitForTimeout(500);
        await page
          .waitForSelector("table.a-bordered tbody tr", { timeout: 5000 })
          .catch(() => {});
      }
    
      // Deduplicate transactions (in case of overlap between pages)
      const uniqueTransactions = deduplicateTransactions(allTransactions);
    
      return {
        balance,
        transactions: uniqueTransactions,
        region,
      };
    }
  • TypeScript interfaces defining the structure of gift card balance and transaction data returned by the tool.
    export interface GiftCardBalance {
      balance: Money;
      lastUpdated: Date;
    }
    
    /**
     * Gift card transaction types.
     */
    export type GiftCardTransactionType =
      | "applied" // Gift card applied to order (debit)
      | "refund" // Refund credited back to gift card balance
      | "added" // Gift card added/redeemed (credit)
      | "reload" // Gift card reloaded (credit)
      | "promotional" // Promotional credit added
      | "unknown";
    
    /**
     * Gift card transaction entry.
     * Note: This is separate from the order Transaction type as it represents
     * gift card balance activity, not payment transactions.
     */
    export interface GiftCardTransaction {
      /** Transaction date */
      date: Date;
    
      /** Human-readable description */
      description: string;
    
      /** Transaction amount (negative for debits, positive for credits) */
      amount: Money;
    
      /** Closing balance after this transaction */
      closingBalance: Money;
    
      /** Transaction type */
      type: GiftCardTransactionType;
    
      /** Associated order ID (if applicable) */
      orderId?: string;
    
      /** Gift card claim code (for 'added' type, partially masked) */
      claimCode?: string;
    
      /** Gift card serial number (for 'added' type) */
      serialNumber?: string;
    }
    
    /**
     * Complete gift card data.
     */
    export interface GiftCardData {
      /** Current gift card balance */
      balance: GiftCardBalance;
    
      /** Transaction history */
      transactions: GiftCardTransaction[];
    
      /** Region this data was extracted from */
      region: string;
    }
  • Helper function to detect and click the 'Next' pagination button on the gift card activity pages.
    async function goToNextGiftCardPage(page: Page): Promise<boolean> {
      try {
        // Look for the "Next" link in the pagination
        const nextLink = page
          .locator(
            'ul.a-pagination li.a-last a, ul.a-pagination a:has-text("Next")',
          )
          .first();
    
        if ((await nextLink.count()) === 0) {
          return false;
        }
    
        // Check if the link is disabled (no href or disabled class)
        const href = await nextLink.getAttribute("href");
        if (!href) {
          return false;
        }
    
        // Click the next link
        await nextLink.click();
    
        // Wait for navigation
        await page.waitForLoadState("domcontentloaded", { timeout: 10000 });
    
        return true;
      } catch {
        return false;
      }
    }
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 of behavioral disclosure. It effectively describes key behaviors: it returns current balance, timestamp, and paginated transaction history with specific fields, and supports multi-page fetching. However, it does not mention authentication needs, rate limits, or error handling, leaving some gaps for a read operation.

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 in the first sentence, followed by detailed return values and pagination support. Every sentence adds value without redundancy, making it efficient and well-structured for quick understanding.

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 no annotations and no output schema, the description compensates well by detailing return values (balance, timestamp, transaction fields) and pagination behavior. It covers the tool's functionality adequately for a read operation, though it could improve by mentioning authentication or error scenarios for full completeness.

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 fully documents parameters like 'region', 'max_pages', and 'fetch_all_pages'. The description adds no additional parameter semantics beyond what the schema provides, such as explaining region implications or pagination details. Baseline 3 is appropriate as the schema handles 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 specific action ('Get current Amazon gift card balance and transaction history') and distinguishes it from siblings like 'get_amazon_gift_card_transactions' by emphasizing it returns both balance and paginated history. It explicitly names the resource (Amazon gift card) and verb (get), making the purpose unambiguous.

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

Usage Guidelines3/5

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

The description implies usage for retrieving gift card data but does not explicitly state when to use this tool versus alternatives like 'get_amazon_gift_card_transactions' or 'export_amazon_gift_cards_csv'. It mentions pagination support, which hints at context for large datasets, but lacks clear guidance on prerequisites or exclusions.

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