Skip to main content
Glama

Search Amazon.in

search_amazon_in
Read-onlyIdempotent

Search Amazon India for products by keyword and get ranked results with cheapest in-stock and best-value picks.

Instructions

Search amazon.in for products by keyword and return ranked listings.

This tool scrapes the public amazon.in search page (no API key needed). It returns a normalised list of results plus two convenience picks:

  • cheapest_in_stock: lowest price among listings showing stock

  • best_value: weighted score = rating × log10(reviews+10) / sqrt(price), requires >=10 reviews

Args:

  • query (string, 2-200 chars): search keywords

  • max_results (int, 1-20, default 5): number of listings to return

  • include_sponsored (bool, default false): include ad listings

Returns: JSON with schema: { "query": string, "total_results": number, "results": [ { "asin": string, "title": string, "url": string, "image": string, "price_inr": number, "price_display": string, "mrp_inr": number, "rating": number, "review_count": number, "prime": boolean, "sponsored": boolean, "in_stock": boolean, "delivery": string, "price_history_url": string } ], "cheapest_in_stock": , "best_value": }

Error handling:

  • "Amazon served a bot-check page" → wait 30-60s and retry

  • "Failed to reach amazon.in" → transient network or throttling

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesKeyword search query (e.g., 'bluetooth speaker under 2000')
max_resultsNoMaximum listings to return (1-20). Default 5.
include_sponsoredNoInclude sponsored / ad listings. Defaults to false.

Implementation Reference

  • src/index.ts:148-230 (registration)
    Tool registration of 'search_amazon_in' via server.registerTool() with input schema, description, and the async handler function.
    server.registerTool(
      "search_amazon_in",
      {
        title: "Search Amazon.in",
        description: `Search amazon.in for products by keyword and return ranked listings.
    
    This tool scrapes the public amazon.in search page (no API key needed). It returns a normalised list of results plus two convenience picks:
     - cheapest_in_stock: lowest price among listings showing stock
     - best_value: weighted score = rating × log10(reviews+10) / sqrt(price), requires >=10 reviews
    
    Args:
      - query (string, 2-200 chars): search keywords
      - max_results (int, 1-20, default 5): number of listings to return
      - include_sponsored (bool, default false): include ad listings
    
    Returns: JSON with schema:
      {
        "query": string,
        "total_results": number,
        "results": [
          {
            "asin": string,
            "title": string,
            "url": string,
            "image": string,
            "price_inr": number,
            "price_display": string,
            "mrp_inr": number,
            "rating": number,
            "review_count": number,
            "prime": boolean,
            "sponsored": boolean,
            "in_stock": boolean,
            "delivery": string,
            "price_history_url": string
          }
        ],
        "cheapest_in_stock": <SearchResultItem>,
        "best_value": <SearchResultItem>
      }
    
    Error handling:
      - "Amazon served a bot-check page" → wait 30-60s and retry
      - "Failed to reach amazon.in" → transient network or throttling`,
        inputSchema: SearchInputSchema.shape,
        annotations: {
          readOnlyHint: true,
          destructiveHint: false,
          idempotentHint: true,
          openWorldHint: true,
        },
      },
      async (params) => {
        try {
          const q = encodeURIComponent(params.query);
          const url = `${AMAZON_BASE}/s?k=${q}`;
          const html = await fetchHtml(url);
          let items = parseSearch(html);
    
          if (!params.include_sponsored) {
            items = items.filter((it) => !it.sponsored);
          }
    
          const limited = items.slice(0, params.max_results);
          const ranks = rankResults(limited);
    
          const output: RankedResults = {
            query: params.query,
            total_results: limited.length,
            results: limited,
            ...ranks,
          };
    
          const text = JSON.stringify(output, null, 2);
          return {
            content: [{ type: "text", text: truncate(text, output) }],
            structuredContent: output as unknown as Record<string, unknown>,
          };
        } catch (err) {
          return { content: [{ type: "text", text: friendlyError(err) }] };
        }
      }
    );
  • The async handler function for search_amazon_in: encodes query, fetches HTML, parses search results, filters sponsored items, limits results, ranks by cheapest/best-value, and returns JSON.
      async (params) => {
        try {
          const q = encodeURIComponent(params.query);
          const url = `${AMAZON_BASE}/s?k=${q}`;
          const html = await fetchHtml(url);
          let items = parseSearch(html);
    
          if (!params.include_sponsored) {
            items = items.filter((it) => !it.sponsored);
          }
    
          const limited = items.slice(0, params.max_results);
          const ranks = rankResults(limited);
    
          const output: RankedResults = {
            query: params.query,
            total_results: limited.length,
            results: limited,
            ...ranks,
          };
    
          const text = JSON.stringify(output, null, 2);
          return {
            content: [{ type: "text", text: truncate(text, output) }],
            structuredContent: output as unknown as Record<string, unknown>,
          };
        } catch (err) {
          return { content: [{ type: "text", text: friendlyError(err) }] };
        }
      }
    );
  • Zod schema SearchInputSchema defines input validation for query (2-200 chars), max_results (1-20, default 5), and include_sponsored (boolean, default false).
    const SearchInputSchema = z
      .object({
        query: z
          .string()
          .min(2, "Query must be at least 2 characters")
          .max(200, "Query must not exceed 200 characters")
          .describe("Keyword search query (e.g., 'bluetooth speaker under 2000')"),
        max_results: z
          .number()
          .int()
          .min(1)
          .max(20)
          .default(5)
          .describe("Maximum listings to return (1-20). Default 5."),
        include_sponsored: z
          .boolean()
          .default(false)
          .describe("Include sponsored / ad listings. Defaults to false."),
      })
      .strict();
  • rankResults() helper: finds cheapest_in_stock and best_value items from search results using a scoring algorithm (rating * log10(reviews+smoothing) / sqrt(price)).
    function rankResults(items: SearchResultItem[]): {
      cheapest_in_stock?: SearchResultItem;
      best_value?: SearchResultItem;
    } {
      const inStock = items.filter(
        (it) => it.in_stock && typeof it.price_inr === "number"
      );
      if (!inStock.length) return {};
    
      const cheapest_in_stock = [...inStock].sort(
        (a, b) => (a.price_inr ?? Infinity) - (b.price_inr ?? Infinity)
      )[0];
    
      // Best value: rating × log10(reviews + smoothing) / sqrt(price).
      // Requires at least MIN_REVIEWS_FOR_BEST_VALUE reviews to avoid noisy picks.
      const scored = inStock
        .filter(
          (it) =>
            typeof it.rating === "number" &&
            typeof it.review_count === "number" &&
            (it.review_count ?? 0) >= MIN_REVIEWS_FOR_BEST_VALUE
        )
        .map((it) => ({
          it,
          score:
            (it.rating! * Math.log10(it.review_count! + LOG_REVIEWS_SMOOTHING)) /
            Math.sqrt(it.price_inr!),
        }))
        .sort((a, b) => b.score - a.score);
    
      const result: ReturnType<typeof rankResults> = {};
      if (cheapest_in_stock) result.cheapest_in_stock = cheapest_in_stock;
      if (scored.length) result.best_value = scored[0]!.it;
      return result;
    }
  • parseSearch() helper: parses Amazon.in search result HTML using cheerio, extracting ASIN, title, price, rating, delivery info for each result card.
    export function parseSearch(html: string): SearchResultItem[] {
      const $: CheerioAPI = cheerio.load(html);
      const items: SearchResultItem[] = [];
    
      $('div[data-component-type="s-search-result"]').each((_, el) => {
        const card = $(el);
        const asin = (card.attr("data-asin") || "").trim();
        if (!asin || !ASIN_REGEX.test(asin)) return;
    
        const item = buildSearchItem(card, asin);
        if (item) items.push(item);
      });
    
      return items;
    }
Behavior4/5

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

Annotations already confirm read-only, idempotent behavior. Description adds scraping method, convenience picks computation, and error handling (bot-check retry), which are useful beyond annotations. Could mention rate limits but still strong.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness4/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with clear first sentence and bullet-pointed sections. Includes full return schema which is lengthy but necessary given no output schema. Could be slightly trimmed but effective.

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?

Covers input constraints, output fields, error conditions, and convenience picks. Missing rate limits or blocking details beyond bot-check, but sufficient for a scraping tool with annotations.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema coverage is 100%, so baseline is 3. Description adds value by detailing return schema (including computed fields like cheapest_in_stock, best_value) and examples, helping understand parameter impact.

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?

Clearly states it searches Amazon.in by keyword and returns ranked listings, with specific verb+resource. Distinguishes from siblings (get_product, price_history_link) by focusing on search.

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?

Indicates scraping public search page and no API key needed, but lacks explicit when-to-use vs alternatives or exclusions. Error handling provides some context, but no direct comparison to siblings.

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/justadityaraj/amazon-in-mcp'

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