> ## Documentation Index
> Fetch the complete documentation index at: https://docs.paybridgenp.com/llms.txt
> Use this file to discover all available pages before exploring further.

# AI assistants (MCP)

> Connect Claude, ChatGPT, Cursor, Claude Code, and any MCP-compatible AI to your PayBridgeNP account. Issue refunds, create payment links, inspect failed payments, and pull KPIs by chatting.

The official Model Context Protocol (MCP) server for PayBridgeNP. Lets any MCP-compatible AI assistant - Claude on web and mobile, Claude Desktop, ChatGPT, Cursor, Claude Code, VS Code, Continue - talk to your PayBridgeNP account through 70 typed tools.

There are two ways to connect, with the same tools either way:

* **Hosted (remote)** - add PayBridgeNP as a connector in Claude (web, mobile, desktop) or ChatGPT, sign in, and approve access on a consent screen. Nothing to install. This is the only option on mobile. [Jump to the hosted setup](#connect-a-hosted-app-claude-web-mobile-chatgpt).
* **Local (npm)** - run the server on your own machine with a scoped token you generate. Good for Cursor, Claude Code, and VS Code. [Jump to the local setup](#run-the-local-server-cursor-claude-code-vs-code).

Either way the model only ever sees JSON results, never your raw API key, and every tool call goes over HTTPS to `api.paybridgenp.com` and runs through the same permission checks as our REST API.

<Tip>
  Source code is open at [github.com/paybridgenp/paybridgenp-mcp](https://github.com/paybridgenp/paybridgenp-mcp). Audit exactly what runs against your key before installing.
</Tip>

## Connect a hosted app (Claude web, mobile, ChatGPT)

No install, no token to copy. The app sends you to PayBridgeNP to sign in and approve.

1. In your assistant's connector settings, add a custom connector with the URL `https://api.paybridgenp.com/mcp`.
   * **Claude**: Settings → Connectors → Add custom connector.
   * **ChatGPT**: Settings → Connectors → Add (developer mode).
2. The app opens a PayBridgeNP sign-in page. Log in with your merchant account.
3. On the consent screen, choose the **project**, the **mode** (sandbox or live), and tick exactly the **access** you want to grant - read-only by default, with write access opt-in per category. Write access needs a Pro plan.
4. Approve. You are sent back to the app, connected.

You can revoke a connected app any time from [`dashboard.paybridgenp.com/mcp`](https://dashboard.paybridgenp.com/mcp) - it stops working immediately.

<Note>
  Actions that ask for confirmation (like refunds) are not available over the hosted connector yet, because the confirmation step needs a channel the remote protocol does not have. Use the local server for those, or wait for the confirm-in-chat fallback. Everything else - reads, payment links, billing objects - works.
</Note>

## Run the local server (Cursor, Claude Code, VS Code)

### 1. Generate a scoped token

Open [`dashboard.paybridgenp.com/mcp`](https://dashboard.paybridgenp.com/mcp). Click **Generate token**.

The new-token form lets you pick:

* **Description** - a label so you can find this token later in the audit log (e.g., "Claude Desktop on my laptop").
* **Scopes** - grouped Read / Write / Sensitive. Read-only is the safe default; opt in to writes per category.
* **Expires** - 7d, 30d, 90d, or never. 30d is recommended.
* **Spend cap (paisa, 24h rolling)** - auto-prefilled to Rs 50,000 when any write scope is enabled. Hard cap on the rolling 24-hour sum of refunds + checkout sessions originated by this token.

Hit **Generate**. The raw `sk_test_…` or `sk_live_…` token is shown **once** - copy it immediately. We can't show it again.

### 2. Paste into your AI assistant

#### Claude Desktop

Add to `~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or `%APPDATA%\Claude\claude_desktop_config.json` (Windows):

```json theme={null}
{
  "mcpServers": {
    "paybridge": {
      "command": "npx",
      "args": ["-y", "@paybridge-np/mcp@latest"],
      "env": { "PAYBRIDGENP_API_KEY": "sk_live_..." }
    }
  }
}
```

Restart Claude Desktop.

#### Cursor

Same JSON in `.cursor/mcp.json` (or via Settings → MCP).

```json theme={null}
{
  "mcpServers": {
    "paybridge": {
      "command": "npx",
      "args": ["-y", "@paybridge-np/mcp@latest"],
      "env": { "PAYBRIDGENP_API_KEY": "sk_live_..." }
    }
  }
}
```

#### Claude Code

```bash theme={null}
claude mcp add paybridge \
  --env PAYBRIDGENP_API_KEY=sk_live_... \
  -- npx -y @paybridge-np/mcp@latest
```

#### VS Code

`.vscode/mcp.json`:

```json theme={null}
{
  "servers": {
    "paybridge": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@paybridge-np/mcp@latest"],
      "env": { "PAYBRIDGENP_API_KEY": "sk_live_..." }
    }
  }
}
```

#### Claude web, mobile, or ChatGPT

These use the hosted connector instead of a local token - see [Connect a hosted app](#connect-a-hosted-app-claude-web-mobile-chatgpt) above.

### 3. Try it

Open your assistant and type something natural:

> Refund the last successful payment from `customer@example.com`.

The agent picks the right tool calls (`list_payments` → `get_payment` → `create_refund`), and PayBridgeNP's MCP server pops up a confirmation modal asking you to approve the refund before it executes. You see the refund result inline.

## What you can ask

The agent figures out the right tool calls. You don't write them by hand.

* *"Show me payments above Rs 5,000 from this week, grouped by provider."*
* *"Why did the webhook to checkout.acme.com fail yesterday at 3pm?"*
* *"Create a payment link for Rs 2,500 titled 'Course access - December batch'."*
* *"What's my analytics overview for the last 30 days - gross volume, success rate, refunds?"*
* *"List all subscriptions that are past due, with the customer email."*
* *"Pause the subscription for [ram@sherpa.com](mailto:ram@sherpa.com) until the end of the month."*

## Tools

70 tools across read + write. Read tools cover the entire account surface; write tools cover refunds, checkout creation, payment-link CRUD, webhook CRUD, and the full billing surface - plans, customers, subscriptions, invoices, coupons, promotions, tax, dunning, and usage metering.

### Read (33 tools)

| Tool                                                                      | Scope            | What it does                                                                                  |
| ------------------------------------------------------------------------- | ---------------- | --------------------------------------------------------------------------------------------- |
| `get_account`                                                             | `account:read`   | Merchant + project + key context (PII masked unless `pii:read`)                               |
| `search_docs`                                                             | `docs:read`      | Search these docs (guides, API reference, providers) and return matching pages with a snippet |
| `list_payments` / `get_payment`                                           | `payments:read`  | Inspect payments with full provider + customer detail                                         |
| `list_refunds` / `get_refund`                                             | `refunds:read`   | Refund history, status, failure reason                                                        |
| `list_checkout_sessions` / `get_checkout_session`                         | `sessions:read`  | In-flight + abandoned checkouts                                                               |
| `list_payment_links` / `get_payment_link`                                 | `links:read`     | Links + view/conversion stats inline                                                          |
| `list_webhook_endpoints` / `list_webhook_deliveries`                      | `webhooks:read`  | Endpoint config + per-delivery debug                                                          |
| `list_plans` / `get_plan`                                                 | `billing:read`   | Subscription billing plans                                                                    |
| `list_customers` / `get_customer`                                         | `billing:read`   | Billing customers                                                                             |
| `list_subscriptions` / `get_subscription`                                 | `billing:read`   | Active + past-due subscriptions                                                               |
| `list_invoices` / `get_invoice`                                           | `billing:read`   | Subscription invoices                                                                         |
| `list_invoice_items`                                                      | `billing:read`   | Pending one-off invoice items on a subscription                                               |
| `list_coupons` / `get_coupon`                                             | `billing:read`   | Discount coupons and their redemption stats                                                   |
| `list_promotion_codes` / `get_promotion_code` / `validate_promotion_code` | `billing:read`   | Promotion codes - list, inspect, or validate a code before applying                           |
| `get_tax_settings`                                                        | `billing:read`   | Active tax configuration for the account                                                      |
| `list_dunning_policies` / `get_dunning_invoice_status`                    | `billing:read`   | Dunning policy definitions + per-invoice dunning state                                        |
| `preview_subscription_proration`                                          | `billing:read`   | Estimate the prorated credit/charge before a plan change                                      |
| `get_subscription_usage_summary` / `list_usage_records`                   | `billing:read`   | Metered usage totals and raw usage record history                                             |
| `get_analytics_overview`                                                  | `analytics:read` | Headline KPIs (total / success rate / volume / funnel / per-provider) over a 1–90 day window  |

### Write (37 tools)

Every write tool is annotated `destructiveHint`. Money-moving tools always elicit confirmation in the host UI before executing.

| Tool                                                            | Scope            | Confirms?                            |
| --------------------------------------------------------------- | ---------------- | ------------------------------------ |
| `create_checkout_session`                                       | `payments:write` | If `amount > 5,000` (paisa: 500,000) |
| `create_refund`                                                 | `refunds:write`  | **Always**                           |
| `create_payment_link`                                           | `links:write`    | No                                   |
| `update_payment_link`                                           | `links:write`    | No                                   |
| `cancel_payment_link`                                           | `links:write`    | No (soft-deactivate, reversible)     |
| `delete_payment_link`                                           | `links:write`    | **Always** (only if never used)      |
| `create_webhook_endpoint`                                       | `webhooks:write` | No (idempotent create)               |
| `update_webhook_endpoint`                                       | `webhooks:write` | No                                   |
| `delete_webhook_endpoint`                                       | `webhooks:write` | **Always**                           |
| `create_plan` / `update_plan`                                   | `billing:write`  | No                                   |
| `create_customer` / `update_customer`                           | `billing:write`  | No                                   |
| `add_customer_credit`                                           | `billing:write`  | No                                   |
| `create_subscription`                                           | `billing:write`  | No                                   |
| `pause_subscription` / `resume_subscription`                    | `billing:write`  | No                                   |
| `cancel_subscription`                                           | `billing:write`  | **Always**                           |
| `change_subscription_plan`                                      | `billing:write`  | No                                   |
| `end_subscription_trial` / `extend_subscription_trial`          | `billing:write`  | No                                   |
| `create_invoice_item` / `delete_invoice_item`                   | `billing:write`  | No                                   |
| `create_coupon` / `deactivate_coupon`                           | `billing:write`  | No                                   |
| `create_promotion_code` / `deactivate_promotion_code`           | `billing:write`  | No                                   |
| `apply_coupon_to_subscription` / `remove_subscription_discount` | `billing:write`  | No                                   |
| `update_tax_settings`                                           | `billing:write`  | No                                   |
| `create_dunning_policy` / `update_dunning_policy`               | `billing:write`  | No                                   |
| `set_subscription_dunning_policy`                               | `billing:write`  | No                                   |
| `stop_invoice_dunning`                                          | `billing:write`  | **Always**                           |
| `retry_invoice_dunning_now`                                     | `billing:write`  | No                                   |
| `report_subscription_usage` / `update_subscription_quantity`    | `billing:write`  | No                                   |

## Prompts

6 built-in prompt templates that appear as slash commands and menu items in Claude Desktop and Cursor. Select one, fill in any arguments, and the agent picks up from there - no need to remember tool names or craft instructions manually.

| Prompt                       | What it does                                                                                                                                                                    | Arguments                                                       |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| `daily_summary`              | End-of-day digest - revenue, payment counts, refunds, checkout funnel completion rate, and any failed webhook deliveries                                                        | None                                                            |
| `monthly_reconciliation`     | Full month reconciliation table: gross volume, net after refunds, success rate, provider breakdown, top 5 customers. Ready to share with an accountant                          | `month` (optional, e.g. `2026-04`)                              |
| `investigate_failed_payment` | Diagnoses why a payment or batch of payments failed. Checks provider error codes, checkout session funnel, and recommends retry / contact customer / escalate                   | `payment_id` (optional) or `customer_email` (optional)          |
| `onboard_customer`           | Creates a billing customer and subscribes them to a plan in one flow. Validates the plan, optionally validates and applies a promotion code, then confirms subscription details | `email`, `name`, `plan_id` (required); `coupon_code` (optional) |
| `review_dunning`             | Lists all past-due invoices, shows retry count and next scheduled retry for each, and categorizes them as Retry now / Stop dunning / Wait. Asks for confirmation before acting  | None                                                            |
| `apply_discount`             | Validates a promotion code, shows the before/after price, then applies the discount to a subscription after confirmation                                                        | `subscription_id`, `promotion_code`                             |

Prompts are available in any host that supports MCP prompts - Claude Desktop ≥ 0.7, Cursor ≥ 0.42, Claude Code current. In Claude Desktop, open the prompt picker with `/` and type `paybridge` to filter to PayBridgeNP prompts.

## Scope reference

16 scopes. Tokens hold an explicit allowlist - anything not in the list returns `403 insufficient_scope` at the API gateway, never reaching the handler.

### Read scopes (granted by default)

| Scope            | Unlocks                                             |
| ---------------- | --------------------------------------------------- |
| `account:read`   | `get_account`                                       |
| `payments:read`  | `list_payments`, `get_payment`                      |
| `refunds:read`   | `list_refunds`, `get_refund`                        |
| `sessions:read`  | `list_checkout_sessions`, `get_checkout_session`    |
| `links:read`     | `list_payment_links`, `get_payment_link`            |
| `webhooks:read`  | `list_webhook_endpoints`, `list_webhook_deliveries` |
| `billing:read`   | All `list_*` / `get_*` billing tools                |
| `analytics:read` | `get_analytics_overview`                            |
| `audit:read`     | (reserved - `list_audit_logs` shipping next)        |
| `docs:read`      | `search_docs`                                       |

### Write scopes (opt in per scope)

| Scope            | Unlocks                                                                                    |
| ---------------- | ------------------------------------------------------------------------------------------ |
| `payments:write` | `create_checkout_session`                                                                  |
| `refunds:write`  | `create_refund`                                                                            |
| `links:write`    | `create_payment_link`, `update_payment_link`, `cancel_payment_link`, `delete_payment_link` |
| `webhooks:write` | webhook CRUD                                                                               |
| `billing:write`  | All billing CRUD + lifecycle                                                               |

### Sensitive

| Scope      | Effect                                                                                         |
| ---------- | ---------------------------------------------------------------------------------------------- |
| `pii:read` | Returns raw `customer_email` and `customer_phone` instead of masked. Never granted by default. |

## Security model

Four overlapping defenses so an agent can't bankrupt you, and a token leak is contained.

### 1. Scope enforcement

Scopes are enforced on every API route before your request reaches the handler. Tokens created for MCP carry an explicit scope allowlist; classic REST API keys are unscoped and keep full access for backward compatibility.

### 2. Elicitation gates on destructive actions

Money-moving tool calls send an MCP `elicitation/create` request to the host. The host shows a confirmation modal with the proposed amount, customer, and action. The tool only proceeds on `accept`. Hosts that don't support elicitation - usually older clients - fail closed with `elicitation_unsupported` and an actionable error pointing back to the dashboard.

For `create_refund`, the server hydrates the underlying payment first, so the modal shows the real amount + customer + provider, not just an opaque payment id.

### 3. 24-hour rolling spend cap

Every checkout session and refund records its `originating_api_key_id`. Before each `POST /v1/checkout` and `POST /v1/refunds`, the server sums the originating spend in the trailing 24 hours; if `current + new > spend_cap_paisa`, the call is rejected with HTTP 403:

```json theme={null}
{
  "error": {
    "message": "MCP token spend cap exceeded. Last 24h spend: Rs 400.00, cap: Rs 500.00, remaining: Rs 100.00.",
    "type": "permission_error",
    "code": "over_spend_cap",
    "spent_paisa": 40000,
    "cap_paisa": 50000,
    "remaining_paisa": 10000,
    "reset_at": "2026-04-19T00:21:12.556Z",
    "request_id": "req_..."
  }
}
```

### 4. Per-token rate limits

Three buckets, all per-token:

* **Total**: 60 calls / 60s
* **Destructive**: 6 calls / 60s
* **Elicitation-gated**: 2 calls / 60s

Returns `429` with `Retry-After` and `X-RateLimit-Bucket` headers. REST keys are unaffected for back-compat.

### Other defenses

* **Audit trail.** Every tool call is recorded with `mcp.tool.<name>`, the token id, and the assistant's name (captured from the MCP `InitializeRequest.clientInfo.name`). Visible live in your dashboard.
* **No token passthrough.** The MCP server never forwards your token to upstream provider APIs. Khalti / eSewa secrets stay server-side.
* **Prompt-injection defense.** Customer-controlled fields (names, descriptions, metadata) are wrapped in `<untrusted>…</untrusted>` fences when returned to the model. Zero-width characters are stripped. Secret patterns (`sk_*`, `pk_*`, `whsec_*`, `Bearer …`) are pattern-redacted on the way out.
* **PII masking.** `customer_email` shows as `ra***@example.com`; `customer_phone` shows as `***1234`. Unmask only by granting `pii:read`.
* **One-click revoke.** Find the token in the dashboard and click the trash icon. The next call returns 401 within seconds.

## Audit + activity feed

Open [`dashboard.paybridgenp.com/mcp`](https://dashboard.paybridgenp.com/mcp). The **Recent activity** card shows the last 24h of MCP-originated events:

* `mcp_token.created` / `mcp_token.revoked`
* `refund.created` (with `via: "mcp"`, `mcp_client_name`, `api_key_id`)
* `checkout_session.created`
* `webhook_endpoint.created` / `.updated` / `.deleted`

Pro-plan merchants see the full audit history at `/logs` with the same MCP tagging.

## Configuration reference

The MCP server reads two env vars when you run it:

| Env var                    | Required | Default                       |
| -------------------------- | -------- | ----------------------------- |
| `PAYBRIDGENP_API_KEY`      | yes      | -                             |
| `PAYBRIDGENP_API_BASE_URL` | no       | `https://api.paybridgenp.com` |

You can also pass `--api-key=sk_live_...` as a CLI argument instead of the env var.

## Troubleshooting

### Tools don't show up in my assistant

1. Restart the assistant after editing config - most hosts only re-read MCP configs at startup.
2. Run `npx -y @paybridge-np/mcp@latest` in a terminal manually. If it errors, the message will tell you what's wrong (usually a missing or revoked token).
3. Check the host's MCP log. Claude Desktop: `~/Library/Logs/Claude/mcp*.log`.

### Every tool call returns 401

Token is revoked, expired, or the env var didn't survive into the host's environment. Generate a fresh token from the dashboard and replace.

### Every write call returns `insufficient_scope`

Your token is read-only. Generate a new token with the relevant write scopes ticked. Don't reuse the read-only token - issue a separate write-scoped token with a tight spend cap so you can revoke it independently.

### `over_spend_cap` after running a few refunds

Either raise the cap on the token or wait for the 24h window to roll. The error response includes `reset_at` - that's when the oldest counted activity ages out.

### `elicitation_unsupported` on a destructive tool

Your host doesn't implement MCP elicitation. Update the host (Claude Desktop ≥ 0.7, Cursor ≥ 0.42, Claude Code current), or perform the action in the PayBridgeNP dashboard instead.

### Customer names show up wrapped in `<untrusted>`

That's deliberate - it tells the model not to interpret merchant-controlled free text as instructions. Defense against prompt injection in metadata / customer fields. Don't strip the wrappers.

### How do I see what the agent is actually doing?

The dashboard's **Recent activity** card shows every MCP tool invocation with the assistant's name, the action, and timestamps. Hosts also typically log tool calls - Claude Desktop shows them inline; Cursor logs them to its dev console.

## Roadmap

* **Confirm-in-chat for write actions** over the hosted connector, so refunds and other confirmation-gated tools work without the local server.
* **More audit + search tools** (`list_audit_logs`, `search_paybridge`).
* **AP2 mandate hooks** for agent-initiated commerce (forward-compat).

Track progress at [github.com/paybridgenp/paybridgenp-mcp](https://github.com/paybridgenp/paybridgenp-mcp).
