ecommerce-marketplace-arbitrage

SturdivantAI/ecommerce-marketplace-arbitrage Checked 3 days ago

Autonomous marketplace arbitrage decision agent (ADK 2.0, MCP, Gemini)

Demo video: https://youtu.be/0yjnugojFk8 An autonomous decision agent that evaluates whether a reseller should purchase a product for profitable resale. Given a product identifier (ASIN), the agent automatically returns one of three sourcing outcomes: BUY, PASS, or ESCALATE (pause for human approval). Built with the Google Agent Development Kit (ADK) 2.0, powered by Gemini models, and managed with the Agents CLI under Google Antigravity.

Summary extracted from the README.

Autonomous Marketplace Arbitrage Decision Agent

Demo video: https://youtu.be/0yjnugojFk8

An autonomous decision agent that evaluates whether a reseller should purchase a product for profitable resale. Given a product identifier (ASIN), the agent automatically returns one of three sourcing outcomes: BUY, PASS, or ESCALATE (pause for human approval).

Built with the Google Agent Development Kit (ADK) 2.0, powered by Gemini models, and managed with the Agents CLI under Google Antigravity.


1. Problem

The Challenge

Resellers earn margin by buying products cheaply and reselling them for more on a marketplace. They source deals wherever products are underpriced. Clearance shelves, store closings, liquidation lots, wholesale suppliers, and yard sales. The hard part is not the buying. It is the decision. For every candidate product, the reseller must judge whether it will sell, and whether it will sell at a profit, before spending money. That judgment combines price, marketplace fees, demand, competition, and selling restrictions. Most resellers make this call by hand, one product at a time, under time pressure on a sourcing trip or against a supplier list.

This problem is not unique to Amazon sellers. It applies to retail and online arbitrage flippers, wholesale sourcing buyers, eBay and Walmart resellers, liquidation and thrift resellers, and small e-commerce procurement teams. Any buyer who makes repeated buy or no-buy decisions under margin and demand uncertainty faces the same core problem.

The Pain Points

  1. Slow, manual evaluation. Checking each product across multiple tools (sales-rank history, fee calculators, seller dashboards) takes minutes per item. A single sourcing session can involve hundreds of products. Most never get reviewed.
  2. Complex, error-prone math. True profit depends on buy cost, referral fee, fulfillment fee, and inbound shipping. Mental math and quick spreadsheets produce mistakes that turn an apparent winner into a loss.
  3. Hidden eligibility traps. Many brands and categories are gated or restricted. A reseller can buy stock they are not allowed to sell, locking up cash in unsellable inventory.
  4. Silent fee erosion. Marketplace fees change over time. Margins calculated on last year's fee structure quietly disappear.
  5. Demand uncertainty. A product with a strong sales rank today can stall tomorrow. Resellers struggle to weigh demand stability, not just a single snapshot.
  6. Capital risk. A wrong buy ties up cash in dead stock. At scale, repeated small misjudgments compound into real losses.
  7. Inconsistent, unauditable judgment. Human decisions vary with fatigue and mood. There is no record of why a product was bought or passed, so mistakes are hard to learn from.

Cost of the Status Quo

The result is a process that is slow, inconsistent, and risky. Resellers review too few products to reliably find winners, make profit errors on the ones they do review, and carry capital risk from restricted or low-demand stock. The bottleneck is decision throughput and decision quality at the same time.

Value

The agent turns a slow, inconsistent, high-risk sourcing process into a fast, consistent, and accountable one. It is a real business problem with measurable impact: better decisions, more products evaluated, and less capital lost to bad buys. That positions it cleanly for the Agents for Business track while remaining general enough for any marketplace.


2. Solution

The agent is implemented as a multi-step graph using ADK 2.0. When a user requests evaluation for an ASIN (and optionally provides custom buy cost or shipping limits), the agent:

  1. Validates the request schemas.
  2. Interacts with a custom Model Context Protocol (MCP) data layer to pull price histories, sales ranks, fees, and brand gating restrictions.
  3. Computes unit economics deterministically.
  4. Judges sales-rank stability and resale risks using a Gemini-powered risk assessor.
  5. Evaluates explicit margin thresholds to make a BUY or PASS decision, or halts execution and raises a human-in-the-loop ESCALATE review request on high-cost or borderline opportunities.

3. Why Agents?

A single prompt or spreadsheet cannot do this reliably. The decision needs:

  • Sequential Tool Use: Querying restriction databases, checking fee categories, and pulling 90-day pricing history must happen step-by-step.
  • Deterministic Oversight: Generative LLMs are prone to arithmetic errors. Sourcing decisions require exact margin math. The agent delegates math to pure code, using the model purely for qualitative risk judgment.
  • Active Pause / Resume: Capital risks dictate that high-budget decisions must stop and prompt a human manager. An agent graph allows yielding a human approval signal and resuming seamlessly.

4. Architecture

Below is the architecture diagram of the agent graph:

Agent Graph Architecture

Node Descriptions

  • validate_input — A Pydantic schema validation node that extracts the 10-character alphanumeric ASIN, buy cost, and shipping inputs from the user prompt.
  • fetch_market_data — Connects to the Marketplace MCP Server to query product metadata, referral fees, FBA fulfillment fees, historical prices, and sales rank (BSR) history.
  • eligibility_gate — A conditional gate that intercepts gated or restricted ASINs and routes them directly to a PASS terminal node.
  • profitability — Executes deterministic margin calculation using compute_margin (implementing the profitability-validator skill) to compute net profit, ROI, and true break-even selling prices.
  • risk_scorer — A structured output LlmAgent using Gemini that evaluates the 90-day BSR history and price volatility to classify resale risk.
  • decision_router — A routing node that automatically approves BUY if ROI >= 30% and risk is low, rejects with a PASS if ROI is negative or below the threshold, or yields an ADK RequestInput to pause for human approval (ESCALATE) if the deal is borderline or cost >= $200.

5. Concepts Demonstrated

Concept Implementation Details File References
Multi-Agent System ADK 2.0 workflow graph, function nodes, and conditional routing app/agent.py
MCP Server Integration Custom Model Context Protocol server exposing 5 marketplace tools mcp_server/server.py
Agent Skills Enforced deterministic profit calculations and STRIDE security policies .agents/skills/profitability-validator/SKILL.md.agents/skills/stride-threat-model/SKILL.md
Security Controls Pydantic validation, Semgrep scans, tool call execution hooks, and STRIDE risk modeling .agents/CONTEXT.md.pre-commit-config.yaml.agents/hooks.jsonthreat_model.md
Production Deployability Standardized FastAPI Reasoning Engine adapter and Terraform configuration arbitrage-agent/deployment_metadata.jsonarbitrage-agent/deployment/terraform/

6. Data and Pluggability

In development and evaluation, the agent connects to the Marketplace MCP Server which serves deterministic, realistic synthetic data based on predefined test ASINs. This design:

  • Allows full functional testing and dry-run deployments with zero scraper/scraper-block dependencies.
  • Ensures zero exposure to marketplace Terms of Service violations.
  • Enables swapping in a live production API (e.g. Keepa, Amazon Selling Partner API) by modifying the MCP server adapter, leaving the agent graph completely untouched.

7. Setup & Run

Prerequisites

  • Python 3.11+
  • Node.js 18+ (for MCP / Playground)
  • Agents CLI (uv tool install google-agents-cli)

Setup Commands

# Clone the repository and navigate to the agent directory
cd arbitrage-agent

# Install project dependencies
uv sync

# Set your Gemini API Key
export GEMINI_API_KEY="your_api_key_here"

# Run linting to verify the graph compiles cleanly
agents-cli lint

# Launch the interactive agent playground
agents-cli playground

Once the playground is active, navigate to http://127.0.0.1:8080/dev-ui/?app=app and submit a prompt such as: Evaluate ASIN B000000024, buy cost 15.00, shipping 2.50


8. Evaluation

We validated the agent against a 10-scenario evaluation suite covering gated items, unprofitable products, clear winners, and high-capital items.

  • Command to Run Locally:
    uv run python arbitrage-agent/tests/eval/run_eval_locally.py
    
  • Result: Matched expected decisions on 10/10 scenarios (100% accuracy).
  • Results Log:
    ====================================================================================================
                          MARKETPLACE ARBITRAGE AGENT LOCAL EVALUATION
    ====================================================================================================
    Loaded 10 evaluation cases. Starting execution...
    
    Case ID                             | Expected   | Status | Explanation
    ----------------------------------------------------------------------------------------------------
    gated_electronics_19                | PASS       | PASS   | Pass: actual outcome 'PASS' matches expected 'PASS'.
    gated_home_kitchen_20               | PASS       | PASS   | Pass: actual outcome 'PASS' matches expected 'PASS'.
    gated_toys_games_95                 | PASS       | PASS   | Pass: actual outcome 'PASS' matches expected 'PASS'.
    thin_margin_toys_21                 | PASS       | PASS   | Pass: actual outcome 'PASS' matches expected 'PASS'.
    unprofitable_books_18               | PASS       | PASS   | Pass: actual outcome 'PASS' matches expected 'PASS'.
    strong_winner_electronics_24        | BUY        | PASS   | Pass: actual outcome 'BUY' matches expected 'BUY'.
    strong_winner_electronics_28        | BUY        | PASS   | Pass: actual outcome 'BUY' matches expected 'BUY'.
    strong_winner_home_kitchen_34       | BUY        | PASS   | Pass: actual outcome 'BUY' matches expected 'BUY'.
    high_capital_electronics_03_205     | ESCALATE   | PASS   | Pass: actual outcome 'ESCALATE' matches expected 'ESCALATE'.
    high_capital_electronics_03_220     | ESCALATE   | PASS   | Pass: actual outcome 'ESCALATE' matches expected 'ESCALATE'.
    ----------------------------------------------------------------------------------------------------
    EVALUATION COMPLETE. Accuracy: 100.0% (10/10 passed)
    ====================================================================================================
    

Detailed logs are saved in eval_results.md.


9. Security

The agent is designed with a defense-in-depth security model:

  • Coding Standards (CONTEXT.md): Defines rigorous standards for input parsing and prohibits raw shell execution or hardcoded keys.
  • Pydantic Input Validation: Blocks malformed queries or injection attempts prior to graph entry.
  • Pre-Commit Secrets Scanning: Enforces a semgrep hook that detects and blocks hardcoded API keys.
  • Tool Execution Guardian: Intercepts run_command via .agents/hooks.json to block destructive instructions (e.g. rm -rf / or mkfs).
  • System Risk Modeling (threat_model.md): Evaluates the workflow using a STRIDE threat assessment, proving mitigations against spoofing, data tampering, and privilege escalation.

10. Future Work

Planned improvements to transition the agent from prototype to a wider production scale:

  • Real Provider Adapter: Swap in Keepa API or Amazon Selling Partner API (SP-API) credentials behind the existing Marketplace MCP Server interface.
  • Predictive Sales-Rank Models: Train a custom Vertex AI model using historical pricing, sales ranks, and buybox metrics to forecast BSR stability trends rather than relying solely on Gemini LLM heuristics.
  • Additional Marketplace Adapters: Create dedicated adapters for eBay, Walmart, and Shopify under the same unified MCP schema to allow cross-marketplace sourcing.
  • Escalation Review Dashboard: Deploy a full-stack Cloud Run web portal where manager-level operators can view, filter, and batch approve/reject the agent's escalated sourcing decisions.