What if you could tell an AI “it’s too hot in here” and it actually opened a window? In this CircuitMagic project you connect Claude to an ESP32-S3 using the Model Context Protocol (MCP). The AI agent can then read a temperature sensor, switch a light and move a servo, just by chatting.
Watch the Video: AI Agents That Control Real Hardware
Chatbot vs AI agent
A chatbot only answers with words. An AI agent can also use tools: it thinks about your request, picks a tool, looks at the result and decides what to do next. In this project, the tools are real pieces of hardware.
What is MCP?
The Model Context Protocol is an open standard for connecting AI applications to tools and data. The official site compares it to a USB-C port for AI applications: one standard plug that many apps and tools can share. You write a small MCP server that lists your tools, and any app that supports MCP, such as Claude Desktop, can use them.
How the system works

- You type a message in Claude Desktop.
- Claude decides which tool to call and sends the request to a Python MCP server running on your computer.
- The server sends a simple web request over Wi-Fi to the ESP32-S3.
- The ESP32 switches the LED, moves the servo or reads the temperature, then sends the result back up the chain.
Required components
- ESP32-S3 dev board (about $10; any Wi-Fi ESP32 works if you change the pins)
- DHT22 temperature and humidity sensor (about $3)
- SG90 micro servo for the model window (about $2)
- LED and 220 ohm resistor (about $1)
- Breadboard, jumper wires, USB cable
- A computer with Arduino IDE, Python 3.10 or newer,
uvand Claude Desktop
Pin connections
Unplug USB power before wiring, and connect all grounds together.
| ESP32-S3 pin | Connection |
|---|---|
| GPIO4 | 220 ohm resistor, then LED long leg (+); LED short leg to GND |
| GPIO5 | Servo signal (orange) |
| 5V | Servo red |
| GND | Servo brown |
| GPIO6 | DHT22 data |
| 3V3 | DHT22 VCC |
| GND | DHT22 GND |
A bare DHT22 sensor needs a 10k pull-up resistor from data to 3V3; most DHT22 modules already have one.
Step 1: ESP32 code (tiny web server)
The ESP32 runs a web server with three endpoints: /light?state=on|off, /window?angle=0..90 and /sensor. The window angle is limited to 90 degrees on the device itself, whatever the AI asks for. In the Arduino IDE, install the ESP32Servo and DHT sensor library (Adafruit) libraries, add your Wi-Fi name and password, and upload.
Note: this sketch has not yet been tested on hardware by CircuitMagic.
#include <WiFi.h>
#include <WebServer.h>
#include <ESP32Servo.h>
#include <DHT.h>
const char* WIFI_SSID = "YOUR_WIFI_NAME";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
#define LED_PIN 4
#define SERVO_PIN 5
#define DHT_PIN 6
#define DHT_TYPE DHT22
const int WINDOW_MAX_ANGLE = 90; // safety limit enforced on the device
WebServer server(80);
Servo windowServo;
DHT dht(DHT_PIN, DHT_TYPE);
bool lightOn = false;
void sendJson(int code, const String& body) {
server.send(code, "application/json", body);
}
void handleLight() {
String state = server.arg("state");
if (state == "on") lightOn = true;
else if (state == "off") lightOn = false;
else {
sendJson(400, "{\"error\":\"state must be on or off\"}");
return;
}
digitalWrite(LED_PIN, lightOn ? HIGH : LOW);
sendJson(200, String("{\"light\":\"") + (lightOn ? "on" : "off") + "\"}");
}
void handleWindow() {
if (!server.hasArg("angle")) {
sendJson(400, "{\"error\":\"angle is required\"}");
return;
}
int angle = constrain(server.arg("angle").toInt(), 0, WINDOW_MAX_ANGLE);
windowServo.write(angle);
sendJson(200, "{\"angle\":" + String(angle) + "}");
}
void handleSensor() {
float t = dht.readTemperature(); // Celsius
float h = dht.readHumidity();
if (isnan(t) || isnan(h)) {
sendJson(500, "{\"error\":\"sensor read failed\"}");
return;
}
sendJson(200, "{\"temperature\":" + String(t, 1) +
",\"humidity\":" + String(h, 0) + "}");
}
void setup() {
Serial.begin(115200);
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
dht.begin();
windowServo.setPeriodHertz(50);
windowServo.attach(SERVO_PIN, 500, 2400);
windowServo.write(0);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
Serial.print("Connecting to Wi-Fi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.print("\nConnected! IP address: ");
Serial.println(WiFi.localIP()); // put this IP in room_server.py
server.on("/light", handleLight);
server.on("/window", handleWindow);
server.on("/sensor", handleSensor);
server.begin();
}
void loop() {
server.handleClient();
}
Open Serial Monitor at 115200 baud and note the IP address it prints. You can test it in a browser on the same network, for example http://192.168.1.50/sensor (use your own IP).
Step 2: The MCP server in Python
Following the official MCP Python quickstart, create a project and install the SDK:
uv init room
cd room
uv venv
uv add "mcp[cli]"
Save this as room_server.py and change ESP32_URL to your board’s IP address. Each tool is a Python function with the @mcp.tool() decorator; its name, type hints and docstring tell Claude what the tool does and what it needs. We checked this server against the MCP Python SDK (version 2.3.0): the three tools register correctly, and asking for an angle above 90 is refused.
import httpx2
from mcp.server import MCPServer
from mcp.server.mcpserver.exceptions import ToolError
ESP32_URL = "http://192.168.1.50" # <-- the IP address your ESP32 printed
mcp = MCPServer("circuitmagic-room")
async def esp_get(path: str, params: dict | None = None) -> dict:
"""Send a GET request to the ESP32 and return its JSON reply."""
async with httpx2.AsyncClient() as client:
try:
response = await client.get(f"{ESP32_URL}{path}", params=params, timeout=5.0)
response.raise_for_status()
return response.json()
except Exception:
raise ToolError("Could not reach the ESP32. Is it powered and on Wi-Fi?")
@mcp.tool()
async def read_temperature() -> str:
"""Read the room temperature (Celsius) and humidity from the DHT22 sensor."""
data = await esp_get("/sensor")
return f"Temperature: {data['temperature']} C, humidity: {data['humidity']} %"
@mcp.tool()
async def set_light(on: bool) -> str:
"""Turn the desk light (LED) on or off.
Args:
on: True to switch the light on, False to switch it off
"""
data = await esp_get("/light", {"state": "on" if on else "off"})
return f"The light is now {data['light']}."
@mcp.tool()
async def set_window(angle: int) -> str:
"""Open or close the model window with the servo.
Args:
angle: 0 = closed, 90 = fully open
"""
if not 0 <= angle <= 90:
raise ToolError("Angle must be between 0 and 90 degrees.")
data = await esp_get("/window", {"angle": angle})
return f"The window is now at {data['angle']} degrees."
if __name__ == "__main__":
mcp.run(transport="stdio")
Important: this is a stdio server, so don’t use print() in it. Anything written to standard output breaks the messages between Claude Desktop and the server.
Step 3: Connect it to Claude Desktop
Open Claude Desktop’s config file (create it if it doesn’t exist):
- macOS:
~/Library/Application Support/Claude/claude_desktop_config.json - Windows:
%APPDATA%\Claude\claude_desktop_config.json
Add the server, using the absolute path to your room folder (on Windows, use double backslashes or forward slashes):
{
"mcpServers": {
"circuitmagic-room": {
"command": "uv",
"args": [
"--directory",
"/ABSOLUTE/PATH/TO/room",
"run",
"room_server.py"
]
}
}
}
Restart Claude Desktop. If it can’t find uv, put the full path to it in "command" (run which uv on macOS/Linux or where uv on Windows).
Try it
Ask something like “It feels hot in here, can you help?”. A typical agent flow: Claude calls read_temperature, sees the reading, decides to call set_window with 90 degrees, the servo opens the window, and Claude tells you what it did. Claude Desktop can ask you to approve a tool before it runs, so you stay in control. Other prompts to try: “Turn on the desk light” or “Close the window if it’s below 22 degrees.”
Safety rules for AI agents
- Only the tools it needs: every tool you add is something the agent can do.
- Limit tools in code: like our 90 degree limit, enforced both in the MCP server and on the ESP32.
- Home network only: the ESP32 uses plain HTTP with no password. Never port-forward it or expose it to the internet.
- Nothing dangerous: never let an AI control mains power, heaters, locks or anything that could hurt someone. Agents can make mistakes.
Troubleshooting
- “Could not reach the ESP32”: check the IP address in
room_server.py, and that your computer and the ESP32 are on the same Wi-Fi network. - Tools don’t appear in Claude Desktop: check the JSON for typos, use absolute paths, and fully restart the app.
- “sensor read failed”: check the DHT22 wiring and pull-up resistor, and wait two seconds between readings.
- Board resets when the servo moves: power the servo from a separate 5 V supply and connect its GND to the ESP32’s GND.
Try next
Add more sensors, a small USB fan, or ask the agent to check your room every morning. For more AI builds, see 10 AI projects you can build for under $20 and more CircuitMagic electronics projects.










