Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

MarginGuard

MarginGuard is a pay-per-call decision service for commerce agents. It combines unit economics with current market evidence to answer questions such as:

  • Is this product worth buying at the offered cost?
  • What selling price preserves the target margin?
  • Is an FX quote or cross-border transfer overpriced?
  • Which evidence supports the recommendation?

Every decision uses decimal monetary arithmetic and includes a reproducible SHA-256 receipt. Paid calls settle with USDT through x402 on X Layer.

Product site · API documentation · Service health

API and MCP endpoints

The REST API is available at https://api.getmarginguard.xyz.

Tool REST endpoint MCP endpoint Default price
check_margin POST /v1/check_margin /mcp/check-margin/ $0.05
get_price_floor POST /v1/get_price_floor /mcp/price-floor/ $0.02
check_fx_cost POST /v1/check_fx_cost /mcp/fx-cost/ $0.02
check_transfer_cost POST /v1/check_transfer_cost /mcp/transfer-cost/ $0.03
contribute_price, coverage, health Free REST routes /mcp/free Free

MCP discovery and initialization are free. Payment is required only when a paid tool is called.

Tools

check_margin

Produces a resale decision—BUY, BUY_SMALL_BATCH, PASS, REPRICE_UP, REPRICE_DOWN, BUNDLE, NEGOTIATE_SUPPLIER, or KILL_PRODUCT—with unit economics, market statistics, confidence, evidence tier, reasoning, and receipt.

{
  "request": {
    "request_id": "quote-2026-001",
    "product": {
      "name": "rice 1kg",
      "category": "cereals",
      "quantity": "1",
      "unit": "kg"
    },
    "country": "PHL",
    "currency": "PHP",
    "unit_cost": "30",
    "fees": [
      {"name": "shipping", "kind": "fixed", "value": "2"},
      {"name": "marketplace", "kind": "pct_price", "value": "0.10"}
    ],
    "target_margin": "0.20"
  }
}

A successful response includes the decision and its basis:

{
  "request_id": "quote-2026-001",
  "decision": "BUY",
  "confidence": "0.85",
  "evidence_tier": "T1_OFFICIAL_SURVEY",
  "economics": {
    "breakeven_price": "35.56",
    "price_floor": "45.71"
  },
  "receipt": {
    "algo": "sha256",
    "hash": "..."
  }
}

The response contains additional market observations, flags, and reasoning. See the OpenAPI documentation and docs/packet.schema.json for the complete contract.

get_price_floor

Calculates breakeven and minimum selling price from unit cost, fixed fees, percentage-of-price fees, and target margin. This tool does not require market evidence.

check_fx_cost

Compares an offered currency conversion with mid-market FX data and available provider quotes. Results use the FAIR, OVERCHARGED, GOUGED, or BEST_ROUTE verdicts.

check_transfer_cost

Evaluates a cross-border transfer against provider quotes plus World Bank source-country outbound and destination-country inbound benchmarks. These benchmarks are contextual country averages, not bilateral corridor prices.

To judge a specific offer, the caller must provide either its exchange rate and fee or its total cost percentage. The returned X Layer stablecoin route is explicitly a fixed planning estimate; it is not a live gas, liquidity, on-ramp, or off-ramp quote.

Free tools

  • coverage reports real per-source coverage, including zero coverage.
  • health reports service status, source freshness, and provider diagnostics.
  • contribute_price accepts observations for a future authenticated contribution system. Contributions do not currently ground decisions.

Evidence and confidence

MarginGuard routes evidence by product, package size, country, currency, and freshness. It requires at least three compatible observations before market evidence can ground a margin decision.

Tier Evidence
T2_LIVE_MARKET_COMPS Validated SerpApi Google Shopping aggregates
T1_OFFICIAL_SURVEY WFP, FAO GIEWS FPMA, Agmarknet, and US BLS
T1_OPEN_SHELF Open Prices / Open Food Facts observations
T0_PLUS_CONTEXT Caller-supplied reference context
T0_INPUTS_ONLY Unit economics without qualifying market evidence

Live shopping results must have compatible package units, positive full prices, multiple sellers, relevant product titles, and currency evidence. Used or refurbished items, installment-only prices, accessories, unrelated variants, duplicates, and reported barcode mismatches are excluded. Only aggregate statistics are stored; raw shopping listings are not retained.

Evidence that is stale, dimensionally incompatible, or missing a supported FX path is excluded rather than guessed. Large cross-source disagreement reduces confidence and is reported in the packet.

Payments and idempotency

Paid requests use x402 v2 with USDT on X Layer (eip155:196):

POST request without payment
  → 402 with PAYMENT-REQUIRED
  → client signs the accepted authorization
  → retry with PAYMENT-SIGNATURE
  → server verifies, computes, settles, and returns PAYMENT-RESPONSE

The same payment proof and identical request return the cached packet without a second charge. Reusing a proof for different request content or another tool is rejected. Failed validation and server errors are not settled or cached as successful decisions.

Quick start

Python 3.11 or newer is required.

git clone https://github.com/Lightlabs-main/MarginGuard.git
cd MarginGuard
python -m venv .venv
. .venv/bin/activate
pip install -r requirements.txt

MG_PAYMENTS_MODE=simulated uvicorn --factory api.app:create_app --port 3000

In another terminal:

curl http://127.0.0.1:3000/v1/health
python -m pytest -q

The server requires an explicit MG_PAYMENTS_MODE value:

  • simulated for payment and idempotency development;
  • disabled for local work without payment enforcement;
  • live for x402 settlement with configured facilitator credentials.

Run python scripts/refresh_all.py to build the complete local evidence database, or use --light for the smaller frequently refreshed sources. Set SERPAPI_API_KEY to enable on-demand live-shopping evidence.

Production architecture

HTTPS / Caddy
    |
FastAPI + MCP + x402 middleware
    |
service and evidence routing
    |---------------------------|
Decimal decision engine      SQLite/WAL
                                |
                     scheduled source refreshes

The decision engine is pure: it performs no network I/O, reads no clock, rejects floating-point values, and receives evidence through a separate routing layer. SQLite stores monetary values as decimal text and uses WAL, busy timeouts, atomic idempotency records, and consistent online backups.

Deployment units and operational procedures are documented in deploy/README.md.

Data sources and limitations

Coverage varies by country, product, package, and date. coverage and health should be consulted instead of assuming universal availability. Live marketplace relevance is conservative but cannot establish that two listings are physically identical when providers omit brand, model, GTIN, variant, or currency metadata.

Collected community contributions are intentionally excluded from decision evidence until wallet authentication, reputation, deduplication, and abuse controls exist.

Security and integrity

  • Decimal-only monetary parsing and serialization
  • Deterministic packets and SHA-256 receipts
  • Evidence freshness and unit-normalization checks
  • Payment-proof replay protection and request-bound idempotency
  • No settlement for failed requests
  • Aggregate-only storage for marketplace results
  • Source-aware health diagnostics and provider failure telemetry
  • SQLite integrity checks, checksum sidecars, and optional encrypted restic backups

Do not commit API keys, facilitator credentials, wallet private keys, or production environment files. Use a disposable, low-balance payer wallet for live tests.

Roadmap

  • Wallet-authenticated community evidence with reputation and abuse controls
  • Additional marketplace providers and regional fallbacks
  • More product-identity and variant verification where provider metadata permits it
  • Expanded country, commodity, FX-provider, and remittance-corridor coverage
  • Continued monitoring, restore drills, and independent deployment reproduction

Historical verification and engineering records live in docs/AUDIT_LOG.md and docs/VERIFICATION_LOG.md, separate from this product overview.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages