Python client library for controlling Minecraft servers remotely.
Installation
Install MCPyLib using pip:
pip install mcpylib
Or using uv (faster alternative):
uv pip install mcpylib
Want faster package management? Try uv!
uv is a blazing-fast Python package manager (10-100x faster than pip).
Install uv
# On macOS/Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# On macOS with Homebrew
brew install uv
# On Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
# quickstart.py
from mcpylib import MCPyLib
# Initialize client
mc = MCPyLib(
ip="127.0.0.1", # Server IP
port=65535, # Server port
token="your_token" # Authentication token
)
# Set a diamond block
mc.setblock(100, 64, 200, "minecraft:diamond_block")
# Get block type
block = mc.getblock(100, 64, 200)
print(f"Block: {block}") # Output: Block: minecraft:diamond_block
# Fill an 11x11x11 region with glass (both corners are included)
count = mc.fill(0, 60, 0, 10, 70, 10, "minecraft:glass")
print(f"Filled {count} blocks") # Output: Filled 1331 blocks
# Get player position
pos = mc.getPos("Steve")
print(f"Player at: {pos}") # Output: Player at: [100, 64, 200]
# Close the connection when you are done
mc.close()
Run the script
# With uv (recommended)
uv run python quickstart.py
# Or with pip
python quickstart.py
The client opens one TCP connection on the first command and reuses it for every later command. If the server closed it (for example after a restart or the server's idle timeout), the next command reconnects automatically. A command that times out raises ConnectionError and is not sent again, because it may still have run on the server.
Call close() when you are done, or use the client as a context manager:
with MCPyLib(token="your_token") as mc:
mc.setblock(100, 64, 200, "minecraft:stone")
Methods
This page covers the core methods. The client has 72 commands in total (effects, inventory, entities, villagers, scoreboards, teams, boss bars, world generation and more); see the full API reference.
Set a block at the specified coordinates with optional block state and NBT data.
Parameters:
x, y, z (int): Block coordinates
block_name (str): Block type (e.g., "minecraft:stone" or "stone"). Item ids that are not blocks (such as "brick") are rejected.
block_state (dict, optional): Block state properties like direction, rotation, etc. Every vanilla property is supported.
nbt (dict, optional): Block entity data. Only "CustomName" (plain-text name for containers such as chests) and "Text1"-"Text4" (sign lines) are applied; other keys are ignored.
Returns:
1 if successful
Raises:
ConnectionError: Failed to connect to server
AuthenticationError: Invalid token
CommandError: Invalid coordinates, block type, or state properties
Example:
# Basic block placement
mc.setblock(100, 64, 200, "minecraft:diamond_block")
mc.setblock(101, 64, 200, "gold_block") # "minecraft:" prefix is optional
# Place a stair facing north
mc.setblock(100, 64, 201, "oak_stairs", block_state={"facing": "north", "half": "bottom"})
# Place a fence gate facing east
mc.setblock(100, 64, 202, "oak_fence_gate", block_state={"facing": "east", "open": "false"})
# Place a log with horizontal axis
mc.setblock(100, 64, 203, "oak_log", block_state={"axis": "x"})
# Place a sign with text
mc.setblock(100, 64, 204, "oak_sign",
block_state={"rotation": "0"},
nbt={"Text1": "Hello", "Text2": "World", "Text3": "", "Text4": ""}
)
# Place a chest with custom name (plain text)
mc.setblock(100, 64, 205, "chest",
block_state={"facing": "north"},
nbt={"CustomName": "My Chest"}
)
# Place a waterlogged fence
mc.setblock(100, 64, 206, "oak_fence", block_state={"waterlogged": "true"})
# Place a door: upper half first, then the lower half
mc.setblock(100, 65, 207, "oak_door", block_state={"facing": "south", "half": "upper"})
mc.setblock(100, 64, 207, "oak_door", block_state={"facing": "south", "half": "lower"})
Common Block State Properties (any vanilla property works):
facing: Direction the block faces ("north", "south", "east", "west", "up", "down")
rotation: Rotation for signs and banners ("0" to "15")
axis: Axis for logs and pillars ("x", "y", "z")
half: "top"/"bottom" for stairs and trapdoors, "upper"/"lower" for doors and tall plants
type: Slab type ("top", "bottom", "double")
part: Bed part ("head", "foot")
shape: Stair shape ("straight", "inner_left", "inner_right", "outer_left", "outer_right"); the game recalculates it when neighboring blocks change
open: Whether doors/gates are open ("true", "false")
powered: Whether redstone components are powered ("true", "false")
waterlogged: Whether block contains water ("true", "false")
For two-block blocks, place both halves: a door's upper half before its lower half, a bed's head before its foot. In the other order the server's block update breaks the half placed first.
Get all blocks in a rectangular region as a 3D array. The returned format is [x][y][z], compatible with edit().
Parameters:
x1, y1, z1 (int): Starting coordinates
x2, y2, z2 (int): Ending coordinates
Returns:
3D list of block type strings (e.g., "minecraft:stone")
Raises:
ConnectionError: Failed to connect to server
AuthenticationError: Invalid token
CommandError: Invalid coordinates
Example:
# Read a region
blocks = mc.getblocks(100, 64, 200, 105, 66, 205)
print(blocks[0][0][0]) # "minecraft:stone"
# Read, modify, and write back
blocks = mc.getblocks(100, 64, 200, 110, 68, 210)
for x in range(len(blocks)):
for y in range(len(blocks[0])):
for z in range(len(blocks[0][0])):
if blocks[x][y][z] == "minecraft:stone":
blocks[x][y][z] = "minecraft:diamond_block"
mc.edit(100, 64, 200, blocks)
action (str): Action to perform ("set", "add", "query")
value (int, optional): Time in ticks for "set" (0-24000) or "add"
Returns:
Current world time (0-24000)
Raises:
ConnectionError: Failed to connect to server
AuthenticationError: Invalid token
CommandError: Invalid action or value out of range
Example:
# Set time to day (1000)
mc.time("set", 1000)
# Add 6000 ticks
mc.time("add", 6000)
# Query current time
current_time = mc.time("query")
print(f"Current time: {current_time}")
weather()
weather(condition: str, duration: int = None) -> bool
selector (str): Entity selector (only these three forms; vanilla selectors such as "@e[type=zombie]" and UUIDs are rejected):
"all" - Remove every non-player entity, including dropped items, armor stands and item frames
Entity type (e.g., "zombie", "creeper") - Remove all of that type
"player:username" - Kill a specific player
Returns:
Number of entities killed. "all" and entity types act on the main world, only on loaded chunks, and remove at most 1000 entities per call.
Raises:
ConnectionError: Failed to connect to server
AuthenticationError: Invalid token
CommandError: Invalid selector or player not found
Example:
# Kill all entities
count = mc.kill("all")
print(f"Killed {count} entities")
# Kill all zombies
zombie_count = mc.kill("zombie")
# Kill all creepers
creeper_count = mc.kill("creeper")
# Kill a specific player
mc.kill("player:Steve")
edit()
edit(x: int, y: int, z: int, blocks: List[List[List]]) -> int
High-performance bulk block editing (like WorldEdit). Place large structures with mixed block types in a single operation.
Parameters:
x, y, z (int): Starting coordinates
blocks (List[List[List]]): 3D array of blocks [x][y][z], where each element can be:
str: Block name (e.g., "stone", "minecraft:glass")
None: Skip this position (leave unchanged)
dict: Complex block with state and NBT:
{
"block": "minecraft:chest",
"block_state": {"facing": "north"}, # Optional
"nbt": {"CustomName": "Storage"} # Optional, same keys as setblock()
}
Returns:
Number of blocks placed (None entries are not counted)
Raises:
ConnectionError: Failed to connect to server
AuthenticationError: Invalid token
CommandError: Invalid block data or coordinates
Example:
# Simple 2x2x2 cube
blocks = [
[["stone", "glass"], ["stone", "glass"]],
[["stone", "glass"], ["stone", "glass"]]
]
mc.edit(100, 64, 200, blocks)
# Mixed mode with complex blocks
blocks = [
[[None, "stone"], ["glass", None]],
[[{
"block": "minecraft:chest",
"block_state": {"facing": "north"},
"nbt": {"CustomName": "Loot"}
}, "stone"], ["diamond_block", "gold_block"]]
]
mc.edit(100, 64, 200, blocks)
# Build a house
blocks = []
for x in range(10):
x_layer = []
for y in range(5):
y_layer = [None] * 10
x_layer.append(y_layer)
blocks.append(x_layer)
# Floor
for x in range(10):
for z in range(10):
blocks[x][0][z] = "stone"
# Walls
for y in range(1, 4):
for x in range(10):
blocks[x][y][0] = "cobblestone"
blocks[x][y][9] = "cobblestone"
for z in range(10):
blocks[0][y][z] = "cobblestone"
blocks[9][y][z] = "cobblestone"
# Roof
for x in range(10):
for z in range(10):
blocks[x][4][z] = "oak_planks"
count = mc.edit(100, 64, 200, blocks)
print(f"House built: {count} blocks")
Performance Notes:
Use edit() for structures with multiple different block types
Use fill() for large areas of the same block
Much faster than calling setblock() repeatedly
Supports thousands of blocks in a single operation
Place doors and beds with setblock() (see above) rather than edit()
CommandError: Region too large (max 32,768 blocks)
Example:
# Clone an 11x11x11 region (both corners are included)
count = mc.clone(0, 64, 0, 10, 74, 10, 20, 64, 0)
print(f"Cloned {count} blocks") # "Cloned 1331 blocks"
# Copy a house from one location to another
mc.clone(100, 64, 100, 110, 74, 110, 200, 64, 200)
Exception Handling
MCPyLib defines custom exceptions:
from mcpylib import MCPyLib, MCPyLibError, ConnectionError, AuthenticationError, CommandError
try:
mc = MCPyLib(token="wrong_token")
mc.setblock(100, 64, 200, "minecraft:stone")
except AuthenticationError as e:
print(f"Authentication failed: {e}")
except ConnectionError as e:
print(f"Connection failed: {e}")
except CommandError as e:
print(f"Command failed: {e}")
except MCPyLibError as e:
print(f"General error: {e}")
Block Names
Block names can be specified with or without the "minecraft:" namespace prefix:
See the Minecraft Wiki for a complete list of block IDs. Use block ids, not item ids: "bricks" is the block, "brick" the item.
Advanced Usage
Custom Timeout
# Set a longer timeout for slow connections
mc = MCPyLib(
ip="192.168.1.100",
port=65535,
token="your_token",
timeout=30.0 # 30 seconds
)
Building Structures
def build_cube(mc, x, y, z, size, block):
"""Build a hollow cube"""
# Bottom and top
mc.fill(x, y, z, x+size, y, z+size, block)
mc.fill(x, y+size, z, x+size, y+size, z+size, block)
# Sides
mc.fill(x, y, z, x, y+size, z+size, block)
mc.fill(x+size, y, z, x+size, y+size, z+size, block)
mc.fill(x, y, z, x+size, y+size, z, block)
mc.fill(x, y, z+size, x+size, y+size, z+size, block)
# Build a hollow 11x11x11 glass cube (from x to x+size, inclusive)
build_cube(mc, 0, 64, 0, 10, "glass")
Following Players
import time
from mcpylib import CommandError
def follow_player(mc, username, interval=1.0):
"""Track player movement"""
try:
while True:
pos = mc.getPos(username)
print(f"{username} is at {pos}")
time.sleep(interval)
except KeyboardInterrupt:
print("Stopped tracking")
except CommandError as e:
print(f"Error: {e}")
follow_player(mc, "Steve")
Requirements
Python 3.11 or higher
A Paper or Spigot 26.1+ server running the MCPyLib plugin 1.2.0
Runtime dependency: python-dotenv (installed automatically; the client itself only uses the standard library, python-dotenv is there for loading .env files in scripts and the examples)