Inspiration

At 7:30 on a Tuesday morning in Eldoret, Kenya, a warehouse team finishes loading maize flour for school deliveries. Twelve bags left on the shelf. Thursday's order needs thirty.

Grace, the procurement officer, won't find out for ninety minutes. She's stuck in traffic and the stock position lives in her head and her Excel file. When she gets to her desk at 9 AM, she calls the supplier. No answer. She sends a WhatsApp. Waits an hour. When the callback comes, the order is simple: 100 bags, KES 320,000. But Grace can't pay. She needs James, the owner, to approve it. James is in a meeting negotiating a KES 800,000 school tender. She waits twenty minutes outside his door.

Then M-Pesa's daily limit blocks the transfer. James has to log into the bank portal himself. By 2:30 PM, seven hours after the stockout was discovered, the supplier finally receives payment.

Three hours of Grace's day gone. Two interruptions to a client meeting worth four times the flour order. A Thursday delivery that nearly failed. And while the entire office was focused on flour, three other products quietly dropped below threshold. Nobody checked.

This is James Waweru's business: Mama Pima Distributors. 47 dukas, 3 supermarkets, 12 schools across Uasin Gishu County. 200+ SKUs, 8 suppliers, KES 2.3 million in monthly procurement. This scene repeats 30 times a month.

McKinsey estimates generative AI can unlock between \$290B and \$550B in supply chain cost reductions globally, roughly 3-4% of functional costs. In East Africa, that potential is entirely unrealized. Distributors at this tier still run on WhatsApp and Excel.

We asked James what he wanted. He said: "I just want to press one button from my phone and know it's handled."

So we asked ourselves a harder question: what if the agent didn't just tell James he had a problem, but actually fixed it and paid the supplier before he finished his breakfast?

That question became StockAgent.

What We Built

StockAgent is an agentic commerce platform for FMCG distributors. Here is what we shipped, working end to end on the live demo:

Three AI Sub-Agents that run as a coordinated pipeline:

  • Stock Agent monitors all products against reorder thresholds, factors in 7-day dispatch velocity (how fast each product is actually selling), and classifies every item as critical, low, or healthy. A product at 30% stock with 100 units sold this week gets flagged before one at 50% with zero movement.
  • Order Agent selects the preferred supplier per product, pulls the default reorder quantity, and calculates total cost in KES.
  • Compliance Agent checks for duplicate pending orders. If a supplier already has an undelivered reorder cycle, the new order is blocked. Prevents double payments automatically.

PayPal Payouts (v1 API) for supplier payments. When the owner approves a reorder cycle, StockAgent converts KES to USD and sends the money directly to the supplier's PayPal email via POST /v1/payments/payouts.

PayPal Invoicing (v2 API) for recipient billing. After goods are dispatched, StockAgent creates a PayPal invoice with line items, quantities, and totals, then auto-sends it to the customer via POST /v2/invoicing/invoices/{id}/send. The customer receives a PayPal invoice they can pay online.

MCP Server (Model Context Protocol) that wraps all PayPal REST APIs as discoverable tools. The AI agent calls GET /tools, sees available payment capabilities (send payout, create invoice, check status), and invokes them. The agent handles reasoning. The MCP server handles execution. Any LLM can plug into this server without modification.

Three automatic trigger modes so no human has to remember to scan:

  1. On dispatch: fires when any dispatch drops stock below threshold
  2. On schedule: background scan every 60 minutes (configurable)
  3. On startup: full inventory scan when the server boots

Email notifications via Gmail/Nodemailer. HTML-formatted tables sent on every key event: stock alerts (with severity), payout confirmations (supplier + batch ID + amount), invoice summaries, and scan-complete confirmations even when all stock is healthy.

Discord notifications via webhook embeds, colour-coded by event type.

PDF invoice generation via PDFKit with line items, totals, and recipient details.

Full demo endpoint (POST /api/agent/demo) that runs the entire agentic commerce loop in one click: dispatches goods, triggers agents, auto-approves the reorder, sends PayPal payout, creates PayPal invoice, fires notifications. Judges can hit it repeatedly.

AG Grid dashboard with sortable, filterable tables for inventory, invoices, dispatches, reorder cycles, and PayPal transactions. Every PayPal API call (payouts and invoices) is logged and displayed in real time.

Postman collection with 26 API requests across 7 folders. Downloadable directly from the dashboard header.

Rule engine fallback. When no AI API key is configured, a deterministic rule engine applies the same severity thresholds, supplier selection, and compliance checks. Same decisions, same output format. The system is fully functional without any external AI service.

SQLite database with 8 tables: suppliers, products, recipients, dispatches, invoices, invoice_items, stock_events, reorder_cycles. Seeded with 5 products, 3 suppliers, 12 recipients (dukas, supermarkets, schools, wholesale), payment terms, and dispatch history.

Deployed live on Render as three free-tier services: stockagent-frontend-r0iq.onrender.com

The Full Cycle in 7 Minutes

Warehouse dispatch logged
        ↓
Stock drops below threshold → Agent activates automatically
        ↓
3 AI sub-agents analyze in parallel (Stock · Order · Compliance)
        ↓
Owner receives alert: "Unga Maize Flour at 12/40 bags.
Reorder 100 from Unga Group - KES 320,000. APPROVE?"
        ↓
Owner clicks APPROVE (one action)
        ↓
MCP Server → PayPal Payouts API → Supplier paid
        ↓
PayPal Invoicing API → Invoice auto-sent to recipient
        ↓
Email + Discord notifications fire

Before StockAgent: 18 hours from stock alert to payment. After StockAgent: 7 minutes.

$$\Delta t = t_{\text{manual}} - t_{\text{agent}} = 18\text{h} - \frac{7}{60}\text{h} \approx 17.9\text{ hours saved per cycle}$$

Across 30 cycles per month, that is 537 hours of procurement work per year returned to the business.

How We Built It

AI Layer

The primary agent orchestrates three sub-agents. Each sub-agent receives structured context (current stock levels, 7-day dispatch velocity, supplier lead times, pending reorder cycles) and returns a JSON decision with reasoning.

The Stock Agent weights urgency by dispatch velocity so fast-selling products get flagged first:

$$\text{urgency} = 1 - \frac{\text{current_stock}}{\text{reorder_threshold}} + \frac{\text{dispatch_velocity}_{7d}}{\text{reorder_quantity}}$$

The agent layer is LLM-agnostic. We built it on the Anthropic SDK, but the MCP server accepts tool calls from any model. Swap the LLM, keep the same payment gateway.

PayPal Layer

All PayPal calls go through the MCP server:

Tool PayPal Endpoint Purpose
send_payout POST /v1/payments/payouts Pay suppliers on approval
create_invoice POST /v2/invoicing/invoices Bill recipients for dispatches
send_invoice POST /v2/invoicing/invoices/{id}/send Auto-send to recipient
transaction_status GET /v1/payments/payouts/{id} Audit trail

All internal pricing is in Kenya Shillings, converted at the MCP boundary:

$$\text{USD} = \frac{\text{KES}}{130}$$

Stack

Layer Technology
AI Agent Anthropic SDK with rule-based fallback
Backend Node.js, Express
Database SQLite (better-sqlite3)
Payments PayPal Payouts v1 + Invoicing v2 via MCP Server
Invoice PDFs PDFKit
Frontend Vanilla JS SPA, AG Grid Community Edition
Notifications Nodemailer/Gmail, Discord webhooks, Twilio WhatsApp
Deployment Render (3 free-tier web services)

Challenges We Ran Into

1. The MCP + PayPal boundary

Getting the AI agent to call PayPal through the MCP server without leaking payment logic into the agent prompt took real iteration. The final design keeps the agent focused on decisions (what to order, from whom, how much) while the MCP server owns execution (OAuth, API calls, error handling, sandbox fallback). Separating these concerns was the most important architectural decision we made.

2. KES as the base currency

All internal pricing is in Kenya Shillings. PayPal requires USD. Building a clean conversion layer at the MCP boundary, rather than storing USD in the database, ensures the agent's cost reasoning stays in the currency that actually means something to James in Eldoret.

3. Demo reliability

A hackathon demo that requires pre-configured state is fragile. We built a /api/agent/demo endpoint that handles its own state: dispatches stock, triggers the agent, approves the cycle, creates the PayPal invoice, all in one deterministic sequence. Judges can hit it repeatedly and get a consistent result.

4. Compliance without false positives

The compliance sub-agent prevents duplicate supplier orders, but early versions blocked the demo whenever stale pending cycles existed from previous runs. We scoped compliance checks to the supplier level rather than the product level. This prevents real duplicates while keeping the demo flow clean.

5. WhatsApp on Twilio trial

Twilio's trial account requires pre-approved templates for WhatsApp messages, which blocks custom freeform alerts. We pivoted to Gmail email notifications via Nodemailer with App Passwords, and kept WhatsApp as an optional channel for production accounts.

Accomplishments We're Proud Of

  • Full agentic commerce loop in one click. Dispatch to AI Analysis to Supplier Payment to Recipient Invoice to Notifications. One human action. Everything else is autonomous.
  • Two PayPal APIs through a single MCP gateway. Payouts for suppliers, Invoicing for recipients. Same server, same tool pattern, clean separation.
  • Zero-key demo. The entire system runs in sandbox mode with no external API keys. Realistic transaction IDs, rule-based AI fallback, silent notification skip. Clone to running in under 5 minutes.
  • Real East African context. KES pricing, 12 recipient types, dispatch velocity, M-Pesa comparison. This is not a generic inventory demo. It is built for a real business in a real market.
  • LLM-agnostic design. The MCP server doesn't care which model calls it. Swap the AI provider without touching the payment layer.

What We Learned

The hardest part of agentic commerce is not the AI. It is the boundary between deciding and doing.

An LLM can analyze stock levels and recommend a reorder in milliseconds. But the moment it touches a live PayPal API, the error surface explodes: OAuth token expiry, rate limits, currency mismatches, duplicate batch IDs, network timeouts.

The MCP pattern solved this cleanly. By wrapping PayPal behind a tool interface, the agent stays in its lane (reasoning) while the MCP server handles all execution complexity. This is not just a hackathon architecture choice. It is how production agentic commerce systems should be built.

We also learned that "agentic" means nothing without a feedback loop. StockAgent closes the loop in both directions: the agent reads from the database (dispatch history, stock levels) and writes to it (reorder cycles, stock updates, invoice records). That bidirectional awareness is what makes it genuinely autonomous rather than just automated.

What's Next for StockAgent

  • Multi-supplier price comparison. Order sub-agent selects the cheapest supplier across the registered list, not just the preferred one.
  • WhatsApp APPROVE flow. Replace the dashboard button with a Twilio reply. The full "breakfast table" experience.
  • M-Pesa integration. PayPal for international suppliers, M-Pesa for local ones. Single agent, two payment rails.
  • Stocking schedule intelligence. Agent learns each recipient's ordering patterns and pre-stages stock before scheduled delivery days.
  • Diron Technologies product. We are building StockAgent into our consulting practice as a commercial product for FMCG distributors across East Africa.

Built With

Share this project:

Updates

Submission history