@blocks-network/mcp-server 0.1.55 → 0.1.64

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.
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Agent presence/availability helper.
3
+ *
4
+ * Calls GET /api/v1/agent-status with the Blocks-Protocol-Version
5
+ * header. Backend route is optionalAuth so the API key is forwarded
6
+ * when available but not required.
7
+ *
8
+ * Response shape mirrors the service's agent-status types.
9
+ */
10
+
11
+ import {
12
+ PROTOCOL_VERSION_HEADER,
13
+ CURRENT_PROTOCOL_VERSION,
14
+ } from './protocol-headers.js';
15
+
16
+ /** MUST stay in sync with the service's agent-status types. */
17
+ export const MAX_AGENT_NAMES = 50;
18
+ export const AGENT_NAME_PATTERN = /^[a-zA-Z0-9_]+$/;
19
+
20
+ export interface AgentInstanceStatus {
21
+ instanceId: string;
22
+ uuid: string;
23
+ online: true;
24
+ /**
25
+ * Reserved — backend currently returns 0 (live activity counters are not
26
+ * yet populated by the agent-status service). Do not use for routing or
27
+ * availability decisions.
28
+ */
29
+ activeTasks: number;
30
+ /** Reserved — backend currently returns 0. See `activeTasks`. */
31
+ concurrentTasksPerInstance: number;
32
+ /** Reserved — backend currently returns 0. See `activeTasks`. */
33
+ startedAt: number;
34
+ sdkVersion: string | null;
35
+ cliVersion: string | null;
36
+ preferredProtocolVersion: string | null;
37
+ protocolVersions: string[];
38
+ }
39
+
40
+ export interface AgentStatus {
41
+ agentName: string;
42
+ instances: AgentInstanceStatus[];
43
+ onlineCount: number;
44
+ /** Reserved — backend currently returns 0. See `AgentInstanceStatus.activeTasks`. */
45
+ totalActiveTasks: number;
46
+ taskCount: number;
47
+ }
48
+
49
+ export interface AgentStatusResponse {
50
+ agents: Record<string, AgentStatus>;
51
+ }
52
+
53
+ export interface FetchAgentStatusOptions {
54
+ baseUrl: string;
55
+ agentNames: string[];
56
+ apiKey?: string;
57
+ fetchImpl?: typeof fetch;
58
+ }
59
+
60
+ export async function fetchAgentStatus(
61
+ opts: FetchAgentStatusOptions,
62
+ ): Promise<AgentStatusResponse> {
63
+ const names = opts.agentNames.map((n) => n.trim()).filter(Boolean);
64
+ if (names.length === 0) {
65
+ throw new Error('agentNames must contain at least one value');
66
+ }
67
+ if (names.length > MAX_AGENT_NAMES) {
68
+ throw new Error(`agentNames must be at most ${MAX_AGENT_NAMES} values`);
69
+ }
70
+ for (const n of names) {
71
+ if (!AGENT_NAME_PATTERN.test(n)) {
72
+ throw new Error(`Invalid agent name: ${n}`);
73
+ }
74
+ }
75
+
76
+ const params = new URLSearchParams({ agentNames: names.join(',') });
77
+ const url = `${opts.baseUrl.replace(/\/+$/, '')}/api/v1/agent-status?${params}`;
78
+ const headers: Record<string, string> = {
79
+ [PROTOCOL_VERSION_HEADER]: CURRENT_PROTOCOL_VERSION,
80
+ };
81
+ if (opts.apiKey) headers['Authorization'] = `Bearer ${opts.apiKey}`;
82
+
83
+ const fetchFn = opts.fetchImpl ?? fetch;
84
+ const response = await fetchFn(url, { headers });
85
+ if (!response.ok) {
86
+ throw new Error(`Agent status failed: HTTP ${response.status}`);
87
+ }
88
+ return (await response.json()) as AgentStatusResponse;
89
+ }
package/src/billing.ts ADDED
@@ -0,0 +1,122 @@
1
+ /**
2
+ * Billing helpers — direct HTTP to the routes that accept Bearer
3
+ * API-key auth (`requireAuth` middleware path on the backend).
4
+ *
5
+ * GET /api/v1/billing/:orgId/consumer/balance
6
+ * POST /api/v1/billing/:orgId/consumer/topup
7
+ *
8
+ * Other billing routes (ledger, usage-summary, dashboard-summary,
9
+ * topup-from-earnings) are session-only on the backend and are not
10
+ * callable from an MCP server holding only an API key.
11
+ */
12
+
13
+ import {
14
+ PROTOCOL_VERSION_HEADER,
15
+ CURRENT_PROTOCOL_VERSION,
16
+ } from './protocol-headers.js';
17
+
18
+ /**
19
+ * Platform minimum top-up amount in USD. MUST stay in sync with
20
+ * the service's MIN_BILLING_AMOUNT
21
+ * (decimal-dollar string `'5'`). The backend rejects values below this floor
22
+ * via `stripeMoneyAtLeast(MIN_BILLING_AMOUNT, ...)`; we mirror it here so MCP
23
+ * callers get the real contract up front instead of a runtime HTTP 400.
24
+ */
25
+ export const MIN_TOPUP_AMOUNT_USD = 5;
26
+
27
+ export interface ConsumerBalance {
28
+ /** Ledger balance as a decimal-dollar string (e.g. "12.34"). */
29
+ balance: string;
30
+ /** Currently reserved (held for in-flight tasks). */
31
+ reservedBalance: string;
32
+ /** balance - reservedBalance. */
33
+ availableBalance: string;
34
+ /** ISO timestamp of when the balance snapshot was taken. */
35
+ updatedAt: string;
36
+ }
37
+
38
+ export interface TopUpSession {
39
+ /** Stripe Checkout URL the user opens in a browser to complete payment. */
40
+ checkoutUrl: string;
41
+ /** Stripe Checkout session id. */
42
+ sessionId: string;
43
+ }
44
+
45
+ export interface BillingClientBase {
46
+ baseUrl: string;
47
+ orgId: string;
48
+ apiKey: string;
49
+ fetchImpl?: typeof fetch;
50
+ }
51
+
52
+ function buildHeaders(apiKey: string): Record<string, string> {
53
+ return {
54
+ [PROTOCOL_VERSION_HEADER]: CURRENT_PROTOCOL_VERSION,
55
+ Authorization: `Bearer ${apiKey}`,
56
+ 'Content-Type': 'application/json',
57
+ };
58
+ }
59
+
60
+ function billingUrl(baseUrl: string, orgId: string, suffix: string): string {
61
+ return `${baseUrl.replace(/\/+$/, '')}/api/v1/billing/${encodeURIComponent(orgId)}${suffix}`;
62
+ }
63
+
64
+ export async function getConsumerBalance(
65
+ opts: BillingClientBase,
66
+ ): Promise<ConsumerBalance> {
67
+ const url = billingUrl(opts.baseUrl, opts.orgId, '/consumer/balance');
68
+ const fetchFn = opts.fetchImpl ?? fetch;
69
+ const response = await fetchFn(url, {
70
+ method: 'GET',
71
+ headers: buildHeaders(opts.apiKey),
72
+ });
73
+ if (!response.ok) {
74
+ throw new Error(`Balance lookup failed: HTTP ${response.status}`);
75
+ }
76
+ return (await response.json()) as ConsumerBalance;
77
+ }
78
+
79
+ export interface CreateTopUpOptions extends BillingClientBase {
80
+ /**
81
+ * Whole-dollar (or whole-cent decimal) USD amount, e.g. 25 or 19.99.
82
+ * Must be at least `MIN_TOPUP_AMOUNT_USD` ($5) — backend rejects below this.
83
+ */
84
+ amountUsd: number;
85
+ }
86
+
87
+ export async function createConsumerTopUp(
88
+ opts: CreateTopUpOptions,
89
+ ): Promise<TopUpSession> {
90
+ if (!Number.isFinite(opts.amountUsd) || opts.amountUsd <= 0) {
91
+ throw new Error('amountUsd must be a positive finite number');
92
+ }
93
+ if (Math.round(opts.amountUsd * 100) / 100 !== opts.amountUsd) {
94
+ throw new Error('amountUsd must be a whole-cent value (no sub-cent fractions)');
95
+ }
96
+ if (opts.amountUsd < MIN_TOPUP_AMOUNT_USD) {
97
+ throw new Error(
98
+ `amountUsd must be at least $${MIN_TOPUP_AMOUNT_USD}.00 (platform minimum)`,
99
+ );
100
+ }
101
+ const amount = opts.amountUsd.toFixed(2);
102
+
103
+ const url = billingUrl(opts.baseUrl, opts.orgId, '/consumer/topup');
104
+ const fetchFn = opts.fetchImpl ?? fetch;
105
+ const response = await fetchFn(url, {
106
+ method: 'POST',
107
+ headers: buildHeaders(opts.apiKey),
108
+ body: JSON.stringify({ amount }),
109
+ });
110
+ if (!response.ok) {
111
+ let detail = '';
112
+ try {
113
+ detail = await response.text();
114
+ } catch {
115
+ // ignore body decode failures
116
+ }
117
+ throw new Error(
118
+ `Top-up failed: HTTP ${response.status}${detail ? ` — ${detail}` : ''}`,
119
+ );
120
+ }
121
+ return (await response.json()) as TopUpSession;
122
+ }