safe-cart-ai

safe-cart-ai

Enables AI agents to browse product catalogs and make purchases through a policy engine that enforces spending limits, requires human approval for certain amounts, and logs all actions to an audit trail.

Category
Visit Server

README

SafeCart-AI

Track: 01 — AI Growth & Agentic Commerce

Problem: Soon, people won't shop by chatting with a merchant's bot — they'll ask their own AI agent to shop for them. Merchants need a safe way to let an AI agent browse their catalog and spend money on a customer's behalf. This project provides that missing trust layer.

What it does

SafeCart-AI exposes a merchant's product catalog to any MCP-compatible AI agent (such as Claude) through the Model Context Protocol.

The agent can browse products and request purchases, but every purchase must pass through a policy engine before Razorpay test-mode order creation.

The policy engine enforces:

  • Explainability — the agent must provide a meaningful reason for the purchase.
  • Bounded spend — purchases are controlled by per-transaction limits and a session-wide spending cap.
  • Gating — mid-range purchases are sent for human approval instead of being automatically executed.
  • Audit trail — purchase attempts are logged with what was requested, why it was requested, and what the system decided.
  • Graceful failure handling — invalid requests such as out-of-stock products are rejected with a clear explanation.

Architecture

AI Agent (Claude, etc.)
        │
        │ MCP tools:
        │ browse_products
        │ get_product_details
        │ request_purchase
        │ get_audit_trail
        ▼
  mcp_server.py
        │
        ▼
    policy.py ──────────────► SQLite audit log
        │                       logs/audit.db
        │
        │ approved requests
        ▼
razorpay_client.py ────────► Razorpay Test-Mode Orders API

dashboard.py (Flask)
        │
        └────────────────────► Human approve/reject UI

Why this design

The payment integration is deliberately separated from the policy engine.

razorpay_client.py is only called after the policy layer approves a purchase request. This keeps the decision-making logic separate from the payment integration and makes the purchase decision explainable and auditable.

The project is designed around the principle:

AI can request a purchase, policy decides whether it is allowed, and higher-risk purchases can require human approval.

Policy Rules

The current demo uses the following limits:

Purchase Amount Decision
≤ ₹2,000 Auto-approved
₹2,001–₹6,000 Human approval required
> ₹6,000 Auto-rejected
Session total > ₹15,000 Rejected

These values can be adjusted in policy.py.

The agent must also provide a meaningful purchase reason. Requests with a missing or very short reason are rejected.

Project Structure

agent-commerce-gateway/
│
├── mcp_server.py
├── policy.py
├── razorpay_client.py
├── dashboard.py
├── test_agent.py
├── requirements.txt
├── README.md
├── .env.example
│
├── data/
│   └── products.json
│
├── templates/
│   └── dashboard.html
│
└── logs/
    └── audit.db

Main files

File Purpose
mcp_server.py Exposes merchant and purchase functionality as MCP tools
policy.py Applies purchase policies and records decisions
razorpay_client.py Creates Razorpay test-mode orders
dashboard.py Provides the human approval/rejection dashboard
test_agent.py Simulates an AI agent and tests the MCP flow
data/products.json Merchant product catalog
logs/audit.db SQLite audit database

Setup

1. Create a virtual environment

Windows:

python -m venv venv
venv\Scripts\activate

Linux/macOS:

python3 -m venv venv
source venv/bin/activate

2. Install dependencies

pip install -r requirements.txt

3. Configure Razorpay Test Mode

Create a .env file from .env.example and add your Razorpay TEST MODE credentials:

RAZORPAY_KEY_ID=your_test_key_id
RAZORPAY_KEY_SECRET=your_test_key_secret

Never commit .env or real credentials to GitHub.

Running the Project

1. Start the MCP server

python mcp_server.py

This starts the server that an MCP-compatible AI agent connects to.

2. Connect an AI agent

For Claude Desktop, add the MCP server to your Claude Desktop configuration:

{
  "mcpServers": {
    "agent-commerce-gateway": {
      "command": "python",
      "args": [
        "/absolute/path/to/mcp_server.py"
      ]
    }
  }
}

Replace /absolute/path/to/mcp_server.py with the actual path on your computer.

Restart Claude Desktop after saving the configuration.

You can then ask the connected AI agent:

Browse this merchant's products.

or:

Buy me the wireless earbuds because I need them for online classes.

3. Start the dashboard

Open another terminal:

python dashboard.py

Then open:

http://localhost:5001

The dashboard is used to view the audit trail and review purchases that require human approval.

How the Purchase Flow Works

Example 1 — Auto-approved purchase

Suppose the user asks:

Buy me the Wireless Earbuds because I need them for online classes.

The AI sends a purchase request containing the product, quantity, and reason.

If the total is within the auto-approval limit:

Purchase Request
       ↓
Policy Check
       ↓
Approved
       ↓
Razorpay Test Order

Example 2 — Human approval

Suppose the user requests the Mechanical Keyboard priced at ₹3,499.

Because it is above the auto-approval limit but within the human-review range:

Purchase Request
       ↓
Policy Check
       ↓
Pending Human Approval
       ↓
Dashboard
       ↓
Human Approves / Rejects

Prototype note: The current implementation records the dashboard approval in the audit database. A production implementation should connect that approval to the subsequent Razorpay order-creation step.

Example 3 — Graceful rejection

If a requested product is out of stock:

Purchase Request
       ↓
Policy Check
       ↓
Out of Stock
       ↓
Rejected
       ↓
Clear Explanation

The system does not silently fail or proceed with payment.

MCP Tools

The MCP server exposes four main tools:

browse_products()

Returns the merchant's current product catalog.

get_product_details(product_id)

Returns detailed information for a specific product.

request_purchase(product_id, quantity, reason)

Requests a purchase on behalf of the user. The request is evaluated by the policy engine before any Razorpay order is created.

get_audit_trail()

Returns purchase attempts and their decisions for the current session.

Audit Trail

Every purchase attempt is stored in SQLite.

The audit record includes:

  • Timestamp
  • Session ID
  • Product ID
  • Product name
  • Price
  • Quantity
  • Purchase reason
  • Decision
  • Decision explanation

This makes it possible to understand:

What did the AI request? Why did it request it? What did the system decide?

Demo Script

For the project demonstration:

  1. Connect the MCP server to the AI agent.
  2. Ask the AI agent to browse the merchant catalog.
  3. Request the Wireless Earbuds (p001, ₹1,499) with a clear reason.
  4. Show that the purchase is auto-approved and a Razorpay test order is created.
  5. Request the Mechanical Keyboard (p003, ₹3,499).
  6. Show that it requires human approval through the dashboard.
  7. Request the 4K Webcam (p005).
  8. Show that the out-of-stock request is rejected gracefully.
  9. Show the complete audit trail.

Testing

A test agent is included to exercise the main MCP flow.

Run:

python test_agent.py

The test script demonstrates:

  • MCP connection
  • Product catalog browsing
  • Low-value purchase
  • Medium-value purchase
  • Out-of-stock purchase
  • Audit trail retrieval

What Broke, and How It Was Solved

1. Invalid purchase reasons

The policy layer requires a meaningful reason for every purchase. Requests with a missing or very short reason are rejected instead of allowing an unexplained purchase.

2. Out-of-stock products

An out-of-stock request is handled inside the policy layer and returned as a clear rejection instead of causing the application to crash.

3. Razorpay failure

Razorpay order creation is wrapped separately from the policy decision. If test-order creation fails after a policy approval, the MCP server catches the exception and returns a clear payment_error result instead of crashing.

4. Spending limits

Purchase totals are checked against both transaction-level limits and the session spending cap before approval.

Limitations / What's Next

This is a prototype designed around the hackathon/demo scope.

  • Session identity is simplified: the current implementation uses one session ID per server run. A production system should associate requests with authenticated agent and user identities.
  • Policy thresholds are static: a production version could adjust limits using agent trust history, user preferences, risk scores, or merchant rules.
  • Test-mode payments only: the project creates Razorpay test-mode orders and does not implement a complete real-payment capture flow.
  • Dashboard authentication: the current Flask dashboard is intended for demonstration and should use authentication and authorization in production.
  • Human approval execution: the current prototype records a human approval in the audit database; a production implementation should connect the approval action to the subsequent payment/order execution step.
  • Prototype security: production deployment would require stronger validation, authentication, authorization, secure session management, and protection against malicious or compromised agents.

Future Scope

Possible future improvements include:

  • Agent authentication and identity management
  • User-specific spending limits
  • Dynamic risk scoring
  • Agent trust/reputation scoring
  • Adaptive policy thresholds
  • Payment status webhooks
  • Complete payment capture flow
  • Secure dashboard authentication
  • Fraud detection
  • Advanced analytics
  • More comprehensive automated tests

🏆 One-Line Pitch

SafeCart-AI is a policy-controlled MCP commerce gateway that lets AI agents shop on behalf of users while enforcing explainable spending limits, human approval for risky purchases, and a complete audit trail.

Core Principle

AI Agent
   ↓
Request Purchase
   ↓
Policy Engine
   ↓
┌──────────────┬─────────────────┬──────────────┐
│              │                 │
Approved    Human Review       Rejected
│              │                 │
↓              ↓                 ↓
Razorpay    Dashboard         No Payment
Test Order  Approval
│              │
└──────────────┴─────────────────┐
                                 ↓
                           Audit Trail

AI requests. Policy decides. Humans control risk. Payment executes only after authorization.

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
E2B

E2B

Using MCP to run code via e2b.

Official
Featured
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured