Codex CLI Claude Skill

minecraft-plugin-dev

Create, modify, and debug server plugins for current Paper 26.x on Java 25 or legacy Bukkit-derived 1.21.x servers on Java 21. Use for JavaPlugin APIs, events, commands, schedulers, configuration, PDC, and Adventure, not client mods or vanilla datapacks.

LLM Mart · 0 points · 11 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download jahrome907-minecraft-agent-skills-.codex_skills_minecraft-plugin-dev-40b1d4e.zip · 32 KB
Part of jahrome907/minecraft-agent-skills — 52 skills

Install

skills CLI npx skills add https://github.com/Jahrome907/minecraft-agent-skills/tree/main/.codex/skills/minecraft-plugin-dev
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install jahrome907-minecraft-agent-skills@llmmart
Git git clone https://github.com/Jahrome907/minecraft-agent-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole jahrome907/minecraft-agent-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

Minecraft Plugin Development Skill

Platform Overview

Platform Base API Notes
Paper Bukkit/Spigot + Paper extensions Recommended; async chunk loading, Adventure native
Spigot Bukkit + Spigot extensions Legacy; fewer APIs, slower
Bukkit Base API only Avoid for new plugins
Folia Paper fork Region-threaded; requires special scheduler APIs

Paper is the recommended target. Paper includes all Bukkit and Spigot APIs plus significant performance improvements and additional APIs.

Routing Boundaries

  • Use when: the target is server-side Paper/Bukkit/Spigot plugin behavior with JavaPlugin APIs.
  • Do not use when: the task requires client-side installable mods or loader APIs (minecraft-modding / minecraft-multiloader).
  • Do not use when: the task is pure vanilla datapack/command content (minecraft-datapack / minecraft-commands-scripting).

Bundled References

  • Read references/runtime-patterns.md when the task touches scheduling, Folia support, PDC, Adventure/MiniMessage, YAML config, Vault, or Paper-specific APIs.
  • Read references/paper-plugin-commands.md for a Paper-only paper-plugin.yml project or Brigadier command registration.

Project Setup

The examples below target current Paper 26.2 and Java 25. For an existing 1.21.x plugin, preserve its 1.21.x-R0.1-SNAPSHOT dependency, Java 21 toolchain, and matching api-version until the project is intentionally ported.

settings.gradle.kts

rootProject.name = "my-plugin"

build.gradle.kts

plugins {
    java
}

group = "com.example"
version = "1.0.0-SNAPSHOT"

repositories {
    mavenCentral()
    maven("https://repo.papermc.io/repository/maven-public/")
}

dependencies {
    compileOnly("io.papermc.paper:paper-api:26.2.build.+")
}

java {
    toolchain.languageVersion.set(JavaLanguageVersion.of(25))
}

tasks {
    processResources {
        // Substitutes ${version} in plugin.yml with the Gradle project version
        filesMatching(listOf("plugin.yml", "paper-plugin.yml")) {
            expand("version" to project.version)
        }
    }
}

Add Shadow only when the plugin has runtime libraries that must be bundled and relocated. Paper and optional plugin APIs such as Vault remain compileOnly and must not be shaded into the plugin JAR.

gradle/wrapper/gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip

Gradle 8.8 cannot run on Java 25. Use Gradle 9.1 or newer for a current Java 25 project. Preserve the existing wrapper and Java 21 toolchain for a legacy 1.21.x project unless its build is intentionally upgraded and verified.


Project Layout

my-plugin/
├── build.gradle.kts
├── settings.gradle.kts
├── gradle/
│   └── wrapper/
│       └── gradle-wrapper.properties
└── src/main/
    ├── java/com/example/myplugin/
    │   ├── MyPlugin.java          ← main class (extends JavaPlugin)
    │   ├── listeners/
    │   │   └── PlayerListener.java
    │   ├── commands/
    │   │   └── MyCommand.java
    │   └── managers/
    │       └── DataManager.java
    └── resources/
        ├── plugin.yml            ← Bukkit-compatible descriptor
        ├── paper-plugin.yml      ← active descriptor for a Paper plugin
        └── config.yml

Core Files

plugin.yml (Bukkit-compatible default)

name: MyPlugin
version: "${version}"
main: com.example.myplugin.MyPlugin
description: An example Paper plugin
author: YourName
website: https://github.com/example/my-plugin
api-version: '26.2'

commands:
  myplugin:
    description: Main plugin command
    usage: /myplugin <subcommand>
    permission: myplugin.use
    aliases: [mp]

permissions:
  myplugin.use:
    description: Allows use of /myplugin
    default: true
  myplugin.admin:
    description: Admin access
    default: op

Match api-version to the oldest Paper API the plugin intentionally supports. Current Paper examples use 26.2; legacy 1.21 and positive 1.21.<patch> values remain valid for older servers. A server older than the declared value refuses to load the plugin.

paper-plugin.yml (experimental Paper-only format)

Prefer plugin.yml for Bukkit-compatible plugins. Use paper-plugin.yml only when the JAR is intentionally Paper-only and needs Paper-plugin behavior such as bootstrapping, loaders, or classloading isolation. It can be the only descriptor, but is not a drop-in replacement: Paper plugins do not use a commands field or getCommand(...) registration. Read references/paper-plugin-commands.md for the paired descriptor, main class, and Brigadier lifecycle registration.

When one JAR ships both descriptors, keep their shared metadata and main class aligned. Do not combine the Paper-only sample with the Bukkit-compatible MyPlugin sample below.

Bukkit-compatible main class

package com.example.myplugin;

import com.example.myplugin.commands.MyCommand;
import com.example.myplugin.listeners.PlayerListener;
import org.bukkit.plugin.java.JavaPlugin;

public final class MyPlugin extends JavaPlugin {

    @Override
    public void onEnable() {
        saveDefaultConfig();

        // Register listeners
        getServer().getPluginManager().registerEvents(new PlayerListener(), this);

        // Register commands
        var cmd = getCommand("myplugin");
        if (cmd == null) {
            throw new IllegalStateException("myplugin command is missing from plugin.yml");
        }
        var handler = new MyCommand(this);
        cmd.setExecutor(handler);
        cmd.setTabCompleter(handler);

        getLogger().info("MyPlugin enabled!");
    }

    @Override
    public void onDisable() {
        getLogger().info("MyPlugin disabled.");
    }

}

Event Listeners

package com.example.myplugin.listeners;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;

public class PlayerListener implements Listener {

    @EventHandler(priority = EventPriority.NORMAL)
    public void onPlayerJoin(PlayerJoinEvent event) {
        event.joinMessage(
            Component.text(event.getPlayer().getName() + " joined!", NamedTextColor.GREEN)
        );
    }

    @EventHandler
    public void onPlayerQuit(PlayerQuitEvent event) {
        event.quitMessage(
            Component.text(event.getPlayer().getName() + " left.", NamedTextColor.YELLOW)
        );
    }

    @EventHandler
    public void onPlayerDeath(PlayerDeathEvent event) {
        // Modify death message using Adventure components
        event.deathMessage(
            Component.text("☠ ", NamedTextColor.RED)
                .append(Component.text(event.getPlayer().getName(), NamedTextColor.WHITE))
                .append(Component.text(" died!", NamedTextColor.RED))
        );
    }
}

EventPriority order

LOWEST → LOW → NORMAL → HIGH → HIGHEST → MONITOR
Use MONITOR for logging only (never modify outcome). On events that implement Cancellable, use ignoreCancelled = true unless you need cancelled events.

Cancellable events

@EventHandler
public void onBlockBreak(BlockBreakEvent event) {
    if (event.getPlayer().hasPermission("myplugin.break.deny")) {
        event.setCancelled(true);
        event.getPlayer().sendMessage(Component.text("You cannot break blocks!", NamedTextColor.RED));
    }
}

Commands

This section is for the plugin.yml path above. Its declared command enables getCommand("myplugin"). For a Paper-only descriptor, use the Brigadier lifecycle example in references/paper-plugin-commands.md.

package com.example.myplugin.commands;

import com.example.myplugin.MyPlugin;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;
import java.util.Locale;

public class MyCommand implements CommandExecutor, TabCompleter {

    private final MyPlugin plugin;

    public MyCommand(MyPlugin plugin) {
        this.plugin = plugin;
    }

    @Override
    public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
                             @NotNull String label, @NotNull String[] args) {
        if (!(sender instanceof Player player)) {
            sender.sendMessage(Component.text("Only players can use this command.", NamedTextColor.RED));
            return true;
        }

        if (!player.hasPermission("myplugin.use")) {
            player.sendMessage(Component.text("No permission.", NamedTextColor.RED));
            return true;
        }

        if (args.length == 0) {
            player.sendMessage(Component.text("Usage: /myplugin <reload|info>", NamedTextColor.YELLOW));
            return true;
        }

        return switch (args[0].toLowerCase(Locale.ROOT)) {
            case "reload" -> {
                plugin.reloadConfig();
                player.sendMessage(Component.text("Config reloaded.", NamedTextColor.GREEN));
                yield true;
            }
            case "info" -> {
                player.sendMessage(Component.text("Version: " + plugin.getDescription().getVersion(), NamedTextColor.AQUA));
                yield true;
            }
            default -> {
                player.sendMessage(Component.text("Unknown subcommand.", NamedTextColor.RED));
                yield true;
            }
        };
    }

    @Override
    public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command,
                                                @NotNull String label, @NotNull String[] args) {
        if (args.length == 1) {
            return List.of("reload", "info").stream()
                .filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT)))
                .toList();
        }
        return List.of();
    }
}

Schedulers

For classic Paper plugins, BukkitScheduler is still fine. If you claim Folia support, route player, entity, region, global, and async work through the matching Folia-aware scheduler. Keep scheduling behind a small project-local interface when one plugin must support both Paper and Folia.

See references/runtime-patterns.md for copy-ready sync, async, cancelable, and Folia-safe scheduler examples.


Persistent Data Container (PDC)

PDC stores arbitrary data on any PersistentDataHolder (players, entities, items, chunks). Data is saved with the world and persists across restarts.

Create NamespacedKey instances once, keep data types stable after release, and use PDC for small metadata rather than large datasets. Prefer config files or a database for large or query-heavy plugin state.

See references/runtime-patterns.md for player, item, chunk, and world PDC examples.


Adventure Text Components

Paper uses Adventure natively for all text. No legacy chat colors. Use Component builders for code-owned messages and MiniMessage for config-driven messages. Avoid legacy ChatColor unless the target project already depends on it for compatibility.

See references/runtime-patterns.md for simple messages, hover/click events, MiniMessage parsing, titles, and action bars.


Configuration (YAML)

src/main/resources/config.yml

# Default config
settings:
  max-players: 20
  welcome-message: "<green>Welcome to the server!"
  cooldown-seconds: 30

database:
  host: localhost
  port: 3306
  name: myplugin_db

Accessing config values

Call saveDefaultConfig() in onEnable(), provide explicit defaults when reading values, and validate config shape before starting long-running tasks.

Custom config file

Use custom YAML files only when separating user config from mutable plugin data is worth the extra file handling. Keep blocking disk writes off hot event paths.

See references/runtime-patterns.md for config read/write and custom YAML examples.


Vault Integration (Economy / Permissions)

Declare Vault as compileOnly, soft-depend on it in plugin metadata, and disable economy features cleanly when the service provider is unavailable. Never assume a Vault-compatible economy plugin is installed just because Vault itself is present.

When Vault support is required, add the JitPack repository and compileOnly("com.github.MilkBowl:VaultAPI:1.7") to the Gradle build.

See references/runtime-patterns.md for a minimal economy setup and charge example.


Paper-Specific APIs

Use Paper APIs when they remove main-thread blocking or simplify Adventure-native behavior. Keep optional plugin integrations behind presence checks and metadata soft-dependencies.

See references/runtime-patterns.md for async chunk loading, custom item meta, profile lookup, and protection-plugin integration examples.


Common Tasks Checklist

Creating a new event listener

  • Create class implementing Listener
  • Annotate methods with @EventHandler
  • Call getServer().getPluginManager().registerEvents(listener, plugin) in onEnable()
  • On cancellable events, add ignoreCancelled = true unless you need cancelled events

Adding a new command

  • For a Bukkit-compatible plugin, define the command in plugin.yml, create a CommandExecutor, and register it with getCommand("name")
  • For a Paper-only plugin, register the command through LifecycleEvents.COMMANDS; do not add a commands field

Saving plugin data

  • For simple values: use config.yml via getConfig() / saveConfig()
  • For per-entity data: use PDC with a NamespacedKey
  • For large datasets: use async scheduler + file I/O or a database

Scheduling a repeating task

  • Determine if task needs main thread (use runTaskTimer) or is I/O (use runTaskTimerAsynchronously)
  • Store the BukkitTask reference so you can cancel in onDisable()
  • Cancel all tasks in onDisable() or use getServer().getScheduler().cancelTasks(plugin)

Build, Validate, and Run

  1. Build the plugin JAR:
    ./gradlew build
    # Output: build/libs/my-plugin-1.0.0-SNAPSHOT.jar
    
  2. Run the bundled validator to catch config and layout errors:
    ./scripts/validate-plugin-layout.sh --root /path/to/plugin-project
    # Strict mode treats warnings as failures:
    ./scripts/validate-plugin-layout.sh --root /path/to/plugin-project --strict
    
    The validator requires Node and includes its own YAML parser for descriptor checks.
  3. Fix any reported errors and re-run until clean.
  4. Deploy: copy the built JAR to server/plugins/ and restart the Paper server. If the real project already applies a Paper dev-server plugin such as xyz.jpenilla.run-paper, use that project's documented dev task instead of assuming ./gradlew runServer exists.

The validator checks:

  • active plugin.yml or paper-plugin.yml required keys (name, version, main, api-version) and repo-supported current 26.<release> or legacy 1.21 / positive 1.21.<patch> values, with warnings for versions newer than the documented examples
  • cross-descriptor metadata consistency when both descriptors are present; paper-plugin.yml is selected as active
  • Active main class path exists and extends JavaPlugin
  • actual server /reload anti-patterns such as Bukkit.reload() or dispatching the server reload command

References

Files (minecraft-agent-skills)
  • references
    • paper-plugin-commands.md 2.6 KB
      # Paper-Only Plugins and Commands
      
      Read this only when the target JAR uses `paper-plugin.yml`. Paper plugins are
      experimental and are not a drop-in replacement for Bukkit-compatible
      `plugin.yml` plugins.
      
      Paper plugins do not use a `commands` field. Register commands through Paper's
      Brigadier lifecycle API; do not call `getCommand(...)` unless the matching
      command is declared in `plugin.yml`.
      
      ## Paired descriptor and main class
      
      This Paper-only example has one descriptor and one matching main class. It does
      not include a Bukkit `plugin.yml`.
      
      ### `src/main/resources/paper-plugin.yml`
      
      ```yaml
      name: PaperOnlyPlugin
      version: "${version}"
      main: com.example.myplugin.PaperOnlyPlugin
      description: An example Paper-only plugin
      api-version: '26.2'
      ```
      
      ### `src/main/java/com/example/myplugin/PaperOnlyPlugin.java`
      
      ```java
      package com.example.myplugin;
      
      import com.mojang.brigadier.Command;
      import io.papermc.paper.command.brigadier.Commands;
      import io.papermc.paper.plugin.lifecycle.event.types.LifecycleEvents;
      import org.bukkit.plugin.java.JavaPlugin;
      
      public final class PaperOnlyPlugin extends JavaPlugin {
      
          @Override
          public void onEnable() {
              this.getLifecycleManager().registerEventHandler(LifecycleEvents.COMMANDS, event -> {
                  event.registrar().register(
                      Commands.literal("myplugin")
                          .executes(context -> {
                              context.getSource().getSender().sendRichMessage("<green>MyPlugin is running.");
                              return Command.SINGLE_SUCCESS;
                          })
                          .build(),
                      "Main Paper-only plugin command"
                  );
              });
          }
      }
      ```
      
      `LifecycleEvents.COMMANDS` re-registers the command when Paper reloads command
      resources. Keep registration inside its handler. Use `Commands.literal(...)` and
      `Commands.argument(...)` to construct larger command trees, and add `requires`
      to the tree when a command needs an access check.
      
      ## When both descriptors are needed
      
      Use both descriptors only when the same JAR intentionally supports the two
      formats. Keep `name`, `version`, `main`, and `api-version` aligned. The
      `plugin.yml` path may use `commands` and `getCommand(...)`; the Paper-plugin
      path must instead register its commands through the lifecycle API.
      
      ## Sources
      
      - [Paper plugins: descriptor differences and commands](https://docs.papermc.io/paper/dev/getting-started/paper-plugins/)
      - [Paper Brigadier registration](https://docs.papermc.io/paper/dev/command-api/basics/registration/)
      - [Paper Brigadier arguments and literals](https://docs.papermc.io/paper/dev/command-api/basics/arguments-and-literals/)
      
    • runtime-patterns.md 7.5 KB
      # Runtime Patterns for Paper Plugins
      
      Use these examples when implementing runtime behavior for Paper/Bukkit plugins.
      All snippets target Java 21 and Paper API 1.21.x unless noted.
      
      ## Schedulers
      
      Classic Paper plugins can use `BukkitScheduler`. Never run blocking I/O on the
      main thread, and switch back to the main thread before touching Bukkit state.
      
      ```java
      // Run once after 20 ticks (1 second)
      plugin.getServer().getScheduler().runTaskLater(plugin, () -> {
          // Bukkit API access is safe here.
      }, 20L);
      
      // Repeating: starts after 0 ticks, runs every 40 ticks.
      plugin.getServer().getScheduler().runTaskTimer(plugin, () -> {
          // Main-thread task logic.
      }, 0L, 40L);
      
      // Async I/O, then return to the main thread for Bukkit API work.
      plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> {
          String data = fetchFromDatabase();
          plugin.getServer().getScheduler().runTask(plugin, () -> {
              Bukkit.broadcastMessage(data);
          });
      });
      ```
      
      Use `BukkitRunnable` when task-local cancellation state is useful.
      
      ```java
      new BukkitRunnable() {
          int count = 0;
      
          @Override
          public void run() {
              count++;
              if (count >= 10) {
                  cancel();
                  return;
              }
              // Repeating task logic.
          }
      }.runTaskTimer(plugin, 0L, 20L);
      ```
      
      For Folia support, choose a scheduler based on the ownership of the work.
      
      ```java
      // Player-bound work: stays with the player's owning region.
      player.getScheduler().run(plugin, task -> {
          player.sendActionBar(Component.text("Checkpoint reached"));
      }, null);
      
      // Location / chunk-bound work.
      plugin.getServer().getRegionScheduler().run(plugin, location, task -> {
          location.getBlock().setType(Material.GOLD_BLOCK);
      });
      
      // Global coordination not tied to one region.
      plugin.getServer().getGlobalRegionScheduler().run(plugin, task -> {
          Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "save-all");
      });
      
      // Blocking I/O stays async.
      plugin.getServer().getAsyncScheduler().runNow(plugin, task -> {
          writeAuditLog();
      });
      ```
      
      ## Persistent Data Container
      
      Create `NamespacedKey` instances once and keep each key's type stable after
      release. PDC is appropriate for small metadata on players, entities, items,
      chunks, and worlds.
      
      ```java
      import org.bukkit.NamespacedKey;
      import org.bukkit.persistence.PersistentDataType;
      
      NamespacedKey killKey = new NamespacedKey(plugin, "kill_count");
      NamespacedKey flagKey = new NamespacedKey(plugin, "vip");
      
      player.getPersistentDataContainer().set(killKey, PersistentDataType.INTEGER, 42);
      player.getPersistentDataContainer().set(flagKey, PersistentDataType.BOOLEAN, true);
      
      int kills = player.getPersistentDataContainer()
          .getOrDefault(killKey, PersistentDataType.INTEGER, 0);
      
      boolean isVip = player.getPersistentDataContainer()
          .getOrDefault(flagKey, PersistentDataType.BOOLEAN, false);
      
      player.getPersistentDataContainer().remove(killKey);
      ```
      
      ```java
      ItemStack item = new ItemStack(Material.DIAMOND_SWORD);
      item.editMeta(meta -> meta.getPersistentDataContainer().set(
          new NamespacedKey(plugin, "custom_id"),
          PersistentDataType.STRING,
          "special_sword"
      ));
      ```
      
      ```java
      NamespacedKey arenaKey = new NamespacedKey(plugin, "arena_id");
      
      chunk.getPersistentDataContainer().set(arenaKey, PersistentDataType.STRING, "spawn");
      
      String arenaId = chunk.getPersistentDataContainer()
          .getOrDefault(arenaKey, PersistentDataType.STRING, "unknown");
      ```
      
      ## Adventure And MiniMessage
      
      Paper uses Adventure natively. Use `Component` builders for code-owned messages
      and MiniMessage for config-owned rich text.
      
      ```java
      import net.kyori.adventure.text.Component;
      import net.kyori.adventure.text.event.ClickEvent;
      import net.kyori.adventure.text.event.HoverEvent;
      import net.kyori.adventure.text.format.NamedTextColor;
      import net.kyori.adventure.text.format.TextDecoration;
      
      player.sendMessage(Component.text("Hello!", NamedTextColor.GREEN));
      player.sendMessage(Component.text("Bold warning", NamedTextColor.RED, TextDecoration.BOLD));
      
      Component message = Component.text()
          .append(Component.text("[Info]", NamedTextColor.AQUA)
              .clickEvent(ClickEvent.runCommand("/myplugin info"))
              .hoverEvent(HoverEvent.showText(Component.text("Run /myplugin info"))))
          .append(Component.text(" for plugin details.", NamedTextColor.WHITE))
          .build();
      player.sendMessage(message);
      ```
      
      ```java
      import net.kyori.adventure.text.minimessage.MiniMessage;
      
      Component parsed = MiniMessage.miniMessage().deserialize(
          "<gradient:red:yellow>Hello World</gradient>"
      );
      ```
      
      ```java
      player.showTitle(Title.title(
          Component.text("Welcome!", NamedTextColor.GOLD),
          Component.text("To " + player.getWorld().getName(), NamedTextColor.YELLOW),
          Title.Times.times(Duration.ofMillis(500), Duration.ofSeconds(3), Duration.ofMillis(500))
      ));
      
      player.sendActionBar(Component.text("Health: " + player.getHealth(), NamedTextColor.RED));
      ```
      
      ## YAML Config
      
      Call `saveDefaultConfig()` in `onEnable()` and always provide explicit defaults
      when reading values.
      
      ```java
      saveDefaultConfig();
      
      int maxPlayers = getConfig().getInt("settings.max-players", 20);
      String message = getConfig().getString("settings.welcome-message", "Welcome!");
      boolean enabled = getConfig().getBoolean("features.pvp", true);
      
      reloadConfig();
      
      getConfig().set("settings.max-players", 30);
      saveConfig();
      ```
      
      Use a custom file when mutable data should be separated from user-editable config.
      
      ```java
      File customFile = new File(getDataFolder(), "data.yml");
      if (!customFile.exists()) {
          saveResource("data.yml", false);
      }
      
      FileConfiguration customConfig = YamlConfiguration.loadConfiguration(customFile);
      customConfig.set("some.key", "value");
      customConfig.save(customFile);
      ```
      
      ## Vault
      
      Vault is an optional bridge. Check for both the Vault plugin and the requested
      service provider before enabling economy behavior.
      
      ```java
      import net.milkbowl.vault.economy.Economy;
      import org.bukkit.plugin.RegisteredServiceProvider;
      
      public class MyPlugin extends JavaPlugin {
          private Economy economy;
      
          @Override
          public void onEnable() {
              if (!setupEconomy()) {
                  getLogger().warning("Vault economy provider unavailable; economy features disabled.");
              }
          }
      
          private boolean setupEconomy() {
              if (getServer().getPluginManager().getPlugin("Vault") == null) return false;
              RegisteredServiceProvider<Economy> rsp =
                  getServer().getServicesManager().getRegistration(Economy.class);
              if (rsp == null) return false;
              economy = rsp.getProvider();
              return economy != null;
          }
      
          public boolean chargePlayer(Player player, double amount) {
              if (economy == null || !economy.has(player, amount)) return false;
              return economy.withdrawPlayer(player, amount).transactionSuccess();
          }
      }
      ```
      
      ## Paper-Specific APIs
      
      Use async Paper APIs to avoid avoidable main-thread blocking.
      
      ```java
      world.getChunkAtAsync(x, z).thenAccept(chunk -> {
          chunk.getBlock(0, 64, 0).setType(Material.GOLD_BLOCK);
      });
      ```
      
      ```java
      ItemStack item = new ItemStack(Material.STICK);
      ItemMeta meta = item.getItemMeta();
      meta.setCustomModelData(1001);
      meta.displayName(Component.text("Magic Wand", NamedTextColor.LIGHT_PURPLE));
      item.setItemMeta(meta);
      ```
      
      ```java
      Bukkit.createProfile(UUID.fromString("00000000-0000-0000-0000-000000000000"))
          .update()
          .thenAccept(profile -> {
              String name = profile.getName();
          });
      ```
      
      Optional protection plugins should be soft dependencies and presence-checked
      before calling their APIs.
      
      ```java
      if (getServer().getPluginManager().getPlugin("WorldGuard") != null) {
          // Use WorldGuard API from a project-specific adapter class.
      }
      ```
      
  • scripts
    • vendor
      • js-yaml.min.cjs 60.2 KB · in bundle
      • LICENSE.js-yaml 1.1 KB · in bundle
    • validate-plugin-layout.sh 10.8 KB
      #!/usr/bin/env bash
      set -euo pipefail
      
      PASS='[PASS]'
      WARN='[WARN]'
      FAIL='[FAIL]'
      
      ROOT='.'
      STRICT=0
      SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
      YAML_MODULE="$SCRIPT_DIR/vendor/js-yaml.min.cjs"
      
      while [[ $# -gt 0 ]]; do
        case "$1" in
          --root)
            ROOT="${2:-}"
            shift 2
            ;;
          --strict)
            STRICT=1
            shift
            ;;
          --help|-h)
            cat <<'USAGE'
      Usage: validate-plugin-layout.sh [--root <path>] [--strict]
      
      Checks Paper/Bukkit plugin layout:
      - required active descriptor keys (name, version, main, api-version)
      - supports plugin.yml-only, paper-plugin.yml-only, or both descriptors
      - uses paper-plugin.yml as the active descriptor when both are present
      - descriptor YAML syntax before key extraction
      - active descriptor main class path exists and extends JavaPlugin
      - warns on actual server /reload anti-pattern usage
      USAGE
            exit 0
            ;;
          *)
            echo "$FAIL unknown arg: $1" >&2
            exit 1
            ;;
        esac
      done
      
      if [[ ! -d "$ROOT" ]]; then
        echo "$FAIL root path does not exist: $ROOT"
        exit 1
      fi
      
      if ! command -v node >/dev/null 2>&1; then
        echo "$FAIL node is required to parse plugin YAML descriptors"
        exit 1
      fi
      
      if [[ ! -f "$YAML_MODULE" ]]; then
        echo "$FAIL missing bundled YAML parser: $YAML_MODULE"
        exit 1
      fi
      
      FAILURES=0
      WARNINGS=0
      CURRENT_LEGACY_API_PATCH=11
      CURRENT_API_RELEASE=2
      
      pass() { echo "$PASS $*"; }
      warn() { echo "$WARN $*"; WARNINGS=$((WARNINGS + 1)); }
      fail() { echo "$FAIL $*"; FAILURES=$((FAILURES + 1)); }
      
      validate_api_version() {
        local value="$1"
      
        if [[ "$value" =~ ^1\.21$ ]]; then
          return 0
        fi
      
        if [[ "$value" =~ ^1\.21\.([1-9][0-9]*)$ ]]; then
          return 0
        fi
      
        if [[ "$value" =~ ^26\.([1-9][0-9]*)$ ]]; then
          return 0
        fi
      
        return 1
      }
      
      warn_if_newer_than_documented_api_version() {
        local value="$1"
        local label="$2"
      
        if [[ "$value" =~ ^1\.21\.([1-9][0-9]*)$ ]] && (( BASH_REMATCH[1] > CURRENT_LEGACY_API_PATCH )); then
          warn "$label api-version is newer than the last documented 1.21.x patch (1.21.${CURRENT_LEGACY_API_PATCH}); verify it against Paper's supported versions"
        elif [[ "$value" =~ ^26\.([1-9][0-9]*)$ ]] && (( BASH_REMATCH[1] > CURRENT_API_RELEASE )); then
          warn "$label api-version is newer than the repo's current Paper example (26.${CURRENT_API_RELEASE}); verify it against the current Paper release line"
        fi
      }
      
      trim() {
        local s="$1"
        s="${s//$'\r'/}"
        s="${s#"${s%%[![:space:]]*}"}"
        s="${s%"${s##*[![:space:]]}"}"
        s="${s#\"}"
        s="${s%\"}"
        s="${s#\'}"
        s="${s%\'}"
        echo "$s"
      }
      
      validate_yaml_descriptor() {
        local file="$1"
        local label="$2"
        local output=""
      
        if output="$(node - "$file" "$label" "$YAML_MODULE" <<'NODE'
      const fs = require('node:fs');
      
      const file = process.argv[2];
      const label = process.argv[3];
      const yamlModule = process.argv[4];
      
      let yaml;
      try {
        yaml = require(yamlModule);
      } catch (error) {
        console.log(`missing bundled YAML parser at ${yamlModule}: ${String(error.message || error)}`);
        process.exit(2);
      }
      
      try {
        const parsed = yaml.load(fs.readFileSync(file, 'utf8'));
        if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
          console.log(`${label} top-level document must be a mapping`);
          process.exit(2);
        }
      } catch (error) {
        console.log(String(error.message || error).split('\n')[0]);
        process.exit(2);
      }
      NODE
      )"; then
          pass "$label is valid YAML"
          return 0
        fi
      
        fail "$label is not valid YAML: $output"
        return 1
      }
      
      extract_yaml_key() {
        local file="$1"
        local key="$2"
      
        node - "$file" "$key" "$YAML_MODULE" <<'NODE'
      const fs = require('node:fs');
      
      const file = process.argv[2];
      const key = process.argv[3];
      const yamlModule = process.argv[4];
      const yaml = require(yamlModule);
      const parsed = yaml.load(fs.readFileSync(file, 'utf8'));
      const value = parsed?.[key];
      
      if (value === undefined || value === null) process.exit(0);
      if (typeof value === 'object') process.exit(0);
      process.stdout.write(String(value));
      NODE
      }
      
      warn_on_reload_misuse() {
        local root="$1"
        local misuse_detected=0
      
        if grep -R -n -E --include='*.java' --include='*.kt' '\b(Bukkit|getServer\(\)|server)\.reload[[:space:]]*\(' "$root/src" >/dev/null 2>&1; then
          misuse_detected=1
        fi
      
        if grep -R -n -E -i --include='*.java' --include='*.kt' "(dispatchCommand|performCommand|chat)\\([^)]*[\"']/?(minecraft:)?reload([[:space:]]|[\"'])" "$root/src" >/dev/null 2>&1; then
          misuse_detected=1
        fi
      
        if [[ "$misuse_detected" -eq 1 ]]; then
          warn "detected actual server reload usage in source (avoid Bukkit.reload() and dispatching /reload)"
        else
          pass "no obvious server /reload anti-pattern detected"
        fi
      }
      
      echo "=== Plugin Layout Validator ==="
      
      name_val=""
      version_val=""
      main_val=""
      api_val=""
      paper_name_val=""
      paper_version_val=""
      paper_main_val=""
      paper_api_val=""
      active_label=""
      active_main_val=""
      
      PLUGIN_YML=""
      if [[ -f "$ROOT/src/main/resources/plugin.yml" ]]; then
        PLUGIN_YML="$ROOT/src/main/resources/plugin.yml"
      elif [[ -f "$ROOT/plugin.yml" ]]; then
        PLUGIN_YML="$ROOT/plugin.yml"
      fi
      
      if [[ -n "$PLUGIN_YML" ]]; then
        pass "found plugin.yml: ${PLUGIN_YML#$ROOT/}"
      
        if validate_yaml_descriptor "$PLUGIN_YML" "plugin.yml"; then
          name_val="$(trim "$(extract_yaml_key "$PLUGIN_YML" "name")")"
          version_val="$(trim "$(extract_yaml_key "$PLUGIN_YML" "version")")"
          main_val="$(trim "$(extract_yaml_key "$PLUGIN_YML" "main")")"
          api_val="$(trim "$(extract_yaml_key "$PLUGIN_YML" "api-version")")"
      
          [[ -n "$name_val" ]] && pass "plugin.yml has name" || fail "plugin.yml missing key: name"
          [[ -n "$version_val" ]] && pass "plugin.yml has version" || fail "plugin.yml missing key: version"
          [[ -n "$main_val" ]] && pass "plugin.yml has main" || fail "plugin.yml missing key: main"
      
          if [[ -z "$api_val" ]]; then
            fail "plugin.yml missing key: api-version"
          elif validate_api_version "$api_val"; then
            pass "plugin.yml api-version is within the documented 26.x / 1.21.x skill scope: $api_val"
            warn_if_newer_than_documented_api_version "$api_val" "plugin.yml"
          elif [[ "$api_val" =~ ^(1\.21\.|26\.)0[0-9]*$ ]]; then
            fail "plugin.yml api-version release must be a positive integer without leading zeroes: $api_val"
          elif [[ "$api_val" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then
            fail "plugin.yml api-version is outside the documented 26.x / 1.21.x skill scope: $api_val"
          else
            fail "plugin.yml api-version has invalid format: $api_val"
          fi
      
        fi
      fi
      
      PAPER_PLUGIN_YML=""
      if [[ -f "$ROOT/src/main/resources/paper-plugin.yml" ]]; then
        PAPER_PLUGIN_YML="$ROOT/src/main/resources/paper-plugin.yml"
      elif [[ -f "$ROOT/paper-plugin.yml" ]]; then
        PAPER_PLUGIN_YML="$ROOT/paper-plugin.yml"
      fi
      
      if [[ -n "$PAPER_PLUGIN_YML" ]]; then
        pass "found paper-plugin.yml: ${PAPER_PLUGIN_YML#$ROOT/}"
      
        if validate_yaml_descriptor "$PAPER_PLUGIN_YML" "paper-plugin.yml"; then
          paper_name_val="$(trim "$(extract_yaml_key "$PAPER_PLUGIN_YML" "name")")"
          paper_version_val="$(trim "$(extract_yaml_key "$PAPER_PLUGIN_YML" "version")")"
          paper_main_val="$(trim "$(extract_yaml_key "$PAPER_PLUGIN_YML" "main")")"
          paper_api_val="$(trim "$(extract_yaml_key "$PAPER_PLUGIN_YML" "api-version")")"
      
          [[ -n "$paper_name_val" ]] && pass "paper-plugin.yml has name" || fail "paper-plugin.yml missing key: name"
          [[ -n "$paper_version_val" ]] && pass "paper-plugin.yml has version" || fail "paper-plugin.yml missing key: version"
          [[ -n "$paper_main_val" ]] && pass "paper-plugin.yml has main" || fail "paper-plugin.yml missing key: main"
      
          if [[ -z "$paper_api_val" ]]; then
            fail "paper-plugin.yml missing key: api-version"
          elif validate_api_version "$paper_api_val"; then
            pass "paper-plugin.yml api-version is within the documented 26.x / 1.21.x skill scope: $paper_api_val"
            warn_if_newer_than_documented_api_version "$paper_api_val" "paper-plugin.yml"
          elif [[ "$paper_api_val" =~ ^(1\.21\.|26\.)0[0-9]*$ ]]; then
            fail "paper-plugin.yml api-version release must be a positive integer without leading zeroes: $paper_api_val"
          elif [[ "$paper_api_val" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?$ ]]; then
            fail "paper-plugin.yml api-version is outside the documented 26.x / 1.21.x skill scope: $paper_api_val"
          else
            fail "paper-plugin.yml api-version has invalid format: $paper_api_val"
          fi
      
          if [[ -n "$PLUGIN_YML" && -n "$name_val" ]]; then
            [[ -n "$paper_name_val" && "$paper_name_val" == "$name_val" ]] && pass "paper-plugin.yml name matches plugin.yml" || fail "paper-plugin.yml name must match plugin.yml"
            [[ -n "$paper_version_val" && "$paper_version_val" == "$version_val" ]] && pass "paper-plugin.yml version matches plugin.yml" || fail "paper-plugin.yml version must match plugin.yml"
            [[ -n "$paper_api_val" && "$paper_api_val" == "$api_val" ]] && pass "paper-plugin.yml api-version matches plugin.yml" || fail "paper-plugin.yml api-version must match plugin.yml"
      
            if [[ -n "$paper_main_val" ]]; then
              [[ "$paper_main_val" == "$main_val" ]] && pass "paper-plugin.yml main matches plugin.yml" || fail "paper-plugin.yml main must match plugin.yml when declared"
            fi
          fi
        fi
      fi
      
      if [[ -z "$PLUGIN_YML" && -z "$PAPER_PLUGIN_YML" ]]; then
        fail "missing plugin descriptor (expected src/main/resources/plugin.yml or paper-plugin.yml)"
      elif [[ -n "$PAPER_PLUGIN_YML" ]]; then
        active_label="paper-plugin.yml"
        active_main_val="$paper_main_val"
        pass "using paper-plugin.yml as the active descriptor"
      else
        active_label="plugin.yml"
        active_main_val="$main_val"
        pass "using plugin.yml as the active descriptor"
      fi
      
      if [[ -n "$active_main_val" ]]; then
        class_path="${active_main_val//./\/}"
        java_file="$ROOT/src/main/java/$class_path.java"
        kotlin_file="$ROOT/src/main/kotlin/$class_path.kt"
      
        if [[ -f "$java_file" ]]; then
          pass "$active_label main class file exists: ${java_file#$ROOT/}"
          if grep -qE 'extends[[:space:]]+JavaPlugin' "$java_file"; then
            pass "$active_label main class extends JavaPlugin"
          else
            fail "$active_label main class does not extend JavaPlugin: ${java_file#$ROOT/}"
          fi
        elif [[ -f "$kotlin_file" ]]; then
          pass "$active_label main class file exists: ${kotlin_file#$ROOT/}"
          if grep -qE ':[[:space:]]*JavaPlugin\(\)' "$kotlin_file"; then
            pass "$active_label main Kotlin class extends JavaPlugin"
          else
            fail "$active_label main Kotlin class does not extend JavaPlugin: ${kotlin_file#$ROOT/}"
          fi
        else
          fail "$active_label main class file not found for '$active_main_val'"
        fi
      fi
      
      echo "Checking /reload anti-pattern..."
      if [[ -d "$ROOT/src" ]]; then
        warn_on_reload_misuse "$ROOT"
      else
        warn "src/ directory not found; skipped reload scan"
      fi
      
      echo ""
      if [[ "$FAILURES" -gt 0 ]]; then
        echo "$FAIL plugin layout validation failed with $FAILURES error(s) and $WARNINGS warning(s)"
        exit 1
      fi
      
      if [[ "$STRICT" -eq 1 && "$WARNINGS" -gt 0 ]]; then
        echo "$FAIL plugin layout strict mode failed on $WARNINGS warning(s)"
        exit 1
      fi
      
      echo "$PASS plugin layout validation passed with $WARNINGS warning(s)"
      
  • SKILL.md 16.8 KB
    ---
    name: minecraft-plugin-dev
    description: "Create, modify, and debug server plugins for current Paper 26.x on Java 25 or legacy Bukkit-derived 1.21.x servers on Java 21. Use for JavaPlugin APIs, events, commands, schedulers, configuration, PDC, and Adventure, not client mods or vanilla datapacks."
    ---
    
    # Minecraft Plugin Development Skill
    
    ## Platform Overview
    
    | Platform | Base API | Notes |
    |----------|----------|-------|
    | **Paper** | Bukkit/Spigot + Paper extensions | Recommended; async chunk loading, Adventure native |
    | **Spigot** | Bukkit + Spigot extensions | Legacy; fewer APIs, slower |
    | **Bukkit** | Base API only | Avoid for new plugins |
    | **Folia** | Paper fork | Region-threaded; requires special scheduler APIs |
    
    > Paper is the recommended target. Paper includes all Bukkit and Spigot APIs plus
    > significant performance improvements and additional APIs.
    
    ### Routing Boundaries
    - `Use when`: the target is server-side Paper/Bukkit/Spigot plugin behavior with JavaPlugin APIs.
    - `Do not use when`: the task requires client-side installable mods or loader APIs (`minecraft-modding` / `minecraft-multiloader`).
    - `Do not use when`: the task is pure vanilla datapack/command content (`minecraft-datapack` / `minecraft-commands-scripting`).
    
    ## Bundled References
    
    - Read `references/runtime-patterns.md` when the task touches scheduling, Folia support, PDC, Adventure/MiniMessage, YAML config, Vault, or Paper-specific APIs.
    - Read `references/paper-plugin-commands.md` for a Paper-only `paper-plugin.yml` project or Brigadier command registration.
    
    ---
    
    ## Project Setup
    
    The examples below target current Paper 26.2 and Java 25. For an existing
    1.21.x plugin, preserve its `1.21.x-R0.1-SNAPSHOT` dependency, Java 21
    toolchain, and matching `api-version` until the project is intentionally ported.
    
    ### `settings.gradle.kts`
    ```kotlin
    rootProject.name = "my-plugin"
    ```
    
    ### `build.gradle.kts`
    ```kotlin
    plugins {
        java
    }
    
    group = "com.example"
    version = "1.0.0-SNAPSHOT"
    
    repositories {
        mavenCentral()
        maven("https://repo.papermc.io/repository/maven-public/")
    }
    
    dependencies {
        compileOnly("io.papermc.paper:paper-api:26.2.build.+")
    }
    
    java {
        toolchain.languageVersion.set(JavaLanguageVersion.of(25))
    }
    
    tasks {
        processResources {
            // Substitutes ${version} in plugin.yml with the Gradle project version
            filesMatching(listOf("plugin.yml", "paper-plugin.yml")) {
                expand("version" to project.version)
            }
        }
    }
    ```
    
    Add Shadow only when the plugin has runtime libraries that must be bundled and
    relocated. Paper and optional plugin APIs such as Vault remain `compileOnly` and
    must not be shaded into the plugin JAR.
    
    ### `gradle/wrapper/gradle-wrapper.properties`
    ```properties
    distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-bin.zip
    ```
    
    Gradle 8.8 cannot run on Java 25. Use Gradle 9.1 or newer for a current Java 25
    project. Preserve the existing wrapper and Java 21 toolchain for a legacy 1.21.x
    project unless its build is intentionally upgraded and verified.
    
    ---
    
    ## Project Layout
    ```
    my-plugin/
    ├── build.gradle.kts
    ├── settings.gradle.kts
    ├── gradle/
    │   └── wrapper/
    │       └── gradle-wrapper.properties
    └── src/main/
        ├── java/com/example/myplugin/
        │   ├── MyPlugin.java          ← main class (extends JavaPlugin)
        │   ├── listeners/
        │   │   └── PlayerListener.java
        │   ├── commands/
        │   │   └── MyCommand.java
        │   └── managers/
        │       └── DataManager.java
        └── resources/
            ├── plugin.yml            ← Bukkit-compatible descriptor
            ├── paper-plugin.yml      ← active descriptor for a Paper plugin
            └── config.yml
    ```
    
    ---
    
    ## Core Files
    
    ### `plugin.yml` (Bukkit-compatible default)
    ```yaml
    name: MyPlugin
    version: "${version}"
    main: com.example.myplugin.MyPlugin
    description: An example Paper plugin
    author: YourName
    website: https://github.com/example/my-plugin
    api-version: '26.2'
    
    commands:
      myplugin:
        description: Main plugin command
        usage: /myplugin <subcommand>
        permission: myplugin.use
        aliases: [mp]
    
    permissions:
      myplugin.use:
        description: Allows use of /myplugin
        default: true
      myplugin.admin:
        description: Admin access
        default: op
    ```
    
    > Match `api-version` to the oldest Paper API the plugin intentionally supports.
    > Current Paper examples use `26.2`; legacy `1.21` and positive `1.21.<patch>`
    > values remain valid for older servers. A server older than the declared value
    > refuses to load the plugin.
    
    ### `paper-plugin.yml` (experimental Paper-only format)
    
    Prefer `plugin.yml` for Bukkit-compatible plugins. Use `paper-plugin.yml` only
    when the JAR is intentionally Paper-only and needs Paper-plugin behavior such
    as bootstrapping, loaders, or classloading isolation. It can be the only
    descriptor, but is not a drop-in replacement: Paper plugins do not use a
    `commands` field or `getCommand(...)` registration. Read
    [`references/paper-plugin-commands.md`](references/paper-plugin-commands.md)
    for the paired descriptor, main class, and Brigadier lifecycle registration.
    
    When one JAR ships both descriptors, keep their shared metadata and main class
    aligned. Do not combine the Paper-only sample with the Bukkit-compatible
    `MyPlugin` sample below.
    
    ### Bukkit-compatible main class
    ```java
    package com.example.myplugin;
    
    import com.example.myplugin.commands.MyCommand;
    import com.example.myplugin.listeners.PlayerListener;
    import org.bukkit.plugin.java.JavaPlugin;
    
    public final class MyPlugin extends JavaPlugin {
    
        @Override
        public void onEnable() {
            saveDefaultConfig();
    
            // Register listeners
            getServer().getPluginManager().registerEvents(new PlayerListener(), this);
    
            // Register commands
            var cmd = getCommand("myplugin");
            if (cmd == null) {
                throw new IllegalStateException("myplugin command is missing from plugin.yml");
            }
            var handler = new MyCommand(this);
            cmd.setExecutor(handler);
            cmd.setTabCompleter(handler);
    
            getLogger().info("MyPlugin enabled!");
        }
    
        @Override
        public void onDisable() {
            getLogger().info("MyPlugin disabled.");
        }
    
    }
    ```
    
    ---
    
    ## Event Listeners
    
    ```java
    package com.example.myplugin.listeners;
    
    import net.kyori.adventure.text.Component;
    import net.kyori.adventure.text.format.NamedTextColor;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.EventPriority;
    import org.bukkit.event.Listener;
    import org.bukkit.event.entity.PlayerDeathEvent;
    import org.bukkit.event.player.PlayerJoinEvent;
    import org.bukkit.event.player.PlayerQuitEvent;
    
    public class PlayerListener implements Listener {
    
        @EventHandler(priority = EventPriority.NORMAL)
        public void onPlayerJoin(PlayerJoinEvent event) {
            event.joinMessage(
                Component.text(event.getPlayer().getName() + " joined!", NamedTextColor.GREEN)
            );
        }
    
        @EventHandler
        public void onPlayerQuit(PlayerQuitEvent event) {
            event.quitMessage(
                Component.text(event.getPlayer().getName() + " left.", NamedTextColor.YELLOW)
            );
        }
    
        @EventHandler
        public void onPlayerDeath(PlayerDeathEvent event) {
            // Modify death message using Adventure components
            event.deathMessage(
                Component.text("☠ ", NamedTextColor.RED)
                    .append(Component.text(event.getPlayer().getName(), NamedTextColor.WHITE))
                    .append(Component.text(" died!", NamedTextColor.RED))
            );
        }
    }
    ```
    
    ### EventPriority order
    `LOWEST → LOW → NORMAL → HIGH → HIGHEST → MONITOR`  
    Use `MONITOR` for logging only (never modify outcome). On events that implement
    `Cancellable`, use `ignoreCancelled = true` unless you need cancelled events.
    
    ### Cancellable events
    ```java
    @EventHandler
    public void onBlockBreak(BlockBreakEvent event) {
        if (event.getPlayer().hasPermission("myplugin.break.deny")) {
            event.setCancelled(true);
            event.getPlayer().sendMessage(Component.text("You cannot break blocks!", NamedTextColor.RED));
        }
    }
    ```
    
    ---
    
    ## Commands
    
    This section is for the `plugin.yml` path above. Its declared command enables
    `getCommand("myplugin")`. For a Paper-only descriptor, use the Brigadier
    lifecycle example in [`references/paper-plugin-commands.md`](references/paper-plugin-commands.md).
    
    ```java
    package com.example.myplugin.commands;
    
    import com.example.myplugin.MyPlugin;
    import net.kyori.adventure.text.Component;
    import net.kyori.adventure.text.format.NamedTextColor;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.command.TabCompleter;
    import org.bukkit.entity.Player;
    import org.jetbrains.annotations.NotNull;
    import org.jetbrains.annotations.Nullable;
    
    import java.util.List;
    import java.util.Locale;
    
    public class MyCommand implements CommandExecutor, TabCompleter {
    
        private final MyPlugin plugin;
    
        public MyCommand(MyPlugin plugin) {
            this.plugin = plugin;
        }
    
        @Override
        public boolean onCommand(@NotNull CommandSender sender, @NotNull Command command,
                                 @NotNull String label, @NotNull String[] args) {
            if (!(sender instanceof Player player)) {
                sender.sendMessage(Component.text("Only players can use this command.", NamedTextColor.RED));
                return true;
            }
    
            if (!player.hasPermission("myplugin.use")) {
                player.sendMessage(Component.text("No permission.", NamedTextColor.RED));
                return true;
            }
    
            if (args.length == 0) {
                player.sendMessage(Component.text("Usage: /myplugin <reload|info>", NamedTextColor.YELLOW));
                return true;
            }
    
            return switch (args[0].toLowerCase(Locale.ROOT)) {
                case "reload" -> {
                    plugin.reloadConfig();
                    player.sendMessage(Component.text("Config reloaded.", NamedTextColor.GREEN));
                    yield true;
                }
                case "info" -> {
                    player.sendMessage(Component.text("Version: " + plugin.getDescription().getVersion(), NamedTextColor.AQUA));
                    yield true;
                }
                default -> {
                    player.sendMessage(Component.text("Unknown subcommand.", NamedTextColor.RED));
                    yield true;
                }
            };
        }
    
        @Override
        public @Nullable List<String> onTabComplete(@NotNull CommandSender sender, @NotNull Command command,
                                                    @NotNull String label, @NotNull String[] args) {
            if (args.length == 1) {
                return List.of("reload", "info").stream()
                    .filter(s -> s.startsWith(args[0].toLowerCase(Locale.ROOT)))
                    .toList();
            }
            return List.of();
        }
    }
    ```
    
    ---
    
    ## Schedulers
    
    For classic Paper plugins, `BukkitScheduler` is still fine. If you claim Folia support,
    route player, entity, region, global, and async work through the matching Folia-aware
    scheduler. Keep scheduling behind a small project-local interface when one plugin must
    support both Paper and Folia.
    
    See `references/runtime-patterns.md` for copy-ready sync, async, cancelable, and
    Folia-safe scheduler examples.
    
    ---
    
    ## Persistent Data Container (PDC)
    
    PDC stores arbitrary data on any `PersistentDataHolder` (players, entities, items, chunks).
    Data is saved with the world and persists across restarts.
    
    Create `NamespacedKey` instances once, keep data types stable after release, and use
    PDC for small metadata rather than large datasets. Prefer config files or a database
    for large or query-heavy plugin state.
    
    See `references/runtime-patterns.md` for player, item, chunk, and world PDC examples.
    
    ---
    
    ## Adventure Text Components
    
    Paper uses [Adventure](https://docs.advntr.dev/) natively for all text. No legacy chat colors.
    Use `Component` builders for code-owned messages and MiniMessage for config-driven
    messages. Avoid legacy `ChatColor` unless the target project already depends on it
    for compatibility.
    
    See `references/runtime-patterns.md` for simple messages, hover/click events,
    MiniMessage parsing, titles, and action bars.
    
    ---
    
    ## Configuration (YAML)
    
    ### `src/main/resources/config.yml`
    ```yaml
    # Default config
    settings:
      max-players: 20
      welcome-message: "<green>Welcome to the server!"
      cooldown-seconds: 30
    
    database:
      host: localhost
      port: 3306
      name: myplugin_db
    ```
    
    ### Accessing config values
    Call `saveDefaultConfig()` in `onEnable()`, provide explicit defaults when reading
    values, and validate config shape before starting long-running tasks.
    
    ### Custom config file
    Use custom YAML files only when separating user config from mutable plugin data is
    worth the extra file handling. Keep blocking disk writes off hot event paths.
    
    See `references/runtime-patterns.md` for config read/write and custom YAML examples.
    
    ---
    
    ## Vault Integration (Economy / Permissions)
    
    Declare Vault as `compileOnly`, soft-depend on it in plugin metadata, and disable
    economy features cleanly when the service provider is unavailable. Never assume a
    Vault-compatible economy plugin is installed just because Vault itself is present.
    
    When Vault support is required, add the JitPack repository and
    `compileOnly("com.github.MilkBowl:VaultAPI:1.7")` to the Gradle build.
    
    See `references/runtime-patterns.md` for a minimal economy setup and charge example.
    
    ---
    
    ## Paper-Specific APIs
    
    Use Paper APIs when they remove main-thread blocking or simplify Adventure-native
    behavior. Keep optional plugin integrations behind presence checks and metadata
    soft-dependencies.
    
    See `references/runtime-patterns.md` for async chunk loading, custom item meta,
    profile lookup, and protection-plugin integration examples.
    
    ---
    
    ## Common Tasks Checklist
    
    ### Creating a new event listener
    - [ ] Create class implementing `Listener`
    - [ ] Annotate methods with `@EventHandler`
    - [ ] Call `getServer().getPluginManager().registerEvents(listener, plugin)` in `onEnable()`
    - [ ] On cancellable events, add `ignoreCancelled = true` unless you need cancelled events
    
    ### Adding a new command
    - [ ] For a Bukkit-compatible plugin, define the command in `plugin.yml`, create a `CommandExecutor`, and register it with `getCommand("name")`
    - [ ] For a Paper-only plugin, register the command through `LifecycleEvents.COMMANDS`; do not add a `commands` field
    
    ### Saving plugin data
    - [ ] For simple values: use `config.yml` via `getConfig()` / `saveConfig()`
    - [ ] For per-entity data: use PDC with a `NamespacedKey`
    - [ ] For large datasets: use async scheduler + file I/O or a database
    
    ### Scheduling a repeating task
    - [ ] Determine if task needs main thread (use `runTaskTimer`) or is I/O (use `runTaskTimerAsynchronously`)
    - [ ] Store the `BukkitTask` reference so you can cancel in `onDisable()`
    - [ ] Cancel all tasks in `onDisable()` or use `getServer().getScheduler().cancelTasks(plugin)`
    
    ---
    
    ## Build, Validate, and Run
    
    1. Build the plugin JAR:
       ```bash
       ./gradlew build
       # Output: build/libs/my-plugin-1.0.0-SNAPSHOT.jar
       ```
    2. Run the bundled validator to catch config and layout errors:
       ```bash
       ./scripts/validate-plugin-layout.sh --root /path/to/plugin-project
       # Strict mode treats warnings as failures:
       ./scripts/validate-plugin-layout.sh --root /path/to/plugin-project --strict
       ```
       The validator requires Node and includes its own YAML parser for descriptor checks.
    3. Fix any reported errors and re-run until clean.
    4. Deploy: copy the built JAR to `server/plugins/` and restart the Paper server.
       If the real project already applies a Paper dev-server plugin such as `xyz.jpenilla.run-paper`,
       use that project's documented dev task instead of assuming `./gradlew runServer` exists.
    
    The validator checks:
    - active `plugin.yml` or `paper-plugin.yml` required keys (`name`, `version`, `main`, `api-version`) and repo-supported current `26.<release>` or legacy `1.21` / positive `1.21.<patch>` values, with warnings for versions newer than the documented examples
    - cross-descriptor metadata consistency when both descriptors are present; `paper-plugin.yml` is selected as active
    - Active main class path exists and extends `JavaPlugin`
    - actual server `/reload` anti-patterns such as `Bukkit.reload()` or dispatching the server reload command
    
    ---
    
    ## References
    
    - Paper API Javadoc: https://jd.papermc.io/paper/
    - Paper plugin descriptor: https://docs.papermc.io/paper/dev/plugin-yml/
    - Paper plugins: https://docs.papermc.io/paper/dev/getting-started/paper-plugins/
    - Paper Brigadier registration: https://docs.papermc.io/paper/dev/command-api/basics/registration/
    - Gradle Java compatibility: https://docs.gradle.org/current/userguide/compatibility.html
    - Adventure (text API): https://docs.advntr.dev/
    - MiniMessage format: https://docs.advntr.dev/minimessage/format.html
    - Vault API: https://github.com/MilkBowl/VaultAPI
    - Bukkit API Javadoc: https://javadoc.io/doc/org.bukkit/bukkit/
    - run-task Gradle plugin: https://github.com/jpenilla/run-task
    

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related