A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.
JavaScript
feat(mcp): add @youpi/mcp-server for Model Context Protocol AI tooling
ArunGupta152656e32aa414df
diff --git a/packages/youpi-mcp/README.md b/packages/youpi-mcp/README.mdnew file mode 100644index 0000000..0bc381a--- /dev/null+++ b/packages/youpi-mcp/README.md@@ -0,0 +1,41 @@+# @youpi/mcp-server++Model Context Protocol (MCP) server for **YOUPI PG V2**, enabling AI coding assistants (Claude Desktop, Antigravity, Cursor, Cline) to directly interact with, audit, and simulate payment gateway operations.++---++## Capabilities & Tools++| Tool Name | Description |+| :--- | :--- |+| **`youpi_check_gateway_health`** | Inspects HTTP operational readiness across ports (6100 Core, 7000 Checkout, 6001 Admin, 6002 SMS, 6003 Gmail). |+| **`youpi_verify_webhook`** | Verifies HMAC-SHA256 signature over raw request bytes and checks timestamp freshness. |+| **`youpi_simulate_bank_notification`** | Formats realistic Indian bank SMS templates (SBI, HDFC, ICICI, Axis, Kotak, PNB) and generates mock observer payloads. |++---++## Configuration++Add to your MCP client configuration (`claude_desktop_config.json` or Antigravity `mcp_config.json`):++```json+{+ "mcpServers": {+ "youpi-pg": {+ "command": "node",+ "args": ["packages/youpi-mcp/src/index.js"],+ "env": {+ "NODE_ENV": "development"+ }+ }+ }+}+```++---++## Running Standalone++```bash+node packages/youpi-mcp/src/index.js+```diff --git a/packages/youpi-mcp/package.json b/packages/youpi-mcp/package.jsonnew file mode 100644index 0000000..b0e8acb--- /dev/null+++ b/packages/youpi-mcp/package.json@@ -0,0 +1,17 @@+{+ "name": "@youpi/mcp-server",+ "version": "1.0.0",+ "description": "Model Context Protocol (MCP) server for YouPI PG payment gateway debugging, slot inspection, and transaction simulation",+ "type": "module",+ "main": "./src/index.js",+ "bin": {+ "youpi-mcp": "./src/index.js"+ },+ "scripts": {+ "start": "node ./src/index.js",+ "test": "node --test src/__tests__/**/*.test.js"+ },+ "dependencies": {+ "@youpi/common": "*"+ }+}diff --git a/packages/youpi-mcp/src/__tests__/mcp-server.test.js b/packages/youpi-mcp/src/__tests__/mcp-server.test.jsnew file mode 100644index 0000000..5c22c72--- /dev/null+++ b/packages/youpi-mcp/src/__tests__/mcp-server.test.js@@ -0,0 +1,123 @@+import { test, describe } from 'node:test';+import assert from 'node:assert/strict';+import crypto from 'node:crypto';+import { YoupiMcpServer } from '../index.js';+import { verifyWebhookSignature, generateBankSmsText } from '../tools.js';++describe('YouPI MCP Server', () => {+ test('initializes with protocolVersion and serverInfo', async () => {+ const server = new YoupiMcpServer();+ const res = await server.handleRequest({+ jsonrpc: '2.0',+ id: 1,+ method: 'initialize'+ });++ assert.equal(res.id, 1);+ assert.equal(res.result.serverInfo.name, 'youpi-mcp-server');+ assert.ok(res.result.capabilities.tools);+ });++ test('lists registered MCP tools', async () => {+ const server = new YoupiMcpServer();+ const res = await server.handleRequest({+ jsonrpc: '2.0',+ id: 2,+ method: 'tools/list'+ });++ assert.equal(res.id, 2);+ const toolNames = res.result.tools.map((t) => t.name);+ assert.ok(toolNames.includes('youpi_check_gateway_health'));+ assert.ok(toolNames.includes('youpi_verify_webhook'));+ assert.ok(toolNames.includes('youpi_simulate_bank_notification'));+ });++ test('verifies valid HMAC webhook signature', async () => {+ const secret = 'test-secret-12345';+ const payload = JSON.stringify({ event: 'SUCCESS', amount: '499.00', utr: '123456789012' });+ const hmac = crypto.createHmac('sha256', secret).update(payload).digest('hex');++ const result = verifyWebhookSignature({+ rawPayload: payload,+ signature: `sha256=${hmac}`,+ secret+ });++ assert.equal(result.valid, true);+ assert.equal(result.error, null);+ });++ test('rejects tampered or invalid webhook signature', async () => {+ const secret = 'test-secret-12345';+ const payload = JSON.stringify({ event: 'SUCCESS', amount: '499.00', utr: '123456789012' });++ const result = verifyWebhookSignature({+ rawPayload: payload,+ signature: 'sha256=0000000000000000000000000000000000000000000000000000000000000000',+ secret+ });++ assert.equal(result.valid, false);+ assert.equal(result.error, 'INVALID_SIGNATURE');+ });++ test('rejects webhook timestamp beyond maxAgeSeconds', async () => {+ const secret = 'test-secret-12345';+ const payload = JSON.stringify({ event: 'SUCCESS' });+ const hmac = crypto.createHmac('sha256', secret).update(payload).digest('hex');+ const staleTimestamp = Date.now() - 600 * 1000; // 10 minutes ago++ const result = verifyWebhookSignature({+ rawPayload: payload,+ signature: hmac,+ secret,+ timestamp: String(staleTimestamp),+ maxAgeSeconds: 300+ });++ assert.equal(result.valid, false);+ assert.equal(result.error, 'WEBHOOK_TIMESTAMP_EXPIRED');+ });++ test('generates realistic bank SMS text and simulated webhook payload', async () => {+ const server = new YoupiMcpServer();+ const res = await server.handleRequest({+ jsonrpc: '2.0',+ id: 3,+ method: 'tools/call',+ params: {+ name: 'youpi_simulate_bank_notification',+ arguments: {+ bank: 'HDFC',+ amount: 499.00,+ utr: '987654321012',+ accountLastDigits: '4321'+ }+ }+ });++ assert.equal(res.id, 3);+ const parsed = JSON.parse(res.result.content[0].text);+ assert.equal(parsed.bank, 'HDFC');+ assert.ok(parsed.generatedSms.includes('INR 499.00'));+ assert.ok(parsed.generatedSms.includes('987654321012'));+ assert.equal(parsed.simulatedWebhookPayload.sender, 'VK-HDFCBK');+ });++ test('returns error for unknown tool call', async () => {+ const server = new YoupiMcpServer();+ const res = await server.handleRequest({+ jsonrpc: '2.0',+ id: 4,+ method: 'tools/call',+ params: {+ name: 'unknown_tool',+ arguments: {}+ }+ });++ assert.equal(res.id, 4);+ assert.equal(res.error.code, -32601);+ });+});diff --git a/packages/youpi-mcp/src/index.js b/packages/youpi-mcp/src/index.jsnew file mode 100644index 0000000..3596a4f--- /dev/null+++ b/packages/youpi-mcp/src/index.js@@ -0,0 +1,148 @@+#!/usr/bin/env node+import readline from 'node:readline';+import {+ TOOLS_DEFINITIONS,+ verifyWebhookSignature,+ generateBankSmsText,+ checkPortHealth+} from './tools.js';++export class YoupiMcpServer {+ constructor(inputStream = process.stdin, outputStream = process.stdout) {+ this.inputStream = inputStream;+ this.outputStream = outputStream;+ }++ async handleRequest(request) {+ const { id, method, params } = request;++ if (method === 'initialize') {+ return {+ jsonrpc: '2.0',+ id,+ result: {+ protocolVersion: '2024-11-05',+ capabilities: { tools: {} },+ serverInfo: {+ name: 'youpi-mcp-server',+ version: '1.0.0'+ }+ }+ };+ }++ if (method === 'notifications/initialized') {+ return null;+ }++ if (method === 'ping') {+ return { jsonrpc: '2.0', id, result: {} };+ }++ if (method === 'tools/list') {+ return {+ jsonrpc: '2.0',+ id,+ result: {+ tools: TOOLS_DEFINITIONS+ }+ };+ }++ if (method === 'tools/call') {+ const name = params?.name;+ const args = params?.arguments || {};++ try {+ let toolResult;+ if (name === 'youpi_verify_webhook') {+ toolResult = verifyWebhookSignature(args);+ } else if (name === 'youpi_simulate_bank_notification') {+ const smsText = generateBankSmsText(args);+ toolResult = {+ bank: args.bank,+ amount: args.amount,+ utr: args.utr,+ generatedSms: smsText,+ simulatedWebhookPayload: {+ sender: `VK-${args.bank}BK`,+ body: smsText,+ timestamp: Date.now()+ }+ };+ } else if (name === 'youpi_check_gateway_health') {+ const ports = [6100, 7000, 6001, 6002, 6003, 5000];+ const checks = await Promise.all(ports.map((p) => checkPortHealth(p, args.host)));+ toolResult = {+ host: args.host || '127.0.0.1',+ services: checks+ };+ } else {+ return {+ jsonrpc: '2.0',+ id,+ error: { code: -32601, message: `Tool not found: ${name}` }+ };+ }++ return {+ jsonrpc: '2.0',+ id,+ result: {+ content: [+ {+ type: 'text',+ text: JSON.stringify(toolResult, null, 2)+ }+ ]+ }+ };+ } catch (err) {+ return {+ jsonrpc: '2.0',+ id,+ error: { code: -32000, message: err.message || 'Internal error' }+ };+ }+ }++ return {+ jsonrpc: '2.0',+ id,+ error: { code: -32601, message: `Method not found: ${method}` }+ };+ }++ start() {+ const rl = readline.createInterface({+ input: this.inputStream,+ output: this.outputStream,+ terminal: false+ });++ rl.on('line', async (line) => {+ const trimmed = line.trim();+ if (!trimmed) return;+ try {+ const parsed = JSON.parse(trimmed);+ const response = await this.handleRequest(parsed);+ if (response) {+ this.outputStream.write(`${JSON.stringify(response)}\n`);+ }+ } catch (err) {+ this.outputStream.write(+ `${JSON.stringify({+ jsonrpc: '2.0',+ id: null,+ error: { code: -32700, message: 'Parse error' }+ })}\n`+ );+ }+ });+ }+}++if (process.argv[1] && process.argv[1].endsWith('index.js')) {+ const server = new YoupiMcpServer();+ server.start();+}diff --git a/packages/youpi-mcp/src/tools.js b/packages/youpi-mcp/src/tools.jsnew file mode 100644index 0000000..43c184b--- /dev/null+++ b/packages/youpi-mcp/src/tools.js@@ -0,0 +1,146 @@+import crypto from 'node:crypto';+import http from 'node:http';++export const TOOLS_DEFINITIONS = [+ {+ name: 'youpi_check_gateway_health',+ description: 'Check the health and operational status of all local YouPI PG services (Payment Core API, Checkout Portal, Observers).',+ inputSchema: {+ type: 'object',+ properties: {+ host: {+ type: 'string',+ description: 'Host to check (defaults to 127.0.0.1)',+ default: '127.0.0.1'+ }+ }+ }+ },+ {+ name: 'youpi_verify_webhook',+ description: 'Verify HMAC-SHA256 signature for a YouPI PG webhook delivery payload.',+ inputSchema: {+ type: 'object',+ properties: {+ rawPayload: {+ type: 'string',+ description: 'The raw, unparsed request payload string'+ },+ signature: {+ type: 'string',+ description: 'The received X-Gateway-Signature header (sha256=<hex>)'+ },+ secret: {+ type: 'string',+ description: 'The merchant webhook secret'+ },+ timestamp: {+ type: 'string',+ description: 'The received X-Gateway-Timestamp header in ms'+ },+ maxAgeSeconds: {+ type: 'number',+ description: 'Maximum permitted age in seconds (default 300)',+ default: 300+ }+ },+ required: ['rawPayload', 'signature', 'secret']+ }+ },+ {+ name: 'youpi_simulate_bank_notification',+ description: 'Simulate an incoming Indian bank SMS credit notification to test automated payment verification.',+ inputSchema: {+ type: 'object',+ properties: {+ bank: {+ type: 'string',+ enum: ['HDFC', 'SBI', 'ICICI', 'AXIS', 'KOTAK', 'PNB'],+ description: 'Target bank sender template to format'+ },+ amount: {+ type: 'number',+ description: 'Amount in INR (e.g. 499.00)'+ },+ utr: {+ type: 'string',+ description: '12-digit bank reference number (UTR / RRN)'+ },+ accountLastDigits: {+ type: 'string',+ description: 'Last 3-4 digits of receiving account',+ default: '1234'+ },+ observerPort: {+ type: 'number',+ description: 'SMS Observer port (default 6002)',+ default: 6002+ }+ },+ required: ['bank', 'amount', 'utr']+ }+ }+];++export function verifyWebhookSignature({ rawPayload, signature, secret, timestamp, maxAgeSeconds = 300 }) {+ if (!rawPayload || !signature || !secret) {+ return { valid: false, error: 'MISSING_REQUIRED_PARAMS' };+ }++ if (timestamp) {+ const tsNum = Number(timestamp);+ if (!Number.isNaN(tsNum)) {+ const now = Date.now();+ const diffMs = Math.abs(now - tsNum);+ if (diffMs > maxAgeSeconds * 1000) {+ return { valid: false, error: 'WEBHOOK_TIMESTAMP_EXPIRED', ageSeconds: Math.round(diffMs / 1000) };+ }+ }+ }++ const sig = signature.startsWith('sha256=') ? signature.slice(7) : signature;+ const hmac = crypto.createHmac('sha256', secret);+ hmac.update(rawPayload, 'utf8');+ const expected = hmac.digest('hex');++ const bufA = Buffer.from(sig, 'hex');+ const bufB = Buffer.from(expected, 'hex');++ if (bufA.length !== bufB.length) {+ return { valid: false, error: 'SIGNATURE_LENGTH_MISMATCH' };+ }++ const matches = crypto.timingSafeEqual(bufA, bufB);+ return { valid: matches, error: matches ? null : 'INVALID_SIGNATURE' };+}++export function generateBankSmsText({ bank, amount, utr, accountLastDigits = '1234' }) {+ const amtFormatted = Number(amount).toFixed(2);+ switch (bank.toUpperCase()) {+ case 'HDFC':+ return `Dear Customer, INR ${amtFormatted} credited to account **${accountLastDigits} on ${new Date().toISOString().slice(0, 10)} by UPI/${utr}/YouPI. Avl bal INR 25,000.00.`;+ case 'SBI':+ return `Your A/C ${accountLastDigits} Credited by Rs ${amtFormatted} on ${new Date().toISOString().slice(0, 10)} by UPI/Ref no ${utr} - SBI.`;+ case 'ICICI':+ return `Dear Customer, Acct XX${accountLastDigits} is credited with Rs ${amtFormatted} on ${new Date().toISOString().slice(0, 10)}. UPI:${utr}.`;+ case 'AXIS':+ return `INR ${amtFormatted} credited to Axis Bank A/c no. XX${accountLastDigits} on ${new Date().toISOString().slice(0, 10)} by UPI ref ${utr}.`;+ case 'KOTAK':+ return `Rs ${amtFormatted} credited to Kotak Bank A/C XX${accountLastDigits} on ${new Date().toISOString().slice(0, 10)} (UPI Ref no ${utr}).`;+ case 'PNB':+ return `A/C *${accountLastDigits} credited with INR ${amtFormatted} on ${new Date().toISOString().slice(0, 10)} via UPI/${utr}. PNB.`;+ default:+ return `Credit of INR ${amtFormatted} received in A/C *${accountLastDigits} via UPI ref ${utr}.`;+ }+}++export async function checkPortHealth(port, host = '127.0.0.1') {+ return new Promise((resolve) => {+ const req = http.request({ host, port, path: '/health', method: 'GET', timeout: 800 }, (res) => {+ resolve({ port, online: res.statusCode >= 200 && res.statusCode < 500, statusCode: res.statusCode });+ });+ req.on('error', () => resolve({ port, online: false, error: 'CONNECTION_REFUSED' }));+ req.on('timeout', () => { req.destroy(); resolve({ port, online: false, error: 'TIMEOUT' }); });+ req.end();+ });+}