Python and TypeScript SDKs
Read, write and list files from a Python or TypeScript backend, create mount tickets for sandboxes, and manage filesystems, limits and webhooks.
The SDKs wrap the files API, mount tickets and the
management API for filesystems, their limits,
sessions and webhooks. Files they write are read by mounts
and the other way round. Both SDKs behave the same way. Python uses
snake_case and is synchronous; TypeScript uses camelCase and returns
promises.
This page shows the SDKs only. The guides show each operation for the CLI, Python, TypeScript and curl side by side, and the API reference maps every method to its CLI command and HTTP call. Grants, members and API keys are managed in the console. Every SDK operation also exists in the CLI and the API.
Install
pip install mountable-sdknpm install mountable-sdkPython 3.10 or newer, synchronous, with one dependency (httpx).
TypeScript and JavaScript: an ES module with type declarations for
Node 18 or newer, Bun and Deno. It uses the platform fetch and has no
runtime dependency.
On Deno, run with --allow-env or pass apiKey, so the SDK can read the key.
Configure
The client reads the API key from MOUNTABLE_API_KEY. MOUNTABLE_API_URL
changes the address, which is https://mountable.io by default. Passing
api_key / apiKey or base_url / baseUrl overrides both. Without a key,
creating the client fails with unauthenticated.
Management calls work inside the key's organisation: org_id / orgId,
then MOUNTABLE_ORG, then the key's own organisation, which the client asks
GET /api/v1/me for once. File operations and mount tickets need no
organisation.
For a backend that works on one filesystem, create a key
limited to that filesystem on the console's API
keys page; it gets its grant at once. Open the handle in a mode the key's
grant allows: filesystem() defaults to "rw", so a read-only key needs
"ro". Keep the key on your server. The SDKs are for backends, not browsers.
Read and write files
from mountable_sdk import Mountable, MountableError
client = Mountable()
fs = client.filesystem("fs_…", mode="rw") # sends nothing until first used
info = fs.write("tickets/AB-42.md", "# AB-42\n")
file = fs.read("tickets/AB-42.md") # file.data (bytes), file.info (FileInfo)
page = fs.list("tickets") # page.entries, page.next (pass it as after=)import { Mountable, MountableError } from "mountable-sdk";
const client = new Mountable();
const fs = client.filesystem("fs_…", "rw"); // sends nothing until first used
const info = await fs.write("tickets/AB-42.md", "# AB-42\n");
const file = await fs.read("tickets/AB-42.md"); // file.data (Uint8Array), file.info (FileInfo)
const page = await fs.list("tickets"); // page.entries, page.next (pass it as after)A filesystem handle creates a one-hour token session on its first call and
keeps the token in memory only. A session within 60 seconds of expiring is
replaced before the next call, and a 401 creates a new session and sends
the call once more, so you never handle tokens yourself. Each handle has its
own session: reuse one handle per filesystem rather than opening one per
request. A handle opened with "ro" reads, lists and follows changes but
cannot write.
read and write hold the whole file in memory. For very large files,
mount the filesystem instead.
In Python, Mountable holds a connection pool: call client.close() when you
are done, or use with Mountable() as client:.
Operations
| Python | TypeScript | Does |
|---|---|---|
Mountable(api_key=None, base_url=None) | new Mountable({ apiKey, baseUrl }) | the client; both default to the environment |
client.filesystem(id, mode="rw") | client.filesystem(id, "rw") | a handle on one filesystem, "rw" or "ro" |
fs.write(path, data, *, if_match=None, if_none_match=False) | fs.write(path, data, { ifMatch, ifNoneMatch }) | create or replace the whole file from bytes or a UTF-8 string; returns its FileInfo |
fs.read(path) | fs.read(path) | the file: .data and .info |
fs.delete(path, *, if_match=None) | fs.delete(path, { ifMatch }) | delete a file, a symbolic link or an empty directory |
fs.list(path="", *, after=None, limit=None) | fs.list(path, { after, limit }) | one directory page: .entries and .next |
fs.changes(cursor=None, wait=25) | fs.changes({ cursor, wait }) | changes after a cursor, waiting up to wait seconds (0–25): .events and .cursor; without a cursor, at once, no events and the current cursor |
client.create_mount_ticket(fs_id, mode="rw", max_duration_seconds=None, idempotency_key=None) | client.createMountTicket(fsId, { mode, maxDurationSeconds, idempotencyKey }) | a one-time ticket for a sandbox to mount with |
client.list_mount_sessions(fs_id) | client.listMountSessions(fsId) | the filesystem's live sessions (a key sees its own) |
client.revoke_mount_session(session_id) | client.revokeMountSession(sessionId) | revoke a session; its mount stops |
client.list_filesystems() | client.listFilesystems() | the filesystems the key can see |
client.create_filesystem(name, *, spending_cap_cents=None, mutations_per_minute=None, byte_quota=None, entry_quota=None) | client.createFilesystem(name, { spendingCapCents, mutationsPerMinute, byteQuota, entryQuota }) | create a filesystem, with limits if given |
client.get_filesystem(fs_id) | client.getFilesystem(fsId) | a filesystem and its limits |
client.update_filesystem(fs_id, *, spending_cap_cents, mutations_per_minute, byte_quota, entry_quota) | client.updateFilesystem(fsId, { … }) | change only the limits passed; None / null removes the cap or the rate |
client.filesystem_usage(fs_id) | client.filesystemUsage(fsId) | stored bytes and entries, 30-day traffic, reserved_cents of this month's cap |
client.create_webhook(fs_id, url, *, path_prefix=None) | client.createWebhook(fsId, url, { pathPrefix }) | a webhook; its .secret is returned once |
client.list_webhooks(fs_id) | client.listWebhooks(fsId) | the filesystem's webhooks and their state |
client.rotate_webhook_secret(fs_id, webhook_id) | client.rotateWebhookSecret(fsId, webhookId) | a new .secret, returned once |
client.enable_webhook(fs_id, webhook_id) | client.enableWebhook(fsId, webhookId) | re-enable a webhook disabled after failures |
client.delete_webhook(fs_id, webhook_id) | client.deleteWebhook(fsId, webhookId) | delete a webhook |
client.delete_filesystem(fs_id) | client.deleteFilesystem(fsId) | delete a filesystem at once, with its files, sessions and S3 keys |
client.create_api_key(name, *, expires_in_days=None, filesystem_id=None, mode=None) | client.createApiKey(name, { expiresInDays, filesystemId, mode }) | an API key, limited to one filesystem if given; its .secret is returned once |
client.list_api_keys() / client.revoke_api_key(key_id) | client.listApiKeys() / client.revokeApiKey(keyId) | the organisation's API keys; revoke one |
client.create_s3_key(fs_id, name, *, mode=None, expires_in_days=None) | client.createS3Key(fsId, name, { mode, expiresInDays }) | an S3 key; .access_key_id and .secret_access_key, the secret returned once |
client.list_s3_keys(fs_id) / client.revoke_s3_key(fs_id, access_key_id) | client.listS3Keys(fsId) / client.revokeS3Key(fsId, accessKeyId) | the filesystem's S3 keys; revoke one |
client.list_grants(fs_id) / client.set_grant(fs_id, principal_type, principal_id, mode) / client.delete_grant(fs_id, grant_id) | client.listGrants(fsId) / client.setGrant(fsId, principalType, principalId, mode) / client.deleteGrant(fsId, grantId) | who may use the filesystem; give or change access; remove it |
The client takes an API key (mtbl_…) or a
management key (mtblm_…), and the API
decides by its kind: filesystem creation, limits, deletion, keys and grants
take a management key; tickets, the files API and webhooks take an API key.
The other kind raises management_key_required or api_key_required. The
key, grant and delete_filesystem methods need mountable-sdk 0.4.0 or
later.
A FileInfo has path, type (file, directory or symlink), size,
etag (files only) and modified_at / modifiedAt as a date. Paths are
relative to the filesystem root, and leading and trailing / are ignored.
The SDK percent-encodes each name for you and refuses a . or .. name
with bad_path before sending anything. The rules for paths, sizes and quotas
are those of the files API.
Write without losing changes
Pass the ETag you last saw to write or delete only if nobody changed the
file meanwhile. if_none_match=True / ifNoneMatch: true creates the file
only if nothing exists at the path. A failed condition raises
precondition_failed with the file's current ETag, or none when nothing
exists:
try:
fs.write("tickets/AB-42.md", "# AB-42, edited\n", if_match=info.etag)
except MountableError as e:
if e.code != "precondition_failed":
raise
print("changed meanwhile; now", e.current_etag)try {
await fs.write("tickets/AB-42.md", "# AB-42, edited\n", { ifMatch: info.etag });
} catch (e) {
if (!(e instanceof MountableError) || e.code !== "precondition_failed") throw e;
console.log("changed meanwhile; now", e.currentEtag);
}The check and the write happen in one step for every other writer, mounts included. See conditional writes. Two jobs that share one task file can follow the stale-edit cookbook.
Follow changes
To stay in sync without gaps, take a cursor first, then list or read what you
need, then follow changes from that cursor. When the history behind a cursor
is gone, changes raises cursor_expired: start again the same way.
def resync() -> str:
cursor = fs.changes().cursor # 1. a cursor first
after = None
while True: # 2. then list, every page
page = fs.list("tickets", after=after)
for entry in page.entries:
print(entry.path, entry.etag)
if page.next is None:
return cursor
after = page.next
cursor = resync()
while True: # 3. then follow changes from the cursor
try:
batch = fs.changes(cursor=cursor, wait=25)
except MountableError as e:
if e.code != "cursor_expired":
raise
cursor = resync()
continue
for event in batch.events: # reconcile each path to event.file
print(event.type, event.path, event.file and event.file.etag)
cursor = batch.cursorasync function resync(): Promise<string> {
const { cursor } = await fs.changes(); // 1. a cursor first
let after: string | undefined;
for (;;) {
// 2. then list, every page
const page = await fs.list("tickets", { after });
for (const entry of page.entries) console.log(entry.path, entry.etag);
if (page.next === null) return cursor;
after = page.next;
}
}
let cursor = await resync();
for (;;) {
// 3. then follow changes from the cursor
let batch;
try {
batch = await fs.changes({ cursor, wait: 25 });
} catch (e) {
if (!(e instanceof MountableError) || e.code !== "cursor_expired") throw e;
cursor = await resync();
continue;
}
for (const event of batch.events) console.log(event.type, event.path, event.file?.etag); // reconcile each path
cursor = batch.cursor;
}Each event is created, updated or deleted, with the path's current
file, or none when nothing exists there any more. Treat events as
invalidations, not a history; see following changes.
Hand a sandbox a mount ticket
Your backend creates the ticket with its API key. The sandbox mounts with the ticket only, so the key never enters the sandbox:
ticket = client.create_mount_ticket(
"fs_…", mode="ro", max_duration_seconds=12 * 3600, idempotency_key="job-42"
)
# pass ticket.ticket to the sandbox on stdin:
# mountable mount --ticket-stdin /mnt/mountableconst ticket = await client.createMountTicket("fs_…", {
mode: "ro",
maxDurationSeconds: 12 * 3600,
idempotencyKey: "job-42",
});
// pass ticket.ticket to the sandbox on stdin:
// mountable mount --ticket-stdin /mnt/mountableThe result has the session's id, filesystem_id / filesystemId, mode,
state, expires_at / expiresAt and ticket_expires_at /
ticketExpiresAt. The ticket itself is returned once, in .ticket, and is
left out when the result is printed or inspected. It is single-use and must
be exchanged within five minutes. Keep the id to
revoke the session later. The session lasts 12
hours unless you pass max_duration_seconds: at least 60 seconds, at most
365 days, and never past the key's expiry.
create_mount_ticket is sent once and never retried by the SDK. Pass your own
idempotency key: without one the SDK picks a random key you cannot reuse.
After an unknown outcome, retry with the same key. A replay returns the same
session with no ticket; check its state:
requested: the ticket was lost. Revoke that session and create a new one with a fresh key.activeor later: the ticket was used. Keep the working mount, and use a new key for another mount.409 idempotency_conflict: a concurrent request with the same key created the session first; retry with the same key to get its replay.
These are the retry rules the CLI follows for you. The full flow, from the sandbox side to revoking, is in Mount from a sandbox.
Manage filesystems, limits and webhooks
A backend that serves end users gives each one a filesystem with its own limits, hands its sandboxes tickets, and follows changes with a webhook. The management key provisions; the API key it creates works with the files:
import os
from mountable_sdk import Mountable
with Mountable(api_key=os.environ["MOUNTABLE_MANAGEMENT_KEY"]) as admin:
user_fs = admin.create_filesystem("user-42", spending_cap_cents=500, mutations_per_minute=120)
admin.update_filesystem(user_fs.id, spending_cap_cents=2000) # only what you pass changes
usage = admin.filesystem_usage(user_fs.id)
print(usage.reserved_cents, "of", 2000, usage.currency)
key = admin.create_api_key("user-42", filesystem_id=user_fs.id)
# store key.secret (mtbl_…) for this user's backend work
with Mountable(api_key=key.secret) as client:
hook = client.create_webhook(user_fs.id, "https://example.com/hooks/mountable")
# store hook.id and hook.secret (whsec_…) where your endpoint reads them
for session in client.list_mount_sessions(user_fs.id):
client.revoke_mount_session(session.id)import { Mountable } from "mountable-sdk";
const admin = new Mountable({ apiKey: process.env.MOUNTABLE_MANAGEMENT_KEY });
const userFs = await admin.createFilesystem("user-42", { spendingCapCents: 500, mutationsPerMinute: 120 });
await admin.updateFilesystem(userFs.id, { spendingCapCents: 2000 }); // only what you pass changes
const usage = await admin.filesystemUsage(userFs.id);
console.log(usage.reservedCents, "of", 2000, usage.currency);
const key = await admin.createApiKey("user-42", { filesystemId: userFs.id });
// store key.secret (mtbl_…) for this user's backend work
const client = new Mountable({ apiKey: key.secret! });
const hook = await client.createWebhook(userFs.id, "https://example.com/hooks/mountable");
// store hook.id and hook.secret (whsec_…) where your endpoint reads them
for (const session of await client.listMountSessions(userFs.id)) {
await client.revokeMountSession(session.id);
}The results are FilesystemInfo (id, name, byte_quota, entry_quota,
spending_cap_cents, mutations_per_minute, created_at),
FilesystemUsage, MountSession, Webhook, ApiKey, S3Key and Grant,
with the API's fields and times as dates. A webhook's secret
is set only by create_webhook and rotate_webhook_secret, an API key's
secret only by create_api_key, and an S3 key's secret_access_key only
by create_s3_key; all are left out when the object is printed or
inspected.
What a key may do is the API's rule: creating,
changing and deleting filesystems, keys and grants take a management key;
every webhook call needs an API key with read-write access to the
filesystem; a key lists and revokes only the sessions it created. A refusal raises MountableError with the API's
code, such as management_key_required.
Verify a webhook
Your endpoint checks each webhook delivery against the
webhook's secret before trusting it (mountable-sdk 0.3.0 or later). Pass
the raw body:
import os
from mountable_sdk import MountableError, verify_webhook
secret = os.environ["MOUNTABLE_WEBHOOK_SECRET"]
last_cursor = -1 # below any cursor, even a first resync's "0"; keep it with your data
def receive(headers, body: bytes) -> int:
global last_cursor
try:
message = verify_webhook(secret, headers, body)
except MountableError: # code "invalid_webhook"
return 400
if int(message.cursor) <= last_cursor: # a duplicate or a late message
return 204
if message.type == "files.resync":
... # list what you need again; events after message.cursor follow
for event in message.events: # invalidations, as from fs.changes()
print(event.type, event.path, event.file and event.file.etag)
last_cursor = int(message.cursor)
return 204import { MountableError, verifyWebhook } from "mountable-sdk";
const secret = process.env.MOUNTABLE_WEBHOOK_SECRET!;
let lastCursor = -1n; // below any cursor, even a first resync's "0"; keep it with your data
export async function POST(request: Request): Promise<Response> {
let message;
try {
message = await verifyWebhook(secret, request.headers, await request.text());
} catch (e) {
if (e instanceof MountableError && e.code === "invalid_webhook") return new Response(null, { status: 400 });
throw e;
}
// A duplicate or a late message:
if (BigInt(message.cursor) <= lastCursor) return new Response(null, { status: 204 });
if (message.type === "files.resync") {
// list what you need again; events after message.cursor follow
}
for (const event of message.events) console.log(event.type, event.path, event.file?.etag);
lastCursor = BigInt(message.cursor);
return new Response(null, { status: 204 });
}It returns a WebhookMessage: id (the webhook-id a retry repeats),
type, timestamp, webhook_id / webhookId, filesystem_id /
filesystemId, events as Change and cursor. It accepts either signature a rotation sends, and refuses a
timestamp more than five minutes from now. TypeScript takes Headers or
Node's req.headers, and the body as a string or bytes.
Errors and retries
Every failure raises (Python) or rejects with (TypeScript) MountableError:
| Field | Holds |
|---|---|
status | the HTTP status, or none when no answer arrived (a network failure, or a check the SDK made before sending) |
code | the API's stable code, such as not_found, read_only, rate_limited or quota_exceeded, as listed in the files API errors; and, when a session or ticket is created, the API errors such as no_grant or payment_required |
message | a readable description |
current_etag / currentEtag | for precondition_failed: the file's ETag now |
retry_after / retryAfter | seconds to wait, from Retry-After or the answer |
The SDK adds codes of its own: network_error when there is no answer,
api_error for an error answer without a code, invalid_request when the
API refuses the request's fields or the SDK refuses an empty, . or .. ID
before sending, org_required when a management call cannot tell the key's
organisation, and invalid_webhook when verify_webhook refuses a
delivery. API and management keys, tokens and webhook secrets never appear
in errors, or when a client or handle is printed.
- Only a
2xxanswer is a success. Redirects are not followed. read,listandchangesare sent once more after a network failure, and so are the management reads,revoke_mount_session,enable_webhook,revoke_api_key,revoke_s3_keyandset_grant.writeanddeleteare never retried: after a timeout their outcome is unknown. Read the file, or use a conditional write, before trying again.create_filesystem,update_filesystem,delete_filesystem,create_webhook,rotate_webhook_secret,delete_webhook,create_api_key,create_s3_keyanddelete_grantare never retried. After an unknown outcome, list or get before trying again: names need not be unique, each webhook call makes a new secret, and a repeated delete answersnot_found.- HTTP errors other than the
401session refresh are not retried. For429, waitretry_afterseconds. - A request fails with
network_errorafter 60 seconds without an answer;changeswaits 60 seconds pluswait. In TypeScript, the time to send a write's body counts toward those 60 seconds, so very large writes need a fast connection.
Source
Both SDKs are open source under Apache-2.0 in
writeitai/mountable.
The behaviour they share is tested case by case, as listed in
the SDK contract.
Packages: mountable-sdk on PyPI
and mountable-sdk on npm.