API Reference¶
Auto-generated from source via mkdocstrings.
Private names (_*) are filtered out. Prefer the public re-exports on
mcbe_ws_sdk when writing host code.
Public package¶
mcbe_ws_sdk
¶
Generic WebSocket gateway SDK for Minecraft Bedrock Edition.
Public surface¶
The gateway SDK exposes a dual-layer interface:
- Low-level: subscribe to an :class:
~mcbe_ws_sdk.gateway.events.EventBuskeyed by :class:~mcbe_ws_sdk.gateway.events.WsEventType. - High-level: implement :class:
~mcbe_ws_sdk.gateway.hook.ConnectionHookand :class:~mcbe_ws_sdk.gateway.sink.ResponseSink, then drive the stack through :class:~mcbe_ws_sdk.gateway.server_facade.McbeServerFacade.
The full connection lifetime, packet request abstraction and byte-safe command chunking are provided; the agent's LLM / message-broker concerns are the host's.
Modules:
-
addon–Addon bridge capability for the MCBE WebSocket SDK.
-
command–Command parsing package: registry + parsed-command value object.
-
config– -
delivery–Outbound delivery adapter for MCBE WebSocket gateway.
-
errors–Public exception hierarchy for mcbe-ws-sdk.
-
flow–Flow control middleware for outbound MCBE command chunking.
-
gateway–MCBE WebSocket gateway SDK.
-
logging–Optional console logging helpers for hosts and examples.
-
profiles–Protocol profiles for MCBE wire compatibility layers.
-
protocol–Minecraft protocol message models.
Classes:
-
AddonBridgeClient–Face an Agent uses to reach the addon bridge.
-
AddonBridgeService–Manage the request/response lifecycle between Python and the addon.
-
ConnectionAddonBridgeClient–Per-connection client bound to one bridge service instance.
-
CommandRegistry–Registry of command prefixes, types, and aliases.
-
McbeOutboundDelivery–Chunk, throttle, send, and optionally log MCBE
commandRequestpayloads. -
BridgeClosedError–Raised when an add-on bridge is closed.
-
BridgeError–Base class for add-on bridge errors.
-
BridgeLimitError–Raised when an add-on bridge protocol limit is exceeded.
-
BridgeTimeoutError–Raised when an add-on bridge request times out.
-
ConfigurationError–Raised when SDK settings are invalid.
-
FacadeLifecycleError–Raised for invalid server facade lifecycle transitions.
-
FrameTooLargeError–Raised when a frame cannot fit within its configured byte budget.
-
McbeWsSdkError–Base class for SDK errors.
-
ProtocolError–Raised when a protocol contract is violated.
-
FlowControlMiddleware–Unified flow control: split outbound long text into safe Minecraft commands.
-
ConnectionHook–Lifecycle + protocol hooks the host injects into the gateway.
-
ConnectionManager–Owns active connections and their response-sender coroutines.
-
ConnectionState–Transport-agnostic connection identity.
-
DefaultResponseSink–Gateway default sink: logs metadata, delivers nothing to game.
-
EventBus–A typed in-process event bus keyed by :class:
WsEventType. -
McbeServerFacade–Owns the WS transport + connection/protocol machinery; host injects the rest.
-
MessageSurfaceConfig–Presentation strings the protocol handler renders status messages with.
-
MinecraftProtocolHandler–Constructs / parses MCBE connection-lifecycle protocol messages.
-
NoOpHook–Gateway default
ConnectionHook— every hook is a no-op. -
OutboundText–A text payload destined for a player (or all players) in the game.
-
ResponseKind–Message categories the response sender can route.
-
ResponseSink–The two outbound delivery routes the response sender dispatches.
-
RouteEnvelope–A response message the response sender routes to a sink method.
-
SubscriptionToken–An opaque handle for one event-bus registration.
-
SystemNotification–A host/system status line surfaced to a player (or all players).
-
WebsocketTransportConfig–Transport knobs for the facade's
websockets.servelifetime. -
WsEventType–Events the connection lifetime and protocol handler can emit.
-
AddonBridgeProfile–Wire-format contract for addon bridge interop.
-
PlayerMessageEvent–Parsed player chat/message event from the WebSocket stream.
Functions:
-
enqueue_response–Put
messageontostate.response_queue, dropping the oldest if full. -
configure_logging–Configure structlog + stdlib logging for compact console output.
AddonBridgeClient
¶
AddonBridgeService
¶
Manage the request/response lifecycle between Python and the addon.
Methods:
-
create_client–Build a client bound to one connection.
-
request_capability–Send a bridge request and wait for the addon's chat callback.
-
is_bridge_chat_message–True if the player chat message is an addon response fragment.
-
is_ui_chat_message–True if the player chat message is a UI chat fragment.
-
handle_player_message–Route a routed message from the simulated player.
-
set_ui_chat_callback–Register the UI chat message callback.
-
close_connection–Tear down the per-connection session on disconnect.
Source code in src/mcbe_ws_sdk/addon/service.py
create_client
¶
Build a client bound to one connection.
request_capability
async
¶
request_capability(connection_id: UUID, capability: str, payload: dict[str, Any], send_command: CommandSender) -> dict[str, Any]
Send a bridge request and wait for the addon's chat callback.
Source code in src/mcbe_ws_sdk/addon/service.py
is_bridge_chat_message
¶
True if the player chat message is an addon response fragment.
Source code in src/mcbe_ws_sdk/addon/service.py
is_ui_chat_message
¶
True if the player chat message is a UI chat fragment.
handle_player_message
async
¶
Route a routed message from the simulated player.
Source code in src/mcbe_ws_sdk/addon/service.py
set_ui_chat_callback
¶
close_connection
¶
Tear down the per-connection session on disconnect.
ConnectionAddonBridgeClient
¶
ConnectionAddonBridgeClient(service: AddonBridgeService, connection_id: UUID, send_command: CommandSender)
Per-connection client bound to one bridge service instance.
Source code in src/mcbe_ws_sdk/addon/service.py
CommandRegistry
¶
Registry of command prefixes, types, and aliases.
Methods:
-
resolve–Resolve a message to
(command_type, content). -
resolve_parsed–Resolve a message to a typed command, including which token matched.
-
add_alias–Register a dynamic alias for an existing command prefix.
-
remove_alias–Remove a previously registered alias.
-
get_command_config–Return the loaded config for a primary command prefix.
-
get_aliases–Return all aliases for a command prefix.
-
list_all_commands–List all commands as
(prefix, type, aliases)tuples. -
get_command_prefix–Return the primary prefix for a command type, if registered.
Source code in src/mcbe_ws_sdk/command/registry.py
resolve
¶
Resolve a message to (command_type, content).
resolve_parsed
¶
Resolve a message to a typed command, including which token matched.
Source code in src/mcbe_ws_sdk/command/registry.py
add_alias
¶
Register a dynamic alias for an existing command prefix.
Source code in src/mcbe_ws_sdk/command/registry.py
remove_alias
¶
Remove a previously registered alias.
Source code in src/mcbe_ws_sdk/command/registry.py
get_command_config
¶
get_aliases
¶
list_all_commands
¶
List all commands as (prefix, type, aliases) tuples.
get_command_prefix
¶
McbeOutboundDelivery
¶
McbeOutboundDelivery(*, connection_id: Any, send_payload: PayloadSender, settings: FlowControlSettings, log_raw_payloads: bool = False)
Chunk, throttle, send, and optionally log MCBE commandRequest payloads.
Methods:
-
send_payload–Send an already-built payload (subscribe, handshake, non-chunked paths).
-
send_tellraw–Send tellraw text and return the number of payloads actually transmitted.
-
send_scriptevent–Send scriptevent text and return the number of payloads actually transmitted.
-
send_raw_command–Send a raw command that must not be semantically split.
-
send_outbound_text–Route an OutboundText message through the delivery adapter.
-
send_system_notification–Route a SystemNotification through the delivery adapter.
-
send_chunked–Send
payloadswith inter-chunk delays.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_payload
async
¶
Send an already-built payload (subscribe, handshake, non-chunked paths).
send_tellraw
async
¶
Send tellraw text and return the number of payloads actually transmitted.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_scriptevent
async
¶
Send scriptevent text and return the number of payloads actually transmitted.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_raw_command
async
¶
send_raw_command(command: str, source: str = 'raw_command', before_send: Callable[[str], None] | None = None) -> str
Send a raw command that must not be semantically split.
Raises FrameTooLargeError when the command exceeds the byte budget.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_outbound_text
async
¶
Route an OutboundText message through the delivery adapter.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_system_notification
async
¶
Route a SystemNotification through the delivery adapter.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_chunked
async
¶
send_chunked(payloads: list[str], delay_kind: str, source: str, *, delay: float | None = None) -> None
Send payloads with inter-chunk delays.
When delay is provided it overrides flow.chunk_delay_for(delay_kind)
so protocol profiles can inject their own cadence (e.g.
profile.response_chunk_delay).
Source code in src/mcbe_ws_sdk/delivery/outbound.py
BridgeClosedError
¶
BridgeError
¶
Bases: McbeWsSdkError
Base class for add-on bridge errors.
BridgeLimitError
¶
Bases: BridgeError, ProtocolError
Raised when an add-on bridge protocol limit is exceeded.
BridgeTimeoutError
¶
Bases: BridgeError
Raised when an add-on bridge request times out.
Source code in src/mcbe_ws_sdk/errors.py
ConfigurationError
¶
Bases: McbeWsSdkError, ValueError
Raised when SDK settings are invalid.
FacadeLifecycleError
¶
Bases: McbeWsSdkError, RuntimeError
Raised for invalid server facade lifecycle transitions.
FrameTooLargeError
¶
Bases: ProtocolError
Raised when a frame cannot fit within its configured byte budget.
ProtocolError
¶
Bases: McbeWsSdkError, ValueError
Raised when a protocol contract is violated.
FlowControlMiddleware
¶
Unified flow control: split outbound long text into safe Minecraft commands.
Methods:
-
chunk_delay_for–Return inter-chunk delay in seconds for a chunking scenario.
-
chunk_tellraw–Split a long tellraw message into
commandRequestJSON payload strings. -
chunk_scriptevent–Split a long scriptevent payload into
commandRequestJSON strings. -
chunk_raw_command–Wrap a raw command as a one-element
commandRequestJSON list.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_delay_for
¶
Return inter-chunk delay in seconds for a chunking scenario.
kind is typically "tellraw" or "scriptevent". Unknown kinds
yield 0.0 (no delay); the caller may treat that as an error.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_tellraw
¶
chunk_tellraw(message: str, color: str = '§a', max_length: int | None = None, target: str = '@a') -> list[str]
Split a long tellraw message into commandRequest JSON payload strings.
Empty text returns []; the caller decides whether anything still must be
sent. Each JSON commandLine text is at most max_length characters,
and the final create_tellraw commandLine stays within the measured
461 B MCBE budget.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_scriptevent
¶
chunk_scriptevent(content: str, message_id: str = 'server:data', max_length: int | None = None) -> list[str]
Split a long scriptevent payload into commandRequest JSON strings.
Empty content returns []; the caller decides whether anything still
must be sent. Each commandLine content segment is at most
max_length characters, and total commandLine bytes stay within
the measured 461 B MCBE budget.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_raw_command
¶
Wrap a raw command as a one-element commandRequest JSON list.
Raw commands must not be truncated past the verb, or later fragments would
be illegal. This method does not chunk: over-budget input raises
FrameTooLargeError for the caller to handle.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
ConnectionHook
¶
Bases: Protocol
Lifecycle + protocol hooks the host injects into the gateway.
Methods:
-
on_connected–Fired after the transport connection is established.
-
on_disconnected–Fired on transport disconnect — host clears per-connection state here.
-
on_player_message–Inbound chat/scriptevent from a player.
-
on_ui_chat_reassembled–Fired when a fragmented UI_CHAT message is fully reassembled.
-
on_command_response–Inbound
commandResponse(resolves run_command futures). -
on_error–Inbound typed
errorframe.
on_connected
async
¶
on_disconnected
async
¶
on_player_message
async
¶
on_player_message(state: ConnectionState, player_event: PlayerMessageEvent, parsed: ParsedCommand | None = None) -> None
Inbound chat/scriptevent from a player.
parsed is the registry match for player_event.message when one
exists; None means free-form chat (or no matching command prefix).
Source code in src/mcbe_ws_sdk/gateway/hook.py
on_ui_chat_reassembled
async
¶
Fired when a fragmented UI_CHAT message is fully reassembled.
on_command_response
async
¶
Inbound commandResponse (resolves run_command futures).
ConnectionManager
¶
ConnectionManager(*, sink: ResponseSink | None = None, event_bus: EventBus | None = None, response_queue_maxsize: int = _DEFAULT_RESPONSE_QUEUE_MAXSIZE)
Owns active connections and their response-sender coroutines.
Construction takes injectable collaborators (sink / event bus) so the facade can supply host-backed variants; both fall back to gateway defaults.
Methods:
-
create_connection–Register a new connection and start its response-sender coroutine.
-
drop_connection–Cancel the sender coroutine, drop the connection, emit DISCONNECTED.
-
shutdown_all–Drop every connection (on server stop).
Source code in src/mcbe_ws_sdk/gateway/connection.py
create_connection
async
¶
create_connection(*, send_payload: SendPayload, connection_id: UUID | None = None) -> ConnectionState
Register a new connection and start its response-sender coroutine.
The returned state carries a fresh bounded response_queue; the host
posts response messages to it (prefer :func:enqueue_response so a full
queue drops the oldest item instead of blocking). send_payload is the
transport frame-send the sink's command routes ultimately deliver through.
Does not emit WsEventType.CONNECTED — that is the facade's job
after handshake + subscribe succeed.
Source code in src/mcbe_ws_sdk/gateway/connection.py
drop_connection
async
¶
Cancel the sender coroutine, drop the connection, emit DISCONNECTED.
Source code in src/mcbe_ws_sdk/gateway/connection.py
shutdown_all
async
¶
ConnectionState
dataclass
¶
ConnectionState(id: UUID = uuid4(), _player_name: str | None = None, send_payload: SendPayload | None = None, response_queue: Queue[object] | None = None)
Transport-agnostic connection identity.
Host-specific / transport wiring lives on the state but typed as opaque
callables so the gateway never imports websockets itself: the facade or
a host transport adapter sets send_payload. response_queue is the
inbound message stream the response sender drains.
Attributes:
-
player_name(str | None) –Most-recent speaker convenience pointer only.
player_name
property
¶
Most-recent speaker convenience pointer only.
.. deprecated::
Use :attr:PlayerMessageEvent.sender for authoritative player identity.
This attribute is retained for backwards compatibility only and will
emit a :class:DeprecationWarning on access.
DefaultResponseSink
¶
Gateway default sink: logs metadata, delivers nothing to game.
on_outbound_text and on_system_notification log metadata (no player
text, no command lines). A real host wires a
:class:~mcbe_ws_sdk.delivery.outbound.McbeOutboundDelivery here.
dispatch remains as a non-protocol convenience for hosts/tests that want
envelope-based routing; the manager never requires it.
Methods:
-
dispatch–Convenience router; not part of :class:
ResponseSink.
dispatch
async
¶
Convenience router; not part of :class:ResponseSink.
Source code in src/mcbe_ws_sdk/gateway/sink.py
EventBus
¶
A typed in-process event bus keyed by :class:WsEventType.
Methods:
-
subscribe–Register
handlerand return a token for this registration. -
unsubscribe–Remove exactly the registration identified by
token. -
handler_count–Return the number of live registrations for
event. -
emit–Await live handlers in subscription order.
Source code in src/mcbe_ws_sdk/gateway/events.py
subscribe
¶
Register handler and return a token for this registration.
Source code in src/mcbe_ws_sdk/gateway/events.py
unsubscribe
¶
handler_count
¶
emit
async
¶
Await live handlers in subscription order.
Each handler is isolated: an exception in one handler does not prevent subsequent handlers from being called.
Source code in src/mcbe_ws_sdk/gateway/events.py
McbeServerFacade
¶
McbeServerFacade(*, settings: GatewaySettings | None = None, hook: ConnectionHook | None = None, sink: ResponseSink | None = None, addon: AddonBridgeService | None = None, registry: CommandRegistry | None = None, surface: MessageSurfaceConfig | None = None)
Owns the WS transport + connection/protocol machinery; host injects the rest.
The constructor takes ONLY keyword arguments and never builds a broker. Each
None collapses to a gateway default so a host can stand up a working
facade with McbeServerFacade() and override collaborators one at a time.
Methods:
-
run_lifetime–Bind a WebSocket server and serve until :meth:
stop/ task cancellation. -
stop–Signal :meth:
run_lifetimeto unwind (idempotent).
Attributes:
-
manager(ConnectionManager) –The facade's owned connection manager.
-
handler(MinecraftProtocolHandler) –The facade's owned protocol handler (command parser + renderer).
-
addon(AddonBridgeService) –The facade's owned addon-bridge service instance.
Source code in src/mcbe_ws_sdk/gateway/server_facade.py
handler
property
¶
The facade's owned protocol handler (command parser + renderer).
run_lifetime
async
¶
Bind a WebSocket server and serve until :meth:stop / task cancellation.
host/port default to settings.websocket.host / port when
None. Uses the websockets async-context-manager API
(async with serve(...) as server), which works on both >=12 and
the v13+ serve shape. Blocks on an internal asyncio.Event so an
explicit stop() returns cleanly; the outer task being cancelled also
unwinds into :meth:_graceful_shutdown.
Source code in src/mcbe_ws_sdk/gateway/server_facade.py
MessageSurfaceConfig
dataclass
¶
MessageSurfaceConfig(welcome_message_template: str = '-----------\n已连接到 MCBE WebSocket 网关\n连接 ID: {connection_id}...\n-----------', error_prefix: str = '❌ 错误: ', info_prefix: str = 'ℹ ', success_prefix: str = '✅ ', error_color: str = '§c', info_color: str = '§b', success_color: str = '§a')
Presentation strings the protocol handler renders status messages with.
A frozen value object so a host can supply any wording/colors via config without the handler importing the host's settings model.
MinecraftProtocolHandler
¶
MinecraftProtocolHandler(command_registry: CommandRegistry, surface: MessageSurfaceConfig | None = None)
Constructs / parses MCBE connection-lifecycle protocol messages.
__init__ takes the collaborators it needs (a command registry and a
presentation surface) and never imports anything host-specific.
Methods:
-
create_subscribe_message–Build the
subscribepayload string for PlayerMessage events. -
create_welcome_message–Render the post-connect welcome banner (plain text; wrap a message).
-
parse_player_message–Parse an inbound
PlayerMessageevent out of a WS frame body. -
parse_command–Resolve
messageto(command_type, content)via the registry. -
parse_typed_command–Resolve
messageto a typed :class:ParsedCommand, orNone. -
get_help_text–Render the in-game help listing from the command registry.
Source code in src/mcbe_ws_sdk/gateway/handler.py
create_subscribe_message
staticmethod
¶
Build the subscribe payload string for PlayerMessage events.
create_welcome_message
¶
Render the post-connect welcome banner (plain text; wrap a message).
Source code in src/mcbe_ws_sdk/gateway/handler.py
parse_player_message
staticmethod
¶
Parse an inbound PlayerMessage event out of a WS frame body.
Source code in src/mcbe_ws_sdk/gateway/handler.py
parse_command
¶
Resolve message to (command_type, content) via the registry.
parse_typed_command
¶
Resolve message to a typed :class:ParsedCommand, or None.
get_help_text
¶
Render the in-game help listing from the command registry.
Source code in src/mcbe_ws_sdk/gateway/handler.py
NoOpHook
¶
Gateway default ConnectionHook — every hook is a no-op.
OutboundText
dataclass
¶
OutboundText(content: str, channel: str = 'content', sequence: int = 0, delivery: DeliveryMode = 'tellraw', player_name: str | None = None, target: str | None = None, message_id: str = 'server:data', id: UUID = uuid4())
A text payload destined for a player (or all players) in the game.
ResponseSink
¶
Bases: Protocol
The two outbound delivery routes the response sender dispatches.
dispatch is intentionally not part of this protocol: the connection
manager routes by envelope kind and calls the matching on_* method
directly so a duck-typed host only needs these two hooks.
RouteEnvelope
dataclass
¶
A response message the response sender routes to a sink method.
Methods:
-
from_message–Classify a host response into a :class:
RouteEnvelope.
from_message
classmethod
¶
Classify a host response into a :class:RouteEnvelope.
Accepts only the gateway's own value objects (OutboundText, SystemNotification) by type. Anything else is rejected — the response loop should never silently drop an unroutable message.
Source code in src/mcbe_ws_sdk/gateway/sink.py
SubscriptionToken
dataclass
¶
An opaque handle for one event-bus registration.
SystemNotification
dataclass
¶
SystemNotification(level: NotificationLevel, message: str, player_name: str | None = None, id: UUID = uuid4())
A host/system status line surfaced to a player (or all players).
WebsocketTransportConfig
dataclass
¶
WebsocketTransportConfig(host: str = '0.0.0.0', port: int = 8080, ping_interval: float | None = 30.0, ping_timeout: float | None = 15.0, close_timeout: float = 15.0, max_size: int | None = 10 * 1024 * 1024, max_queue: int | None = 32, response_queue_maxsize: int = 256)
Transport knobs for the facade's websockets.serve lifetime.
PlayerMessageEvent
¶
Bases: BaseModel
Parsed player chat/message event from the WebSocket stream.
Methods:
-
from_event_body–Parse a
PlayerMessageEventfrom an event body dict.
from_event_body
classmethod
¶
Parse a PlayerMessageEvent from an event body dict.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
enqueue_response
¶
Put message onto state.response_queue, dropping the oldest if full.
No-ops when the connection has no queue. On overflow the oldest item is discarded and a warning is logged so a slow consumer cannot back-pressure the host forever.
Source code in src/mcbe_ws_sdk/gateway/connection.py
configure_logging
¶
Configure structlog + stdlib logging for compact console output.
Parameters¶
level:
Root log level name (default INFO).
colors:
Force colour on/off. None (default) enables colour only when stdout
is a TTY.
Source code in src/mcbe_ws_sdk/logging.py
Gateway¶
mcbe_ws_sdk.gateway
¶
MCBE WebSocket gateway SDK.
The gateway package owns the connection lifecycle, event bus, hook/sink
protocols and the response routing machinery. The host application (the main
repo) injects behaviour by implementing
:class:~mcbe_ws_sdk.gateway.hook.ConnectionHook and
:class:~mcbe_ws_sdk.gateway.sink.ResponseSink, then drives the stack through
:class:~mcbe_ws_sdk.gateway.server_facade.McbeServerFacade.
Modules:
-
connection–Connection state + connection manager owned by the gateway.
-
events–WebSocket gateway event bus.
-
handler–MCBE WebSocket protocol handler.
-
hook–Connection lifecycle hook protocol.
-
messages–WebSocket gateway message value objects.
-
server_facade–Gateway entry point: the facade the host drives the SDK stack through.
-
sink–Response routing sink +
RouteEnvelopevalue object +DefaultResponseSink.
Classes:
-
WebsocketTransportConfig–Transport knobs for the facade's
websockets.servelifetime. -
ConnectionManager–Owns active connections and their response-sender coroutines.
-
ConnectionState–Transport-agnostic connection identity.
-
EventBus–A typed in-process event bus keyed by :class:
WsEventType. -
SubscriptionToken–An opaque handle for one event-bus registration.
-
WsEventType–Events the connection lifetime and protocol handler can emit.
-
MessageSurfaceConfig–Presentation strings the protocol handler renders status messages with.
-
MinecraftProtocolHandler–Constructs / parses MCBE connection-lifecycle protocol messages.
-
ConnectionHook–Lifecycle + protocol hooks the host injects into the gateway.
-
NoOpHook–Gateway default
ConnectionHook— every hook is a no-op. -
OutboundText–A text payload destined for a player (or all players) in the game.
-
SystemNotification–A host/system status line surfaced to a player (or all players).
-
McbeServerFacade–Owns the WS transport + connection/protocol machinery; host injects the rest.
-
DefaultResponseSink–Gateway default sink: logs metadata, delivers nothing to game.
-
ResponseKind–Message categories the response sender can route.
-
ResponseSink–The two outbound delivery routes the response sender dispatches.
-
RouteEnvelope–A response message the response sender routes to a sink method.
Functions:
-
enqueue_response–Put
messageontostate.response_queue, dropping the oldest if full.
WebsocketTransportConfig
dataclass
¶
WebsocketTransportConfig(host: str = '0.0.0.0', port: int = 8080, ping_interval: float | None = 30.0, ping_timeout: float | None = 15.0, close_timeout: float = 15.0, max_size: int | None = 10 * 1024 * 1024, max_queue: int | None = 32, response_queue_maxsize: int = 256)
Transport knobs for the facade's websockets.serve lifetime.
ConnectionManager
¶
ConnectionManager(*, sink: ResponseSink | None = None, event_bus: EventBus | None = None, response_queue_maxsize: int = _DEFAULT_RESPONSE_QUEUE_MAXSIZE)
Owns active connections and their response-sender coroutines.
Construction takes injectable collaborators (sink / event bus) so the facade can supply host-backed variants; both fall back to gateway defaults.
Methods:
-
create_connection–Register a new connection and start its response-sender coroutine.
-
drop_connection–Cancel the sender coroutine, drop the connection, emit DISCONNECTED.
-
shutdown_all–Drop every connection (on server stop).
Source code in src/mcbe_ws_sdk/gateway/connection.py
create_connection
async
¶
create_connection(*, send_payload: SendPayload, connection_id: UUID | None = None) -> ConnectionState
Register a new connection and start its response-sender coroutine.
The returned state carries a fresh bounded response_queue; the host
posts response messages to it (prefer :func:enqueue_response so a full
queue drops the oldest item instead of blocking). send_payload is the
transport frame-send the sink's command routes ultimately deliver through.
Does not emit WsEventType.CONNECTED — that is the facade's job
after handshake + subscribe succeed.
Source code in src/mcbe_ws_sdk/gateway/connection.py
drop_connection
async
¶
Cancel the sender coroutine, drop the connection, emit DISCONNECTED.
Source code in src/mcbe_ws_sdk/gateway/connection.py
shutdown_all
async
¶
ConnectionState
dataclass
¶
ConnectionState(id: UUID = uuid4(), _player_name: str | None = None, send_payload: SendPayload | None = None, response_queue: Queue[object] | None = None)
Transport-agnostic connection identity.
Host-specific / transport wiring lives on the state but typed as opaque
callables so the gateway never imports websockets itself: the facade or
a host transport adapter sets send_payload. response_queue is the
inbound message stream the response sender drains.
Attributes:
-
player_name(str | None) –Most-recent speaker convenience pointer only.
player_name
property
¶
Most-recent speaker convenience pointer only.
.. deprecated::
Use :attr:PlayerMessageEvent.sender for authoritative player identity.
This attribute is retained for backwards compatibility only and will
emit a :class:DeprecationWarning on access.
EventBus
¶
A typed in-process event bus keyed by :class:WsEventType.
Methods:
-
subscribe–Register
handlerand return a token for this registration. -
unsubscribe–Remove exactly the registration identified by
token. -
handler_count–Return the number of live registrations for
event. -
emit–Await live handlers in subscription order.
Source code in src/mcbe_ws_sdk/gateway/events.py
subscribe
¶
Register handler and return a token for this registration.
Source code in src/mcbe_ws_sdk/gateway/events.py
unsubscribe
¶
handler_count
¶
emit
async
¶
Await live handlers in subscription order.
Each handler is isolated: an exception in one handler does not prevent subsequent handlers from being called.
Source code in src/mcbe_ws_sdk/gateway/events.py
SubscriptionToken
dataclass
¶
An opaque handle for one event-bus registration.
MessageSurfaceConfig
dataclass
¶
MessageSurfaceConfig(welcome_message_template: str = '-----------\n已连接到 MCBE WebSocket 网关\n连接 ID: {connection_id}...\n-----------', error_prefix: str = '❌ 错误: ', info_prefix: str = 'ℹ ', success_prefix: str = '✅ ', error_color: str = '§c', info_color: str = '§b', success_color: str = '§a')
Presentation strings the protocol handler renders status messages with.
A frozen value object so a host can supply any wording/colors via config without the handler importing the host's settings model.
MinecraftProtocolHandler
¶
MinecraftProtocolHandler(command_registry: CommandRegistry, surface: MessageSurfaceConfig | None = None)
Constructs / parses MCBE connection-lifecycle protocol messages.
__init__ takes the collaborators it needs (a command registry and a
presentation surface) and never imports anything host-specific.
Methods:
-
create_subscribe_message–Build the
subscribepayload string for PlayerMessage events. -
create_welcome_message–Render the post-connect welcome banner (plain text; wrap a message).
-
parse_player_message–Parse an inbound
PlayerMessageevent out of a WS frame body. -
parse_command–Resolve
messageto(command_type, content)via the registry. -
parse_typed_command–Resolve
messageto a typed :class:ParsedCommand, orNone. -
get_help_text–Render the in-game help listing from the command registry.
Source code in src/mcbe_ws_sdk/gateway/handler.py
create_subscribe_message
staticmethod
¶
Build the subscribe payload string for PlayerMessage events.
create_welcome_message
¶
Render the post-connect welcome banner (plain text; wrap a message).
Source code in src/mcbe_ws_sdk/gateway/handler.py
parse_player_message
staticmethod
¶
Parse an inbound PlayerMessage event out of a WS frame body.
Source code in src/mcbe_ws_sdk/gateway/handler.py
parse_command
¶
Resolve message to (command_type, content) via the registry.
parse_typed_command
¶
Resolve message to a typed :class:ParsedCommand, or None.
get_help_text
¶
Render the in-game help listing from the command registry.
Source code in src/mcbe_ws_sdk/gateway/handler.py
ConnectionHook
¶
Bases: Protocol
Lifecycle + protocol hooks the host injects into the gateway.
Methods:
-
on_connected–Fired after the transport connection is established.
-
on_disconnected–Fired on transport disconnect — host clears per-connection state here.
-
on_player_message–Inbound chat/scriptevent from a player.
-
on_ui_chat_reassembled–Fired when a fragmented UI_CHAT message is fully reassembled.
-
on_command_response–Inbound
commandResponse(resolves run_command futures). -
on_error–Inbound typed
errorframe.
on_connected
async
¶
on_disconnected
async
¶
on_player_message
async
¶
on_player_message(state: ConnectionState, player_event: PlayerMessageEvent, parsed: ParsedCommand | None = None) -> None
Inbound chat/scriptevent from a player.
parsed is the registry match for player_event.message when one
exists; None means free-form chat (or no matching command prefix).
Source code in src/mcbe_ws_sdk/gateway/hook.py
on_ui_chat_reassembled
async
¶
Fired when a fragmented UI_CHAT message is fully reassembled.
on_command_response
async
¶
Inbound commandResponse (resolves run_command futures).
NoOpHook
¶
Gateway default ConnectionHook — every hook is a no-op.
OutboundText
dataclass
¶
OutboundText(content: str, channel: str = 'content', sequence: int = 0, delivery: DeliveryMode = 'tellraw', player_name: str | None = None, target: str | None = None, message_id: str = 'server:data', id: UUID = uuid4())
A text payload destined for a player (or all players) in the game.
SystemNotification
dataclass
¶
SystemNotification(level: NotificationLevel, message: str, player_name: str | None = None, id: UUID = uuid4())
A host/system status line surfaced to a player (or all players).
McbeServerFacade
¶
McbeServerFacade(*, settings: GatewaySettings | None = None, hook: ConnectionHook | None = None, sink: ResponseSink | None = None, addon: AddonBridgeService | None = None, registry: CommandRegistry | None = None, surface: MessageSurfaceConfig | None = None)
Owns the WS transport + connection/protocol machinery; host injects the rest.
The constructor takes ONLY keyword arguments and never builds a broker. Each
None collapses to a gateway default so a host can stand up a working
facade with McbeServerFacade() and override collaborators one at a time.
Methods:
-
run_lifetime–Bind a WebSocket server and serve until :meth:
stop/ task cancellation. -
stop–Signal :meth:
run_lifetimeto unwind (idempotent).
Attributes:
-
manager(ConnectionManager) –The facade's owned connection manager.
-
handler(MinecraftProtocolHandler) –The facade's owned protocol handler (command parser + renderer).
-
addon(AddonBridgeService) –The facade's owned addon-bridge service instance.
Source code in src/mcbe_ws_sdk/gateway/server_facade.py
handler
property
¶
The facade's owned protocol handler (command parser + renderer).
run_lifetime
async
¶
Bind a WebSocket server and serve until :meth:stop / task cancellation.
host/port default to settings.websocket.host / port when
None. Uses the websockets async-context-manager API
(async with serve(...) as server), which works on both >=12 and
the v13+ serve shape. Blocks on an internal asyncio.Event so an
explicit stop() returns cleanly; the outer task being cancelled also
unwinds into :meth:_graceful_shutdown.
Source code in src/mcbe_ws_sdk/gateway/server_facade.py
DefaultResponseSink
¶
Gateway default sink: logs metadata, delivers nothing to game.
on_outbound_text and on_system_notification log metadata (no player
text, no command lines). A real host wires a
:class:~mcbe_ws_sdk.delivery.outbound.McbeOutboundDelivery here.
dispatch remains as a non-protocol convenience for hosts/tests that want
envelope-based routing; the manager never requires it.
Methods:
-
dispatch–Convenience router; not part of :class:
ResponseSink.
dispatch
async
¶
Convenience router; not part of :class:ResponseSink.
Source code in src/mcbe_ws_sdk/gateway/sink.py
ResponseSink
¶
Bases: Protocol
The two outbound delivery routes the response sender dispatches.
dispatch is intentionally not part of this protocol: the connection
manager routes by envelope kind and calls the matching on_* method
directly so a duck-typed host only needs these two hooks.
RouteEnvelope
dataclass
¶
A response message the response sender routes to a sink method.
Methods:
-
from_message–Classify a host response into a :class:
RouteEnvelope.
from_message
classmethod
¶
Classify a host response into a :class:RouteEnvelope.
Accepts only the gateway's own value objects (OutboundText, SystemNotification) by type. Anything else is rejected — the response loop should never silently drop an unroutable message.
Source code in src/mcbe_ws_sdk/gateway/sink.py
enqueue_response
¶
Put message onto state.response_queue, dropping the oldest if full.
No-ops when the connection has no queue. On overflow the oldest item is discarded and a warning is logged so a slow consumer cannot back-pressure the host forever.
Source code in src/mcbe_ws_sdk/gateway/connection.py
connection
¶
Connection state + connection manager owned by the gateway.
Extends the minimal :class:ConnectionState foundation with the lifecycle the
host drives through the facade: per-connection response queues, an outbound
send_payload callable (the transport's frame send, e.g. websocket.send),
and a :class:ConnectionManager that owns the response-sender coroutine and
emits DISCONNECTED on the
:class:~mcbe_ws_sdk.gateway.events.EventBus.
CONNECTED is intentionally not emitted here — the facade emits it after
a successful handshake + subscribe, at the same moment as hook.on_connected.
The response-sender loop never builds Minecraft commands itself. It classifies
each queued message with
:meth:~mcbe_ws_sdk.gateway.sink.RouteEnvelope.from_message and routes it
inline to the sink's on_* methods, pushing the application-specific mapping
entirely onto the host's HostSink.
Classes:
-
ConnectionState–Transport-agnostic connection identity.
-
ConnectionManager–Owns active connections and their response-sender coroutines.
Functions:
-
enqueue_response–Put
messageontostate.response_queue, dropping the oldest if full.
ConnectionState
dataclass
¶
ConnectionState(id: UUID = uuid4(), _player_name: str | None = None, send_payload: SendPayload | None = None, response_queue: Queue[object] | None = None)
Transport-agnostic connection identity.
Host-specific / transport wiring lives on the state but typed as opaque
callables so the gateway never imports websockets itself: the facade or
a host transport adapter sets send_payload. response_queue is the
inbound message stream the response sender drains.
Attributes:
-
player_name(str | None) –Most-recent speaker convenience pointer only.
player_name
property
¶
Most-recent speaker convenience pointer only.
.. deprecated::
Use :attr:PlayerMessageEvent.sender for authoritative player identity.
This attribute is retained for backwards compatibility only and will
emit a :class:DeprecationWarning on access.
ConnectionManager
¶
ConnectionManager(*, sink: ResponseSink | None = None, event_bus: EventBus | None = None, response_queue_maxsize: int = _DEFAULT_RESPONSE_QUEUE_MAXSIZE)
Owns active connections and their response-sender coroutines.
Construction takes injectable collaborators (sink / event bus) so the facade can supply host-backed variants; both fall back to gateway defaults.
Methods:
-
create_connection–Register a new connection and start its response-sender coroutine.
-
drop_connection–Cancel the sender coroutine, drop the connection, emit DISCONNECTED.
-
shutdown_all–Drop every connection (on server stop).
Source code in src/mcbe_ws_sdk/gateway/connection.py
create_connection
async
¶
create_connection(*, send_payload: SendPayload, connection_id: UUID | None = None) -> ConnectionState
Register a new connection and start its response-sender coroutine.
The returned state carries a fresh bounded response_queue; the host
posts response messages to it (prefer :func:enqueue_response so a full
queue drops the oldest item instead of blocking). send_payload is the
transport frame-send the sink's command routes ultimately deliver through.
Does not emit WsEventType.CONNECTED — that is the facade's job
after handshake + subscribe succeed.
Source code in src/mcbe_ws_sdk/gateway/connection.py
drop_connection
async
¶
Cancel the sender coroutine, drop the connection, emit DISCONNECTED.
Source code in src/mcbe_ws_sdk/gateway/connection.py
shutdown_all
async
¶
enqueue_response
¶
Put message onto state.response_queue, dropping the oldest if full.
No-ops when the connection has no queue. On overflow the oldest item is discarded and a warning is logged so a slow consumer cannot back-pressure the host forever.
Source code in src/mcbe_ws_sdk/gateway/connection.py
events
¶
WebSocket gateway event bus.
Classes:
-
WsEventType–Events the connection lifetime and protocol handler can emit.
-
SubscriptionToken–An opaque handle for one event-bus registration.
-
EventBus–A typed in-process event bus keyed by :class:
WsEventType.
SubscriptionToken
dataclass
¶
An opaque handle for one event-bus registration.
EventBus
¶
A typed in-process event bus keyed by :class:WsEventType.
Methods:
-
subscribe–Register
handlerand return a token for this registration. -
unsubscribe–Remove exactly the registration identified by
token. -
handler_count–Return the number of live registrations for
event. -
emit–Await live handlers in subscription order.
Source code in src/mcbe_ws_sdk/gateway/events.py
subscribe
¶
Register handler and return a token for this registration.
Source code in src/mcbe_ws_sdk/gateway/events.py
unsubscribe
¶
handler_count
¶
emit
async
¶
Await live handlers in subscription order.
Each handler is isolated: an exception in one handler does not prevent subsequent handlers from being called.
Source code in src/mcbe_ws_sdk/gateway/events.py
handler
¶
MCBE WebSocket protocol handler.
Relocated from the main repo services/websocket/minecraft.py. Responsible
for constructing subscribe messages, parsing inbound PlayerMessageEvent,
resolving typed commands, and rendering the small set of on-screen status
messages the connection lifecycle needs (info / success / error).
Deliberately host-config-agnostic: presentation strings (welcome template,
status prefixes, colors) come in through a frozen
:class:MessageSurfaceConfig value object instead of the host's
MinecraftConfig. Command resolution is delegated to an injected
:class:~mcbe_ws_sdk.command.registry.CommandRegistry.
create_chat_request was deliberately removed — it constructs the host's
models.messages.ChatRequest and reads per-player provider/template state,
which is now the host's concern (built inside its ConnectionHook /
command dispatcher). The renderer methods like
:meth:create_info_message remain because the host still needs to surface
status lines; the host's HostSink delivers the resulting
:class:TellrawMessage over the outbound delivery adapter.
Classes:
-
TellrawMessage–A structured outbound tellraw line.
-
MessageSurfaceConfig–Presentation strings the protocol handler renders status messages with.
-
MinecraftProtocolHandler–Constructs / parses MCBE connection-lifecycle protocol messages.
TellrawMessage
dataclass
¶
A structured outbound tellraw line.
Carries the plain text, the MC color, and the tellraw target so the delivery layer can chunk + serialize without re-parsing its own output.
MessageSurfaceConfig
dataclass
¶
MessageSurfaceConfig(welcome_message_template: str = '-----------\n已连接到 MCBE WebSocket 网关\n连接 ID: {connection_id}...\n-----------', error_prefix: str = '❌ 错误: ', info_prefix: str = 'ℹ ', success_prefix: str = '✅ ', error_color: str = '§c', info_color: str = '§b', success_color: str = '§a')
Presentation strings the protocol handler renders status messages with.
A frozen value object so a host can supply any wording/colors via config without the handler importing the host's settings model.
MinecraftProtocolHandler
¶
MinecraftProtocolHandler(command_registry: CommandRegistry, surface: MessageSurfaceConfig | None = None)
Constructs / parses MCBE connection-lifecycle protocol messages.
__init__ takes the collaborators it needs (a command registry and a
presentation surface) and never imports anything host-specific.
Methods:
-
create_subscribe_message–Build the
subscribepayload string for PlayerMessage events. -
create_welcome_message–Render the post-connect welcome banner (plain text; wrap a message).
-
parse_player_message–Parse an inbound
PlayerMessageevent out of a WS frame body. -
parse_command–Resolve
messageto(command_type, content)via the registry. -
parse_typed_command–Resolve
messageto a typed :class:ParsedCommand, orNone. -
get_help_text–Render the in-game help listing from the command registry.
Source code in src/mcbe_ws_sdk/gateway/handler.py
create_subscribe_message
staticmethod
¶
Build the subscribe payload string for PlayerMessage events.
create_welcome_message
¶
Render the post-connect welcome banner (plain text; wrap a message).
Source code in src/mcbe_ws_sdk/gateway/handler.py
parse_player_message
staticmethod
¶
Parse an inbound PlayerMessage event out of a WS frame body.
Source code in src/mcbe_ws_sdk/gateway/handler.py
parse_command
¶
Resolve message to (command_type, content) via the registry.
parse_typed_command
¶
Resolve message to a typed :class:ParsedCommand, or None.
get_help_text
¶
Render the in-game help listing from the command registry.
Source code in src/mcbe_ws_sdk/gateway/handler.py
hook
¶
Connection lifecycle hook protocol.
The host (the main repo's McbeHost) implements these six points to
inject the application-specific behaviour the gateway deliberately does NOT
implement: prompt/context management, LLM dispatch, command routing, and addon
linkage. NoOpHook is the gateway's built-in default — it defines the
complete contract so a host can subclass and override only what it needs.
All hooks return None and are purely side-effecting. on_player_message
receives an optional pre-parsed :class:~mcbe_ws_sdk.command.registry.ParsedCommand
so the host does not need to re-run the registry.
Classes:
-
ConnectionHook–Lifecycle + protocol hooks the host injects into the gateway.
-
NoOpHook–Gateway default
ConnectionHook— every hook is a no-op.
ConnectionHook
¶
Bases: Protocol
Lifecycle + protocol hooks the host injects into the gateway.
Methods:
-
on_connected–Fired after the transport connection is established.
-
on_disconnected–Fired on transport disconnect — host clears per-connection state here.
-
on_player_message–Inbound chat/scriptevent from a player.
-
on_ui_chat_reassembled–Fired when a fragmented UI_CHAT message is fully reassembled.
-
on_command_response–Inbound
commandResponse(resolves run_command futures). -
on_error–Inbound typed
errorframe.
on_connected
async
¶
on_disconnected
async
¶
on_player_message
async
¶
on_player_message(state: ConnectionState, player_event: PlayerMessageEvent, parsed: ParsedCommand | None = None) -> None
Inbound chat/scriptevent from a player.
parsed is the registry match for player_event.message when one
exists; None means free-form chat (or no matching command prefix).
Source code in src/mcbe_ws_sdk/gateway/hook.py
on_ui_chat_reassembled
async
¶
Fired when a fragmented UI_CHAT message is fully reassembled.
on_command_response
async
¶
Inbound commandResponse (resolves run_command futures).
NoOpHook
¶
Gateway default ConnectionHook — every hook is a no-op.
messages
¶
WebSocket gateway message value objects.
These are the display / delivery contract types the gateway produces on its
event bus and routes through :class:~mcbe_ws_sdk.gateway.sink.ResponseSink.
They are intentionally lean: they carry only the fields a gateway renderer or
delivery path needs (what to say, to whom, how). They do NOT carry the agent's
conversation framing (connection_id / BaseMessage.id / timestamp) — that
host-specific metadata stays on the :class:ConnectionState the event is paired
with. Keeping these types dependency-free is what lets the gateway layer type a
sink without importing the agent's models.messages / core.queue.
Classes:
-
OutboundText–A text payload destined for a player (or all players) in the game.
-
SystemNotification–A host/system status line surfaced to a player (or all players).
OutboundText
dataclass
¶
OutboundText(content: str, channel: str = 'content', sequence: int = 0, delivery: DeliveryMode = 'tellraw', player_name: str | None = None, target: str | None = None, message_id: str = 'server:data', id: UUID = uuid4())
A text payload destined for a player (or all players) in the game.
SystemNotification
dataclass
¶
SystemNotification(level: NotificationLevel, message: str, player_name: str | None = None, id: UUID = uuid4())
A host/system status line surfaced to a player (or all players).
server_facade
¶
Gateway entry point: the facade the host drives the SDK stack through.
:class:McbeServerFacade OWNS the WebSocket transport and the connection /
protocol machinery (the :class:~mcbe_ws_sdk.gateway.connection.ConnectionManager
response-sender loops, the
:class:~mcbe_ws_sdk.gateway.handler.MinecraftProtocolHandler command parser,
and the per-connection
:class:~mcbe_ws_sdk.addon.service.AddonBridgeService sessions) but deliberately
does NOT own any host application concern: there is no MessageBroker, no LLM
worker, no provider selection. All of that is injected by the
host via the :class:~mcbe_ws_sdk.gateway.hook.ConnectionHook lifecycle hooks
and the :class:~mcbe_ws_sdk.gateway.sink.ResponseSink outbound routes — the
same dependency-inversion the gateway already applies internally (see
:class:NoOpHook, :class:DefaultResponseSink).
It mirrors the current main-repo WebSocketServer orchestration
(services/websocket/server.py) — accept → handshake → subscribe →
welcome → message loop → disconnect → shutdown — but inverted: the server
receives its collaborators; it does not build the host-only ones.
Lifetime::
facade = McbeServerFacade(hook=my_hook, sink=my_sink)
await facade.run_lifetime() # blocks until ``stop()`` / cancelled
# ... or drive it on an explicit host asyncio.Task and cancel it.
See docs/batch-d-scope.md section B for the authoritative spec.
Classes:
-
McbeServerFacade–Owns the WS transport + connection/protocol machinery; host injects the rest.
McbeServerFacade
¶
McbeServerFacade(*, settings: GatewaySettings | None = None, hook: ConnectionHook | None = None, sink: ResponseSink | None = None, addon: AddonBridgeService | None = None, registry: CommandRegistry | None = None, surface: MessageSurfaceConfig | None = None)
Owns the WS transport + connection/protocol machinery; host injects the rest.
The constructor takes ONLY keyword arguments and never builds a broker. Each
None collapses to a gateway default so a host can stand up a working
facade with McbeServerFacade() and override collaborators one at a time.
Methods:
-
run_lifetime–Bind a WebSocket server and serve until :meth:
stop/ task cancellation. -
stop–Signal :meth:
run_lifetimeto unwind (idempotent).
Attributes:
-
manager(ConnectionManager) –The facade's owned connection manager.
-
handler(MinecraftProtocolHandler) –The facade's owned protocol handler (command parser + renderer).
-
addon(AddonBridgeService) –The facade's owned addon-bridge service instance.
Source code in src/mcbe_ws_sdk/gateway/server_facade.py
handler
property
¶
The facade's owned protocol handler (command parser + renderer).
run_lifetime
async
¶
Bind a WebSocket server and serve until :meth:stop / task cancellation.
host/port default to settings.websocket.host / port when
None. Uses the websockets async-context-manager API
(async with serve(...) as server), which works on both >=12 and
the v13+ serve shape. Blocks on an internal asyncio.Event so an
explicit stop() returns cleanly; the outer task being cancelled also
unwinds into :meth:_graceful_shutdown.
Source code in src/mcbe_ws_sdk/gateway/server_facade.py
sink
¶
Response routing sink + RouteEnvelope value object + DefaultResponseSink.
The response sender coroutine never builds Minecraft commands itself. Instead it
asks a :class:ResponseSink to deliver a :class:RouteEnvelope, pushing the
application-specific mapping entirely onto the host.
:class:DefaultResponseSink is the gateway's built-in base — it logs
OUTBOUND_TEXT and SYSTEM_NOTIFICATION messages (metadata only, no player
text) and does nothing else. A host wires an
:class:~mcbe_ws_sdk.delivery.outbound.McbeOutboundDelivery here.
Classes:
-
ResponseKind–Message categories the response sender can route.
-
RouteEnvelope–A response message the response sender routes to a sink method.
-
ResponseSink–The two outbound delivery routes the response sender dispatches.
-
DefaultResponseSink–Gateway default sink: logs metadata, delivers nothing to game.
RouteEnvelope
dataclass
¶
A response message the response sender routes to a sink method.
Methods:
-
from_message–Classify a host response into a :class:
RouteEnvelope.
from_message
classmethod
¶
Classify a host response into a :class:RouteEnvelope.
Accepts only the gateway's own value objects (OutboundText, SystemNotification) by type. Anything else is rejected — the response loop should never silently drop an unroutable message.
Source code in src/mcbe_ws_sdk/gateway/sink.py
ResponseSink
¶
Bases: Protocol
The two outbound delivery routes the response sender dispatches.
dispatch is intentionally not part of this protocol: the connection
manager routes by envelope kind and calls the matching on_* method
directly so a duck-typed host only needs these two hooks.
DefaultResponseSink
¶
Gateway default sink: logs metadata, delivers nothing to game.
on_outbound_text and on_system_notification log metadata (no player
text, no command lines). A real host wires a
:class:~mcbe_ws_sdk.delivery.outbound.McbeOutboundDelivery here.
dispatch remains as a non-protocol convenience for hosts/tests that want
envelope-based routing; the manager never requires it.
Methods:
-
dispatch–Convenience router; not part of :class:
ResponseSink.
dispatch
async
¶
Convenience router; not part of :class:ResponseSink.
Source code in src/mcbe_ws_sdk/gateway/sink.py
Addon bridge¶
mcbe_ws_sdk.addon
¶
Addon bridge capability for the MCBE WebSocket SDK.
Modules:
Classes:
-
AddonBridgeClient–Face an Agent uses to reach the addon bridge.
-
AddonBridgeService–Manage the request/response lifecycle between Python and the addon.
-
ConnectionAddonBridgeClient–Per-connection client bound to one bridge service instance.
AddonBridgeClient
¶
AddonBridgeService
¶
Manage the request/response lifecycle between Python and the addon.
Methods:
-
create_client–Build a client bound to one connection.
-
request_capability–Send a bridge request and wait for the addon's chat callback.
-
is_bridge_chat_message–True if the player chat message is an addon response fragment.
-
is_ui_chat_message–True if the player chat message is a UI chat fragment.
-
handle_player_message–Route a routed message from the simulated player.
-
set_ui_chat_callback–Register the UI chat message callback.
-
close_connection–Tear down the per-connection session on disconnect.
Source code in src/mcbe_ws_sdk/addon/service.py
create_client
¶
Build a client bound to one connection.
request_capability
async
¶
request_capability(connection_id: UUID, capability: str, payload: dict[str, Any], send_command: CommandSender) -> dict[str, Any]
Send a bridge request and wait for the addon's chat callback.
Source code in src/mcbe_ws_sdk/addon/service.py
is_bridge_chat_message
¶
True if the player chat message is an addon response fragment.
Source code in src/mcbe_ws_sdk/addon/service.py
is_ui_chat_message
¶
True if the player chat message is a UI chat fragment.
handle_player_message
async
¶
Route a routed message from the simulated player.
Source code in src/mcbe_ws_sdk/addon/service.py
set_ui_chat_callback
¶
close_connection
¶
Tear down the per-connection session on disconnect.
ConnectionAddonBridgeClient
¶
ConnectionAddonBridgeClient(service: AddonBridgeService, connection_id: UUID, send_command: CommandSender)
Per-connection client bound to one bridge service instance.
Source code in src/mcbe_ws_sdk/addon/service.py
service
¶
Addon bridge service.
Relocated from the main repo services/addon/service.py
Changes vs. the original:
- No module-level
_addon_bridge_servicesingleton and noget_addon_bridge_service()factory. The service is constructed with an explicit :class:AddonBridgeSettingsand any number of independent instances may coexist. - Timeout and profile are taken from
AddonBridgeSettingsinstead of a mutable global settings read. is_bridge_chat_message/is_ui_chat_messageuse the configured profile.
Classes:
-
AddonBridgeClient–Face an Agent uses to reach the addon bridge.
-
AddonBridgeService–Manage the request/response lifecycle between Python and the addon.
-
ConnectionAddonBridgeClient–Per-connection client bound to one bridge service instance.
AddonBridgeClient
¶
AddonBridgeService
¶
Manage the request/response lifecycle between Python and the addon.
Methods:
-
create_client–Build a client bound to one connection.
-
request_capability–Send a bridge request and wait for the addon's chat callback.
-
is_bridge_chat_message–True if the player chat message is an addon response fragment.
-
is_ui_chat_message–True if the player chat message is a UI chat fragment.
-
handle_player_message–Route a routed message from the simulated player.
-
set_ui_chat_callback–Register the UI chat message callback.
-
close_connection–Tear down the per-connection session on disconnect.
Source code in src/mcbe_ws_sdk/addon/service.py
create_client
¶
Build a client bound to one connection.
request_capability
async
¶
request_capability(connection_id: UUID, capability: str, payload: dict[str, Any], send_command: CommandSender) -> dict[str, Any]
Send a bridge request and wait for the addon's chat callback.
Source code in src/mcbe_ws_sdk/addon/service.py
is_bridge_chat_message
¶
True if the player chat message is an addon response fragment.
Source code in src/mcbe_ws_sdk/addon/service.py
is_ui_chat_message
¶
True if the player chat message is a UI chat fragment.
handle_player_message
async
¶
Route a routed message from the simulated player.
Source code in src/mcbe_ws_sdk/addon/service.py
set_ui_chat_callback
¶
close_connection
¶
Tear down the per-connection session on disconnect.
ConnectionAddonBridgeClient
¶
ConnectionAddonBridgeClient(service: AddonBridgeService, connection_id: UUID, send_command: CommandSender)
Per-connection client bound to one bridge service instance.
Source code in src/mcbe_ws_sdk/addon/service.py
session
¶
Addon bridge session management.
Classes:
-
PendingAddonRequest–Pending state for a single bridge request.
-
AddonBridgeSession–Maintain bridge requests and fragment buffers for one connection.
PendingAddonRequest
dataclass
¶
PendingAddonRequest(request_id: str, capability: str, payload: dict[str, Any], future: Future[dict[str, Any]])
Pending state for a single bridge request.
AddonBridgeSession
¶
Maintain bridge requests and fragment buffers for one connection.
Methods:
-
create_request–Create and register a pending request.
-
handle_chat_chunk–Consume a chat fragment; resolve its request future once complete.
-
close–Close the session, failing every pending request.
-
handle_ui_chat_chunk–Consume a UI chat fragment; return the chunk and a completed message if available.
Source code in src/mcbe_ws_sdk/addon/session.py
create_request
¶
Create and register a pending request.
Source code in src/mcbe_ws_sdk/addon/session.py
handle_chat_chunk
¶
Consume a chat fragment; resolve its request future once complete.
Source code in src/mcbe_ws_sdk/addon/session.py
close
¶
Close the session, failing every pending request.
Source code in src/mcbe_ws_sdk/addon/session.py
handle_ui_chat_chunk
¶
Consume a UI chat fragment; return the chunk and a completed message if available.
Source code in src/mcbe_ws_sdk/addon/session.py
Flow control¶
mcbe_ws_sdk.flow
¶
Flow control middleware for outbound MCBE command chunking.
Modules:
-
flow_control–Byte-safe outbound command chunking for MCBE
commandLinelimits.
Classes:
-
FlowControlMiddleware–Unified flow control: split outbound long text into safe Minecraft commands.
FlowControlMiddleware
¶
Unified flow control: split outbound long text into safe Minecraft commands.
Methods:
-
chunk_delay_for–Return inter-chunk delay in seconds for a chunking scenario.
-
chunk_tellraw–Split a long tellraw message into
commandRequestJSON payload strings. -
chunk_scriptevent–Split a long scriptevent payload into
commandRequestJSON strings. -
chunk_raw_command–Wrap a raw command as a one-element
commandRequestJSON list.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_delay_for
¶
Return inter-chunk delay in seconds for a chunking scenario.
kind is typically "tellraw" or "scriptevent". Unknown kinds
yield 0.0 (no delay); the caller may treat that as an error.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_tellraw
¶
chunk_tellraw(message: str, color: str = '§a', max_length: int | None = None, target: str = '@a') -> list[str]
Split a long tellraw message into commandRequest JSON payload strings.
Empty text returns []; the caller decides whether anything still must be
sent. Each JSON commandLine text is at most max_length characters,
and the final create_tellraw commandLine stays within the measured
461 B MCBE budget.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_scriptevent
¶
chunk_scriptevent(content: str, message_id: str = 'server:data', max_length: int | None = None) -> list[str]
Split a long scriptevent payload into commandRequest JSON strings.
Empty content returns []; the caller decides whether anything still
must be sent. Each commandLine content segment is at most
max_length characters, and total commandLine bytes stay within
the measured 461 B MCBE budget.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_raw_command
¶
Wrap a raw command as a one-element commandRequest JSON list.
Raw commands must not be truncated past the verb, or later fragments would
be illegal. This method does not chunk: over-budget input raises
FrameTooLargeError for the caller to handle.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
flow_control
¶
Byte-safe outbound command chunking for MCBE commandLine limits.
Classes:
-
FlowControlMiddleware–Unified flow control: split outbound long text into safe Minecraft commands.
FlowControlMiddleware
¶
Unified flow control: split outbound long text into safe Minecraft commands.
Methods:
-
chunk_delay_for–Return inter-chunk delay in seconds for a chunking scenario.
-
chunk_tellraw–Split a long tellraw message into
commandRequestJSON payload strings. -
chunk_scriptevent–Split a long scriptevent payload into
commandRequestJSON strings. -
chunk_raw_command–Wrap a raw command as a one-element
commandRequestJSON list.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_delay_for
¶
Return inter-chunk delay in seconds for a chunking scenario.
kind is typically "tellraw" or "scriptevent". Unknown kinds
yield 0.0 (no delay); the caller may treat that as an error.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_tellraw
¶
chunk_tellraw(message: str, color: str = '§a', max_length: int | None = None, target: str = '@a') -> list[str]
Split a long tellraw message into commandRequest JSON payload strings.
Empty text returns []; the caller decides whether anything still must be
sent. Each JSON commandLine text is at most max_length characters,
and the final create_tellraw commandLine stays within the measured
461 B MCBE budget.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_scriptevent
¶
chunk_scriptevent(content: str, message_id: str = 'server:data', max_length: int | None = None) -> list[str]
Split a long scriptevent payload into commandRequest JSON strings.
Empty content returns []; the caller decides whether anything still
must be sent. Each commandLine content segment is at most
max_length characters, and total commandLine bytes stay within
the measured 461 B MCBE budget.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
chunk_raw_command
¶
Wrap a raw command as a one-element commandRequest JSON list.
Raw commands must not be truncated past the verb, or later fragments would
be illegal. This method does not chunk: over-budget input raises
FrameTooLargeError for the caller to handle.
Source code in src/mcbe_ws_sdk/flow/flow_control.py
Protocol models¶
mcbe_ws_sdk.protocol
¶
Minecraft protocol message models.
Modules:
-
minecraft–Minecraft protocol message models (WebSocket envelopes and helpers).
Classes:
-
PlayerMessageEvent–Parsed player chat/message event from the WebSocket stream.
PlayerMessageEvent
¶
Bases: BaseModel
Parsed player chat/message event from the WebSocket stream.
Methods:
-
from_event_body–Parse a
PlayerMessageEventfrom an event body dict.
from_event_body
classmethod
¶
Parse a PlayerMessageEvent from an event body dict.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
minecraft
¶
Minecraft protocol message models (WebSocket envelopes and helpers).
Classes:
-
MinecraftHeader–Minecraft WebSocket message header.
-
MinecraftOrigin–Command origin metadata on a request body.
-
MinecraftCommandBody–Body of a
commandRequestframe. -
MinecraftSubscribeBody–Body of a subscribe request.
-
MinecraftMessage–Generic Minecraft WebSocket message envelope.
-
MinecraftCommand–Minecraft
commandRequestmessage. -
MinecraftSubscribe–Minecraft event subscription message.
-
PlayerMessageEvent–Parsed player chat/message event from the WebSocket stream.
Functions:
-
sanitize_tellraw_target–Return a command-safe tellraw target without allowing command injection.
-
validate_scriptevent_message_id–Validate a scriptevent message id before embedding it in commandLine.
-
sanitize_tellraw_text–Escape tellraw text before embedding in the rawtext JSON value.
MinecraftCommand
¶
Bases: BaseModel
Minecraft commandRequest message.
Methods:
-
create_tellraw–Build a tellraw command request.
-
create_scriptevent–Build a scriptevent command request.
-
create_raw–Build a raw command-line command request.
create_tellraw
classmethod
¶
Build a tellraw command request.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
create_scriptevent
classmethod
¶
Build a scriptevent command request.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
create_raw
classmethod
¶
MinecraftSubscribe
¶
Bases: BaseModel
Minecraft event subscription message.
Methods:
-
player_message–Subscribe to the
PlayerMessageevent.
player_message
classmethod
¶
PlayerMessageEvent
¶
Bases: BaseModel
Parsed player chat/message event from the WebSocket stream.
Methods:
-
from_event_body–Parse a
PlayerMessageEventfrom an event body dict.
from_event_body
classmethod
¶
Parse a PlayerMessageEvent from an event body dict.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
sanitize_tellraw_target
¶
Return a command-safe tellraw target without allowing command injection.
Player names are left unquoted whenever they contain no whitespace, quotes,
or backslashes. This is required for non-ASCII Bedrock names (e.g. 玩家):
wrapping them in double quotes makes the selector fail to match.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
validate_scriptevent_message_id
¶
Validate a scriptevent message id before embedding it in commandLine.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
sanitize_tellraw_text
¶
Escape tellraw text before embedding in the rawtext JSON value.
MCBE treats % as a format placeholder inside tellraw text; double it so
literal percents render. Quote/backslash escaping is left to json.dumps.
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
Profiles¶
mcbe_ws_sdk.profiles
¶
Protocol profiles for MCBE wire compatibility layers.
Modules:
-
mcbews_v1–mcbews v1 protocol profile.
Classes:
-
AddonBridgeProfile–Wire-format contract for addon bridge interop.
Delivery¶
mcbe_ws_sdk.delivery
¶
Outbound delivery adapter for MCBE WebSocket gateway.
Modules:
-
outbound–MCBE outbound delivery adapter.
Classes:
-
McbeOutboundDelivery–Chunk, throttle, send, and optionally log MCBE
commandRequestpayloads.
McbeOutboundDelivery
¶
McbeOutboundDelivery(*, connection_id: Any, send_payload: PayloadSender, settings: FlowControlSettings, log_raw_payloads: bool = False)
Chunk, throttle, send, and optionally log MCBE commandRequest payloads.
Methods:
-
send_payload–Send an already-built payload (subscribe, handshake, non-chunked paths).
-
send_tellraw–Send tellraw text and return the number of payloads actually transmitted.
-
send_scriptevent–Send scriptevent text and return the number of payloads actually transmitted.
-
send_raw_command–Send a raw command that must not be semantically split.
-
send_outbound_text–Route an OutboundText message through the delivery adapter.
-
send_system_notification–Route a SystemNotification through the delivery adapter.
-
send_chunked–Send
payloadswith inter-chunk delays.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_payload
async
¶
Send an already-built payload (subscribe, handshake, non-chunked paths).
send_tellraw
async
¶
Send tellraw text and return the number of payloads actually transmitted.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_scriptevent
async
¶
Send scriptevent text and return the number of payloads actually transmitted.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_raw_command
async
¶
send_raw_command(command: str, source: str = 'raw_command', before_send: Callable[[str], None] | None = None) -> str
Send a raw command that must not be semantically split.
Raises FrameTooLargeError when the command exceeds the byte budget.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_outbound_text
async
¶
Route an OutboundText message through the delivery adapter.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_system_notification
async
¶
Route a SystemNotification through the delivery adapter.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_chunked
async
¶
send_chunked(payloads: list[str], delay_kind: str, source: str, *, delay: float | None = None) -> None
Send payloads with inter-chunk delays.
When delay is provided it overrides flow.chunk_delay_for(delay_kind)
so protocol profiles can inject their own cadence (e.g.
profile.response_chunk_delay).
Source code in src/mcbe_ws_sdk/delivery/outbound.py
outbound
¶
MCBE outbound delivery adapter.
Classes:
-
McbeOutboundDelivery–Chunk, throttle, send, and optionally log MCBE
commandRequestpayloads.
McbeOutboundDelivery
¶
McbeOutboundDelivery(*, connection_id: Any, send_payload: PayloadSender, settings: FlowControlSettings, log_raw_payloads: bool = False)
Chunk, throttle, send, and optionally log MCBE commandRequest payloads.
Methods:
-
send_payload–Send an already-built payload (subscribe, handshake, non-chunked paths).
-
send_tellraw–Send tellraw text and return the number of payloads actually transmitted.
-
send_scriptevent–Send scriptevent text and return the number of payloads actually transmitted.
-
send_raw_command–Send a raw command that must not be semantically split.
-
send_outbound_text–Route an OutboundText message through the delivery adapter.
-
send_system_notification–Route a SystemNotification through the delivery adapter.
-
send_chunked–Send
payloadswith inter-chunk delays.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_payload
async
¶
Send an already-built payload (subscribe, handshake, non-chunked paths).
send_tellraw
async
¶
Send tellraw text and return the number of payloads actually transmitted.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_scriptevent
async
¶
Send scriptevent text and return the number of payloads actually transmitted.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_raw_command
async
¶
send_raw_command(command: str, source: str = 'raw_command', before_send: Callable[[str], None] | None = None) -> str
Send a raw command that must not be semantically split.
Raises FrameTooLargeError when the command exceeds the byte budget.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_outbound_text
async
¶
Route an OutboundText message through the delivery adapter.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_system_notification
async
¶
Route a SystemNotification through the delivery adapter.
Source code in src/mcbe_ws_sdk/delivery/outbound.py
send_chunked
async
¶
send_chunked(payloads: list[str], delay_kind: str, source: str, *, delay: float | None = None) -> None
Send payloads with inter-chunk delays.
When delay is provided it overrides flow.chunk_delay_for(delay_kind)
so protocol profiles can inject their own cadence (e.g.
profile.response_chunk_delay).
Source code in src/mcbe_ws_sdk/delivery/outbound.py
Command registry¶
mcbe_ws_sdk.command
¶
Command parsing package: registry + parsed-command value object.
Modules:
-
registry–Command registry + parsed-command value object, relocated from the host app.
Classes:
-
CommandRegistry–Registry of command prefixes, types, and aliases.
CommandRegistry
¶
Registry of command prefixes, types, and aliases.
Methods:
-
resolve–Resolve a message to
(command_type, content). -
resolve_parsed–Resolve a message to a typed command, including which token matched.
-
add_alias–Register a dynamic alias for an existing command prefix.
-
remove_alias–Remove a previously registered alias.
-
get_command_config–Return the loaded config for a primary command prefix.
-
get_aliases–Return all aliases for a command prefix.
-
list_all_commands–List all commands as
(prefix, type, aliases)tuples. -
get_command_prefix–Return the primary prefix for a command type, if registered.
Source code in src/mcbe_ws_sdk/command/registry.py
resolve
¶
Resolve a message to (command_type, content).
resolve_parsed
¶
Resolve a message to a typed command, including which token matched.
Source code in src/mcbe_ws_sdk/command/registry.py
add_alias
¶
Register a dynamic alias for an existing command prefix.
Source code in src/mcbe_ws_sdk/command/registry.py
remove_alias
¶
Remove a previously registered alias.
Source code in src/mcbe_ws_sdk/command/registry.py
get_command_config
¶
get_aliases
¶
list_all_commands
¶
List all commands as (prefix, type, aliases) tuples.
get_command_prefix
¶
registry
¶
Command registry + parsed-command value object, relocated from the host app.
The registry turns a {prefix: type | config} mapping into a matcher that
resolves an inbound message to a typed command. Matching is whole-word: a
prefix/alias matches only when it is the entire message or is followed by
whitespace, so #prefix_xyz does NOT match the #prefix token.
Classes:
-
MinecraftCommandConfig–A loaded command definition (prefix, type, aliases, description, usage).
-
CommandRegistry–Registry of command prefixes, types, and aliases.
MinecraftCommandConfig
dataclass
¶
MinecraftCommandConfig(prefix: str, type: str, description: str, aliases: tuple[str, ...] = tuple(), usage: str | None = None)
A loaded command definition (prefix, type, aliases, description, usage).
CommandRegistry
¶
Registry of command prefixes, types, and aliases.
Methods:
-
resolve–Resolve a message to
(command_type, content). -
resolve_parsed–Resolve a message to a typed command, including which token matched.
-
add_alias–Register a dynamic alias for an existing command prefix.
-
remove_alias–Remove a previously registered alias.
-
get_command_config–Return the loaded config for a primary command prefix.
-
get_aliases–Return all aliases for a command prefix.
-
list_all_commands–List all commands as
(prefix, type, aliases)tuples. -
get_command_prefix–Return the primary prefix for a command type, if registered.
Source code in src/mcbe_ws_sdk/command/registry.py
resolve
¶
Resolve a message to (command_type, content).
resolve_parsed
¶
Resolve a message to a typed command, including which token matched.
Source code in src/mcbe_ws_sdk/command/registry.py
add_alias
¶
Register a dynamic alias for an existing command prefix.
Source code in src/mcbe_ws_sdk/command/registry.py
remove_alias
¶
Remove a previously registered alias.
Source code in src/mcbe_ws_sdk/command/registry.py
get_command_config
¶
get_aliases
¶
list_all_commands
¶
List all commands as (prefix, type, aliases) tuples.
get_command_prefix
¶
Config & logging¶
mcbe_ws_sdk.config
¶
Classes:
-
WebsocketTransportConfig–Transport knobs for the facade's
websockets.servelifetime.
WebsocketTransportConfig
dataclass
¶
WebsocketTransportConfig(host: str = '0.0.0.0', port: int = 8080, ping_interval: float | None = 30.0, ping_timeout: float | None = 15.0, close_timeout: float = 15.0, max_size: int | None = 10 * 1024 * 1024, max_queue: int | None = 32, response_queue_maxsize: int = 256)
Transport knobs for the facade's websockets.serve lifetime.
mcbe_ws_sdk.logging
¶
Optional console logging helpers for hosts and examples.
The SDK itself only emits structured events via structlog.get_logger.
Hosts that want a readable console should call :func:configure_logging once
at process start. Defaults match the compact style used by the parent MCBE AI
Agent host: no level/event column padding, local timestamps, key=value fields.
Functions:
-
configure_logging–Configure structlog + stdlib logging for compact console output.
configure_logging
¶
Configure structlog + stdlib logging for compact console output.
Parameters¶
level:
Root log level name (default INFO).
colors:
Force colour on/off. None (default) enables colour only when stdout
is a TTY.
Source code in src/mcbe_ws_sdk/logging.py
Errors¶
mcbe_ws_sdk.errors
¶
Public exception hierarchy for mcbe-ws-sdk.
Classes:
-
McbeWsSdkError–Base class for SDK errors.
-
ConfigurationError–Raised when SDK settings are invalid.
-
ProtocolError–Raised when a protocol contract is violated.
-
FrameTooLargeError–Raised when a frame cannot fit within its configured byte budget.
-
BridgeError–Base class for add-on bridge errors.
-
BridgeTimeoutError–Raised when an add-on bridge request times out.
-
BridgeClosedError–Raised when an add-on bridge is closed.
-
BridgeLimitError–Raised when an add-on bridge protocol limit is exceeded.
-
FacadeLifecycleError–Raised for invalid server facade lifecycle transitions.
ConfigurationError
¶
Bases: McbeWsSdkError, ValueError
Raised when SDK settings are invalid.
ProtocolError
¶
Bases: McbeWsSdkError, ValueError
Raised when a protocol contract is violated.
FrameTooLargeError
¶
Bases: ProtocolError
Raised when a frame cannot fit within its configured byte budget.
BridgeError
¶
Bases: McbeWsSdkError
Base class for add-on bridge errors.
BridgeTimeoutError
¶
Bases: BridgeError
Raised when an add-on bridge request times out.
Source code in src/mcbe_ws_sdk/errors.py
BridgeClosedError
¶
BridgeLimitError
¶
Bases: BridgeError, ProtocolError
Raised when an add-on bridge protocol limit is exceeded.
FacadeLifecycleError
¶
Bases: McbeWsSdkError, RuntimeError
Raised for invalid server facade lifecycle transitions.