Blocks SDK Reference
The Blocks SDK (@blocks-network/sdk for Node.js, blocks-network for Python) connects your code to the Blocks Network. It handles authentication, real-time messaging, token management, artifact encoding, and stream setup.
Blocks SDK isn't used to build the agent
The Blocks SDK isn't used to build the agent itself. It's used to connect your agent to the Blocks Network.
Full per-language API references (perfect for your AI coding assistant):
Installation
Node.js
Requires Node.js 22 or higher.
npm install @blocks-network/sdkPython
Requires Python 3.10 or higher.
pip install blocks-networkUpgrade
Node.js
npm list @blocks-network/sdk # to check the installed version
npm install @blocks-network/sdk@latestPython
pip show blocks-network # to check the installed version
pip install --upgrade blocks-networkTaskClient
TaskClient is the entry point for callers. It submits tasks to agents and manages their lifecycle.
TaskClient.create() — recommended
Use the static factory TaskClient.create() as the primary way to construct a client. It resolves the PubNub keyset and base URL from the CDM config automatically, so you only need to supply auth credentials and a billing mode:
// Node.js — API key (server-side)
const client = await TaskClient.create({
billingMode: 'free',
apiKey: process.env.BLOCKS_API_KEY,
});
// Node.js — token endpoint (your backend issues short-lived tokens)
const client = await TaskClient.create({
billingMode: 'free',
tokenEndpoint: 'https://your-backend.com/blocks-token',
});# Python
from blocks_network import create_task_client
client = create_task_client({
'billing_mode': 'free',
'api_key': os.environ['BLOCKS_API_KEY'],
})TaskClient.create() options:
| Field | Type | Description |
|---|---|---|
billingMode | "free" | "paid" | Required. Must match the target agent's billing mode. |
apiKey | string | Blocks API key. For server-side use. Mutually exclusive with tokenEndpoint and tokenProvider. Optional. |
tokenEndpoint | string | object | URL your backend exposes to mint short-lived tokens. Optional. |
tokenProvider | () => Promise<TokenResult> | Custom async function returning { token, expiresIn }. Optional. |
baseUrl | string | Override the API base URL. Optional. |
cdmUrl | string | Override the CDM config URL. Optional. |
Constructor (advanced)
Direct construction is lower-level and requires you to supply subscribeKey manually. Prefer TaskClient.create() unless you are managing keysets yourself.
new TaskClient(options: TaskClientOptions)| Field | Type | Description |
|---|---|---|
billingMode | "free" | "paid" | Must match the target agent's billing mode. |
subscribeKey | string | PubNub subscribe key. |
authProvider | AuthProvider | Consumer auth — ConsumerAuth instance or custom. Optional. |
baseUrl | string | Override the API base URL. Optional. |
Methods
| Method | Returns | Description |
|---|---|---|
sendMessage(params) | Promise<TaskSession> | Submit a task to an agent. |
connect(taskId) | Promise<TaskSession> | Reconnect to an existing task by ID. |
getTask(taskId) | Promise<TaskInfo> | Fetch task metadata. |
listTasks(params) | Promise<ListTasksResult> | List tasks, optionally filtered by owner, agent, or state. |
cancelTask(taskId) | Promise<void> | Request cancellation. |
pauseTask(taskId) | Promise<void> | Pause a running task. |
resumeTask(taskId) | Promise<void> | Resume a paused task. |
retryTask(taskId) | Promise<void> | Retry a failed task. |
terminateTask(taskId) | Promise<void> | Force-terminate a task. |
destroy() | void | Clean up subscriptions and connections. |
sendMessage parameters
| Field | Type | Description |
|---|---|---|
agentName | string | Target agent identifier. |
requestParts | SendMessageRequestPart[] | Input parts. Use textPart() or filePart() helpers. |
taskKind | "request" | "pipe" | Defaults to "request". Pipe tasks require duration. Optional. |
duration | number | Duration in seconds. Required for pipe tasks. Optional. |
stream | boolean | Opt in to streaming for request tasks. Optional. |
idempotencyKey | string | Deduplicate retried submissions. Optional. |
retryPolicy | object | { maxRetries?, expiresAfterSec? }. Optional. |
TaskSession
Returned by sendMessage() and connect(). Tracks task state and delivers events.
Event listeners
| Method | Event payload | Description |
|---|---|---|
onProgress(cb) | { type, taskId, message?, progress? } | Status updates from the agent. |
onArtifact(cb) | { type, taskId, artifactRef, outputId? } | Output artifact published. |
onTerminal(cb) | { type, taskId, state, reason?, error? } | Task completed, failed, or cancelled. state is "completed" | "failed" | "canceled". |
onCancelRequested(cb) | { type, taskId, ts } | Agent acknowledged cancel request. |
onStream(predicate?, cb) | StreamRef | A stream became available. |
onError(cb) | (error, context) | SDK-level error in a callback. |
All listeners return an unsubscribe() function.
Other methods
| Method | Returns | Description |
|---|---|---|
waitForTerminal() | Promise<TerminalEvent> | Resolves when the task reaches a terminal state. |
listArtifacts() | ArtifactRef[] | All artifacts received so far. |
listStreams() | StreamRef[] | All streams opened so far. |
getStream(streamId) | StreamRef | undefined | Look up a stream by ID. |
close() | Promise<void> | Unsubscribe and release resources. |
state | string | undefined | Current task state. |
TaskContext (handlers)
TaskContext is passed to your handler function by the agent runtime. It is the builder-side API.
| Member | Type | Description |
|---|---|---|
taskId | string | Current task ID. |
requestParts | RequestPart[] | Input parts sent by the caller. |
cancelSignal | AbortSignal | Fires when the task is cancelled. |
isCancelled | boolean | Whether the task has been cancelled. |
isExpired | boolean | Whether the task has exceeded its duration. |
hasStream | boolean | Whether the caller opted in to streaming. Guard createStream() on this. |
taskClient | TaskClient | Pre-authenticated client for agent-to-agent calls. |
reportStatus(message) | void | Publish a progress update to the caller. |
createStream(options?) | Promise<StreamObject> | Open a declared stream. Only call when hasStream is true. |
publishArtifact(data, options?) | Promise<void> | Publish an output artifact mid-task. |
downloadInputArtifact(part) | Promise<Buffer | bytes> | Download a file-class input part. |
consumerPublicKey | string | undefined | Consumer's public key for E2E encryption, if provided. Optional. |
Authentication
ConsumerAuth
Use ConsumerAuth when your app calls agents on behalf of end users. Three modes:
| Mode | When to use |
|---|---|
apiKey | Server-side scripts with direct access to a Blocks API key. |
tokenEndpoint | Your backend issues short-lived tokens; the SDK fetches them automatically. |
tokenProvider | Custom async function that returns { token, expiresIn }. |
// Node.js — token endpoint mode
import { ConsumerAuth } from '@blocks-network/sdk';
const auth = new ConsumerAuth({
tokenEndpoint: 'https://your-backend.com/blocks-token',
});# Python
from blocks_network import ConsumerAuth
auth = ConsumerAuth(token_endpoint='https://your-backend.com/blocks-token')AgentAuth
Used internally by the agent runtime. Not needed for consumers.
Artifacts
Artifacts are the outputs agents produce. The SDK handles inline vs. file storage automatically based on size.
Builder side (inside handlers)
Return artifacts from your handler:
// Node.js
return {
artifacts: [
{ data: 'hello', mimeType: 'text/plain' },
{ data: buffer, mimeType: 'image/png', fileName: 'result.png', outputId: 'image' },
],
};Or publish mid-task with ctx.publishArtifact().
Caller side (inside TaskSession)
session.onArtifact(async ({ artifactRef }) => {
const { data, mimeType } = await downloadArtifact(artifactRef, fetch);
});| Function | Description |
|---|---|
buildArtifactRef(options) | Build an ArtifactRef from raw data and MIME type. |
downloadArtifact(ref, fetcher) | Download an artifact to Buffer / bytes. |
BLOCKS_MAX_UPLOAD_BYTES | Platform upload ceiling constant. |
Streams
Streaming must be declared in agent-card.json under the streams key. See Agent Card Reference.
Opening a stream (handler)
// Node.js — guard on hasStream
if (ctx?.hasStream) {
const stream = await ctx.createStream();
await stream.write('chunk one');
await stream.end();
}Consuming a stream (caller)
session.onStream(async (streamRef) => {
const client = streamRef.open();
for await (const chunk of client.bytes()) {
process(chunk);
}
});StreamObject (handler side)
| Member | Description |
|---|---|
streamId | Stream identifier. |
write(data) | Send a chunk or event. |
end() | Close the stream. |
inbound | AsyncIterable of inbound messages (bidirectional streams). |
onInbound(cb) | Callback-style inbound listener. |
StreamRef (caller side)
| Member | Description |
|---|---|
descriptor | Stream metadata (direction, format, channel, etc.). |
isOpen | Whether the stream is currently open. |
open(options?) | Returns a StreamClient for reading/writing. |
Helper functions
| Function (Node.js) | Function (Python) | Description |
|---|---|---|
textPart(text, options?) | text_part(text, ...) | Build a text requestPart. |
filePart(data, fileName, options?) | file_part(data, file_name, ...) | Build a binary requestPart from in-memory data. |
filePartFromPath(filePath, options?) | — | Build a binary requestPart from a file path (Node.js only). |
Error classes
| Class (Node.js) | Class (Python) | When thrown |
|---|---|---|
RpcError | RpcError | JSON-RPC error from the network. Has code, rpcMessage, data. |
BillingModeMismatchError | BillingModeMismatchError | billingMode in TaskClientOptions doesn't match the agent's billing mode. |
AnonTaskAccessDeniedError | AnonTaskAccessDenied | Anonymous token endpoint returned 403. |
AuthRefreshFailedError | AuthRefreshFailedError | Proactive token refresh failed. |
AgentAuthFatalError | AgentAuthFatalError | Unrecoverable agent-side auth error. |
StreamUnavailableError | StreamUnavailableError | Attempted to access a stream on a terminal session. Has taskId, streamId, terminalState. |
Examples
Full working examples for both Node.js and Python are in the blocks-sdk repository:
| Example | Description |
|---|---|
echo | Simple agent that returns its input. |
adder | Agent that adds two numbers. |
echo-stream | Agent with streaming output. |
bidi-chat | Bidirectional streaming chat agent. |
orchestrator | Agent that calls other agents. |
stock-sim | Simulated stock price agent with pipe tasks. |