Skip to main content

Public addon APIs

Import another @bedrock-core addon's public API like a library while its code and authoritative state run in its own behavior pack. The provider build generates typed JavaScript clients using the existing RPC, state and event services. Consumers bundle those clients through normal package imports; Builder is optional for consumers.

Export the provider's API​

Keep each public API entry inside the behavior pack that owns it. Expose that entry and its authored manifest through package.json:

package.json (fragment)
{
"name": "@studio/economy",
"exports": {
".": "./packs/BP/scripts/api/index.ts",
"./values": "./packs/BP/scripts/api/values.ts",
"./manifest.json": "./packs/BP/manifest.json"
}
}

The manifest's namespace and UUID identify the owning scripted pack. Importing the published addon's manifest.json returns immutable authored metadata.

Public callable signatures return promises, including operations that complete immediately in the provider. This gives provider and consumer the same TypeScript signature:

packs/BP/scripts/api/index.ts
import { authorize } from '@bedrock-core/server';
import { balances, playerOf } from '../storage';

export const API = {
async getBalance(playerId: string, actorId?: string): Promise<number> {
authorize({ entity: playerId }, actorId, 'read');

return balances.for(playerOf(playerId)).get()?.gold ?? 0;
},
};

Register the exported implementation object alongside the addon's other declarations:

packs/BP/scripts/main.ts
import { core, registerModule } from '@bedrock-core/server';
import { API } from './api';
import manifest from '../manifest.json';

const { economy } = core.register({ manifest, economy: registerModule(API) });

Builder associates checked metadata with exported objects before the script entry runs. registerModule(API) publishes the owning public entry through that Runtime and returns the original, writable implementation as economy. Register the exported object itself; a separately constructed copy has no associated public entry. Choose a registration key that does not replace a Runtime member; core.api remains the API facade. Several public entries can use separate declarations. Stopping Core withdraws the installed entries, and failed installation rolls back partial publication. Exporting an object alone does not publish it.

API modules initialize before Core registration. Access registered services inside API methods or declaration installers. Install prerequisite declarations before the API declaration when its initial snapshots need those services.

The API object can group async functions, observables, signals, nested APIs and shared value constructors. Export interfaces and types normally from the same file. Value classes retain their explicit codecs and shared executable entries, described below. The generated package exposes read-only consumer handles while the provider keeps its writable sources.

Keep input validation, authorization and storage access in the provider. Builder checks supported export types at build time; providers validate actual inputs and permissions when called. Imported functions do not transfer authority to the consumer.

Publish the API package​

Build the provider normally. When its package exports public entries alongside an owning manifest, Builder writes a publishable package to dist/api. The package contains .d.ts declarations, executable client bindings, explicit export metadata and owner manifests. Provider functions, storage and class-backed object implementations remain in the behavior pack. Intentionally shared value classes and codecs are included as public code.

Publish or distribute that directory through npm, a package archive, a Git repository or a local package source. For example, create a local archive without running package scripts:

npm pack ./dist/api --ignore-scripts

The package version uses package.json when supplied, otherwise the primary API owner's manifest version. The owner's UUID and native version remain manifest-owned. Runtime dependencies are ordinary package dependencies, allowing compatible API packages to share the consumer's installed runtime modules.

Set the profile's api option to change the destination or disable API publication. API packages and native packs publish in one transaction; build or publication failures retain the prior outputs. Warm builds reuse checked package output, and watch mode ignores generated package files.

Import an addon API​

In Builder projects, install the addon package and declare it once in the consumer's authored manifest:

manifest.json (fragment)
{
"dependencies": [{ "module_name": "@studio/economy" }]
}

The declaration supplies the native pack requirement and Core namespace. Consumer code uses ordinary named or namespace imports:

import { API } from '@studio/economy';
import * as economy from '@studio/economy';

const ownBalance = await API.getBalance(player.id, player.id);
const sameBalance = await economy.API.getBalance(player.id, player.id);

For published API packages, Builder reads explicit owner metadata and bundles the ready client entry. It does not inspect or evaluate provider implementation code. Required entries supply native pack requirements; optional entries remain runtime checks. Exported package subpaths work the same way. Types and interfaces remain compile-time-only imports.

Local authored addon packages also work before publication. Builder checks their exported types and generates equivalent bindings without evaluating their implementations.

For local consumer type-checking against generated read-only views, install the provider's generated dist/api package. Importing its authored source package exposes the implementation's original TypeScript types.

Ordinary helper libraries use package dependencies and normal bundling. A module_name declaration identifies an external addon or native Minecraft API.

Import with another bundler​

Install the published package, import its API normally and bundle the package together with its runtime dependencies. Keep only native Minecraft modules external. For esbuild:

await build({
entryPoints: ['src/main.ts'],
outfile: 'packs/BP/scripts/main.js',
bundle: true,
format: 'esm',
platform: 'neutral',
external: ['@minecraft/*'],
});

Declare the provider's behavior-pack header.uuid and header.version in the consumer's native manifest. Include the native Minecraft module requirements used by the bundled client. An API package is bundled JavaScript; a native pack dependency does not expose its exports as a native scripting module.

The consumer needs no core.register() call. API use lazily starts a shared client endpoint using the existing Sync services. If Core is registered in the same bundle, the client uses that connection. API-only endpoints do not register an addon and include no persistence or translations. Shared-value and metadata-only imports do not initialize transport.

Late Core registration routes new calls through Core. Calls already in progress, including discovery waits and call-scoped callbacks, finish on the API-only endpoint within their existing deadlines; that endpoint stops after its calls settle. Retained class-backed handles preserve identity, forwarding, state and signal subscriptions across registration. Provider disposal or replacement still invalidates those handles. Providing public APIs or new class-backed API objects requires Core registration.

Packages with several behavior packs​

Export each pack's manifest alongside its API entry. Builder selects the closest exported manifest above the API's runtime entry file:

package.json (fragment)
{
"name": "@studio/addons",
"exports": {
".": "./packs/economy/scripts/api/index.ts",
"./manifest.json": "./packs/economy/manifest.json",
"./stats": "./packs/stats/scripts/api/index.ts",
"./stats/manifest.json": "./packs/stats/manifest.json"
}
}

The Economy pack binds @studio/addons; the Stats pack binds @studio/addons/stats. Each registers its exported API object with its own manifest and uses a different namespace. API entries in another pack must expose that pack's manifest rather than inheriting an outer pack's ownership.

Consumers declare the entry for each pack they use:

Consumer manifest.json (fragment)
{
"dependencies": [{ "module_name": "@studio/addons" }],
"optionalDependencies": [{ "module_name": "@studio/addons/stats" }]
}

Each record resolves its owner's UUID, version and Core namespace. Required entries create native pack requirements; optional entries do not. A root dependency also covers subpaths owned by that same BP. A subpath owned by another BP needs its own dependency, as Stats does here. Builder reports an undeclared cross-pack import before compiling the consumer.

Share state and events​

Place observable and signal sources directly in the registered API object:

packs/BP/scripts/api/index.ts (fragment)
import { observable, signal } from '@bedrock-core/observable';

export const API = {
currency: observable('emerald'),
balanceChanged: signal<{ playerId: string; gold: number }>(),
};

The provider calls API.currency.set(...) and API.balanceChanged.emit(...). Generated consumer declarations expose ReadonlyObservable and Signal views, without setters or emitters. Consumer state can be undefined while its provider or snapshot is unavailable. Explicit read-only views remain supported.

import { API } from '@studio/economy';

const current = API.currency.get();
const stopState = API.currency.subscribe((next, previous) => {
updateCurrency(next, previous);
});
const stopEvents = API.balanceChanged.subscribe(({ playerId, gold }) => {
updateBalance(playerId, gold);
});

stopState();
stopEvents();

State reads use the synchronized local snapshot. Events have no replay: subscribe before the event occurs. Unsubscribe functions are idempotent, and stopping the consuming runtime releases its subscriptions. Public signal exports use Signal<T> and return cleanup functions. Convert a native event source with toSignal before exporting it. Native filter options are selected during conversion in the provider; imported subscriptions do not accept remote filters.

Export objects and constants​

Nested plain objects may group supported methods and handles. Static JSON-safe constants are copied into immutable client metadata:

export const economyInfo = {
name: 'Economy',
currency: { precision: 0 },
} as const;

Use a state handle for values that change. Builder reads constant initializers statically; it does not execute provider functions to obtain values.

Share value classes​

Give a value class a static readonly codec with synchronous encode and decode functions. The encoded result must be defined, supported application data; decode validates that data and reconstructs a local instance:

packs/BP/scripts/api/values.ts
import type { Codec } from '@bedrock-core/server-runtime';

export class Money {
static readonly codec: Codec<Money, number> = {
encode: value => value.gold,
decode: gold => {
if (!Number.isFinite(gold)) { throw new TypeError('Invalid gold amount'); }

return new Money(gold);
},
};

constructor(readonly gold: number) {}

format(): string { return `${this.gold} gold`; }
}

Expose this file as a separate package entry, such as ./values above. Keep that entry and its runtime imports engine-free: classes, codecs and data can run in both addons and during build-time evaluation. Type-only Runtime imports erase normally. Keep remote functions, observable handles, signal sources and provider initialization in the API entry. You can reexport the class there:

packs/BP/scripts/api/index.ts (fragment)
import { Money } from './values';

export { Money } from './values';

export async function double(price: Money): Promise<Money> {
return new Money(price.gold * 2);
}

Consumers import Money from either the API or its shared entry. Its constructor and methods execute locally; API calls encode the value and reconstruct it using the receiving addon's copy of the class. Provider code receives its own Money instances, so instanceof Money works in each addon. These values have no shared object identity or live connection to the original instance.

Builder emits adaptations where declared types require codecs or references, including nested objects, arrays, tuples, maps, sets, state and event payloads. The surrounding supported data graph retains its structure. Codec outputs are copied as data without recursively applying other class codecs. Nullable values remain distinct even when a codec encodes its instance as null. Keep classes used in state and events immutable: imported snapshots are frozen, and repeated reads return the same decoded snapshot until its source changes.

Published packages must include the shared executable class module and its declarations, alongside the API declarations. Classes from ordinary shared library dependencies can use the same contract when their implementation is exposed through an explicit package entry.

Pass async callbacks​

An API input can include an async callback. Builder supplies the reverse RPC automatically, and the callback runs in the calling addon with its captured local values:

Provider API
import { Money } from './values';

export async function approveQuote(
price: Money,
confirm: (price: Money) => Promise<boolean>,
): Promise<Money | null> {
return await confirm(price) ? price : null;
}
Consumer
import { approveQuote, Money } from '@studio/economy';

const budget = 20;
const accepted = await approveQuote(
new Money(12),
async price => price.gold <= budget,
);

console.warn(accepted?.format() ?? 'Quote declined');

Callback arguments and results support the same application data, declared value classes and supported references as normal calls. Callback exceptions reject the provider's awaited callback; uncaught provider errors reject the original caller. Providers must validate their own authoritative decisions rather than trusting a consumer callback.

Callbacks belong to the containing API call. Await them before returning. Completion, failure, timeout or runtime shutdown releases their temporary handlers; a retained callback rejects after its call ends. Callbacks do not extend the outer RPC timeout. Use exported signals for ongoing notifications. Callbacks must return promises and cannot accept or return other callbacks. Returning a callback from an API is unsupported.

Pass Minecraft entity references​

Use the official Entity and Player types directly in public signatures, including callback arguments, results, state and signal payloads. Builder recognizes these types and Runtime transfers their IDs, then resolves native handles in the receiving addon. These types need no authored codec.

Nested objects can combine entity references with the same async methods, observable state, signals and value classes:

Public API declaration
import type { Entity, Player } from '@minecraft/server';
import type { ReadonlyObservable, Signal } from '@bedrock-core/observable';
import type { Money } from './values';

export interface WorldApi {
readonly afterEvents: {
readonly entityDropItem: Signal<{
entityId: string;
entity: Entity | undefined;
itemTypeId: string;
price: Money;
}>;
};
readonly timeOfDay: ReadonlyObservable<number | undefined>;
getPlayer(id: string): Promise<Player | undefined>;
track(entity: Entity): Promise<void>;
quote(
entity: Entity,
price: Money,
approve: (entity: Entity, price: Money) => Promise<Money>,
): Promise<{ entity: Entity; price: Money }>;
}

export declare const world: WorldApi;

The provider implements world as nested plain objects and exposes public Signal and ReadonlyObservable views. Given an existing entity handle, consumers keep normal imports and inferred callback types:

import { Money, world } from '@studio/economy';

const stop = world.afterEvents.entityDropItem.subscribe(event => {
console.warn(`${event.entityId}: ${event.price.format()}`);
if (event.entity?.isValid) { event.entity.addTag('observed'); }
});

const quote = await world.quote(entity, new Money(10), async (reference, price) => {
return new Money(reference.hasTag('discount') ? price.gold / 2 : price.gold);
});

stop();

Entity lookup uses the current world. A required argument that no longer resolves rejects its API call before the provider function runs. An unavailable required result rejects the receiving call. Nullable references resolve to the declared missing value, undefined or null; when both are allowed, absence uses undefined. Invalid reference data and non-player entities supplied as Player are rejected. Providers still validate their own inputs and permissions.

Signals can arrive after an entity disappears. Keep a stable entityId alongside an optional handle when the event remains useful after removal. Snapshot references resolve when that snapshot is decoded; unchanged snapshots retain their decoded identity. Retained native handles follow Minecraft's isValid lifecycle. Copied event/state containers and value classes are frozen while native handles remain usable. Event subscriptions stay active until unsubscribed or the consuming Runtime stops.

Entity, Player, Dimension and Block use built-in reference adapters. Addon-owned API objects use instance-bound references with async methods and ordinary observable/signal views. See reference transport for object ownership, disposal and the Minecraft coverage matrix. Simulated-player GameTests must load @minecraft/server-gametest in each participating pack so its native class bindings are available.

Availability and errors​

Importing an API is safe before core.register(). State reads return undefined until a snapshot is available. Runtime clients can use their API-only endpoint before Core registration. Build-time imports remain inert, and invoking calls during source evaluation rejects. Providers publish their implementations through registerModule(API) in the owning Runtime's normal declaration lifecycle.

The addon registry derives identity from each registered manifest and advertises the API export names that are ready. Calls wait up to 100 ticks for the requested export, then use RPC's response timeout of 100 ticks. Missing methods and provider exceptions reject the caller's promise through RPC. TypeScript signatures stay in build-time declarations.

Place optional addons in optionalDependencies using the same module_name form. Their API declarations can be installed and imported while the behavior pack is absent. Calls reject when the provider is unavailable; state reads return undefined. Combine configuration and imported state with observables for optional integrations. Use the registry when presence itself is part of the behavior.

Withdrawing a public export removes its registry advertisement, RPC handlers, state and event subscriptions. Discovery detects addon disappearance or replacement and Sync invalidates its snapshots and pending RPC calls. The discovery timeout for an absent addon is 320 ticks; packets from an older running instance are ignored. Stopping the consumer rejects its pending calls and releases listeners, including subscriptions queued before registration.

Library services that select owners dynamically use core.api.createModule(ownerNamespace, localApiObject) through the registered runtime. The implementation object supplies Builder's generated contract; the namespace selects the remote owner. The returned view does not publish or install the local implementation. Navigation and catalog discovery select namespaces from the registry internally.

Library module declarations​

A reusable library can create a separate API object for each Runtime. Export a concrete factory returning ModuleDeclaration<T> and return registerModule(API) from its implementation:

src/api.ts
import { registerModule, type ModuleDeclaration } from '@bedrock-core/server-runtime';
import type { ReadonlyObservable } from '@bedrock-core/observable';

export interface LibraryApi {
readonly count: ReadonlyObservable<number | undefined>;
open(id: string): Promise<boolean>;
}

export function createLibraryApi(
count: ReadonlyObservable<number | undefined>,
open: LibraryApi['open'],
): ModuleDeclaration<LibraryApi> {
const API: LibraryApi = { count, open };

return registerModule(API);
}

Generate the library's checked wrapper before packaging it:

npx bc-builder api-library src/api.ts src/api.generated.ts

Import the factory from api.generated.ts inside the library. The wrapper attaches metadata to every new implementation without evaluating a provider at build time. It uses the same supported public types and codecs as addon API generation. The protocol identifier includes a fingerprint of the public contract, so incompatible signatures use distinct identifiers. Factories need one concrete, non-generic signature.

Install the returned declaration through core.register() or core.install(). The installed accessor is the declaration's original api object. Use core.api.createModule(ownerNamespace, declaration.api) to address another Runtime using the same checked library contract. This view does not publish the local declaration.

Ship the generated wrapper with the library. Consumers can use their ordinary bundler without a provider transform. Regenerate it when its public types or codec contracts change. The adjacent JSON receipt records the output hash and source input hashes; libraries can check owned inputs during their build. A receipt alone does not recheck changed dependency types.

Limits​

Public calls, state and event payloads support primitives, arrays, plain data objects, Map, Set, Date, RegExp, ArrayBuffer, typed arrays and DataView. They also support value classes with explicit codecs, supported native references and addon-owned API object references. API inputs can include call-scoped async callbacks. Builder rejects unsupported public types; providers validate actual inputs and permissions.

Structured data preserves undefined object fields and array entries, sparse array holes, bigint, non-finite numbers and negative zero. Supported data graphs retain shared references and cycles within one transmitted value. Generated calls also preserve argument positions, including explicit trailing undefined arguments, so default parameters, rest arguments and argument count work for local and remote calls. Structured values require protocol v3 support in the receiving Runtime; Sync data values lists supported built-ins and copy semantics.

These are copied values rather than shared JavaScript objects. State and event containers are read-only snapshots; function results can be used as local data. Symbols, weak collections, arbitrary functions and unadapted class instances are unsupported.

Synchronous callable exports and mutable computed constants cannot be public API methods or metadata. Declare async operations, read-only handles or static immutable values instead. API objects must have a statically describable shape. Union alternatives must use the same codec, reference or callback mapping, apart from nullable alternatives. Use explicit package export subpaths; wildcard exports are unsupported.

Next steps​