Skip to main content
Glama

execute_sql

Read-only

Esegue UNA query SQL di sola lettura sul data-hub storico dell'account (DuckDB, un file per org). È LA STRADA PRIMARIA per OGNI domanda di ANALYTICS, in particolare la PERFORMANCE Amazon Ads: ACoS, ROAS, spesa, click, impression, vendite/ordini per campagna o keyword, keyword che sprecano, campagne zombie, performance PER PLACEMENT — Top of Search / Rest of Search / Product Pages / Amazon Business (tabelle fact_campaign_daily, fact_keyword_daily, fact_campaign_placement_daily). Idem storico/trend/velocity/giorni-di-copertura/analisi incrociate. È anche la strada per il MARGINE REALE e il P&L: fee Amazon, commissioni, rimborsi/refund, reimbursement, netto incassato (tabella fact_settlement_txn, dal Settlement Report V2 — ciò che Amazon paga davvero). Per lo STATO CORRENTE (prezzi, stock, bid, budget, stato campagne live) usa invece i tool SP-API/Ads (ads_list_*). Solo SELECT/WITH/SHOW/DESCRIBE/EXPLAIN/SUMMARIZE, una sola query, output limitato. Non serve (e non si può) specificare l'account: la query gira automaticamente sui dati dell'org collegata.

Tabelle disponibili (un file DuckDB per org, sola lettura). CHIAVE dei fatti = OUTPOST (un seller su un marketplace). • dim_outpost(outpost_id, seller_id, marketplace_id, region, profile_id, label) — l'OUTPOST: un seller su un marketplace. JOINa i fatti qui per seller/mercato/nome leggibile. • dim_date(date, year, month, week, dow) — calendario dei giorni SINCRONIZZATI. • dim_product(seller_id, sku, asin, title, brand, category, image_url, fulfillment_channel, updated_at) — identità prodotto PER SELLER. • fact_sku_daily_sales(date, outpost_id, seller_id, marketplace_id, sku, units_sold, units_returned, gross_sales, currency, units_pending, gross_pending) — vendite grezze SKU×giorno PER OUTPOST. units_sold/gross_sales = ordini AUTORIZZATI (consolidato); units_pending/gross_pending = ordini PENDING (pagamento non ancora autorizzato: Amazon non dà il prezzo finché è Pending → gross_pending è ~0, il segnale è units_pending). Sommare solo units_sold NON conta i pending → i giorni recenti sembrano bassi/incompleti. gross_sales è in valuta NATIVA (colonna currency): raggruppa per currency, non sommare valute diverse. • v_daily_sales(date, outpost_id, seller_id, marketplace_id, sku, units_sold, units_pending, units_ordered, units_returned, gross_sales, gross_pending, gross_ordered, currency, maturity) — VIEW pronta su fact_sku_daily_sales: units_ordered/gross_ordered = autorizzato + pending = i numeri che Seller Central mostra per data ordine; maturity (provisional|consolidated) già calcolata per riga. Per totali unità/fatturato per giorno o SKU, e per QUALSIASI confronto con Seller Central, usa QUESTA (SUM(units_ordered), SUM(gross_ordered)) invece di sommare a mano units_sold. • fact_inventory_snapshot(date, outpost_id, seller_id, marketplace_id, sku, qty_fulfillable, qty_inbound, qty_transfer, qty_reserved, qty_mfn, sales_rank, price, currency) — stock/prezzo storicizzato; per lo stock CORRENTE usa l'ULTIMO snapshot per outpost. ATTENZIONE al canale: qty_fulfillable è lo stock FBA e per gli SKU FBM è strutturalmente 0 — per gli FBM lo stock è qty_mfn (-1 = "sempre disponibile", NULL = ignoto); prima di dire "senza stock" guarda fulfillment_channel. qty_transfer = pezzi in trasferimento tra centri Amazon (non vendibili ORA ma in arrivo); qty_inbound = spedizioni verso Amazon. COPERTURA "oggi" = qty_fulfillable/velocity; COPERTURA "reale" = (qty_fulfillable+qty_transfer+qty_inbound)/velocity — usa la reale per l'urgenza di riordino, così la merce in arrivo non genera falsi allarmi. • fact_buybox_snapshot(date, outpost_id, seller_id, marketplace_id, asin, buy_box_price, buy_box_listing_price, shipping, currency, condition, lowest_price, offer_count, i_win_buy_box, winner_is_fba, has_buy_box, no_buy_box_reason, source) — Buy Box del PROPRIO catalogo per outpost. buy_box_price = landed (all-in). Usa l'ULTIMO snapshot per outpost; i_win_buy_box=true = la vinco io; has_buy_box=false → vedi no_buy_box_reason. Per pochi ASIN arbitrari usa get_buybox_prices (live). • fact_campaign_daily(date, outpost_id, seller_id, marketplace_id, profile_id, campaign_id, campaign_name, impressions, clicks, cost, sales_7d, purchases_7d, units_7d, ad_product) — performance campagne per CAMPAGNA×giorno, PER OUTPOST. ad_product = SP (Sponsored Products) | SB (Sponsored Brands) | SD (Sponsored Display): filtra per tipo o aggrega. NB: per SB/SD sales_7d/purchases_7d possono essere 0 se Amazon non espone quelle colonne per quel reportTypeId. • fact_keyword_daily(date, outpost_id, seller_id, marketplace_id, profile_id, campaign_id, ad_group_id, keyword_id, keyword_text, match_type, impressions, clicks, cost, sales_7d, purchases_7d) — performance SP per KEYWORD×giorno, PER OUTPOST. • fact_campaign_placement_daily(date, outpost_id, seller_id, marketplace_id, profile_id, campaign_id, campaign_name, placement, placement_raw, impressions, clicks, cost, sales_7d, purchases_7d, units_7d, tos_impression_share, currency) — performance SP per CAMPAGNA × PLACEMENT × giorno, PER OUTPOST. placement = PLACEMENT_TOP (Top of Search) | PLACEMENT_REST_OF_SEARCH (rest of search / "Other") | PLACEMENT_PRODUCT_PAGE (pagine prodotto / "Detail Page") | SITE_AMAZON_BUSINESS — la STESSA lingua dei moltiplicatori placement_bidding. tos_impression_share = quota % di impression Top of Search (solo sulla riga PLACEMENT_TOP, NULL se assente). È la tabella per "quale placement spende/converte meglio" e per decidere i moltiplicatori: ACoS per placement = SUM(cost)/SUM(sales_7d) GROUP BY campaign_id, placement; poi ads_list_sp_campaigns (placement_adjustments attuali) → ads_update_sp_campaign placement_bidding. Vuota = nessun giro Ads dopo l'attivazione (freschezza: hub_sync_meta source ads_placement). • fact_search_term_daily(date, outpost_id, seller_id, marketplace_id, profile_id, campaign_id, ad_group_id, keyword_id, keyword_text, match_type, search_term, impressions, clicks, cost, sales_7d, purchases_7d, currency) — TERMINI DI RICERCA REALI degli utenti Amazon per giorno (Search Term Report SP), incrociati con la keyword/target che li ha catturati. È la base del KEYWORD HARVESTING: termini con conversioni e buon ACoS che NON sono ancora keyword exact → proponili con ads_create_sp_keywords; termini che sprecano (spesa, 0 conversioni) → ads_create_sp_negative_keywords. Nelle campagne AUTO keyword_id/keyword_text sono la targeting clause (close-match, ...). • fact_settlement_txn(settlement_id, posted_date, deposit_date, outpost_id, seller_id, marketplace_id, transaction_type, order_id, sku, amount_type, amount_description, quantity, amount, currency) — FINANCE: transazioni dal Settlement Report V2 di Amazon (AUTOREVOLE: è ciò che Amazon paga davvero). Il lato COSTI del P&L: commissioni, fee FBA, rimborsi/refund, reimbursement, tasse trattenute. amount è FIRMATO (fee e refund sono negativi) → il NETTO di un periodo = SUM(amount). transaction_type: Order | Refund | ServiceFee | other-transaction... ; amount_type/amount_description classificano la voce (es. ItemFees/Commission, ItemFees/FBAPerUnitFulfillmentFee). Le voci di account (fee abbonamento, storage, trasferimenti) hanno sku NULL. Copre solo i settlement GIÀ CHIUSI da Amazon (~ogni 14g): gli ultimi giorni non sono ancora in un settlement → per il fatturato recente usa fact_sku_daily_sales; per margine/fee/rimborsi usa questa. Valuta NATIVA: raggruppa per currency. • fact_vendor_po_item(outpost_id, seller_id, marketplace_id, po_number, item_seq, po_date, po_state, po_status, po_type, last_updated, delivery_window_start, delivery_window_end, ship_to, asin, vendor_sku, ordered_qty, accepted_qty, rejected_qty, received_qty, confirmation_status, receive_status, last_receive_date, net_cost, list_price, currency, updated_at) — VENDOR (1P, Vendor Central): una riga per riga di PO (Purchase Order) degli ultimi ~90 giorni. È SELL-IN (quanto Amazon ordina/accetta/riceve dal vendor), NON sell-out (vendite ai clienti finali): non sommarlo MAI a fact_sku_daily_sales. Quantità in pezzi; accepted/rejected/received NULL = stato del PO non ancora letto. net_cost = prezzo di acquisto unitario pagato da Amazon al vendor. VIEW v_vendor_sell_in_daily(outpost_id, marketplace_id, date, currency, pos, ordered_units, accepted_units, rejected_units, received_units, ordered_value, accepted_value, received_value_est): sell-in per giorno del PO; received_value_est = received × net_cost è una STIMA di quanto Amazon pagherà, non il pagamento effettivo. Sell-out vendor, inventario vendor, traffico e pagamenti NON sono nel hub: leggi hub_sync_meta (source LIKE 'vendor_%') per il motivo (es. ruolo Brand Analytics mancante) e dillo all'utente. • hub_findings(outpost_id, rule_key, entity_type, entity_id, seller_id, marketplace_id, severity, status, title, payload, proposed_action, first_seen_at, last_seen_at, resolved_at) — PROBLEMI OPERATIVI rilevati ogni giorno dal motore deterministico (worker): rule_key = buybox_lost | buybox_suppressed | stockout_risk | ads_no_stock | ads_dead_sku | negative_margin; status = open|approved|executed|dismissed|resolved; payload/proposed_action sono JSON (stringa). Per la lista pronta usa il tool findings_list; questa tabella serve per conteggi/trend/analisi incrociate (es. findings aperti per outpost, tempo medio di risoluzione da first_seen_at a resolved_at). • hub_sync_meta(source, outpost_id, last_sync_at, rows_written, note) — freschezza dato PER OUTPOST (source: orders|catalog|buybox|ads_campaign|ads_keyword|ads_search_term|ads_placement|settlement|findings|vendor_po; per i vendor anche vendor_sales_report|vendor_inventory_report|vendor_traffic_report|vendor_buybox|vendor_payout con rows_written=0 e il motivo in note). • WooCommerce (tabelle SEPARATE, chiave store_id = id dello store da woo_list_stores, MAI outpost_id; nessuna tabella o view Amazon le include): woo_dim_store(store_id, status, first_synced_at, last_synced_at), woo_dim_product(store_id, item_id, product_id, variation_id, parent_id, type, sku, ean, name, status, price, regular_price, sale_price, manage_stock, stock_quantity, stock_status, date_modified), woo_fact_stock_snapshot(date, store_id, item_id, sku, stock_quantity, stock_status, price), woo_fact_order(store_id, order_id, number, status, date_created, date_modified, currency, total, shipping_total, payment_method, billing_country, shipping_country, customer_hash), woo_fact_order_line(store_id, order_id, line_no, product_id, variation_id, sku, name, quantity, total), woo_hub_sync_meta(store_id, source, last_sync_at, last_full_at), VIEW woo_v_daily_sales(date, store_id, sku, currency, units, gross_sales, orders), VIEW woo_v_customer_rfm(store_id, customer_hash, currency, last_order_at, first_order_at, frequency, monetary) [customer_hash = HMAC pseudonimo dell'email, NULL se l'ordine non è stato risincronizzato con la chiave]. Per confrontare con Amazon unisci per SKU (lower(trim(sku))) a dim_product, senza sommare valute diverse. Per le viste pronte c'è il tool woo_hub_query. OUTPOST: un'azienda può avere PIÙ seller sullo STESSO marketplace (caso agenzia). Per non mischiarli, filtra/raggruppa per outpost_id (o JOIN dim_outpost). marketplace_id da solo NON identifica un singolo venditore. NULL→0: fact è sparso (solo vendite reali). Per "0 vs non-sincronizzato" fai LEFT JOIN da dim_date e COALESCE(units_sold,0). GIORNI RECENTI = PROVVISORI (leggi PRIMA di analizzare "ieri"/"oggi"): gli ultimi ~2-3 giorni — e QUALSIASI giorno con units_pending>0 — NON sono completi: gli ordini si autorizzano e rientrano nelle 24-72h successive (è normale che il numero di ieri salga nei giorni dopo). MAX(date) riflette la spina dim_date, estesa a OGGI a ogni sync → NON è una prova di completezza: MAX(date)=oggi non vuol dire che oggi/ieri siano completi. Quando analizzi giorni recenti calcola ed ESPONI sempre la maturità e avvisa l'utente: maturity = CASE WHEN date >= CURRENT_DATE - INTERVAL 2 DAY OR COALESCE(units_pending,0) > 0 THEN 'provisional' ELSE 'consolidated' END. Non confrontare un giorno provisional con uno consolidated senza dichiararlo. La freschezza dell'ultima sync è in hub_sync_meta.last_sync_at (source='orders'). RICONCILIAZIONE con Seller Central (fatturato ordinato): "Ordered Product Sales" di Seller Central, per DATA ORDINE, = gross_sales + gross_pending (autorizzato + in attesa di autorizzazione). gross_sales da SOLO conta solo gli ordini autorizzati → è più BASSO di Seller Central sui giorni recenti (dove molti ordini sono ancora pending). Quando l'utente confronta col fatturato di Seller Central, o chiede "fatturato ordinato", usa SUM(gross_sales + gross_pending), NON solo gross_sales. Su giorni consolidati (≥3-4g fa) gross_pending→0 e le due coincidono. (Residui: fuso UTC vs marketplace e tasse restano marginali.) Scorciatoia: la VIEW v_daily_sales espone units_ordered/gross_ordered e maturity già pronti. Metriche Ads (NON sono colonne, derivale in query): ACoS = cost/NULLIF(sales_7d,0); ROAS = sales_7d/NULLIF(cost,0); CTR = clicks/NULLIF(impressions,0); CVR = purchases_7d/NULLIF(clicks,0); TACoS = SUM(cost) / SUM(gross_sales da fact_sku_daily_sales sullo STESSO outpost). MARGINE REALE / P&L (da fact_settlement_txn, derivalo in query): netto incassato = SUM(amount); lordo = SUM(amount) FILTER (amount_type ILIKE '%ItemPrice%' AND transaction_type = 'Order'); fee totali = SUM(amount) FILTER (amount_type ILIKE '%fee%'); refund = SUM(amount) FILTER (transaction_type = 'Refund'); margine dopo Ads = netto − SUM(cost da fact_campaign_daily stesso outpost/periodo, stessa currency); incidenza fee % = −fee/lordo. Per SKU: GROUP BY sku (le voci account-level hanno sku NULL: mostrale come riga "account"). PER ACOS / SPESA / PERFORMANCE ADS STORICA: usa fact_campaign_daily / fact_keyword_daily / fact_campaign_placement_daily (per placement) QUI — è immediato. NON chiedere il report Ads live di Amazon (async, lento): solo per il dato di OGGI non ancora nel hub. Controlla hub_sync_meta (source ads_campaign) per la freschezza.

Input Schema

NameRequiredDescriptionDefault
sqlYesLa query SQL di lettura. Una sola istruzione, niente ";" multipli.
max_rowsNoRighe massime da restituire (default e tetto: 5000).

Schema Changelog

Changes observed during successful MCP inspections.

  1. Added
  2. Removed
  3. First observed

TDQS

A4.8/5.0
Behavior5/5

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

Annotations already declare readOnlyHint=true, openWorldHint=false, and destructiveHint=false, but the description adds substantial behavioral context beyond them: only SELECT/WITH/SHOW/DESCRIBE/EXPLAIN/SUMMARIZE, a single query, output limited, and no account parameter because it runs automatically on the linked org. It also discloses freshness caveats (recent days provisional, settlement lag, vendor data gaps), NULL-to-zero behavior, and outpost/currency pitfalls.

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?

The description is very long, but it is front-loaded with the primary use and constraints, then organized into a useful table catalog with caveats. Some repetition exists, such as repeated explanations of gross_sales + gross_pending reconciliation and the v_daily_sales shortcut, but most content earns its place given the breadth of the data hub.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool exposing an entire analytical warehouse with no output schema, the description is highly complete: it documents available tables and views, keys, fact grains, freshness metadata, provisional-day handling, reconciliation rules with Seller Central, Ads metric formulas, P&L derivation, vendor limitations, and separate WooCommerce tables. An agent has enough context to write correct queries without guessing core semantics.

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 the schema already documents `sql` and `max_rows`. The description nevertheless adds rich semantics for what SQL is valid and how to write correct queries: allowed statement types, single-statement constraint, table schemas, required outpost joins, currency grouping, maturity handling, and metric derivations. It does not add much about `max_rows` beyond the schema, keeping it from a 5.

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?

States a precise verb and resource: executes one read-only SQL query on the account historical data hub (DuckDB). It explicitly distinguishes itself from sibling live-data tools (SP-API/Ads tools for current prices/stock/bids and woo_hub_query for WooCommerce), so an agent can identify its role without opening the schema.

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

Usage Guidelines5/5

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

Gives explicit when-to-use guidance: primary path for analytics, Amazon Ads performance, margin/P&L, settlement finance, vendor sell-in, and historical trends. It also names alternatives and exclusions: use SP-API/Ads tools for current state, do not request the live async Ads report except for today's data, use findings_list for ready-made findings, and use woo_hub_query for WooCommerce views.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Try in Browser

Glama MCP Gateway

Add one secure layer between your agents and this server.

Resources