I built a small Node.js price check on , which gives AI agents ecommerce data over MCP: product search in shops worldwide, and every seller's offer for one product. I asked it about one product, Sony's WH-1000XM5 headphones, in Malaysia, Singapore and Indonesia.
Getting prices was easy. Getting a cheapest price you'd stake a recommendation on took seven checks. Here they are, each with what the live data returned.
Where the checks fit
1. Match the exact model, not a lookalike name
Search for the WH-1000XM5 and you also get the WF-1000XM5, which are earbuds, plus the older WH-1000XM4 and the newer WH-1000XM6. On Amazon Singapore, the search returned no priced WH-1000XM5 at all: just the XM6, rival brands and accessories.
Treat the words with a digit in them as the model, and match them loosely, because shops write the same product as WH-1000XM5, WH1000XM5 and WH 1000 XM5.
2. Leave out accessories
A title where the model comes after “for”, or after words like “ear pads”, “case” or “replacement”, is selling an add-on: “Earpads for Sony WH-1000XM5”. In Singapore, one of the four listings across shops was ear pads. Skip this check, and an agent can recommend a set of ear pads as the deal of the day.
3. Check where the seller is
Asked for Malaysian offers, the data marked some shops as abroad, like Desertcart in the UAE. Others came back with no country at all, so they looked local: a Hong Kong shop, an Indian shop, a Spanish one, and an eBay seller with RM 292.22 delivery.
Leave out what's marked abroad, and label the rest “country not given” instead of calling them local. It matters: after every other check, the cheapest offer was the Hong Kong shop.
4. Set aside prices that can't be real
Every seller's offer for Sony Store Malaysia's listing ran from RM 38.90 to RM 2,383.63, and the product's headline price was the lowest of them: RM 38.90, for headphones Sony sells at RM 1,399. On Lazada's own search it was starker:
Cheapest first: 4 listings
1. MYR 775.00 lazada.com.my
2. MYR 1,099.00 lazada.com.my
3. MYR 1,199.00 lazada.com.my
4. MYR 1,499.00 lazada.com.my
Set aside, far below the rest (the median price is RM 46.35). Check these listings before trusting them:
MYR 38.00 lazada.com.my below a 4x jump in price
MYR 38.90 lazada.com.my below a 4x jump in price
...14 more, from MYR 38.90 to MYR 80.00A median alone wouldn't have caught these. The cheap listings outnumbered the real ones 16 to 4, so the median, RM 46.35, was itself one of the cheap prices. What gave them away was the jump from RM 80 to RM 775.
So set aside anything under half the median, or below a 4x jump between neighbouring prices, and show it as “check before trusting” rather than dropping it. Prices can be impossible the other way, too: one Shopee Indonesia search came back 100,000 times too high, because Shopee stores prices with a scale factor and that answer missed it. Three later runs were right.
5. Skip what's out of stock, and compare with delivery
Delivery reorders the list. The cheapest real offer was RM 996.68 plus RM 40.42 delivery, Sony Store's RM 1,399 came with free delivery, and one shop's RM 1,799 came with RM 350 of it. Rank by price with delivery where the shop gives it, mark the rest “delivery cost not given”, and leave out what's out of stock.
Here are all five checks together, on every seller's offer for Sony Store Malaysia's listing:
Cheapest first, with delivery where the shop gives it: 15 offers
1. RM 1,037.10 友和 Yoho RM 996.68 + RM 40.42 delivery; country not given
3. RM 1,110.96 Harsha delivery cost not given; ask the shop about stock; country not given
4. RM 1,195.00 Shopee delivery cost not given
5. RM 1,238.00 Music Bliss Malaysia RM 1,230.00 + RM 8.00 delivery
8. RM 1,399.00 Sony Store Malaysia free delivery
15. RM 2,149.00 allithypermarket.com.my RM 1,799.00 + RM 350.00 delivery
Set aside, far below the rest (the median price is RM 1,329.00). Check these listings before trusting them:
RM 38.90 Lazada Malaysia under half the median price; below a 4x jump in price
RM 600.00 CeX under half the median price
Left out:
5 from shops outside MY (cheapest: RM 1,480.42 at Desertcart.ae)
2 out of stock
1 whose title doesn't name WH-1000XM5 or looks like an accessory6. Don't stop at one shop's search
Harvey Norman Malaysia's own search returned no_results, half an hour after the search across Malaysian shops had found its RM 1,399 listing. And the list of sellers depends on where you start: Sony Store's listing led to 25 offers, Shopee's to 5.
If one shop finds nothing, try the search across shops before telling the user it isn't sold there.
7. Cap what every call can spend
Agents loop, so give every paid call a ceiling. datawebot makes this easy: check_site is free and says what a search will cost, every paid call takes max_credits, and failed searches cost nothing. A search across a country's shops costs 25 credits, one shop 5, and reading every offer for a product 1.
The sample checks the price and your balance first, and stops before spending if a run could go over budget. The key's daily cap backs that up: when it was close, a 25-credit search was refused before it ran. And every timeout came back marked retryable, with “Nothing was charged”.
The checklist
- Match the exact model, not a lookalike name.
- Leave out accessories.
- Check where the seller is.
- Set aside prices that can't be real, in both directions.
- Skip what's out of stock, and compare with delivery.
- Don't stop at one shop's search.
- Cap what every call can spend.
The sample
Everything above comes from , a Node.js command line with no dependencies, built and tested on Windows 11. It has 23 offline tests that cost nothing, saved runs you can replay for free, and from the same session.
The checks above live in one file, as pure functions. The other is a small MCP client:
src/offers.js (254 lines)
// The rules that turn datawebot's seller offers into a list you can trust.
//
// "Cheapest first" alone goes wrong on real data. In one Malaysian run for the Sony WH-1000XM5,
// the offers for one product ran from RM 38.90 to RM 2,383.63: the bottom one was almost certainly
// not the real thing, some shops were abroad or out of stock, and delivery added up to RM 350.
// So this file:
// 1. keeps only offers whose title names the model you asked for (and that aren't accessories),
// 2. moves shops in other markets, out-of-stock offers and repeated listings out of the way,
// 3. sets aside prices far below the rest, rather than ranking them first (two checks, because
// on a shop's own search the fakes can outnumber the real listings and drag the median down),
// 4. sorts what's left by price with delivery, where the shop gives its delivery cost.
// Everything here is pure (no network), so it's easy to test.
/**
* Builds a pattern for the model number in a search, so titles can be checked against it.
* "Sony WH-1000XM5" becomes a pattern that matches WH-1000XM5, WH1000XM5 and WH 1000 XM5,
* but not WF-1000XM5 (the earbuds), WH-1000XM4 or WH-1000XM50.
* Words with a digit count as the model; with none, every word must appear, in order.
*/
export function modelPattern(query) {
const words = query.trim().split(/\s+/);
const model = words.filter((word) => /\d/.test(word));
const parts = (model.length ? model : words).map((word) => {
const runs = word.match(/[\p{L}]+|\d+/gu) ?? [];
return runs.map(escapeRegExp).join("[\\s-]?");
});
// Not preceded by a letter or digit, and not followed by another digit (XM5 must not match XM50).
return new RegExp(`(?<![\\p{L}\\d])${parts.join(".*")}(?!\\d)`, "iu");
}
/** The model as it appears in the search, for messages: "WH-1000XM5". */
export function modelLabel(query) {
const model = query.trim().split(/\s+/).filter((word) => /\d/.test(word));
return model.length ? model.join(" ") : query.trim();
}
// Words that mark an add-on when they come before the model, as in "Earpads for Sony WH-1000XM5".
const ACCESSORY_WORDS = /\b(ear ?pads?|cushions?|cases?|covers?|stands?|holders?|hangers?|cables?|replacements?|protectors?|skins?|straps?|adapters?|compatible)\b/i;
/**
* True when a title is for something made to go with the model, not the model itself:
* "Wicked Cushions Extra Thick Earpads for Sony WH-1000XM5" is, but
* "Sony WH-1000XM5 Wireless Headphones with Carrying Case" isn't (the case comes after the model).
*/
export function looksLikeAccessory(title, pattern) {
const match = pattern.exec(title ?? "");
if (!match) return false;
const before = title.slice(0, match.index);
return /\bfor\b/i.test(before) || ACCESSORY_WORDS.test(before);
}
/**
* Chooses which search result to read offers for: the first one (datawebot lists best matches
* first) that names the model, isn't an accessory, has a price and isn't from another market.
* Shops in the asked country come before shops with no country given.
* Only cross-shop results ("g_" ids) carry every seller's offer, so those are preferred.
*/
export function pickListing(products = [], { country, pattern }) {
const usable = products.filter(
(p) => p?.price?.amount > 0 && pattern.test(p.title ?? "") && !looksLikeAccessory(p.title, pattern) && !p.other_market,
);
const rank = (p) =>
(String(p.product_id ?? "").startsWith("g_") ? 0 : 2) + (p.shop_country?.toUpperCase() === country?.toUpperCase() ? 0 : 1);
// Array.prototype.sort is stable, so equal ranks keep datawebot's order.
return [...usable].sort((a, b) => rank(a) - rank(b))[0] ?? null;
}
/**
* Sorts one product's offers into groups. Returns:
* ranked offers worth comparing, cheapest first by price with delivery (see costOf)
* suspicious offers far below the rest, set aside to check, each with its reasons:
* under minShare (half) of the median price, or below a jumpFactor (4x) price jump
* otherMarket shops datawebot marks as outside the asked country
* outOfStock offers the shop shows as out of stock
* otherCurrency offers priced in a different currency from the rest, which can't be compared
* unmatched titles that don't name the model, or that look like accessories
* noPrice offers without a price
* duplicates the same shop, title and price seen again
* median the median item price of the comparable offers, or null
* currency the currency they're in
*/
export function sortOffers(offers = [], { pattern, minShare = 0.5, jumpFactor = 4 }) {
const groups = { ranked: [], suspicious: [], otherMarket: [], outOfStock: [], otherCurrency: [], unmatched: [], noPrice: [], duplicates: [] };
const seen = new Set();
const comparable = [];
for (const raw of offers) {
const offer = normalize(raw);
if (!(offer.amount > 0)) groups.noPrice.push(offer);
else if (!pattern.test(offer.title) || looksLikeAccessory(offer.title, pattern)) groups.unmatched.push(offer);
else if (offer.otherMarket) groups.otherMarket.push(offer);
else if (offer.stock === "out_of_stock") groups.outOfStock.push(offer);
else {
const key = `${offer.shop.toLowerCase()}|${offer.amount}|${offer.title.toLowerCase()}`;
if (seen.has(key)) groups.duplicates.push(offer);
else {
seen.add(key);
comparable.push(offer);
}
}
}
// Compare like with like: keep the currency most offers use.
const currency = mostCommon(comparable.map((o) => o.currency));
const sameCurrency = comparable.filter((o) => o.currency === currency);
groups.otherCurrency = comparable.filter((o) => o.currency !== currency);
// Both checks use item prices: a RM 38.90 listing is suspicious with or without delivery.
// - The median check catches a few low prices among many real ones.
// - The jump check catches the opposite: when cheap fakes outnumber the real listings, the
// median is itself a fake price, but the jump from RM 49.90 to RM 1,099 still gives them away.
// It needs at least two offers above the jump, so one absurdly high price can't set
// everything else aside.
const amounts = sameCurrency.map((o) => o.amount);
const median = medianOf(amounts);
const floor = jumpFloor(amounts, { factor: jumpFactor, minAbove: 2 });
const shareText = minShare === 0.5 ? "under half the median price" : `under ${Math.round(minShare * 100)}% of the median price`;
for (const offer of sameCurrency) {
const reasons = [];
if (median !== null && offer.amount < minShare * median) reasons.push(shareText);
if (floor !== null && offer.amount < floor) reasons.push(`below a ${jumpFactor}x jump in price`);
if (reasons.length) groups.suspicious.push({ ...offer, reasons });
else groups.ranked.push(offer);
}
const byCost = (a, b) => costOf(a) - costOf(b);
groups.ranked.sort(byCost);
groups.suspicious.sort(byCost);
groups.otherMarket.sort(byCost);
return { ...groups, median, currency };
}
/**
* What an offer costs to compare by: the price with delivery when the delivery cost is known,
* else the item price. (datawebot fills total_text even when delivery is unknown, and then it's
* just the item price, so a total only counts when the delivery cost is known.)
*/
export function costOf(offer) {
return offer.totalAmount ?? offer.amount;
}
// A currency marker right before an amount: "RM 350", "S$12", "Rp 15.000", "€4,90", "+ $5".
// Not inside a word, so "form 5" never reads as "RM 5".
const MONEY = /(?<![A-Za-z])(?:RM|MYR|S\$|SGD|US\$|USD|A\$|AUD|HK\$|HKD|Rp|IDR|€|EUR|£|GBP|¥|JPY|฿|THB|₱|PHP|₫|VND|₹|INR|\$)\s?(\d[\d.,]*)/i;
/**
* Reads a delivery cost as shops write it: "Free" and "Free delivery between 3 - 8 Dec" are 0,
* "+ RM 95.99" and "Delivery RM 350" are amounts. Only a number next to a currency marker counts,
* so the dates in "between 3 - 8 Dec" are never read as a price. Returns null when unclear.
*/
export function parseDelivery(text) {
if (typeof text !== "string" || !text.trim()) return null;
if (/\bfree\b/i.test(text)) return 0;
const money = text.match(MONEY);
if (money) return parseAmount(money[1]);
const plus = text.match(/^\s*\+\s*(\d[\d.,]*)\s*$/); // "+ 95.99" with no currency
return plus ? parseAmount(plus[1]) : null;
}
/**
* Reads a number from a price as shops write it: "RM 1,037.10", "Rp 3.400.000", "€1.234,56".
* When both separators appear, the last one is the decimal mark. A lone separator followed by
* exactly three digits is a thousands separator ("1,037" and "3.400" are thousands).
*/
export function parseAmount(text) {
if (typeof text !== "string") return null;
const found = text.match(/\d[\d.,\s]*/);
if (!found) return null;
let digits = found[0].replace(/\s/g, "").replace(/[.,]$/, "");
const comma = digits.lastIndexOf(",");
const dot = digits.lastIndexOf(".");
if (comma > -1 && dot > -1) {
digits = comma > dot ? digits.replace(/\./g, "").replace(",", ".") : digits.replace(/,/g, "");
} else if (comma > -1 || dot > -1) {
const mark = comma > -1 ? "," : ".";
const groups = digits.split(mark);
const thousands = groups.length > 2 || groups.at(-1).length === 3;
digits = thousands ? groups.join("") : groups.join(".");
}
const amount = Number(digits);
return Number.isFinite(amount) ? amount : null;
}
/**
* Reads stock from an offer's details list ("In stock online", "Out of stock online", ...) or
* from a search result's availability field ("in_stock", "out_of_stock").
*/
function stockOf(details, availability) {
const text = [...(Array.isArray(details) ? details : []), String(availability ?? "").replace(/_/g, " ")].join(" ");
if (/out of stock/i.test(text)) return "out_of_stock";
if (/contact for (online )?availability/i.test(text)) return "ask_shop";
if (/in stock/i.test(text)) return "in_stock";
return null;
}
/** One flat shape for an offer, whatever datawebot sent. */
function normalize(offer) {
const price = offer.price ?? {};
const amount = typeof price.amount === "number" ? price.amount : Number(price.amount);
// Delivery comes as "Free", "+ RM 8.00", "Delivery RM 350", "Free delivery between 3 - 8 Dec"
// or nothing. The total is datawebot's when it gives one, else worked out from the delivery cost.
const shipping = offer.shipping_text ?? null;
const delivery = parseDelivery(shipping);
const known = shipping !== null && delivery !== null;
const total = known ? parseAmount(offer.total_text) ?? (amount > 0 ? Math.round((amount + delivery) * 100) / 100 : null) : null;
return {
shop: String(offer.shop ?? "unknown shop"),
title: String(offer.title ?? ""),
url: offer.url ?? null,
amount,
currency: price.currency ?? null,
priceText: price.text ?? (price.amount != null ? `${price.currency ?? ""} ${price.amount}`.trim() : null),
shipping,
delivery: known ? delivery : null, // the delivery cost as a number, when it's clear
totalText: known && offer.total_text ? offer.total_text : null,
totalAmount: total,
stock: stockOf(offer.details, offer.availability),
shopCountry: offer.shop_country ?? null,
otherMarket: Boolean(offer.other_market),
marketplace: Boolean(offer.marketplace),
seller: offer.seller ?? null,
};
}
/**
* Looks for a big gap in the sorted prices: a price at least `factor` times the one below it,
* with at least `minAbove` prices from there up. Returns the price at the top of the highest such
* gap (everything below it is "far below the rest"), or null when there's no gap that big.
*/
function jumpFloor(amounts, { factor, minAbove }) {
const sorted = [...amounts].sort((a, b) => a - b);
for (let i = sorted.length - 1; i >= 1; i--) {
if (sorted.length - i >= minAbove && sorted[i] >= factor * sorted[i - 1]) return sorted[i];
}
return null;
}
function medianOf(values) {
if (!values.length) return null;
const sorted = [...values].sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2);
return sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2;
}
function mostCommon(values) {
const counts = new Map();
for (const value of values) counts.set(value, (counts.get(value) ?? 0) + 1);
let best = null;
for (const [value, count] of counts) if (best === null || count > counts.get(best)) best = value;
return best;
}
function escapeRegExp(text) {
return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}src/datawebot.js (140 lines)
// A tiny client for datawebot's MCP server, with no dependencies (Node 22 has fetch built in).
//
// MCP's "Streamable HTTP" transport is plain HTTP: every request is one JSON-RPC message sent
// with POST, and the answer comes back either as JSON or as a short event stream. datawebot's
// server is stateless, so each call stands on its own (no session to open first).
export const MCP_URL = "https://mcp.datawebot.com/mcp";
/** An error from datawebot, with the HTTP status and datawebot's own error code when there is one. */
export class DatawebotError extends Error {
constructor(message, { status, code, retryable = false, data } = {}) {
super(message);
this.name = "DatawebotError";
this.status = status; // HTTP status, e.g. 401 when the key is missing, expired or revoked
this.code = code; // datawebot's code, e.g. "insufficient_credits" or "source_unavailable"
this.retryable = retryable; // datawebot says whether trying again later can help
this.data = data; // the full error body, for logging
}
}
let nextId = 1;
/**
* Sends one JSON-RPC request to the MCP server and returns the parsed response message.
* The key goes in the Authorization header only; it is never logged or put in an error.
*/
export async function rpc(apiKey, method, params = {}) {
if (!apiKey) throw new DatawebotError("DATAWEBOT_API_KEY is not set. Put it in .env (see .env.example).", { code: "no_key" });
const response = await fetch(MCP_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${apiKey}`,
"Content-Type": "application/json",
// The transport requires clients to accept both answer formats.
Accept: "application/json, text/event-stream",
"User-Agent": "datawebot-price-check/0.1",
},
body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, params }),
});
const text = await response.text();
const message = parseMessage(text, response.headers.get("content-type") ?? "");
if (!response.ok) {
// e.g. 401 login_required. The body explains, so keep its message (never the request).
const code = message?.error?.data?.code ?? message?.error?.code ?? message?.code;
const detail = message?.error?.message ?? message?.message ?? text.slice(0, 300);
throw new DatawebotError(`HTTP ${response.status}: ${detail}`, { status: response.status, code, data: message ?? text });
}
if (!message) throw new DatawebotError(`No JSON-RPC answer in the response: ${text.slice(0, 300)}`, { status: response.status });
return message;
}
/**
* Calls one datawebot tool and returns its structured answer: { data, summary, meta, next }.
*
* datawebot reports tool problems (a shop that timed out, too few credits, a missing argument)
* as a normal answer marked isError, with a JSON error in its text, not as a JSON-RPC error.
* Both kinds become a DatawebotError here, so callers have one thing to catch.
*/
export async function callTool(apiKey, name, args = {}) {
const message = await rpc(apiKey, "tools/call", { name, arguments: args });
if (message.error) {
throw new DatawebotError(message.error.message ?? "JSON-RPC error", { code: message.error.code, data: message.error });
}
const result = message.result ?? {};
if (result.isError) {
const error = readToolError(result);
throw new DatawebotError(error.message, { code: error.code, retryable: error.retryable, data: error });
}
return result.structuredContent ?? parseJson(firstText(result)) ?? {};
}
/**
* Like callTool, but waits for slow answers. A search can answer { status: "working",
* request_id, check_after_seconds } first; get_results (free) collects it when it's ready.
* Never send the original request again while it's working: that could pay twice.
*/
export async function callToolAndWait(apiKey, name, args = {}, { maxWaitSeconds = 240, sleep = defaultSleep, onWait } = {}) {
const started = Date.now();
let answer = await callTool(apiKey, name, args);
while (answer?.data?.status === "working") {
const requestId = answer.data.request_id;
const elapsed = (Date.now() - started) / 1000;
if (elapsed > maxWaitSeconds) {
throw new DatawebotError(
`Still working after ${Math.round(elapsed)} s. Collect it later, for free, with get_results and request_id ${requestId}.`,
{ code: "still_working", retryable: true, data: { request_id: requestId } },
);
}
// Wait as long as datawebot asks, within sensible bounds, then collect.
const seconds = Math.min(Math.max(Number(answer.data.check_after_seconds) || 5, 2), 15);
onWait?.(seconds);
await sleep(seconds * 1000);
answer = await callTool(apiKey, "get_results", { request_id: requestId });
}
return answer;
}
/** Reads datawebot's { error: { code, message, retryable } } out of an isError answer. */
function readToolError(result) {
const text = firstText(result);
const error = parseJson(text)?.error ?? result.structuredContent?.error ?? {};
return {
code: error.code ?? "tool_error",
message: error.message ?? (text || "datawebot returned an error without a message"),
retryable: Boolean(error.retryable),
next: error.next,
};
}
/** Reads a JSON-RPC message from either a JSON body or an event stream ("data: {...}" lines). */
function parseMessage(text, contentType) {
if (contentType.includes("text/event-stream")) {
for (const line of text.split(/\r?\n/)) {
if (!line.startsWith("data:")) continue;
const candidate = parseJson(line.slice(5).trim());
if (candidate && ("result" in candidate || "error" in candidate)) return candidate;
}
return null;
}
return parseJson(text);
}
function firstText(result) {
return result.content?.find((part) => part.type === "text")?.text ?? "";
}
function parseJson(text) {
try {
return JSON.parse(text);
} catch {
return null;
}
}
function defaultSleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}To run it yourself, you need Node.js 22.9 or newer and a free datawebot account. The README has the steps, and what each run costs.