Skip to main content
Glama
Retail POS MCP Server

Retail POS MCP Server

README.md
<p align="center">
  <img src="./assets/hero.svg" width="100%" alt="Retail POS MCP Server: AI clients -> dual-transport MCP (stdio + OAuth 2.1 HTTP) -> 31 Zod tools -> Store Web API -> PostgreSQL with RBAC and audit log" />
</p>

<p align="center">
  <img src="https://img.shields.io/badge/MCP-Server%20v1.32-22d3ee?style=for-the-badge&labelColor=0b1020" alt="MCP Server" />
  <img src="https://img.shields.io/badge/Tools-19%20Read%20%C2%B7%2012%20Write-a78bfa?style=for-the-badge&labelColor=0b1020" alt="31 Tools" />
  <img src="https://img.shields.io/badge/Auth-OAuth%202.1%20%2B%20PKCE-34d399?style=for-the-badge&labelColor=0b1020" alt="OAuth 2.1 PKCE" />
  <img src="https://img.shields.io/badge/Runtime-Node.js%20ESM-fbbf24?style=for-the-badge&labelColor=0b1020" alt="Node.js ESM" />
  <img src="https://img.shields.io/badge/Schema-Zod%20v4%20%2B%20Express%205-f472b6?style=for-the-badge&labelColor=0b1020" alt="Zod + Express 5" />
</p>

<h3 align="center">A production-grade Model Context Protocol (MCP) server that lets AI assistants safely read and manage a multi-tenant retail POS store in plain Englishβ€”with RBAC, OAuth 2.1 + PKCE, and full audit logging.</h3>

> **About this repo.** This repository showcases the complete architecture, source code, tests, and engineering walkthrough of an **API-first Retail POS MCP Server** I designed and built. Store/product branding is intentionally generalized; all code, schemas, OAuth flows, and tests are self-contained and runnable out of the box (including a mock Store API in [`examples/mock-store-api.js`](examples/mock-store-api.js)).

---

## πŸ“Œ Contents

1. [The idea in one minute](#-the-idea-in-one-minute)
2. [Architecture & dual transports](#%EF%B8%8F-architecture--dual-transports)
3. [How it works: Read-Only vs Write / Mutating](#-how-it-works-read-only-vs-write--mutating)
4. [OAuth 2.1 + PKCE remote connector](#-oauth-21--pkce-remote-connector)
5. [Skills, tools & tech stack](#-skills-tools--tech-stack)
6. [How I built it (step by step)](#%EF%B8%8F-how-i-built-it-step-by-step)
7. [Real-world use cases](#-real-world-use-cases)
8. [Key advantages](#-key-advantages)
9. [Quickstart & testing](#%EF%B8%8F-quickstart--testing)
10. [Repository structure](#%EF%B8%8F-repository-structure)
11. [Author](#-author)

---

## ⚑ The idea in one minute

Retail store owners and managers spend hours clicking through back-office admin panels to check daily sales, audit cashier shift discrepancies, update variant prices, or record customer credit (*Khata*) repayments.

Instead of giving an LLM raw SQL access to a multi-tenant database (dangerous!), this **MCP server** sits strictly in front of the **Store Web REST API** and authenticates as a **real store user**:

| Before (Admin UI / Raw DB Risk) | After (API-First MCP Server) |
|---|---|
| Manual clicks across sales, catalogue, shifts, and credit screens | Ask in plain English from **Claude Code, Claude Desktop, claude.ai, or mobile** |
| Direct DB bots bypass validation and break multi-tenant isolation | **Zero direct DB access** β€” every call runs through API validation, RBAC, and RLS |
| AI edits look anonymous or unattributed | Every mutation writes to the **Store Activity Audit Log** under that user's name |
| Separate integrations per client (local vs cloud) | **One shared core** (`createServer.js` + `tools.js`) powers both `stdio` and OAuth HTTP |
| Floating-point rupee bugs in financial mutations | **Rupees in β†’ integer paise out** (`toPaise`), plus UUID idempotency keys |

```mermaid
flowchart LR
    U["πŸ‘€ Store Owner / Manager<br/>Plain-English Prompt"] --> AI["πŸ€– AI Client<br/>Claude Code Β· Desktop Β· claude.ai"]
    AI --> T{"Transport"}
    T -- "Local" --> STD["stdio<br/>server.js"]
    T -- "Remote" --> HTTP["Streamable HTTP + OAuth 2.1<br/>httpServer.js"]
    STD & HTTP --> CORE["βš™οΈ Shared MCP Core<br/>31 Zod Tools + Annotations"]
    CORE -- "Authorization: Bearer &lt;storeToken&gt;" --> API["πŸ›‘οΈ Store Web API<br/>RBAC Β· Validation Β· Audit Log"]
    API --> DB[("πŸ—„οΈ PostgreSQL<br/>Row-Level Security")]

    style CORE fill:#1e1b4b,stroke:#a78bfa,color:#fff
    style API fill:#064e3b,stroke:#34d399,color:#fff
```

---

## πŸ—οΈ Architecture & dual transports

<p align="center">
  <img src="./assets/mcp-architecture-flow.gif" width="100%" alt="Animated end-to-end request lifecycle across AI Client, Transport (stdio or OAuth 2.1 HTTP), MCP Core (31 Zod Tools and Rupee-to-Paise conversion), Store Web API (RBAC), and PostgreSQL Audit Log" />
</p>

The server runs in **two transport modes** from the exact same tool registry ([`src/tools.js`](src/tools.js)) and server factory ([`src/createServer.js`](src/createServer.js)):

```mermaid
flowchart TB
    subgraph Local["1. Local Mode (src/server.js)"]
        direction LR
        LC["Claude Code / Claude Desktop"] -- "stdin / stdout<br/>JSON-RPC" --> ST["StdioServerTransport"]
        ST --> AC1["apiClient.js<br/>(lazy login + auto re-auth on 401)"]
    end

    subgraph Remote["2. Remote Connector Mode (src/httpServer.js)"]
        direction LR
        RC["claude.ai / Mobile / Remote MCP"] -- "HTTPS" --> CF["Cloudflare Tunnel / Reverse Proxy"]
        CF -- "127.0.0.1:8787" --> EX["Express 5 + OAuth 2.1 Router<br/>+ StreamableHTTPServerTransport"]
        EX --> AC2["Stateless per-request apiClient.js<br/>(Bearer token from OAuth session)"]
    end

    AC1 & AC2 -- "Bearer &lt;store_tenant_session&gt;" --> API["Private Store Web API (:4000)<br/>RBAC + Optimistic Versioning + Audit Log"]
    API --> PG[("PostgreSQL 19<br/>Row-Level Security")]

    classDef box fill:#0f172a,stroke:#22d3ee,color:#e2e8f0
    class LC,ST,AC1,RC,CF,EX,AC2 box
```

| Transport | Entry Point | Auth Strategy | Best For |
|---|---|---|---|
| **Local `stdio`** | [`src/server.js`](src/server.js) | `STORE_EMAIL` + `STORE_PASSWORD` in local env; logs in on first tool call and auto-refreshes on `401` | Claude Code CLI, Claude Desktop, Cursor on a trusted dev/manager machine |
| **Remote Streamable HTTP** | [`src/httpServer.js`](src/httpServer.js) | **OAuth 2.1 + PKCE (`S256`)** via store sign-in page; passwords are never stored; stateless per request | `claude.ai`, Claude Desktop custom connectors, mobile apps via Cloudflare Tunnel |

πŸ“– Deep dive: [`docs/01-architecture-and-transports.md`](docs/01-architecture-and-transports.md)

---

## πŸ”’ How it works: Read-Only vs Write / Mutating

<p align="center">
  <img src="./assets/read-vs-write-safety.gif" width="100%" alt="Animated comparison of the 19 Read-Only tools (auto-run, paise-to-rupee formatting) vs 12 Write/Change tools (confirm-first guardrail, rupee-to-paise conversion, UUID idempotency keys, RBAC and Audit Log)" />
</p>

Every tool in [`src/tools.js`](src/tools.js) declares standard **MCP tool annotations** so AI clients know when a call is safe to auto-execute versus when to pause for human confirmation:

```js
export const READ   = { readOnlyHint: true,  destructiveHint: false, idempotentHint: true,  openWorldHint: false };
export const WRITE  = { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false };
export const CHANGE = { readOnlyHint: false, destructiveHint: true,  idempotentHint: true,  openWorldHint: false };
```

### 1. Read-Only Tools (`19` tools β€” `readOnlyHint: true`)
- **Zero side effects:** Map strictly to `GET` endpoints; AI clients run them freely to gather context, look up UUIDs, and generate summaries.
- **POS-sensitive domains stay Read-Only:** Sales bills, returns/credit notes, and cashier shift X/Z reports are **read-only by design**β€”live POS checkout belongs at the counter, never in an AI chat.
- **Raw paise transparency:** API responses return exact integer `...Paise` values; server instructions direct the AI to divide by `100` when presenting `β‚Ή` amounts.

### 2. Write & Mutating Tools (`12` tools β€” `6 WRITE` + `6 CHANGE`)
- **Confirm-first guardrail:** Server instructions (`src/createServer.js`) require the assistant to confirm exact rupee amounts, SKUs, and status changes with the user before calling mutating tools.
- **Float-safe money conversion:** Inputs accept human-friendly rupees (`849.50`) and pass through [`toPaise()`](src/tools.js) (`Math.round(num * 100)` via [`src/money.js`](src/money.js)) so floating-point precision errors never hit financial ledgers.
- **Idempotency & concurrency guards:**
  - `record_khata_payment` and `adjust_khata_balance` generate a fresh `crypto.randomUUID()` per request to prevent duplicate ledger entries on retries.
  - `update_store_settings`, `update_product`, and `update_variant` pass optional `expectedVersion` for optimistic concurrency control.
- **Role-gated at the API:** Even if a prompt tries to invoke a write tool, a `CASHIER` session is rejected by the backend RBAC middleware (`403 Forbidden`), while `INVENTORY_MANAGER` or `STORE_OWNER` succeeds and logs the edit.

<details>
<summary><b>πŸ“‹ Full 31-Tool Inventory (19 Read-Only Β· 12 Write/Change)</b></summary>

| Domain | Read-Only Tools (`19`) | Write / Change Tools (`12`) |
|---|---|---|
| **Session & Store** | `whoami`, `get_overview`, `get_store_settings` | `update_store_settings` (`CHANGE`) |
| **Catalogue & Variants** | `list_products`, `get_product`, `list_taxonomy` | `create_taxonomy_item` (`WRITE`), `create_product` (`WRITE`), `update_product` (`CHANGE`), `set_product_status` (`CHANGE`), `add_variants` (`WRITE`), `update_variant` (`CHANGE`) |
| **Sales, Returns & Shifts** | `list_sales`, `sales_summary`, `get_sale`, `list_returns`, `returns_summary`, `list_shifts`, `get_shift` | *None β€” POS counter only* |
| **Customers & Credit Ledger** | `list_customers`, `khata_summary`, `get_customer` | `create_customer` (`WRITE`), `set_customer_credit` (`CHANGE`), `record_khata_payment` (`WRITE`), `adjust_khata_balance` (`WRITE`) |
| **Staff & POS Devices** | `list_staff`, `list_roles_and_outlets`, `list_devices` | `create_staff` (`WRITE`) |

</details>

πŸ“– Complete reference: [`docs/03-tools-read-vs-write.md`](docs/03-tools-read-vs-write.md)

---

## πŸ” OAuth 2.1 + PKCE remote connector

<p align="center">
  <img src="./assets/oauth-pkce-sequence.svg" width="100%" alt="OAuth 2.1 + PKCE S256 sequence diagram between AI Client, MCP HTTP Connector, and Store Web API" />
</p>

Remote connectors (`claude.ai`, mobile) cannot safely store plaintext passwords in local JSON config files. Instead, [`src/oauthProvider.js`](src/oauthProvider.js) and [`src/httpServer.js`](src/httpServer.js) implement a full **OAuth 2.1 Authorization Server** using `@modelcontextprotocol/sdk`'s `mcpAuthRouter` and `requireBearerAuth`:

1. **Protected Resource Discovery:** Unauthenticated `POST /mcp` returns `401` with `WWW-Authenticate: Bearer resource_metadata="..."`.
2. **Dynamic Client Registration (`POST /register`):** Only redirect URIs matching `MCP_REDIRECT_HOSTS` (`claude.ai`, `claude.com`, `localhost`, `127.0.0.1`) over HTTPS (or local HTTP) are acceptedβ€”blocking open-redirect phishing.
3. **PKCE `S256` & Store Sign-In (`GET /authorize` β†’ `POST /oauth/login`):** Serves a clean login form protected by `express-rate-limit` (`20 attempts / 15 min / IP`). Credentials are forwarded once to `/api/store/auth/login` and **immediately discarded**β€”only the resulting session token stays in memory.
4. **Single-Use Code β†’ Resource-Bound Token (`POST /token`):** Authorization codes expire in **2 minutes** and are deleted on first exchange; issued Bearer tokens are bound to `/mcp` and expire with the 12-hour store session (no refresh tokens).
5. **Instant Revocation:** If a staff account is deactivated or logged out, the next `401` calls `provider.forgetToken()`, immediately invalidating the connector token.

πŸ“– Security deep dive: [`docs/02-oauth-security-and-rbac.md`](docs/02-oauth-security-and-rbac.md)

---

## 🧰 Skills, tools & tech stack

### Engineering Skills & AI Workflows Used
- **Claude Code CLI & Progressive Context Docs:** Maintained structured architecture & module reference docs (`PROJECT_CONTEXT.md`, module specs) so AI coding sessions accurately mapped DTOs, RBAC permission keys, and error formats before writing code.
- **MCP Tool Design Patterns:** Applied strict `READ` / `WRITE` / `CHANGE` annotations, server-level behavioral instructions, ID-first lookup patterns, and deterministic `rupees β†’ integer paise` adapters.
- **Test-Driven Verification:** Built isolated unit tests (mock `fetch`), full OAuth + Streamable HTTP integration tests, and live `stdio` end-to-end tests using Node's native test runner.

### Tech Stack

| Layer | Technology / Package | Version | Purpose |
|---|---|---|---|
| **MCP SDK** | `@modelcontextprotocol/sdk` | `1.32.2` | `McpServer`, `StdioServerTransport`, `StreamableHTTPServerTransport`, `mcpAuthRouter`, `requireBearerAuth`, and test `Client` |
| **Schema Validation** | `zod` | `4.6.7` | Runtime argument validation & JSON Schema generation for all 31 tools |
| **HTTP Server** | `express` | `5.3.0` | Stateless `/mcp` endpoint, OAuth metadata routes, `/oauth/login`, `/health` |
| **Abuse Protection** | `express-rate-limit` | `8.7.5` | Brute-force throttling (`20 req / 15 min / IP`) on `/oauth/login` |
| **Runtime & Crypto** | **Node.js (ESM)** | `26.x` | Native `fetch`, `AbortSignal.timeout`, `node:crypto` (`randomUUID`, `randomBytes`), `node:test` |
| **Backend Context** | **Express 5 + Prisma + PostgreSQL 19** | β€” | Multi-tenant Store Web API with RBAC, Row-Level Security (RLS), and immutable audit logs |
| **Secure Exposure** | **Cloudflare Tunnel (`cloudflared`)** | latest | Exposes local `:8787` over HTTPS without opening inbound firewall ports or exposing the API/DB |

πŸ“– Full stack notes: [`docs/04-skills-tools-and-tech-stack.md`](docs/04-skills-tools-and-tech-stack.md)

---

## πŸ› οΈ How I built it (step by step)

1. **Mapped the Store Web API:** Audited auth, owner analytics, catalogue/variant, credit ledger (*Khata*), shifts, and staff routes to catalog exact payloads and permission keys.
2. **Enforced API-First Isolation:** Built [`src/apiClient.js`](src/apiClient.js) to log in via `POST /api/store/auth/login`, parse the `HttpOnly` session cookie, send `Authorization: Bearer`, and auto-relogin once on `401` in local mode.
3. **Engineered the 31-Tool Registry:** Implemented [`src/tools.js`](src/tools.js) with Zod schemas, `READ`/`WRITE`/`CHANGE` annotations, `toPaise()` conversion, and `crypto.randomUUID()` idempotency IDs.
4. **Shipped Local `stdio` Mode:** Wired [`src/server.js`](src/server.js) into Claude Code (`claude mcp add`) and Claude Desktop, keeping `stdout` strictly clean for JSON-RPC.
5. **Added Remote OAuth 2.1 + Streamable HTTP:** Built [`src/oauthProvider.js`](src/oauthProvider.js) and [`src/httpServer.js`](src/httpServer.js) so remote connectors authenticate via PKCE `S256` without storing passwords.
6. **Tested End-to-End:** Verified unit logic, OAuth replay/allow-list/PKCE edge cases, and live `stdio` tool execution behind a Cloudflare Tunnel.

---

## πŸ’¬ Use cases

| Role | Plain-English Prompt | Tools Executed | Outcome |
|---|---|---|---|
| **Store Owner** | *"What were today's net sales and any cashier drawer mismatches?"* | `sales_summary` β†’ `list_shifts({ mismatch: true })` | Instant β‚Ή totals + flagged shifts (Read-Only) |
| **Inventory Manager** | *"Drop Slim Fit Shirt size M selling price to β‚Ή2,499."* | `list_products` β†’ `get_product` β†’ *(confirm)* β†’ `update_variant` | Converts `2499 β†’ 249900` paise with `expectedVersion` & audit log |
| **Accounts / Owner** | *"Record a β‚Ή500 UPI credit payment from Ramesh (ref UPI-98231)."* | `list_customers` β†’ *(confirm)* β†’ `record_khata_payment` | Posts idempotent repayment with UUID & updates ledger |
| **Store Manager** | *"Add a new Cashier account for Anita with starting PIN 4821."* | `list_roles_and_outlets` β†’ *(confirm)* β†’ `create_staff` | Creates staff login & returns onboarding details |
| **Auditor** | *"Show offline bills from yesterday flagged for review."* | `list_sales({ offline: true, flagged: true })` | Surfaces synced offline bills needing review |

πŸ“„ Worked transcripts: [`examples/sample-prompts-and-workflows.md`](examples/sample-prompts-and-workflows.md)

---

## πŸš€ Key advantages

- **Zero Direct Database Exposure:** AI never receives SQL credentials or raw DB accessβ€”PostgreSQL stays private behind the Store API.
- **True Multi-Tenant RBAC:** A Cashier's MCP session is blocked from price changes by the exact same middleware that governs the web UI.
- **Complete Auditability:** Every mutation appears in the store's activity log under the real user who authorized the session.
- **Zero Upstream Backend Changes:** Reuses existing Bearer/cookie auth middleware and validation routes as a clean, additive service.
- **Financial Precision:** Integer-paise conversion + UUID idempotency keys + optimistic `expectedVersion` protect money and inventory state.
- **Write Once, Run Everywhere:** One tool layer powers local CLI agents (`stdio`) and cloud/mobile assistants (`Streamable HTTP + OAuth 2.1`).

---

## ▢️ Quickstart & testing

### 1. Install & Run the Built-in Test Suite

```bash
npm install
npm test
```

`npm test` runs:
- **Unit tests** ([`tests/tools.test.js`](tests/tools.test.js)): rupee-to-paise math, 31 unique tool names & annotations (19 Read / 12 Write), Bearer login + `401` auto-relogin, and API error mapping.
- **OAuth 2.1 + Streamable HTTP tests** ([`tests/http.oauth.test.js`](tests/http.oauth.test.js)): `401` resource metadata discovery, redirect-host allow-list rejection, dynamic registration, HTML login, PKCE `S256` token exchange, single-use code replay rejection, and live `whoami` + `listTools` over Streamable HTTP.
- **Optional `stdio` end-to-end test** ([`tests/server.integration.test.js`](tests/server.integration.test.js)): automatically runs when a Store API (or the included demo API) is up.

### 2. Try It Live with the Included Mock Store API

```bash
# Terminal 1: start the lightweight demo Store API on http://127.0.0.1:4000
npm run demo:api

# Terminal 2: run all tests including the live stdio integration suite
STORE_EMAIL=owner@demo-store.example STORE_PASSWORD=demo-pass npm test
```

### 3. Connect to Claude Code / Claude Desktop (Local `stdio`)

```bash
claude mcp add retail-pos-store \
  -e STORE_API_BASE_URL=http://localhost:4000 \
  -e STORE_EMAIL=inventory-manager@example-store.in \
  -e STORE_PASSWORD=your-staff-password \
  -- node /absolute/path/to/retail-pos-mcp-server/src/server.js
```

Or copy [`examples/claude_desktop_config.json`](examples/claude_desktop_config.json) into your `claude_desktop_config.json`.

### 4. Run as a Remote OAuth 2.1 Connector (`claude.ai` / Mobile)

```bash
# 1. Expose local port 8787 via Cloudflare Quick Tunnel
cloudflared tunnel --url http://127.0.0.1:8787

# 2. Start the OAuth + Streamable HTTP server with the printed HTTPS URL
MCP_PUBLIC_URL=https://<random>.trycloudflare.com npm run start:http
```

Then add `https://<random>.trycloudflare.com/mcp` under **Settings β†’ Connectors β†’ Add custom connector** and sign in with your store user credentials.

---

## πŸ—‚οΈ Repository structure

```text
retail-pos-mcp-server/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ money.js                          # Float-safe rupees -> integer paise converter
β”‚   β”œβ”€β”€ apiClient.js                      # Store Web API client (cookie login -> Bearer + 401 retry)
β”‚   β”œβ”€β”€ tools.js                          # 31 Zod-validated tools (19 Read-Only + 12 Write/Change)
β”‚   β”œβ”€β”€ createServer.js                   # Shared McpServer factory + confirm-first instructions
β”‚   β”œβ”€β”€ server.js                         # Local stdio entry point (Claude Code / Desktop / Cursor)
β”‚   β”œβ”€β”€ oauthProvider.js                  # OAuth 2.1 + PKCE S256 + sign-in HTML + allow-list
β”‚   └── httpServer.js                     # Express 5 + Streamable HTTP + rate-limited /oauth/login
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ tools.test.js                     # Unit tests: money, 31 tools, auth retry, errors
β”‚   β”œβ”€β”€ http.oauth.test.js                # Full OAuth 2.1 + PKCE + Streamable HTTP test
β”‚   └── server.integration.test.js        # Live stdio end-to-end integration test
β”œβ”€β”€ docs/
β”‚   β”œβ”€β”€ 01-architecture-and-transports.md # API-first architecture & stdio vs HTTP deep dive
β”‚   β”œβ”€β”€ 02-oauth-security-and-rbac.md     # OAuth 2.1 sequence, PKCE, allow-list, RBAC & audit log
β”‚   β”œβ”€β”€ 03-tools-read-vs-write.md         # Complete 31-tool matrix (19 Read vs 12 Write)
β”‚   └── 04-skills-tools-and-tech-stack.md # Build steps, skills, tools, and package versions
β”œβ”€β”€ examples/
β”‚   β”œβ”€β”€ claude_desktop_config.json        # Ready-to-use Claude Desktop MCP config
β”‚   β”œβ”€β”€ mock-store-api.js                 # Zero-DB mock Store Web API for instant local testing
β”‚   └── sample-prompts-and-workflows.md   # Real Read-Only and Read->Confirm->Write walkthroughs
β”œβ”€β”€ assets/
β”‚   β”œβ”€β”€ hero.svg                          # Animated hero architecture banner
β”‚   β”œβ”€β”€ mcp-architecture-flow.gif         # Animated 6-step end-to-end request lifecycle
β”‚   β”œβ”€β”€ read-vs-write-safety.gif          # Animated Read-Only vs Write/Change safety model
β”‚   └── oauth-pkce-sequence.svg           # Animated OAuth 2.1 + PKCE S256 sequence diagram
β”œβ”€β”€ .env.example
β”œβ”€β”€ .gitignore
β”œβ”€β”€ LICENSE
└── package.json
```

---

## πŸ‘€ Author

<div align="center">

**Suyog Patil**
*Data Engineer Β· AI Engineering Β· MCP Servers Β· Agentic Systems*

[![LinkedIn](https://img.shields.io/badge/LinkedIn-Suyog%20Patil-0A66C2?style=for-the-badge&logo=linkedin&logoColor=white)](https://www.linkedin.com/in/suyog-patil-0089241b2/)
[![GitHub](https://img.shields.io/badge/GitHub-suyogpatil395-181717?style=for-the-badge&logo=github&logoColor=white)](https://github.com/suyogpatil395)

⭐ If this MCP server architecture helped you build safe, RBAC-governed AI connectors, consider starring the repo.

</div>