MidnightCommands is the Kotlin library I use for commands on MidnightSky (https://mattlack.com/project/1748549972604). The library isn't open-source, but I can share how it works and some snippets.
MidnightSky has over 500 commands, so making a new one has to be quick. A command is a class with a small builder DSL: you list its parameters, write an executor, and the library handles parsing, error messages, permission checks and tab completion.
Where it came from
MidnightSky's older commands are built on ultragrav/Commands (https://github.com/ultragrav/Commands), a Java library mostly written by my friend Magnus Petz. In late 2024 I wrote MidnightCommands as a Kotlin replacement. The main differences:
- Commands are defined with a Kotlin DSL instead of overriding methods
- Executors are suspending functions, since almost everything on MidnightSky uses coroutines
- Arguments are type-safe and can be validated right where they're declared
- Tab completion comes for free from the parameter definitions
Defining a command
Here's a real one, an administrative command for setting the network's player cap:
object CmdPlayerCapSet : NewMidnightCommand("set") {
init {
params {
integer("capacity") {
checks {
paramCheck(it >= 0) { "Capacity must be greater than or equal to 0" }
}
}
}
executor {
coroutineMain {
val capacity: Int = arg("capacity")
getProxy<MasterPlayerService>().setPlayerCap(capacity)
respond("<7>Player cap set to <c>$capacity".toComp())
}
}
}
}
If a player types something that isn't an integer, or a negative number, they get an error message and the executor never runs. Commands need a permission by default, so noPermission() has to be called explicitly to make one public.
Parameters
The built-in parameter types are string, greedyString (the rest of the input), integer, long, double, boolean, enum, and options, which takes a list of valid values that can depend on who is running the command. Any parameter can have checks { } for validation, and a default(...), which makes it optional. There's also union { }, which tries each of several parameters in order and uses the first one that parses.
Type-safe arguments
arg("capacity") works, but it relies on the name and the type matching what was declared. So in 2025 I added param { }, which returns a typed accessor for the parameter. Here's part of /config checkout, from MidnightSky's Git-like configuration system:
object CmdConfigCheckout : NewMidnightCommand("checkout") {
init {
val commit = param {
custom("commit", CommitParser)
}
val config = param {
options("config") {
getter { ModuleConfig.instance.getConfigs() }
default(null)
}
}
executor {
val commit = commit.get()
val config = config.get()
// ...
}
}
}
commit.get() is already a GameConfigCommit, with no casting and no strings to keep in sync.
Custom parsers
The commit parameter above uses a custom parser. A parser turns the next token(s) into a value and suggests completions, and both of those are suspending, so a parser can make RPC calls. CommitParser accepts a commit ID prefix or HEAD, and even supports HEAD~2 like Git:
object CommitParser : CmdParamParser<GameConfigCommit> {
override suspend fun parse(ctx: ParamContext): GameConfigCommit {
val input = ctx.takeOne().lowercase()
val behind = if ('~' in input) input.substringAfter('~').toIntOrNull() ?: 0 else 0
val service = getProxy<MasterConfigService>()
val base = when {
input.startsWith("head") -> ModuleConfig.instance.structure.branches[ModuleConfig.instance.branchName]!!.head
else -> {
val id = input.substringBefore("~", missingDelimiterValue = input)
val ids = service.getCommitIds(id)
if (ids.size > 1) problem("Ambiguous commit ID: $id, could be any of ${ids.joinToString(", ")}")
val uuid = ids.firstOrNull() ?: problem("No commit with ID: $id")
service.getCommit(uuid) ?: problem("No commit with ID: $id")
}
}
var out = base
repeat(behind) {
if (out.parents.size != 1) problem("Cannot walk through non-linear commit history!")
out = service.getCommit(out.parents.first()) ?: problem("Parent commit no longer exists")
}
return out
}
override suspend fun getCompletions(ctx: ParamContext): List<Completion> {
val current = ctx.takeOne()
val commits = getProxy<MasterConfigService>().getCommitIds(current)
return commits.map { Completion("$it") } + listOf(Completion("HEAD"))
}
}
problem(...) throws a parse error, and its message is shown to the player in red.
How it works
Parsing
The input is split into tokens in a ParamContext, which supports mark() and reset(). Each parameter is parsed in order. If an optional parameter fails to parse, the context is reset to the mark and the default is used instead, so the same tokens can be tried by the next parameter. Checks run after parsing, so they always get a value of the right type.
Commands can have child commands (like set above, which is a child of /player-cap). When processing input, a command first checks whether the next token is one of its children's aliases, and if so hands the rest of the input to that child.
Tab completion
Completions come from the same parameter definitions. The library parses as far as it can, and the first parameter that fails to parse is the one the player is currently typing, so its parser gives the suggestions. If that parameter is optional, the player might be typing the next one instead, so its suggestions are included too. Children's aliases are suggested as well, and permission checks happen during completion, so players don't see suggestions for commands they can't use.
Living alongside the old library
Both libraries run side by side. New commands can be registered on their own, and calling interop() on one wraps it in a class that turns it into an old-style command, converting its aliases, parameters and child commands. That's how /config checkout above can be a child of the older /config command. About 80 of MidnightSky's command files use the new library so far, and the rest still run on the old one.