Описание
Blaxel SDK for TypeScript
README
Blaxel is a perpetual sandbox platform that achieves near instant latency by keeping infinite secure sandboxes on automatic standby, while co-hosting your agent logic to cut network overhead.
This repository contains Blaxel's TypeScript SDK, which lets you create and manage sandboxes and other resources on Blaxel.
Installation
# npm
npm install @blaxel/core
# yarn
yarn add @blaxel/core
# bun
bun add @blaxel/core
Authentication
The SDK authenticates with your Blaxel workspace using these sources (in priority order):
- Blaxel CLI, when logged in
- Environment variables in
.envfile (BL_WORKSPACE,BL_API_KEY) - System environment variables
- Blaxel configuration file (
~/.blaxel/config.yaml)
When developing locally, the recommended method is to just log in to your workspace with the Blaxel CLI:
bl login YOUR-WORKSPACE
This allows you to run Blaxel SDK functions that will automatically connect to your workspace without additional setup. When you deploy on Blaxel, this connection persists automatically.
When running Blaxel SDK from a remote server that is not Blaxel-hosted, we recommend using environment variables as described in the third option above.
Usage
Sandboxes
Sandboxes are secure, instant-launching compute environments that scale to zero after inactivity and resume in under 25ms.
Base image contents: The default
blaxel/base-image:latestis Alpine Linux with Node.js 22 and git pre-installed. It does not include Python or other language runtimes. To use Python, either specifyblaxel/py-app:latestas your image (Python 3.12) or install it in the base image withapk add --no-cache python3 py3-pip.
import { SandboxInstance } from "@blaxel/core";
// Create a new sandbox
const sandbox = await SandboxInstance.createIfNotExists({
name: "my-sandbox",
image: "blaxel/base-image:latest",
memory: 4096,
region: "us-pdx-1",
ports: [{ target: 3000, protocol: "HTTP" }],
labels: { env: "dev", project: "my-project" },
ttl: "24h"
});
// Get existing sandbox
const existing = await SandboxInstance.get("my-sandbox");
// Delete sandbox (using class)
await SandboxInstance.delete("my-sandbox");
// Delete sandbox (using instance)
await existing.delete();
Listing resources
List methods return one page at a time. The result contains data, meta, and helpers for fetching more pages when you want them.
import { SandboxInstance } from "@blaxel/core";
const page = await SandboxInstance.list({
limit: 50,
sort: "createdAt:desc",
});
for (const sandbox of page.data) {
console.log(sandbox.metadata.name);
}
if (page.hasMore) {
const nextPage = await page.nextPage();
console.log(nextPage?.data);
}
// Optional auto-pagination, inspired by Stripe's SDK.
for await (const sandbox of page) {
console.log(sandbox.metadata.name);
}
const firstThousand = await page.autoPagingToArray({ limit: 1000 });
Preview URLs
Generate public preview URLs to access services running in your sandbox:
import { SandboxInstance } from "@blaxel/core";
// Get existing sandbox
const sandbox = await SandboxInstance.get("my-sandbox");
// Start a web server in the sandbox
await sandbox.process.exec({
command: "npm run dev -- --port 3000",
workingDir: "/app",
waitForPorts: [3000]
});
// Create a public preview URL
const preview = await sandbox.previews.createIfNotExists({
metadata: { name: "app-preview" },
spec: {
port: 3000,
public: true
}
});
console.log(preview.spec?.url); // https://xyz.preview.bl.run
Previews can also be private, with or without a custom prefix. When you create a private preview URL, a token is required to access the URL, passed as a request parameter or request header.
// ...
// Create a private preview URL
const privatePreview = await sandbox.previews.createIfNotExists({
metadata: { name: "private-app-preview" },
spec: {
port: 3000,
public: false
}
});
// Create a public preview URL with a custom prefix
const customPreview = await sandbox.previews.createIfNotExists({
metadata: { name: "custom-app-preview" },
spec: {
port: 3000,
prefixUrl: "my-app",
public: true
}
});
Process execution
Execute and manage processes in your sandbox:
import { SandboxInstance } from "@blaxel/core";
// Get existing sandbox
const sandbox = await SandboxInstance.get("my-sandbox");
// Execute a command
const process = await sandbox.process.exec({
name: "build-process",
command: "npm run build",
workingDir: "/app",
waitForCompletion: true,
timeout: 60000 // 60 seconds
});
// Kill a running process
await sandbox.process.kill("build-process");
Restart a process if it fails, up to a maximum number of restart attempts:
// ...
// Run with auto-restart on failure
process = await sandbox.process.exec({
name: "web-server",
command: "npm run dev -- --host 0.0.0.0 --port 3000",
restartOnFailure: true,
maxRestarts: 5
});
Filesystem operations
Manage files and directories within your sandbox:
import { SandboxInstance } from "@blaxel/core";
import * as fs from "fs";
// Get existing sandbox
const sandbox = await SandboxInstance.get("my-sandbox");
// Write and read text files
await sandbox.fs.write("/app/config.json", '{"key": "value"}');
const content = await sandbox.fs.read("/app/config.json");
// Write and read binary files
const binaryData = fs.readFileSync("./image.png");
await sandbox.fs.writeBinary("/app/image.png", binaryData);
const blob = await sandbox.fs.readBinary("/app/image.png");
// Create directories
await sandbox.fs.mkdir("/app/uploads");
// List files
const { subdirectories, files } = await sandbox.fs.ls("/app");
// Search for text within files
const matches = await sandbox.fs.grep("pattern", "/app", {
caseSensitive: true,
contextLines: 2,
maxResults: 5,
filePattern: "*.ts",
excludeDirs: ["node_modules"]
});
// Find files and directories matching specified patterns:
const results = await sandbox.fs.find("/app", {
type: "file",
patterns: ["*.md", "*.html"],
maxResults: 1000
});
// Watch for file changes
const handle = sandbox.fs.watch("/app", (event) => {
console.log(event.op, event.path);
}, {
withContent: true,
ignore: ["node_modules", ".git"]
});
// Close watcher
handle.close();
Volumes
Persist data by attaching and using volumes:
import { VolumeInstance, SandboxInstance } from "@blaxel/core";
// Create a volume
const volume = await VolumeInstance.createIfNotExists({
name: "my-volume",
size: 1024, // MB
region: "us-pdx-1",
labels: { env: "test", project: "12345" }
});
// Attach volume to sandbox
const sandbox = await SandboxInstance.createIfNotExists({
name: "my-sandbox",
image: "blaxel/base-image:latest",
volumes: [
{ name: "my-volume", mountPath: "/data", readOnly: false }
]
});
// List first page of volumes
const volumes = await VolumeInstance.list();
for (const volume of volumes.data) {
console.log(volume.name);
}
// Delete volume (using class)
await VolumeInstance.delete("my-volume");
// Delete volume (using instance)
await volume.delete();
Batch jobs
Blaxel lets you support agentic workflows by offloading asynchronous batch processing tasks to its scalable infrastructure, where they can run in parallel. Jobs can run multiple times within a single execution and accept optional input parameters.
import { blJob } from "@blaxel/core";
// Create and run a job execution
const job = blJob("job-name");
const executionId = await job.createExecution({
tasks: [
{ name: "John" },
{ name: "Jane" },
{ name: "Bob" }
]
});
// Get execution status
// Returns: "pending" | "running" | "completed" | "failed"
const status = await job.getExecutionStatus(executionId);
// Get execution details
const execution = await job.getExecution(executionId);
console.log(execution.status, execution.metadata);
// Wait for completion
try {
const result = await job.waitForExecution(executionId, {
maxWait: 300000, // 5 minutes (milliseconds)
interval: 2000, // Poll every 2 seconds (milliseconds)
});
console.log(`Completed: ${result.status}`);
} catch (error) {
console.log(`Timeout: ${error.message}`);
}
// List first page of executions
const executions = await job.listExecutions();
for (const execution of executions.data) {
console.log(execution.status);
}
// Delete an execution
await job.deleteExecution(executionId);
Framework integrations
Blaxel provides additional packages for framework-specific integrations and telemetry:
- @blaxel/telemetry - OpenTelemetry instrumentation
- @blaxel/vercel - Vercel AI SDK integration
- @blaxel/llamaindex - LlamaIndex integration
- @blaxel/langgraph - LangGraph integration
- @blaxel/mastra - Mastra integration
Model use
Blaxel acts as a unified gateway for model APIs, centralizing access credentials, tracing and telemetry. You can integrate with any model API provider, or deploy your own custom model. When a model is deployed on Blaxel, a global API endpoint is also created to call it.
The SDK includes a helper function that creates a reference to a model deployed on Blaxel and returns a framework-specific model client that routes API calls through Blaxel's unified gateway.
import { blModel } from "@blaxel/core";
// With Vercel AI SDK
import { blModel } from "@blaxel/vercel";
const model = await blModel("gpt-5-mini");
// With LangChain
import { blModel } from "@blaxel/langgraph";
const model = await blModel("gpt-5-mini");
// With LlamaIndex
import { blModel } from "@blaxel/llamaindex";
const model = await blModel("gpt-5-mini");
// With Mastra
import { blModel } from "@blaxel/mastra";
const model = await blModel("gpt-5-mini");
MCP tool use
Blaxel lets you deploy and host Model Context Protocol (MCP) servers, accessible at a global endpoint over streamable HTTP.
The SDK includes a helper function that retrieves and returns tool definitions from a Blaxel-hosted MCP server in the format required by specific frameworks.
// With Vercel AI SDK
import { blTools } from "@blaxel/vercel";
const tools = await blTools(['sandbox/my-sandbox'])
// With Mastra
import { blTools } from "@blaxel/mastra";
const tools = await blTools(['sandbox/my-sandbox'])
// With LlamaIndex
import { blTools } from "@blaxel/llamaindex";
const tools = await blTools(['sandbox/my-sandbox'])
// With LangChain
import { blTools } from "@blaxel/langgraph";
const tools = await blTools(['sandbox/my-sandbox'])
Here is an example of retrieving tool definitions from a Blaxel sandbox's MCP server in the format required by Vercel's AI SDK:
import { SandboxInstance } from "@blaxel/core";
import { blTools } from "@blaxel/vercel";
// Create a new sandbox
const sandbox = await SandboxInstance.createIfNotExists({
name: "my-sandbox",
image: "blaxel/base-image:latest",
memory: 4096,
region: "us-pdx-1",
ttl: "24h"
});
// Get sandbox tools
const tools = await blTools(['sandbox/my-sandbox'])
Telemetry
Instrumentation happens automatically when workloads run on Blaxel.
Enable automatic telemetry by importing the @blaxel/telemetry package:
import "@blaxel/telemetry";
Data collection
Error tracking
The SDK includes error tracking that captures exceptions originating from the SDK itself (not your application code). It collects data including the error type, message, stack trace, SDK version, workspace name, and so on. No user or application data is collected.
Error tracking is off by default since v0.2.76. To explicitly disable it in older versions:
export DO_NOT_TRACK=1
Or add to ~/.blaxel/config.yaml:
tracking: false
Where both settings exist, the DO_NOT_TRACK variable takes precedence.
Telemetry
Telemetry, delivered via OpenTelemetry, is controlled by the BL_ENABLE_OPENTELEMETRY environment variable.
When you deploy an agent to Blaxel, the platform automatically injects BL_ENABLE_OPENTELEMETRY=true into the environment.
When developing locally, this environment variable is not set and therefore defaults to false.
To explicitly disable telemetry, override the variable in your Blaxel deployment:
export BL_ENABLE_OPENTELEMETRY=false
For more information, refer to our documentation.
Requirements
- Node.js v18 or later
Contributing
Contributions are welcome! Please feel free to submit a pull request.
License
This project is licensed under the MIT License. See the LICENSE file for details.
Установить Vercel в Claude Desktop, Claude Code, Cursor
unyly install vercelСтавит в Claude Desktop, Claude Code, Cursor и VS Code — сам разбирается с npx, uvx и сборкой из исходников.
Впервые? Поставь CLI: curl -fsSL https://unyly.org/install | sh
Или настроить вручную
Выполни в терминале:
claude mcp add vercel -- npx -y @blaxel/vercelFAQ
Vercel MCP бесплатный?
Да, Vercel MCP бесплатный — установка в пару кликов через Unyly без оплаты.
Нужен ли API-ключ для Vercel?
Нет, Vercel работает без API-ключей и переменных окружения.
Vercel — hosted или self-hosted?
Self-hosted: сервер запускается локально на твоей машине командой из раздела установки.
Как установить Vercel в Claude Desktop, Claude Code или Cursor?
Открой Vercel на unyly.org, выбери вкладку своего клиента (Claude Desktop, Claude Code, Cursor) и нажми Install — конфиг сгенерируется автоматически, без правки JSON.
Похожие MCP
Fetch
Web content fetching and conversion for efficient LLM usage.
AWS KB Retrieval
Retrieval from AWS Knowledge Base using Bedrock Agent Runtime.
автор: modelcontextprotocolSpring AI MCP Server
Provides auto-configuration for setting up an MCP server in Spring Boot applications.
llm-analysis-assistant
A very streamlined mcp client that supports calling and monitoring stdio/sse/streamableHttp, and can also view request responses through the /logs page. It also
автор: xuzexin-hzCompare Vercel with
Не уверен что выбрать?
Найди свой стек за 60 секунд
Автор?
Embed-бейдж для README
Похожее
Все в категории ai
