Skip to content
vakrahulPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

9 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Agent Commerce Gateway

AI agents already understand what humans want to buy. The missing layer is a safe transaction system that converts agent intent into an authorized, verifiable payment. This repository builds that layer — and uses it to grow merchant revenue.

Feature Highlights

# Feature What it does
1 AI Buyer Agent LLM function-calling loop — searches catalog, gets quotes, scores upsells. No payment tool on the agent surface.
2 Agent-to-Agent Commerce Any external agent (ACME Bot, Claude, Cursor) can transact with the gateway over public HTTP — fully proven by external_buyer.py.
3 Four Commerce Channels Direct UI, MCP stdio, merchant SDK, and protocol adapters (UAP/ACP/AP2/x402) all hit the same deterministic core.
4 UAP-Shaped Authorization Register / verify / mandate lifecycle enforced on checkout when agent_id or mandate_id is sent.
5 MCP with Claude Desktop Five tools over stdio — search, quote, recommend, submit intent. Claude can buy from TrailKit without a browser.
6 XGBoost ML Upselling Trained on synthetic pair data (ROC-AUC 0.7125 vs 0.5606 popularity baseline). Merchant must approve before it shows buyers.
7 Merchant Revenue Center PAID-only analytics, product-pair mining, ML-ranked opportunities, A/B lift measurement.
8 Treatment / Control A/B Every eligible checkout tagged T or C by session hash. Lift is measured on PAID orders only.
9 Merchant Campaign Control Merchant creates, activates, and deactivates discount campaigns. Agents can see live campaign prices.
10 Reusable SDK Drop-in middleware (agentic_commerce_sdk). Any merchant binds their catalog + Razorpay keys and gets a safe agent-commerce surface instantly.
11 Three Merchant Apps TrailKit (main demo), Ecoyaan (eco-products, live on Vercel), ShopKart (SDK example on port 9001).
12 Policy Engine Enforces spend caps, currency, duplicate carts, stock checks — with full decision trace in the audit ledger.
13 One-Time Cart-Bound Authorization Authorizations bind to one cart hash, expire, and are atomically consumed exactly once.
14 Append-Only Audit Trail Every state transition, tool call, webhook, and policy decision is written to audit_events. No UPDATE or DELETE API.
15 Razorpay Test Mode End-to-End Real order creation, checkout.js capture, HMAC-verified webhook, payments API cross-check — all idempotent.
16 Cloudflare Webhook Tunnel cloudflared exposes /webhooks/razorpay publicly so Razorpay cloud can reach localhost. Named tunnel = same URL every run.
17 Price-Mismatch Safety If merchant changes price after authorization, checkout is blocked before any Razorpay call — audited as BLOCKED_PRICE_MISMATCH.
18 Graceful Failure Handling 6 failure types handled cleanly: price mismatch, duplicate cart, out-of-stock, payment failure, forged webhook, rail outage.

What it is

A working gateway between an autonomous AI buyer and a real merchant storefront ("TrailKit Travel Co."), running on Razorpay Test Mode:

  • Buyer side: an LLM function-calling agent that searches the catalog, obtains fresh quotes, scores upsells with XGBoost, and submits a bounded purchase plan. The LLM has no payment tool; money moves only after explicit human approval.
  • Merchant side: an AI Revenue Center with analytics, product-pair mining, model-ranked opportunities, a merchant approval gate, and treatment/control (A/B) attribution on every eligible checkout.
  • Deterministic core: a policy engine, one-time cart-bound authorizations, fresh-quote revalidation, a final amount boundary inside the order-creation transaction, idempotent webhook processing, and an append-only audit ledger.
  • Protocol surface: GET /.well-known/agent-commerce.json exposes eight commerce primitives (DISCOVER, CATALOG, QUOTE, INTENT, AUTHORIZE, PAY, VERIFY, FULFILL). An independent client ("ACME Procurement Bot") completes a purchase using only these public endpoints, proving the merchant is transactable by any agent.

Verified results (summary)

  • Real Razorpay Test Mode capture end-to-end, webhook signature verified, cross-checked against the payments API, completed idempotently.
  • 540 generated adversarial/edge-case scenarios against the deterministic core: 100% correct handling. Zero unauthorized successes, zero duplicate leaks, zero missed price changes, 100% webhook safety.
  • 50 live LLM agent runs graded on deterministic criteria: 50/50 pass (first run was 49/50; one prompt rule was clarified and re-run in full).
  • XGBoost upsell model: test ROC-AUC 0.7125, beating a popularity baseline (0.5606) and an association-rules baseline (0.7020). Metrics and limits are documented in docs/MODEL_CARD.md.

See docs/EVALUATION.md for methodology and full numbers.

Quick start

Prerequisites: Python 3.11+, Node 18+, PostgreSQL 14+.

  1. Backend setup

    cd backend python -m venv .venv .venv\Scripts\pip install -r requirements.txt (Windows) copy .env.example .env then fill values

    Required environment (.env): DATABASE_URL, RZP_KEY_ID, RZP_KEY_SECRET, RZP_WEBHOOK_SECRET, GEMINI_API_KEY, GEMINI_MODEL. Optional: QDRANT_URL, QDRANT_API_KEY (vector RAG falls back to Postgres search without them).

  2. Create schema and seed the merchant

    .venv\Scripts\python scripts\create_db.py set DATABASE_URL=postgresql+psycopg://postgres:@localhost:5432/agent_commerce .venv\Scripts\python scripts\seed.py

  3. Run the API (default port 8123)

    .venv\Scripts\python -m uvicorn app.main:app --port 8123

  4. Frontend

    cd ..\frontend npm install npm run dev (http://localhost:5173)

  5. Try it

    • Open http://localhost:5173/buyer and send: "I'm going to Bangalore for 5 days. Find me a waterproof laptop backpack under Rs.3000"
    • Approve the plan card; complete the Razorpay Test checkout.
    • Independent-agent proof: python scripts\external_buyer.py [--demo-failure]

Tests and evaluation

cd backend && .venv\Scripts\python -m pytest # unit/integration .venv\Scripts\python eval\run_eval.py # 540-scenario suite .venv\Scripts\python eval\agent_eval.py # 50 live agent runs .venv\Scripts\python ml\prepare_catalog_synth.py && .venv\Scripts\python ml\train_upsell.py

Webhooks during local development

Razorpay needs a public HTTPS URL. Start a quick tunnel:

tools\cloudflared.exe tunnel --url http://localhost:8123

Then register https:///webhooks/razorpay in the Razorpay dashboard (payment.captured, payment.failed) with the same secret as RZP_WEBHOOK_SECRET. Checkout also works without webhooks: the callback verification path completes orders, and both paths are idempotent.

Documentation

  • ARCHITECTURE.md — components, data flow, safety design, protocol layer
  • EVALUATION.md — evaluation methodology and measured results
  • MODEL_CARD.md — upsell model: data, features, metrics, limitations
  • DEMO_SCRIPT.md — five-minute demonstration walkthrough
  • MCP_SERVER.md — Model Context Protocol surface (connect Claude Desktop)
  • SDK.md — plug-and-play agent-commerce middleware for merchants

Gallery & Integrations

Screenshot 2026-09-04 174403 Screenshot 2026-09-04 175551 Screenshot 2026-09-04 175459

1. Shopkart Merchant

Screenshot 2026-09-04 174734

2. Ecoyaan Merchant

Screenshot 2026-09-04 175337

3. Claude Desktop

Screenshot 2026-09-04 175207 Screenshot 2026-09-04 175127

4. ML Upsell Growth

Screenshot 2026-09-04 175551

MCP server

The merchant is also exposed as a Model Context Protocol server, so any MCP client (Claude Desktop, Cursor, Razorpay Agent Studio) can discover and buy from TrailKit through the same deterministic core. Tools: search_catalog, get_product, request_quote, score_recommendations, submit_purchase_intent (gated; refuses when caps are exceeded). Setup and Claude Desktop config: docs/MCP_SERVER.md. Smoke test:

cd backend && .venv\Scripts\python mcp_server\smoke_test.py

SDK: agent-commerce in ten lines

The gateway's guardrails are also packaged as reusable middleware (backend/sdk/agentic_commerce_sdk/). Any merchant app binds its own catalog resolver and Razorpay test keys, then exposes /agent/quote, /agent/purchase-intent and a verified webhook endpoint - server-side pricing, bounded intents, hard ceilings, and explainable refusals included. Working (details in docs/SDK.md; a real Test Mode order was created through the SDK).

Vision and Capabilities

We have:

  • AI buyer.
  • Agent-to-agent commerce.
  • UAP-shaped authorization.
  • ML-powered upselling.
  • Merchant-controlled campaigns.
  • Four commerce channels.
  • MCP with Claude Desktop.
  • A reusable SDK.
  • Three merchant applications.
  • Razorpay Test Mode.
  • Cloudflare webhook connectivity.
  • Policy enforcement.
  • And an append-only audit trail.

Our final vision is: AI understands the customer. ML finds the revenue opportunity. The merchant decides. The gateway protects the money. Razorpay executes the payment. And the ledger proves what happened.

That is how we make merchants sellable to AI buyers while helping them grow their revenue.

Architecture & Integration

Below are the 4 commerce channels exposed by the gateway, detailing the Action and Response flow for MCP agents and UAP alignment.

Channel 1: Discovery & Catalog

sequenceDiagram
    participant Agent as MCP Client (Agent)
    participant Gateway as Agent Commerce Gateway
    
    Agent->>Gateway: Action: search_catalog(query)
    Gateway-->>Agent: Response: SKU list, prices, live stock
    
    Agent->>Gateway: Action: get_product(sku)
    Gateway-->>Agent: Response: Detailed description, features
Loading

Channel 2: Intent & Quote

sequenceDiagram
    participant Agent as MCP Client (Agent)
    participant Gateway as Agent Commerce Gateway
    participant ML as XGBoost ML Engine
    
    Agent->>Gateway: Action: request_quote(sku)
    Gateway-->>Agent: Response: quote_id, server-computed paise, TTL
    
    Agent->>Gateway: Action: score_recommendations(cart)
    Gateway->>ML: Evaluate Pairings
    ML-->>Gateway: Ranked Upsells
    Gateway-->>Agent: Response: Cross-sell SKUs
Loading

Channel 3: Authorization (Policy Enforcement)

sequenceDiagram
    participant Agent as MCP Client (Agent)
    participant Gateway as Agent Commerce Gateway (Policy Engine)
    
    Agent->>Gateway: Action: submit_purchase_intent(quote_id, limit)
    Gateway->>Gateway: Evaluate Policy (Price, TTL, Duplicates)
    alt Limit Exceeded or Stale Quote
        Gateway-->>Agent: Response: REFUSED (Structured Error)
    else Policy Passed
        Gateway-->>Agent: Response: AUTHORIZED (Order Pending)
    end
Loading

Channel 4: Payment & Verification (Rail & Ledger)

sequenceDiagram
    participant Client as Client / UAP Mandate
    participant Gateway as Agent Commerce Gateway
    participant Razorpay as Razorpay Test Mode
    participant Ledger as Audit Ledger
    
    Client->>Gateway: Approve Intent / Pay
    Gateway->>Razorpay: Capture Payment
    Razorpay-->>Gateway: Payment Status / Verify
    
    par Webhook Reliability
        Razorpay-)Gateway: Webhook (HMAC verified)
    end
    
    Gateway->>Ledger: Append-only event (PAID)
    Gateway-->>Client: Response: Verified Receipt
Loading

Positioning and disclosures

This is an experimental interoperability layer built around common agent-commerce primitives shared by emerging protocols (NPCI UAP, ACP, AP2, x402). It is not an official implementation of any of them and no compliance is claimed. Adapters for specific specs plug in at the protocol boundary without touching the core.

All money movement uses Razorpay Test Mode. Training data for the upsell model is synthetic and clearly labeled as such wherever used. Known limitations are listed in docs/EVALUATION.md rather than hidden.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages