Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions doc/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,6 @@ Spice86 ships with **65+ MCP tools** organized into these capability scopes:

### Input Automation
- `send_keyboard_key`: Send a keystroke (press + release or hold)
- `press_key`: Write a BIOS key code straight into the BDA keyboard ring (`ascii`, `scancode`; extended keys use `ascii=0`). Takes effect on the next INT 16h read with no GUI involvement — use it when you need exact scan codes or headless delivery.
- `send_mouse_packet`: Send raw mouse data packet
- `send_mouse_move`: Move mouse cursor
- `send_mouse_button`: Press/release mouse button

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ namespace Spice86.Core.Emulator.Devices.Input.Keyboard;
using Spice86.Core.Emulator.Devices.ExternalInput;
using Spice86.Core.Emulator.IOPorts;
using Spice86.Core.Emulator.Memory;
using Spice86.Core.Emulator.VM;
using Spice86.Core.Emulator.VM.DeviceScheduler;
using Spice86.Shared.Interfaces;

/// <summary>
/// Emulates the Intel 8042 keyboard controller, providing PS/2 keyboard and mouse (auxiliary device) port functionality
Expand Down Expand Up @@ -88,7 +88,7 @@ public partial class Intel8042Controller : DefaultIOPortHandler {
public Intel8042Controller(State state, IOPortDispatcher ioPortDispatcher,
A20Gate a20Gate, DualPic dualPic, DeviceScheduler scheduler, bool failOnUnhandledPort,
ILogger loggerService,
IGuiKeyboardEvents? gui = null)
IKeyboardInputEvents? gui = null)
: base(state, failOnUnhandledPort, loggerService) {
_a20Gate = a20Gate;
_cpuState = state;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
namespace Spice86.Core.Emulator.Devices.Input.Keyboard;


using Spice86.Core.Emulator.VM;
using Spice86.Core.Emulator.VM.DeviceScheduler;
using Spice86.Shared.Emulator.Keyboard;
using Spice86.Shared.Interfaces;

using System.Collections.Generic;
using System.Diagnostics;
Expand All @@ -20,7 +20,7 @@ public partial class PS2Keyboard {
private readonly ILogger _loggerService;
private readonly KeyboardScancodeConverter _scancodeConverter = new();
private readonly DeviceScheduler _scheduler;
private readonly IGuiKeyboardEvents? _gui;
private readonly IKeyboardInputEvents? _gui;
private readonly EventHandler _typematicTickHandler;
private readonly EventHandler _ledsAllOnExpireHandler;

Expand Down Expand Up @@ -74,7 +74,7 @@ public partial class PS2Keyboard {
/// <param name="gui">Optional GUI interface for keyboard events.</param>
public PS2Keyboard(Intel8042Controller controller,
DeviceScheduler scheduler, ILogger loggerService,
IGuiKeyboardEvents? gui = null) {
IKeyboardInputEvents? gui = null) {
_controller = controller;
_loggerService = loggerService;
_scheduler = scheduler;
Expand All @@ -93,9 +93,12 @@ public PS2Keyboard(Intel8042Controller controller,
if (_gui is not null) {
_gui.KeyDown += OnKeyEvent;
_gui.KeyUp += OnKeyEvent;
_gui.AllKeysReleased += OnAllKeysReleased;
}
}

private void OnAllKeysReleased(object? sender, EventArgs e) => ReleaseAllKeys();

private void WarnResend() {
if (_loggerService.IsEnabled(LogLevel.Warning)) {
_loggerService.LogWarning("KEYBOARD: Resend command not implemented");
Expand Down
42 changes: 0 additions & 42 deletions src/Spice86.Core/Emulator/Mcp/EmulatorMcpServices.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ namespace Spice86.Core.Emulator.Mcp;

using Spice86.Core.Emulator.CPU;
using Spice86.Core.Emulator.CPU.CfgCpu;
using Spice86.Core.Emulator.Devices.Input.Keyboard;
using Spice86.Core.Emulator.Devices.Sound;
using Spice86.Core.Emulator.Devices.Sound.Blaster;
using Spice86.Core.Emulator.Devices.Sound.Midi;
Expand All @@ -15,7 +14,6 @@ namespace Spice86.Core.Emulator.Mcp;
using Spice86.Core.Emulator.InterruptHandlers.Bios.Structures;
using Spice86.Core.Emulator.InterruptHandlers.Dos.Ems;
using Spice86.Core.Emulator.InterruptHandlers.Dos.Xms;
using Spice86.Core.Emulator.InterruptHandlers.Input.Keyboard;
using Spice86.Core.Emulator.IOPorts;
using Spice86.Core.Emulator.Memory;
using Spice86.Core.Emulator.OperatingSystem;
Expand Down Expand Up @@ -70,21 +68,6 @@ public sealed class EmulatorMcpServices(

public ILogger LoggerService { get; } = loggerService;

/// <summary>
/// Gets or sets the Intel 8042 PS/2 controller used for keyboard/mouse MCP automation.
/// </summary>
public Intel8042Controller? Intel8042Controller {
get => _intel8042Controller;
set {
_intel8042Controller = value;
if (value is not null) {
SubscribeKeyboardReconcileOnPause();
}
}
}

private Intel8042Controller? _intel8042Controller;

/// <summary>
/// Gets or sets the input event hub. MCP tools must post keyboard/mouse
/// mutations through this hub so they run on the emulator thread, matching
Expand Down Expand Up @@ -122,11 +105,6 @@ public Intel8042Controller? Intel8042Controller {
/// </summary>
public BiosDataArea? BiosDataArea { get; set; }

/// <summary>
/// Gets or sets the BIOS keyboard buffer for direct key injection.
/// </summary>
public BiosKeyboardBuffer? BiosKeyboardBuffer { get; set; }

/// <summary>
/// Gets or sets the interrupt vector table used by BIOS and DOS MCP tools.
/// </summary>
Expand All @@ -137,26 +115,6 @@ public Intel8042Controller? Intel8042Controller {
/// </summary>
public Dos? Dos { get; set; }

private bool _keyboardReconcileSubscribed;

/// <summary>
/// Subscribes the keyboard device to release all held keys whenever the emulator pauses. Key-ups
/// dropped while paused (or lost when the window deactivates) would otherwise leave a modifier
/// latched in the guest's BIOS state. The release is marshalled onto the emulator thread via
/// <see cref="InputEventHub"/> so it is safe to call from the UI thread.
/// </summary>
internal void SubscribeKeyboardReconcileOnPause() {
if (_keyboardReconcileSubscribed
|| Intel8042Controller is null
|| InputEventHub is null) {
return;
}

InputEventHub inputEventHub = InputEventHub;
PauseHandler.Pausing += () => inputEventHub.ReleaseAllKeys();
_keyboardReconcileSubscribed = true;
}

// Shared MCP breakpoint tracking state (survives transient tool instances)
private readonly object _mcpBreakpointsLock = new();
private readonly Lock _toolsLock = new();
Expand Down
59 changes: 0 additions & 59 deletions src/Spice86.Core/Emulator/Mcp/EmulatorMcpTools.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ namespace Spice86.Mcp;
using Spice86.Core.Emulator.Devices.Timer;
using Spice86.Core.Emulator.Devices.Video;
using Spice86.Core.Emulator.InterruptHandlers.Bios.Structures;
using Spice86.Core.Emulator.InterruptHandlers.Input.Keyboard;
using Spice86.Core.Emulator.InterruptHandlers.VGA.Enums;
using Spice86.Core.Emulator.InterruptHandlers.VGA.Records;
using Spice86.Core.Emulator.InterruptHandlers.Dos.Ems;
Expand Down Expand Up @@ -576,64 +575,6 @@ public CallToolResult SendKeyboardKey(string key, bool isPressed) {
});
}

[McpServerTool(Name = "press_key", UseStructuredContent = true), Description("Press a key by writing its BIOS key code directly into the BIOS keyboard buffer (BDA ring at 0040:001E). Parameters: ascii (0-255), scancode (0-255). For extended keys (arrows, function keys): ascii=0, scancode=0x48/0x50/0x4B/0x4D (up/down/left/right). The key code is (scancode<<8)|ascii, exactly what INT 09h stores and INT 16h dequeues, so it works headless with no GUI. No key-up event is generated (the BIOS buffer holds press codes only). Fails when the buffer is full (the game has not consumed pending keys). Prefer this over send_keyboard_key when you need exact scan codes or GUI-independent delivery.")]
public CallToolResult PressKey(int ascii, int scanCode) {
return ExecuteTool(() => {
lock (_services.ToolsLock) {
if (ascii is < 0 or > 255) {
throw new ArgumentException("ascii must be 0-255");
}

if (scanCode is < 0 or > 255) {
throw new ArgumentException("scancode must be 0-255");
}

BiosKeyboardBuffer? buffer = _services.BiosKeyboardBuffer;
if (buffer == null) {
throw new InvalidOperationException("BiosKeyboardBuffer is not wired");
}

ushort keyCode = (ushort)((scanCode << 8) | ascii);
if (!buffer.EnqueueKeyCode(keyCode)) {
throw new InvalidOperationException("BIOS keyboard buffer is full; the emulated program has not consumed pending keys.");
}

return new {
KeyCode = $"0x{keyCode:X4}",
Ascii = ascii,
ScanCode = scanCode,
Success = true
};
}
});
}

[McpServerTool(Name = "send_mouse_packet", UseStructuredContent = true), Description("Send raw PS/2 AUX bytes to the mouse controller as a hex string (1-8 bytes, no separators). For a standard 3-byte packet, use SSXXYY: SS=status byte, XX=X delta, YY=Y delta. Status byte bit layout: bit0=left button, bit1=right button, bit2=middle button, bit3=always 1 for a normal packet header, bit4=X sign, bit5=Y sign, bit6=X overflow, bit7=Y overflow. XX and YY are signed 8-bit deltas (two's complement). Examples: 080000 (no movement, no button), 090100 (left button + X=+1), 08FF00 (X=-1).")]
public CallToolResult SendMousePacket([StringSyntax("Hexadecimal")] string packetData) {
return ExecuteTool(() => {
lock (_services.ToolsLock) {
Intel8042Controller? controller = _services.Intel8042Controller;
if (controller == null) {
throw new InvalidOperationException("PS/2 controller is not available");
}

byte[] bytes = ParseHexData(packetData);
if (bytes.Length > 8) {
throw new ArgumentException("Mouse packet must be 1-8 bytes", nameof(packetData));
}

foreach (byte packetByte in bytes) {
controller.AddAuxByte(packetByte);
}

return new EmulatorControlResponse {
Success = true,
Message = $"Mouse packet sent ({bytes.Length} byte(s))"
};
}
});
}

[McpServerTool(Name = "send_mouse_move", UseStructuredContent = true), Description("Move the mouse to a normalized position on screen. x and y are in the range [0.0, 1.0] relative to the emulated display: (0,0) is top-left, (1,1) is bottom-right.")]
public CallToolResult SendMouseMove(double x, double y) {
return ExecuteTool(() => {
Expand Down
11 changes: 11 additions & 0 deletions src/Spice86.Core/Emulator/VM/IKeyboardInputEvents.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Spice86.Core.Emulator.VM;

using Spice86.Shared.Interfaces;

/// <summary>
/// Keyboard events delivered to emulated keyboard devices, including reconciliation of all held keys.
/// </summary>
public interface IKeyboardInputEvents : IGuiKeyboardEvents {
/// <summary>Raised when all held keys must be released.</summary>
event EventHandler? AllKeysReleased;
}
22 changes: 22 additions & 0 deletions src/Spice86.Core/Emulator/VM/Input/Events/InputEvents.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace Spice86.Core.Emulator.VM.Input.Events;

using Spice86.Shared.Emulator.Keyboard;
using Spice86.Shared.Emulator.Mouse;

/// <summary>Base record for host input actions queued through <see cref="InputEventHub"/>.</summary>
public abstract record InputEvent;

/// <summary>A host keyboard press or release event.</summary>
public sealed record KeyboardInput(KeyboardEventArgs Args) : InputEvent;

/// <summary>A host mouse move event.</summary>
public sealed record MouseMoveInput(MouseMoveEventArgs Args) : InputEvent;

/// <summary>A host mouse button press or release event.</summary>
public sealed record MouseButtonInput(MouseButtonEventArgs Args) : InputEvent;

/// <summary>A request to release all currently held keys.</summary>
public sealed record ReleaseAllKeysInput : InputEvent;

/// <summary>A request to change the emulated clock time multiplier.</summary>
public sealed record TimeMultiplierInput(double Multiplier) : InputEvent;
Loading
Loading