#
tokens: 9216/50000 12/12 files
lines: off (toggle) GitHub
raw markdown copy
# Directory Structure

```
├── .DS_Store
├── .gitignore
├── .idea
│   ├── .gitignore
│   └── vcs.xml
├── Chotu.png
├── choturobo.jpg
├── LICENSE
├── mapleTruck.jpg
├── package.json
├── README.MD
├── spect2.md
├── src
│   ├── backup.ts
│   ├── choturobo.ts
│   ├── chotuwireless.ts
│   ├── ino
│   │   ├── arm_rest.ino
│   │   ├── complexOpenAITalker.ino
│   │   ├── esp32.ino
│   │   ├── esp32Complex.ino
│   │   ├── esp32Motor.ino
│   │   ├── esp32Move.ino
│   │   ├── haircare_2.ino
│   │   ├── haircare.ino
│   │   ├── helloworld.ino
│   │   ├── nanoLEDAndBuzz.ino
│   │   ├── push_pull.ino
│   │   ├── restapi.ino
│   │   ├── servoVas.ino
│   │   ├── speaker.ino
│   │   └── wifi.ino
│   └── talker.ts
├── techspec.md
└── tsconfig.json
```

# Files

--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------

```
/tmp
/out-tsc

/node_modules
npm-debug.log*
yarn-debug.log*
yarn-error.log*
/.pnp
.pnp.js

.vscode/*
```

--------------------------------------------------------------------------------
/.idea/.gitignore:
--------------------------------------------------------------------------------

```
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

```

--------------------------------------------------------------------------------
/README.MD:
--------------------------------------------------------------------------------

```markdown
# **Chotu Robo Server - MCP Server for Arduino **

<div align="center">
  <img src="Chotu.png" alt="Chotu Robo" width="300" height="300">
</div>


## DEMO

👉 [Chotu Robo Demo 1](https://www.linkedin.com/posts/vishalrow_robotics-artificialintelligence-openai-activity-7312972405512028160-FfPB?utm_source=share&utm_medium=member_desktop&rcm=ACoAAABupTgBwY_78GTh-90OXNsbtOgGHbRO7HQ)

👉  [Chotu Robo Demo 2](https://www.linkedin.com/posts/vishalrow_claudeai-anthropic-ai-activity-7307097300147834880-Mi7n?utm_source=share&utm_medium=member_desktop&rcm=ACoAAABupTgBwY_78GTh-90OXNsbtOgGHbRO7HQ)

👉  [Chotu Robo Demo 3](https://www.linkedin.com/posts/vishalrow_autonomousrobot-springboot-artificialintelligence-activity-7316839291148554240-jFyM?utm_source=share&utm_medium=member_desktop&rcm=ACoAAABupTgBwY_78GTh-90OXNsbtOgGHbRO7HQ)

👉  [Chotu Robo Demo 4](https://www.linkedin.com/feed/update/urn:li:activity:7319065900031098880/)  

👉  [Chotu Robo Article](https://www.linkedin.com/pulse/arduino-robot-controlled-artificial-intelligence-using-vishal-mysore-kwltc/?utm_source=share&utm_medium=member_android&utm_campaign=share_via)

👉  [Chotu Robo Article 2](https://www.linkedin.com/pulse/choturobo-mapletruck-step-guide-building-ai-powered-vishal-mysore-elvzc/?trackingId=0oj6GKrfS5eZu%2B9OYuIb3w%3D%3D)  


<div align="center">
  <img src="mapleTruck.jpg" alt="Chotu Robo" width="300" height="300">
</div> 

## Overview 
 
This project showcases how to integrate Arduino-based robotics (using the **NodeMCU ESP32** or **Arduino Nano 368** board) with **AI** using the **MCP (Model Context Protocol)** framework from Claude AI by Anthropic. It provides a seamless connection between hardware components and AI through a simple interface that can be controlled by a user via a mobile phone or computer.

This system acts as a **robotic server** (named **Chotu Robo**) that can interact with various physical components like LEDs, motors, servos, fans, sensors, and more. These components can be controlled remotely by sending commands to the server, which in turn controls the hardware via the ESP32 or Arduino Nano 368 microcontroller.

This setup opens up the possibility for future AI-based applications, such as controlling the robot through AI assistants (like Claude) from mobile or web applications.

The Chotu Robot operates in two modes: Wired Mode and Wireless Mode, each designed for different use cases and hardware configurations.

### Wired Mode - Arduino Nano 368
In Wired Mode, the robot uses an Arduino Nano 368 board, where the code is uploaded directly via USB. This mode does not support real-time commands over the network as it requires a physical USB connection to operate. The robot runs its pre-uploaded code, making it suitable for projects where Wi-Fi or network connectivity is not required.

### Wireless Mode - ESP32 Wi-Fi Enabled Web Server
In Wireless Mode, the robot is powered by an ESP32 board. The ESP32 connects to your local Wi-Fi network and starts a Wi-Fi enabled web server that listens for real-time commands through REST API or WebSocket. This mode allows the robot to interact with external devices and control various hardware components like LEDs, motors, servos, and fans.

Once the ESP32 is connected to Wi-Fi, it accepts incoming commands that control hardware functionality in real-time. These commands can be sent from a TypeScript MCP server or a Java Spring-based MCP server, allowing seamless integration between microcontroller hardware and AI-based systems for automation, robotics, or IoT applications.

## Features

1. **LED Control**: Blink an LED for a given duration.
2. **Buzzer Control**: Sound a buzzer for a specified time.
3. **Motor Control**: Run a motor at a certain speed for a set time.
4. **Servo Control**: Move a servo motor to a specific angle.
5. **Fan Control**: Turn a fan on/off.
6. **Relay Control**: Switch a relay on or off.
7. **Sensor Readings**:
    - Read **temperature** from a sensor.
    - Measure **distance** using an ultrasonic sensor.
8. **AI-powered Commands**: Control the robot using AI-based prompts for actions like moving, starting, stopping, turning, and adjusting speed.

## Components Used

- **NodeMCU ESP32** or **Arduino Nano 368**: Microcontrollers responsible for controlling the hardware and communicating with the server.
- **Johnny-Five**: The JavaScript robotics and IoT library to interact with the hardware components.
- **MCP Framework**: The Model Context Protocol framework to handle requests and interactions with external systems, enabling AI-based communication.
- **Sensors & Actuators**:
    - **LED** (for indicating status)
    - **Buzzer**
    - **Servo Motor**
    - **Motor**
    - **Relay Module**
    - **Ultrasonic Distance Sensor**
    - **Temperature Sensor**

## How It Works

The **Chotu Robo Server** acts as the main hub for handling commands from an AI system. The following flow outlines how the system works:

1. **Setup**:
    - The **NodeMCU ESP32** or **Arduino Nano 368** board is connected to various sensors and actuators (LEDs, motors, etc.).
    - The **Johnny-Five** library allows the server to control hardware components through the microcontroller.

2. **MCP Integration**:
    - The **McpServer** manages communication between the hardware and AI.
    - The server provides several **tools** (commands) such as `blinkLED`, `buzz`, `runMotor`, `moveServo`, and more.
    - Each tool is associated with a specific function, and the server waits for commands from the AI system to execute those actions.

3. **AI Control**:
    - **AI Prompts** are used to trigger actions like moving the robot (`move-chotu`), controlling speed (`set-chotu-speed`), and turning the robot (`turn-chotu`).
    - The AI uses **Claude** or other AI assistants to send commands to the server. The server processes these commands and interacts with the hardware accordingly.

4. **Real-Time Communication**:
    - **StdioServerTransport** ensures the server can connect to external AI systems and execute commands in real-time.

5. **User Commands**:
    - The AI can send user-friendly commands like **"turn Chotu left"** or **"set speed to 5"** to control the robot's behavior.

## Commands and Tools

Here are some of the available commands and their functionalities:

- **`blinkLED`**: Blink the LED for a specified time.
- **`buzz`**: Activate the buzzer for a certain duration.
- **`runMotor`**: Start the motor at a given speed for a set period.
- **`moveServo`**: Move the servo motor to a specified angle.
- **`controlFan`**: Turn the fan on or off.
- **`toggleRelay`**: Switch a relay module on or off.
- **`readTemperature`**: Get the current temperature reading.
- **`readDistance`**: Measure the distance using the ultrasonic sensor.
- **`move-chotu`**: Move Chotu in specific steps (via AI prompt).
- **`start-chotu`**: Start Chotu and get ready to operate.
- **`stop-chotu`**: Stop Chotu and shut down operations.
- **`turn-chotu`**: Turn Chotu to a specified direction (left or right).
- **`set-chotu-speed`**: Set the speed for Chotu.

## How to Use

### Requirements

1. **Hardware**:
    - **NodeMCU ESP32** or **Arduino Nano 368** (or any supported Arduino/ESP32 board).
    - Various sensors and actuators (LED, servo, motor, ultrasonic sensor, temperature sensor, relay).

2. **Software**:
    - Install **Node.js**.
    - Install **Johnny-Five** for hardware control.
    - Use the **MCP SDK** to integrate with AI.
    - Use the **Arduino IDE** to program the microcontroller.

### Steps to Setup

1. Install **Node.js** and **Johnny-Five**:
   ```bash
   npm install johnny-five
   npm install @modelcontextprotocol/sdk
   Set up the ESP32 or Arduino Nano 368 on the Arduino IDE:

   Install the ESP32 board support in the Arduino IDE for ESP32 or Arduino Nano 368 board if using.
   Connect the NodeMCU ESP32 or Arduino Nano 368 to your computer via USB.
   Upload the Code to the Board:
        
   Use the Arduino IDE to upload the provided code to the ESP32 or Arduino Nano 368.
   ```
   Run the Server:
        
        Start the MCP server by running the script. This will set up the server and establish communication with the hardware.
        Connect to the AI:
        
        Send commands from the AI system (like Claude) to control the robot.
Example AI Commands
Move Chotu:

Command: "Move Chotu forward by 5 steps."
Action: The robot will move based on the specified number of steps.
Set Speed:

Command: "Set speed to 10."
Action: The robot's speed will be adjusted accordingly.
Turn Left:

Command: "Turn Chotu left."
Action: The robot will rotate left.

### Debug using the MCP Inspector:
```  npx @modelcontextprotocol/inspector node  build/choturobo.js ```

## Future Improvements
This project can serve as a foundational framework for developing more advanced AI-based robotic systems. You can extend the functionality by:
1. **Adding more sensors** like cameras or microphones.
2. **Integrating advanced AI models** for better decision-making.
3. **Developing a mobile app or web interface** to control the robot via a graphical interface.
4. **Using a Raspberry Pi**:
    - **Setup**: Use a Raspberry Pi to run the MCP server and control the hardware components.
    - **Installation**:
        ```bash
        sudo apt-get update
        sudo apt-get install nodejs npm
        npm install johnny-five
        npm install @modelcontextprotocol/sdk
        ```
    - **Connecting to Java-based Server**:
        - **Java Server Setup**: Create a Java-based MCP server to handle requests and communicate with the Raspberry Pi.
        - **Java Code Example**:
            ```java
            import org.modelcontextprotocol.server.McpServer;
            import org.modelcontextprotocol.server.transport.WebSocketTransport;

            public class ChotuRoboServer {
                public static void main(String[] args) {
                    McpServer server = new McpServer();
                    WebSocketTransport transport = new WebSocketTransport("ws://raspberrypi.local:8080");
                    server.connect(transport);

                    // Define tools and prompts here
                    server.tool("blinkLED", params -> {
                        // Implement LED blinking logic
                    });

                    server.start();
                }
            }
            ```
        - **Running the Server**:
            ```bash
            javac -cp modelcontextprotocol-sdk.jar ChotuRoboServer.java
            java -cp .:modelcontextprotocol-sdk.jar ChotuRoboServer
            ```
    - **Connecting Raspberry Pi to Java Server**:
        - Ensure the Raspberry Pi and Java server are on the same network.
        - Use WebSocket or REST API to send commands from the Java server to the Raspberry Pi.
        - Example command from Java server to Raspberry Pi:
            ```java
            WebSocketClient client = new WebSocketClient(new URI("ws://raspberrypi.local:8080"));
            client.connect();
            client.send("{\"command\": \"blinkLED\", \"params\": {\"time\": 5}}");
            ```

By following these steps, you can enhance the Chotu Robo project with more advanced features and better integration with AI and Java-based systems.
```

--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------

```
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="VcsDirectoryMappings">
    <mapping directory="$PROJECT_DIR$/.." vcs="Git" />
    <mapping directory="$PROJECT_DIR$" vcs="Git" />
  </component>
</project>
```

--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------

```json
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "outDir": "./build",
    "rootDir": "./src",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules"]
}

```

--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------

```json
{
  "name": "choturoboserver",
  "version": "0.1.0",
  "description": "A Model Context Protocol server",
  "private": true,
  "type": "module",
  "bin": {
    "choturoboserver": "./build/index.js"
  },
  "files": [
    "build"
  ],
  "scripts": {
    "build": "tsc && node -e \"require('fs').chmodSync('build/index.js', '755')\"",
    "prepare": "npm run build",
    "watch": "tsc --watch",
    "inspector": "npx @modelcontextprotocol/inspector build/index.js"
  },
  "dependencies": {
    "@modelcontextprotocol/sdk": "^1.6.1",
    "@types/johnny-five": "^2.1.11",
    "axios": "^1.8.3",
    "johnny-five": "^2.1.0",
    "zod-to-json-schema": "^3.24.3"
  },
  "devDependencies": {
    "@types/node": "^20.17.24",
    "typescript": "^5.3.3"
  }
}

```

--------------------------------------------------------------------------------
/src/talker.ts:
--------------------------------------------------------------------------------

```typescript
import axios from 'axios';
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import {z} from "zod";



// Create the cookgpt server
const server = new McpServer({
    name: "ChotuRoboServer",
    version: "1.0.0",

});
async function talkChotu<T>(message: string): Promise<{ error: string }> {
    try {
        const response = await axios.post('https://your-esp32-server-ip/speak', message, {
            headers: {
                'Content-Type': 'text/plain'
            }
        });
        return response.data;
    } catch (error) {
        console.error('Error sending request to ChotuRoboServer:', error);
        return { error: 'Failed to communicate with ChotuRoboServer' };
    }
}

server.tool(
    "talkChotu",
    { chotuWillSayThisMessage: z.string() }, // ✅ Use `z.number()` instead of `z.bigint()`
    async ({ chotuWillSayThisMessage }) => {
        const alertsData = await  talkChotu(chotuWillSayThisMessage);  // Call the imported blinkLED function
        return {
            content: [{type: "text", text: `Chotu has delivered this message ${chotuWillSayThisMessage}`}]
        };

    }
);


```

--------------------------------------------------------------------------------
/techspec.md:
--------------------------------------------------------------------------------

```markdown
**BadaBot/BadaRobo Technical Specification**

**1. System Overview**

* **System Name:** BadaBot (Current Iteration), BadaRobo (Future Iteration)
* **Purpose:** Voice/text-controlled robotic platform for physical actions and sensor readings.
* **Architecture:** Multi-tiered (Cloud AI, Server, Microcontroller API, Low-level Control).
* **Future:** Raspberry Pi-based platform with enhanced AI, web control, and advanced sensors.

**2. Functional Requirements**

* **User Interaction:**
    * Accept voice/text commands (natural language).
    * Interpret commands as English queries.
* **Command Processing:**
    * Use Claude AI for query processing and command generation.
    * Provide MCP Server for command management.
* **Physical Control:**
    * Control LED (blink).
    * Generate buzzer tones.
    * Control stepper motor (rotation).
    * Detect water (sensor).
* **Communication:**
    * Wi-Fi for wireless command transfer.
    * Firmata for ESP32-Arduino Nano communication.
    * REST API (future).

**3. Technical Specifications**

* **3.1. Hardware Components**
    * **Arduino Nano:**
        * Interfaces: Digital/Analog I/O.
        * Language: Arduino C/C++.
    * **ESP32:**
        * Interfaces: Wi-Fi, Serial (Firmata).
        * Language: Arduino C/C++.
    * **Actuators:** LED, Buzzer, Stepper Motor.
    * **Sensors:** Water Detection Sensor.
    * **Future:** Raspberry Pi, Advanced Sensors.
* **3.2. Software Components**
    * **Claude AI:**
        * Purpose: NLP, Command Generation.
    * **MCP Server (TypeScript):**
        * Purpose: Command Processing.
        * Modules: Request Handler, Processing Engine, AI Tools.
    * **ESP32 Firmware (Arduino C/C++):**
        * Purpose: REST API, Wireless.
        * Modules: API Endpoints, Wi-Fi Module, Arduino Control.
    * **Arduino Nano Firmware (Arduino C/C++):**
        * Purpose: Hardware Control.
        * Modules: LED, Buzzer, Motor, Water Sensor.
    * **Future:** Web Server, Integrated Claude AI.
* **3.3. Communication Protocols**
    * Wi-Fi (802.11).
    * REST API.
    * Firmata.

**4. Future Development (BadaRobo)**

* Migrate to Raspberry Pi.
* Integrate Claude AI.
* Develop web-based REST API interface.
* Incorporate advanced sensors.
* Enhance AI processing.

**5. Testing and Validation**

* Unit testing (software).
* Integration testing (hardware/software).
* Functional testing (user commands).
* Performance testing (response, stability).

**6. Deployment**

* Home/educational environments.
* Future: Industrial/research settings.
```

--------------------------------------------------------------------------------
/src/chotuwireless.ts:
--------------------------------------------------------------------------------

```typescript
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";


// Create the cookgpt server
const server = new McpServer({
    name: "ChotuRoboServer",
    version: "1.0.0",

});
// Register available resources

server.tool(
    "moveBackward",
    { steps: z.number() }, // Takes the number of steps to move clockwise
    ({ steps }) => {
        fetch("http://192.168.2.116/clockwise", {
            method: "GET",
        }).then((response) => response.json())  // Process the API response if needed
            .catch((error) => {
                console.error("Error during moveForward request:", error);
            });

        return {
            content: [{ type: "text", text: `I am moving the motor clockwise for ${steps} steps.` }],
        };
    }
);

server.tool(
    "moveForward",
    { steps: z.number() }, // Takes the number of steps to move counterclockwise
    ({ steps }) => {
        fetch("http://192.168.2.116/counterclockwise", {
            method: "GET",
        }).then((response) => response.json())  // Process the API response if needed
            .catch((error) => {
                console.error("Error during moveBackward request:", error);
            });

        return {
            content: [{ type: "text", text: `I am moving the motor counterclockwise for ${steps} steps.` }],
        };
    }
);

server.tool(
    "makeChotuSpeak",
    { message: z.string() }, // Takes a string message to be spoken
    ({ message }) => {
        const encodedMessage = encodeURIComponent(message); // Encode the message for URL safety
        const url = `http://localhost:8080/sendAudioLocal?textToPlay=${encodedMessage}`;

        fetch(url, {
            method: "GET",
        })
            .then((response) => response.json()) // Process the API response if needed
            .catch((error) => {
                console.error("Error during makeChotuSpeak request:", error);
            });

        return {
            content: [{ type: "text", text: `Your message "${message}" has been delivered.` }],
        };
    }
);

server.tool(
    "makeChotuSing",
    { message: z.string() }, // Takes a string message to be spoken
    ({ message }) => {
        const encodedMessage = encodeURIComponent(message); // Encode the message for URL safety
        const url = `http://localhost:8080/singASong?actor=${encodedMessage}`;

        fetch(url, {
            method: "GET",
        })
            .then((response) => response.json()) // Process the API response if needed
            .catch((error) => {
                console.error("Error during makeChotuSpeak request:", error);
            });

        return {
            content: [{ type: "text", text: `Your message "${message}" has been delivered.` }],
        };
    }
);

async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("Chotu Robo Running");
}

main().catch((error) => {
    console.error("Fatal error in main():", error);
    process.exit(1);
});
```

--------------------------------------------------------------------------------
/spect2.md:
--------------------------------------------------------------------------------

```markdown
**Arduino Component Specifications: BadaBot/BadaRobo**

This document details the specifications and functionalities of the Arduino components used within the BadaBot/BadaRobo system, focusing on the Arduino Nano and its associated peripherals.

**1. Arduino Nano (Core Control Unit)**

* **1.1. Overview:**
    * The Arduino Nano serves as the low-level control unit, directly interfacing with and managing the physical actuators and sensors.
    * It receives commands from the ESP32 via the Firmata protocol.
    * It executes precise control signals to manipulate the peripherals.
* **1.2. Technical Specifications:**
    * Microcontroller: Atmel ATmega328P.
    * Operating Voltage: 5V.
    * Input Voltage (recommended): 7-12V.
    * Digital I/O Pins: 14 (of which 6 provide PWM output).
    * Analog Input Pins: 8.
    * Flash Memory: 32 KB (ATmega328P).
    * SRAM: 2 KB (ATmega328P).
    * EEPROM: 1 KB (ATmega328P).
    * Clock Speed: 16 MHz.
* **1.3. Firmware Functionalities:**
    * **1.3.1. LED Control (LEDControl):**
        * Function: Controls the on/off state of an LED.
        * Implementation: Digital output pin manipulation.
        * Control: Receives blink commands (on/off, duration) from the ESP32.
    * **1.3.2. Buzzer Control (BuzzerControl):**
        * Function: Generates audible tones using a piezoelectric buzzer.
        * Implementation: PWM output pin manipulation to produce varying frequencies.
        * Control: Receives frequency and duration commands from the ESP32.
    * **1.3.3. Stepper Motor Control (MotorControl):**
        * Function: Controls the rotational movement of a stepper motor.
        * Implementation: Digital output pin sequences to drive the motor windings.
        * Control: Receives step count, direction, and speed commands from the ESP32.
    * **1.3.4. Water Detection Sensor (WaterSensor):**
        * Function: Reads the state of a water detection sensor.
        * Implementation: Analog input pin reading to determine water presence.
        * Data Transmission: Sends sensor readings to the ESP32 via Firmata.

**2. Peripherals**

* **2.1. LED:**
    * Type: Standard Light Emitting Diode.
    * Function: Visual indication of system activity or status.
    * Interface: Connected to a digital output pin of the Arduino Nano.
* **2.2. Buzzer:**
    * Type: Piezoelectric Buzzer.
    * Function: Audible feedback for system events or alerts.
    * Interface: Connected to a PWM output pin of the Arduino Nano.
* **2.3. Stepper Motor:**
    * Type: Unipolar or Bipolar Stepper Motor (specific type to be defined).
    * Function: Precise rotational movement for mechanical actuation.
    * Interface: Connected to multiple digital output pins of the Arduino Nano, driven by a stepper motor driver.
* **2.4. Water Detection Sensor:**
    * Type: Resistive or Capacitive Water Detection Sensor (specific type to be defined).
    * Function: Detects the presence of water.
    * Interface: Connected to an analog input pin of the Arduino Nano.

**3. Communication (Firmata)**

* **3.1. Overview:**
    * Firmata is used for serial communication between the ESP32 and the Arduino Nano.
    * It allows the ESP32 to send high-level commands to the Arduino Nano, which then executes them.
* **3.2. Implementation:**
    * The Arduino Nano runs the StandardFirmata firmware.
    * The ESP32 sends Firmata messages to control digital and analog pins, and to receive analog sensor readings.

**4. Power Requirements**

* **4.1. Arduino Nano:**
    * Powered by 5V from the ESP32 or an external power supply.
* **4.2. Peripherals:**
    * Power requirements for each peripheral will be determined based on their specific specifications.
    * A separate power supply may be required for the stepper motor, depending on its power consumption.

**5. Future Considerations**

* Potential expansion of sensor capabilities.
* Integration of additional actuators.
* Optimization of Firmata communication for improved performance.
* Consideration of a more powerful arduino board if more pins or processing power is needed.
```

--------------------------------------------------------------------------------
/src/backup.ts:
--------------------------------------------------------------------------------

```typescript
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

import {
    CallToolRequestSchema,
    CompleteRequestSchema,
    CreateMessageRequest,
    CreateMessageResultSchema,
    GetPromptRequestSchema,
    ListPromptsRequestSchema,
    ListResourcesRequestSchema,
    ListResourceTemplatesRequestSchema,
    ListToolsRequestSchema,
    ReadResourceRequestSchema,
    Resource,
    SetLevelRequestSchema,
    SubscribeRequestSchema,
    Tool,
    ToolSchema,
    UnsubscribeRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
import {zodToJsonSchema} from "zod-to-json-schema";


// Create the cookgpt server
const server = new McpServer({
    name: "ChotuRobo",
    version: "1.0.0",

});
import { Board, Led, Servo, Motor, Pin, Relay, Sensor } from "johnny-five";

// Initialize Board
const board = new Board();

// Declare peripherals globally
let led: Led | null = null;
let buzzer: Led | null = null;
let motor: Motor | null = null;
let servo: Servo | null = null;
let fan: Led | null = null;
let relay: Relay | null = null;
let temperatureSensor: Sensor | null = null;
let ultrasonicSensor: Sensor | null = null;

board.on("ready", () => {
    console.log("Board is ready!");

    // Initialize components
    led = new Led(10); // LED on pin 10
    buzzer = new Led(9); // Buzzer on pin 9
    motor = new Motor({
        pins: { pwm: 6, dir: 7 }, // PWM on pin 6, direction on pin 7
    });
    servo = new Servo(5); // Servo motor on pin 5
    fan = new Led(4); // Fan connected to pin 4
    relay = new Relay(3); // Relay module on pin 3
    temperatureSensor = new Sensor("A0"); // Temperature sensor on analog pin A0
    ultrasonicSensor = new Sensor("A1"); // Ultrasonic sensor on analog pin A1

    console.log("All peripherals initialized.");
});
// Define LED globally
const ToolInputSchema = ToolSchema.shape.inputSchema;

server.tool(
    "blinkLED",
    { time: z.number() }, // ✅ Use `z.number()` instead of `z.bigint()`
    async ({ time }) => {
        if (board.isReady && led) {
            led.blink(time);
            setTimeout(() => led!.stop().off(), 5000); // Stop blinking after 5 seconds
        }

            return {
                content: [{ type: "text", text: `I will blink the LED for ${time}` }]
            };

    }
);

server.tool(
    "buzz",
    { time: z.number() },
    async ({ time }) => {
        if (board.isReady && buzzer) {
            buzzer.on();
            setTimeout(() => buzzer!.off(), time);
        }
        return {
            content: [{ type: "text", text: `Buzzer will sound for ${time} milliseconds.` }]
        };
    }
);

server.tool(
    "runMotor",
    { speed: z.number() },
    async ({ speed }) => {
        if (board.isReady && motor) {
            motor.start(speed);
            setTimeout(() => motor!.stop(), 5000); // Stop motor after 5 seconds
        }
        return {
            content: [{ type: "text", text: `Motor running at speed ${speed}.` }]
        };
    }
);

server.tool(
    "moveServo",
    { angle: z.number() },
    async ({ angle }) => {
        if (board.isReady && servo) {
            servo.to(angle);
        }
        return {
            content: [{ type: "text", text: `Servo moved to ${angle} degrees.` }]
        };
    }
);

server.tool(
    "controlFan",
    { state: z.boolean() },
    async ({ state }) => {
        if (board.isReady && fan) {
            state ? fan.on() : fan!.off();
        }
        return {
            content: [{ type: "text", text: `Fan turned ${state ? "on" : "off"}.` }]
        };
    }
);

server.tool(
    "toggleRelay",
    { state: z.boolean() },
    async ({ state }) => {
        if (board.isReady && relay) {
            state ? relay.open() : relay.close();
        }
        return {
            content: [{ type: "text", text: `Relay switched ${state ? "ON" : "OFF"}.` }]
        };
    }
);

server.tool(
    "readTemperature",
    {},
    async () => {
        if (board.isReady && temperatureSensor) {
            const temp = temperatureSensor.value; // Read from sensor
            return {
                content: [{ type: "text", text: `Current temperature: ${temp}°C.` }]
            };
        }
        return {
            content: [{ type: "text", text: "Temperature sensor not available." }]
        };
    }
);

server.tool(
    "readDistance",
    {},
    async () => {
        if (board.isReady && ultrasonicSensor) {
            const distance = ultrasonicSensor.raw; // Read distance in cm
            return {
                content: [{ type: "text", text: `Detected object at ${distance} cm.` }]
            };
        }
        return {
            content: [{ type: "text", text: "Ultrasonic sensor not available." }]
        };
    }
);






```

--------------------------------------------------------------------------------
/src/choturobo.ts:
--------------------------------------------------------------------------------

```typescript
import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";
import pkg from 'johnny-five';
const { Board, Led, Servo, Motor, Relay, Sensor } = pkg;


// Create the cookgpt server
const server = new McpServer({
    name: "ChotuRoboServer",
    version: "1.0.0",

});
// Register available resources





async function blinkLED<T>(time: number): Promise<T | null> {

    const board = new Board({
        debug: false, //
    });

    board.on("ready", () => {
        const led = new Led(10); // Create LED on pin 10

        // Blink the LED for the specified time
         led.blink(time*1000);

        // Stop blinking after 5 seconds
        setTimeout(() => {
            led.stop().off(); // Stop and turn off the LED
            return ("done") as T;
        }, 5000);
    });

    board.on("error", (error) => {
        return "error on board"// Reject the Promise if there is an error
    });
    return ("done") as T;
}

async function buzz<T>(time: number): Promise<T | null> {

    const board = new Board({
        debug: false, //
    });

    board.on("ready", () => {
        const buzzer = new Led(12);
        if (board.isReady && buzzer) {
            buzzer.on();
            setTimeout(() => buzzer!.off(), time);
        }
    });

    board.on("error", (error) => {
        return "error on board"// Reject the Promise if there is an error
    });
    return ("done") as T;
}

server.tool(
    "chotuBlinkEyes",
    { time: z.number() }, // ✅ Use `z.number()` instead of `z.bigint()`
    async ({ time }) => {
        const alertsData = await  blinkLED(time);  // Call the imported blinkLED function
          return {
                content: [{type: "text", text: `I am blinking the eyes of chotu for ${time}`}]
            };

    }
);

server.tool(
    "chotuBuzzSound",
    { time: z.number() }, // ✅ Use `z.number()` instead of `z.bigint()`
    async ({ time }) => {
        const alertsData = await  buzz(time);  // Call the imported blinkLED function
        return {
            content: [{type: "text", text: `I am buzzing the Chotu for ${time}`}]
        };

    }
);

server.tool(
    "runMotor",
    { speed: z.number() },
    async ({ speed }) => {
        const board = new Board({
            debug: false, //
        });
        const motor = new Motor({
            pins: { pwm: 6, dir: 7 }, // PWM on pin 6, direction on pin 7
        });

        if (board.isReady && motor) {
            motor.start(speed);
            setTimeout(() => motor!.stop(), 5000); // Stop motor after 5 seconds
        }
        return {
            content: [{ type: "text", text: `Motor running at speed ${speed}.` }]
        };
    }
);

server.tool(
    "moveServo",
    { angle: z.number() },
    async ({ angle }) => {
        const board = new Board({
            debug: false, //
        });
       const servo = new Servo(5); // Servo motor on pin 5

        if (board.isReady && servo) {
            servo.to(angle);
        }
        return {
            content: [{ type: "text", text: `Servo moved to ${angle} degrees.` }]
        };
    }
);

server.tool(
    "controlFan",
    { state: z.boolean() },
    async ({ state }) => {

        const board = new Board({
            debug: false, //
        });
        const  fan = new Led(4); // Fan connected to pin 4

        if (board.isReady && fan) {
            state ? fan.on() : fan!.off();
        }
        return {
            content: [{ type: "text", text: `Fan turned ${state ? "on" : "off"}.` }]
        };
    }
);

server.tool(
    "toggleRelay",
    { state: z.boolean() },
    async ({ state }) => {
        const board = new Board({
            debug: false, //
        });
        const relay = new Relay(3); // Relay module on pin 3

        if (board.isReady && relay) {
            state ? relay.open() : relay.close();
        }
        return {
            content: [{ type: "text", text: `Relay switched ${state ? "ON" : "OFF"}.` }]
        };
    }
);

server.tool(
    "readTemperature",
    {},
    async () => {
        const board = new Board({
            debug: false, //
        });
        const temperatureSensor = new Sensor("A0"); // Temperature sensor on analog pin A0

        if (board.isReady && temperatureSensor) {
            const temp = temperatureSensor.value; // Read from sensor
            return {
                content: [{ type: "text", text: `Current temperature: ${temp}°C.` }]
            };
        }
        return {
            content: [{ type: "text", text: "Temperature sensor not available." }]
        };
    }
);

server.tool(
    "readDistance",
    {},
    async () => {
        const board = new Board({
            debug: false, //
        });
        const ultrasonicSensor = new Sensor("A1"); // Ultrasonic sensor on analog pin A1
        if (board.isReady && ultrasonicSensor) {
            const distance = ultrasonicSensor.raw; // Read distance in cm
            return {
                content: [{ type: "text", text: `Detected object at ${distance} cm.` }]
            };
        }
        return {
            content: [{ type: "text", text: "Ultrasonic sensor not available." }]
        };
    }
);
server.prompt(
    "move-chotu",
    { steps: z.string() },
    ({ steps }) => ({
        messages: [{
            role: "user",
            content: {
                type: "text",
                text: `I will move chotu this any steps :\n\n${steps}`
            }
        }]
    })
);

server.prompt(
    "start-chotu",
    {},
    () => ({
        messages: [{
            role: "user",
            content: {
                type: "text",
                text: "Initializing Chotu and getting ready to operate."
            }
        }]
    })
);

server.prompt(
    "stop-chotu",
    {},
    () => ({
        messages: [{
            role: "user",
            content: {
                type: "text",
                text: "Stopping Chotu safely and shutting down operations."
            }
        }]
    })
);

server.prompt(
    "turn-chotu",
    { direction: z.enum(["left", "right"]) },
    ({ direction }) => ({
        messages: [{
            role: "user",
            content: {
                type: "text",
                text: `Turning Chotu to the ${direction}.`
            }
        }]
    })
);

server.prompt(
    "set-chotu-speed",
    { speed: z.string() },
    ({ speed }) => ({
        messages: [{
            role: "user",
            content: {
                type: "text",
                text: `Setting Chotu's speed to ${speed}.`
            }
        }]
    })
);
async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("Chotu Robo Running");
}

main().catch((error) => {
    console.error("Fatal error in main():", error);
    process.exit(1);
});
```