khqrpay-mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/LICENSE +21 -0
- package/README.md +65 -2
- package/dist/api.d.ts +23 -0
- package/dist/api.js +50 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +12 -0
- package/dist/server.d.ts +16 -0
- package/dist/server.js +154 -0
- package/dist/signature.d.ts +15 -0
- package/dist/signature.js +27 -0
- package/package.json +54 -4
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0 (2026-11-19)
|
|
4
|
+
|
|
5
|
+
- First release: create_test_payment, simulate_test_payment, get_payment, list_payments, get_usage and check_webhook_signature, over stdio. Test keys do everything; live keys never create or change payments, and read only with KHQRPAY_MCP_LIVE_READS=1.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 KHQRPay
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,66 @@
|
|
|
1
|
-
#
|
|
1
|
+
# khqrpay-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A local [MCP](https://modelcontextprotocol.io) server for [KHQRPay](https://khqrpay.dev), the KHQR payment gateway and API for Cambodia. It lets an AI coding tool create and check KHQR test payments, read payments, show your plan's usage and check webhook signatures while it builds your integration. It runs on your own machine, with your own key.
|
|
4
|
+
|
|
5
|
+
## What it can do
|
|
6
|
+
|
|
7
|
+
| Tool | What it does | Key |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| `create_test_payment` | Creates a test payment: a KHQR no bank will pay, with a hosted checkout page | Test only |
|
|
10
|
+
| `simulate_test_payment` | Moves a test payment to scanned, paid, expired or failed; your test webhook endpoints get the events | Test only |
|
|
11
|
+
| `get_payment` | Reads one payment: status, amounts, expiry, whether it was paid late | Test, or live with opt-in |
|
|
12
|
+
| `list_payments` | Lists payments, newest first, a page at a time | Test, or live with opt-in |
|
|
13
|
+
| `get_usage` | Shows your plan's paid transactions used and left | Test, or live with opt-in |
|
|
14
|
+
| `check_webhook_signature` | Checks an `X-KHQRPay-Signature` header against a raw body, and says why it fails | Runs locally |
|
|
15
|
+
|
|
16
|
+
## Safe by default
|
|
17
|
+
|
|
18
|
+
- **Test keys do everything.** Use a `kp_test_` key: test payments never reach a bank and never count toward your plan.
|
|
19
|
+
- **Live keys never create or change anything.** With a `kp_live_` key, `create_test_payment` and `simulate_test_payment` refuse, and the read tools work only if you set `KHQRPAY_MCP_LIVE_READS=1`.
|
|
20
|
+
- **Secrets stay in the environment.** Keys are read from environment variables and never printed. The webhook signing secret is never a tool argument, and `check_webhook_signature` never shows the right signature.
|
|
21
|
+
- **No polling.** Reads count toward your account's daily read allowance, so the read tools tell the model to read once, not in a loop. Your own app should follow payments with webhooks.
|
|
22
|
+
|
|
23
|
+
## Set up
|
|
24
|
+
|
|
25
|
+
You need Node.js 18 or newer and a test key from the KHQRPay dashboard (*API keys*, with the page set to *Test*).
|
|
26
|
+
|
|
27
|
+
**Claude Code**
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
claude mcp add khqrpay -e KHQRPAY_SECRET_KEY=kp_test_… -- npx -y khqrpay-mcp
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
**Claude Desktop, Cursor and other clients** that read an `mcpServers` file (`claude_desktop_config.json`, `.cursor/mcp.json`):
|
|
34
|
+
|
|
35
|
+
```json
|
|
36
|
+
{
|
|
37
|
+
"mcpServers": {
|
|
38
|
+
"khqrpay": {
|
|
39
|
+
"command": "npx",
|
|
40
|
+
"args": ["-y", "khqrpay-mcp"],
|
|
41
|
+
"env": { "KHQRPAY_SECRET_KEY": "kp_test_…" }
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Add `"KHQRPAY_WEBHOOK_SECRET": "whsec_…"` to `env` to use `check_webhook_signature` with your test endpoint's signing secret.
|
|
48
|
+
|
|
49
|
+
## Environment
|
|
50
|
+
|
|
51
|
+
| Variable | What it's for |
|
|
52
|
+
| --- | --- |
|
|
53
|
+
| `KHQRPAY_SECRET_KEY` | Your KHQRPay key. `kp_test_` for every tool; `kp_live_` for the read tools only, with the next variable |
|
|
54
|
+
| `KHQRPAY_MCP_LIVE_READS` | Set to `1` to let a live key read payments and usage. Nothing ever creates or changes live payments |
|
|
55
|
+
| `KHQRPAY_WEBHOOK_SECRET` | A webhook endpoint's signing secret, for `check_webhook_signature` |
|
|
56
|
+
| `KHQRPAY_API_BASE` | Another KHQRPay address, for testing. Must be https, or http on localhost |
|
|
57
|
+
|
|
58
|
+
## Learn more
|
|
59
|
+
|
|
60
|
+
- [KHQRPay docs](https://khqrpay.dev/docs): payments, webhooks, test mode and going live.
|
|
61
|
+
- [The AI brief](https://khqrpay.dev/llms-full.txt): every docs page in one file, for your coding tool's context.
|
|
62
|
+
- Official SDKs: [Node.js](https://www.npmjs.com/package/khqrpay), [Python](https://pypi.org/project/khqrpay/) and [PHP](https://packagist.org/packages/khqrpay/khqrpay-php).
|
|
63
|
+
|
|
64
|
+
## License
|
|
65
|
+
|
|
66
|
+
MIT
|
package/dist/api.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** What a call to the KHQRPay API came back with: the body, or the API's error code and message. */
|
|
2
|
+
export type ApiResult = {
|
|
3
|
+
ok: true;
|
|
4
|
+
status: number;
|
|
5
|
+
body: unknown;
|
|
6
|
+
} | {
|
|
7
|
+
ok: false;
|
|
8
|
+
status: number;
|
|
9
|
+
error: string;
|
|
10
|
+
message: string;
|
|
11
|
+
retryAfter?: number;
|
|
12
|
+
};
|
|
13
|
+
export declare class KhqrPayApi {
|
|
14
|
+
private readonly key;
|
|
15
|
+
private readonly base;
|
|
16
|
+
private readonly fetchImpl;
|
|
17
|
+
private readonly userAgent;
|
|
18
|
+
constructor(key: string, base: string, fetchImpl: typeof fetch, userAgent: string);
|
|
19
|
+
request(method: "GET" | "POST", path: string, opts?: {
|
|
20
|
+
body?: unknown;
|
|
21
|
+
idempotencyKey?: string;
|
|
22
|
+
}): Promise<ApiResult>;
|
|
23
|
+
}
|
package/dist/api.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
export class KhqrPayApi {
|
|
2
|
+
key;
|
|
3
|
+
base;
|
|
4
|
+
fetchImpl;
|
|
5
|
+
userAgent;
|
|
6
|
+
constructor(key, base, fetchImpl, userAgent) {
|
|
7
|
+
this.key = key;
|
|
8
|
+
this.base = base;
|
|
9
|
+
this.fetchImpl = fetchImpl;
|
|
10
|
+
this.userAgent = userAgent;
|
|
11
|
+
}
|
|
12
|
+
async request(method, path, opts = {}) {
|
|
13
|
+
const headers = { Authorization: `Bearer ${this.key}`, "User-Agent": this.userAgent, Accept: "application/json" };
|
|
14
|
+
if (opts.body !== undefined)
|
|
15
|
+
headers["Content-Type"] = "application/json";
|
|
16
|
+
if (opts.idempotencyKey)
|
|
17
|
+
headers["Idempotency-Key"] = opts.idempotencyKey;
|
|
18
|
+
let res;
|
|
19
|
+
try {
|
|
20
|
+
res = await this.fetchImpl(`${this.base}${path}`, {
|
|
21
|
+
method,
|
|
22
|
+
headers,
|
|
23
|
+
body: opts.body === undefined ? undefined : JSON.stringify(opts.body),
|
|
24
|
+
signal: AbortSignal.timeout(15_000),
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
return { ok: false, status: 0, error: "network_error", message: `KHQRPay couldn't be reached: ${err.message}` };
|
|
29
|
+
}
|
|
30
|
+
const text = await res.text();
|
|
31
|
+
let body = null;
|
|
32
|
+
try {
|
|
33
|
+
body = text ? JSON.parse(text) : null;
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
body = null;
|
|
37
|
+
}
|
|
38
|
+
if (res.ok)
|
|
39
|
+
return { ok: true, status: res.status, body };
|
|
40
|
+
const err = (body ?? {});
|
|
41
|
+
const retry = Number(res.headers.get("retry-after"));
|
|
42
|
+
return {
|
|
43
|
+
ok: false,
|
|
44
|
+
status: res.status,
|
|
45
|
+
error: typeof err.error === "string" ? err.error : `http_${res.status}`,
|
|
46
|
+
message: typeof err.message === "string" ? err.message : `KHQRPay answered HTTP ${res.status}.`,
|
|
47
|
+
...(Number.isFinite(retry) && retry > 0 ? { retryAfter: retry } : {}),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// khqrpay-mcp: a local MCP server for KHQRPay, spoken over stdin and stdout. Nothing is written to stdout but the
|
|
3
|
+
// protocol, and the keys are read from the environment and never printed.
|
|
4
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
5
|
+
import { createServer } from "./server.js";
|
|
6
|
+
const server = createServer({
|
|
7
|
+
secretKey: process.env.KHQRPAY_SECRET_KEY,
|
|
8
|
+
webhookSecret: process.env.KHQRPAY_WEBHOOK_SECRET,
|
|
9
|
+
allowLiveReads: process.env.KHQRPAY_MCP_LIVE_READS === "1",
|
|
10
|
+
apiBase: process.env.KHQRPAY_API_BASE,
|
|
11
|
+
});
|
|
12
|
+
await server.connect(new StdioServerTransport());
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
export declare const VERSION = "0.1.0";
|
|
3
|
+
export type ServerOptions = {
|
|
4
|
+
/** The KHQRPay secret key: kp_test_… for everything, or kp_live_… for reads only, and only with allowLiveReads. */
|
|
5
|
+
secretKey?: string;
|
|
6
|
+
/** The webhook endpoint's signing secret (whsec_…), for check_webhook_signature only. */
|
|
7
|
+
webhookSecret?: string;
|
|
8
|
+
/** With a kp_live_ key, allow the read tools (get_payment, list_payments, get_usage). Creating and simulating never take a live key. */
|
|
9
|
+
allowLiveReads?: boolean;
|
|
10
|
+
/** Another KHQRPay address, for testing: https, or http on localhost. */
|
|
11
|
+
apiBase?: string;
|
|
12
|
+
fetch?: typeof fetch;
|
|
13
|
+
/** The clock, in seconds, for check_webhook_signature. */
|
|
14
|
+
now?: () => number;
|
|
15
|
+
};
|
|
16
|
+
export declare function createServer(options?: ServerOptions): McpServer;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
3
|
+
import { z } from "zod";
|
|
4
|
+
import { KhqrPayApi } from "./api.js";
|
|
5
|
+
import { checkSignature } from "./signature.js";
|
|
6
|
+
export const VERSION = "0.1.0";
|
|
7
|
+
const DEFAULT_BASE = "https://khqrpay.dev";
|
|
8
|
+
const KEY = /^kp_(test|live)_[A-Za-z0-9_-]{16,128}$/;
|
|
9
|
+
const text = (value) => ({ content: [{ type: "text", text: value }] });
|
|
10
|
+
const fail = (value) => ({ content: [{ type: "text", text: value }], isError: true });
|
|
11
|
+
const json = (summary, value) => text(`${summary}\n${JSON.stringify(value, null, 2)}`);
|
|
12
|
+
/** An API error as the model should read it: the code to act on, the message, and whether to wait or stop. */
|
|
13
|
+
function apiError(r) {
|
|
14
|
+
let advice = "";
|
|
15
|
+
if (r.status === 429 && r.retryAfter) {
|
|
16
|
+
advice = r.retryAfter > 60
|
|
17
|
+
? ` Retry-After is ${r.retryAfter} seconds: that's a day-long limit, so stop and tell the user instead of retrying.`
|
|
18
|
+
: ` Wait ${r.retryAfter} seconds before trying again, and don't retry in a loop.`;
|
|
19
|
+
}
|
|
20
|
+
return fail(`KHQRPay answered ${r.status || "nothing"} ${r.error}: ${r.message}${advice}`);
|
|
21
|
+
}
|
|
22
|
+
export function createServer(options = {}) {
|
|
23
|
+
const key = options.secretKey?.trim();
|
|
24
|
+
const match = key ? KEY.exec(key) : null;
|
|
25
|
+
const mode = match ? match[1] : null;
|
|
26
|
+
const base = (options.apiBase?.trim() || DEFAULT_BASE).replace(/\/+$/, "");
|
|
27
|
+
const baseOk = /^https:\/\//.test(base) || /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/.test(base);
|
|
28
|
+
const api = mode && baseOk ? new KhqrPayApi(key, base, options.fetch ?? fetch, `khqrpay-mcp/${VERSION}`) : null;
|
|
29
|
+
const now = options.now ?? (() => Date.now() / 1000);
|
|
30
|
+
/** The API, if this server's key may do this kind of thing; otherwise why not, in words for the user. */
|
|
31
|
+
function gate(kind) {
|
|
32
|
+
if (!key)
|
|
33
|
+
return { result: fail("KHQRPAY_SECRET_KEY isn't set for this server. Create a test key (kp_test_…) under API keys in the KHQRPay dashboard and put it in the server's environment.") };
|
|
34
|
+
if (!mode)
|
|
35
|
+
return { result: fail("KHQRPAY_SECRET_KEY doesn't look like a KHQRPay key. It starts with kp_test_ (or kp_live_) and comes from the dashboard's API keys page.") };
|
|
36
|
+
if (!baseOk || !api)
|
|
37
|
+
return { result: fail("KHQRPAY_API_BASE must be an https address (or http on localhost).") };
|
|
38
|
+
if (mode === "live" && kind === "write")
|
|
39
|
+
return { result: fail("This server has a live key, and it never creates or changes live payments. Give it a test key (kp_test_…) to create and simulate test payments.") };
|
|
40
|
+
if (mode === "live" && !options.allowLiveReads)
|
|
41
|
+
return { result: fail("This server has a live key. Reading live payments needs KHQRPAY_MCP_LIVE_READS=1 in its environment; with a test key (kp_test_…) every tool works.") };
|
|
42
|
+
return { api };
|
|
43
|
+
}
|
|
44
|
+
const server = new McpServer({ name: "khqrpay", version: VERSION });
|
|
45
|
+
server.registerTool("create_test_payment", {
|
|
46
|
+
title: "Create a test payment",
|
|
47
|
+
description: "Creates a KHQRPay test payment: a KHQR that no bank will pay, with a hosted checkout page. Only with a kp_test_ key: this server never creates live payments. Returns the payment, including checkout_url and expires_at. Move it with simulate_test_payment; the store's test webhook endpoints get the events.",
|
|
48
|
+
inputSchema: {
|
|
49
|
+
amount: z.union([z.string(), z.number()]).describe('Dollars with up to 2 decimals ("16.88"), or whole riel ("5000").'),
|
|
50
|
+
currency: z.enum(["USD", "KHR"]).default("USD").describe("The currency the amount is in."),
|
|
51
|
+
reference_id: z.string().min(1).max(255).optional().describe("Your order id, as a string."),
|
|
52
|
+
metadata: z.record(z.string(), z.unknown()).optional().describe("Your own JSON object: up to 50 keys and 4 KB."),
|
|
53
|
+
},
|
|
54
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
55
|
+
}, async ({ amount, currency, reference_id, metadata }) => {
|
|
56
|
+
const g = gate("write");
|
|
57
|
+
if ("result" in g)
|
|
58
|
+
return g.result;
|
|
59
|
+
const body = { amount, currency, ...(reference_id ? { reference_id } : {}), ...(metadata ? { metadata } : {}) };
|
|
60
|
+
const r = await g.api.request("POST", "/v1/payments", { body, idempotencyKey: `mcp-${randomUUID()}` });
|
|
61
|
+
if (!r.ok)
|
|
62
|
+
return apiError(r);
|
|
63
|
+
const p = r.body;
|
|
64
|
+
return json(`Test payment ${p.id}: ${p.amount} ${p.currency}, checkout ${p.checkout_url}, offered until ${p.expires_at}.`, r.body);
|
|
65
|
+
});
|
|
66
|
+
server.registerTool("simulate_test_payment", {
|
|
67
|
+
title: "Simulate a test payment",
|
|
68
|
+
description: "Moves a test payment to scanned, paid, expired or failed, as if the customer and the bank had acted, and the store's test webhook endpoints get the matching event. Test payments only. To try a late payment, simulate expired and then paid. A status the payment can't move to changes nothing.",
|
|
69
|
+
inputSchema: {
|
|
70
|
+
id: z.string().min(1).describe("The test payment's id."),
|
|
71
|
+
status: z.enum(["scanned", "paid", "expired", "failed"]),
|
|
72
|
+
},
|
|
73
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: true },
|
|
74
|
+
}, async ({ id, status }) => {
|
|
75
|
+
const g = gate("write");
|
|
76
|
+
if ("result" in g)
|
|
77
|
+
return g.result;
|
|
78
|
+
const r = await g.api.request("POST", `/v1/test/payments/${encodeURIComponent(id)}/simulate`, { body: { status } });
|
|
79
|
+
if (!r.ok)
|
|
80
|
+
return apiError(r);
|
|
81
|
+
const p = r.body;
|
|
82
|
+
return json(`Test payment ${p.id} is now ${p.status}.`, r.body);
|
|
83
|
+
});
|
|
84
|
+
const readNote = "Each call counts toward the account's daily read allowance, so read when you need the answer and never poll in a loop; application code should follow payments with webhooks.";
|
|
85
|
+
server.registerTool("get_payment", {
|
|
86
|
+
title: "Get a payment",
|
|
87
|
+
description: `Reads one payment by its id: status (pending, scanned, paid, expired or failed), amounts, expiry, and whether it was paid late. ${readNote}`,
|
|
88
|
+
inputSchema: { id: z.string().min(1).describe("The payment's id.") },
|
|
89
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
90
|
+
}, async ({ id }) => {
|
|
91
|
+
const g = gate("read");
|
|
92
|
+
if ("result" in g)
|
|
93
|
+
return g.result;
|
|
94
|
+
const r = await g.api.request("GET", `/v1/payments/${encodeURIComponent(id)}`);
|
|
95
|
+
if (!r.ok)
|
|
96
|
+
return apiError(r);
|
|
97
|
+
const p = r.body;
|
|
98
|
+
return json(`Payment ${p.id} (${p.livemode ? "live" : "test"}) is ${p.status}.`, r.body);
|
|
99
|
+
});
|
|
100
|
+
server.registerTool("list_payments", {
|
|
101
|
+
title: "List payments",
|
|
102
|
+
description: `Lists the store's payments in the key's mode, newest first, one page at a time; each leaves out metadata, which get_payment returns. ${readNote}`,
|
|
103
|
+
inputSchema: {
|
|
104
|
+
status: z.enum(["pending", "scanned", "paid", "expired", "failed"]).optional(),
|
|
105
|
+
limit: z.number().int().min(1).max(100).default(10),
|
|
106
|
+
cursor: z.string().optional().describe("next_cursor from the previous page, with the same status."),
|
|
107
|
+
},
|
|
108
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
109
|
+
}, async ({ status, limit, cursor }) => {
|
|
110
|
+
const g = gate("read");
|
|
111
|
+
if ("result" in g)
|
|
112
|
+
return g.result;
|
|
113
|
+
const q = new URLSearchParams({ limit: String(limit) });
|
|
114
|
+
if (status)
|
|
115
|
+
q.set("status", status);
|
|
116
|
+
if (cursor)
|
|
117
|
+
q.set("cursor", cursor);
|
|
118
|
+
const r = await g.api.request("GET", `/v1/payments?${q}`);
|
|
119
|
+
if (!r.ok)
|
|
120
|
+
return apiError(r);
|
|
121
|
+
const list = r.body;
|
|
122
|
+
return json(`${list.data?.length ?? 0} payment(s)${list.has_more ? ", and more: pass next_cursor for the next page" : ""}.`, r.body);
|
|
123
|
+
});
|
|
124
|
+
server.registerTool("get_usage", {
|
|
125
|
+
title: "Get plan usage",
|
|
126
|
+
description: "Shows the account's plan, its paid transactions used and left this period, and when the period ends. Only paid live payments count; test payments never do.",
|
|
127
|
+
inputSchema: {},
|
|
128
|
+
annotations: { readOnlyHint: true, openWorldHint: true },
|
|
129
|
+
}, async () => {
|
|
130
|
+
const g = gate("read");
|
|
131
|
+
if ("result" in g)
|
|
132
|
+
return g.result;
|
|
133
|
+
const r = await g.api.request("GET", "/v1/usage");
|
|
134
|
+
if (!r.ok)
|
|
135
|
+
return apiError(r);
|
|
136
|
+
const u = r.body;
|
|
137
|
+
return json(`Plan ${u.plan}: ${u.used} of ${u.limit} paid transactions used, ${u.remaining} left.`, r.body);
|
|
138
|
+
});
|
|
139
|
+
server.registerTool("check_webhook_signature", {
|
|
140
|
+
title: "Check a webhook signature",
|
|
141
|
+
description: "Checks an X-KHQRPay-Signature header against a webhook's raw body, with the signing secret from this server's KHQRPAY_WEBHOOK_SECRET (the secret is never an argument and never shown). Says why a check fails: a malformed header, a timestamp more than 5 minutes off, or a mismatch. Runs on this machine; nothing is sent anywhere.",
|
|
142
|
+
inputSchema: {
|
|
143
|
+
raw_body: z.string().describe("The request body exactly as received, before any JSON parsing."),
|
|
144
|
+
signature_header: z.string().describe("The X-KHQRPay-Signature header's value: t=<unix seconds>,v1=<hex>."),
|
|
145
|
+
},
|
|
146
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
147
|
+
}, async ({ raw_body, signature_header }) => {
|
|
148
|
+
const check = checkSignature(raw_body, signature_header, options.webhookSecret, now());
|
|
149
|
+
return check.valid
|
|
150
|
+
? text(`Valid: signed ${check.age_seconds} seconds ago with this endpoint's secret.`)
|
|
151
|
+
: text(`Not valid. ${check.reason}`);
|
|
152
|
+
});
|
|
153
|
+
return server;
|
|
154
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type SignatureCheck = {
|
|
2
|
+
valid: true;
|
|
3
|
+
timestamp: number;
|
|
4
|
+
age_seconds: number;
|
|
5
|
+
} | {
|
|
6
|
+
valid: false;
|
|
7
|
+
reason: string;
|
|
8
|
+
};
|
|
9
|
+
/**
|
|
10
|
+
* Checks an X-KHQRPay-Signature header ("t=<unix seconds>,v1=<hex>") against a webhook's raw body: v1 is the hex
|
|
11
|
+
* HMAC-SHA256 of "<t>.<raw body>", keyed with the endpoint's signing secret, and t must be within 5 minutes of now.
|
|
12
|
+
* An unset or empty secret refuses everything, since HMAC accepts an empty key. It says why a check fails, but never
|
|
13
|
+
* what the right signature would be.
|
|
14
|
+
*/
|
|
15
|
+
export declare function checkSignature(rawBody: string, header: string, secret: string | undefined, nowSeconds?: number, toleranceSec?: number): SignatureCheck;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
/**
|
|
3
|
+
* Checks an X-KHQRPay-Signature header ("t=<unix seconds>,v1=<hex>") against a webhook's raw body: v1 is the hex
|
|
4
|
+
* HMAC-SHA256 of "<t>.<raw body>", keyed with the endpoint's signing secret, and t must be within 5 minutes of now.
|
|
5
|
+
* An unset or empty secret refuses everything, since HMAC accepts an empty key. It says why a check fails, but never
|
|
6
|
+
* what the right signature would be.
|
|
7
|
+
*/
|
|
8
|
+
export function checkSignature(rawBody, header, secret, nowSeconds = Date.now() / 1000, toleranceSec = 300) {
|
|
9
|
+
if (!secret) {
|
|
10
|
+
return { valid: false, reason: "KHQRPAY_WEBHOOK_SECRET isn't set for this server, so nothing can be checked. Set it to the endpoint's signing secret (whsec_…) in the server's environment." };
|
|
11
|
+
}
|
|
12
|
+
const h = String(header ?? "");
|
|
13
|
+
const t = /(?:^|,)\s*t=(\d{1,12})\s*(?=,|$)/.exec(h)?.[1];
|
|
14
|
+
const v1 = /(?:^|,)\s*v1=([0-9a-fA-F]{64})\s*(?=,|$)/.exec(h)?.[1];
|
|
15
|
+
if (!t || !v1)
|
|
16
|
+
return { valid: false, reason: "The header isn't in the form t=<unix seconds>,v1=<64 hex digits>." };
|
|
17
|
+
const age = Math.round(nowSeconds - Number(t));
|
|
18
|
+
if (Math.abs(age) > toleranceSec) {
|
|
19
|
+
return { valid: false, reason: `The timestamp is ${Math.abs(age)} seconds ${age > 0 ? "old" : "in the future"}. A signature more than 5 minutes off is refused.` };
|
|
20
|
+
}
|
|
21
|
+
const expected = createHmac("sha256", secret).update(`${t}.${rawBody}`).digest();
|
|
22
|
+
const given = Buffer.from(v1, "hex");
|
|
23
|
+
if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
|
|
24
|
+
return { valid: false, reason: "The signature doesn't match this body and secret. Check the body is the raw bytes as received, not JSON parsed and written out again, and that the secret is the signing secret of the endpoint that received the event." };
|
|
25
|
+
}
|
|
26
|
+
return { valid: true, timestamp: Number(t), age_seconds: age };
|
|
27
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "khqrpay-mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "MCP server for KHQRPay: lets AI coding tools create and check KHQR test payments, read payments and check webhook signatures, with your own key.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mcp",
|
|
7
|
+
"model-context-protocol",
|
|
8
|
+
"khqr",
|
|
9
|
+
"khqrpay",
|
|
10
|
+
"bakong",
|
|
11
|
+
"cambodia",
|
|
12
|
+
"payments",
|
|
13
|
+
"webhook"
|
|
14
|
+
],
|
|
15
|
+
"homepage": "https://khqrpay.dev/docs",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/khqrpay-dev/khqrpay-mcp.git"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/khqrpay-dev/khqrpay-mcp/issues"
|
|
22
|
+
},
|
|
23
|
+
"license": "MIT",
|
|
24
|
+
"author": "KHQRPay (https://khqrpay.dev)",
|
|
25
|
+
"type": "module",
|
|
26
|
+
"bin": {
|
|
27
|
+
"khqrpay-mcp": "dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"main": "dist/server.js",
|
|
30
|
+
"types": "dist/server.d.ts",
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"CHANGELOG.md"
|
|
36
|
+
],
|
|
37
|
+
"engines": {
|
|
38
|
+
"node": ">=18"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "rm -rf dist && tsc -p tsconfig.json && chmod +x dist/index.js",
|
|
42
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"smoke": "node scripts/smoke.mjs",
|
|
45
|
+
"prepublishOnly": "npm run typecheck && npm test && npm run build"
|
|
46
|
+
},
|
|
47
|
+
"dependencies": {
|
|
48
|
+
"@modelcontextprotocol/sdk": "^1.32.2",
|
|
49
|
+
"zod": "^3.25.76"
|
|
50
|
+
},
|
|
51
|
+
"devDependencies": {
|
|
52
|
+
"@types/node": "^26.6.6",
|
|
53
|
+
"typescript": "^7.0.2",
|
|
54
|
+
"vitest": "^5.1.0"
|
|
55
|
+
}
|
|
56
|
+
}
|