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
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
libusbdriver for our device (with VID/PIDCAFE:0300) so that Windows can communicate with it. - simpleio.py: A Python script that uses
pyusb(which runs on top oflibusb) 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
uvto create a virtual environment and install necessary libraries.uv init mcp_server: Create a newuvprojectuv add "mcp[cli]": Install themcplibraryuv add pyusb: Installpyusbto 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_controlwhich the AI can invoke. When this tool is called, it calls theusb_ledfunction insimpleio.pyto 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 thecommand."--directory", "D:/hong/mcp_server/usb_device_bot": Tellsuvto work in the directory containingserver.pyandsimpleio.py."run", "server.py": Instructsuvto run theserver.pyfile.
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:
Result: https://youtu.be/IZkFcYTdxvw
All example code can be downloaded at:
https://github.com/wichayen/AI_experimental