AI Hardware Control with MCP


Overview

The MCP (Model Context Protocol) has been out for a while now. I thought it would be interesting to connect it to hardware, so I decided to experiment with it. I will keep it simple, just allowing the AI to command turning lights on/off.

For example, type the command below to the AI:
Prompt:

Turn on blue, red, green, yellow lights, loop 3 times

The result will be as shown in the YouTube video below:

System Architecture

graph TD C1[Claude] subgraph "Windows PC" W1[Claude desktop app] W2[MCP server] W3[USB host] end subgraph "USB device" subgraph "ESP32" E1[CPU] E2[USB device] E3[SPI] end U2[LCD] end C1 <--> W1 W2 <--> W3 W3 <--> E2 E1 <--> E2 E1 <--> E3 E3 --> U2

Steps

1. Create ESP32 USB Device with Arduino

First, we will program the ESP32-S3 to act as a Vendor-Specific USB Device using the TinyUSB library, which allows the computer to recognize the ESP32 as a custom USB device. This code will handle receiving commands via USB to control the display on the connected TFT ILI9488 screen.

Caution: In Arduino IDE, you must set Tools > USB CDC On Boot to "Disabled" and Tools > USB Mode to "USB-OTG (TinyUSB)".

Code: vendor_generic_inout_ili9488.ino

// vendor_generic_inout_ili9488.ino (showing only critical parts)

// =============================================================================
// LIBRARIES & GLOBAL OBJECTS
// =============================================================================
#include <TFT_eSPI.h>
#include "USB.h"
#include "tusb.h"

TFT_eSPI tft = TFT_eSPI();

// =============================================================================
// USB DEVICE CONFIGURATION
// =============================================================================
// --- Custom VID/PID ---
#define MY_VID 0xCAFE
#define MY_PID 0x0300

// --- USB Command Protocol ---
#define CMD_UPDATE_STATUS 0x31 // Command to update the LED/color status

// ... (USB Descriptors and Callbacks are omitted) ...

// =============================================================================
// APPLICATION LOGIC & COMMAND HANDLING
// =============================================================================

// This function is called when data is sent from the computer via USB
void handleUsbCommand(uint8_t* buf, uint32_t count) {
  // ... (Echo data back for debugging) ...

  // Parse command and sent data
  uint8_t command = buf[0];

  switch (command) {
    case CMD_UPDATE_STATUS:
      // buf[10] onwards is the status of each LED color (0 or 1)
      updateStatusRects(&buf[10]);
      break;

    // ... (other commands) ...
  }
}

// Function to draw color rectangles on TFT screen according to received data
void updateStatusRects(const uint8_t* status_bytes) {
    const int RECT_X = 160 - 50;
    const int RECT_W = 100;
    const int RECT_H = 100;

    // Draw rectangles based on received status: if 1 show color, if 0 show black
    tft.fillRect(RECT_X, 50,  RECT_W, RECT_H, status_bytes[0] ? TFT_BLUE   : TFT_BLACK);
    tft.fillRect(RECT_X, 150, RECT_W, RECT_H, status_bytes[1] ? TFT_RED    : TFT_BLACK);
    tft.fillRect(RECT_X, 250, RECT_W, RECT_H, status_bytes[2] ? TFT_GREEN  : TFT_BLACK);
    tft.fillRect(RECT_X, 350, RECT_W, RECT_H, status_bytes[3] ? TFT_YELLOW : TFT_BLACK);
}

// =============================================================================
// MAIN SETUP & LOOP
// =============================================================================

void setup() {
  // ... (Setup Serial, TFT) ...

  // --- Important: Set USB Mode in Arduino IDE ---
  // Tools -> USB CDC On Boot: "Disabled"
  // Tools -> USB Mode: "USB-OTG (TinyUSB)"

  // Start USB Stack
  USB.begin();

  // ... (Show initial screen display) ...
}

void loop() {
  // All USB communication is handled via callbacks (Event-driven)
  // Main loop doesn't need to do much
  delay(10);
}

2. Test USB Interface on Windows PC

After uploading the code to the ESP32, we must make Windows recognize our USB device first.

  • libusb: A library that allows programs on the PC to communicate with USB devices directly.
  • Zadig (<a href="https://zadig.akeo.ie/">https://zadig.akeo.ie/): Since our USB device is not certified, we must use Zadig to install the libusb driver for our device (with VID/PID CAFE:0300) so that Windows can communicate with it.
  • simpleio.py: A Python script that uses pyusb (which runs on top of libusb) to directly test sending data to our ESP32. This confirms that the USB connection works correctly before moving to the next step.

Code: simpleio.py

This script will send byte data to the ESP32 to control the colors of the LEDs displayed on the TFT screen.
Note: In the code, the path to libusb-1.0.dll is hardcoded. If you installed it elsewhere, do not forget to modify the path accordingly.

import usb.core
import usb.backend.libusb1
import usb.util
import binascii
import time

def usb_led(b, r, g, y):
    b = 0x1 if b != 0 else 0x0
    r = 0x1 if r != 0 else 0x0
    g = 0x1 if g != 0 else 0x0
    y = 0x1 if y != 0 else 0x0    
    
    # Specify the path to the libusb-1.0.dll
    # *** แก้ไข path ตรงนี้ให้ตรงกับที่ที่คุณติดตั้ง libusb ไว้ ***
    usb.core.find(backend=usb.backend.libusb1.get_backend(find_library=lambda x: "D:/hong/github/AI_experimental/usb_driver/libusb-1.0.26-binaries/libusb-1.0.26-binaries/VS2015-x64/dll/libusb-1.0.dll"))

    # Find the USB device based on its vendor and product IDs
    vendor_id = 0xCAFE  # Device's vendor ID
    product_id = 0x0300  # Device's product ID

    # Find the device
    device = usb.core.find(idVendor=vendor_id, idProduct=product_id)
    if device is None:
        raise ValueError('Device not found')

    # set the active configuration. With no arguments, the first
    # configuration will be the active one
    device.set_configuration()

    # Find the bulk endpoints for data in and data out
    endpoint_out = 0x01  # Endpoint address for data out
    endpoint_in = 0x81   # Endpoint address for data in

    # [Command ID, x, y, ..., payload]
    data_to_send = bytes([0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, b, r, g, y])
    device.write(endpoint_out, data_to_send)
    
    # Clean up
    device.reset()

3. MCP Server

In this step, we will create a server that serves as a "tool" for the AI (Claude) using FastMCP.

  • uv: A fast Python package manager. We will use uv to create a virtual environment and install necessary libraries.
    • uv init mcp_server: Create a new uv project
    • uv add "mcp[cli]": Install the mcp library
    • uv add pyusb: Install pyusb to allow Python to communicate with the USB device
  • server.py: The core of this step. This script creates the MCP server and defines a "tool" named led_control which the AI can invoke. When this tool is called, it calls the usb_led function in simpleio.py to send commands to the ESP32.

Code: server.py

"""
MCP server version of agent.py
Implements the same tools (calculator, LED control, time, multiply)
"""
import json
import datetime
from typing import Optional
from mcp.server.fastmcp import FastMCP

import os
from simpleio import usb_led
    
# --- Initialize MCP server ---
mcp = FastMCP("general-assistant-mcp")

# --- Tool: LED control ---
@mcp.tool()
def led_control(
    blue: Optional[int] = None,
    red: Optional[int] = None,
    green: Optional[int] = None,
    yellow: Optional[int] = None,
) -> str:
    """
    Turn LEDs on/off. Provide 1 for ON, 0 for OFF.
    Example: led_control(red=1, blue=0)
    """
    print(f"
user control led -> blue:{blue}, red:{red}, green:{green}, yellow:{yellow}")
    # Call the usb_led function, defaulting to 0 if a color is not specified
    usb_led(blue or 0, red or 0, green or 0, yellow or 0)
    led = {"blue": blue, "red": red, "green": green, "yellow": yellow}
    return json.dumps(led)

# --- Resource: Info ---
@mcp.resource("info://agent")
def agent_info() -> str:
    """Provide general information about this agent MCP server."""
    return (
        "General Assistant MCP Server — can calculate, control LEDs, "
        "get current time, and multiply numbers."
    )

# --- Main entry ---
if __name__ == "__main__":
    mcp.run()

4. Claude Desktop Settings

Finally, we must configure the Claude Desktop app to recognize our MCP server by editing the claude_desktop_config.json file located at %APPDATA%\Claude (or ...\AppData\Roaming\Claude).

We will add a new object to mcpServers, naming it usb_device_bot, and specify the command to run our server.

claude_desktop_config.json

{
    "mcpServers": {
        "usb_device_bot": {
            "command": "uv",
            "args": [
                "--directory",
                "D:/hong/mcp_server/usb_device_bot",
                "run",
                "server.py"
            ]
        }
    }
}
  • command: The main command to run, in this case, uv.
  • args: Arguments to pass to the command.
    • "--directory", "D:/hong/mcp_server/usb_device_bot": Tells uv to work in the directory containing server.py and simpleio.py.
    • "run", "server.py": Instructs uv to run the server.py file.

Once all settings are configured, when we enable the usb_device_bot tool in Claude, it will run our MCP server and allow Claude to invoke the led_control function we created.

Note: You can check whether Claude recognizes the MCP from the settings menu.


Additional Details

In addition to natural language commands, if we type a clear command, such as writing it as a Mermaid flowchart, it seems to make it even easier for the AI to process.

Prompt:

please do below flowchart
flowchart TD A[Start, n = 0] --> B[Turn ON red LED] B --> C[Turn OFF red LED] C --> C1[n = n + 1] C1 --> D{n == 3?} D -- No --> B D -- Yes --> E[End]

Below is the flowchart:

flowchart TD A[Start, n = 0] --> B[Turn ON red LED] B --> C[Turn OFF red LED] C --> C1[n = n + 1] C1 --> D{n == 3?} D -- No --> B D -- Yes --> E[End]

Result: https://youtu.be/IZkFcYTdxvw


All example code can be downloaded at:
https://github.com/wichayen/AI_experimental