Skip to main content

MindPy

A Python-first, asyncio-native framework for building intelligent Minecraft bots.

CI PyPI Python License: MIT


MindPy lets you write Python bots for Minecraft servers — from a simple greeter to a full autonomous AI agent — using a clean, event-driven API with zero external Minecraft dependencies.

import asyncio
from mindpy import Bot, EventTypes, Event

async def main():
    async with Bot("mc.example.com", username="Scout") as bot:

        @bot.on(EventTypes.BOT_SPAWNED)
        async def on_spawn(event: Event) -> None:
            await bot.chat("Hello, world!")

        @bot.on(EventTypes.CHAT_MESSAGE)
        async def on_chat(event: Event) -> None:
            raw = event.data["raw"]
            if "come here" in raw:
                await bot.chat("On my way!")

        await bot.run()

asyncio.run(main())

Features

Category Capabilities
Protocol Asyncio-native MC Java Edition 1.8 → 1.21+, no external dependency
Auth Offline mode + Microsoft OAuth2 (Device Code Flow) online mode
World numpy uint16 chunk storage, 3-D spatial entity index
Navigation A* pathfinding (Chebyshev heuristic), waypoints, path smoothing
AI OpenAI / Anthropic / Gemini / Ollama LLM providers, tool calling, reflection
Memory Working, short-term, long-term, conversation, world, player, task, knowledge-base
Tasks Interruptible, suspendable, serializable, cancelable task system
Goals Hierarchical goal decomposition
Events Priority-sorted publish/subscribe with wildcard patterns & SubscriptionToken
Plugins Auto-discovery, dependency resolution, lifecycle hooks
Config YAML / JSON / TOML / env-var config with sentinel-safe fallbacks
CI ruff, mypy, pytest on Ubuntu + Windows, PyPI trusted publishing

Installation

Requires Python ≥ 3.12

pip install mindpy

With LLM support:

pip install "mindpy[llm]"      # OpenAI, Anthropic, Gemini

Development install:

git clone https://github.com/CybersharpX/MindPy.git
cd MindPy
pip install -e ".[dev,llm]"
pre-commit install

Quick Start

Offline mode (cracked server)

import asyncio
from mindpy import Bot, EventTypes, Event

async def main():
    bot = Bot(host="localhost", port=25565, username="MyBot")

    @bot.on(EventTypes.BOT_CONNECTED)
    async def ready(event: Event) -> None:
        await bot.chat("MindPy is online!")

    async with bot:
        await bot.run()

asyncio.run(main())

Online mode (Microsoft account)

import asyncio
from mindpy import Bot
from mindpy.protocol.auth import MicrosoftAuth

async def main():
    # Authenticate once — paste the URL into your browser
    async with MicrosoftAuth() as auth:
        profile = await auth.device_flow_auth()

    async with Bot("mc.example.com", auth_profile=profile, online_mode=True) as bot:
        await bot.run()

asyncio.run(main())

Choosing a protocol version

from mindpy import Bot
from mindpy.protocol.codec import ProtocolRegistry

# List all explicitly supported versions
print(ProtocolRegistry.supported_versions())
# [47, 340, 754, 762, 765, 769]

# 47  = Minecraft 1.8
# 340 = Minecraft 1.12.2
# 754 = Minecraft 1.16.5
# 762 = Minecraft 1.19.4
# 765 = Minecraft 1.20.4
# 769 = Minecraft 1.21+   (also used as fallback for 1.21.x patches)

bot = Bot("localhost", protocol_version=769)  # explicitly use 1.21

Event System

Every in-game event flows through the EventBus:

from mindpy import Bot, Event, EventTypes
from mindpy.events import handler          # class-level decorator
from mindpy.events.event import EventPriority

bot = Bot("localhost")

# --- Option 1: fluent bot.on() decorator ---
@bot.on(EventTypes.CHAT_MESSAGE, priority=EventPriority.HIGH)
async def on_chat(event: Event) -> None:
    print(event.data["raw"])

# --- Option 2: wildcard subscription ---
@bot.on("bot.*")
async def on_any_bot_event(event: Event) -> None:
    print(f"[bot] {event.event_type}")

# --- Option 3: SubscriptionToken (cancel later) ---
token = bot.event_bus.subscribe("player.joined", on_chat)
# ... later:
token.cancel()

# --- Option 4: wait for a single event ---
event = await bot.event_bus.wait_for(EventTypes.BOT_SPAWNED, timeout=30.0)

Built-in event types (mindpy.events.event.EventTypes):

Event Trigger
bot.connected TCP connection + login succeeded
bot.disconnected Graceful or forced disconnect
bot.spawned JoinGame packet received
bot.died Health reached 0
bot.health_changed UpdateHealth packet
bot.position_changed Server-forced teleport
bot.reconnecting Reconnect attempt starting
bot.error Unhandled connection error
chat.message Any chat packet received
chunk.loaded / chunk.unloaded World chunk events
entity.* Entity spawn/despawn/move/damage
task.* / goal.* Task and goal lifecycle
plugin.* Plugin load/unload

Bot API Reference

Full documentation available at docs/BOT_API.md

Bot.__init__

Bot(
    host: str = "localhost",
    port: int = 25565,
    username: str = "MindPyBot",
    auth_profile: AuthProfile | None = None,
    protocol_version: int = 765,       # 1.20.4 default
    online_mode: bool = False,
    view_distance: int = 10,
    config: Config | None = None,
)

Core methods

Method Description
await bot.connect() TCP connect + full login sequence
await bot.disconnect() Graceful disconnect, publishes event
await bot.reconnect() Exponential-backoff retry loop
await bot.run() Block until disconnected
await bot.chat(msg) Send chat message (truncated to 256 chars)
await bot.say(msg) Alias for chat()
await bot.move_to(x, y, z) Send position update packet
bot.is_connected() True if in PLAY state
bot.get_position() (x, y, z) tuple
bot.get_health() Current health (0.0–20.0)
bot.get_hunger() Current food level (0–20)

High-level API

MindPy provides three levels of abstraction:

Level 1 - Core API:

  • Connection, chat, movement, interaction
  • Event system, state access
  • Inventory, world, entities

Level 2 - Bot Tools:

  • bot.goto() - Pathfinding navigation
  • bot.mine() - Resource gathering
  • bot.craft() - Crafting operations
  • bot.attack() - Combat actions
  • bot.equip_best_tool() - Tool selection

Level 3 - Intelligent Behaviors:

  • bot.explore() - Autonomous exploration
  • bot.guard() - Area protection
  • bot.farm() - Automated farming
  • bot.build() - Construction tasks

See docs/BOT_API.md for complete API documentation.

BotState fields

bot.state.connected       # bool
bot.state.health          # float (0.0–20.0)
bot.state.hunger          # int (0–20)
bot.state.saturation      # float
bot.state.x, .y, .z       # float – world position
bot.state.yaw, .pitch     # float – look direction
bot.state.entity_id       # int – server-assigned entity ID
bot.state.game_mode       # int – 0=survival 1=creative 2=adventure 3=spectator
bot.state.dimension       # str – e.g. "minecraft:overworld"
bot.state.position        # property → (x, y, z)

Protocol Layer

mindpy.protocol is a standalone asyncio-native Minecraft protocol implementation — no any other external MC protocol library needed.

from mindpy.protocol import MinecraftConnection, ProtocolRegistry, ConnectionState
from mindpy.protocol.login import LoginOrchestrator

# Low-level usage (normally you just use Bot)
conn = MinecraftConnection("localhost", 25565, protocol_version=765, registry=...)
await conn.connect()

orchestrator = LoginOrchestrator(conn, username="Bot")
await orchestrator.login()    # transitions conn to PLAY state

# Register per-packet handlers
from mindpy.protocol.versions.v765 import KeepAliveClientboundPacket

@conn.on_packet(KeepAliveClientboundPacket)
async def handle_ka(packet):
    ...

AI Integration

import asyncio
from mindpy import Bot, EventTypes, Event
from mindpy.llm import LLMManager
from mindpy.ai import AIAgent, AgentContext

async def main():
    # Setup LLM
    llm = LLMManager()
    llm.setup_openai(api_key="sk-...", model="gpt-4o")

    agent = AIAgent(llm, system_prompt="You are a Minecraft helper bot.")

    bot = Bot("localhost")

    @bot.on(EventTypes.CHAT_MESSAGE)
    async def on_chat(event: Event) -> None:
        raw = event.data.get("raw", "")
        ctx = AgentContext(position=bot.state.position, health=bot.state.health)
        reply = await agent.decide(ctx, user_message=raw)
        await bot.chat(reply[:256])

    async with bot:
        await bot.run()

asyncio.run(main())

Testing

# Run all tests
pytest

# Run only protocol tests
pytest tests/test_protocol.py -v

# Run with coverage
pytest --cov=mindpy --cov-report=term-missing

More test commands and conventions are documented in docs/testing.md.


Documentation

Doc Link
Getting Started docs/getting-started.md
Architecture docs/architecture.md
API Reference docs/api.md
Plugin Development docs/plugin-development.md
Protocol Guide docs/protocol.md
Examples examples/

Contributing

See CONTRIBUTING.md. PRs are welcome!

git clone https://github.com/CybersharpX/MindPy.git
cd MindPy
pip install -e ".[dev]"
pre-commit install
pytest

License

MIT — see LICENSE.


MindPy is inspired by Mineflayer but is a ground-up Python reimplementation with a native asyncio protocol layer, numpy world storage, and first-class AI/LLM integration.

Release files for mindpy 0.2.8

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for mindpy 0.2.8
File Size Uploaded
mindpy-0.2.8.tar.gz 123.1 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for mindpy 0.2.8
File Interpreter ABI Platform
mindpy-0.2.8-py3-none-any.whl Python 3 none any Details

Total release size: 295.6 kB

Release files / mindpy-0.2.8.tar.gz

Download URL mindpy-0.2.8.tar.gz
Size 123.1 kB
Tags Source
SHA-256 checksum
How to use checksums
84175f3bf9c48235c201270cd8e1f5407a5a4aced36d218ccc462024b334a171
BLAKE2b-256 checksum
How to use checksums
b34c5a1b9f2821802d0ce56c4876c07636571057cbb19d13bdf8cdb84db8fefc
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.2

Release files / mindpy-0.2.8-py3-none-any.whl

Download URL mindpy-0.2.8-py3-none-any.whl
Size 172.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
bcde426b269f3e9af52cb3c54abc449eda2439ddad97e59ade53e3f5752e657b
BLAKE2b-256 checksum
How to use checksums
e119ac3ba170bf63966ea2227e2128d703195106c4ee77b34a74597208da59ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.14.2

Release history Release notifications | RSS feed

This release

0.2.8 This release

2 release files

0.2.5

2 release files

0.2.1

2 release files

0.2.0

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page