@blocks-network/mcp-server 0.1.62 → 0.1.65

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/LICENSE ADDED
@@ -0,0 +1,26 @@
1
+ Blocks Network Software Development Kit License Agreement
2
+ Copyright © 2026 Blocks Network Inc. All rights reserved.
3
+
4
+ Subject to the terms and conditions of the license, you are hereby granted
5
+ a non-exclusive, worldwide, royalty-free license to (a) copy and modify
6
+ the software in source code or binary form for use with the software services
7
+ and interfaces provided by Blocks Network, and (b) redistribute unmodified copies
8
+ of the software to third parties. The software may not be incorporated in
9
+ or used to provide any product or service competitive with the products
10
+ and services of Blocks Network.
11
+
12
+ The above copyright notice and this license shall be included
13
+ in or with all copies or substantial portions of the software.
14
+
15
+ This license does not grant you permission to use the trade names, trademarks,
16
+ service marks, or product names of Blocks Network, except as required for reasonable
17
+ and customary use in describing the origin of the software and reproducing
18
+ the content of this license.
19
+
20
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF
21
+ ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
23
+ EVENT SHALL BLOCKS NETWORK OR THE AUTHORS OR COPYRIGHT HOLDERS OF THE SOFTWARE BE
24
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
25
+ CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
26
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -2,29 +2,30 @@
2
2
 
3
3
  MCP (Model Context Protocol) server that exposes Blocks Network consumer operations as tools for AI assistants.
4
4
 
5
- ## Setup
6
-
7
- ```bash
8
- cd mcp
9
- npm install
10
- npm run build
11
- ```
5
+ Get API Key: https://app.blocks.ai/manage/api-keys
12
6
 
13
7
  ## Environment Variables
14
8
 
15
9
  | Variable | Required | Description |
16
10
  |----------|----------|-------------|
17
11
  | `BLOCKS_API_KEY` | Yes | Your Blocks Network API key |
12
+ | `BLOCKS_ORG_ID` | For billing tools | Your consumer org ID (required by `check_balance` and `request_topup`). Find it in the dashboard URL or `blocks whoami --json`. |
18
13
  | `BLOCKS_MCP_FILE_ROOT` | No | Allowed root directory for file uploads (default: cwd) |
19
14
 
20
15
  All other configuration (keys, endpoints) is resolved automatically from CDM.
21
16
 
22
17
  ## Installation
23
18
 
19
+ ```bash
20
+ npm i @blocks-network/mcp-server
21
+ ```
22
+
23
+ `BLOCKS_ORG_ID` in the snippets below is only required by the billing tools (`check_balance`, `request_topup`); omit it if you don't plan to use them.
24
+
24
25
  ### Claude Code (CLI)
25
26
 
26
27
  ```bash
27
- claude mcp add blocks-network -- node /path/to/blocks-sdk/mcp/dist/index.js
28
+ claude mcp add blocks-network -- npx @blocks-network/mcp-server
28
29
  ```
29
30
 
30
31
  Or add to your `.claude/settings.json`:
@@ -33,10 +34,11 @@ Or add to your `.claude/settings.json`:
33
34
  {
34
35
  "mcpServers": {
35
36
  "blocks-network": {
36
- "command": "node",
37
- "args": ["/path/to/blocks-sdk/mcp/dist/index.js"],
37
+ "command": "npx",
38
+ "args": ["@blocks-network/mcp-server"],
38
39
  "env": {
39
- "BLOCKS_API_KEY": "your-api-key"
40
+ "BLOCKS_API_KEY": "your-api-key",
41
+ "BLOCKS_ORG_ID": "your-consumer-org-id"
40
42
  }
41
43
  }
42
44
  }
@@ -51,10 +53,11 @@ Add to your `claude_desktop_config.json`:
51
53
  {
52
54
  "mcpServers": {
53
55
  "blocks-network": {
54
- "command": "node",
55
- "args": ["/path/to/blocks-sdk/mcp/dist/index.js"],
56
+ "command": "npx",
57
+ "args": ["@blocks-network/mcp-server"],
56
58
  "env": {
57
- "BLOCKS_API_KEY": "your-api-key"
59
+ "BLOCKS_API_KEY": "your-api-key",
60
+ "BLOCKS_ORG_ID": "your-consumer-org-id"
58
61
  }
59
62
  }
60
63
  }
@@ -73,10 +76,11 @@ Create an `mcp.json` file:
73
76
  {
74
77
  "mcpServers": {
75
78
  "blocks-network": {
76
- "command": "node",
77
- "args": ["/path/to/blocks-sdk/mcp/dist/index.js"],
79
+ "command": "npx",
80
+ "args": ["@blocks-network/mcp-server"],
78
81
  "env": {
79
- "BLOCKS_API_KEY": "your-api-key"
82
+ "BLOCKS_API_KEY": "your-api-key",
83
+ "BLOCKS_ORG_ID": "your-consumer-org-id"
80
84
  }
81
85
  }
82
86
  }
@@ -91,10 +95,11 @@ Add to your `~/.gemini/settings.json`:
91
95
  {
92
96
  "mcpServers": {
93
97
  "blocks-network": {
94
- "command": "node",
95
- "args": ["/path/to/blocks-sdk/mcp/dist/index.js"],
98
+ "command": "npx",
99
+ "args": ["@blocks-network/mcp-server"],
96
100
  "env": {
97
- "BLOCKS_API_KEY": "your-api-key"
101
+ "BLOCKS_API_KEY": "your-api-key",
102
+ "BLOCKS_ORG_ID": "your-consumer-org-id"
98
103
  }
99
104
  }
100
105
  }
@@ -109,9 +114,17 @@ Add to your `~/.gemini/settings.json`:
109
114
  | `get_task` | Get the current status of a task |
110
115
  | `list_tasks` | List tasks, optionally filtered by agent or state |
111
116
  | `cancel_task` | Cancel a running task |
117
+ | `pause_task` | Pause a running pipe task |
118
+ | `resume_task` | Resume a paused pipe task |
119
+ | `retry_task` | Retry a failed task |
112
120
  | `list_agents` | List available agents in the registry |
121
+ | `search_agent` | Search the registry for agents by free-text query (name, description, tags, provider, category) |
113
122
  | `get_agent_card` | Get the full agent card for a specific agent |
123
+ | `get_agent_status` | Check live availability for agents (online instance count and total task count). Per-instance live activity counters (`activeTasks`, `concurrentTasksPerInstance`, `startedAt`, `totalActiveTasks`) are reserved in the response shape but currently return `0` — the backend does not yet populate them. |
114
124
  | `connect_task` | Connect to an existing task and stream events |
125
+ | `download_artifact` | Download a single task artifact by file name (inline content or save to disk) |
126
+ | `check_balance` | Get the consumer billing balance for the configured org |
127
+ | `request_topup` | Create a Stripe Checkout URL to add USD to the consumer balance (user completes payment in a browser). Minimum top-up is `$5` (platform `MIN_BILLING_AMOUNT`). |
115
128
 
116
129
  ## Development
117
130
 
@@ -0,0 +1,49 @@
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
+ /** MUST stay in sync with the service's agent-status types. */
11
+ export declare const MAX_AGENT_NAMES = 50;
12
+ export declare const AGENT_NAME_PATTERN: RegExp;
13
+ export interface AgentInstanceStatus {
14
+ instanceId: string;
15
+ uuid: string;
16
+ online: true;
17
+ /**
18
+ * Reserved — backend currently returns 0 (live activity counters are not
19
+ * yet populated by the agent-status service). Do not use for routing or
20
+ * availability decisions.
21
+ */
22
+ activeTasks: number;
23
+ /** Reserved — backend currently returns 0. See `activeTasks`. */
24
+ concurrentTasksPerInstance: number;
25
+ /** Reserved — backend currently returns 0. See `activeTasks`. */
26
+ startedAt: number;
27
+ sdkVersion: string | null;
28
+ cliVersion: string | null;
29
+ preferredProtocolVersion: string | null;
30
+ protocolVersions: string[];
31
+ }
32
+ export interface AgentStatus {
33
+ agentName: string;
34
+ instances: AgentInstanceStatus[];
35
+ onlineCount: number;
36
+ /** Reserved — backend currently returns 0. See `AgentInstanceStatus.activeTasks`. */
37
+ totalActiveTasks: number;
38
+ taskCount: number;
39
+ }
40
+ export interface AgentStatusResponse {
41
+ agents: Record<string, AgentStatus>;
42
+ }
43
+ export interface FetchAgentStatusOptions {
44
+ baseUrl: string;
45
+ agentNames: string[];
46
+ apiKey?: string;
47
+ fetchImpl?: typeof fetch;
48
+ }
49
+ export declare function fetchAgentStatus(opts: FetchAgentStatusOptions): Promise<AgentStatusResponse>;
@@ -0,0 +1,40 @@
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
+ import { PROTOCOL_VERSION_HEADER, CURRENT_PROTOCOL_VERSION, } from './protocol-headers.js';
11
+ /** MUST stay in sync with the service's agent-status types. */
12
+ export const MAX_AGENT_NAMES = 50;
13
+ export const AGENT_NAME_PATTERN = /^[a-zA-Z0-9_]+$/;
14
+ export async function fetchAgentStatus(opts) {
15
+ const names = opts.agentNames.map((n) => n.trim()).filter(Boolean);
16
+ if (names.length === 0) {
17
+ throw new Error('agentNames must contain at least one value');
18
+ }
19
+ if (names.length > MAX_AGENT_NAMES) {
20
+ throw new Error(`agentNames must be at most ${MAX_AGENT_NAMES} values`);
21
+ }
22
+ for (const n of names) {
23
+ if (!AGENT_NAME_PATTERN.test(n)) {
24
+ throw new Error(`Invalid agent name: ${n}`);
25
+ }
26
+ }
27
+ const params = new URLSearchParams({ agentNames: names.join(',') });
28
+ const url = `${opts.baseUrl.replace(/\/+$/, '')}/api/v1/agent-status?${params}`;
29
+ const headers = {
30
+ [PROTOCOL_VERSION_HEADER]: CURRENT_PROTOCOL_VERSION,
31
+ };
32
+ if (opts.apiKey)
33
+ headers['Authorization'] = `Bearer ${opts.apiKey}`;
34
+ const fetchFn = opts.fetchImpl ?? fetch;
35
+ const response = await fetchFn(url, { headers });
36
+ if (!response.ok) {
37
+ throw new Error(`Agent status failed: HTTP ${response.status}`);
38
+ }
39
+ return (await response.json());
40
+ }
@@ -0,0 +1,50 @@
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
+ * Platform minimum top-up amount in USD. MUST stay in sync with
14
+ * the service's MIN_BILLING_AMOUNT
15
+ * (decimal-dollar string `'5'`). The backend rejects values below this floor
16
+ * via `stripeMoneyAtLeast(MIN_BILLING_AMOUNT, ...)`; we mirror it here so MCP
17
+ * callers get the real contract up front instead of a runtime HTTP 400.
18
+ */
19
+ export declare const MIN_TOPUP_AMOUNT_USD = 5;
20
+ export interface ConsumerBalance {
21
+ /** Ledger balance as a decimal-dollar string (e.g. "12.34"). */
22
+ balance: string;
23
+ /** Currently reserved (held for in-flight tasks). */
24
+ reservedBalance: string;
25
+ /** balance - reservedBalance. */
26
+ availableBalance: string;
27
+ /** ISO timestamp of when the balance snapshot was taken. */
28
+ updatedAt: string;
29
+ }
30
+ export interface TopUpSession {
31
+ /** Stripe Checkout URL the user opens in a browser to complete payment. */
32
+ checkoutUrl: string;
33
+ /** Stripe Checkout session id. */
34
+ sessionId: string;
35
+ }
36
+ export interface BillingClientBase {
37
+ baseUrl: string;
38
+ orgId: string;
39
+ apiKey: string;
40
+ fetchImpl?: typeof fetch;
41
+ }
42
+ export declare function getConsumerBalance(opts: BillingClientBase): Promise<ConsumerBalance>;
43
+ export interface CreateTopUpOptions extends BillingClientBase {
44
+ /**
45
+ * Whole-dollar (or whole-cent decimal) USD amount, e.g. 25 or 19.99.
46
+ * Must be at least `MIN_TOPUP_AMOUNT_USD` ($5) — backend rejects below this.
47
+ */
48
+ amountUsd: number;
49
+ }
50
+ export declare function createConsumerTopUp(opts: CreateTopUpOptions): Promise<TopUpSession>;
@@ -0,0 +1,72 @@
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
+ import { PROTOCOL_VERSION_HEADER, CURRENT_PROTOCOL_VERSION, } from './protocol-headers.js';
13
+ /**
14
+ * Platform minimum top-up amount in USD. MUST stay in sync with
15
+ * the service's MIN_BILLING_AMOUNT
16
+ * (decimal-dollar string `'5'`). The backend rejects values below this floor
17
+ * via `stripeMoneyAtLeast(MIN_BILLING_AMOUNT, ...)`; we mirror it here so MCP
18
+ * callers get the real contract up front instead of a runtime HTTP 400.
19
+ */
20
+ export const MIN_TOPUP_AMOUNT_USD = 5;
21
+ function buildHeaders(apiKey) {
22
+ return {
23
+ [PROTOCOL_VERSION_HEADER]: CURRENT_PROTOCOL_VERSION,
24
+ Authorization: `Bearer ${apiKey}`,
25
+ 'Content-Type': 'application/json',
26
+ };
27
+ }
28
+ function billingUrl(baseUrl, orgId, suffix) {
29
+ return `${baseUrl.replace(/\/+$/, '')}/api/v1/billing/${encodeURIComponent(orgId)}${suffix}`;
30
+ }
31
+ export async function getConsumerBalance(opts) {
32
+ const url = billingUrl(opts.baseUrl, opts.orgId, '/consumer/balance');
33
+ const fetchFn = opts.fetchImpl ?? fetch;
34
+ const response = await fetchFn(url, {
35
+ method: 'GET',
36
+ headers: buildHeaders(opts.apiKey),
37
+ });
38
+ if (!response.ok) {
39
+ throw new Error(`Balance lookup failed: HTTP ${response.status}`);
40
+ }
41
+ return (await response.json());
42
+ }
43
+ export async function createConsumerTopUp(opts) {
44
+ if (!Number.isFinite(opts.amountUsd) || opts.amountUsd <= 0) {
45
+ throw new Error('amountUsd must be a positive finite number');
46
+ }
47
+ if (Math.round(opts.amountUsd * 100) / 100 !== opts.amountUsd) {
48
+ throw new Error('amountUsd must be a whole-cent value (no sub-cent fractions)');
49
+ }
50
+ if (opts.amountUsd < MIN_TOPUP_AMOUNT_USD) {
51
+ throw new Error(`amountUsd must be at least $${MIN_TOPUP_AMOUNT_USD}.00 (platform minimum)`);
52
+ }
53
+ const amount = opts.amountUsd.toFixed(2);
54
+ const url = billingUrl(opts.baseUrl, opts.orgId, '/consumer/topup');
55
+ const fetchFn = opts.fetchImpl ?? fetch;
56
+ const response = await fetchFn(url, {
57
+ method: 'POST',
58
+ headers: buildHeaders(opts.apiKey),
59
+ body: JSON.stringify({ amount }),
60
+ });
61
+ if (!response.ok) {
62
+ let detail = '';
63
+ try {
64
+ detail = await response.text();
65
+ }
66
+ catch {
67
+ // ignore body decode failures
68
+ }
69
+ throw new Error(`Top-up failed: HTTP ${response.status}${detail ? ` — ${detail}` : ''}`);
70
+ }
71
+ return (await response.json());
72
+ }
package/dist/index.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
- import { resolve, relative } from 'node:path';
3
- import { realpathSync } from 'node:fs';
2
+ import { resolve, relative, dirname } from 'node:path';
3
+ import { realpathSync, mkdirSync, writeFileSync } from 'node:fs';
4
4
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
5
5
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
6
6
  import { z } from 'zod';
7
7
  import { TaskClient, textPart, filePartFromPath, fetchCdmConfig, getAgent, BLOCKS_MAX_UPLOAD_BYTES, } from '@blocks-network/sdk';
8
- import { listAgentsAuthenticated } from './registry-list.js';
9
- import { sendTask, getTask, listTasks, cancelTask, listAgents, getAgentCard, connectTask, defaultFileSize, } from './tools.js';
8
+ import { listAllAgentsAuthenticated } from './registry-list.js';
9
+ import { fetchAgentStatus, MAX_AGENT_NAMES } from './agent-status.js';
10
+ import { getConsumerBalance, createConsumerTopUp } from './billing.js';
11
+ import { sendTask, getTask, listTasks, cancelTask, pauseTask, resumeTask, retryTask, listAgents, searchAgents, getAgentCard, getAgentStatus, connectTask, downloadArtifact, checkBalance, requestTopup, defaultFileSize, } from './tools.js';
10
12
  const ALLOWED_ROOT = process.env.BLOCKS_MCP_FILE_ROOT ?? process.cwd();
11
13
  if (!process.env.BLOCKS_API_KEY) {
12
14
  console.error('Warning: BLOCKS_API_KEY is not set. Private agents and paid tasks will not work.');
@@ -27,6 +29,19 @@ function validateFilePath(filePath) {
27
29
  }
28
30
  return real;
29
31
  }
32
+ function resolveSavePath(filePath) {
33
+ const root = realpathSync(resolve(ALLOWED_ROOT));
34
+ const resolved = resolve(root, filePath);
35
+ const rel = relative(root, resolved);
36
+ if (rel.startsWith('..') || resolve(root, rel) !== resolved) {
37
+ throw new Error(`Save path must be within ${ALLOWED_ROOT}`);
38
+ }
39
+ mkdirSync(dirname(resolved), { recursive: true });
40
+ return resolved;
41
+ }
42
+ function writeFile(filePath, data) {
43
+ writeFileSync(filePath, data);
44
+ }
30
45
  const taskClients = new Map();
31
46
  let resolvedBaseUrl;
32
47
  async function getBaseUrl() {
@@ -52,10 +67,16 @@ async function getTaskClient(billingMode = 'free') {
52
67
  const deps = {
53
68
  getBaseUrl,
54
69
  getApiKey: () => process.env.BLOCKS_API_KEY,
70
+ getOrgId: () => process.env.BLOCKS_ORG_ID,
55
71
  getTaskClient,
56
72
  getAgentByName: (agentName, options) => getAgent(agentName, options),
57
- listAgents: listAgentsAuthenticated,
73
+ listAgents: listAllAgentsAuthenticated,
74
+ fetchAgentStatus,
75
+ getConsumerBalance,
76
+ createConsumerTopUp,
58
77
  validateFilePath,
78
+ resolveSavePath,
79
+ writeFile,
59
80
  fileSize: defaultFileSize,
60
81
  maxUploadBytes: BLOCKS_MAX_UPLOAD_BYTES,
61
82
  filePartFromPath,
@@ -87,19 +108,67 @@ server.tool('list_tasks', 'List tasks, optionally filtered by agent or state', {
87
108
  limit: z.number().optional().describe('Max results to return'),
88
109
  }, (params) => listTasks(params, deps));
89
110
  server.tool('cancel_task', 'Cancel a running task', { taskId: z.string().describe('The task ID to cancel') }, (params) => cancelTask(params, deps));
90
- server.tool('list_agents', 'List available agents in the Blocks Network registry. Use listing="private" with an API key to discover your private agents.', {
91
- skill: z.string().optional().describe('Filter by skill name'),
111
+ server.tool('pause_task', 'Pause a running pipe task. Resume later with resume_task.', { taskId: z.string().describe('The task ID to pause') }, (params) => pauseTask(params, deps));
112
+ server.tool('resume_task', 'Resume a paused pipe task', { taskId: z.string().describe('The task ID to resume') }, (params) => resumeTask(params, deps));
113
+ server.tool('retry_task', 'Retry a failed task', { taskId: z.string().describe('The task ID to retry') }, (params) => retryTask(params, deps));
114
+ server.tool('list_agents', 'List available agents in the Blocks Network registry. By default only agents with at least one online instance are returned; set includeOffline=true to also list registered agents that are currently offline. Use listing="private" with an API key to discover your private agents.', {
115
+ tag: z.string().optional().describe('Filter by tag slug'),
92
116
  listing: z
93
117
  .enum(['public', 'private'])
94
118
  .optional()
95
119
  .describe('Filter by listing visibility (default: public)'),
96
- limit: z.number().optional().describe('Max results to return'),
120
+ limit: z
121
+ .number()
122
+ .optional()
123
+ .describe('Max agents to fetch across all pages; omit to fetch all'),
124
+ includeOffline: z
125
+ .boolean()
126
+ .optional()
127
+ .describe('Include agents with no online instances (default: false)'),
97
128
  }, (params) => listAgents(params, deps));
129
+ server.tool('search_agent', 'Search the Blocks Network registry for agents matching a free-text query. The query matches against agent name, display name, description, tags, provider, and category, and supports field qualifiers (e.g. "agentname:translate", tag:"data"), quoted phrases, and negation ("-deprecated"). By default only agents with at least one online instance are returned; set includeOffline=true to also include matching agents that are currently offline. Use listing="private" with an API key to search your private agents.', {
130
+ query: z.string().describe('Free-text search query'),
131
+ tag: z.string().optional().describe('Additionally filter by tag slug'),
132
+ listing: z
133
+ .enum(['public', 'private'])
134
+ .optional()
135
+ .describe('Filter by listing visibility (default: public)'),
136
+ limit: z
137
+ .number()
138
+ .optional()
139
+ .describe('Max matching agents to fetch across all pages; omit to fetch all'),
140
+ includeOffline: z
141
+ .boolean()
142
+ .optional()
143
+ .describe('Include agents with no online instances (default: false)'),
144
+ }, (params) => searchAgents(params, deps));
98
145
  server.tool('get_agent_card', 'Get the full agent card for a specific agent', { agentName: z.string().describe('Agent name to look up') }, (params) => getAgentCard(params, deps));
146
+ server.tool('get_agent_status', 'Check live availability for one or more agents: how many instances are online, total task count for the agent, and SDK/CLI versions per instance. (Per-instance live activity counters such as `activeTasks`, `concurrentTasksPerInstance`, `startedAt`, and `totalActiveTasks` are reserved in the response shape but not yet populated by the backend — they currently return 0.)', {
147
+ agentNames: z
148
+ .array(z.string())
149
+ .min(1)
150
+ .max(MAX_AGENT_NAMES)
151
+ .describe(`Agent names to check (1-${MAX_AGENT_NAMES})`),
152
+ }, (params) => getAgentStatus(params, deps));
153
+ server.tool('check_balance', 'Get the consumer billing balance for the configured org (BLOCKS_ORG_ID): ledger balance, active reservations, and available balance.', {}, (_params) => checkBalance({}, deps));
154
+ server.tool('request_topup', 'Create a Stripe Checkout session to add USD to the consumer balance. Returns a URL the user opens in a browser to complete payment; the MCP server does not handle payment itself. Minimum top-up is $5 (platform `MIN_BILLING_AMOUNT`).', {
155
+ amountUsd: z
156
+ .number()
157
+ .positive()
158
+ .describe('Amount to add in USD (e.g. 25 or 19.99). Whole-cent precision. Must be at least $5 (platform minimum).'),
159
+ }, (params) => requestTopup(params, deps));
99
160
  server.tool('connect_task', 'Connect to an existing task, stream events and data until completion', {
100
161
  taskId: z.string().describe('The task ID to connect to'),
101
162
  timeoutMs: z.number().optional().describe('Timeout in milliseconds (default: 60000)'),
102
163
  }, (params) => connectTask(params, deps));
164
+ server.tool('download_artifact', 'Download a single artifact from a task by file name. If savePath is provided, writes the artifact to disk under BLOCKS_MCP_FILE_ROOT; otherwise returns the content inline (text decoded, binary base64-encoded).', {
165
+ taskId: z.string().describe('The task ID that produced the artifact'),
166
+ fileName: z.string().describe('Artifact file name as listed by get_task'),
167
+ savePath: z
168
+ .string()
169
+ .optional()
170
+ .describe('Optional path (relative to BLOCKS_MCP_FILE_ROOT) to write the artifact to'),
171
+ }, (params) => downloadArtifact(params, deps));
103
172
  function shutdown() {
104
173
  for (const client of taskClients.values()) {
105
174
  client.destroy();
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Shared protocol-version header constants for direct-HTTP backend
3
+ * callers (`registry-list`, `agent-status`, `billing`).
4
+ *
5
+ * MUST stay in sync with
6
+ * blocks-sdk/sdks/node/src/runtime/protocol-version.ts (the canonical
7
+ * source). Until the SDK exports these from its public surface, both
8
+ * files must update atomically when the protocol version bumps.
9
+ */
10
+ export declare const PROTOCOL_VERSION_HEADER = "Blocks-Protocol-Version";
11
+ export declare const CURRENT_PROTOCOL_VERSION = "2026-05-01";
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Shared protocol-version header constants for direct-HTTP backend
3
+ * callers (`registry-list`, `agent-status`, `billing`).
4
+ *
5
+ * MUST stay in sync with
6
+ * blocks-sdk/sdks/node/src/runtime/protocol-version.ts (the canonical
7
+ * source). Until the SDK exports these from its public surface, both
8
+ * files must update atomically when the protocol version bumps.
9
+ */
10
+ export const PROTOCOL_VERSION_HEADER = 'Blocks-Protocol-Version';
11
+ export const CURRENT_PROTOCOL_VERSION = '2026-05-01';
@@ -5,15 +5,13 @@
5
5
  * header (required by the backend protocol-version middleware) and an
6
6
  * optional Bearer API key for private/owned listings.
7
7
  */
8
- export declare const PROTOCOL_VERSION_HEADER = "Blocks-Protocol-Version";
9
- export declare const CURRENT_PROTOCOL_VERSION = "2026-05-01";
10
8
  export interface AgentListEntry {
11
9
  agentName: string;
12
10
  name?: string;
13
11
  description?: string;
14
12
  listing?: string;
15
13
  billingMode?: string;
16
- skills?: Array<{
14
+ tags?: Array<{
17
15
  id: string;
18
16
  name: string;
19
17
  }>;
@@ -21,13 +19,35 @@ export interface AgentListEntry {
21
19
  export interface ListAgentsOptions {
22
20
  baseUrl: string;
23
21
  apiKey?: string;
24
- skill?: string;
22
+ /** Free-text search query (`q`); matches agent name, description, tags, etc. */
23
+ q?: string;
24
+ tag?: string;
25
25
  listing?: 'public' | 'private';
26
+ /** Page size for a single request. The backend caps this at 100. */
26
27
  limit?: number;
28
+ /** Opaque pagination cursor returned as `next` by a previous request. */
29
+ cursor?: string;
27
30
  fetchImpl?: typeof fetch;
28
31
  }
29
32
  export interface ListAgentsResult {
30
33
  agents: AgentListEntry[];
31
34
  totalCount?: number;
35
+ /** Opaque cursor for the next page, or null/absent when there are no more. */
36
+ next?: string | null;
37
+ /** Total agents with at least one online instance (ignores cursor). */
38
+ totalOnlineCount?: number;
32
39
  }
40
+ /** Backend maximum page size for GET /api/v1/registry/agents. */
41
+ export declare const REGISTRY_PAGE_SIZE = 100;
33
42
  export declare function listAgentsAuthenticated(opts: ListAgentsOptions): Promise<ListAgentsResult>;
43
+ /**
44
+ * Fetch every agent by following the `next` cursor until it's null/absent.
45
+ *
46
+ * Uses the backend's maximum page size (100) to minimise round-trips. The
47
+ * optional `maxAgents` cap bounds the total number of agents collected and
48
+ * shrinks the final page request so we never over-fetch. The latest
49
+ * `totalCount`/`totalOnlineCount` seen are carried forward to the result.
50
+ */
51
+ export declare function listAllAgentsAuthenticated(opts: ListAgentsOptions & {
52
+ maxAgents?: number;
53
+ }): Promise<ListAgentsResult>;
@@ -5,12 +5,17 @@
5
5
  * header (required by the backend protocol-version middleware) and an
6
6
  * optional Bearer API key for private/owned listings.
7
7
  */
8
- export const PROTOCOL_VERSION_HEADER = 'Blocks-Protocol-Version';
9
- export const CURRENT_PROTOCOL_VERSION = '2026-05-01';
8
+ import { PROTOCOL_VERSION_HEADER, CURRENT_PROTOCOL_VERSION, } from './protocol-headers.js';
9
+ /** Backend maximum page size for GET /api/v1/registry/agents. */
10
+ export const REGISTRY_PAGE_SIZE = 100;
11
+ /** Safety backstop so a misbehaving (never-null) cursor can't loop forever. */
12
+ const MAX_PAGES = 1000;
10
13
  export async function listAgentsAuthenticated(opts) {
11
14
  const params = new URLSearchParams({ include: 'full' });
12
- if (opts.skill)
13
- params.set('skill', opts.skill);
15
+ if (opts.q)
16
+ params.set('q', opts.q);
17
+ if (opts.tag)
18
+ params.set('tag', opts.tag);
14
19
  if (opts.listing) {
15
20
  params.set('listing', opts.listing);
16
21
  if (opts.listing === 'private')
@@ -18,6 +23,8 @@ export async function listAgentsAuthenticated(opts) {
18
23
  }
19
24
  if (opts.limit)
20
25
  params.set('limit', String(opts.limit));
26
+ if (opts.cursor)
27
+ params.set('cursor', opts.cursor);
21
28
  const url = `${opts.baseUrl.replace(/\/+$/, '')}/api/v1/registry/agents?${params}`;
22
29
  const headers = {
23
30
  [PROTOCOL_VERSION_HEADER]: CURRENT_PROTOCOL_VERSION,
@@ -31,3 +38,42 @@ export async function listAgentsAuthenticated(opts) {
31
38
  }
32
39
  return (await response.json());
33
40
  }
41
+ /**
42
+ * Fetch every agent by following the `next` cursor until it's null/absent.
43
+ *
44
+ * Uses the backend's maximum page size (100) to minimise round-trips. The
45
+ * optional `maxAgents` cap bounds the total number of agents collected and
46
+ * shrinks the final page request so we never over-fetch. The latest
47
+ * `totalCount`/`totalOnlineCount` seen are carried forward to the result.
48
+ */
49
+ export async function listAllAgentsAuthenticated(opts) {
50
+ const agents = [];
51
+ let cursor = opts.cursor;
52
+ let totalCount;
53
+ let totalOnlineCount;
54
+ const cap = opts.maxAgents;
55
+ for (let page = 0; page < MAX_PAGES; page++) {
56
+ const remaining = cap !== undefined ? cap - agents.length : undefined;
57
+ if (remaining !== undefined && remaining <= 0)
58
+ break;
59
+ const pageSize = remaining !== undefined
60
+ ? Math.min(REGISTRY_PAGE_SIZE, remaining)
61
+ : REGISTRY_PAGE_SIZE;
62
+ const result = await listAgentsAuthenticated({
63
+ ...opts,
64
+ limit: pageSize,
65
+ cursor,
66
+ });
67
+ agents.push(...result.agents);
68
+ if (result.totalCount !== undefined)
69
+ totalCount = result.totalCount;
70
+ if (result.totalOnlineCount !== undefined) {
71
+ totalOnlineCount = result.totalOnlineCount;
72
+ }
73
+ cursor = result.next ?? undefined;
74
+ if (!cursor)
75
+ break;
76
+ }
77
+ const trimmed = cap !== undefined ? agents.slice(0, cap) : agents;
78
+ return { agents: trimmed, totalCount, totalOnlineCount, next: null };
79
+ }