@xmcp-dev/billing 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 +54 -2
- package/dist/index.d.ts +29 -0
- package/dist/index.js +100 -0
- package/package.json +34 -3
package/README.md
CHANGED
|
@@ -1,3 +1,55 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @xmcp-dev/billing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Meter tool admissions with `@xmcp-dev/billing`, then deliver durable usage events to Metronome or Stripe Billing Meters. One middleware covers filesystem tools. The application owns customer authentication, persistence, pricing, and credit policy.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pnpm add @xmcp-dev/billing
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
## Record before executing
|
|
10
|
+
|
|
11
|
+
```ts
|
|
12
|
+
import { usageBilling } from "@xmcp-dev/billing";
|
|
13
|
+
|
|
14
|
+
export const mcp = usageBilling({
|
|
15
|
+
customer: (context) => context.get<string>("billingCustomerId"),
|
|
16
|
+
units: (context) => (context.params.name === "report" ? 3 : 1),
|
|
17
|
+
admit: async (event) => {
|
|
18
|
+
// In one database transaction: check/debit credits and INSERT this event
|
|
19
|
+
// into a durable outbox. Resolve true only after COMMIT; false denies.
|
|
20
|
+
return yourBillingStore.admit(event);
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
`yourBillingStore` represents your application's transactional persistence, not an exported xmcp API. The [runnable example](https://github.com/basementstudio/xmcp/tree/main/examples/billing-http) supplies a concrete SQLite implementation and delivery worker. An earlier authenticated middleware must set the billing customer ID, or verify the current request inside `customer`. Never accept a billing customer ID or price directly from untrusted tool arguments.
|
|
26
|
+
|
|
27
|
+
`admit` receives an immutable event containing `id`, `customerId`, `tool`, positive integer `units`, and an ISO `timestamp`. The ID identifies one execution round. Returning false denies execution; throwing returns a generic tool error and does not run the handler. Listings, prompts, and resources bypass billing.
|
|
28
|
+
|
|
29
|
+
This meters **admitted attempts**. Once admission commits, subsequent failure, cancellation, or a crash does not refund credits. Each input-required execution round is another admission. If your product bills only completed work, its business transaction must record that completion and usage together; this admission middleware is not that billing model. Tool retries are new attempts; delivery retries reuse the stored event ID.
|
|
30
|
+
|
|
31
|
+
## Deliver from a worker
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { metronomeEvents, stripeMeterEvents } from "@xmcp-dev/billing";
|
|
35
|
+
|
|
36
|
+
const deliver = metronomeEvents({
|
|
37
|
+
secretKey: process.env.METRONOME_API_KEY!,
|
|
38
|
+
eventName: "xmcp_tool_attempt",
|
|
39
|
+
});
|
|
40
|
+
// Existing Stripe Billing Meters users can choose:
|
|
41
|
+
const deliverToStripe = stripeMeterEvents({
|
|
42
|
+
secretKey: process.env.STRIPE_SECRET_KEY!,
|
|
43
|
+
eventName: "xmcp_tool_attempt",
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Read pending events from your outbox, await `deliver(event)`, then mark the row delivered. Retain failures for retry and alert on persistent errors. A crash after provider acceptance may cause redelivery: Stripe receives the same event identifier and idempotency key; Metronome receives the same `transaction_id`. Providers' deduplication windows are finite. The example stops automatic delivery for events older than 23 hours so an operator can reconcile ambiguous records before replaying them. API acceptance does not prove successful invoicing; monitor provider ingestion errors and reconcile your outbox.
|
|
48
|
+
|
|
49
|
+
[Stripe recommends Metronome for new usage-based integrations](https://docs.stripe.com/billing/subscriptions/usage-based/recording-usage). Configure a Metronome billable metric for `xmcp_tool_attempt` that sums `properties.units`, plus the customer's product/contract. For existing Stripe Billing Meters, configure the matching meter event name, `stripe_customer_id` customer field, `value` sum field, and a subscribed metered price. These adapters do not create subscriptions, contracts, invoices, or checkout sessions.
|
|
50
|
+
|
|
51
|
+
## Prepaid credits
|
|
52
|
+
|
|
53
|
+
The example atomically debits local integer usage credits and inserts an outbox event before allowing a tool call. It never checks an eventually consistent invoice total as a real-time spending gate. Grants are explicit demo administrative commands. A production grant must come from a verified, idempotently handled purchase or entitlement event. Do not add credits from an unsigned webhook or a client assertion.
|
|
54
|
+
|
|
55
|
+
SQLite demonstrates durability on one host. Deployments across hosts need a shared transactional store with equivalent atomic behavior. Keep each outbox bound to one provider configuration; changing providers requires reconciling outstanding records. No Redis, payment SDK, or job-queue service is required by the plugin itself.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { McpMiddleware, McpMiddlewareContext } from "xmcp";
|
|
2
|
+
export interface UsageEvent {
|
|
3
|
+
/** Generated once per admitted execution round; retain across delivery retries. */
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly customerId: string;
|
|
6
|
+
readonly tool: string;
|
|
7
|
+
readonly units: number;
|
|
8
|
+
readonly timestamp: string;
|
|
9
|
+
}
|
|
10
|
+
type ToolContext = Extract<McpMiddlewareContext, {
|
|
11
|
+
method: "tools/call";
|
|
12
|
+
}>;
|
|
13
|
+
export interface UsageBillingOptions {
|
|
14
|
+
customer: (context: ToolContext) => string | undefined | Promise<string | undefined>;
|
|
15
|
+
units?: number | ((context: ToolContext) => number | Promise<number>);
|
|
16
|
+
/** Atomically persist the event and debit any credits. False denies execution.
|
|
17
|
+
* Must complete durably before resolving true. Throwing also denies execution. */
|
|
18
|
+
admit: (event: UsageEvent) => Promise<boolean>;
|
|
19
|
+
}
|
|
20
|
+
/** Meter admitted attempts before execution; storage and credit policy are application-owned. */
|
|
21
|
+
export declare function usageBilling(options: UsageBillingOptions): McpMiddleware;
|
|
22
|
+
export interface UsageDeliveryOptions {
|
|
23
|
+
secretKey: string;
|
|
24
|
+
eventName: string;
|
|
25
|
+
fetch?: typeof globalThis.fetch;
|
|
26
|
+
}
|
|
27
|
+
export declare function stripeMeterEvents(options: UsageDeliveryOptions): (event: UsageEvent) => Promise<void>;
|
|
28
|
+
export declare function metronomeEvents(options: UsageDeliveryOptions): (event: UsageEvent) => Promise<void>;
|
|
29
|
+
export {};
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
const denied = (text) => ({
|
|
2
|
+
isError: true,
|
|
3
|
+
content: [{ type: "text", text }],
|
|
4
|
+
});
|
|
5
|
+
/** Meter admitted attempts before execution; storage and credit policy are application-owned. */
|
|
6
|
+
export function usageBilling(options) {
|
|
7
|
+
return async (context, next) => {
|
|
8
|
+
if (context.method !== "tools/call")
|
|
9
|
+
return next();
|
|
10
|
+
context.signal.throwIfAborted();
|
|
11
|
+
const customerId = await options.customer(context);
|
|
12
|
+
context.signal.throwIfAborted();
|
|
13
|
+
if (!customerId?.trim())
|
|
14
|
+
return denied("A verified billing customer is required.");
|
|
15
|
+
const units = typeof options.units === "function"
|
|
16
|
+
? await options.units(context)
|
|
17
|
+
: (options.units ?? 1);
|
|
18
|
+
if (!Number.isSafeInteger(units) || units < 1)
|
|
19
|
+
throw new Error("Billing units must be a positive safe integer.");
|
|
20
|
+
context.signal.throwIfAborted();
|
|
21
|
+
let admitted;
|
|
22
|
+
try {
|
|
23
|
+
admitted = await options.admit(Object.freeze({
|
|
24
|
+
id: crypto.randomUUID(),
|
|
25
|
+
customerId,
|
|
26
|
+
tool: context.params.name,
|
|
27
|
+
units,
|
|
28
|
+
timestamp: new Date().toISOString(),
|
|
29
|
+
}));
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
context.signal.throwIfAborted();
|
|
33
|
+
return denied("Usage could not be recorded. Please try again later.");
|
|
34
|
+
}
|
|
35
|
+
context.signal.throwIfAborted();
|
|
36
|
+
if (admitted !== true)
|
|
37
|
+
return denied("Usage allowance exhausted.");
|
|
38
|
+
// An admission is billable even if the handler fails, needs input, or is
|
|
39
|
+
// cancelled. Delivery retries reuse the stored event, never this callback.
|
|
40
|
+
return next();
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
// Bound a worker delivery attempt; the durable outbox retains failures for retry.
|
|
44
|
+
const DELIVERY_TIMEOUT_MS = 15_000;
|
|
45
|
+
function validate(event) {
|
|
46
|
+
if (!event.id ||
|
|
47
|
+
!event.customerId ||
|
|
48
|
+
!Number.isSafeInteger(event.units) ||
|
|
49
|
+
event.units < 1 ||
|
|
50
|
+
!Number.isFinite(Date.parse(event.timestamp)))
|
|
51
|
+
throw new Error("Invalid stored usage event.");
|
|
52
|
+
}
|
|
53
|
+
export function stripeMeterEvents(options) {
|
|
54
|
+
return async (event) => {
|
|
55
|
+
validate(event);
|
|
56
|
+
const body = new URLSearchParams({
|
|
57
|
+
event_name: options.eventName,
|
|
58
|
+
identifier: event.id,
|
|
59
|
+
timestamp: String(Math.floor(Date.parse(event.timestamp) / 1000)),
|
|
60
|
+
"payload[stripe_customer_id]": event.customerId,
|
|
61
|
+
"payload[value]": String(event.units),
|
|
62
|
+
});
|
|
63
|
+
const response = await (options.fetch ?? fetch)("https://api.stripe.com/v1/billing/meter_events", {
|
|
64
|
+
method: "POST",
|
|
65
|
+
headers: {
|
|
66
|
+
Authorization: `Bearer ${options.secretKey}`,
|
|
67
|
+
"Content-Type": "application/x-www-form-urlencoded",
|
|
68
|
+
"Idempotency-Key": event.id,
|
|
69
|
+
},
|
|
70
|
+
body,
|
|
71
|
+
signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
|
|
72
|
+
});
|
|
73
|
+
if (!response.ok)
|
|
74
|
+
throw new Error(`Stripe usage delivery failed (${response.status}).`);
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
export function metronomeEvents(options) {
|
|
78
|
+
return async (event) => {
|
|
79
|
+
validate(event);
|
|
80
|
+
const response = await (options.fetch ?? fetch)("https://api.metronome.com/v1/ingest", {
|
|
81
|
+
method: "POST",
|
|
82
|
+
headers: {
|
|
83
|
+
Authorization: `Bearer ${options.secretKey}`,
|
|
84
|
+
"Content-Type": "application/json",
|
|
85
|
+
},
|
|
86
|
+
body: JSON.stringify([
|
|
87
|
+
{
|
|
88
|
+
transaction_id: event.id,
|
|
89
|
+
customer_id: event.customerId,
|
|
90
|
+
event_type: options.eventName,
|
|
91
|
+
timestamp: event.timestamp,
|
|
92
|
+
properties: { units: event.units, tool: event.tool },
|
|
93
|
+
},
|
|
94
|
+
]),
|
|
95
|
+
signal: AbortSignal.timeout(DELIVERY_TIMEOUT_MS),
|
|
96
|
+
});
|
|
97
|
+
if (!response.ok)
|
|
98
|
+
throw new Error(`Metronome usage delivery failed (${response.status}).`);
|
|
99
|
+
};
|
|
100
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xmcp-dev/billing",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Billing integration for xmcp",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist"
|
|
18
|
+
],
|
|
19
|
+
"peerDependencies": {
|
|
20
|
+
"xmcp": "^1.6.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@types/node": "^22.19.2",
|
|
24
|
+
"typescript": "^5.9.3",
|
|
25
|
+
"tsx": "^4.21.0",
|
|
26
|
+
"xmcp": "1.7.1"
|
|
27
|
+
},
|
|
28
|
+
"repository": {
|
|
29
|
+
"type": "git",
|
|
30
|
+
"url": "https://github.com/basementstudio/xmcp",
|
|
31
|
+
"directory": "packages/plugins/billing"
|
|
32
|
+
},
|
|
33
|
+
"scripts": {
|
|
34
|
+
"build": "rm -rf dist && tsc",
|
|
35
|
+
"test": "node --import tsx --test test/*.test.ts"
|
|
36
|
+
}
|
|
6
37
|
}
|