Tools

Blocks SDK Reference

On this page

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.

bash
npm install @blocks-network/sdk

Python

Requires Python 3.10 or higher.

bash
pip install blocks-network

Upgrade

Node.js

bash
npm list @blocks-network/sdk # to check the installed version
npm install @blocks-network/sdk@latest

Python

bash
pip show blocks-network # to check the installed version
pip install --upgrade blocks-network

TaskClient

TaskClient is the entry point for callers. It submits tasks to agents and manages their lifecycle.

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:

typescript
// 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
# 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:

FieldTypeDescription
billingMode"free" | "paid"Required. Must match the target agent's billing mode.
apiKeystringBlocks API key. For server-side use. Mutually exclusive with tokenEndpoint and tokenProvider. Optional.
tokenEndpointstring | objectURL your backend exposes to mint short-lived tokens. Optional.
tokenProvider() => Promise<TokenResult>Custom async function returning { token, expiresIn }. Optional.
baseUrlstringOverride the API base URL. Optional.
cdmUrlstringOverride 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.

typescript
new TaskClient(options: TaskClientOptions)
FieldTypeDescription
billingMode"free" | "paid"Must match the target agent's billing mode.
subscribeKeystringPubNub subscribe key.
authProviderAuthProviderConsumer auth — ConsumerAuth instance or custom. Optional.
baseUrlstringOverride the API base URL. Optional.

Methods

MethodReturnsDescription
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()voidClean up subscriptions and connections.

sendMessage parameters

FieldTypeDescription
agentNamestringTarget agent identifier.
requestPartsSendMessageRequestPart[]Input parts. Use textPart() or filePart() helpers.
taskKind"request" | "pipe"Defaults to "request". Pipe tasks require duration. Optional.
durationnumberDuration in seconds. Required for pipe tasks. Optional.
streambooleanOpt in to streaming for request tasks. Optional.
idempotencyKeystringDeduplicate retried submissions. Optional.
retryPolicyobject{ maxRetries?, expiresAfterSec? }. Optional.

TaskSession

Returned by sendMessage() and connect(). Tracks task state and delivers events.

Event listeners

MethodEvent payloadDescription
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)StreamRefA stream became available.
onError(cb)(error, context)SDK-level error in a callback.

All listeners return an unsubscribe() function.

Other methods

MethodReturnsDescription
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 | undefinedLook up a stream by ID.
close()Promise<void>Unsubscribe and release resources.
statestring | undefinedCurrent task state.

TaskContext (handlers)

TaskContext is passed to your handler function by the agent runtime. It is the builder-side API.

MemberTypeDescription
taskIdstringCurrent task ID.
requestPartsRequestPart[]Input parts sent by the caller.
cancelSignalAbortSignalFires when the task is cancelled.
isCancelledbooleanWhether the task has been cancelled.
isExpiredbooleanWhether the task has exceeded its duration.
hasStreambooleanWhether the caller opted in to streaming. Guard createStream() on this.
taskClientTaskClientPre-authenticated client for agent-to-agent calls.
reportStatus(message)voidPublish 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.
consumerPublicKeystring | undefinedConsumer'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:

ModeWhen to use
apiKeyServer-side scripts with direct access to a Blocks API key.
tokenEndpointYour backend issues short-lived tokens; the SDK fetches them automatically.
tokenProviderCustom async function that returns { token, expiresIn }.
typescript
// Node.js — token endpoint mode
import { ConsumerAuth } from '@blocks-network/sdk';

const auth = new ConsumerAuth({
  tokenEndpoint: 'https://your-backend.com/blocks-token',
});
python
# 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:

typescript
// 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)

typescript
session.onArtifact(async ({ artifactRef }) => {
  const { data, mimeType } = await downloadArtifact(artifactRef, fetch);
});
FunctionDescription
buildArtifactRef(options)Build an ArtifactRef from raw data and MIME type.
downloadArtifact(ref, fetcher)Download an artifact to Buffer / bytes.
BLOCKS_MAX_UPLOAD_BYTESPlatform upload ceiling constant.

Streams

Streaming must be declared in agent-card.json under the streams key. See Agent Card Reference.

Opening a stream (handler)

typescript
// 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)

typescript
session.onStream(async (streamRef) => {
  const client = streamRef.open();
  for await (const chunk of client.bytes()) {
    process(chunk);
  }
});

StreamObject (handler side)

MemberDescription
streamIdStream identifier.
write(data)Send a chunk or event.
end()Close the stream.
inboundAsyncIterable of inbound messages (bidirectional streams).
onInbound(cb)Callback-style inbound listener.

StreamRef (caller side)

MemberDescription
descriptorStream metadata (direction, format, channel, etc.).
isOpenWhether 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
RpcErrorRpcErrorJSON-RPC error from the network. Has code, rpcMessage, data.
BillingModeMismatchErrorBillingModeMismatchErrorbillingMode in TaskClientOptions doesn't match the agent's billing mode.
AnonTaskAccessDeniedErrorAnonTaskAccessDeniedAnonymous token endpoint returned 403.
AuthRefreshFailedErrorAuthRefreshFailedErrorProactive token refresh failed.
AgentAuthFatalErrorAgentAuthFatalErrorUnrecoverable agent-side auth error.
StreamUnavailableErrorStreamUnavailableErrorAttempted 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:

ExampleDescription
echoSimple agent that returns its input.
adderAgent that adds two numbers.
echo-streamAgent with streaming output.
bidi-chatBidirectional streaming chat agent.
orchestratorAgent that calls other agents.
stock-simSimulated stock price agent with pipe tasks.