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–MCBEWS/1 protocol profile exports.
-
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.
-
LegacyUiChatCallbackAdapter–Adapt the pre-0.2.0 three-argument callback to the typed DTO callback.
-
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.
-
AddonControlHook–Optional hook for authenticated session/approval ToolPlayer DTOs.
-
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. -
LegacyUiChatHook–Pre-0.2.0 UI callback shape used only through an explicit adapter.
-
LegacyUiChatHookAdapter–Adapt a legacy three-argument UI hook to the typed callback boundary.
-
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.
-
McbewsV1Profile–Concrete MCBEWS/1 wire profile.
-
ToolPlayerMessage–A control-channel message accepted only from the trusted ToolPlayer.
-
McbewsV1Delivery– -
ApprovalDecision–Typed approval decision carried by the ToolPlayer chat channel.
-
SessionError–Stable, bounded session error object.
-
SessionRequest–Validated session operation request from the trusted ToolPlayer.
-
SessionResponse–Atomic session response correlated to one :class:
SessionRequest. -
TextResponseChunk–One validated
mcbews:text_respframe. -
TextResponseMessage–A complete, ordered text response after bounded reassembly.
-
TokenUsage–Compact token usage included only in a final text response frame.
-
UiChatMessage–A complete UI chat message with its originating conversation.
-
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.
-
classify_tool_player_message–Authenticate and classify one ToolPlayer chat message.
-
is_tool_player_channel_message–Return whether a message uses a reserved MCBEWS/1 control prefix.
-
decode_approval_decision–Decode a typed or one-cycle legacy ToolPlayer approval decision.
-
decode_session_request_chat–Decode
MCBEWS|SESSION|<json>into a validated DTO. -
decode_session_response_message–Decode an Addon
mcbews:session_respevent body. -
decode_text_response_frame–Decode and validate one text response frame, rejecting unknown roles.
-
encode_approval_decision–Encode a typed approval decision for the trusted ToolPlayer channel.
-
encode_session_request_chat–Encode the atomic session request chat envelope.
-
encode_session_response_command–Encode one atomic
mcbews:session_respcommandRequest payload. -
load_manifest–Load the immutable MCBEWS/1 manifest from the installed package.
-
load_wire_vectors–Load the immutable executable MCBEWS/1 conformance vectors.
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.
-
is_tool_player_channel_message–Return whether message is reserved for a ToolPlayer channel.
-
classify_tool_player_message–Authenticate and classify a reserved ToolPlayer message.
-
handle_player_message–Route a routed message from the simulated player.
-
set_ui_chat_callback–Register the typed UI chat message callback.
-
set_legacy_ui_chat_callback–Register a legacy callback through an explicit migration adapter.
-
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
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
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.
Source code in src/mcbe_ws_sdk/addon/service.py
is_tool_player_channel_message
¶
Return whether message is reserved for a ToolPlayer channel.
classify_tool_player_message
¶
Authenticate and classify a reserved ToolPlayer message.
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
¶
set_legacy_ui_chat_callback
¶
Register a legacy callback through an explicit migration adapter.
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
LegacyUiChatCallbackAdapter
¶
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
AddonControlHook
¶
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
¶
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
LegacyUiChatHook
¶
LegacyUiChatHookAdapter
¶
McbeServerFacade
¶
McbeServerFacade(*, settings: GatewaySettings | None = None, hook: ConnectionHook | None = None, legacy_ui_chat_hook: LegacyUiChatHook | 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.
McbewsV1Profile
dataclass
¶
McbewsV1Profile(*, capability_request_script_event_id: str | None = None, capability_response_chat_prefix: str | None = None, ui_chat_chunk_prefix: str | None = None, session_request_chat_prefix: str | None = None, session_request_script_event_id: str | None = None, session_response_script_event_id: str | None = None, text_response_script_event_id: str | None = None, approval_allow_chat_prefix: str | None = None, approval_deny_chat_prefix: str | None = None, trusted_bridge_player_name: str | None = None, capability_request_schema_version: int | None = None, session_schema_version: int | None = None, text_response_framing_version: int | None = None, ddui_persistence_version: int | None = None, command_line_byte_budget: int | None = None, upstream_max_content_code_points: int | None = None, response_max_buffers: int | None = None, response_max_chunks_per_message: int | None = None, response_max_message_bytes: int | None = None, response_max_total_buffer_bytes: int | None = None, response_buffer_ttl_ms: int | None = None, session_response_max_command_bytes: int | None = None, response_chunk_delay: float = 0.15, response_prelude_delay: float = 0.5, bridge_request_message_id: str | None = None, bridge_response_prefix: str | None = None, ui_chat_prefix: str | None = None, bridge_sender: str | None = None, response_message_id: str | None = None, session_request_message_id: str | None = None, session_response_message_id: str | None = None, request_version: int | None = None)
Concrete MCBEWS/1 wire profile.
The semantic field names are the protocol authority. Wire identifiers, schema versions and safety bounds come from the installed manifest and cannot be replaced by a runtime profile seam. The empirical command budget may be lowered for a deployment and response delays remain operational knobs. Historical names are accepted for one migration cycle only when they still select the manifest value.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/profile.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
ToolPlayerMessage
dataclass
¶
ToolPlayerMessage(channel: ToolPlayerChannel, sender: str, raw_message: str, session_request: SessionRequest | None = None, approval_decision: ApprovalDecision | None = None)
A control-channel message accepted only from the trusted ToolPlayer.
McbewsV1Delivery
¶
McbewsV1Delivery(outbound: McbeOutboundDelivery, *, profile: McbewsV1Profile = MCBEWS_V1, sleeper: Sleeper = asyncio.sleep)
Methods:
-
send_session_response–Send one atomic correlated session response.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/delivery.py
send_session_response
async
¶
Send one atomic correlated session response.
Session responses deliberately bypass generic scriptevent chunking. A
result that does not fit is encoded as one SESSION_RESPONSE_TOO_LARGE
error by :func:encode_session_response_command.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/delivery.py
ApprovalDecision
¶
Bases: BaseModel
Typed approval decision carried by the ToolPlayer chat channel.
legacy=True is only used by the decoder for an id-only decision. Such
a decision deliberately has no owner and must be resolved by a Host pending
approval store; it is never treated as coming from the transport sender.
Attributes:
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
classify_tool_player_message
¶
classify_tool_player_message(sender: str, message: str, profile: McbewsV1Profile = MCBEWS_V1) -> ToolPlayerMessage | None
Authenticate and classify one ToolPlayer chat message.
None means either that the sender is not the trusted ToolPlayer or the
message is ordinary player chat. Malformed reserved messages raise a typed
:class:ProtocolError; callers can log/drop them without passing them to a
business hook.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/classifier.py
is_tool_player_channel_message
¶
Return whether a message uses a reserved MCBEWS/1 control prefix.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/classifier.py
decode_approval_decision
¶
Decode a typed or one-cycle legacy ToolPlayer approval decision.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_session_request_chat
¶
Decode MCBEWS|SESSION|<json> into a validated DTO.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_session_response_message
¶
decode_session_response_message(message: str, profile: McbewsV1Profile = MCBEWS_V1) -> SessionResponse
Decode an Addon mcbews:session_resp event body.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_text_response_frame
¶
Decode and validate one text response frame, rejecting unknown roles.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_approval_decision
¶
Encode a typed approval decision for the trusted ToolPlayer channel.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_request_chat
¶
Encode the atomic session request chat envelope.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_response_command
¶
encode_session_response_command(response: SessionResponse, flow: FlowControlMiddleware, profile: McbewsV1Profile = MCBEWS_V1) -> str
Encode one atomic mcbews:session_resp commandRequest payload.
A large successful result is replaced by a correlated structured error. No generic chunker is called, so a receiver never sees a fragment that looks like a complete JSON response.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
load_manifest
¶
Load the immutable MCBEWS/1 manifest from the installed package.
load_wire_vectors
¶
Load the immutable executable MCBEWS/1 conformance vectors.
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.
-
AddonControlHook–Optional hook for authenticated session/approval ToolPlayer DTOs.
-
ConnectionHook–Lifecycle + protocol hooks the host injects into the gateway.
-
LegacyUiChatHook–Pre-0.2.0 UI callback shape used only through an explicit adapter.
-
LegacyUiChatHookAdapter–Adapt a legacy three-argument UI hook to the typed callback boundary.
-
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
AddonControlHook
¶
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
¶
on_command_response
async
¶
Inbound commandResponse (resolves run_command futures).
LegacyUiChatHook
¶
LegacyUiChatHookAdapter
¶
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, legacy_ui_chat_hook: LegacyUiChatHook | 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. -
LegacyUiChatHook–Pre-0.2.0 UI callback shape used only through an explicit adapter.
-
LegacyUiChatHookAdapter–Adapt a legacy three-argument UI hook to the typed callback boundary.
-
AddonControlHook–Optional hook for authenticated session/approval ToolPlayer DTOs.
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
¶
on_command_response
async
¶
Inbound commandResponse (resolves run_command futures).
NoOpHook
¶
Gateway default ConnectionHook — every hook is a no-op.
LegacyUiChatHook
¶
LegacyUiChatHookAdapter
¶
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, legacy_ui_chat_hook: LegacyUiChatHook | 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.
-
LegacyUiChatCallbackAdapter–Adapt the pre-0.2.0 three-argument callback to the typed DTO callback.
-
ToolPlayerMessage–A control-channel message accepted only from the trusted ToolPlayer.
-
ApprovalDecision–Typed approval decision carried by the ToolPlayer chat channel.
-
SessionRequest–Validated session operation request from the trusted ToolPlayer.
-
SessionResponse–Atomic session response correlated to one :class:
SessionRequest. -
TextResponseChunk–One validated
mcbews:text_respframe. -
TextResponseMessage–A complete, ordered text response after bounded reassembly.
-
UiChatMessage–A complete UI chat message with its originating conversation.
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.
-
is_tool_player_channel_message–Return whether message is reserved for a ToolPlayer channel.
-
classify_tool_player_message–Authenticate and classify a reserved ToolPlayer message.
-
handle_player_message–Route a routed message from the simulated player.
-
set_ui_chat_callback–Register the typed UI chat message callback.
-
set_legacy_ui_chat_callback–Register a legacy callback through an explicit migration adapter.
-
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
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
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.
Source code in src/mcbe_ws_sdk/addon/service.py
is_tool_player_channel_message
¶
Return whether message is reserved for a ToolPlayer channel.
classify_tool_player_message
¶
Authenticate and classify a reserved ToolPlayer message.
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
¶
set_legacy_ui_chat_callback
¶
Register a legacy callback through an explicit migration adapter.
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
LegacyUiChatCallbackAdapter
¶
ToolPlayerMessage
dataclass
¶
ToolPlayerMessage(channel: ToolPlayerChannel, sender: str, raw_message: str, session_request: SessionRequest | None = None, approval_decision: ApprovalDecision | None = None)
A control-channel message accepted only from the trusted ToolPlayer.
ApprovalDecision
¶
Bases: BaseModel
Typed approval decision carried by the ToolPlayer chat channel.
legacy=True is only used by the decoder for an id-only decision. Such
a decision deliberately has no owner and must be resolved by a Host pending
approval store; it is never treated as coming from the transport sender.
Attributes:
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:
-
LegacyUiChatCallbackAdapter–Adapt the pre-0.2.0 three-argument callback to the typed DTO callback.
-
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.
LegacyUiChatCallbackAdapter
¶
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.
-
is_tool_player_channel_message–Return whether message is reserved for a ToolPlayer channel.
-
classify_tool_player_message–Authenticate and classify a reserved ToolPlayer message.
-
handle_player_message–Route a routed message from the simulated player.
-
set_ui_chat_callback–Register the typed UI chat message callback.
-
set_legacy_ui_chat_callback–Register a legacy callback through an explicit migration adapter.
-
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
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
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.
Source code in src/mcbe_ws_sdk/addon/service.py
is_tool_player_channel_message
¶
Return whether message is reserved for a ToolPlayer channel.
classify_tool_player_message
¶
Authenticate and classify a reserved ToolPlayer message.
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
¶
set_legacy_ui_chat_callback
¶
Register a legacy callback through an explicit migration adapter.
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–Prepare tellraw body 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
¶
Prepare tellraw body text before embedding in the rawtext JSON value.
Quote/backslash escaping is left to json.dumps. Plain % is left
unchanged: Bedrock rawtext text components render a single percent
literally, and doubling it surfaces as %% in chat (e.g. context usage
tips like 20.0%).
Source code in src/mcbe_ws_sdk/protocol/minecraft.py
Profiles¶
mcbe_ws_sdk.profiles
¶
MCBEWS/1 protocol profile exports.
MCBEWS/1 is the sole runtime profile. AddonBridgeProfile is retained as a
deprecated type alias/re-export for source compatibility; it is not a runtime
extension seam and SDK settings accept the concrete profile only.
Modules:
-
mcbews_v1–MCBEWS/1 protocol implementation and canonical assets.
Classes:
-
McbewsV1Profile–Concrete MCBEWS/1 wire profile.
McbewsV1Profile
dataclass
¶
McbewsV1Profile(*, capability_request_script_event_id: str | None = None, capability_response_chat_prefix: str | None = None, ui_chat_chunk_prefix: str | None = None, session_request_chat_prefix: str | None = None, session_request_script_event_id: str | None = None, session_response_script_event_id: str | None = None, text_response_script_event_id: str | None = None, approval_allow_chat_prefix: str | None = None, approval_deny_chat_prefix: str | None = None, trusted_bridge_player_name: str | None = None, capability_request_schema_version: int | None = None, session_schema_version: int | None = None, text_response_framing_version: int | None = None, ddui_persistence_version: int | None = None, command_line_byte_budget: int | None = None, upstream_max_content_code_points: int | None = None, response_max_buffers: int | None = None, response_max_chunks_per_message: int | None = None, response_max_message_bytes: int | None = None, response_max_total_buffer_bytes: int | None = None, response_buffer_ttl_ms: int | None = None, session_response_max_command_bytes: int | None = None, response_chunk_delay: float = 0.15, response_prelude_delay: float = 0.5, bridge_request_message_id: str | None = None, bridge_response_prefix: str | None = None, ui_chat_prefix: str | None = None, bridge_sender: str | None = None, response_message_id: str | None = None, session_request_message_id: str | None = None, session_response_message_id: str | None = None, request_version: int | None = None)
Concrete MCBEWS/1 wire profile.
The semantic field names are the protocol authority. Wire identifiers, schema versions and safety bounds come from the installed manifest and cannot be replaced by a runtime profile seam. The empirical command budget may be lowered for a deployment and response delays remain operational knobs. Historical names are accepted for one migration cycle only when they still select the manifest value.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/profile.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
mcbews_v1
¶
MCBEWS/1 protocol implementation and canonical assets.
Modules:
-
classifier–Trusted ToolPlayer channel classification for MCBEWS/1.
-
codec– -
delivery– -
manifest–Canonical MCBEWS/1 protocol assets.
-
models–Typed MCBEWS/1 wire DTOs.
-
profile–
Classes:
-
ToolPlayerMessage–A control-channel message accepted only from the trusted ToolPlayer.
-
AddonBridgeRequest–Capability request sent to the reference Addon.
-
ApprovalDecision–Typed approval decision carried by the ToolPlayer chat channel.
-
SessionError–Stable, bounded session error object.
-
SessionRequest–Validated session operation request from the trusted ToolPlayer.
-
SessionResponse–Atomic session response correlated to one :class:
SessionRequest. -
TextResponseChunk–One validated
mcbews:text_respframe. -
TextResponseMessage–A complete, ordered text response after bounded reassembly.
-
TokenUsage–Compact token usage included only in a final text response frame.
-
UiChatMessage–A complete UI chat message with its originating conversation.
-
McbewsV1Profile–Concrete MCBEWS/1 wire profile.
Functions:
-
classify_tool_player_message–Authenticate and classify one ToolPlayer chat message.
-
is_tool_player_channel_message–Return whether a message uses a reserved MCBEWS/1 control prefix.
-
decode_approval_decision–Decode a typed or one-cycle legacy ToolPlayer approval decision.
-
decode_session_request_chat–Decode
MCBEWS|SESSION|<json>into a validated DTO. -
decode_session_response_message–Decode an Addon
mcbews:session_respevent body. -
decode_text_response_frame–Decode and validate one text response frame, rejecting unknown roles.
-
encode_approval_decision–Encode a typed approval decision for the trusted ToolPlayer channel.
-
encode_session_request_chat–Encode the atomic session request chat envelope.
-
encode_session_response_command–Encode one atomic
mcbews:session_respcommandRequest payload. -
encode_session_response_json–Serialize a session response with compact wire aliases.
-
reassemble_text_response_chunks–Reassemble already validated text chunks with metadata consistency checks.
-
load_manifest–Load the immutable MCBEWS/1 manifest from the installed package.
-
load_wire_vectors–Load the immutable executable MCBEWS/1 conformance vectors.
ToolPlayerMessage
dataclass
¶
ToolPlayerMessage(channel: ToolPlayerChannel, sender: str, raw_message: str, session_request: SessionRequest | None = None, approval_decision: ApprovalDecision | None = None)
A control-channel message accepted only from the trusted ToolPlayer.
ApprovalDecision
¶
Bases: BaseModel
Typed approval decision carried by the ToolPlayer chat channel.
legacy=True is only used by the decoder for an id-only decision. Such
a decision deliberately has no owner and must be resolved by a Host pending
approval store; it is never treated as coming from the transport sender.
Attributes:
McbewsV1Profile
dataclass
¶
McbewsV1Profile(*, capability_request_script_event_id: str | None = None, capability_response_chat_prefix: str | None = None, ui_chat_chunk_prefix: str | None = None, session_request_chat_prefix: str | None = None, session_request_script_event_id: str | None = None, session_response_script_event_id: str | None = None, text_response_script_event_id: str | None = None, approval_allow_chat_prefix: str | None = None, approval_deny_chat_prefix: str | None = None, trusted_bridge_player_name: str | None = None, capability_request_schema_version: int | None = None, session_schema_version: int | None = None, text_response_framing_version: int | None = None, ddui_persistence_version: int | None = None, command_line_byte_budget: int | None = None, upstream_max_content_code_points: int | None = None, response_max_buffers: int | None = None, response_max_chunks_per_message: int | None = None, response_max_message_bytes: int | None = None, response_max_total_buffer_bytes: int | None = None, response_buffer_ttl_ms: int | None = None, session_response_max_command_bytes: int | None = None, response_chunk_delay: float = 0.15, response_prelude_delay: float = 0.5, bridge_request_message_id: str | None = None, bridge_response_prefix: str | None = None, ui_chat_prefix: str | None = None, bridge_sender: str | None = None, response_message_id: str | None = None, session_request_message_id: str | None = None, session_response_message_id: str | None = None, request_version: int | None = None)
Concrete MCBEWS/1 wire profile.
The semantic field names are the protocol authority. Wire identifiers, schema versions and safety bounds come from the installed manifest and cannot be replaced by a runtime profile seam. The empirical command budget may be lowered for a deployment and response delays remain operational knobs. Historical names are accepted for one migration cycle only when they still select the manifest value.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/profile.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
classify_tool_player_message
¶
classify_tool_player_message(sender: str, message: str, profile: McbewsV1Profile = MCBEWS_V1) -> ToolPlayerMessage | None
Authenticate and classify one ToolPlayer chat message.
None means either that the sender is not the trusted ToolPlayer or the
message is ordinary player chat. Malformed reserved messages raise a typed
:class:ProtocolError; callers can log/drop them without passing them to a
business hook.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/classifier.py
is_tool_player_channel_message
¶
Return whether a message uses a reserved MCBEWS/1 control prefix.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/classifier.py
decode_approval_decision
¶
Decode a typed or one-cycle legacy ToolPlayer approval decision.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_session_request_chat
¶
Decode MCBEWS|SESSION|<json> into a validated DTO.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_session_response_message
¶
decode_session_response_message(message: str, profile: McbewsV1Profile = MCBEWS_V1) -> SessionResponse
Decode an Addon mcbews:session_resp event body.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_text_response_frame
¶
Decode and validate one text response frame, rejecting unknown roles.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_approval_decision
¶
Encode a typed approval decision for the trusted ToolPlayer channel.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_request_chat
¶
Encode the atomic session request chat envelope.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_response_command
¶
encode_session_response_command(response: SessionResponse, flow: FlowControlMiddleware, profile: McbewsV1Profile = MCBEWS_V1) -> str
Encode one atomic mcbews:session_resp commandRequest payload.
A large successful result is replaced by a correlated structured error. No generic chunker is called, so a receiver never sees a fragment that looks like a complete JSON response.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_response_json
¶
Serialize a session response with compact wire aliases.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
reassemble_text_response_chunks
¶
Reassemble already validated text chunks with metadata consistency checks.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
load_manifest
¶
Load the immutable MCBEWS/1 manifest from the installed package.
load_wire_vectors
¶
Load the immutable executable MCBEWS/1 conformance vectors.
classifier
¶
Trusted ToolPlayer channel classification for MCBEWS/1.
Classes:
-
ToolPlayerMessage–A control-channel message accepted only from the trusted ToolPlayer.
Functions:
-
is_tool_player_channel_message–Return whether a message uses a reserved MCBEWS/1 control prefix.
-
classify_tool_player_message–Authenticate and classify one ToolPlayer chat message.
ToolPlayerMessage
dataclass
¶
ToolPlayerMessage(channel: ToolPlayerChannel, sender: str, raw_message: str, session_request: SessionRequest | None = None, approval_decision: ApprovalDecision | None = None)
A control-channel message accepted only from the trusted ToolPlayer.
is_tool_player_channel_message
¶
Return whether a message uses a reserved MCBEWS/1 control prefix.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/classifier.py
classify_tool_player_message
¶
classify_tool_player_message(sender: str, message: str, profile: McbewsV1Profile = MCBEWS_V1) -> ToolPlayerMessage | None
Authenticate and classify one ToolPlayer chat message.
None means either that the sender is not the trusted ToolPlayer or the
message is ordinary player chat. Malformed reserved messages raise a typed
:class:ProtocolError; callers can log/drop them without passing them to a
business hook.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/classifier.py
codec
¶
Functions:
-
encode_session_request_chat–Encode the atomic session request chat envelope.
-
decode_session_request_chat–Decode
MCBEWS|SESSION|<json>into a validated DTO. -
encode_session_response_json–Serialize a session response with compact wire aliases.
-
encode_session_response_command–Encode one atomic
mcbews:session_respcommandRequest payload. -
decode_session_response_message–Decode an Addon
mcbews:session_respevent body. -
decode_approval_decision–Decode a typed or one-cycle legacy ToolPlayer approval decision.
-
decode_text_response_frame–Decode and validate one text response frame, rejecting unknown roles.
-
reassemble_text_response_chunks–Reassemble already validated text chunks with metadata consistency checks.
-
encode_approval_decision–Encode a typed approval decision for the trusted ToolPlayer channel.
encode_session_request_chat
¶
Encode the atomic session request chat envelope.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_session_request_chat
¶
Decode MCBEWS|SESSION|<json> into a validated DTO.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_response_json
¶
Serialize a session response with compact wire aliases.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_session_response_command
¶
encode_session_response_command(response: SessionResponse, flow: FlowControlMiddleware, profile: McbewsV1Profile = MCBEWS_V1) -> str
Encode one atomic mcbews:session_resp commandRequest payload.
A large successful result is replaced by a correlated structured error. No generic chunker is called, so a receiver never sees a fragment that looks like a complete JSON response.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_session_response_message
¶
decode_session_response_message(message: str, profile: McbewsV1Profile = MCBEWS_V1) -> SessionResponse
Decode an Addon mcbews:session_resp event body.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_approval_decision
¶
Decode a typed or one-cycle legacy ToolPlayer approval decision.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
decode_text_response_frame
¶
Decode and validate one text response frame, rejecting unknown roles.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
reassemble_text_response_chunks
¶
Reassemble already validated text chunks with metadata consistency checks.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
encode_approval_decision
¶
Encode a typed approval decision for the trusted ToolPlayer channel.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/codec.py
delivery
¶
Classes:
McbewsV1Delivery
¶
McbewsV1Delivery(outbound: McbeOutboundDelivery, *, profile: McbewsV1Profile = MCBEWS_V1, sleeper: Sleeper = asyncio.sleep)
Methods:
-
send_session_response–Send one atomic correlated session response.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/delivery.py
send_session_response
async
¶
Send one atomic correlated session response.
Session responses deliberately bypass generic scriptevent chunking. A
result that does not fit is encoded as one SESSION_RESPONSE_TOO_LARGE
error by :func:encode_session_response_command.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/delivery.py
manifest
¶
Canonical MCBEWS/1 protocol assets.
The JSON resources in this module are intentionally small and executable. The Python codec, the reference Addon and downstream conformance checks all project their constants and vectors from the same shape instead of treating a hand copied list of strings as the protocol authority.
Functions:
-
load_manifest–Load the immutable MCBEWS/1 manifest from the installed package.
-
load_wire_vectors–Load the immutable executable MCBEWS/1 conformance vectors.
models
¶
Typed MCBEWS/1 wire DTOs.
The models intentionally keep the compact wire aliases (v, cid,
sid and u) at the boundary while exposing semantic Python names to
Host adapters.
Classes:
-
AddonBridgeRequest–Capability request sent to the reference Addon.
-
UiChatMessage–A complete UI chat message with its originating conversation.
-
SessionRequest–Validated session operation request from the trusted ToolPlayer.
-
SessionError–Stable, bounded session error object.
-
SessionResponse–Atomic session response correlated to one :class:
SessionRequest. -
ApprovalDecision–Typed approval decision carried by the ToolPlayer chat channel.
-
TokenUsage–Compact token usage included only in a final text response frame.
-
TextResponseChunk–One validated
mcbews:text_respframe. -
TextResponseMessage–A complete, ordered text response after bounded reassembly.
ApprovalDecision
¶
Bases: BaseModel
Typed approval decision carried by the ToolPlayer chat channel.
legacy=True is only used by the decoder for an id-only decision. Such
a decision deliberately has no owner and must be resolved by a Host pending
approval store; it is never treated as coming from the transport sender.
Attributes:
protocol_error_message
¶
Convert a Pydantic validation error to the SDK boundary error type.
profile
¶
Classes:
-
McbewsV1Profile–Concrete MCBEWS/1 wire profile.
McbewsV1Profile
dataclass
¶
McbewsV1Profile(*, capability_request_script_event_id: str | None = None, capability_response_chat_prefix: str | None = None, ui_chat_chunk_prefix: str | None = None, session_request_chat_prefix: str | None = None, session_request_script_event_id: str | None = None, session_response_script_event_id: str | None = None, text_response_script_event_id: str | None = None, approval_allow_chat_prefix: str | None = None, approval_deny_chat_prefix: str | None = None, trusted_bridge_player_name: str | None = None, capability_request_schema_version: int | None = None, session_schema_version: int | None = None, text_response_framing_version: int | None = None, ddui_persistence_version: int | None = None, command_line_byte_budget: int | None = None, upstream_max_content_code_points: int | None = None, response_max_buffers: int | None = None, response_max_chunks_per_message: int | None = None, response_max_message_bytes: int | None = None, response_max_total_buffer_bytes: int | None = None, response_buffer_ttl_ms: int | None = None, session_response_max_command_bytes: int | None = None, response_chunk_delay: float = 0.15, response_prelude_delay: float = 0.5, bridge_request_message_id: str | None = None, bridge_response_prefix: str | None = None, ui_chat_prefix: str | None = None, bridge_sender: str | None = None, response_message_id: str | None = None, session_request_message_id: str | None = None, session_response_message_id: str | None = None, request_version: int | None = None)
Concrete MCBEWS/1 wire profile.
The semantic field names are the protocol authority. Wire identifiers, schema versions and safety bounds come from the installed manifest and cannot be replaced by a runtime profile seam. The empirical command budget may be lowered for a deployment and response delays remain operational knobs. Historical names are accepted for one migration cycle only when they still select the manifest value.
Source code in src/mcbe_ws_sdk/profiles/mcbews_v1/profile.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 | |
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.