Skip to content
vanfdavPublic

About

Minimal MTP (Media Transfer Protocol) client over WebUSB, in TypeScript

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

webmtp

Minimal MTP (Media Transfer Protocol / PIMA 15740) client over WebUSB, in TypeScript with no runtime dependencies. Lets a browser page talk directly to an MTP device (e-reader, phone, camera, audio player, …): inspect the device and its storages, walk folders, upload and download files with progress and cancellation, and create, rename, move, copy, and delete objects.

Live demo: MTP file browser — plug in an MTP device and browse it from the page (Chrome/Edge only).

Requirements & platform support

WebUSB needs a secure context (HTTPS or localhost) and a Chromium-based browser (Chrome/Edge); Firefox and Safari do not ship WebUSB.

Whether the browser can claim the MTP interface depends on the OS, because only one driver may own a USB interface at a time:

  • macOS — best supported. There is no built-in MTP driver, so the interface is usually free. If a third-party MTP helper is installed (Android File Transfer, OpenMTP, …), quit it first; some run a background agent that grabs devices the moment they enumerate.
  • Linux — works once the desktop lets go of the device. GNOME/KDE auto-mount MTP devices via GVfs/KIO; unmount the device and, if needed, stop the monitor (gvfs-mtp-volume-monitor). Claiming also requires write access to the USB device node — add a udev rule for your device's vendor id (or use a group like plugdev) rather than running the browser as root.
  • Windows — effectively unsupported. The inbox Windows Portable Devices (WPD) kernel driver claims every MTP interface and Chrome cannot detach it; making WebUSB work means swapping the driver for WinUSB (e.g. with Zadig), which in turn breaks Explorer's normal access to the device. Use macOS or Linux instead.

Usage

import { MtpDevice, requestMtpDevice, ROOT_PARENT } from "@vanfdav/webmtp";

// Must be called from a user gesture (e.g. a click handler).
const usbDevice = await requestMtpDevice();

const mtp = new MtpDevice(usbDevice);
await mtp.open(); // claims the bulk in/out MTP interface
await mtp.openSession();

// Who am I talking to, and is there room?
const device = await mtp.getDeviceInfo();
const [storageId] = await mtp.getStorageIds();
const storage = await mtp.getStorageInfo(storageId);
console.log(`${device.manufacturer} ${device.model}: ${storage.freeSpace} bytes free`);

// mkdir -p, then upload with progress + cancellation.
const folder = await mtp.ensurePath(storageId, "documents/incoming");
const controller = new AbortController();
const bytes = new Uint8Array(await file.arrayBuffer());
const handle = await mtp.sendFile(storageId, folder, file.name, bytes, {
  signal: controller.signal,
  onProgress: (sent, total) => console.log(`${Math.round((100 * sent) / total)}%`),
});

// List, download, reorganize.
const entries = await mtp.listFolder(storageId, folder);
const downloaded = await mtp.getObject(handle, { onProgress: console.log });
await mtp.rename(handle, "renamed.bin");
await mtp.moveObject(handle, storageId, ROOT_PARENT);
await mtp.deleteObject(handle);

await mtp.closeSession();
await mtp.close();

requestMtpDevice() matches both the standard PTP/MTP interface class (6/1/1) and the vendor-specific triple (0xFF/0xFF/0) that many devices — Android phones in MTP mode, Kindles — actually use for MTP. The vendor triple is deliberately loose; picking a non-MTP device just fails cleanly at open()/openSession(). If a device still doesn't show up, pass extra filters (requestMtpDevice([{ vendorId: 0x1949 }])) or fall back to navigator.usb.requestDevice({ filters: [] }) to list everything.

API surface

  • Session & device — open, close, openSession, closeSession, getDeviceInfo (cached), supportsOperation.
  • Storages — getStorageIds, getStorageInfo (capacity, free space, access capability).
  • Browsing — listFolder (names, sizes, and modification times; one bulk GetObjectPropList round-trip when the device supports it, per-object GetObjectInfo fallback otherwise), findChildByName, getObjectHandles, getObjectInfo, getNumObjects.
  • Reading — getObject (whole object, streamed into a preallocated buffer, with progress), getPartialObject (ranged reads).
  • Writing — sendFile (progress, AbortSignal cancellation, embedded modification date), createFolder, ensurePath (mkdir -p).
  • Manipulation — rename, moveObject, copyObject, deleteObject.
  • Datasets — parseDeviceInfo, parseStorageInfo, parseObjectInfo, parseObjectPropList, plus Reader/Writer little-endian codecs (including the 1-byte-length UTF-16LE MTP string encoding).
  • Constants — opcodes, response codes (all named for error messages), object formats, property codes, datatypes, ROOT_PARENT.

Protocol notes (hard-won)

  • TransactionID must start at 0: transactions outside a session (GetDeviceInfo, OpenSession) must use TransactionID 0 per the PTP/MTP spec; some devices reject a non-zero id with Invalid_Parameter. Inside a session ids increment per transaction.
  • Babble avoidance: bulk-in reads always request whole max-packet-size buffers; asking for fewer bytes than the device sends makes Chrome surface a transfer error ("babble").
  • Zero-length packet termination: when a data phase's total length is an exact multiple of the endpoint max packet size, MTP requires a trailing zero-length packet — otherwise the device waits forever.
  • Cancellation is two-level: the AbortSignal stops the host-side chunk loop, then a best-effort PTP Cancel class request (with a Get Device Status poll and endpoint clearHalt) tells the device to discard the transaction.
  • Transfers stream in 1 MiB chunks (a multiple of the packet size, so no premature short packet mid-transfer); downloads preallocate from the container length announced in the first packet.

Limitations

  • Object sizes in the ObjectInfo dataset are u32-limited (4 GiB); true

    4 GiB support would need the SendObjectPropList creation flow.

  • The MTP event (interrupt) endpoint is not consumed; device-side change notifications are ignored.

Development

pnpm install
pnpm test          # unit tests against a scripted fake USB device
pnpm lint          # typecheck src + tests
pnpm build         # emit dist/
pnpm demo:build    # assemble the demo page into _site/ (serve with any static server)

The demo under examples/file-browser/ is what deploys to GitHub Pages on every push to main.

Provenance

This library was designed, written, and tested by Claude (Anthropic's Claude Fable 5 model, driving Claude Code) in collaboration with a human maintainer. The protocol behavior is covered by the unit-test suite against a scripted fake USB device, and the code is exercised against real hardware through the application it was originally built for. Review it with the same care as any other dependency.

Credits

This is an original implementation, but the protocol details were cross-checked against two BSD-2-Clause projects, both gratefully acknowledged:

License

MIT

About

Minimal MTP (Media Transfer Protocol) client over WebUSB, in TypeScript

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages