Metadata-Version: 2.5
Name: toucan-payments-mcp
Version: 1.0.3
Summary: Model Context Protocol (MCP) server for Toucan Payments online payment gateway APIs
Project-URL: Homepage, https://toucanpay.in
Author-email: Toucan Payments Platform Engineering <engineering@toucanpay.in>
License: MIT
License-File: LICENSE
Keywords: ai,claude,cursor,grafana,langfuse,langsmith,llm,mcp,model-context-protocol,paylink,payment-gateway,payments,prometheus,toucan,toucan-payments
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Office/Business :: Financial :: Point-Of-Sale
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: click>=8.1.7
Requires-Dist: httpx>=0.27.0
Requires-Dist: mcp<3,>=2.0.0
Requires-Dist: prometheus-client>=0.20.0
Requires-Dist: pydantic-settings>=2.2.0
Requires-Dist: pydantic>=2.7.0
Requires-Dist: python-dotenv>=1.0.1
Requires-Dist: rich>=13.7.1
Requires-Dist: starlette>=0.37.0
Requires-Dist: uvicorn[standard]>=0.29.0
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.23.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Provides-Extra: tracing
Requires-Dist: langfuse>=2.0.0; extra == 'tracing'
Description-Content-Type: text/markdown

# Toucan Payments MCP Server

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
[![MCP Version](https://img.shields.io/badge/MCP-2.0+-green.svg)](https://modelcontextprotocol.io/)
[![Docker Ready](https://img.shields.io/badge/docker-ready-blue.svg)](https://www.docker.com/)
[![Observability](https://img.shields.io/badge/metrics-Prometheus%20%7C%20Grafana-orange.svg)](https://prometheus.io/)

The official **Model Context Protocol (MCP)** server for **Toucan Payments**. Connect AI assistants—including **Claude Desktop**, **Cursor**, **VS Code**, **Windsurf**, and custom LLM agents—directly to Toucan Payments online payment gateway APIs using secure Bearer authentication tokens.

Built by the Toucan Payments team, this server provides a production-grade, highly observable, and container-ready bridge between generative AI models and payment infrastructure.

---

## Table of Contents

1. [Architecture & Hosting](#architecture--hosting)
2. [Prerequisites](#prerequisites)
3. [Packaging & Distribution](#packaging--distribution)
4. [Quick Start](#quick-start)
5. [CLI Commands Reference](#cli-commands-reference)
6. [Supported AI Clients](#supported-ai-clients)
7. [Available Tools Specification](#available-tools-specification)
8. [Observability & Monitoring](#observability--monitoring)
   - [Prometheus Metrics Exporter](#prometheus-metrics-exporter)
   - [Grafana Dashboards](#grafana-dashboards)
   - [Langfuse Tracing](#langfuse-tracing)
   - [LangSmith Tracing](#langsmith-tracing)
9. [Docker & Containerized Deployment](#docker--containerized-deployment)
10. [Configuration Reference](#configuration-reference)
11. [Testing](#testing)
12. [License](#license)

---

## Architecture & Hosting

The Toucan Payments MCP Server provides dual runtime modes designed to serve both local AI paired-programming tools and centralized cloud infrastructure:

```mermaid
flowchart TD
    subgraph AI Assistants & Clients
        Claude[Claude Desktop]
        Cursor[Cursor IDE]
        VSCode[VS Code / Copilot]
        Agent[Autonomous LLM Agent]
    end

    subgraph Toucan Payments MCP Server
        CLI[toucan-mcp CLI / Stdio Transport]
        SSE[SSE / Streamable HTTP Server :8000]
        Router[Tool Registry & Security Validator]
        PromExporter[Prometheus Metrics Exporter :9090 / :8000/metrics]
        TraceEngine[Langfuse & LangSmith Tracer]
    end

    subgraph Observability
        Prom[Prometheus Server]
        Graf[Grafana Dashboard :3000]
        LF[Langfuse Cloud / Self-Hosted]
        LS[LangSmith Cloud]
    end

    subgraph Toucan Payments Gateway
        PayLinkAPI["POST /api/paylink/cre (Merchant API - PDF 1)"]
        CheckStatusAPI["POST /api/pay/v1/checkStatus (Pay API - PDF 2)"]
        CheckoutAPI["POST /api/auth/getpaymentsession (Checkout API - PDF 3)"]
        CallbackEngine["Payment Callbacks / Webhooks"]
    end

    Claude -->|Stdio JSON-RPC| CLI
    Cursor -->|Stdio JSON-RPC| CLI
    VSCode -->|Stdio JSON-RPC| CLI
    Agent -->|SSE / HTTP| SSE

    CLI --> Router
    SSE --> Router

    Router --> PromExporter
    Router --> TraceEngine
    PromExporter --> Prom
    Prom --> Graf
    TraceEngine --> LF
    TraceEngine --> LS

    Router -->|Bearer Auth / HTTPS| PayLinkAPI
    Router -->|Bearer Auth / HTTPS| CheckStatusAPI
    Router -->|Form URL / HTTPS| CheckoutAPI
    CallbackEngine -.->|Validate| Router
```

### Hosting Modes
1. **Local Stdio Mode (Default):** Executed as a child process by Claude Desktop, Cursor, or VS Code over `stdin`/`stdout`. A background daemon exposes Prometheus metrics on port `9090`.
2. **Internal Server Mode (SSE / Streamable HTTP):** Hosted on internal infrastructure or Kubernetes behind reverse proxies (Nginx/ALB). Exposes `/sse` and `/messages` for MCP streaming, `/health` for container probes, and `/metrics` for Prometheus scraping on port `8000`.

---

## Prerequisites

- **Python 3.10+** or **Astral uv** (recommended for zero-overhead virtual environments).
- **Node.js 18+** (optional, only if launching via `npx @toucanpayments/toucan-payments-mcp`).
- **Docker & Docker Compose** (optional, for full containerized deployment).
- **Toucan Payments Credentials:** Bearer access token, merchant number, and terminal credentials provisioned by the Toucan Payments acquiring team.

---

## Packaging & Distribution

The server is packaged for universal distribution across three primary mediums:

1. **Python Package Index (PyPI):**
   ```bash
   pip install toucan-payments-mcp
   # Or using uv:
   uv tool install toucan-payments-mcp
   ```
2. **Node Package Manager (NPM / npx):**
   Execute directly without manual repository cloning:
   ```bash
   npx -y @toucanpayments/toucan-payments-mcp start
   ```
3. **Docker Hub / Container Image:**
   ```bash
   docker pull vivektc/toucan-payments-mcp:1.0.3

   docker run --rm -p 8000:8000 -p 9090:9090 \
     -e TOUCAN_ACCESS_TOKEN=... \
     -e TOUCAN_MERCHANT_NUMBER=... \
     -e TOUCAN_TERMINAL_NUMBER=... \
     -e TOUCAN_TERMINAL_MODEL_KEY=... \
     -e TOUCAN_MERCHANT_MODEL_KEY=... \
     -e TOUCAN_MERCHANT_NAME=... \
     vivektc/toucan-payments-mcp:1.0.3

   # Or build locally:
   docker build -t toucan-payments-mcp:latest .
   ```
   Merchant and terminal identifiers have no built-in defaults and must be provided. See CHANGELOG.md for release notes.

---

## Quick Start

### 1. Clone & Setup Virtual Environment
```bash
git clone https://github.com/toucan-payments/toucan-payments-mcp.git
cd toucan-payments-mcp

# Using Astral uv (recommended):
uv venv --python 3.12
uv pip install -e ".[tracing,dev]"

# Or using standard python venv:
python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
pip install -r requirements.txt
pip install -e .
```

### 2. Configure Credentials
Run the interactive configuration CLI:
```bash
toucan-mcp configure
```
Or create a `.env` file from the provided template:
```bash
cp .env.example .env
```
Fill in your credentials:
```env
TOUCAN_ENV=uat
TOUCAN_ACCESS_TOKEN=eyJhbGciOiJSUzI1NiJ9...
TOUCAN_MERCHANT_NUMBER=100000000000001
TOUCAN_TERMINAL_NUMBER=10000001
```

### 3. Verify Connection
```bash
toucan-mcp test
```

### 4. Auto-Configure AI Assistant
```bash
toucan-mcp setup cursor        # For Cursor IDE
toucan-mcp setup claude-desktop # For Claude Desktop
toucan-mcp setup vscode        # For Visual Studio Code
toucan-mcp setup windsurf      # For Windsurf
```

---

## CLI Commands Reference

The `toucan-mcp` CLI mirrors the command suite of modern enterprise MCP servers:

| Command | Description |
|:---|:---|
| `toucan-mcp start` | Launch the server in stdio transport mode (default) |
| `toucan-mcp start --transport sse --port 8000` | Launch server in HTTP / SSE mode for internal hosting |
| `toucan-mcp configure` | Interactively configure Bearer token and merchant defaults |
| `toucan-mcp test` | Test network latency and credentials against Toucan gateway |
| `toucan-mcp setup <client>` | Automatically configure AI client (`cursor`, `claude-desktop`, `vscode`, `windsurf`) |
| `toucan-mcp setup <client> --print` | Print MCP client JSON configuration snippet without writing |
| `toucan-mcp status` | Print active configuration, environment mode, and telemetry status |
| `toucan-mcp --version` | Display current package version |

---

## Supported AI Clients

### 1. Cursor IDE
Configuration file location: `~/.cursor/mcp.json`
```json
{
  "mcpServers": {
    "toucan-payments": {
      "command": "toucan-mcp",
      "args": ["start", "--transport", "stdio"],
      "env": {
        "TOUCAN_ENV": "uat",
        "TOUCAN_ACCESS_TOKEN": "YOUR_BEARER_TOKEN",
        "TOUCAN_MERCHANT_NUMBER": "100000000000001",
        "TOUCAN_TERMINAL_NUMBER": "10000001"
      }
    }
  }
}
```

### 2. Claude Desktop
Configuration file locations:
- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows:** `%APPDATA%\Claude\claude_desktop_config.json`
```json
{
  "mcpServers": {
    "toucan-payments": {
      "command": "toucan-mcp",
      "args": ["start"],
      "env": {
        "TOUCAN_ENV": "uat",
        "TOUCAN_ACCESS_TOKEN": "YOUR_BEARER_TOKEN"
      }
    }
  }
}
```

### 3. Visual Studio Code
Configuration file location: `.vscode/mcp.json`
```json
{
  "servers": {
    "toucan-payments": {
      "command": "toucan-mcp",
      "args": ["start"],
      "env": {
        "TOUCAN_ENV": "uat",
        "TOUCAN_ACCESS_TOKEN": "YOUR_BEARER_TOKEN"
      }
    }
  }
}
```

---

## Available Tools Specification

In alignment with the architect's instructions, the initial release focuses on core payment capabilities:

### 1. `create_payment_link` (Write Operation)
Generates a payment link matching the Toucan Payments Create Pay Link API specification (`1.pdf`).
- **Endpoint:** `POST /api/paylink/cre`
- **Supported Options:** Fixed amount, customer-entered amount, single-use, reusable, partial payments, customizable ISO-8601 expiry timestamps.
- **Parameters:**
  - `amount` *(Optional[float | str])*: Payment amount. If omitted, customer enters amount at payment time.
  - `currency` *(str, default "INR")*: ISO-4217 currency code.
  - `description` *(str, default "purchase")*: Transaction description displayed to customer.
  - `one_time_use` *(bool, default True)*: Link expires immediately upon first successful payment.
  - `allow_partial` *(bool, default False)*: Allows customer to pay partial instalments.
  - `expiry_hours` *(int, default 24)*: Hours before link expiration.
  - `expiry_date` *(Optional[str])*: Explicit ISO timestamp (e.g. `2026-05-01T23:59:59`).
  - `merchant_number`, `terminal_number`, `terminal_model_key`, `merchant_model_key`, `merchant_name`: Optional overrides for terminal routing.

### 2. `check_payment_status` (Read Operation)
Queries the real-time processing status of a payment matching the Toucan Payments Check Status API specification (`2.pdf`).
- **Endpoint:** `POST /api/pay/v1/checkStatus`
- **Parameters:**
  - `invoice_number` *(str, required)*: Unique transaction invoice number or orderNo (minimum 15 digits, e.g. `176129831762956`).
  - `rrn` *(Optional[str])*: Optional Retrieval Reference Number (RRN) from bank transaction.
  - `terminal_number` *(Optional[str])*: Terminal number associated with the transaction (defaults to configured terminal).
  - `merchant_number` *(Optional[str])*: Merchant account number (defaults to configured merchant).
- **Output:** Returns approval status (`actionCode: "00"` signifies success), approval code, RRN, settled amounts, customer masked VPA, and timestamps.

### 3. `verify_payment_callback` (Verification Operation)
Validates and parses asynchronous webhook/callback payloads from Toucan Payments (`2.pdf` pages 6–7).
- **Parameters:**
  - `callback_payload` *(Union[str, dict], required)*: Raw JSON payload received on webhook endpoint.
  - `expected_terminal_number` *(Optional[str])*: Expected terminal number.
  - `expected_invoice_number` *(Optional[str])*: Expected invoice number.
- **Validation Rules:**
  - Verifies `pspRefNo` format: ensures it matches the combination `terminalNumber + invoiceNumber`.
  - Confirms `payeeRespCode == "00"` and `status == "SUCCESS"`.
  - Returns formatted verification breakdown and standard Toucan acknowledgment response (`{"success": true}`).

### 4. `check_gateway_health` (Read Operation)
Diagnoses end-to-end connectivity between the MCP server and Toucan Payments endpoints.
- Validates active environment URLs, Bearer token presence, round-trip HTTP latency, and Prometheus exporter status.

### 5. `create_checkout_session` / `get_payment_session` (Checkout Operation - PDF 3)
Initiates a web checkout session matching the Toucan Payments Check Out-API specification (`3.pdf`).
- **Endpoint:** `POST /api/auth/getpaymentsession`
- **Request Format:** `Content-Type: application/x-www-form-urlencoded`
- **Parameters:**
  - `order_id` *(str, required)*: Unique transaction invoice number or order ID (minimum 15 digits, e.g. `12022025173230443`). Form key: `o`.
  - `amount` *(Union[float, int, str], required)*: Transaction monetary amount to charge (e.g. `23`). Form key: `ta`.
  - `customer_name` *(str, required)*: Sender / customer full name (e.g. `Test Customer`). Form key: `name`.
  - `customer_phone` *(str, required)*: Sender / customer mobile phone number (e.g. `9000000000`). Form key: `phone`.
  - `customer_email` *(str, required)*: Sender / customer email address (e.g. `test.customer@example.com`). Form key: `emailId`.
  - `currency` *(str, default "INR")*: ISO-4217 currency code. Form key: `c`.
  - `terminal_id` *(Optional[str])*: Mapped terminal ID (defaults to configured `TOUCAN_TERMINAL_NUMBER`). Form key: `t`.
  - `merchant_token` *(Optional[str])*: Merchant designated JWT authorization token (defaults to configured `TOUCAN_ACCESS_TOKEN`). Form key: `mac`.
  - `merchant_url` *(Optional[str])*: Merchant environment URL (defaults to configured merchant base URL). Form key: `murl`.
  - `hash_amount` *(Optional[str])*: SHA-512 hexadecimal hash of transaction amount `ta` (`computeSHA512(str(ta))`). Automatically computed if omitted! Form key: `ha`.
- **Response Behavior:**
  - Extracts the checkout navigation URL from the HTTP `Location` response header (`HTTP 302 Found`) or JSON response body (`{"Location": "..."}`).
  - Navigates the customer to the checkout page or displays it in a mobile WebView. Subsequent payment flows (UPI, Card, NetBanking) are handled within the checkout interface.
- **Error Codes (from PDF 3):**
  - `302`: Redirect URL returned in `Location` header (or failure URL if terminal or parameters are invalid).
  - `200`: Request successful but redirect URL was not sent from backend.
  - `404`: Given Merchant token is not authorized to access the API.

---

## Observability & Monitoring

Enterprise-grade observability is built directly into the server core.

### Prometheus Metrics Exporter
- **When running in SSE / HTTP Mode (`--transport sse`):** Metrics are served at `http://<host>:8000/metrics`.
- **When running in Stdio Mode (`--transport stdio`):** A lightweight background daemon automatically serves Prometheus metrics at `http://localhost:9090/metrics`.

#### Exported Metrics:
| Metric Name | Type | Labels | Description |
|:---|:---|:---|:---|
| `toucan_mcp_tool_calls_total` | Counter | `tool_name`, `status` | Total MCP tool invocations |
| `toucan_mcp_tool_duration_seconds` | Histogram | `tool_name` | Latency distribution of tool calls |
| `toucan_api_requests_total` | Counter | `endpoint`, `method`, `http_status` | Outbound HTTP calls to Toucan gateway |
| `toucan_api_duration_seconds` | Histogram | `endpoint` | Outbound HTTP round-trip latency |
| `toucan_mcp_active_sessions` | Gauge | — | Active client connections |

### Grafana Dashboards
A ready-to-use Grafana dashboard is located in `grafana/dashboards/toucan_mcp.json`.
When running with Docker Compose, Grafana automatically provisions:
- Tool execution rates (QPS)
- Tool success vs error breakdown (pie chart)
- 95th percentile tool execution latency
- Outbound API round-trip latency
- HTTP response status code distribution

### Langfuse Tracing
To trace LLM tool invocations with execution inputs, outputs, latencies, and metadata in Langfuse:
```env
LANGFUSE_PUBLIC_KEY=pk-lf-...
LANGFUSE_SECRET_KEY=sk-lf-...
LANGFUSE_HOST=https://cloud.langfuse.com
```

### LangSmith Tracing
To enable LangSmith / OpenTelemetry tracing:
```env
LANGSMITH_API_KEY=lsv2_pt_...
LANGSMITH_PROJECT=toucan-payments-mcp
LANGCHAIN_TRACING_V2=true
```

---

## Docker & Containerized Deployment

Deploy the MCP server alongside Prometheus and Grafana with a single command:

```bash
docker compose up -d
```

### Exposed Endpoints:
- **Toucan MCP Server:** `http://localhost:8000/sse` (Health: `http://localhost:8000/health`, Metrics: `http://localhost:8000/metrics`)
- **Prometheus UI:** `http://localhost:9091`
- **Grafana Dashboard:** `http://localhost:3000` (User: `admin`, Password: the `GRAFANA_ADMIN_PASSWORD` you set in `.env`; the stack will not start without it)

---

## Configuration Reference

All settings can be specified via environment variables or inside `.env`:

| Variable | Type | Default | Description |
|:---|:---|:---|:---|
| `TOUCAN_ENV` | string | `uat` | Gateway environment (`uat` or `prod`) |
| `TOUCAN_ACCESS_TOKEN` | string | *None* | Bearer authentication token |
| `TOUCAN_MERCHANT_BASE_URL` | string | `https://merchant.testtoucanpay.in` | Merchant terminal API base URL |
| `TOUCAN_PAY_BASE_URL` | string | `https://pay.testtoucanpay.in` | Check status API base URL |
| `TOUCAN_MERCHANT_NUMBER` | string | *(required)* | 15-digit merchant account number |
| `TOUCAN_TERMINAL_NUMBER` | string | *(required)* | Mapped terminal number |
| `TOUCAN_TERMINAL_MODEL_KEY`| string | *(required for payment links)* | Terminal model key |
| `TOUCAN_MERCHANT_MODEL_KEY`| string | *(required for payment links)* | Merchant model key |
| `TOUCAN_MERCHANT_NAME` | string | *(required for payment links)* | Merchant display brand name |
| `MCP_TRANSPORT` | string | `stdio` | Transport protocol (`stdio`, `sse`, `streamable-http`) |
| `MCP_HOST` | string | `0.0.0.0` | Host interface for HTTP binding |
| `MCP_PORT` | int | `8000` | Port for HTTP/SSE binding |
| `PROMETHEUS_ENABLED` | bool | `true` | Enable Prometheus metrics exporter |
| `PROMETHEUS_PORT` | int | `9090` | Prometheus scrape port in stdio mode |

---

## Testing

Run the automated test suite with pytest:
```bash
pytest -v
```

---

## License

This project is licensed under the MIT License. See [LICENSE](LICENSE) for details.
