Developing on Mycel
Mycel ships as one universal jar for Fabric, Forge, and NeoForge alike, distributed through JitPack. One jar per Minecraft line: the plain release tag (for example 1.6.1) is for 26.3, and 1.6.1-26.2 and 1.6.1-26.1 are for the older lines. A commit hash or main-SNAPSHOT also work for 26.3. The pattern below is exactly how InstantXP, AutoBlockRefiller, and Better Librarians are built; all three repos are small enough to read end to end.
Depending on Mycel
repositories {
mavenCentral()
maven { url 'https://jitpack.io' }
}
dependencies {
// Same line on Fabric, Forge and NeoForge. Minecraft 26.x is not
// obfuscated, so Loom has no modImplementation.
implementation 'com.github.MyCelium-GG:MyCel-Lib:1.6.1'
// For Minecraft 26.2 or 26.1, add the line to the tag:
// implementation 'com.github.MyCelium-GG:MyCel-Lib:1.6.1-26.2'
}
Minimal integration
Metadata, a config value, and an event subscription. File IO, loader events, and diagnostics come from Mycel:
public static final ModMetadata META =
ModMetadata.builder("mymod", "My Mod", "1.0.0").build();
public static final ConfigValue<Boolean> ENABLED;
public static final MycelConfig CONFIG;
public static void init() { // called from each loader entrypoint
Mycel.initialize();
Mycel.registerMod(META);
ConfigBuilder builder = Mycel.config(META);
ENABLED = builder.booleanValue("enabled", true, "Whether the feature runs.");
CONFIG = builder.build(); // loads config/mymod.json
MycelEvents.onPlayerJoin(event -> {
if (Mycel.isEnabled("mymod") && ENABLED.get()) {
PlayerUtil.sendMessage(event.player(), Component.literal("Hi!"));
}
});
}
API reference
Every class below lives in common and works the same on all three loaders. This page is the guided tour; every class and method is documented in full at api.mycelium-gg.org. Mycel follows semantic versioning for everything listed there. Anything in my.celium.org.internal is not public API and can change in any release.
- Config · Chat output · Screens and HUD · Events · Scheduling
- Networking · Registration · Entity replacement · Utilities · Commands
- Data files · Unit tests
- Update checks · Anonymous stats · Support dumps · House rules
Config
Besides booleanValue: intValue(key, def, min, max, desc), longValue, doubleValue, stringValue, enumValue, stringListValue. Group values with builder.category("tweaks") and go back with builder.root(). Version the file with schemaVersion + migrate, and reload it with CONFIG.reload() or /mycel reload mymod.
ConfigBuilder builder = Mycel.config(META).schemaVersion(2)
.migrate(1, json -> json.add("radius", json.remove("range"))); // v1 -> v2
ConfigValue<Integer> RADIUS = builder.intValue("radius", 8, 1, 32, "Pickup radius in blocks.");
builder.category("sounds");
ConfigValue<Boolean> PING = builder.booleanValue("ping", true, "Play a sound on pickup.");
MycelConfig CONFIG = builder.build();
RADIUS.onChange(value -> rebuildCache(value)); // fires on /mycel set, the screen and reload
Players can view values with /mycel get mymod [key], change them live with /mycel set mymod <key> <value> (validated exactly like the config screen, so bad input is rejected with a hint) or restore defaults with /mycel reset mymod [key]. That needs no extra code; it works for every registered config.
Chat output
TextUtil carries the shared palette (see colors below) and a Mycel » message kit: ok, fail, note, caution for single lines (green, rose, plain and amber text); header to open a list (underlined title), then item rows (they start with a grey ›) and detail lines; keyValue for settings; button, suggest, link and copy for clickable underlined labels with a hover hint. For your own tag, keep a ChatVoice: static final ChatVoice VOICE = TextUtil.voice("Pets"); then VOICE.ok(name, " came running.") (strings become body text, components keep their style). Never use ChatFormatting colors or § codes.
Screens and HUD
MycelTheme is the same palette as ARGB for drawing (BG, SURFACE, BORDER, ACCENT, TEXT, DIM, GOOD, WARN, BAD …) plus panel() for a wiki card, colored() and fit(). Client only.
Mycel.openConfigScreen(parent, "mymod") builds the generated config screen and is safe to call on a dedicated server, where it returns null. Register it for the mod-list entry on Forge/NeoForge; on Fabric add a one-line ModMenu integration.
Events
MycelEvents covers only the events every loader spells differently: player join, player leave, server started/stopped, and entity replaced. Everything else should use the loader's own event bus. All listeners run on the server thread, and a listener that throws is logged and skipped.
MycelEvents.onPlayerJoin(event -> greet(event.player()));
MycelEvents.onPlayerLeave(event -> forget(event.player().getUUID()));
MycelEvents.onServerLifecycle(event -> {
if (event.phase() == ServerLifecycleEvent.Phase.STARTED) {
Store.load(event.server());
} else { // STOPPED
Store.save();
}
});
Scheduling
MycelScheduler.runLater(ticks, task) and runEvery(ticks, task) run on the server thread and may touch the world. runEvery returns a ScheduledTask you can cancel(); every task is also dropped when the server stops. runAsync runs on a shared background pool for IO and must never touch game state: hop back with runOnServer.
MycelScheduler.runAsync(() -> {
String text = download(); // background thread
MycelScheduler.runOnServer(() -> apply(text)); // back on the server thread
});
ScheduledTask sweep = MycelScheduler.runEvery(200, Cleaner::sweep); // every 10 s
Networking
Payloads are plain vanilla CustomPacketPayload records. Describe one with PacketDefinition.toClient or toServer, register it once during init, and send it with the matching MycelNetwork method. Handlers always run on the game thread. Name channels after your mod id (mymod:greet); Mycel warns otherwise.
public record GreetPacket(String message) implements CustomPacketPayload {
public static final Type<GreetPacket> TYPE =
new Type<>(Identifier.fromNamespaceAndPath("mymod", "greet"));
public static final StreamCodec<FriendlyByteBuf, GreetPacket> CODEC =
StreamCodec.composite(ByteBufCodecs.STRING_UTF8, GreetPacket::message, GreetPacket::new);
@Override
public Type<? extends CustomPacketPayload> type() {
return TYPE;
}
}
GREET = PacketDefinition.toClient(GreetPacket.TYPE, GreetPacket.CODEC,
(packet, context) -> showToast(packet.message())); // client thread
MycelNetwork.register(META, GREET);
MycelNetwork.sendToPlayer(player, GREET, new GreetPacket("hi"));
Senders: sendToPlayer, sendToAll(server, …), sendToTracking(level, chunkPos, …) for players near a chunk, and sendToServer from client code. In a toServer handler, context.sender() is the player who sent it; treat everything in the payload as untrusted. On Fabric, call FabricNetworking.flush() from your main entrypoint and FabricNetworking.flushClient() from your client entrypoint if you register packets after Mycel's own entrypoints ran (both are safe to call more than once).
Channels are optional on every loader, so players with your mod can join servers without it and the other way round. Every sender skips a peer without the channel; ask MycelNetwork.canSend(player, GREET) on the server, or canSendToServer(PACKET) on the client, when you want a fallback such as a chat line or hiding a client feature the server cannot act on. On Forge all Mycel packets share Mycel's own channel, so there it tells you whether the client has Mycel at all.
Before Mycel 1.4.0 a toServer packet crashed Fabric clients, NeoForge channels were required, and Forge handled packets twice when a mod sent both ways. Require Mycel 1.4.0 or newer if you use networking.
Registration
MycelRegistry covers the common cases (items, blocks, entity types) with one deferred API. Register during mod construction or your entrypoint, and only call get() later, in handlers: the object does not exist before the loader creates it. Minecraft 26.x refuses items and blocks whose properties have no id, so use registerWithKey, which hands you the key for setId.
MycelRegistry<Item> items = MycelRegistry.items(META);
DeferredEntry<Item> WIDGET = items.registerWithKey("widget",
key -> new Item(new Item.Properties().setId(key)));
// later, e.g. in an event handler
ItemStack stack = new ItemStack(WIDGET.get());
Entity replacement
EntityReplacer.replace(level, oldEntity, fresh, options) swaps one entity for another on the server thread and fires onEntityReplaced. By default it carries over position, rotation, velocity, custom name, equipment, health, persistence, passengers, leash and flags; switch any of them off with ReplaceOptions.builder().
Villager fresh = EntityType.VILLAGER.create(level, EntitySpawnReason.CONVERSION);
EntityReplacer.replace(level, zombie, fresh,
ReplaceOptions.builder().equipment(false).health(false).build());
Utilities
| Class | What it does |
|---|---|
PlayerUtil | sendMessage, sendActionBar, giveItem (drops what does not fit), hasItem / countItem / removeItem, playSound, teleport, teleportToLevel |
InventoryUtil | count, contains, remove, insert and findSlot on any Container, by item or predicate |
ItemUtil | null-safe isEmpty, count, matches (item and components), copyWithCount, displayName, damage |
BlockUtil | getState, setBlock, isAir / isWater / isLava / isReplaceable / isOpaque, findNearbyBlock(level, center, radius, predicate) |
EntityUtil | getNearbyEntities, getNearbyPlayers, isMob, copyEquipment, copyName, persist |
MycelLog | one shared logger; infoMod / warnMod prefix lines with your mod id |
Mycel | getPlatform, isClient, getConfigDir, isModLoaded, getModVersion, getLoadedMods, and isEnabled / setEnabled for a runtime on/off switch |
Commands
Register commands with each loader's own command event, then use CommandHelper inside them: permission(source, level), player(source), isPlayer, and success / info / failure to reply with the shared chat style. Players see your mod in /mycel mods as soon as it calls registerMod.
Data files
For data that is not a setting (pets, highlights, saved lists), use MycelDataFile instead of writing files yourself. Saves are atomic, so a crash never leaves half a file. A file that cannot be read is kept as name.broken and you start from your fallback, so the next save cannot wipe what the player had.
static final MycelDataFile FILE = MycelDataFile.inConfigDir(META, "mymod_data.json");
Root root = FILE.read(Root.class, Root::new); // never null, never throws
root.entries.put(key, value);
FILE.write(root);
// per world, at <world>/data/mymod/pets.json
MycelDataFile pets = MycelDataFile.inWorld(server, META, "pets.json");
If the JSON parses but your own checks reject it, call FILE.quarantine("reason") to keep it aside the same way. Reads and writes are plain file IO; move big files off the server thread with MycelScheduler.runAsync.
Unit tests
Tests run without a loader or a game. Point Mycel at a temp folder before your mod's first Mycel call:
@BeforeAll
static void boot(@TempDir Path dir) {
MycelTesting.useConfigDir(dir);
MyMod.init();
}
Use MycelTesting.usePlatform(...) for a hand-written PlatformService when a test needs other mods to look installed.
Update checks
Add .updateUrl("https://…/mymod.json") to your ModMetadata builder and serve {"version": "1.0.1", "url": "https://…"} there. HTTPS only; leave it out to opt out. Checks run in the background at most once per launch. /mycel mods marks mods with an update, and operators get one chat line per session listing them. Players can turn checks off with enableUpdateChecker and the chat line with notifyOpsOfUpdates, both in config/mycel.json. See Updates for the files this wiki serves.
Anonymous stats
Since 1.6.0, ModStats (my.celium.org.stats) sends your mod's own numbers to your FastStats project, through the FastStats copy inside Mycel: no FastStats dependency of your own, every Minecraft line, and the same consent as Mycel (the player's answer on Mycel's screen, shareStats on servers). Nothing is sent before that answer.
public static final ModStats STATS = ModStats.builder(META, "your-project-token")
.number("pets_tracked", PetStore::count)
.numberMap("species", PetStore::countBySpecies)
.counters("planned_items") // a map of counts, reset after each send
.errors("com.example.mymod.") // error reports for your package
.start();
STATS.count("command_find"); // the "usage" map
STATS.count("planned_items", "diamond_sword");
Register every metric id (and usage) as a data source in your FastStats project first, or FastStats drops it. Suppliers run on a background thread every 30 minutes; return null to skip a metric for that send. Never send names, chat, addresses or anything a player typed. Start a dev client with -Dmycel.stats.selftest=true to put one dev_test count in every counter and check they arrive.
Support dumps
/mycel dump already includes every Mycel mod's config, so registering your config is all it takes. Mycel.getLoadedMods() lists every installed mod if you need it yourself.
House rules
Loader-independent code goes in common (vanilla imports only); loader quirks stay in thin per-loader entrypoints using each loader's native event bus. No per-tick scans without a reason, no sync HTTP, no required background threads.
Colors
Every MyCelium chat line uses these hex colors (since Mycel 1.6.0), chosen to read well on chat's dark backdrop. Use them through TextUtil, never ChatFormatting.
PRIMARY#FF3B3B · the bold mod tagBODY ACCENT INFO#F4F4F5 · text, names, values, buttonsSUCCESS#4ADE80 · it workedWARN#FBBF24 · carefulERROR#F87171 · failedMUTED#C4C4CC · details, versions, hintsFAINT#9A9AA3 · the », the › rows, separatorsBRIGHT#FFFFFF · titlesMycel » Commands
› Using Mycel 1.6.0 (Up to date)
Pets » Rex came running.
Mycel » No setting called 'speed'. Did you mean spead?
Mycel » Uploads are off in mycel.json.
Project layout
common/ loader-independent mod code (no loader imports)
fabric/ Fabric entrypoint + fabric.mod.json
forge/ Forge entrypoint + mods.toml
neoforge/ NeoForge entrypoint + neoforge.mods.toml
buildSrc/ shared Gradle conventions
Building
You need JDK 25. Then:
./gradlew build # all loaders + tests
./gradlew :common:test # unit tests only
First builds download and process Minecraft (caches around a gigabyte, decompile takes a few minutes, peaks around 6-8 GB RAM); later builds are incremental. Finished jars land in fabric/build/libs, forge/build/libs, and neoforge/build/libs.
Example repos
- InstantXP - tick-driven collection, int config
- AutoBlockRefiller - event-driven refill with deferred check
- Better Librarians - client-side HUD card, persistent data store, client commands
- BedrockPlacing - a client-to-server packet, wired per loader
- More Beacon Colors - packets both ways, optional on both sides, world-saved data
- API docs - every public class and method
- MyCel-Lib - the library itself, plus a join-greeting example mod proving the whole API