@coinvello/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/README.md +196 -2
- package/dist/client.d.ts +32 -0
- package/dist/client.js +86 -0
- package/dist/docs/llms-full.txt +792 -0
- package/dist/docs/llms.txt +56 -0
- package/dist/docs/openapi.yaml +8045 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +85 -0
- package/dist/server.d.ts +20 -0
- package/dist/server.js +442 -0
- package/dist/verify.d.ts +17 -0
- package/dist/verify.js +58 -0
- package/package.json +57 -4
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* coinvello-mcp entry point.
|
|
4
|
+
*
|
|
5
|
+
* coinvello-mcp stdio transport (Claude Desktop, Claude Code, Cursor, Windsurf)
|
|
6
|
+
* coinvello-mcp --http [port] Streamable HTTP transport on http://127.0.0.1:<port>/mcp (default 3333)
|
|
7
|
+
*
|
|
8
|
+
* Environment:
|
|
9
|
+
* COINVELLO_API_KEY cv_test_... (recommended) or cv_live_...
|
|
10
|
+
* COINVELLO_API_BASE default https://api.coinvello.com/v1 (use http://localhost:4242/v1 for the mock)
|
|
11
|
+
* COINVELLO_ALLOW_LIVE must be "1" to start with a cv_live_ key
|
|
12
|
+
* COINVELLO_API_VERSION optional CoinVello-Version pin
|
|
13
|
+
* MCP_HTTP_HOST bind address for --http (default 127.0.0.1)
|
|
14
|
+
*/
|
|
15
|
+
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
16
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
17
|
+
import { createServer as createHttpServer } from "node:http";
|
|
18
|
+
import { assertKeyAllowed, configFromEnv, createServer, SERVER_VERSION } from "./server.js";
|
|
19
|
+
const args = process.argv.slice(2);
|
|
20
|
+
if (args.includes("--version") || args.includes("-v")) {
|
|
21
|
+
console.log(SERVER_VERSION);
|
|
22
|
+
process.exit(0);
|
|
23
|
+
}
|
|
24
|
+
if (args.includes("--help") || args.includes("-h")) {
|
|
25
|
+
console.log(`coinvello-mcp ${SERVER_VERSION}
|
|
26
|
+
Usage: coinvello-mcp [--http [port]]
|
|
27
|
+
Env: COINVELLO_API_KEY, COINVELLO_API_BASE, COINVELLO_ALLOW_LIVE, COINVELLO_API_VERSION
|
|
28
|
+
Docs: https://coinvello.com/ai`);
|
|
29
|
+
process.exit(0);
|
|
30
|
+
}
|
|
31
|
+
const cfg = configFromEnv();
|
|
32
|
+
try {
|
|
33
|
+
// Fail fast with a readable message instead of on the first tool call.
|
|
34
|
+
assertKeyAllowed(cfg);
|
|
35
|
+
}
|
|
36
|
+
catch (e) {
|
|
37
|
+
console.error(`[coinvello-mcp] ${e.message}`);
|
|
38
|
+
if (!process.env.COINVELLO_MCP_LAZY)
|
|
39
|
+
process.exit(2);
|
|
40
|
+
}
|
|
41
|
+
const httpIdx = args.indexOf("--http");
|
|
42
|
+
if (httpIdx >= 0) {
|
|
43
|
+
const port = Number(args[httpIdx + 1]) || Number(process.env.PORT) || 3333;
|
|
44
|
+
const host = process.env.MCP_HTTP_HOST || "127.0.0.1";
|
|
45
|
+
const httpServer = createHttpServer(async (req, res) => {
|
|
46
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host ?? "localhost"}`);
|
|
47
|
+
if (url.pathname === "/health") {
|
|
48
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
49
|
+
res.end(JSON.stringify({ ok: true, name: "coinvello", version: SERVER_VERSION }));
|
|
50
|
+
return;
|
|
51
|
+
}
|
|
52
|
+
if (url.pathname !== "/mcp") {
|
|
53
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
54
|
+
res.end(JSON.stringify({ error: "use POST /mcp" }));
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
// Stateless mode: a fresh server + transport per request, no session ids to manage.
|
|
58
|
+
const server = createServer(cfg);
|
|
59
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
60
|
+
res.on("close", () => {
|
|
61
|
+
transport.close();
|
|
62
|
+
server.close();
|
|
63
|
+
});
|
|
64
|
+
try {
|
|
65
|
+
await server.connect(transport);
|
|
66
|
+
await transport.handleRequest(req, res);
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
console.error("[coinvello-mcp] request failed:", e);
|
|
70
|
+
if (!res.headersSent) {
|
|
71
|
+
res.writeHead(500, { "Content-Type": "application/json" });
|
|
72
|
+
res.end(JSON.stringify({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: null }));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
});
|
|
76
|
+
httpServer.listen(port, host, () => {
|
|
77
|
+
console.error(`[coinvello-mcp] Streamable HTTP on http://${host}:${port}/mcp (${cfg.baseUrl ?? "https://api.coinvello.com/v1"})`);
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
const server = createServer(cfg);
|
|
82
|
+
const transport = new StdioServerTransport();
|
|
83
|
+
await server.connect(transport);
|
|
84
|
+
console.error(`[coinvello-mcp] ready on stdio (${cfg.baseUrl ?? "https://api.coinvello.com/v1"}, ${cfg.apiKey?.startsWith("cv_live_") ? "LIVE" : "test"} mode)`);
|
|
85
|
+
}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoinVello MCP server: tools, resources and prompts.
|
|
3
|
+
*
|
|
4
|
+
* Tools talk to https://api.coinvello.com/v1 (or COINVELLO_API_BASE, e.g. the local reference
|
|
5
|
+
* server at http://localhost:4242/v1) with the key from COINVELLO_API_KEY. Live keys (cv_live_)
|
|
6
|
+
* are refused unless COINVELLO_ALLOW_LIVE=1 so an agent cannot accidentally touch mainnet money.
|
|
7
|
+
*/
|
|
8
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
9
|
+
export declare const SERVER_NAME = "coinvello";
|
|
10
|
+
export declare const SERVER_VERSION = "0.1.0";
|
|
11
|
+
export interface ServerConfig {
|
|
12
|
+
apiKey?: string;
|
|
13
|
+
baseUrl?: string;
|
|
14
|
+
allowLive?: boolean;
|
|
15
|
+
apiVersion?: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function configFromEnv(env?: NodeJS.ProcessEnv): ServerConfig;
|
|
18
|
+
/** Throws a clear error when the key is missing or is a live key without the explicit opt-in. */
|
|
19
|
+
export declare function assertKeyAllowed(cfg: ServerConfig): void;
|
|
20
|
+
export declare function createServer(cfg?: ServerConfig): McpServer;
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoinVello MCP server: tools, resources and prompts.
|
|
3
|
+
*
|
|
4
|
+
* Tools talk to https://api.coinvello.com/v1 (or COINVELLO_API_BASE, e.g. the local reference
|
|
5
|
+
* server at http://localhost:4242/v1) with the key from COINVELLO_API_KEY. Live keys (cv_live_)
|
|
6
|
+
* are refused unless COINVELLO_ALLOW_LIVE=1 so an agent cannot accidentally touch mainnet money.
|
|
7
|
+
*/
|
|
8
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
9
|
+
import { readFile } from "node:fs/promises";
|
|
10
|
+
import { dirname, resolve } from "node:path";
|
|
11
|
+
import { fileURLToPath } from "node:url";
|
|
12
|
+
import { z } from "zod";
|
|
13
|
+
import { CoinVelloApiError, CoinVelloClient } from "./client.js";
|
|
14
|
+
import { verifyCoinVelloSignature } from "./verify.js";
|
|
15
|
+
export const SERVER_NAME = "coinvello";
|
|
16
|
+
export const SERVER_VERSION = "0.1.0";
|
|
17
|
+
export function configFromEnv(env = process.env) {
|
|
18
|
+
return {
|
|
19
|
+
apiKey: env.COINVELLO_API_KEY,
|
|
20
|
+
baseUrl: env.COINVELLO_API_BASE,
|
|
21
|
+
allowLive: env.COINVELLO_ALLOW_LIVE === "1" || env.COINVELLO_ALLOW_LIVE === "true",
|
|
22
|
+
apiVersion: env.COINVELLO_API_VERSION,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
/** Throws a clear error when the key is missing or is a live key without the explicit opt-in. */
|
|
26
|
+
export function assertKeyAllowed(cfg) {
|
|
27
|
+
if (!cfg.apiKey) {
|
|
28
|
+
throw new Error("COINVELLO_API_KEY is not set. Create a test key (cv_test_...) at https://coinvello.com/app/settings.php (Settings -> API keys), " +
|
|
29
|
+
"or run the local mock (api/reference-server, npm start) and use any cv_test_ key with COINVELLO_API_BASE=http://localhost:4242/v1.");
|
|
30
|
+
}
|
|
31
|
+
if (/^cv_live_/.test(cfg.apiKey) && !cfg.allowLive) {
|
|
32
|
+
throw new Error("Refusing to start with a LIVE key (cv_live_...). This server creates real invoices and credit purchases. " +
|
|
33
|
+
"Use a cv_test_ key, or set COINVELLO_ALLOW_LIVE=1 if you really want an AI agent operating on mainnet.");
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
// ---------------------------------------------------------------------------------------------
|
|
37
|
+
// Shared zod fragments (mirroring openapi.yaml)
|
|
38
|
+
// ---------------------------------------------------------------------------------------------
|
|
39
|
+
const Decimal = z.string().regex(/^-?\d+(\.\d+)?$/, "decimal string such as \"49.99\"");
|
|
40
|
+
const AssetId = z.string().regex(/^[a-z0-9]+:[a-z0-9]+$/, "asset id such as btc:bitcoin or usdc:polygon");
|
|
41
|
+
const Chain = z.enum(["bitcoin", "ethereum", "base", "arbitrum", "optimism", "polygon", "bnb", "avalanche", "robinhood", "solana", "tron"]);
|
|
42
|
+
const Metadata = z.record(z.string().max(500)).optional().describe("Up to 50 string key/value pairs returned on the object and in webhooks.");
|
|
43
|
+
const InvoiceStatus = z.enum(["new", "pending", "confirming", "paid", "underpaid", "overpaid", "expired", "cancelled", "refund_requested"]);
|
|
44
|
+
const PaymentStatus = z.enum(["detected", "confirming", "confirmed", "failed"]);
|
|
45
|
+
const Customer = z.object({ email: z.string().email().optional(), name: z.string().max(200).optional(), reference: z.string().max(128).optional() }).optional();
|
|
46
|
+
const RecordType = z.enum(["payment_received", "payment_reversed", "refund_sent", "fee_prepaid", "fee_onchain", "credit_purchase", "credit_adjustment", "conversion", "offramp_payout"]);
|
|
47
|
+
const ExportDataset = z.enum(["records", "invoices", "payments", "refunds", "sweeps", "credit_ledger", "credit_purchases", "conversions", "offramp_payouts", "all"]);
|
|
48
|
+
const ExportFormat = z.enum(["csv", "xlsx", "json"]);
|
|
49
|
+
const ExportPreset = z.enum(["generic", "journal", "quickbooks", "xero", "koinly", "cointracker", "coinledger"]);
|
|
50
|
+
const ExportStatus = z.enum(["queued", "processing", "ready", "failed", "expired"]);
|
|
51
|
+
const FiatCurrency = z.string().regex(/^[A-Z]{3}$/, "ISO 4217 code such as USD or EUR");
|
|
52
|
+
const IncludeSimulated = z.boolean().optional().describe("Test mode only: include rows created by simulate_test_payment, which the sandbox hides by default. Ignored with a live key.");
|
|
53
|
+
const Paging = {
|
|
54
|
+
limit: z.number().int().min(1).max(100).optional().describe("Page size (default 20)."),
|
|
55
|
+
cursor: z.string().optional().describe("next_cursor from the previous page."),
|
|
56
|
+
};
|
|
57
|
+
function json(data) {
|
|
58
|
+
return { content: [{ type: "text", text: JSON.stringify(data, null, 2) }], structuredContent: isObject(data) ? data : undefined };
|
|
59
|
+
}
|
|
60
|
+
function isObject(v) {
|
|
61
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
62
|
+
}
|
|
63
|
+
function toolError(e) {
|
|
64
|
+
if (e instanceof CoinVelloApiError) {
|
|
65
|
+
return {
|
|
66
|
+
isError: true,
|
|
67
|
+
content: [{ type: "text", text: JSON.stringify({ http_status: e.status, error: e.error, hint: hintFor(e) }, null, 2) }],
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
const msg = e instanceof Error ? e.message : String(e);
|
|
71
|
+
return { isError: true, content: [{ type: "text", text: JSON.stringify({ error: { type: "client_error", message: msg } }) }] };
|
|
72
|
+
}
|
|
73
|
+
function hintFor(e) {
|
|
74
|
+
switch (e.error.code) {
|
|
75
|
+
case "insufficient_credits":
|
|
76
|
+
return "The available credits cannot cover this invoice's estimated fee (details: available, required, bundles_url); the balance never goes below zero. Buy credits: list_credit_bundles -> create_credit_purchase -> pay the returned payment option (or open checkout_url). Or switch the account to pay as you go (billing_plan; auto_switch_to_pay_as_you_go, on by default, does it automatically where pay as you go is available). Test mode never runs out of credits.";
|
|
77
|
+
case "asset_not_enabled":
|
|
78
|
+
case "xpub_required":
|
|
79
|
+
return "Bitcoin needs an extended public key: call create_wallet with type=xpub and the xpub/zpub/vpub, not a single address.";
|
|
80
|
+
case "address_invalid":
|
|
81
|
+
return "The address failed validation (format, checksum, network, zero/burn address or a token contract). Copy it again from the wallet; see error.param.";
|
|
82
|
+
case "export_not_ready":
|
|
83
|
+
return "The file is still being built: call get_export until status is ready, then use download_url.";
|
|
84
|
+
case "export_expired":
|
|
85
|
+
return "Export files are kept 7 days. Call create_export again with the same parameters.";
|
|
86
|
+
case "test_mode_only":
|
|
87
|
+
return "This endpoint only works with a cv_test_ key.";
|
|
88
|
+
case "api_key_invalid":
|
|
89
|
+
case "api_key_missing":
|
|
90
|
+
return "Check COINVELLO_API_KEY. Keys look like cv_test_... or cv_live_...";
|
|
91
|
+
case "resource_missing":
|
|
92
|
+
return e.status === 404 && /\/wallets/.test(e.error.message ?? "")
|
|
93
|
+
? "The local reference server does not implement wallet CRUD; it pre-registers one mock wallet per chain."
|
|
94
|
+
: "No object with that id in this mode (test objects are invisible to live keys and vice versa).";
|
|
95
|
+
default:
|
|
96
|
+
return undefined;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
// ---------------------------------------------------------------------------------------------
|
|
100
|
+
// Resource documents
|
|
101
|
+
// ---------------------------------------------------------------------------------------------
|
|
102
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
103
|
+
async function loadDoc(localCandidates, remoteUrl) {
|
|
104
|
+
for (const p of localCandidates) {
|
|
105
|
+
try {
|
|
106
|
+
return await readFile(p, "utf8");
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
/* try next */
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const res = await fetch(remoteUrl);
|
|
113
|
+
if (!res.ok)
|
|
114
|
+
throw new Error(`Could not load ${remoteUrl}: ${res.status}`);
|
|
115
|
+
return res.text();
|
|
116
|
+
}
|
|
117
|
+
const DOCS = {
|
|
118
|
+
llmsFull: {
|
|
119
|
+
local: [resolve(here, "docs", "llms-full.txt"), resolve(here, "..", "..", "llms-full.txt")],
|
|
120
|
+
remote: "https://coinvello.com/llms-full.txt",
|
|
121
|
+
},
|
|
122
|
+
llms: {
|
|
123
|
+
local: [resolve(here, "docs", "llms.txt"), resolve(here, "..", "..", "llms.txt")],
|
|
124
|
+
remote: "https://coinvello.com/llms.txt",
|
|
125
|
+
},
|
|
126
|
+
openapi: {
|
|
127
|
+
local: [resolve(here, "docs", "openapi.yaml"), resolve(here, "..", "..", "..", "openapi.yaml")],
|
|
128
|
+
remote: "https://coinvello.com/.well-known/openapi.yaml",
|
|
129
|
+
},
|
|
130
|
+
};
|
|
131
|
+
// ---------------------------------------------------------------------------------------------
|
|
132
|
+
// Prompts
|
|
133
|
+
// ---------------------------------------------------------------------------------------------
|
|
134
|
+
const FRAMEWORKS = [
|
|
135
|
+
"nextjs", "express", "fastapi", "flask", "django", "laravel", "rails", "sinatra", "go", "woocommerce", "shopify", "generic",
|
|
136
|
+
];
|
|
137
|
+
function integrationPrompt(framework, extras) {
|
|
138
|
+
const currency = extras.currency ?? "USD";
|
|
139
|
+
const assets = extras.assets ?? "btc:bitcoin, eth:ethereum, usdc:polygon, usdt:tron";
|
|
140
|
+
return [
|
|
141
|
+
`Integrate CoinVello (non-custodial crypto payments, https://api.coinvello.com/v1) into this ${framework} project.`,
|
|
142
|
+
"",
|
|
143
|
+
"Read the resource coinvello://docs/llms-full.txt first; it contains the complete API contract and reference code.",
|
|
144
|
+
"",
|
|
145
|
+
"Requirements:",
|
|
146
|
+
`1. Server-side only: read the API key from the COINVELLO_API_KEY environment variable (cv_test_ in development). Never ship it to the browser.`,
|
|
147
|
+
`2. Add a "start payment" route that creates a checkout session with POST /checkout-sessions: amount as a decimal string, currency ${currency}, accepted_assets [${assets}], order_id, success_url, cancel_url, metadata.order_id, and an Idempotency-Key derived from the order id. Redirect the customer (303) to the returned url.`,
|
|
148
|
+
"3. Add a webhook route at /webhooks/coinvello that reads the RAW request body, verifies the CoinVello-Signature header (t=<unix>,v1=<hex HMAC-SHA256 of \"<t>.<raw body>\" keyed with COINVELLO_WEBHOOK_SECRET; reject |now - t| > 300 s; constant-time compare; any v1 may match), dedupes on event.id, and fulfils the order ONLY on invoice.paid. Flag invoice.underpaid / overpaid / expired. Respond 2xx within 10 seconds.",
|
|
149
|
+
"4. Store checkout session id and invoice id on the order so GET /invoices/{id} can be used for reconciliation.",
|
|
150
|
+
"5. Keep amounts as strings everywhere; never convert to floats.",
|
|
151
|
+
"6. Add the two environment variables to the project's example env file and document the setup in a few lines (create the webhook endpoint with POST /webhooks or the create_webhook tool, store the whsec_ secret).",
|
|
152
|
+
"7. Verify end to end: with a cv_test_ key (or the local mock at http://localhost:4242/v1), create a session with create_checkout_session, run simulate_test_payment on its invoice_id with enough confirmations, and confirm the webhook handler marked the order paid.",
|
|
153
|
+
"",
|
|
154
|
+
"Use the framework's idioms (routing, env config, raw-body access). If a CoinVello cookbook recipe exists for this framework in api/ai/cookbook, follow its structure.",
|
|
155
|
+
extras.language ? `Write the code in ${extras.language}.` : "",
|
|
156
|
+
]
|
|
157
|
+
.filter(Boolean)
|
|
158
|
+
.join("\n");
|
|
159
|
+
}
|
|
160
|
+
// ---------------------------------------------------------------------------------------------
|
|
161
|
+
// Server factory
|
|
162
|
+
// ---------------------------------------------------------------------------------------------
|
|
163
|
+
export function createServer(cfg = configFromEnv()) {
|
|
164
|
+
const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION }, {
|
|
165
|
+
instructions: [
|
|
166
|
+
"CoinVello is a non-custodial crypto payment processor: payments go straight to the merchant's own wallet, no KYC/KYB, fees are prepaid credits bought in crypto, 11 networks.",
|
|
167
|
+
"Typical flow: create_checkout_session -> redirect the customer to `url` -> fulfil on the `invoice.paid` webhook (verify with verify_webhook_signature) -> reconcile with get_invoice.",
|
|
168
|
+
"Amounts are decimal strings. Asset ids are `<asset>:<chain>` like btc:bitcoin, usdc:polygon, usdt:tron.",
|
|
169
|
+
"Bookkeeping and tax: list_records is the book of record (every payment, fee and credit purchase valued when it happened), get_records_summary gives period totals, create_export builds CSV/Excel/JSON files (with QuickBooks, Xero, Koinly, CoinTracker and CoinLedger presets). With a test key pass include_simulated=true to see simulated payments.",
|
|
170
|
+
"Read coinvello://docs/llms-full.txt for the complete contract before writing integration code.",
|
|
171
|
+
cfg.apiKey ? (/^cv_live_/.test(cfg.apiKey) ? "WARNING: a LIVE key is configured; tools create real objects." : "A test key is configured; nothing here touches mainnet.") : "No API key configured; tools will fail until COINVELLO_API_KEY is set.",
|
|
172
|
+
].join(" "),
|
|
173
|
+
});
|
|
174
|
+
let client = null;
|
|
175
|
+
const api = () => {
|
|
176
|
+
if (!client) {
|
|
177
|
+
assertKeyAllowed(cfg);
|
|
178
|
+
client = new CoinVelloClient({ apiKey: cfg.apiKey, baseUrl: cfg.baseUrl, apiVersion: cfg.apiVersion });
|
|
179
|
+
}
|
|
180
|
+
return client;
|
|
181
|
+
};
|
|
182
|
+
const run = async (fn) => {
|
|
183
|
+
try {
|
|
184
|
+
return json(await fn());
|
|
185
|
+
}
|
|
186
|
+
catch (e) {
|
|
187
|
+
return toolError(e);
|
|
188
|
+
}
|
|
189
|
+
};
|
|
190
|
+
// ---------------------------------------------------------------- tools: checkout & invoices
|
|
191
|
+
server.registerTool("create_checkout_session", {
|
|
192
|
+
title: "Create a hosted checkout session",
|
|
193
|
+
description: "Create a CoinVello hosted checkout session (an invoice plus a payment page at pay.coinvello.com). Redirect the customer to the returned `url`. " +
|
|
194
|
+
"Amounts are decimal strings. `currency` is an ISO code (USD, EUR...) or an asset id to price in crypto. Fulfil orders from the invoice.paid webhook, never from the redirect.",
|
|
195
|
+
inputSchema: {
|
|
196
|
+
amount: Decimal.describe("Total to charge, e.g. \"49.99\"."),
|
|
197
|
+
currency: z.string().describe("ISO 4217 code such as USD/EUR/GBP, or an asset id such as btc:bitcoin."),
|
|
198
|
+
success_url: z.string().url().describe("Where the hosted page sends the customer after payment."),
|
|
199
|
+
cancel_url: z.string().url().optional(),
|
|
200
|
+
accepted_assets: z.array(AssetId).optional().describe("Assets the customer may pay with; defaults to all assets with an enabled wallet."),
|
|
201
|
+
order_id: z.string().max(128).optional().describe("Your order reference; indexed and searchable."),
|
|
202
|
+
description: z.string().max(500).optional(),
|
|
203
|
+
customer: Customer,
|
|
204
|
+
line_items: z
|
|
205
|
+
.array(z.object({ name: z.string().max(200), quantity: z.number().int().min(1), unit_amount: Decimal, description: z.string().max(500).optional(), image_url: z.string().url().optional() }))
|
|
206
|
+
.optional(),
|
|
207
|
+
redirect_on: z.enum(["confirming", "paid"]).optional().describe("When the hosted page redirects to success_url (default confirming)."),
|
|
208
|
+
expires_in: z.number().int().min(300).max(86400).optional().describe("Seconds until expiry (default 1800)."),
|
|
209
|
+
locale: z.string().optional(),
|
|
210
|
+
branding: z.object({ theme: z.enum(["light", "dark", "auto"]).optional(), logo_url: z.string().url().optional(), primary_color: z.string().regex(/^#[0-9a-fA-F]{6}$/).optional(), merchant_name: z.string().max(100).optional() }).optional(),
|
|
211
|
+
collect_email: z.boolean().optional(),
|
|
212
|
+
tax: z
|
|
213
|
+
.object({ amount: Decimal, rate: Decimal.nullable().optional(), label: z.string().max(60).nullable().optional(), jurisdiction: z.string().max(20).nullable().optional() })
|
|
214
|
+
.optional()
|
|
215
|
+
.describe("The tax portion of the sale as you computed it, in the invoice currency and included in `amount` (e.g. {\"amount\":\"7.98\",\"rate\":\"0.19\",\"label\":\"VAT 19%\",\"jurisdiction\":\"DE\"}); copied to the records and exports. jurisdiction is a code you choose, never anything about the payer."),
|
|
216
|
+
metadata: Metadata,
|
|
217
|
+
idempotency_key: z.string().max(255).optional().describe("Stable key per order so retries do not create duplicate sessions, e.g. order-123-checkout."),
|
|
218
|
+
},
|
|
219
|
+
}, async ({ idempotency_key, ...body }) => run(() => api().post("/checkout-sessions", body, idempotency_key)));
|
|
220
|
+
server.registerTool("get_invoice", {
|
|
221
|
+
title: "Get an invoice",
|
|
222
|
+
description: "Retrieve an invoice (inv_...) with its status, payment_options (address, amount, payment_uri, qr_payload) and paid summary. Use for polling or reconciliation. Accepts a checkout session id (cs_...) too and returns the session with the invoice expanded.",
|
|
223
|
+
inputSchema: { id: z.string().describe("inv_... or cs_... id") },
|
|
224
|
+
}, async ({ id }) => run(() => (id.startsWith("cs_") ? api().get(`/checkout-sessions/${encodeURIComponent(id)}`, { expand: "invoice" }) : api().get(`/invoices/${encodeURIComponent(id)}`))));
|
|
225
|
+
server.registerTool("list_invoices", {
|
|
226
|
+
title: "List invoices",
|
|
227
|
+
description: "List invoices, newest first, filterable by status, order_id or customer_email. Returns { object: 'list', data, has_more, next_cursor }.",
|
|
228
|
+
inputSchema: {
|
|
229
|
+
...Paging,
|
|
230
|
+
status: InvoiceStatus.optional(),
|
|
231
|
+
order_id: z.string().optional(),
|
|
232
|
+
customer_email: z.string().optional(),
|
|
233
|
+
created_gte: z.string().optional().describe("RFC 3339 timestamp"),
|
|
234
|
+
created_lte: z.string().optional().describe("RFC 3339 timestamp"),
|
|
235
|
+
},
|
|
236
|
+
}, async (q) => run(() => api().get("/invoices", { ...q, "created[gte]": q.created_gte, "created[lte]": q.created_lte, created_gte: undefined, created_lte: undefined })));
|
|
237
|
+
server.registerTool("list_payments", {
|
|
238
|
+
title: "List payments",
|
|
239
|
+
description: "List on-chain payments (pay_...) with tx_hash, confirmations, amount and status (detected, confirming, confirmed, failed). Filter by invoice_id, status, chain or tx_hash.",
|
|
240
|
+
inputSchema: { ...Paging, invoice_id: z.string().optional(), status: PaymentStatus.optional(), chain: Chain.optional(), tx_hash: z.string().optional() },
|
|
241
|
+
}, async (q) => run(() => api().get("/payments", q)));
|
|
242
|
+
// ---------------------------------------------------------------- tools: wallets
|
|
243
|
+
server.registerTool("create_wallet", {
|
|
244
|
+
title: "Register a merchant wallet",
|
|
245
|
+
description: "Register a receiving wallet the merchant controls. type=xpub for bitcoin (CoinVello derives a fresh address per invoice from the extended PUBLIC key); type=address for ethereum, base, arbitrum, optimism, polygon, bnb, avalanche, robinhood, solana, tron. " +
|
|
246
|
+
"Never pass a private key or seed phrase. The wallet is usable at once in live and test mode; addresses are validated strictly (format, checksum, network, no token contracts). For xpubs, show the returned first_address so the merchant can compare it with their wallet's first receive address. Signed-message verification (POST /wallets/{id}/verification then /verify) is optional and never required.",
|
|
247
|
+
inputSchema: {
|
|
248
|
+
type: z.enum(["xpub", "address"]),
|
|
249
|
+
chain: Chain,
|
|
250
|
+
label: z.string().max(100),
|
|
251
|
+
xpub: z.string().optional().describe("xpub/ypub/zpub (BTC), tpub/upub/vpub (testnets) or an output descriptor. Required when type=xpub."),
|
|
252
|
+
derivation_path: z.string().regex(/^m(\/\d+'?)*$/).optional().describe("Account path such as m/84'/0'/0'. Inferred from the prefix when omitted."),
|
|
253
|
+
address_type: z.enum(["p2pkh", "p2sh-p2wpkh", "p2wpkh", "p2tr"]).optional(),
|
|
254
|
+
start_index: z.number().int().min(0).optional(),
|
|
255
|
+
address: z.string().optional().describe("Checksummed EVM address, Solana pubkey or Tron address. Required when type=address."),
|
|
256
|
+
assets: z.array(AssetId).optional().describe("Assets accepted at this address, e.g. [\"usdc:polygon\",\"usdt:polygon\"]. Defaults to the native asset. Each must be listed by list_assets for the key's mode."),
|
|
257
|
+
enabled: z.boolean().optional(),
|
|
258
|
+
metadata: Metadata,
|
|
259
|
+
},
|
|
260
|
+
}, async (body) => {
|
|
261
|
+
if (body.type === "xpub" && body.xpub && /^(xprv|yprv|zprv|tprv|uprv|vprv|Ltpv)/.test(body.xpub)) {
|
|
262
|
+
return toolError(new Error("That looks like an extended PRIVATE key (xprv). Refusing to send it. Export the extended public key (xpub/zpub/vpub) instead, and rotate this key."));
|
|
263
|
+
}
|
|
264
|
+
return run(() => api().post("/wallets", body));
|
|
265
|
+
});
|
|
266
|
+
server.registerTool("list_wallets", {
|
|
267
|
+
title: "List wallets",
|
|
268
|
+
description: "List registered wallets with chain, type, status (active/verified/archived) and accepted assets. Use it to see which assets can be offered on an invoice.",
|
|
269
|
+
inputSchema: { ...Paging, chain: Chain.optional(), status: z.enum(["active", "verified", "archived", "unverified"]).optional() },
|
|
270
|
+
}, async (q) => run(() => api().get("/wallets", q)));
|
|
271
|
+
// ---------------------------------------------------------------- tools: webhooks
|
|
272
|
+
server.registerTool("create_webhook", {
|
|
273
|
+
title: "Create a webhook endpoint",
|
|
274
|
+
description: "Register a webhook endpoint. The response contains `secret` (whsec_...) ONCE: store it as COINVELLO_WEBHOOK_SECRET. Live endpoints must be HTTPS; test endpoints may be http://localhost. Use events [\"*\"] for everything or a list such as [\"invoice.paid\",\"invoice.expired\"].",
|
|
275
|
+
inputSchema: {
|
|
276
|
+
url: z.string().url(),
|
|
277
|
+
events: z.array(z.string()).min(1).describe("Event types or [\"*\"]. Common: invoice.paid, invoice.confirming, invoice.underpaid, invoice.overpaid, invoice.expired, payment.detected, checkout_session.completed."),
|
|
278
|
+
description: z.string().max(200).optional(),
|
|
279
|
+
enabled: z.boolean().optional(),
|
|
280
|
+
metadata: Metadata,
|
|
281
|
+
},
|
|
282
|
+
}, async (body) => run(() => api().post("/webhooks", body)));
|
|
283
|
+
server.registerTool("verify_webhook_signature", {
|
|
284
|
+
title: "Verify a CoinVello-Signature header",
|
|
285
|
+
description: "Verify a webhook delivery locally (no API call). Pass the exact raw request body, the CoinVello-Signature header (t=...,v1=...) and the endpoint secret (whsec_...). " +
|
|
286
|
+
"Implements the spec: HMAC-SHA256 over \"<t>.<raw body>\", 300 s tolerance, constant-time compare against any v1. Returns valid=true/false with the reason and the parsed event. Set ignore_timestamp=true when checking an old captured delivery.",
|
|
287
|
+
inputSchema: {
|
|
288
|
+
raw_body: z.string().describe("Raw body bytes exactly as received (no re-serialisation)."),
|
|
289
|
+
signature_header: z.string().describe("Value of the CoinVello-Signature header."),
|
|
290
|
+
secret: z.string().describe("Endpoint secret whsec_..."),
|
|
291
|
+
tolerance_seconds: z.number().int().min(0).optional(),
|
|
292
|
+
ignore_timestamp: z.boolean().optional().describe("Skip the replay-window check (only for inspecting historical deliveries)."),
|
|
293
|
+
},
|
|
294
|
+
}, async ({ raw_body, signature_header, secret, tolerance_seconds, ignore_timestamp }) => {
|
|
295
|
+
const result = verifyCoinVelloSignature(raw_body, signature_header, secret, {
|
|
296
|
+
toleranceSec: ignore_timestamp ? Number.MAX_SAFE_INTEGER : tolerance_seconds,
|
|
297
|
+
});
|
|
298
|
+
return { ...json(result), isError: false };
|
|
299
|
+
});
|
|
300
|
+
// ---------------------------------------------------------------- tools: credits
|
|
301
|
+
server.registerTool("get_credits_balance", {
|
|
302
|
+
title: "Get processing-credit balance",
|
|
303
|
+
description: "Return the merchant's prepaid processing-credit balance: balance (= available + reserved, never negative), available (free to spend), reserved (estimated fees of open invoices paid with credits), low_balance_threshold, estimated_payments_remaining, auto_topup. There are no free live credits. 1 credit = $0.01 nominal; a confirmed payment consumes about 30 bps of its fiat value (floor 2, cap 2000).",
|
|
304
|
+
inputSchema: {},
|
|
305
|
+
}, async () => run(() => api().get("/credits/balance")));
|
|
306
|
+
server.registerTool("list_credit_bundles", {
|
|
307
|
+
title: "List credit bundles",
|
|
308
|
+
description: "List purchasable credit bundles with USD price, price_per_credit and indicative crypto_prices per asset. Bigger bundles cost less per credit (effective rate ~0.30% down to <0.10%).",
|
|
309
|
+
inputSchema: {},
|
|
310
|
+
}, async () => run(() => api().get("/credits/bundles")));
|
|
311
|
+
server.registerTool("create_credit_purchase", {
|
|
312
|
+
title: "Buy credits (creates a crypto invoice)",
|
|
313
|
+
description: "Create a crypto credit purchase (cpu_...). Returns payment.payment_options with the address/amount to pay (CoinVello's operator wallet) and a hosted checkout_url. Credits are added when the payment confirms. Card purchases and automatic top-up are set up by the merchant in the dashboard, not through this tool. In test mode credits are free, so this is mainly for exercising the flow (pay it with simulate_test_payment).",
|
|
314
|
+
inputSchema: {
|
|
315
|
+
bundle_id: z.string().describe("From list_credit_bundles, e.g. bnd_growth_15000."),
|
|
316
|
+
pay_asset: z.string().optional().describe("Asset symbol to pay with, lowercase, e.g. usdt. Requires pay_chain. Omit for every option."),
|
|
317
|
+
pay_chain: Chain.optional(),
|
|
318
|
+
expires_in: z.number().int().min(600).max(86400).optional(),
|
|
319
|
+
metadata: Metadata,
|
|
320
|
+
idempotency_key: z.string().max(255).optional(),
|
|
321
|
+
},
|
|
322
|
+
}, async ({ idempotency_key, ...body }) => run(() => api().post("/credits/purchases", body, idempotency_key)));
|
|
323
|
+
// ---------------------------------------------------------------- tools: records & exports
|
|
324
|
+
server.registerTool("list_records", {
|
|
325
|
+
title: "List accounting records",
|
|
326
|
+
description: "List the account's book of record, newest first: one immutable row per movement of value (payment_received, fee_prepaid, credit_purchase, refund_sent, fee_onchain, conversion, offramp_payout...) valued when it happened. " +
|
|
327
|
+
"Each record has `value` (market value at the block time in the reporting currency, rate and source included), `value_usd`, `contract_value` (what the customer owed at the invoice's locked rate), `tax`, the on-chain proof (tx_hash, block_height, addresses, explorer_url) and an invoice snapshot. " +
|
|
328
|
+
"`currency` re-values from value_usd at the historical rate. With a test key, rows created by simulate_test_payment appear only with include_simulated=true. Returns { object: 'list', data, has_more, next_cursor }.",
|
|
329
|
+
inputSchema: {
|
|
330
|
+
...Paging,
|
|
331
|
+
type: RecordType.optional(),
|
|
332
|
+
asset: AssetId.optional().describe("Records whose received, sent or fee leg is this asset."),
|
|
333
|
+
chain: Chain.optional(),
|
|
334
|
+
invoice_id: z.string().optional(),
|
|
335
|
+
order_id: z.string().optional(),
|
|
336
|
+
tx_hash: z.string().optional(),
|
|
337
|
+
occurred_gte: z.string().optional().describe("RFC 3339 timestamp; block time at or after."),
|
|
338
|
+
occurred_lte: z.string().optional().describe("RFC 3339 timestamp; block time at or before."),
|
|
339
|
+
currency: FiatCurrency.optional().describe("Re-value `value` into this currency (default: the account's reporting currency)."),
|
|
340
|
+
include_simulated: IncludeSimulated,
|
|
341
|
+
},
|
|
342
|
+
}, async (q) => run(() => api().get("/records", q)));
|
|
343
|
+
server.registerTool("get_records_summary", {
|
|
344
|
+
title: "Get totals for a period",
|
|
345
|
+
description: "Sales (invoiced at the locked rates), received_market_value (what the coins were worth when they landed), valuation_difference, tax_collected, refunds, fees_prepaid and credits_consumed, fees_onchain, network_fees, credit_purchases and net_received, with payment counts, over occurred_at in the given timezone and currency. " +
|
|
346
|
+
"period_start is inclusive and period_end exclusive (a date such as 2026-01-01, or a date-time). group_by returns the same totals per month, asset, chain, type or address in `groups`. With a test key, simulated rows count only with include_simulated=true.",
|
|
347
|
+
inputSchema: {
|
|
348
|
+
period_start: z.string().describe("Inclusive, read in `timezone`: a date (2026-01-01) or a date-time."),
|
|
349
|
+
period_end: z.string().describe("Exclusive."),
|
|
350
|
+
currency: FiatCurrency.optional(),
|
|
351
|
+
timezone: z.string().optional().describe("IANA zone used to bucket occurred_at, e.g. Europe/Berlin. Default: the account's records timezone."),
|
|
352
|
+
group_by: z.enum(["month", "asset", "chain", "type", "address"]).optional(),
|
|
353
|
+
include_simulated: IncludeSimulated,
|
|
354
|
+
},
|
|
355
|
+
}, async (q) => run(() => api().get("/records/summary", q)));
|
|
356
|
+
server.registerTool("create_export", {
|
|
357
|
+
title: "Export records as CSV, Excel or JSON",
|
|
358
|
+
description: "Create an export of the records (default), another dataset, or `all` (the year-end package) for a period, or for the entire history when period is null or omitted. " +
|
|
359
|
+
"Returns the export object: small exports are already `ready` with `file` (name, content_type, bytes, sha256) and a signed `download_url` valid until `download_expires_at` (files are kept 7 days); " +
|
|
360
|
+
"while `queued` or `processing` call get_export. Vendor presets (quickbooks, xero, koinly, cointracker, coinledger) and journal need dataset=records and format=csv (otherwise 422). " +
|
|
361
|
+
"Verify the downloaded file against file.sha256. With a test key pass include_simulated=true to include simulated payments.",
|
|
362
|
+
inputSchema: {
|
|
363
|
+
format: ExportFormat,
|
|
364
|
+
dataset: ExportDataset.optional().describe("Default records."),
|
|
365
|
+
preset: ExportPreset.optional().describe("Column layout for the records dataset (default generic)."),
|
|
366
|
+
period: z
|
|
367
|
+
.object({ start: z.string().describe("Inclusive, e.g. 2026-07-01."), end: z.string().describe("Exclusive, e.g. 2026-10-01.") })
|
|
368
|
+
.nullable()
|
|
369
|
+
.optional()
|
|
370
|
+
.describe("Read in `timezone`. Null or omitted exports the entire history."),
|
|
371
|
+
timezone: z.string().optional().describe("IANA zone, e.g. America/New_York. Default: the account's records timezone."),
|
|
372
|
+
currency: FiatCurrency.optional().describe("Reporting currency of the value columns."),
|
|
373
|
+
include_simulated: IncludeSimulated,
|
|
374
|
+
metadata: Metadata,
|
|
375
|
+
idempotency_key: z.string().max(255).optional().describe("Stable key so a retry does not start a second export, e.g. records-2026-q3."),
|
|
376
|
+
},
|
|
377
|
+
}, async ({ idempotency_key, ...body }) => run(() => api().post("/exports", body, idempotency_key)));
|
|
378
|
+
server.registerTool("get_export", {
|
|
379
|
+
title: "Get an export",
|
|
380
|
+
description: "Retrieve an export (exp_...): status (queued, processing, ready, failed, expired), rows, file { name, content_type, bytes, sha256 }, download_url and download_expires_at, failure_reason. Poll after create_export until ready.",
|
|
381
|
+
inputSchema: { id: z.string().describe("exp_... id from create_export") },
|
|
382
|
+
}, async ({ id }) => run(() => api().get(`/exports/${encodeURIComponent(id)}`)));
|
|
383
|
+
// ---------------------------------------------------------------- tools: rates & assets
|
|
384
|
+
server.registerTool("get_rates", {
|
|
385
|
+
title: "Get indicative exchange rates",
|
|
386
|
+
description: "Mid-market rates for supported assets against a fiat base (default USD). Indicative only; invoices lock their own rate at creation.",
|
|
387
|
+
inputSchema: {
|
|
388
|
+
base: z.string().optional().describe("ISO 4217 code or asset id, default USD."),
|
|
389
|
+
assets: z.array(AssetId).optional().describe("Restrict to these asset ids."),
|
|
390
|
+
},
|
|
391
|
+
}, async ({ base, assets }) => run(() => api().get("/rates", { base, assets: assets?.join(",") })));
|
|
392
|
+
server.registerTool("list_assets", {
|
|
393
|
+
title: "List supported assets",
|
|
394
|
+
description: "Every asset CoinVello accepts in the API key's mode: id (btc:bitcoin, usdc:polygon, eurc:base...), symbol, chain, kind (native/token), contract_address, decimals, required_confirmations, min_amount, testnet name and the wallet_type (xpub or address) needed to accept it. Tokens without a testnet contract (DAI, usdc:bnb, usdt on base/arbitrum/optimism/avalanche/solana, and the Bitcoin tokens wbtc/cbbtc/btcb) are live-only, so a test key does not list them.",
|
|
395
|
+
inputSchema: { chain: Chain.optional().describe("Filter by chain.") },
|
|
396
|
+
}, async ({ chain }) => run(async () => {
|
|
397
|
+
const list = await api().get("/assets");
|
|
398
|
+
if (chain && Array.isArray(list.data))
|
|
399
|
+
return { ...list, data: list.data.filter((a) => a.chain === chain) };
|
|
400
|
+
return list;
|
|
401
|
+
}));
|
|
402
|
+
// ---------------------------------------------------------------- tools: testing
|
|
403
|
+
server.registerTool("simulate_test_payment", {
|
|
404
|
+
title: "Simulate a payment (test mode)",
|
|
405
|
+
description: "Create a synthetic on-chain payment for an invoice (inv_) or credit purchase (cpu_) and run it through the real state machine and webhook pipeline. Test keys only. " +
|
|
406
|
+
"confirmations=0 -> payment.detected / invoice.pending; confirmations >= required -> invoice.paid. Use a smaller/larger amount to simulate underpaid/overpaid. Reuse tx_hash to advance the same payment.",
|
|
407
|
+
inputSchema: {
|
|
408
|
+
invoice_id: z.string().describe("inv_... or cpu_..."),
|
|
409
|
+
asset: AssetId.optional().describe("Which payment option to pay; defaults to the first accepted asset."),
|
|
410
|
+
amount: Decimal.optional().describe("Amount in the asset; defaults to the exact payment_options[].amount."),
|
|
411
|
+
confirmations: z.number().int().min(0).optional().describe("Default 0 (detected only)."),
|
|
412
|
+
tx_hash: z.string().optional(),
|
|
413
|
+
from_address: z.string().optional(),
|
|
414
|
+
delay_seconds: z.number().int().min(0).max(300).optional(),
|
|
415
|
+
},
|
|
416
|
+
}, async (body) => run(() => api().post("/test/simulate_payment", body)));
|
|
417
|
+
// ---------------------------------------------------------------- resources
|
|
418
|
+
server.registerResource("llms-full", "coinvello://docs/llms-full.txt", { title: "CoinVello complete integration guide", description: "Single-document API guide: auth, checkout sessions, redirect, webhook verification, polling, credits, errors, with curl/Node/Python/PHP examples.", mimeType: "text/plain" }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: await loadDoc(DOCS.llmsFull.local, DOCS.llmsFull.remote) }] }));
|
|
419
|
+
server.registerResource("llms", "coinvello://docs/llms.txt", { title: "CoinVello llms.txt index", description: "Short, link-rich summary of the CoinVello API.", mimeType: "text/plain" }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "text/plain", text: await loadDoc(DOCS.llms.local, DOCS.llms.remote) }] }));
|
|
420
|
+
server.registerResource("openapi", "coinvello://openapi.yaml", { title: "CoinVello OpenAPI 3.1 specification", description: "Every endpoint, schema, example and webhook payload of https://api.coinvello.com/v1.", mimeType: "application/yaml" }, async (uri) => ({ contents: [{ uri: uri.href, mimeType: "application/yaml", text: await loadDoc(DOCS.openapi.local, DOCS.openapi.remote) }] }));
|
|
421
|
+
// ---------------------------------------------------------------- prompts
|
|
422
|
+
for (const fw of FRAMEWORKS) {
|
|
423
|
+
server.registerPrompt(`integrate-coinvello-into-${fw}`, {
|
|
424
|
+
title: `Integrate CoinVello into ${fw}`,
|
|
425
|
+
description: `Step-by-step instructions for adding non-custodial crypto checkout (checkout session + verified webhook) to a ${fw} project.`,
|
|
426
|
+
argsSchema: {
|
|
427
|
+
currency: z.string().optional().describe("Pricing currency, default USD"),
|
|
428
|
+
assets: z.string().optional().describe("Comma-separated asset ids, default btc:bitcoin, eth:ethereum, usdc:polygon, usdt:tron"),
|
|
429
|
+
},
|
|
430
|
+
}, ({ currency, assets }) => ({
|
|
431
|
+
messages: [{ role: "user", content: { type: "text", text: integrationPrompt(fw, { currency, assets }) } }],
|
|
432
|
+
}));
|
|
433
|
+
}
|
|
434
|
+
server.registerPrompt("integrate-coinvello-into-framework", {
|
|
435
|
+
title: "Integrate CoinVello into any framework",
|
|
436
|
+
description: "Same procedure for a framework not listed; pass its name.",
|
|
437
|
+
argsSchema: { framework: z.string().describe("e.g. Spring Boot, Phoenix, Hono"), currency: z.string().optional(), assets: z.string().optional() },
|
|
438
|
+
}, ({ framework, currency, assets }) => ({
|
|
439
|
+
messages: [{ role: "user", content: { type: "text", text: integrationPrompt(framework, { currency, assets }) } }],
|
|
440
|
+
}));
|
|
441
|
+
return server;
|
|
442
|
+
}
|
package/dist/verify.d.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface VerifyResult {
|
|
2
|
+
valid: boolean;
|
|
3
|
+
reason?: string;
|
|
4
|
+
timestamp?: number;
|
|
5
|
+
age_seconds?: number;
|
|
6
|
+
expected_v1?: string;
|
|
7
|
+
event?: unknown;
|
|
8
|
+
}
|
|
9
|
+
export declare function parseSignatureHeader(header: string): {
|
|
10
|
+
t: number;
|
|
11
|
+
v1: string[];
|
|
12
|
+
};
|
|
13
|
+
export declare function computeSignature(secret: string, timestamp: number, rawBody: string | Buffer): string;
|
|
14
|
+
export declare function verifyCoinVelloSignature(rawBody: string | Buffer, header: string, secret: string, opts?: {
|
|
15
|
+
toleranceSec?: number;
|
|
16
|
+
now?: number;
|
|
17
|
+
}): VerifyResult;
|
package/dist/verify.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CoinVello webhook signature verification.
|
|
3
|
+
*
|
|
4
|
+
* Header: CoinVello-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256>[,v1=<hex>]
|
|
5
|
+
* Signed: "<t>.<raw body>" with HMAC-SHA256 keyed by the endpoint secret (whsec_..., UTF-8, prefix included)
|
|
6
|
+
* Rules: reject if |now - t| > tolerance (300 s); constant-time compare against any v1; dedupe on event.id
|
|
7
|
+
*/
|
|
8
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
9
|
+
export function parseSignatureHeader(header) {
|
|
10
|
+
let t = 0;
|
|
11
|
+
const v1 = [];
|
|
12
|
+
for (const part of header.split(",")) {
|
|
13
|
+
const idx = part.indexOf("=");
|
|
14
|
+
if (idx < 0)
|
|
15
|
+
continue;
|
|
16
|
+
const k = part.slice(0, idx).trim();
|
|
17
|
+
const v = part.slice(idx + 1).trim();
|
|
18
|
+
if (k === "t")
|
|
19
|
+
t = Number(v);
|
|
20
|
+
else if (k === "v1")
|
|
21
|
+
v1.push(v);
|
|
22
|
+
}
|
|
23
|
+
return { t, v1 };
|
|
24
|
+
}
|
|
25
|
+
export function computeSignature(secret, timestamp, rawBody) {
|
|
26
|
+
const body = Buffer.isBuffer(rawBody) ? rawBody : Buffer.from(rawBody, "utf8");
|
|
27
|
+
return createHmac("sha256", secret).update(`${timestamp}.`).update(body).digest("hex");
|
|
28
|
+
}
|
|
29
|
+
export function verifyCoinVelloSignature(rawBody, header, secret, opts = {}) {
|
|
30
|
+
const tolerance = opts.toleranceSec ?? 300;
|
|
31
|
+
const now = opts.now ?? Math.floor(Date.now() / 1000);
|
|
32
|
+
if (!header)
|
|
33
|
+
return { valid: false, reason: "missing CoinVello-Signature header" };
|
|
34
|
+
const { t, v1 } = parseSignatureHeader(header);
|
|
35
|
+
if (!t || !Number.isFinite(t))
|
|
36
|
+
return { valid: false, reason: "missing or invalid t= in header" };
|
|
37
|
+
const age = Math.abs(now - t);
|
|
38
|
+
if (age > tolerance)
|
|
39
|
+
return { valid: false, reason: `timestamp outside tolerance (${age}s > ${tolerance}s)`, timestamp: t, age_seconds: age };
|
|
40
|
+
if (v1.length === 0)
|
|
41
|
+
return { valid: false, reason: "no v1= signature in header", timestamp: t, age_seconds: age };
|
|
42
|
+
const expectedHex = computeSignature(secret, t, rawBody);
|
|
43
|
+
const expected = Buffer.from(expectedHex, "hex");
|
|
44
|
+
const ok = v1.some((s) => {
|
|
45
|
+
const b = Buffer.from(s, "hex");
|
|
46
|
+
return b.length === expected.length && timingSafeEqual(b, expected);
|
|
47
|
+
});
|
|
48
|
+
if (!ok)
|
|
49
|
+
return { valid: false, reason: "signature mismatch", timestamp: t, age_seconds: age, expected_v1: expectedHex };
|
|
50
|
+
let event = undefined;
|
|
51
|
+
try {
|
|
52
|
+
event = JSON.parse(Buffer.isBuffer(rawBody) ? rawBody.toString("utf8") : rawBody);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
/* body is not JSON; still a valid signature */
|
|
56
|
+
}
|
|
57
|
+
return { valid: true, timestamp: t, age_seconds: age, expected_v1: expectedHex, event };
|
|
58
|
+
}
|