Skip to content
MCWSLoader edited this page Nov 14, 2026 · 2 revisions

API Reference

MCWSLoader exposes several programmatic APIs for Mod development and a REST API for the WebUI.


Table of Contents


Mod System

TypeScript

The core (lib/, web/server.ts, ws.ts, main.ts) is strict TypeScript. Bundled Mods are TypeScript too and are hot-loaded from mods/ through tsx without a build step. Import the runtime base class for typed injected dependencies (this.Command, this.Current, this.client, ...):

import ModBase from "../../lib/modbase.js";

export default class MyMod extends ModBase {
	constructor(client) {
		super();
		this.client = client;
	}

	onCommand() {
		return { normal: [this.Command.create("x", "demo").setFunc(() => {})] };
	}
}

Run npm run typecheck / npm run typecheck:mods for the backend and Mods, and cd web/frontend && npm run typecheck for the Vue frontend.

Injected API

Every Mod (client and server) receives the same core API, injected onto the instance after construction (and mirrored onto the class as statics):

Property Description
this.modName Mod name from manifest.json
this.config Global config.json merged with the Mod's own config.json
this.storage Per-Mod key/value store (get/set/has/delete/clear/keys/values/entries)
this.logger Logger prefixed with Client:<name> / Server:<name>
this.emit/on/off Event bus (in-process for client Mods, global for server Mods)
this.sapi.on/off/send/exists Client Mods only: SAPI message bridge
this.client Client Mods only: the WebSocket connection
this.Command Command builder (see Command Framework)
this.Current Global runtime state (client, clientMods, properties)
this.PermissionManager Permission queries (query/add/remove/get/set)
this.ServerModManager / this.ClientModManager Manager classes
this.reloadConfig Re-read config.json into the shared config object
this.fs, this.path, this.fileURLToPath, this.exec, this.readline Node / terminal helpers

Client Mods also get client.<modName> pointing at their instance. Only the members relevant to a Mod are injected; server Mods do not receive client or sapi.

ClientModManager

Manages client-side Mods. One instance per WebSocket connection.

Static Properties:

Property Type Description
ClientModManager.loadedMod Object<string, Function> Map of loaded Mod class definitions

Static Methods:

Method Returns Description
ClientModManager.load() Promise<void> Scan mods/ manifests and register every enabled client Mod
ClientModManager.syncClasses() Promise<void> Re-sync the class registry after an enable/disable/import (drops removed Mods, imports new ones)
ClientModManager.reloadAllClients() Promise<{ success: string[], failed: string[] }> Sync classes, then reload/instantiate Mods on every connected client

Instance Properties:

Property Type Description
clientMod.client Object The WebSocket connection
clientMod.sapi SAPIMessageHandler Shared SAPI polling handler
clientMod.modInstances Object<string, Object> Map of Mod name → instance
clientMod.commands { normal: [], user: [], op: [], owner: [] } Commands grouped by permission level

Instance Methods:

Method Returns Description
clientMod.reload(name) Promise<{ success: boolean, message: string }> Reload a single client Mod by name
clientMod.reloadAll() Promise<{ success: string[], failed: string[] }> Instantiate newly registered Mods, unload removed ones, reload the rest
clientMod.unload(name) boolean Destroy one Mod instance, remove its subscriptions/SAPI handlers and refresh the command index
clientMod.getMod(name) Object | null Get a Mod instance by name
clientMod.getAllMods() Object<string, Object> Get all Mod instances
clientMod.callModMethod(method, ...args) void Call a method on all Mod instances
clientMod.destroy() void Destroy all Mod instances and clean up

Mod Lifecycle:

A client Mod class receives the WebSocket client in its constructor. Infrastructure is injected after construction:

class MyMod {
	constructor(client) {
		this.client = client; // WebSocket connection
	}
	// Injected after construction:
	// this.modName, this.config, this.storage, this.logger
	// this.emit(event, data), this.on(event, callback), this.off(event)
	// this.sapi.on(type, cb), this.sapi.off(type), this.sapi.send(type, data)

	onStart() { /* called after injection */ }
	onDestroy() { /* called on unload */ }
	onPocket(data) { /* called on every WebSocket message */ }

	commands() {
		return {
			normal: [ /* commands */ ],
			user: [ /* commands */ ],
			op: [ /* commands */ ],
			owner: [ /* commands */ ]
		};
	}
}

Command Framework

Command is injected into every Mod instance (also available as a static on the class).

Method Returns Description
Command.create(name, description) Command Create a command definition (name without prefix)
.addString/.addInteger/.addFloat/.addBoolean/.addEnum(values) Command Add a required parameter (chainable)
.addOptionalString/.addOptionalInteger/.addOptionalFloat/.addOptionalBoolean/.addOptionalEnum(values) Command Add an optional parameter
.setFunc((sender, ...args) => ...) Command Handler; a returned Promise is awaited for errors
.matches(tokens) boolean Whether Command.parseArgs(text) targets this command
.execute(commander, text, onError?) { status, message } | false Parse and run; false when the name does not match
.executeTokens(commander, tokens, onError?) { status, message } | false Run with pre-parsed tokens; onError receives async handler rejections
Command.parseArgs(text) string[] Split text into tokens, honoring double-quoted arguments

commands() (or onCommand()) may return any of normal, user, op, owner. At dispatch time the chat line is parsed once, then only the matching command runs, gated by the sender's permission level. Duplicate command names are logged and ignored (the first registration wins). The prefix comes from config.commandPrefix and must be non-empty.


ServerModManager

Singleton manager for server-side Mods (one per server, not per connection).

Static Properties:

Property Type Description
ServerModManager.loadedMod Object<string, Function> Map of loaded Mod class definitions
ServerModManager.modInstances Object<string, Object> Map of Mod name → instance

Static Methods:

Method Returns Description
ServerModManager.load() Promise<void> Load all server Mods from config.mods.server
ServerModManager.syncClasses() Promise<void> Re-sync the class registry after an enable/disable/import
ServerModManager.reloadAll() Promise<{ success: string[], failed: string[] }> Sync classes, instantiate new Mods, unload removed ones, reload the rest, then re-collect terminal commands
ServerModManager.getLoadedModNames() string[] Get all loaded Mod names
ServerModManager.destroy() void Destroy all server Mods

Instance methods are available through ServerModManager._inst(): reload(name), unload(name), getMod(name), getAllMods().

Server Mod Lifecycle:

Server Mods are singletons. Infrastructure is injected onto both the instance and the class:

class MyServerMod {
	constructor() { /* no client arg */ }

	// Injected:
	// this.modName, this.config, this.storage, this.logger
	// this.emit(event, data) — sends to Current.client's client Mods
	// this.on(event, cb) — listens on Current.client events
	// this.onAll(event, cb) — listens on ALL clients via EventBus
	// this.off(event)
	// this.sapi — bound to Current.client's SAPI polling

	onStart() { /* called on load */ }
	onDestroy() { /* called on unload */ }
	onClientConnect(client, isMainClient) { /* new client connected */ }
	onClientDisconnect(client, isMainClient) { /* client disconnected */ }
	onMainClientConnect(client) { /* main client connected */ }
	onMainClientDisconnect() { /* main client disconnected */ }
	onMainClientSwitch(oldClient, newClient) { /* main client switched */ }
	onMessage(client, data) { /* raw WebSocket message from any client */ }
}

Client Utils

The Utils class (lib/utils.ts) is bound to each WebSocket connection as client.utils. Methods are also directly available on the client object.

Command Methods

Method Returns Description
client.sendCommand(command) Promise<string | undefined> Send command silently (no error)
client.runCommand(command, timeout?) Promise<Object> Execute command and return response (default 10s timeout)

Subscription Methods

Method Returns Description
client.subscribe(event, callback?, owner?) boolean Subscribe to a Bedrock event
client.unsubscribe(event) void Unsubscribe from an event

Messaging Methods

Method Returns Description
client.tell(msg, target?, isPrefix?) void Send tellraw message (OP required)
client.tellAll(msg) void Broadcast message to all players

Query Methods

Method Returns Description
client.getLocation(target?) Promise<{ x, y, z, dimension } | null> Get player location
client.getPosition(target?) Promise<{ x, y, z } | null> Get player position
client.getDimension(target?) Promise<string | null> Get player dimension
client.getInventory(target?) Promise<Object | undefined> Get player inventory
client.getLocalPlayer() Promise<string | undefined> Get local player name via getlocalplayername
client.getPermission() number Get permission level (0–3)
client.closechat() Promise<boolean> Close the chat window

Event Bus

Global pub/sub for inter-Mod communication (lib/mods.ts → eventBus).

Method Description
eventBus.on(event, modName, callback) Subscribe to an event
eventBus.off(event, modName) Unsubscribe from an event
eventBus.emit(event, data, excludeMod?) Publish an event (optionally exclude one Mod)
eventBus.clearMod(modName) Remove all subscriptions for a Mod
eventBus.clear() Remove all subscriptions

Storage

Per-Mod persistent key-value storage (lib/mods.ts → StorageManager).

Method Description
StorageManager.getStore(modName) Get (or create) a Mod's storage instance

ModStorage instance:

Method Returns Description
storage.get(key, default?) * Get a value
storage.set(key, value) void Set a value
storage.delete(key) boolean Delete a key
storage.has(key) boolean Check if key exists
storage.clear() void Clear all data
storage.keys() string[] Get all keys
storage.values() *[] Get all values
storage.entries() [string, *][] Get all entries

Permission Manager

File-based permission system (lib/permission.ts).

Method Returns Description
PermissionManager.get(object?) Promise<Object | Array> Get full config or specific group ("all", "owner", "op", "user", "blocker")
PermissionManager.set(newPermission) Promise<true | Error> Overwrite entire permission config
PermissionManager.add(group, value) Promise<true | Error> Add a player to a group ("op", "user", "blocker")
PermissionManager.remove(group, value) Promise<true | Error> Remove a player from a group
PermissionManager.query(queried) Promise<number | Error> Query permission level: -1=blocker, 0=normal, 1=user, 2=op, 3=owner

Current State

Global runtime state (lib/current.ts).

Property/Method Type Description
Current.client Object | null Current main client WebSocket connection
Current.clientMods Map<Object, ClientModManager> All connected clients → their Mod managers
Current.properties Object Runtime key-value properties
Current.has(key) boolean Check if a property exists
Current.get(key) * Get a property value
Current.set(key, value) * Set a property value
Current.reset() void Reset all state (called on main client disconnect)

HTTP API

REST API served by the WebUI backend. All endpoints require X-Auth-Token header except /api/login. Cross-origin browser clients are rejected unless their origin is listed in web.ui.allowedOrigins; same-origin WebUI requests need no extra configuration.

Authentication

Method Endpoint Auth Description
POST /api/login No Login with { password }, returns { ok, token }

Status

Method Endpoint Description
GET /api/status Server status, connections, mods, SAPI state

Auth

Method Endpoint Description
POST /api/auth/change-password Change the WebUI password ({ oldPassword, newPassword }). The startup temporary password is accepted as oldPassword. Invalidates all sessions.
POST /api/logout Destroy the current session token server-side

Configuration

Method Endpoint Description
GET /api/config Get config. Secrets are masked: web.auth.passwordHash/salt become "", ai.options.apiKey becomes "***".
PUT /api/config Save config to disk and reload. Masked secrets sent back unchanged are preserved (not overwritten with the placeholder).

Permissions

Method Endpoint Description
GET /api/permissions Get full permission config
PUT /api/permissions Overwrite permission config
POST /api/permissions/:group/:player Add player to group (owner, op, user, blocker)
DELETE /api/permissions/:group/:player Remove player from group

Mods

Method Endpoint Description
GET /api/mods List all loaded Mods
POST /api/mods/reload-all Reload config + all Mods
POST /api/mods/import Import a Mod archive (multipart/form-data, field file, .wsmod/.zip). Add ?overwrite=1 to overwrite an existing Mod. Responses: { ok: true, name, folder }; 409 + code: "CONFLICT" with { name, folder } when the Mod already exists and overwrite was not set; 400 + code: "INVALID_FORMAT" for a bad archive; 500 with code: "DEPENDENCY_FAILED" / "INSTALL_FAILED" on install failure.
POST /api/mods/:name/delete Delete a Mod (folder + mods_config.json entry)
POST /api/mods/:name/enable Enable a Mod
POST /api/mods/:name/disable Disable a Mod
POST /api/mods/:name/reload Reload a single Mod
GET /api/mods/:name/config Get Mod config
PUT /api/mods/:name/config Save Mod config
GET /api/mods/:name/manifest Get Mod manifest
GET /api/mods/:name/readme Get Mod README

Commands

Method Endpoint Description
GET /api/commands List all registered commands
POST /api/command Execute a Bedrock command ({ command })

Clients

Method Endpoint Description
GET /api/clients List connected clients (includes localPlayerName, trusted)
POST /api/clients/:id/tell Send tell to a client ({ message })
POST /api/clients/:id/approve Approve a pending WebSocket client (trusted messages only)
POST /api/clients/:id/revoke Revoke trust; the client can no longer send commands
POST /api/clients/:id/set-main Set a client as main (rejected while pending)
POST /api/clients/:id/disconnect Disconnect a client

Logs

Method Endpoint Description
GET /api/logs?name=app&lines=200 Read log file

Chat

Method Endpoint Description
GET /api/chat Read last 100 chat lines
POST /api/chat Send chat via main client ({ message })

System

Method Endpoint Description
GET /api/system/process Node.js process info (pid, memory, uptime)
POST /api/system/kill Kill the server process
POST /api/system/restart Gracefully restart the server

Update

Method Endpoint Description
GET /api/update/check Check for latest version on GitHub
GET /api/update/tags List available release versions
POST /api/update/do Update to latest version
POST /api/update/rollback Rollback to a specific version ({ tag })

Clone this wiki locally